问:
Toast not working in Service
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

```<code><service android:name=".MyService"></service>
</code>```

ClientActivity

```<code>package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}
</code>```

MyService

```<code>package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}
</code>```

答:
Toast always works with Application's main thread. So you have to be sure that you use thread in main thread.

And still if you want to use Toast in service, then you have to use Handler.

Please check out the below example for Handler in Thread :

```<code>private Context mContext;

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext=getApplicationContext();//Get the context here
    }

    //Use this method to show toast
    void showToast(){
        if(mContext != null){
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run()
            {
                    Toast.makeText(mContext, "Display your message here", Toast.LENGTH_SHORT)show();
            }
        });

    }
}
</code>```

Title: Toast not working in Service

Body:
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

<service android:name=".MyService"></service>

ClientActivity

package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}

MyService

package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

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

Body:
Toast always works with Application's main thread. So you have to be sure that you use thread in main thread.

And still if you want to use Toast in service, then you have to use Handler.

Please check out the below example for Handler in Thread :

private Context mContext;

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext=getApplicationContext();//Get the context here
    }

    //Use this method to show toast
    void showToast(){
        if(mContext != null){
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run()
            {
                    Toast.makeText(mContext, "Display your message here", Toast.LENGTH_SHORT)show();
            }
        });

    }
}


来源: stackexchange

问:
PHP Escaping double Quote on echo with onclick
Please notice the addslashes($model->subject) part in the code below. If the subject contains single quote, it works fine but if it has double quote, javascript generates error and treats that the onclick method ends on the double quote character. How to solve that error?

```<code>    $string.=" <a href='#' class='' data-toggle='modal' "
    . "onclick=\"to_edit('" . $model->id . "','" . $model->doc_type_level_1 . "','" . $model->doc_type_level_2 . "','" . $model->doc_type_level_3 . "','" . addslashes($model->subject) . "','" . $model->date . "',"
    . "'" . $model->date_release . "','" . $model->is_confidential . "'"
    . ")\" "
    . "data-target='#modal_doc' ><span class='fa fa-pencil'></span></a>";
</code>```

答:
You should use htmlspecialchars to convert these entities, use following code:

```<code>htmlspecialchars($model->subject, ENT_QUOTES);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please notice the addslashes($model->subject) part in the code below. If the subject contains single quote, it works fine but if it has double quote, javascript generates error and treats that the onclick method ends on the double quote character. How to solve that error?

    $string.=" id . "','" . $model->doc_type_level_1 . "','" . $model->doc_type_level_2 . "','" . $model->doc_type_level_3 . "','" . addslashes($model->subject) . "','" . $model->date . "',"
    . "'" . $model->date_release . "','" . $model->is_confidential . "'"
    . ")\" "
    . "data-target='#modal_doc' >";

Body:
You should use htmlspecialchars to convert these entities, use following code:

htmlspecialchars($model->subject, ENT_QUOTES);


问:
Express Error Handling Opinion & Best Practice
I have more of a code architecture question about error handling NodeJs Express apps. I am not sure on what is the best pattern for error handling. On that note, what situations should be considered as an error. For instance, is a 401 Unauthorized code considered an error even though this response is expected when sending bad credentials?

When using:

```<code>//app.js file
app.use(err, req, res, next){}
</code>```

I generally tend to only put 5xx errors here which would represent situations in which a database cannot be found or no network connection issue or function failures. As for the rest, I would manually send back a status code, such as a 401, from the controller by explicitly coding res.status(xxx).send(); or something of the sort. But the issue behind what I'm doing is I tend to repeat myself and have to place logging scattered across the app. Is my approach fine? Should I instead be creating multiple error handling middlewares for different ranges of status codes? I need an opnion

答:
I prefer using middleware with your custom error class to deal with this problem.

Let's see a error class, which contains a custom error message, http status code and logLevel if incase you employ logger.

```<code>module.exports = class ApiCalError extends Error {
  constructor (message, status, logLevel) {

    // Calling parent constructor of base Error class.
    super(message);

    // Capturing stack trace, excluding constructor call from it.
    Error.captureStackTrace(this, this.constructor);

    // Saving class name in the property of our custom error as a shortcut.
    this.name = this.constructor.name;

    // You can use any additional properties you want.
    // I'm going to use preferred HTTP status for this error types.
    // `500` is the default value if not specified.
    this.status = status || 400;

    this.logLevel = logLevel || 'warn';

  }

  toResponseJSON () {
    return {
        success: false,
        message: this.message
    }
  }
};
</code>```

Now, let's took a look at a controller. We have only sent successful response from this controller, and passed custom errors to middleware.

```<code>  exports.Login = function(req, res, next) {
        const validationResult = validateLoginForm(req.body)
        if (!validationResult.success) {
            var err = new customError(validationResult.message, 400, 'warn')
            return next(err)
        } else {
            return passport.authenticate('local-login', (err, token, userData) => {
                if (err) {
                    if (err.name == 'IncorrectCredentialsError' || err.name == 'EmailNotVerified') {
                        var error = new customError(err.message, 400, 'warn')
                        return next(error)
                    }
                    return next(err)
                }
                return res.json({
                    success: true,
                    message: 'You have successfully logged in!',
                    token,
                    user: userData
                })
            })(req, res, next)
        }
    }
</code>```

Now, let's take a look at logger and error handlers middlewares. Here, logger will log the errors in api and pass the error to error handlers. These functions would then be used in app.use().

```<code>    // Import library

    var Logger = function(logger) {
        return function(err, req, res, next) {
            var meta = {
                path: req.originalUrl,
                method: req.method,
                'user-agent': req.headers['user-agent'],
                origin: req.headers.origin
            }
            if (err instanceof customError) {
                logger.log(err.logLevel, err.message, meta)
                return next(err)
            } else {
                logger.log('error', err.message, meta)
                return next(err)
            }
        }
    }
    var ErrorHandler = function() {
        return function(err, req, res, next) {
            if (err instanceof customError) {
                return res.status(err.status).json(err.toResponseJSON())
            }else{
                return res.status(500).json({
                    success: false,
                    message: err.message
                })
            }
        }
    }

    module.exports = {
        Logger,
        ErrorHandler
    }
</code>```

Body:
I have more of a code architecture question about error handling NodeJs Express apps. I am not sure on what is the best pattern for error handling. On that note, what situations should be considered as an error. For instance, is a 401 Unauthorized code considered an error even though this response is expected when sending bad credentials?

When using:

//app.js file
app.use(err, req, res, next){}

I generally tend to only put 5xx errors here which would represent situations in which a database cannot be found or no network connection issue or function failures. As for the rest, I would manually send back a status code, such as a 401, from the controller by explicitly coding res.status(xxx).send(); or something of the sort. But the issue behind what I'm doing is I tend to repeat myself and have to place logging scattered across the app. Is my approach fine? Should I instead be creating multiple error handling middlewares for different ranges of status codes? I need an opnion

Body:
I prefer using middleware with your custom error class to deal with this problem.

Let's see a error class, which contains a custom error message, http status code and logLevel if incase you employ logger.

module.exports = class ApiCalError extends Error {
  constructor (message, status, logLevel) {

    // Calling parent constructor of base Error class.
    super(message);

    // Capturing stack trace, excluding constructor call from it.
    Error.captureStackTrace(this, this.constructor);

    // Saving class name in the property of our custom error as a shortcut.
    this.name = this.constructor.name;

    // You can use any additional properties you want.
    // I'm going to use preferred HTTP status for this error types.
    // `500` is the default value if not specified.
    this.status = status || 400;

    this.logLevel = logLevel || 'warn';

  }

  toResponseJSON () {
    return {
        success: false,
        message: this.message
    }
  }
};

Now, let's took a look at a controller. We have only sent successful response from this controller, and passed custom errors to middleware.

  exports.Login = function(req, res, next) {
        const validationResult = validateLoginForm(req.body)
        if (!validationResult.success) {
            var err = new customError(validationResult.message, 400, 'warn')
            return next(err)
        } else {
            return passport.authenticate('local-login', (err, token, userData) => {
                if (err) {
                    if (err.name == 'IncorrectCredentialsError' || err.name == 'EmailNotVerified') {
                        var error = new customError(err.message, 400, 'warn')
                        return next(error)
                    }
                    return next(err)
                }
                return res.json({
                    success: true,
                    message: 'You have successfully logged in!',
                    token,
                    user: userData
                })
            })(req, res, next)
        }
    }

Now, let's take a look at logger and error handlers middlewares. Here, logger will log the errors in api and pass the error to error handlers. These functions would then be used in app.use().

    // Import library

    var Logger = function(logger) {
        return function(err, req, res, next) {
            var meta = {
                path: req.originalUrl,
                method: req.method,
                'user-agent': req.headers['user-agent'],
                origin: req.headers.origin
            }
            if (err instanceof customError) {
                logger.log(err.logLevel, err.message, meta)
                return next(err)
            } else {
                logger.log('error', err.message, meta)
                return next(err)
            }
        }
    }
    var ErrorHandler = function() {
        return function(err, req, res, next) {
            if (err instanceof customError) {
                return res.status(err.status).json(err.toResponseJSON())
            }else{
                return res.status(500).json({
                    success: false,
                    message: err.message
                })
            }
        }
    }

    module.exports = {
        Logger,
        ErrorHandler
    }


问:
Update UITableView height when tweet loaded
I have a UITableViewCell which contains a TWTRTweetView with auto layout. I am loading a tweet like this:

```<code>- (void)loadTweetWithId:(NSString *)tweetId {

    if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
        mTweetId = tweetId;
        [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
            if (tweet) {
                NSLog(@"Tweet loaded!");
                [mTweetView configureWithTweet:tweet];
                [mTweetView setShowActionButtons:YES];
                //[mTweetView setDelegate:self];
                [mTweetView setPresenterViewController:self.viewController];
                [mTweetView setNeedsLayout];
                [mTweetView layoutIfNeeded];
                [mTweetView layoutSubviews];
                hc.constant = mTweetView.frame.size.height;
                [self updateConstraints];
                [self layoutIfNeeded];
                [self layoutSubviews];
                [self.tableView setNeedsLayout];
                [self.tableView layoutIfNeeded];
                [self.tableView layoutSubviews];
            } else {
                NSLog(@"Tweet load error: %@", [error localizedDescription]);
            }
        }];
    }
}
</code>```

When tweet loaded cell doesn't resize unless I scroll it out and scroll it to back. I have tried several approaches as you can see in code snippet. But non of these works. My table view uses full auto layout approach which doesn't implement cell height for row function. How can i fix this?

UPDATE:

Using:

```<code>[self.tableView beginUpdates];
[self.tableView endUpdates];
</code>```

is not possible because when I do that all cells being redrawn and very big jumping happens and that is not acceptable. Also I have confirmed that tweet completion block runs in main thread.

UPDATE 2:

I have also tried to cache tweet view with tweet id and reload cell for related index path and give the same tweet view for tweet id. The cell height is corrected but it doesn't become visible until scroll out/in.

UPDATE 3:

I give constraints to tweet view in xib of the cell and height constraint is connected. So this is not a main thread issue. I have also mentioned that reloading particular cell at index doesn't work.

While working an other solution I have seen some sample TwitterKit codes that uses TWTRTweetTableViewCell but was preloading tweets to configure the cells. So I have done the same. This is a workaround of course.

答:
Try reloading that particular cell, after you loaded the tweet using,</p>

```<code>- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths
              withRowAnimation:(UITableViewRowAnimation)animation;
</code>```

Body:
I have a UITableViewCell which contains a TWTRTweetView with auto layout. I am loading a tweet like this:

- (void)loadTweetWithId:(NSString *)tweetId {

    if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
        mTweetId = tweetId;
        [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
            if (tweet) {
                NSLog(@"Tweet loaded!");
                [mTweetView configureWithTweet:tweet];
                [mTweetView setShowActionButtons:YES];
                //[mTweetView setDelegate:self];
                [mTweetView setPresenterViewController:self.viewController];
                [mTweetView setNeedsLayout];
                [mTweetView layoutIfNeeded];
                [mTweetView layoutSubviews];
                hc.constant = mTweetView.frame.size.height;
                [self updateConstraints];
                [self layoutIfNeeded];
                [self layoutSubviews];
                [self.tableView setNeedsLayout];
                [self.tableView layoutIfNeeded];
                [self.tableView layoutSubviews];
            } else {
                NSLog(@"Tweet load error: %@", [error localizedDescription]);
            }
        }];
    }
}

When tweet loaded cell doesn't resize unless I scroll it out and scroll it to back. I have tried several approaches as you can see in code snippet. But non of these works. My table view uses full auto layout approach which doesn't implement cell height for row function. How can i fix this?

UPDATE:

Using:

[self.tableView beginUpdates];
[self.tableView endUpdates];

is not possible because when I do that all cells being redrawn and very big jumping happens and that is not acceptable. Also I have confirmed that tweet completion block runs in main thread.

UPDATE 2:

I have also tried to cache tweet view with tweet id and reload cell for related index path and give the same tweet view for tweet id. The cell height is corrected but it doesn't become visible until scroll out/in.

UPDATE 3:

I give constraints to tweet view in xib of the cell and height constraint is connected. So this is not a main thread issue. I have also mentioned that reloading particular cell at index doesn't work.

While working an other solution I have seen some sample TwitterKit codes that uses TWTRTweetTableViewCell but was preloading tweets to configure the cells. So I have done the same. This is a workaround of course.

Body:
Try reloading that particular cell, after you loaded the tweet using,

- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths
              withRowAnimation:(UITableViewRowAnimation)animation;


问:
JUnit test — analysing expected Exceptions
In JUnit, I'm currently using annotation to expect an exception in my tests.

Is there a way to analyse this exception? For example, I expect a CriticalServerException, but I also want to verify the content of the getMessage method.

答:
```<code>try{
    //your code expecting to throw an exception
    fail("Failed to assert :No exception thrown");
} catch(CriticalServerException ex){
    assertNotNull("Failed to assert", ex.getMessage())
    assertEquals("Failed to assert", "Expected Message", ex.getMessage());
}
</code>```


问:
python pandas filter and aggregate multiple columns and write into CSV
I want to read a CSV file and count / aggregate on multiple columns

My input data is as follows

```<code>unique_identifier,date,flag1,flag2,flag3
a1,7/1/2017,FALSE,TRUE,FALSE
a2,7/1/2017,FALSE,TRUE,FALSE
a3,7/1/2017,FALSE,TRUE,FALSE
a4,7/1/2017,TRUE,FALSE,FALSE
a5,7/1/2017,FALSE,FALSE,FALSE
a6,7/2/2017,FALSE,FALSE,TRUE
a7,7/2/2017,FALSE,FALSE,TRUE
a8,7/2/2017,FALSE,TRUE,FALSE
q9,7/2/2017,FALSE,TRUE,TRUE
</code>```

Am new to pandas and so far by reading various questions here looks like I need to use one or more of set_index(), .append(), , .join(), .agg()

I have the individual results but cannot get the new results I want.

```<code>import pandas as pd

df = pd.read_csv("flagdata.csv")

print (df["date"].value_counts())

df_flag1 = df[df.flag1 == True]
df_flag1  = df_flag1["date"].value_counts()
print (df_flag1)

df_flag2 = df[df.flag2 == True]
df_flag2 = df_flag2["date"].value_counts()
print (df_flag2)

df_flag3 = df[df.flag3 == True]
df_flag3 = df_flag3["date"].value_counts()
print (df_flag3)
</code>```

I want to get a count of True Flags for each date to create a new csv file with the following result - date, total count, flag1 true count, flag2 true count, flag3 true count

```<code>date,count,flag1,flag2,flag3
7/1/2017,5,1,3,0
7/2/2017,4,0,2,3
</code>```

答:
groupby() and created new count field reset_index as "count" then in seconf df groupby for sum of all True

```<code>df1= df.groupby("date")["date"].count().reset_index(name="count")
df2= df.groupby("date").sum().astype(int).reset_index()
df3 = pd.merge(df1,df2, on="date")
df3.to_csv("output.csv",index=False)
</code>```

Body:
I want to read a CSV file and count / aggregate on multiple columns

My input data is as follows

unique_identifier,date,flag1,flag2,flag3
a1,7/1/2017,FALSE,TRUE,FALSE
a2,7/1/2017,FALSE,TRUE,FALSE
a3,7/1/2017,FALSE,TRUE,FALSE
a4,7/1/2017,TRUE,FALSE,FALSE
a5,7/1/2017,FALSE,FALSE,FALSE
a6,7/2/2017,FALSE,FALSE,TRUE
a7,7/2/2017,FALSE,FALSE,TRUE
a8,7/2/2017,FALSE,TRUE,FALSE
q9,7/2/2017,FALSE,TRUE,TRUE

Am new to pandas and so far by reading various questions here looks like I need to use one or more of set_index(), .append(), , .join(), .agg()

I have the individual results but cannot get the new results I want.

import pandas as pd

df = pd.read_csv("flagdata.csv")

print (df["date"].value_counts())

df_flag1 = df[df.flag1 == True]
df_flag1  = df_flag1["date"].value_counts()
print (df_flag1)

df_flag2 = df[df.flag2 == True]
df_flag2 = df_flag2["date"].value_counts()
print (df_flag2)

df_flag3 = df[df.flag3 == True]
df_flag3 = df_flag3["date"].value_counts()
print (df_flag3)

I want to get a count of True Flags for each date to create a new csv file with the following result - date, total count, flag1 true count, flag2 true count, flag3 true count

date,count,flag1,flag2,flag3
7/1/2017,5,1,3,0
7/2/2017,4,0,2,3

Body:
groupby() and created new count field reset_index as "count" then in seconf df groupby for sum of all True

df1= df.groupby("date")["date"].count().reset_index(name="count")
df2= df.groupby("date").sum().astype(int).reset_index()
df3 = pd.merge(df1,df2, on="date")
df3.to_csv("output.csv",index=False)


问:
Java regex expression to include underscore
I am trying with the below line, which ignores underscore but I want to change it to include underscore.

```<code>String name = "$SF_Update$";
String regexp = "\\$(.*?)(?:[\\_].*)?\\$"; // want to change this line
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(name);
</code>```

I tried the below options:

```<code>String regexp ="\\$([a-zA-Z]+(?:_[a-zA-Z]+)*)\\$"
</code>```

It includes underscore but it is considering the next line strings which doesn't have a $ at the end as well, like:
"$SF_Update$"
"$SF_Updateone"
Please provide a solution.

答:
Code:

```<code>String str1 = "$SF_Update$";
String str2 = "$SF_Update_One$";
String str3 = "$SF_Update_One";
Pattern pattern = Pattern.compile("\\$([^_]+_{1}[^_]+)\\$");
Matcher matcher1 = pattern.matcher(str1);
Matcher matcher2 = pattern.matcher(str2);
Matcher matcher3 = pattern.matcher(str3);
if (matcher1.matches())
    System.out.println(str1 + " => " + matcher1.group(1));
else
    System.out.println(str1 + " => " + "No Match.");
if (matcher2.matches())
    System.out.println(str2 + " => " + matcher2.group(1));
else
    System.out.println(str2 + " => " + "No Match.");
if (matcher3.matches())
    System.out.println(str3 + " => " + matcher3.group(1));
else
    System.out.println(str3 + " => " + "No Match.");
</code>```

Output:

```<code>$SF_Update$ => SF_Update
$SF_Update_One$ => No Match.
$SF_Update_One => No Match.
</code>```

Body:
I am trying with the below line, which ignores underscore but I want to change it to include underscore.

String name = "$SF_Update$";
String regexp = "\\$(.*?)(?:[\\_].*)?\\$"; // want to change this line
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(name);

I tried the below options:

String regexp ="\\$([a-zA-Z]+(?:_[a-zA-Z]+)*)\\$"

It includes underscore but it is considering the next line strings which doesn't have a $ at the end as well, like:
"$SF_Update$"
"$SF_Updateone"
Please provide a solution.

Body:
Code:

String str1 = "$SF_Update$";
String str2 = "$SF_Update_One$";
String str3 = "$SF_Update_One";
Pattern pattern = Pattern.compile("\\$([^_]+_{1}[^_]+)\\$");
Matcher matcher1 = pattern.matcher(str1);
Matcher matcher2 = pattern.matcher(str2);
Matcher matcher3 = pattern.matcher(str3);
if (matcher1.matches())
    System.out.println(str1 + " => " + matcher1.group(1));
else
    System.out.println(str1 + " => " + "No Match.");
if (matcher2.matches())
    System.out.println(str2 + " => " + matcher2.group(1));
else
    System.out.println(str2 + " => " + "No Match.");
if (matcher3.matches())
    System.out.println(str3 + " => " + matcher3.group(1));
else
    System.out.println(str3 + " => " + "No Match.");

Output:

$SF_Update$ => SF_Update
$SF_Update_One$ => No Match.
$SF_Update_One => No Match.


问:
Selenium HtmlUnitDriver clicking on checkbox
I'm trying to get my checkbox clicked while running using selenium.

I have no issue running my test when using chromedriver.
But when I switch to HtmlUnitDriver, it will throw error when it reaches the clicking of checkbox action. The error thrown is

org.openga.selenium.ElementNotVisibleException: You may only interact with visible elements

I've tried multiple methods like:

```<code>driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).sendKeys(Keys.SPACE);
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();
</code>```

But none of it works. Can someone help me out?

答:
Okay. I've tried both the suggested answer but none works.

So I decided to move on to PhantomJS and it works.

PhantomJS

Thanks everyone!

Body:
I'm trying to get my checkbox clicked while running using selenium.

I have no issue running my test when using chromedriver.
But when I switch to HtmlUnitDriver, it will throw error when it reaches the clicking of checkbox action. The error thrown is

org.openga.selenium.ElementNotVisibleException: You may only interact with visible elements

I've tried multiple methods like:

driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).sendKeys(Keys.SPACE);
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();

But none of it works. Can someone help me out?


问:
Integration of IBM Rhapsody with IAR Workbench using the property (.prp) files
I want to integrate IBM Rhapsody with IAR Workbench so that, I will be  able to use the Code generated in Rhapsody with the compilers of IAR. One way I found was using the .prp files of Rhapsody. I am unaware of using the .prp files.</p>

答:
Rhapsody supports workflow and platform integration with Eclipse. IAR Workbench also has Eclipse plugin.

You can start by installing Rhapsody Workflow integration plugin in your Eclipse, create Eclipse configuration in Rhapsody and generate code for this configuration.

This way you will also create Eclipse project. Try to build that project to discover what should be modified. The project should include paths, Rhapsody Framework's missing libraries, etc.

From this point on you can ask more specific questions regarding Rhapsody customization. .prp files are only one of possible ways.

BTW, which Rhapsody framework and language do you want to use? There are

OXF C++

SXFC++

OXF C

MXf C

SMXF C


问:
No module named 'pip' after pip installed
Has anyone been in the same situation?

```<code>    $ which pip
    /usr/local/bin/pip
    $pip
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 7, in <module>
        from pip import main
    ModuleNotFoundError: No module named 'pip'
    $ python
    Python 2.7.6 (default, Oct 26 2016, 20:30:19)
    [GCC 4.8.4] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import pip
    >>> pip.__version__
    '9.0.1'
</code>```

the same situation is happened on other packages

```<code>    $ easy_install
    Traceback (most recent call last):
      File "/usr/local/bin/easy_install", line 7, in <module>
        from setuptools.command.easy_install import main
    ModuleNotFoundError: No module named 'setuptools'
    $ virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/virtualenv", line 7, in <module>
        from virtualenv import main
    ModuleNotFoundError: No module named 'virtualenv'
</code>```

they are all installed.

ubuntu 16.04 python 2

答:
Install pip and virtualenv for Ubuntu 10.10 Maverick and newer

```<code>$ sudo apt-get install python-pip python-dev build-essential
$ sudo pip install --upgrade pip
$ sudo pip install --upgrade virtualenv
</code>```

For older versions of Ubuntu

```<code>sudo apt-get install python-setuptools python-dev build-essential
sudo easy_install pip
$ sudo pip install --upgrade virtualenv
</code>```

Hope this helps..!

Body:
Has anyone been in the same situation?

    $ which pip
    /usr/local/bin/pip
    $pip
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 7, in <module>
        from pip import main
    ModuleNotFoundError: No module named 'pip'
    $ python
    Python 2.7.6 (default, Oct 26 2016, 20:30:19)
    [GCC 4.8.4] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import pip
    >>> pip.__version__
    '9.0.1'

the same situation is happened on other packages

    $ easy_install
    Traceback (most recent call last):
      File "/usr/local/bin/easy_install", line 7, in <module>
        from setuptools.command.easy_install import main
    ModuleNotFoundError: No module named 'setuptools'
    $ virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/virtualenv", line 7, in <module>
        from virtualenv import main
    ModuleNotFoundError: No module named 'virtualenv'

they are all installed.

ubuntu 16.04 python 2

Body:
Install pip and virtualenv for Ubuntu 10.10 Maverick and newer

$ sudo apt-get install python-pip python-dev build-essential
$ sudo pip install --upgrade pip
$ sudo pip install --upgrade virtualenv

For older versions of Ubuntu

sudo apt-get install python-setuptools python-dev build-essential
sudo easy_install pip
$ sudo pip install --upgrade virtualenv

Hope this helps..!


问:
Share structure between GraphQL schemas
I have a Apollo GraphQL server talking to an API returning responses with roughly the following structure:

```<code>{
  "pagination": {
    "page": 1,
    // more stuff
  },
  sorting: {
    // even more stuff
  },
  data: [ // Actual data ]
}
</code>```

This structure is going to be shared across pretty much all responses from this API, that I'm using extensively. data is going to be an array most of the time, but can also be an object.

How can I write this in an efficient way, so that I don't have to repeat all these pagination and sorting fields on every data type in my schemas?

Thanks a lot!

答:
When you define your schema, you will end up abstracting out pagination, sorting, etc. as separate types. So the schema will look something like:

```<code>type Bar {
  pagination: Pagination
  sorting: SortingOptions
  data: BarData # I'm an object
}
type Foo {
  pagination: Pagination
  sorting: SortingOptions
  data: [FooData] # I'm an array
}
# more types similar to above
type Pagination {
  page: Int
  # more fields
}
type SortingOptions {
  # more fields
}
type BarData {
  # more fields
}
</code>```

So you won't have to list each field within Pagination multiple times regardless. Each type that uses Pagination, however, will still need to specify it as a field -- there's no escaping that requirement.

Alternatively, you could set up a single Type to use for all your objects. In this case, the data field would be an Interface (Data), with FooData, BarData, etc. each implementing it. In your resolver for Data, you would define a __resolveType function to determine which kind of Data to return. You can pass in a typename variable with your query and then use that variable in the __resolveType function to return the correct type.

You can see a good example of Interface in action in the Apollo docs.

The downside to this latter approach is that you have to return either a single Data object or an Array of them -- you can't mix and match -- so you would probably have to change the structure of the returned object to make it work.

Title: Share structure between GraphQL schemas

Body:
I have a Apollo GraphQL server talking to an API returning responses with roughly the following structure:

{
  "pagination": {
    "page": 1,
    // more stuff
  },
  sorting: {
    // even more stuff
  },
  data: [ // Actual data ]
}

This structure is going to be shared across pretty much all responses from this API, that I'm using extensively. data is going to be an array most of the time, but can also be an object.

How can I write this in an efficient way, so that I don't have to repeat all these pagination and sorting fields on every data type in my schemas?

Thanks a lot!

Body:
When you define your schema, you will end up abstracting out pagination, sorting, etc. as separate types. So the schema will look something like:

type Bar {
  pagination: Pagination
  sorting: SortingOptions
  data: BarData # I'm an object
}
type Foo {
  pagination: Pagination
  sorting: SortingOptions
  data: [FooData] # I'm an array
}
# more types similar to above
type Pagination {
  page: Int
  # more fields
}
type SortingOptions {
  # more fields
}
type BarData {
  # more fields
}

So you won't have to list each field within Pagination multiple times regardless. Each type that uses Pagination, however, will still need to specify it as a field -- there's no escaping that requirement.

Alternatively, you could set up a single Type to use for all your objects. In this case, the data field would be an Interface (Data), with FooData, BarData, etc. each implementing it. In your resolver for Data, you would define a __resolveType function to determine which kind of Data to return. You can pass in a typename variable with your query and then use that variable in the __resolveType function to return the correct type.

You can see a good example of Interface in action in the Apollo docs.

The downside to this latter approach is that you have to return either a single Data object or an Array of them -- you can't mix and match -- so you would probably have to change the structure of the returned object to make it work.


问:
Non Real Time Serial Data Plotter
I'm working on a motion sensor project, and I would like to acquire acceleration data from a sensor (MPU6050) attached to Arduino. So I get the 3 values of acceleration ax, ay and az and  I send them in the USB serial link.

Now I can get the ax, ay, and az values and plot them correctly and all is working good.

THE PROBLEM: is that it's not real-time, ie. when I vibrate the sensor the values don't change simultaneousely like the instant serial plotter of Arduino which I didn't use because I want to analyse these data later in MATLAB (to do pattern recognition tasks so I can distinguish movements).

This is my code, I need to know what part consumes that time and what can I do to overcome this problem?

NOTE: I tried to use also pySerial to acquire data and Matplotlib but I had the same problem, it's not simultaneous.

```<code>%%real time data plot from a serial port
% Original script written by Moidu thavot.

%%Clear all variables
clc;
clear all;
close all;

if isempty(instrfind) == 0
    fclose(instrfind); % Close com ports
    delete(instrfind); % Clear com ports
end

%%Variables (Edit yourself)

SerialPort='com6'; %serial port
TimeInterval=0;%time interval between each input.
loop=inf;%count values
yMIN = -100;
yMAX = 100;
xWIDTH = 200;
%%Set up the serial port object
s = serial(SerialPort, 'BaudRate', 115200); % setup comport
fopen(s);

time = now;
y1 = 0;
y2 = 0;
y3 = 0;
%% Set up the figure
figureHandle = figure('NumberTitle','off',...
    'Name','Acceleration Plots',...
    'Color',[0 0 0],'Visible','off');

% Set axes
axesHandle = axes('Parent',figureHandle,...
    'YGrid','on',...
    'YColor',[0.9725 0.9725 0.9725],...
    'XGrid','on',...
    'XColor',[0.9725 0.9725 0.9725],...
    'Color',[0 0 0]);

hold on;

plotHandle1 = plot(axesHandle,time,y1,'LineWidth',1,'Color',[1 0 0]);
plotHandle2 = plot(axesHandle,time,y2,'LineWidth',1,'Color',[0 1 0]);
plotHandle3 = plot(axesHandle,time,y3,'LineWidth',1,'Color',[0 0 1]);

%xlim(axesHandle,[min(time) max(time+0.001)]);
%ylim([yMIN yMAX]);

% Create xlabel
xlabel('Time','FontWeight','bold','FontSize',14,'Color',[1 1 0]);

% Create ylabel
ylabel('Acceleration Values','FontWeight','bold','FontSize',14,'Color',[1 1 0]);

% Create title
title('Real Time Data','FontSize',15,'Color',[1 1 0]);

%% Initializing variables

y1(1)=0;
y2(1)=0;
y3(1)=0;
time(1)=0;
count = 2;
while ~isequal(count,loop)

    u = fscanf(s, '%f %f %f');
    y1(count) = u(1);
    y2(count) = u(2);
    y3(count) = u(3);

    time(count) = count;

    xlim([max(time-xWIDTH) max(time)]);

    set(plotHandle1,'YData',y1,'XData',time);
    set(plotHandle2,'YData',y2,'XData',time);
    set(plotHandle3,'YData',y3,'XData',time);
    set(figureHandle,'Visible','on');
    datetick('x','mm/DD HH:MM');

    pause(TimeInterval);
    count = count +1;
end

%% Clean up the serial port
fclose(s);
delete(s);
clear s;
</code>```

答:
1- Get rid of the pause in your while loop. Instead, take a look at what you are reading from the serial port if data is available go ahead with the processing and showing, if not repeat the loop.

2- Use 'drawnow' with 'limitrate' after you set the plots

3- check the baudrate, In MATLAB side you can still increase it. I don't know about the arduino  side

Title: Non Real Time Serial Data Plotter

Body:
I'm working on a motion sensor project, and I would like to acquire acceleration data from a sensor (MPU6050) attached to Arduino. So I get the 3 values of acceleration ax, ay and az and  I send them in the USB serial link.

Now I can get the ax, ay, and az values and plot them correctly and all is working good.

THE PROBLEM: is that it's not real-time, ie. when I vibrate the sensor the values don't change simultaneousely like the instant serial plotter of Arduino which I didn't use because I want to analyse these data later in MATLAB (to do pattern recognition tasks so I can distinguish movements).

This is my code, I need to know what part consumes that time and what can I do to overcome this problem?

NOTE: I tried to use also pySerial to acquire data and Matplotlib but I had the same problem, it's not simultaneous.

%%real time data plot from a serial port
% Original script written by Moidu thavot.

%%Clear all variables
clc;
clear all;
close all;

if isempty(instrfind) == 0
    fclose(instrfind); % Close com ports
    delete(instrfind); % Clear com ports
end

%%Variables (Edit yourself)

SerialPort='com6'; %serial port
TimeInterval=0;%time interval between each input.
loop=inf;%count values
yMIN = -100;
yMAX = 100;
xWIDTH = 200;
%%Set up the serial port object
s = serial(SerialPort, 'BaudRate', 115200); % setup comport
fopen(s);

time = now;
y1 = 0;
y2 = 0;
y3 = 0;
%% Set up the figure
figureHandle = figure('NumberTitle','off',...
    'Name','Acceleration Plots',...
    'Color',[0 0 0],'Visible','off');

% Set axes
axesHandle = axes('Parent',figureHandle,...
    'YGrid','on',...
    'YColor',[0.9725 0.9725 0.9725],...
    'XGrid','on',...
    'XColor',[0.9725 0.9725 0.9725],...
    'Color',[0 0 0]);

hold on;

plotHandle1 = plot(axesHandle,time,y1,'LineWidth',1,'Color',[1 0 0]);
plotHandle2 = plot(axesHandle,time,y2,'LineWidth',1,'Color',[0 1 0]);
plotHandle3 = plot(axesHandle,time,y3,'LineWidth',1,'Color',[0 0 1]);

%xlim(axesHandle,[min(time) max(time+0.001)]);
%ylim([yMIN yMAX]);

% Create xlabel
xlabel('Time','FontWeight','bold','FontSize',14,'Color',[1 1 0]);

% Create ylabel
ylabel('Acceleration Values','FontWeight','bold','FontSize',14,'Color',[1 1 0]);

% Create title
title('Real Time Data','FontSize',15,'Color',[1 1 0]);

%% Initializing variables

y1(1)=0;
y2(1)=0;
y3(1)=0;
time(1)=0;
count = 2;
while ~isequal(count,loop)

    u = fscanf(s, '%f %f %f');
    y1(count) = u(1);
    y2(count) = u(2);
    y3(count) = u(3);

    time(count) = count;

    xlim([max(time-xWIDTH) max(time)]);

    set(plotHandle1,'YData',y1,'XData',time);
    set(plotHandle2,'YData',y2,'XData',time);
    set(plotHandle3,'YData',y3,'XData',time);
    set(figureHandle,'Visible','on');
    datetick('x','mm/DD HH:MM');

    pause(TimeInterval);
    count = count +1;
end

%% Clean up the serial port
fclose(s);
delete(s);
clear s;


问:
How to synchronize wxpython Gauge widget with threads in python?
My python project has multiple threads running. I want to add a gauge widget from the wxpython library to show the progress. I want the gauge to fill until my first thread completes. How do I achieve this? I am using Python 2.7 on Windows.</p>

答:
You can use some simple things
remember to import the module:

```<code>import os
</code>```

and then put this on the frame

```<code>def __init__(self, *a, **k):
    filename = 'game.exe'

    self.timer = wx.Timer()
    self.Bind(wx.EVT_TIMER, self.OnUpdateGauge, self.timer)
    self.timer.Start()
    self.proc = os.popen(filename) # start the process

def OnUpdateGauge(self, event):
    if self.proc.poll() == None: # return None if still running and 0 if stopped
        self.timer.Stop()
        return
    else:
        '''do something with the gauge'''
</code>```

hope those help

Body:
You can use some simple things
remember to import the module:

import os

and then put this on the frame

def __init__(self, *a, **k):
    filename = 'game.exe'

    self.timer = wx.Timer()
    self.Bind(wx.EVT_TIMER, self.OnUpdateGauge, self.timer)
    self.timer.Start()
    self.proc = os.popen(filename) # start the process

def OnUpdateGauge(self, event):
    if self.proc.poll() == None: # return None if still running and 0 if stopped
        self.timer.Stop()
        return
    else:
        '''do something with the gauge'''

hope those help


问:
IIF statement in ms access query returns #error when testing for null
The IIF function in my query is returning #ERROR when I know the record i'm querying meets the criteria. My query is as follows:

```<code>SELECT tbl1.ItemCode, IIf(IsNull([tbl2].[True Available Quantity]) Or
[tbl2].[True Available Quantity]="",[tbl1].[EvalInstock],[tbl2].[True
Available Quantity]) AS InStock
FROM tbl1 LEFT JOIN tbl2 ON tbl1.ItemCode = tbl2.[Item No#]
WHERE (((tbl1.ItemCode)="3003"));
</code>```

The WHERE part is just to limit this query for testing on a record I know has data in the [tbl2].[True Available Quantity] field.

The ultimate goal is to return all items in tbl1 and use the [True Available Quantity] value from tbl2 if it is there and if not, use EvalInstock from tbl1. I appreciate any advice!

答:
You problem is most likely, that VBA always checks both conditions:

```<code>IsNull([tbl2].[True Available Quantity]) Or [tbl2].[True Available Quantity]=""
</code>```

thus, if Null, the second condition also returns Null which can't be compared, and then IIf doesn't know what to do.

So try with Nz:

```<code>SELECT
    tbl1.ItemCode,
    Nz([tbl2].[True Available Quantity], [tbl1].[EvalInstock]) AS InStock
FROM
    tbl1
LEFT JOIN
    tbl2
    ON tbl1.ItemCode = tbl2.[Item No#]
WHERE
    tbl1.ItemCode = "3003";
</code>```

Body:
The IIF function in my query is returning #ERROR when I know the record i'm querying meets the criteria. My query is as follows:

SELECT tbl1.ItemCode, IIf(IsNull([tbl2].[True Available Quantity]) Or
[tbl2].[True Available Quantity]="",[tbl1].[EvalInstock],[tbl2].[True
Available Quantity]) AS InStock
FROM tbl1 LEFT JOIN tbl2 ON tbl1.ItemCode = tbl2.[Item No#]
WHERE (((tbl1.ItemCode)="3003"));

The WHERE part is just to limit this query for testing on a record I know has data in the [tbl2].[True Available Quantity] field.

The ultimate goal is to return all items in tbl1 and use the [True Available Quantity] value from tbl2 if it is there and if not, use EvalInstock from tbl1. I appreciate any advice!

Body:
You problem is most likely, that VBA always checks both conditions:

IsNull([tbl2].[True Available Quantity]) Or [tbl2].[True Available Quantity]=""

thus, if Null, the second condition also returns Null which can't be compared, and then IIf doesn't know what to do.

So try with Nz:

SELECT
    tbl1.ItemCode,
    Nz([tbl2].[True Available Quantity], [tbl1].[EvalInstock]) AS InStock
FROM
    tbl1
LEFT JOIN
    tbl2
    ON tbl1.ItemCode = tbl2.[Item No#]
WHERE
    tbl1.ItemCode = "3003";


问:
What's the magic of arrays in C#
```<code>int[] a = new int[5];
string[] b = new string[1];
</code>```

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

答:
And why did they(the c# team) make
  this design(I mean why it's not
  something like Array...

Generics are ideal for defining a container, as they constrain the element type so you can't insert type A and try to retrieve type B.

But generics were not added until CLR2/C#2. So arrays had to provide type safety in their own way.

Even so, it's not that different to generics. You note that there is no special class for int[]. But nor would there be for Array<int>. In generics there would only be the generic class Array<T>, and the CLR "magically" creates specialised versions for distinct type argument you use. So it would be no less "magic" if generics were used.

Despite this, in the CLR the type of any object is reified (it exists as a value you can manipulate), of type Type, and can be obtained with typeof. So although there is no code declaration of any array type (and why would you need to see it?) there is a Type object that you can query.

By the way, there was a design flaw in the way arrays constrain element types. You can declare an array:

```<code>int[] ints = ...
</code>```

You can then store it in a looser variable:

```<code>object[] objs = ints;
</code>```

But that means you can insert a string (at least it appears so at compile time):

```<code>objs[3] = "Oh dear";
</code>```

At runtime it throws an exception. The idea of static type checking is to catch this kind of thing at compile time, not runtime. Generics would not have had this problem because they don't give assignment compatibility to generic class instances based on the compatibility of their type parameters. (Since C#4/CLR4 they have gained the ability to do that where it makes sense, but that wouldn't make sense for a mutable array.)

ContentLicense: CC BY-SA 2.5

Title: What's the magic of arrays in C#

Body:
int[] a = new int[5];
string[] b = new string[1];

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

Body:
And why did they(the c# team) make
  this design(I mean why it's not
  something like Array...

Generics are ideal for defining a container, as they constrain the element type so you can't insert type A and try to retrieve type B.

But generics were not added until CLR2/C#2. So arrays had to provide type safety in their own way.

Even so, it's not that different to generics. You note that there is no special class for int[]. But nor would there be for Array<int>. In generics there would only be the generic class Array<T>, and the CLR "magically" creates specialised versions for distinct type argument you use. So it would be no less "magic" if generics were used.

Despite this, in the CLR the type of any object is reified (it exists as a value you can manipulate), of type Type, and can be obtained with typeof. So although there is no code declaration of any array type (and why would you need to see it?) there is a Type object that you can query.

By the way, there was a design flaw in the way arrays constrain element types. You can declare an array:

int[] ints = ...

You can then store it in a looser variable:

object[] objs = ints;

But that means you can insert a string (at least it appears so at compile time):

objs[3] = "Oh dear";

At runtime it throws an exception. The idea of static type checking is to catch this kind of thing at compile time, not runtime. Generics would not have had this problem because they don't give assignment compatibility to generic class instances based on the compatibility of their type parameters. (Since C#4/CLR4 they have gained the ability to do that where it makes sense, but that wouldn't make sense for a mutable array.)


问:
long press and drag on edittext to select text android
I am new to android. I was trying to implement a long press and then drag to select text in an edit text. I used onTouchListner to set the selection. The selection part is working fine, but I have a couple of problems implementing this.

The keyboard is not popping up.

The text selection handles are not showing.

I can not achieve long click and then drag to select the text(just
drag is working).

If anyone could point me in the right direction or share some code that would be much helpful.
Thanks!

Here's my code

```<code>public class MainActivity extends AppCompatActivity {
private float mLastTouchX;
private float mLastTouchy;
private EditText sampleET;
private int start;
private int stop;
private String log = "MAIN_ACTIVITY";
private int mActivePointerId = INVALID_POINTER_ID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sampleET = (EditText) findViewById(R.id.sample_ET);
    sampleET.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (MotionEventCompat.getActionMasked(event)) {

                case MotionEvent.ACTION_DOWN: {
                    final float x = event.getX();
                    final float y = event.getY();
                    // start pos
                    mLastTouchX = x;
                    mLastTouchy = y;
                    Log.d(log, "Start X" + mLastTouchX);
                    Log.d(log, "Start Y" + mLastTouchy);
                    start = sampleET.getOffsetForPosition(x, y);
                    sampleET.setSelection(start);
                    // finger id saved
                    mActivePointerId = event.getPointerId(0);
                    break;
                }

                case MotionEvent.ACTION_MOVE: {
                    final float x = event.getX();
                    final float y = event.getY();
                    Log.d(log, "New X" + x);
                    Log.d(log, "New Y" + y);
                    stop = sampleET.getOffsetForPosition(x, y);
                    sampleET.setSelection(start, stop);
                    break;
                }

                case MotionEvent.ACTION_UP: {
                    mActivePointerId = INVALID_POINTER_ID;
                    break;
                }

                case MotionEvent.ACTION_CANCEL: {
                    mActivePointerId = INVALID_POINTER_ID;
                    break;
                }

                case MotionEvent.ACTION_POINTER_UP: {
                    final int pointerIndex = MotionEventCompat.getActionIndex(event);
                    final int pointerId = event.getPointerId(pointerIndex);
                    if (pointerId == mActivePointerId) {
                        // active pointer up. Choose a new
                        // active pointer and adjust.
                        final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                        mLastTouchX = event.getX(newPointerIndex);
                        mLastTouchy = event.getY(newPointerIndex);
                        mActivePointerId = event.getPointerId(newPointerIndex);
                    }
                    break;
                }
            }
            return true;
        }
    });
}
</code>```

}

答:
I believe an EditText by default has the operations you need. The text selection handles and the keyboard popping up by default are already implemented, and it's likely that you've overwritten that functionality with your custom onTouchListener. </p>

<p>If you're looking for custom functionality on an EditText, I suggest extending the EditText with your own custom view, and then creating custom methods as per your requirements. </p>

Body:
I am new to android. I was trying to implement a long press and then drag to select text in an edit text. I used onTouchListner to set the selection. The selection part is working fine, but I have a couple of problems implementing this.

The keyboard is not popping up.

The text selection handles are not showing.

I can not achieve long click and then drag to select the text(just
drag is working).

If anyone could point me in the right direction or share some code that would be much helpful.
Thanks!

Here's my code

public class MainActivity extends AppCompatActivity {
private float mLastTouchX;
private float mLastTouchy;
private EditText sampleET;
private int start;
private int stop;
private String log = "MAIN_ACTIVITY";
private int mActivePointerId = INVALID_POINTER_ID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sampleET = (EditText) findViewById(R.id.sample_ET);
    sampleET.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (MotionEventCompat.getActionMasked(event)) {

                case MotionEvent.ACTION_DOWN: {
                    final float x = event.getX();
                    final float y = event.getY();
                    // start pos
                    mLastTouchX = x;
                    mLastTouchy = y;
                    Log.d(log, "Start X" + mLastTouchX);
                    Log.d(log, "Start Y" + mLastTouchy);
                    start = sampleET.getOffsetForPosition(x, y);
                    sampleET.setSelection(start);
                    // finger id saved
                    mActivePointerId = event.getPointerId(0);
                    break;
                }

                case MotionEvent.ACTION_MOVE: {
                    final float x = event.getX();
                    final float y = event.getY();
                    Log.d(log, "New X" + x);
                    Log.d(log, "New Y" + y);
                    stop = sampleET.getOffsetForPosition(x, y);
                    sampleET.setSelection(start, stop);
                    break;
                }

                case MotionEvent.ACTION_UP: {
                    mActivePointerId = INVALID_POINTER_ID;
                    break;
                }

                case MotionEvent.ACTION_CANCEL: {
                    mActivePointerId = INVALID_POINTER_ID;
                    break;
                }

                case MotionEvent.ACTION_POINTER_UP: {
                    final int pointerIndex = MotionEventCompat.getActionIndex(event);
                    final int pointerId = event.getPointerId(pointerIndex);
                    if (pointerId == mActivePointerId) {
                        // active pointer up. Choose a new
                        // active pointer and adjust.
                        final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                        mLastTouchX = event.getX(newPointerIndex);
                        mLastTouchy = event.getY(newPointerIndex);
                        mActivePointerId = event.getPointerId(newPointerIndex);
                    }
                    break;
                }
            }
            return true;
        }
    });
}

}

Body:
I believe an EditText by default has the operations you need. The text selection handles and the keyboard popping up by default are already implemented, and it's likely that you've overwritten that functionality with your custom onTouchListener.

If you're looking for custom functionality on an EditText, I suggest extending the EditText with your own custom view, and then creating custom methods as per your requirements.


问:
EXT JS how to get data
I'm a first time learner of EXT Js and on the example http://examples.sencha.com/extjs/6.2.0/examples/kitchensink/#array-grid I'm trying to find out how the table is being populated and can't find the source of the content of the table.
Anyone who's used EXT Js before should find it trivial to find the source of the data or recommend how and if it's possible to test extjs on a platform like jsfiddle.</p>

答:
There are many procedure by which you can get data for the grid.

First way is binding data to the code itself.

But before that how to bind data and how it work in grid, You need to create your data store and then bind this store to your grid in store.

Here is an example code :

```<code>Ext.create('Ext.data.Store', {
    storeId: 'simpsonsStore',
    fields:[ 'name', 'email', 'phone'],
    data: [
        { name: 'Lisa', email: 'lisa@simpsons.com', phone: '555-111-1224' },
        { name: 'Bart', email: 'bart@simpsons.com', phone: '555-222-1234' },
        { name: 'Homer', email: 'homer@simpsons.com', phone: '555-222-1244' },
        { name: 'Marge', email: 'marge@simpsons.com', phone: '555-222-1254' }
    ]
});

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    columns: [
        { text: 'Name', dataIndex: 'name' },
        { text: 'Email', dataIndex: 'email', flex: 1 },
        { text: 'Phone', dataIndex: 'phone' }
    ],
    height: 200,
    width: 400,
    renderTo: Ext.getBody()
});
</code>```

Here is sencha fiddle for you.
Sencha Fiddle

The second way where you can fetch data from JSON or XML. In this case also you have to create a data store(Which may be json store or Array store) and again binding to the grid. Only data part will change. Here you need to fetch data from the json by using some ajax call.

Here is the example code.

```<code>    var store = new Ext.data.JsonStore({
        // store configs
        storeId: 'myStore',

        proxy: {
            type: 'ajax',
            url: 'get-images.php',
            reader: {
                type: 'json',
                rootProperty: 'images'
            }
        },

    //alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
    fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
});
</code>```

and then call your bind your store as we did in previous code.
 I will suggest you to please  go through this links

Usefull link

Grid PAnel _ Grid Panel
Data Store - Data Store
JSON STore

Title: EXT JS how to get data

Body:
There are many procedure by which you can get data for the grid.

First way is binding data to the code itself.

But before that how to bind data and how it work in grid, You need to create your data store and then bind this store to your grid in store.

Here is an example code :

Ext.create('Ext.data.Store', {
    storeId: 'simpsonsStore',
    fields:[ 'name', 'email', 'phone'],
    data: [
        { name: 'Lisa', email: 'lisa@simpsons.com', phone: '555-111-1224' },
        { name: 'Bart', email: 'bart@simpsons.com', phone: '555-222-1234' },
        { name: 'Homer', email: 'homer@simpsons.com', phone: '555-222-1244' },
        { name: 'Marge', email: 'marge@simpsons.com', phone: '555-222-1254' }
    ]
});

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    columns: [
        { text: 'Name', dataIndex: 'name' },
        { text: 'Email', dataIndex: 'email', flex: 1 },
        { text: 'Phone', dataIndex: 'phone' }
    ],
    height: 200,
    width: 400,
    renderTo: Ext.getBody()
});

Here is sencha fiddle for you.
Sencha Fiddle

The second way where you can fetch data from JSON or XML. In this case also you have to create a data store(Which may be json store or Array store) and again binding to the grid. Only data part will change. Here you need to fetch data from the json by using some ajax call.

Here is the example code.

    var store = new Ext.data.JsonStore({
        // store configs
        storeId: 'myStore',

        proxy: {
            type: 'ajax',
            url: 'get-images.php',
            reader: {
                type: 'json',
                rootProperty: 'images'
            }
        },

    //alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
    fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
});

and then call your bind your store as we did in previous code.
 I will suggest you to please  go through this links

Usefull link

Grid PAnel _ Grid Panel
Data Store - Data Store
JSON STore


问:
session_start() works fine in firefox but not working in chrome
session_start() works fine in firefox but not working in chrome. And also I have written session_start() at the top of a file but still, it's not working in google chrome.
I have added a check in my code if session is set then a page will be displayed to user. and in chrome it always goes to else statement . In firefox it works perfectly.

```<code><?php
        session_start();
        include("connection.php");
      if (isset($_SESSION['adminid'])) {

?>
<!DOCTYPE html>
<html>
<head>

<title>SezaPharma AdminPanel</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <link rel="shortcut icon" type="image/png" href="images/favicon.png"/>

</head>
<body>

<div class="dashboard">
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">All Products</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Add New Product</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Setting</button>
  <a href="logout.php" ><button class="tablinks" onclick="openCity(event, 'Tokyo')" >Logout</button></a>
</div>

<div id="London" class="tabcontent" style="overflow:auto">

  <div class="site_wrapper" >

<div class="clearfix margin_top10"></div>

<div class="works01"  >

<div class="container"  >

    <div id="grid-container" class="cbp-l-grid-fullWidth"  style="overflow:visible;">

     <?php

    $select_post=mysqli_query($conn,"select * from products ORDER BY PID desc") or die(mysqli_error());

    while($post=mysqli_fetch_array($select_post))
    {

    ?>

        <div class="cbp-item <?php echo $post['PTYPE'];?>">
            <div class="cbp-caption">
                <div class="cbp-caption-defaultWrap">
                    <img style="width:100%; height:200px;" src="UploadedImage/<?php echo $post['PIMAGELOC'];?>" alt="">
                </div>
                <div class="cbp-caption-activeWrap">
                    <div class="cbp-l-caption-alignCenter">
                        <div class="cbp-l-caption-body">
                            <h3><?php echo $post['PNAME'];?></h3>
                            <br />

                            <a href="delete_product.php?PID=<?php echo $post['PID']; ?>" class="cbp-l-caption-buttonLeft" data-title="Looking Publishing <br>reasonable always">Delete</a>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- end item -->

        <?php
        }

    ?>

    </div>

</div>
</div><!-- end works section -->

<!-- ######### JS FILES ######### -->
<!-- get jQuery used for the theme -->
<script type="text/javascript" src="js/universal/jquery.js"></script>
<script src="js/style-switcher/styleselector.js"></script>
<script src="js/animations/js/animations.min.js" type="text/javascript"></script>
<script src="js/mainmenu/bootstrap.min.js"></script>
<script src="js/mainmenu/customeUI.js"></script>
<script src="js/scrolltotop/totop.js" type="text/javascript"></script>
<script type="text/javascript" src="js/mainmenu/sticky.js"></script>
<script type="text/javascript" src="js/mainmenu/modernizr.custom.75180.js"></script>
<script type="text/javascript" src="js/cubeportfolio/jquery.cubeportfolio.min.js"></script>
<script type="text/javascript" src="js/cubeportfolio/main31.js"></script>
</body>
</html>
<?php } else{ echo " You mus Loggedin to acces this page"; }     ?>
</code>```

答:
The problem cannot be the browser because they are affected likewise in case of web server trouble. Check if you have cookies disabled in Google Chrome

If you are running your code in your own machine, make sure the local server is online mode; sometimes Mozilla Firefox is flexible in this case.

Something wrong in you code: you have  and  out of the PHP condition

EDIT

```<code><?php
    session_start();
    include("connection.php");
  if (isset($_SESSION['adminid'])) {

?>
<!DOCTYPE html>
<html>
<head>

<title>SezaPharma AdminPanel</title>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="shortcut icon" type="image/png" href="images/favicon.png"/>

</head>
<body>

<div class="dashboard">
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">All Products</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Add New Product</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Setting</button>
<a href="logout.php" ><button class="tablinks" onclick="openCity(event, 'Tokyo')" >Logout</button></a>
</div>

<div id="London" class="tabcontent" style="overflow:auto">

 <div class="site_wrapper" >

 <div class="clearfix margin_top10"></div>

  <div class="works01"  >

   <div class="container"  >

 <div id="grid-container" class="cbp-l-grid-fullWidth"  style="overflow:visible;">

  <?php

$select_post=mysqli_query($conn,"select * from products ORDER BY PID desc") or die(mysqli_error());

while($post=mysqli_fetch_array($select_post))
{

?>

    <div class="cbp-item <?php echo $post['PTYPE'];?>">
        <div class="cbp-caption">
            <div class="cbp-caption-defaultWrap">
                <img style="width:100%; height:200px;" src="UploadedImage/<?php echo $post['PIMAGELOC'];?>" alt="">
            </div>
            <div class="cbp-caption-activeWrap">
                <div class="cbp-l-caption-alignCenter">
                    <div class="cbp-l-caption-body">
                        <h3><?php echo $post['PNAME'];?></h3>
                        <br />

                        <a href="delete_product.php?PID=<?php echo $post['PID']; ?>" class="cbp-l-caption-buttonLeft" data-title="Looking Publishing <br>reasonable always">Delete</a>
                    </div>
                </div>
            </div>
        </div>
    </div><!-- end item -->

    <?php
    }

?>

</div>

 </div>
 </div><!-- end works section -->

  <!-- ######### JS FILES ######### -->
  <!-- get jQuery used for the theme -->
  <script type="text/javascript" src="js/universal/jquery.js"></script>
  <script src="js/style-switcher/styleselector.js"></script>
  <script src="js/animations/js/animations.min.js" type="text/javascript">
  </script>
  <script src="js/mainmenu/bootstrap.min.js"></script>
  <script src="js/mainmenu/customeUI.js"></script>
  <script src="js/scrolltotop/totop.js" type="text/javascript"></script>
  <script type="text/javascript" src="js/mainmenu/sticky.js"></script>
  <script type="text/javascript" src="js/mainmenu/modernizr.custom.75180.js"></script>
  <script type="text/javascript" src="js/cubeportfolio/jquery.cubeportfolio.min.js"></script>
  <script type="text/javascript" src="js/cubeportfolio/main31.js"></script>
  </body>
  </html>
  <?php } else{ echo " You mus Loggedin to acces this page"; }   ?>
</code>```

Body:
session_start() works fine in firefox but not working in chrome. And also I have written session_start() at the top of a file but still, it's not working in google chrome.
I have added a check in my code if session is set then a page will be displayed to user. and in chrome it always goes to else statement . In firefox it works perfectly.

<?php
        session_start();
        include("connection.php");
      if (isset($_SESSION['adminid'])) {

?>
<!DOCTYPE html>

<title>SezaPharma AdminPanel</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <link rel="shortcut icon" type="image/png" href="images/favicon.png"/>

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">All Products</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Add New Product</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Setting</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" >Logout</button>

     <?php

    $select_post=mysqli_query($conn,"select * from products ORDER BY PID desc") or die(mysqli_error());

    while($post=mysqli_fetch_array($select_post))
    {

    ?>

        <div class="cbp-item <?php echo $post['PTYPE'];?>">

                    <img style="width:100%; height:200px;" src="UploadedImage/<?php echo $post['PIMAGELOC'];?>" alt="">

<?php echo $post['PNAME'];?>

                            <a href="delete_product.php?PID=<?php echo $post['PID']; ?>" class="cbp-l-caption-buttonLeft" data-title="Looking Publishing
reasonable always">Delete

        <?php
        }

    ?>

<?php } else{ echo " You mus Loggedin to acces this page"; }     ?>

Body:
The problem cannot be the browser because they are affected likewise in case of web server trouble. Check if you have cookies disabled in Google Chrome

If you are running your code in your own machine, make sure the local server is online mode; sometimes Mozilla Firefox is flexible in this case.

Something wrong in you code: you have </body> and </html> out of the PHP condition

EDIT

<?php
    session_start();
    include("connection.php");
  if (isset($_SESSION['adminid'])) {

?>
<!DOCTYPE html>
<html>
<head>

<title>SezaPharma AdminPanel</title>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="shortcut icon" type="image/png" href="images/favicon.png"/>

</head>
<body>

<div class="dashboard">
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">All Products</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Add New Product</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Setting</button>
<a href="logout.php" ><button class="tablinks" onclick="openCity(event, 'Tokyo')" >Logout</button></a>
</div>

<div id="London" class="tabcontent" style="overflow:auto">

 <div class="site_wrapper" >

 <div class="clearfix margin_top10"></div>

  <div class="works01"  >

   <div class="container"  >

 <div id="grid-container" class="cbp-l-grid-fullWidth"  style="overflow:visible;">

  <?php

$select_post=mysqli_query($conn,"select * from products ORDER BY PID desc") or die(mysqli_error());

while($post=mysqli_fetch_array($select_post))
{

?>

    <div class="cbp-item <?php echo $post['PTYPE'];?>">
        <div class="cbp-caption">
            <div class="cbp-caption-defaultWrap">
                <img style="width:100%; height:200px;" src="UploadedImage/<?php echo $post['PIMAGELOC'];?>" alt="">
            </div>
            <div class="cbp-caption-activeWrap">
                <div class="cbp-l-caption-alignCenter">
                    <div class="cbp-l-caption-body">
                        <h3><?php echo $post['PNAME'];?></h3>
                        <br />

                        <a href="delete_product.php?PID=<?php echo $post['PID']; ?>" class="cbp-l-caption-buttonLeft" data-title="Looking Publishing <br>reasonable always">Delete</a>
                    </div>
                </div>
            </div>
        </div>
    </div><!-- end item -->

    <?php
    }

?>

</div>

 </div>
 </div><!-- end works section -->

  <!-- ######### JS FILES ######### -->
  <!-- get jQuery used for the theme -->
  <script type="text/javascript" src="js/universal/jquery.js"></script>
  <script src="js/style-switcher/styleselector.js"></script>
  <script src="js/animations/js/animations.min.js" type="text/javascript">
  </script>
  <script src="js/mainmenu/bootstrap.min.js"></script>
  <script src="js/mainmenu/customeUI.js"></script>
  <script src="js/scrolltotop/totop.js" type="text/javascript"></script>
  <script type="text/javascript" src="js/mainmenu/sticky.js"></script>
  <script type="text/javascript" src="js/mainmenu/modernizr.custom.75180.js"></script>
  <script type="text/javascript" src="js/cubeportfolio/jquery.cubeportfolio.min.js"></script>
  <script type="text/javascript" src="js/cubeportfolio/main31.js"></script>
  </body>
  </html>
  <?php } else{ echo " You mus Loggedin to acces this page"; }   ?>


问:
AVCapturesession change video orientation while recording
I need to change the video orientation while recording a video using AVCaptureSession. I've make it to change the orientation before start recording using the following code but I need to change the orientation during the record process.

```<code>- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [self orientationChanged];
}

//Respond with the rotation
- (void)orientationChanged {
    AVCaptureConnection *videoConnection = nil;

    for ( AVCaptureConnection *connection in [_movieFileOutput connections] )
    {
        NSLog(@"%@", connection);
        for ( AVCaptureInputPort *port in [connection inputPorts] )
        {
            NSLog(@"%@", port);
            if ( [[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
    }

    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if (deviceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];
    }
    else if (deviceOrientation == UIInterfaceOrientationPortrait) {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
    }

    else if (deviceOrientation == UIInterfaceOrientationLandscapeLeft) {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft];
    }

    else {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
    }
}
</code>```

答:
You can use this code to change the orientation during the record process:</p>

```<code>AVCaptureConnection *videoConnection = [self.videoOutPut connectionWithMediaType:AVMediaTypeVideo];
- (void)_setOrientationForConnection:(AVCaptureConnection *)connection
{
    if (!connection || ![connection isVideoOrientationSupported])
        return;

    AVCaptureVideoOrientation captureOrientation = AVCaptureVideoOrientationPortrait;

    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    switch (deviceOrientation) {
        case UIDeviceOrientationLandscapeLeft:
            captureOrientation = AVCaptureVideoOrientationLandscapeRight;
            break;
        case UIDeviceOrientationLandscapeRight:
            captureOrientation = AVCaptureVideoOrientationLandscapeLeft;
            break;
        case UIDeviceOrientationPortrait:
            captureOrientation = AVCaptureVideoOrientationPortrait;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            captureOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            break;
        default:
            break;
    }

    [connection setVideoOrientation:captureOrientation];
}
</code>```

Body:
I need to change the video orientation while recording a video using AVCaptureSession. I've make it to change the orientation before start recording using the following code but I need to change the orientation during the record process.

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [self orientationChanged];
}

//Respond with the rotation
- (void)orientationChanged {
    AVCaptureConnection *videoConnection = nil;

    for ( AVCaptureConnection *connection in [_movieFileOutput connections] )
    {
        NSLog(@"%@", connection);
        for ( AVCaptureInputPort *port in [connection inputPorts] )
        {
            NSLog(@"%@", port);
            if ( [[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
    }

    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if (deviceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];
    }
    else if (deviceOrientation == UIInterfaceOrientationPortrait) {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
    }

    else if (deviceOrientation == UIInterfaceOrientationLandscapeLeft) {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft];
    }

    else {
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
        [videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
    }
}

Body:
You can use this code to change the orientation during the record process:

AVCaptureConnection *videoConnection = [self.videoOutPut connectionWithMediaType:AVMediaTypeVideo];
- (void)_setOrientationForConnection:(AVCaptureConnection *)connection
{
    if (!connection || ![connection isVideoOrientationSupported])
        return;

    AVCaptureVideoOrientation captureOrientation = AVCaptureVideoOrientationPortrait;

    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    switch (deviceOrientation) {
        case UIDeviceOrientationLandscapeLeft:
            captureOrientation = AVCaptureVideoOrientationLandscapeRight;
            break;
        case UIDeviceOrientationLandscapeRight:
            captureOrientation = AVCaptureVideoOrientationLandscapeLeft;
            break;
        case UIDeviceOrientationPortrait:
            captureOrientation = AVCaptureVideoOrientationPortrait;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            captureOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            break;
        default:
            break;
    }

    [connection setVideoOrientation:captureOrientation];
}


问:
Print HTML table in console using Java
I have a StringBuilder which contains a HTML table. I want to know, if I can print this table in the console using some kind of library or anything.
For example:

```<code>StringBuilder string = "<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
</table>"
</code>```

I want to print this above string in a table format in console such that I do not need to specify any table information like column header or any other information.

答:
@jhutan try this one to generate the output you are looking for.</p>

```<code>public static void main(String[] args) throws IOException {
    String html = "https://www.w3schools.com/html/html_tables.asp";
    Document doc = Jsoup.connect(html).get();
    Elements tableElements = doc.select("table");
    Elements tableHeaderEles = tableElements.select("th");
    System.out.println("headers");
    System.out.println("tableHeaderEles.size()" + tableHeaderEles.size());
    StringBuilder th = new StringBuilder();
    for (int i = 0; i < tableHeaderEles.size(); i++) {

        th.append(tableHeaderEles.get(i).text());
        th.append(" ");
    }
    System.out.println(th);

    Elements tableRowElements = tableElements.select(":not(thead) tr");
    for (int i = 0; i < tableRowElements.size(); i++) {
        Element row = tableRowElements.get(i);
        Elements rowItems = row.select("td");
        StringBuilder a = new StringBuilder();
        for (int j = 0; j < rowItems.size(); j++) {
            a.append(rowItems.get(j).text());
        }
        System.out.println(" " + a);
        //  System.out.println();
    }
}
</code>```

Title: Print HTML table in console using Java

Body:
I have a StringBuilder which contains a HTML table. I want to know, if I can print this table in the console using some kind of library or anything.
For example:

StringBuilder string = "

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

"

I want to print this above string in a table format in console such that I do not need to specify any table information like column header or any other information.

Body:
@jhutan try this one to generate the output you are looking for.

public static void main(String[] args) throws IOException {
    String html = "https://www.w3schools.com/html/html_tables.asp";
    Document doc = Jsoup.connect(html).get();
    Elements tableElements = doc.select("table");
    Elements tableHeaderEles = tableElements.select("th");
    System.out.println("headers");
    System.out.println("tableHeaderEles.size()" + tableHeaderEles.size());
    StringBuilder th = new StringBuilder();
    for (int i = 0; i < tableHeaderEles.size(); i++) {

        th.append(tableHeaderEles.get(i).text());
        th.append(" ");
    }
    System.out.println(th);

    Elements tableRowElements = tableElements.select(":not(thead) tr");
    for (int i = 0; i < tableRowElements.size(); i++) {
        Element row = tableRowElements.get(i);
        Elements rowItems = row.select("td");
        StringBuilder a = new StringBuilder();
        for (int j = 0; j < rowItems.size(); j++) {
            a.append(rowItems.get(j).text());
        }
        System.out.println(" " + a);
        //  System.out.println();
    }
}


问:
How to bind bootstrap modal using *ngFor in angular2
I want to display my data in the bootstrap modal using angular2. I have binded my data in modal using '*ngFor'. But using *ngFor, modal not showing data as per their behaviour(when clicking on the right arrow, data should change and first data come as default). but when I apply active class with the 'item', its showing complete data but in vertically format. And I want it should show one image and its detail in one's.

Here is my

app.component.html

```<code><div class="modal fade" id="feedbackModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" title="Close"> <span class="glyphicon glyphicon-remove"></span></button>
            </div>
            <div class="modal-body">
                <div class="row text-center">
                    <h4>Details</h4>
                </div>

                <div id="myGallery" class="carousel slide" data-interval="false">
                    <div class="carousel-inner">
                        <div class="item active" *ngFor="let modalData of cnnTableData">
                            <div class="row">
                                <div class="col-sm-6">
                                    <br>
                                    <img src={{modalData.Image}} style="width:100%;min-height: 211px;">
                                </div>
                                <div class="col-sm-6">
                                    <div>
                                        <h6><b>Image Name</b></h6>
                                        <small>{{modalData.Name}}</small>
                                    </div><br>
                                </div>
                            </div>
                        </div>
                    </div>
                    <a class="left carousel-control" href="#myGallery" role="button" data-slide="prev" style="margin-left: -84px;"> <span class="glyphicon glyphicon-chevron-left"></span></a>
                    <a class="right carousel-control" href="#myGallery" role="button" data-slide="next" style="margin-right: -84px;"> <span class="glyphicon glyphicon-chevron-right"></span></a>

                </div>
            </div>
            <div class="modal-footer">
                <br><br>
            </div>
        </div>
    </div>
</div>
</code>```

And my output which is coming from above code :

答:
at first you need to organize the application, divide your application into components.

for example create a component represent the HTML template where *ngFor directive is mentioned in you application

the component  TypeScript  file

```

    @Component({
        selector: 'my-component',
        templateUrl: 'my-component.html', // mentioned below
      })
      export class myComponent implements OnChanges, OnInit{
        @Input index:number;
        @Input selectedIndex:number;

        className:string;

       ngOnInit(){
         this.className = index==0?"active":"";
       }

       ngOnChanges(){
         if(selectedIndex == index)
           this.className = "active";
         else
           this.className = "";
       }
      }

```

and this is the component template, HTML file

```<code><div [class]="'item' className">
   <div class="row">
      <div class="col-sm-6">
          <br>
              <img src={{modalData.Image}} style="width:100%;min-height: 211px;">
     </div>
     <div class="col-sm-6">
          <div>
             <h6><b>Image Name</b></h6>
             <small>{{modalData.Name}}</small>
          </div><br>
     </div>
 </div>
</code>```

now we have the component, lets use it in the appComponent.

inside the appComponent

```<code> <my-component
*ngFor=" let modalData of cnnTableData ;#i = index"
[index]="i"
[selectedIndex]="currentIndex"> //current index is in the appComponent class
</my-component>
</code>```

inside the appComponent class you need to track the click event and reflect it to the variable currentIndex

```<code>currentIndex:number = 0;

clickLeft(){
  this.currentIndex++;
}

clickRight(){
  this.currentIndex--;
}

// take in account the length of the items.
</code>```

Body:
I want to display my data in the bootstrap modal using angular2. I have binded my data in modal using '*ngFor'. But using *ngFor, modal not showing data as per their behaviour(when clicking on the right arrow, data should change and first data come as default). but when I apply active class with the 'item', its showing complete data but in vertically format. And I want it should show one image and its detail in one's.

Here is my

app.component.html

                <button type="button" class="close" data-dismiss="modal" title="Close"> </button>

Details

Image Name

                                        {{modalData.Name}}

And my output which is coming from above code :

Body:
at first you need to organize the application, divide your application into components.

for example create a component represent the HTML template where *ngFor directive is mentioned in you application

the component  TypeScript  file

    @Component({
        selector: 'my-component',
        templateUrl: 'my-component.html', // mentioned below
      })
      export class myComponent implements OnChanges, OnInit{
        @Input index:number;
        @Input selectedIndex:number;

        className:string;

       ngOnInit(){
         this.className = index==0?"active":"";
       }

       ngOnChanges(){
         if(selectedIndex == index)
           this.className = "active";
         else
           this.className = "";
       }
      }

and this is the component template, HTML file

<div [class]="'item' className">
   <div class="row">
      <div class="col-sm-6">
          <br>
              <img src={{modalData.Image}} style="width:100%;min-height: 211px;">
     </div>
     <div class="col-sm-6">
          <div>
             <h6><b>Image Name</b></h6>
             <small>{{modalData.Name}}</small>
          </div><br>
     </div>
 </div>

now we have the component, lets use it in the appComponent.

inside the appComponent

 <my-component
*ngFor=" let modalData of cnnTableData ;#i = index"
[index]="i"
[selectedIndex]="currentIndex"> //current index is in the appComponent class
</my-component>

inside the appComponent class you need to track the click event and reflect it to the variable currentIndex

currentIndex:number = 0;

clickLeft(){
  this.currentIndex++;
}

clickRight(){
  this.currentIndex--;
}

// take in account the length of the items.