问:
unable to get intent message on click of notification
Hello this problem focuses on

On click of notification, app should load different url in web view

Problem here I am not able to get pending intent value using .getStringExtra in MainActivity.java  I am getting null every time

I am not an android guy so plz don't judge me if I have done any silly mistake

Posting code for three files

Main_activity

MyNotificationManager

MyFireBaseMessagingServices

MainActivity

```<code>package com.xyz.zzz;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import static android.R.attr.button;

 public class MainActivity extends AppCompatActivity{
    private TextView textView;
    private BroadcastReceiver broadcastReceiver;
    private Button buttonRegister;
    private LinearLayout WB;
    private LinearLayout WB_ERROR;
    public String notiIntent  = "false";
    WebView webView;
    private boolean loadcheck = true;
    private String loaderror ="No Error";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WB = (LinearLayout)this.findViewById(R.id.webViewLayout);
        WB_ERROR = (LinearLayout)this.findViewById(R.id.webErrorLayout);
        final ProgressDialog progDailog = ProgressDialog.show(this, "", "Loading...",true);
        final TextView textViewToChange = (TextView) findViewById(R.id.errorMsg);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedError(WebView view, int error_code, String description , String falingUrl){
                //  webView.loadUrl("file:///android_assets/error.html");
                WB.setVisibility(LinearLayout.GONE);
                WB_ERROR.setVisibility(LinearLayout.VISIBLE);
                loadcheck = false;
                loaderror = description;
                if(error_code == -8 || error_code == -6) {
                    textViewToChange.setText("Poor Internet Connectivity");
                }
                if(error_code == -14 || error_code == -2){
                    textViewToChange.setText("No Internet Connection");
                }
                /*Toast.makeText(MainActivity.this, "This is my Toast message!"+ error_code,
                        Toast.LENGTH_LONG).show();*/
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                progDailog.show();
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onPageFinished(WebView view, final String url) {
                if (progDailog != null && progDailog.isShowing()) {
                    progDailog.dismiss();
                }

               /* Toast.makeText(MainActivity.this, "This is my Toast message!",
                        Toast.LENGTH_LONG).show();
                Log.e("onpageload" , view);*/
                //WB.setVisibility(LinearLayout.VISIBLE);
            }

        });

        Bundle extra = getIntent().getExtras();
        if(extra != null) {
            Log.d("Notification", extra.("url") + "hello Noti");
        }
        Intent intent = this.getIntent();
        if(intent != null && intent.getStringExtra("url") != null ) {
            Log.d("Notification", intent.getStringExtra("url"));
        }
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null)
            {
                //Cry about not being clicked on
            }
            else if (extras.getBoolean("NotiClick"))
            {
                //Do your stuff here mate :)
            }

        }

        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.loadUrl("example.com/index.php?" + SharedPrefManager.getmInstance(this).getToken());
        buttonRegister = (Button) findViewById(R.id.retryButton);
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progDailog.show();
                createWebView();
                checkERROR();
            }
        });

        Log.d("sas",SharedPrefManager.getmInstance(this).getToken());
        Log.d("Click Intent",notiIntent);
    }

    public void createWebView(){
        webView.loadUrl("example.com/index.php?" + SharedPrefManager.getmInstance(this).getToken());
    }

    public void checkERROR(){
        if(loadcheck != false){
            WB.setVisibility(LinearLayout.VISIBLE);
            WB_ERROR.setVisibility(LinearLayout.GONE);
        }
    }

    public void setNotiIntent(){
     notiIntent = "true";
        Log.d("ssssss","asas");
    }

}
</code>```

Now MYFIREBASEMESSAGING SERVICES

```<code>package com.XYZ.anew;

import android.content.Intent;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import static com.google.android.gms.internal.zzs.TAG;

/**
 * Created by AR on 16-10-2017.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCMmessageR";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be:
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body1: " + remoteMessage.getNotification().getBody());
        }
        Log.d(TAG, "Message Notification Body2: " + remoteMessage.getNotification().getBody());
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        notifyUser(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
    }

    public void notifyUser(String from , String notification){
        MyNotificationManager  myNotificationManager = new MyNotificationManager(getApplicationContext());
        myNotificationManager.showNotification(from , notification , new Intent(getApplicationContext() , MainActivity.class));
    }
}
</code>```

Now MY NOTIFICATION MANAGER

```<code>package com.XYZ.anew;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by AR on 16-10-2017.
 */

public class MyNotificationManager{
    private Context ctx;

    public static final int NOTIFICATION_ID = 234;
    public MyNotificationManager(Context ctx){
        this.ctx = ctx;
    }
    public void showNotification(String from, String notification , Intent intent){
        MainActivity ctsx = new MainActivity();
        ctsx.setNotiIntent();
        intent.putExtra("url",true);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                ctx,
                NOTIFICATION_ID,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);

        Notification mNotification = builder.setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setContentTitle(from)
                .setContentText(notification)
                .setSound(uri)
                .build();
        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotification.defaults |= Notification.DEFAULT_SOUND;

        NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID , mNotification);

    }
}
</code>```

答:
Your problem is here:

```<code>intent.putExtra("url",true);
</code>```

You added an "extra" with the key "url" and the value "true". This is a boolean. If you call getStringExtra("url") you will get null. If you call ``getBooleanExtra("url")you will gettrue`.

Also...

You absolutely positively cannot do this (in showNotification()):

```<code>    MainActivity ctsx = new MainActivity();
</code>```

Only Android can instantiate Android components (Service, Activity, etc.).

If you need a Context, you need to have it passed into your method.

Body:
Hello this problem focuses on

On click of notification, app should load different url in web view

Problem here I am not able to get pending intent value using .getStringExtra in MainActivity.java  I am getting null every time

I am not an android guy so plz don't judge me if I have done any silly mistake

Posting code for three files

Main_activity

MyNotificationManager

MyFireBaseMessagingServices

MainActivity

package com.xyz.zzz;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import static android.R.attr.button;

 public class MainActivity extends AppCompatActivity{
    private TextView textView;
    private BroadcastReceiver broadcastReceiver;
    private Button buttonRegister;
    private LinearLayout WB;
    private LinearLayout WB_ERROR;
    public String notiIntent  = "false";
    WebView webView;
    private boolean loadcheck = true;
    private String loaderror ="No Error";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WB = (LinearLayout)this.findViewById(R.id.webViewLayout);
        WB_ERROR = (LinearLayout)this.findViewById(R.id.webErrorLayout);
        final ProgressDialog progDailog = ProgressDialog.show(this, "", "Loading...",true);
        final TextView textViewToChange = (TextView) findViewById(R.id.errorMsg);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedError(WebView view, int error_code, String description , String falingUrl){
                //  webView.loadUrl("file:///android_assets/error.html");
                WB.setVisibility(LinearLayout.GONE);
                WB_ERROR.setVisibility(LinearLayout.VISIBLE);
                loadcheck = false;
                loaderror = description;
                if(error_code == -8 || error_code == -6) {
                    textViewToChange.setText("Poor Internet Connectivity");
                }
                if(error_code == -14 || error_code == -2){
                    textViewToChange.setText("No Internet Connection");
                }
                /*Toast.makeText(MainActivity.this, "This is my Toast message!"+ error_code,
                        Toast.LENGTH_LONG).show();*/
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                progDailog.show();
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onPageFinished(WebView view, final String url) {
                if (progDailog != null && progDailog.isShowing()) {
                    progDailog.dismiss();
                }

               /* Toast.makeText(MainActivity.this, "This is my Toast message!",
                        Toast.LENGTH_LONG).show();
                Log.e("onpageload" , view);*/
                //WB.setVisibility(LinearLayout.VISIBLE);
            }

        });

        Bundle extra = getIntent().getExtras();
        if(extra != null) {
            Log.d("Notification", extra.("url") + "hello Noti");
        }
        Intent intent = this.getIntent();
        if(intent != null && intent.getStringExtra("url") != null ) {
            Log.d("Notification", intent.getStringExtra("url"));
        }
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null)
            {
                //Cry about not being clicked on
            }
            else if (extras.getBoolean("NotiClick"))
            {
                //Do your stuff here mate :)
            }

        }

        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.loadUrl("example.com/index.php?" + SharedPrefManager.getmInstance(this).getToken());
        buttonRegister = (Button) findViewById(R.id.retryButton);
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progDailog.show();
                createWebView();
                checkERROR();
            }
        });

        Log.d("sas",SharedPrefManager.getmInstance(this).getToken());
        Log.d("Click Intent",notiIntent);
    }

    public void createWebView(){
        webView.loadUrl("example.com/index.php?" + SharedPrefManager.getmInstance(this).getToken());
    }

    public void checkERROR(){
        if(loadcheck != false){
            WB.setVisibility(LinearLayout.VISIBLE);
            WB_ERROR.setVisibility(LinearLayout.GONE);
        }
    }

    public void setNotiIntent(){
     notiIntent = "true";
        Log.d("ssssss","asas");
    }

}

Now MYFIREBASEMESSAGING SERVICES

package com.XYZ.anew;

import android.content.Intent;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import static com.google.android.gms.internal.zzs.TAG;

/**
 * Created by AR on 16-10-2017.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCMmessageR";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be:
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body1: " + remoteMessage.getNotification().getBody());
        }
        Log.d(TAG, "Message Notification Body2: " + remoteMessage.getNotification().getBody());
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        notifyUser(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
    }

    public void notifyUser(String from , String notification){
        MyNotificationManager  myNotificationManager = new MyNotificationManager(getApplicationContext());
        myNotificationManager.showNotification(from , notification , new Intent(getApplicationContext() , MainActivity.class));
    }
}

Now MY NOTIFICATION MANAGER

package com.XYZ.anew;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by AR on 16-10-2017.
 */

public class MyNotificationManager{
    private Context ctx;

    public static final int NOTIFICATION_ID = 234;
    public MyNotificationManager(Context ctx){
        this.ctx = ctx;
    }
    public void showNotification(String from, String notification , Intent intent){
        MainActivity ctsx = new MainActivity();
        ctsx.setNotiIntent();
        intent.putExtra("url",true);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                ctx,
                NOTIFICATION_ID,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);

        Notification mNotification = builder.setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setContentTitle(from)
                .setContentText(notification)
                .setSound(uri)
                .build();
        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotification.defaults |= Notification.DEFAULT_SOUND;

        NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID , mNotification);

    }
}

Body:
Your problem is here:

intent.putExtra("url",true);

You added an "extra" with the key "url" and the value "true". This is a boolean. If you call getStringExtra("url") you will get null. If you call ``getBooleanExtra("url")you will gettrue`.

Also...

You absolutely positively cannot do this (in showNotification()):

    MainActivity ctsx = new MainActivity();

Only Android can instantiate Android components (Service, Activity, etc.).

If you need a Context, you need to have it passed into your method.


来源: stackexchange

问:
MySQL / PHP - Multi tier category structure
I'm building a website that contains a product database. Each product belongs to a category. The structure of categories is multi-tiered and can contain any number of tiers, for example:

Electronics > Games Consoles > Xbox > Xbox One > Games > etc..

Fashion > Mens > Shirts > Long Sleeved

I always assign the product to the "last" category in the tier.

Here is the structure of my category table:

```<code>id       name            parent_id
================================
1        Fashion         NULL
2        Mens            1
3        Shirts          2
4        Long Sleeved    3
5        Short Sleeved   3
</code>```

I'm using Yii2 as my application framework, but the same concepts should apply to most MVC Frameworks, or at least those that implement an ORM like ActiveRecord.

What I want to do is:

For any category level, get the "master" parent. I.e. for Shirts it would be Fashion

For any category level, get all "last" level categories in the tier. I.e. for Mens it would be Long Sleeved and Short Sleeved.

(more advanced) For any category level, find out the number of children / parents it has.

I have the following default relations in my model:

```<code>public function getParent()
{
    return $this->hasOne(Category::className(), ['id' => 'parent_id']);
}

public function getParent()
{
    return $this->hasMany(Category::className(), ['parent_id' => 'id']);
}
</code>```

The following is a function I have created which outputs the "tree" for any given category:

```<code>public function getParentTree()
{
    $array = [];

    // $this->parent refers to the 'getParent()' relation above
    if(!empty($this->parent))
    {
        $array[] = $this->parent->name;

        if(!empty($this->parent->parent))
            $array[] = $this->parent->parent->name;

                if(!empty($this->parent->parent->parent))
                    $array[] = $this->parent->parent->parent->name;
    }
    else
        $array[] = "(none)";

    $output = implode(" --> ", array_reverse($array));

    return $output;
}
</code>```

But there is a lot of repetition here and it looks ugly. But it is also leading me to be believe perhaps I have taken the wrong approach and need to restructure the database itself?

答:
Bill I think I have resolved this issue in YII2 -> Models.

Below is my code.

```<code>public static function getSubCategories($parent_id = NULL, $level = 0)
{
    // Get the Category from table
    // Here you can use caching Yii::$app->cache->get to avoid multiple queries
    $categories = Category::find()->select(['id', 'parent_id', 'name'])->where(['parent_id' => $parent_id])->asArray()->all();

    // Logic of Nth level to return
    self::$max_down_level += 1;
    if($level != 0 && self::$max_down_level > $level) return $categories;

    // Now for each sub categories find and return chidren as Array
    foreach($categories as $key => $category)
    {
        $categories[$key]['children'] = self::getSubCategories($category['id'], $level);
    }

    return $categories;
}
</code>```

Also do not forget to declare public static $max_down_level = 0; variable in your model class. and now call the function like below.

To get all the children of Parent category self::getSubCategories(NULL)

To get all the children up to 2nd level self::getSubCategories(NULL, 2)

Same way above you can declare recursive function for getting parent Categories.

```<code>public static function getParentCategories($parent_id, $level = 0)
{
    // Get the Category from table
    // Here you can use caching Yii::$app->cache->get to avoid multiple queries
    $categories = Category::find()->select(['id', 'parent_id', 'name'])->where(['id' => $parent_id])->asArray()->all();

    // Logic of Nth level to return
    self::$max_up_level += 1;
    if($level != 0 && self::$max_up_level > $level) return $categories;

    foreach($categories as $key => $category)
    {
        $categories[$key]['parent'] = self::getParentCategories($category['parent_id'], $level);
    }

    return $categories;
}
</code>```

Also do not forget to declare public static $max_up_level = 0; variable in your model class. and now call the function like below.

To get all the children of Parent category self::getParentCategories(16, 0)

To get all the children up to 2nd level self::getParentCategories(16, 2)

You can use your own class name instead of self

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm building a website that contains a product database. Each product belongs to a category. The structure of categories is multi-tiered and can contain any number of tiers, for example:

Electronics > Games Consoles > Xbox > Xbox One > Games > etc..

Fashion > Mens > Shirts > Long Sleeved

I always assign the product to the "last" category in the tier.

Here is the structure of my category table:

id       name            parent_id
================================
1        Fashion         NULL
2        Mens            1
3        Shirts          2
4        Long Sleeved    3
5        Short Sleeved   3

I'm using Yii2 as my application framework, but the same concepts should apply to most MVC Frameworks, or at least those that implement an ORM like ActiveRecord.

What I want to do is:

For any category level, get the "master" parent. I.e. for Shirts it would be Fashion

For any category level, get all "last" level categories in the tier. I.e. for Mens it would be Long Sleeved and Short Sleeved.

(more advanced) For any category level, find out the number of children / parents it has.

I have the following default relations in my model:

public function getParent()
{
    return $this->hasOne(Category::className(), ['id' => 'parent_id']);
}

public function getParent()
{
    return $this->hasMany(Category::className(), ['parent_id' => 'id']);
}

The following is a function I have created which outputs the "tree" for any given category:

public function getParentTree()
{
    $array = [];

    // $this->parent refers to the 'getParent()' relation above
    if(!empty($this->parent))
    {
        $array[] = $this->parent->name;

        if(!empty($this->parent->parent))
            $array[] = $this->parent->parent->name;

                if(!empty($this->parent->parent->parent))
                    $array[] = $this->parent->parent->parent->name;
    }
    else
        $array[] = "(none)";

    $output = implode(" --> ", array_reverse($array));

    return $output;
}

But there is a lot of repetition here and it looks ugly. But it is also leading me to be believe perhaps I have taken the wrong approach and need to restructure the database itself?

Body:
Bill I think I have resolved this issue in YII2 -> Models.

Below is my code.

public static function getSubCategories($parent_id = NULL, $level = 0)
{
    // Get the Category from table
    // Here you can use caching Yii::$app->cache->get to avoid multiple queries
    $categories = Category::find()->select(['id', 'parent_id', 'name'])->where(['parent_id' => $parent_id])->asArray()->all();

    // Logic of Nth level to return
    self::$max_down_level += 1;
    if($level != 0 && self::$max_down_level > $level) return $categories;

    // Now for each sub categories find and return chidren as Array
    foreach($categories as $key => $category)
    {
        $categories[$key]['children'] = self::getSubCategories($category['id'], $level);
    }

    return $categories;
}

Also do not forget to declare public static $max_down_level = 0; variable in your model class. and now call the function like below.

To get all the children of Parent category self::getSubCategories(NULL)

To get all the children up to 2nd level self::getSubCategories(NULL, 2)

Same way above you can declare recursive function for getting parent Categories.

public static function getParentCategories($parent_id, $level = 0)
{
    // Get the Category from table
    // Here you can use caching Yii::$app->cache->get to avoid multiple queries
    $categories = Category::find()->select(['id', 'parent_id', 'name'])->where(['id' => $parent_id])->asArray()->all();

    // Logic of Nth level to return
    self::$max_up_level += 1;
    if($level != 0 && self::$max_up_level > $level) return $categories;

    foreach($categories as $key => $category)
    {
        $categories[$key]['parent'] = self::getParentCategories($category['parent_id'], $level);
    }

    return $categories;
}

Also do not forget to declare public static $max_up_level = 0; variable in your model class. and now call the function like below.

To get all the children of Parent category self::getParentCategories(16, 0)

To get all the children up to 2nd level self::getParentCategories(16, 2)

You can use your own class name instead of self

Hope this helps.


问:
Disabled <input> that allows text selection?
Is it possible for a disabled <input> tag to support text selection?

答: You may want to use a readonly input and style it with CSS.

ContentLicense: CC BY-SA 2.5


问:
Making a two dimensional arraylist
I would like to make a two dimensional arraylist.
Currently I have an arraylist which displays all values.
I would like to put these values in arraylist of arraylist which would look like this:
from [value1,value2,value3,value4,value5,value6]

to
[[value1,value2,value3],[value4,value5,value6]]

How can I achieve this?

Thanks in advance

Edit: So I have an Arraylist with the some random values (string)
[**Activity_Name,Activity,Name**,value4,value5,value6,value7,value8,value9]

I would like to group every 3 values in another arraylist which would look like this:
[[value1,value2,value],
[value4,value5,value6] etc

But at the moment it only gives me the value of the first 3 components so:
[[activityname,activity,name],
[activityname,activity,name] etc

答:
Here is a simple example, a list of list of integers:

```<code>ArrayList<ArrayList<Integer>> a = new ArrayList<>();
a.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
a.add(new ArrayList<>(Arrays.asList(3, 4, 5)));
System.out.println(a);
</code>```

Output:

[[1, 2, 3], [3, 4, 5]]

Is that what you want, just some simple array lists, it's a bit ugly to add a list to another list like this, but just Arrays.asList(1, 2, 3) doesn't work in Java.

Ok here my extended answer, it divides the list in 3 element sublists, you can use ArrayList.subList for that:

```<code>ArrayList<String> src = new ArrayList<>(Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9"));
ArrayList<ArrayList<String>> dst = new ArrayList<>();

for (int i = 0; i < src.size(); i+=3) {
    dst.add(new ArrayList<>(src.subList(i, i + 3)));
}

System.out.println(dst);
</code>```

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Title: Making a two dimensional arraylist

Body:
Here is a simple example, a list of list of integers:

ArrayList<ArrayList<Integer>> a = new ArrayList<>();
a.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
a.add(new ArrayList<>(Arrays.asList(3, 4, 5)));
System.out.println(a);

Output:

[[1, 2, 3], [3, 4, 5]]

Is that what you want, just some simple array lists, it's a bit ugly to add a list to another list like this, but just Arrays.asList(1, 2, 3) doesn't work in Java.

Ok here my extended answer, it divides the list in 3 element sublists, you can use ArrayList.subList for that:

ArrayList<String> src = new ArrayList<>(Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9"));
ArrayList<ArrayList<String>> dst = new ArrayList<>();

for (int i = 0; i < src.size(); i+=3) {
    dst.add(new ArrayList<>(src.subList(i, i + 3)));
}

System.out.println(dst);

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


问:
fetch response.json() and response.status
Is this the only way to use the body.json() and also get the status code?

```<code>let status;

return fetch(url)
    .then((response => {
         status = response.status;
         return response.json()
     })
    .then(response => {
        return {
            response: response,
            status: status
        }
    });
</code>```

This doesn't work as it returns a promise in the response field:

```<code>.then((response)=> {return {response: response.json(), status: response.status}})
</code>```

答:
Did you try this?</p>

```<code>return fetch(url)
    .then((r)=> {return {response: r.json(), status: r.status}})
</code>```

Body:
Is this the only way to use the body.json() and also get the status code?

let status;

return fetch(url)
    .then((response => {
         status = response.status;
         return response.json()
     })
    .then(response => {
        return {
            response: response,
            status: status
        }
    });

This doesn't work as it returns a promise in the response field:

.then((response)=> {return {response: response.json(), status: response.status}})

Body:
Did you try this?

return fetch(url)
    .then((r)=> {return {response: r.json(), status: r.status}})


问:
FileName -FilePath comparison
I'm trying to compare the 2 file names.

I build a file name and then compare it to the one in the directory. My code is not able to compare the strings. Please let me know, what am I doing wrong? There are no errors, but the the strings is never equal.

```<code>DateTime dt = DateTime.Now;
Filename = "Account Daily " + dt.ToString("yyyy-MM-dd") + " .xslx";

FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
    if (String.Compare(aFile.ToString(),Filename) == 1)
    {
        // Send email with this attachment
    }
}
</code>```

答:
If all you're trying to do is check to see if there is a particular file in a particular folder, then you could use the GetFiles() overload that has a searchpattern argument to find files that appear to have today's date:

```<code>Directory.GetFiles("c:\\my\\path", $"*{DateTime.Now.ToString("yyyy-MM-dd")}.xlsx");
</code>```

Title: FileName -FilePath comparison

Body:
I'm trying to compare the 2 file names.

I build a file name and then compare it to the one in the directory. My code is not able to compare the strings. Please let me know, what am I doing wrong? There are no errors, but the the strings is never equal.

DateTime dt = DateTime.Now;
Filename = "Account Daily " + dt.ToString("yyyy-MM-dd") + " .xslx";

FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
    if (String.Compare(aFile.ToString(),Filename) == 1)
    {
        // Send email with this attachment
    }
}

Body:
If all you're trying to do is check to see if there is a particular file in a particular folder, then you could use the GetFiles() overload that has a searchpattern argument to find files that appear to have today's date:

Directory.GetFiles("c:\\my\\path", $"*{DateTime.Now.ToString("yyyy-MM-dd")}.xlsx");


答:
Say you want to create a 2D arraylist of strings you can do the following in Java 8.

```<code>public class Test {

  public static void print2DStringList(List<List<String>> twoDList){
      if(twoDList != null){
         System.out.println("*****2D list content*****");
         for(List<String> sublist: twoDList){
            for(String str: sublist){
                System.out.println(str);
            }
            System.out.println("-----------");
         }
      }
  }

  public static void main(String... args){

     List<List<String>> twoDList = new ArrayList<>();

     for(int i=1; i <= 2; i++){
        twoDList.add(new ArrayList<String>());
        for(int j=1; j <= 3; j++){
          twoDList.get(i).add("Sub list " + i + " item " + j);
        }
     }

     System.out.println("=> Initialize List");
     print2DStringList(twoDList);

     //Adding an item into sublist2 of twoDList
     twoDList.get(1).add("Here is another item");

     System.out.println("=> After adding another item");
     print2DStringList(twoDList);

     //modifying the first item of sublist1 of twoDList
     twoDList.get(0).set(0,"***Sub list 1 item 1***");

     System.out.println("=> After modifying the first item of sublist1");
     print2DStringList(twoDList);

  }

}
</code>```

That's just the logic

Title: Making a two dimensional arraylist

Body:
I would like to make a two dimensional arraylist.
Currently I have an arraylist which displays all values.
I would like to put these values in arraylist of arraylist which would look like this:
from [value1,value2,value3,value4,value5,value6]

to
[[value1,value2,value3],[value4,value5,value6]]

How can I achieve this?

Thanks in advance

Edit: So I have an Arraylist with the some random values (string)
[**Activity_Name,Activity,Name**,value4,value5,value6,value7,value8,value9]

I would like to group every 3 values in another arraylist which would look like this:
[[value1,value2,value],
[value4,value5,value6] etc

But at the moment it only gives me the value of the first 3 components so:
[[activityname,activity,name],
[activityname,activity,name] etc

Body:
Say you want to create a 2D arraylist of strings you can do the following in Java 8.

public class Test {

  public static void print2DStringList(List<List<String>> twoDList){
      if(twoDList != null){
         System.out.println("*****2D list content*****");
         for(List<String> sublist: twoDList){
            for(String str: sublist){
                System.out.println(str);
            }
            System.out.println("-----------");
         }
      }
  }

  public static void main(String... args){

     List<List<String>> twoDList = new ArrayList<>();

     for(int i=1; i <= 2; i++){
        twoDList.add(new ArrayList<String>());
        for(int j=1; j <= 3; j++){
          twoDList.get(i).add("Sub list " + i + " item " + j);
        }
     }

     System.out.println("=> Initialize List");
     print2DStringList(twoDList);

     //Adding an item into sublist2 of twoDList
     twoDList.get(1).add("Here is another item");

     System.out.println("=> After adding another item");
     print2DStringList(twoDList);

     //modifying the first item of sublist1 of twoDList
     twoDList.get(0).set(0,"***Sub list 1 item 1***");

     System.out.println("=> After modifying the first item of sublist1");
     print2DStringList(twoDList);

  }

}

That's just the logic


问:
Why should I NOT use the /optimize switch to compile my C# code?
In Visual Studio 2008 there is an option "Optimize Code" that probably corresponds to the /optimize option. It is never enabled, not even when in "Release" mode.

Why should I not want this option to be enabled at all times?

答:
To make this clear, optimization does inline functions and eliminate some variables. When debugging optimized code, you won't get as much help by the IDE as usual, since some of the code actually does not exist anymore. So for debugging, turn if off (default).

In languages like C++ optimization sometimes (often) has critical side effect that need to be considered. As far as i know, this is not or almost not the case for C#, so from the point of correctness of your code, it probably does not matter if you optimize or not.

OwnerDisplayName: boris callens

OwnerDisplayName: mafutrct


问:
Add Seperate Sum Functions to an IQueryable LINQ Statement
I'm looking to populate a Telerik RadGrid with an IQueryable DataSource but include 5 Total columns inside that Grid. I have built separate functions for the Totals when I create individual reports, but am having some trouble iterating them into my current LINQ statement for the Grid.

My current LINQ statement looks like this:

```<code>public static IQueryable GetUnapprovedTimesheets(string Period)
    {
        DataContext Data = new DataContext();

        var Times = (from c in Data.System_Times
                     where c.Period == Period && c.Status == 1
                     orderby c.Employee.LName
                     select c).GroupBy(s => s.EmployeeID).Select(x => x.FirstOrDefault());

        return Times;
    }
</code>```

This statement grabs the Timesheets for the Period entered, and shows the records with a status of 1, these are then displayed grouped by EmployeeID. This statement pulls everything into the Grid properly but I would like to also add Totals for Regular, Overtime, Travel, and Sub.

The functions I have built separately for dynamic reporting look something like this:

```<code>public static decimal? GetTotalReg(int EmployeeID, string Period)
    {
        DataContext Data = new DataContext();
        var Total = (from c in Data.Times
                     where c.EmployeeID == EmployeeID && c.Period == Period && c.PayCode == "211"
                     select c.Hours);

        return Total.Sum();
    }
</code>```

Is there any way to incorporate the Second Statement into the First? (Keeping in mind that I will have to incorporate not just one, but 5 Sum statements)

This one statement will then be used as an IQueryable DataSource for my RadGrid, called by DataField=" " of the RadGrid.

答:
Something like this:

```<code>public static IQueryable GetUnapprovedTimesheets(string period)
{
   DataContext data = new DataContext();

   var times = data
                   .Where(a => a.Period == period && a.Status == 1)
                   .OrderBy(a => a.Employee.LName)
                   .GroupBy(a => a.EmployeeID)
                   .Select(
                      a => new{
                               System_Time = a.FirstOrDefault(),
                               TotalReg = data.Times
                                           .Where(b => b.EmployeeID == a.Key
                                                    && b.Period == period
                                                    && b.PayCode == "211")
                                           .Sum(b => b.Hours)
                              }
                          );

   return times;
}
</code>```

Edit:
Sorry, I just noticed the GetTotalReg call uses a different entity. I'll modify my answer.

Update: TotalReg is now summed from data.Times

Body:
I'm looking to populate a Telerik RadGrid with an IQueryable DataSource but include 5 Total columns inside that Grid. I have built separate functions for the Totals when I create individual reports, but am having some trouble iterating them into my current LINQ statement for the Grid.

My current LINQ statement looks like this:

public static IQueryable GetUnapprovedTimesheets(string Period)
    {
        DataContext Data = new DataContext();

        var Times = (from c in Data.System_Times
                     where c.Period == Period && c.Status == 1
                     orderby c.Employee.LName
                     select c).GroupBy(s => s.EmployeeID).Select(x => x.FirstOrDefault());

        return Times;
    }

This statement grabs the Timesheets for the Period entered, and shows the records with a status of 1, these are then displayed grouped by EmployeeID. This statement pulls everything into the Grid properly but I would like to also add Totals for Regular, Overtime, Travel, and Sub.

The functions I have built separately for dynamic reporting look something like this:

public static decimal? GetTotalReg(int EmployeeID, string Period)
    {
        DataContext Data = new DataContext();
        var Total = (from c in Data.Times
                     where c.EmployeeID == EmployeeID && c.Period == Period && c.PayCode == "211"
                     select c.Hours);

        return Total.Sum();
    }

Is there any way to incorporate the Second Statement into the First? (Keeping in mind that I will have to incorporate not just one, but 5 Sum statements)

This one statement will then be used as an IQueryable DataSource for my RadGrid, called by DataField=" " of the RadGrid.

Body:
Something like this:

public static IQueryable GetUnapprovedTimesheets(string period)
{
   DataContext data = new DataContext();

   var times = data
                   .Where(a => a.Period == period && a.Status == 1)
                   .OrderBy(a => a.Employee.LName)
                   .GroupBy(a => a.EmployeeID)
                   .Select(
                      a => new{
                               System_Time = a.FirstOrDefault(),
                               TotalReg = data.Times
                                           .Where(b => b.EmployeeID == a.Key
                                                    && b.Period == period
                                                    && b.PayCode == "211")
                                           .Sum(b => b.Hours)
                              }
                          );

   return times;
}

Edit:
Sorry, I just noticed the GetTotalReg call uses a different entity. I'll modify my answer.

Update: TotalReg is now summed from data.Times


问:
Libreoffice Calc Finding MAX from a subset of results
I have a Libreoffice Calc workbook for tracking writing, with 3 sheets in it. 'Time Tracking', 'Time Summary' and 'Yearly Stats'. 'Time Tracking' is where user data is entered, 'Time Summary' is a pivot table for 'Time Tracking'; and 'Yearly Stats' shows long-term progress.

Time Summary (running off some test data) looks a bit like this:

```<code>       |Column A (Weeks)       | ... |Column M (Total Words)
-------+-----------------------+-----+----------------------
Row 7  |02/10/17 - 08/10/17    |     |3500
Row 8  |13/11/17 - 19/11/17    |     |2300
Row 9  |30/04/18 - 06/05/18    |     |1000
Row 10 |30/10/17 - 05/11/17    |     |700
</code>```

Yearly Stats looks like this:

```<code>       |A                   |B       |C
-------+--------------------+--------+----
Row 1  |                    |2017    |2018
Row 2  |Total Words         |6500    |1000
...
Row 7  |Max Words (Week)    |3500    |3500
</code>```

The formula for 'Yearly Stats'.B7:C7 is currently =MAX($'Time Summary'.$M$7:$M$10), but I need to modify it to filter by the year on the column heading.

https://ask.libreoffice.org/en/question/62260/minif-and-maxif-function-in-calc/ looked to be useful, but when I tried it, the MAX from the formula was returning the MAX of ROW - being 10 - rather than ROW returning the position of the MAX value - even though it seems to work in the example file from the link.

The example formula is:

```<code>=IFERROR(INDEX($Sheet1.$J$2:$J$13,MAX(ROW($Sheet1.$J$2:$J$13)*($Sheet1.$A$2:$A$13=A2))-1,1),NA())
</code>```

My formula uses RIGHT() to compare the last two characters of the column heading with the last two chars of the week in $'Time Summary':$A$7:$A$10 and is:

```<code>=IFERROR(INDEX($'Time Summary'.$M$7:$M$10,MAX(ROW('Time Summary'.$M$7:$M$10)*(RIGHT($'Time Summary'.$A7:$A$10,2)=RIGHT(B1,2)))-6,1),NA())
</code>```

I have, of course, remembered to press CTRL+SHIFT+ENTER as the instructions say, to get the array in the formula to work.

So that's the explanation of my problem. What is it that I'm getting wrong?

答:
Ok, this is a bit long-winded, but I've managed to solve the problem by using the following formula:

```<code>=IF(MAX(IF(RIGHT(INDIRECT(CONCATENATE("$'Time Summary'.$A7:$A$",COUNTIF($'Time Summary'.$A:$A,"<>''")+2)),2)=RIGHT(B1,2),INDIRECT(CONCATENATE("$'Time Summary'.$Q$",ROW(INDIRECT(CONCATENATE("$'Time Summary'.$Q7:$Q$",COUNTIF($'Time Summary'.$Q:$Q,"<>''")+5))))),0))>0,MAX(IF(RIGHT(INDIRECT(CONCATENATE("$'Time Summary'.$A$7:$A$",COUNTIF($'Time Summary'.$A:$A,"<>''")+2)),2)=RIGHT(B1,2),INDIRECT(CONCATENATE("'Time Summary'.$Q",ROW(INDIRECT(CONCATENATE("$'Time Summary'.$Q$7:$Q$",COUNTIF($'Time Summary'.$Q:$Q,"<>''")+5))))),0)),NA())
</code>```

It is wrapped in an IF that replaces any 0 result with '#NA' (just for neatness of output).
Also the right half of the ranges specified make use of a calculation to figure out where the bottom row is, leaving out the total, so that's another reason it's so huge.

Body:
I have a Libreoffice Calc workbook for tracking writing, with 3 sheets in it. 'Time Tracking', 'Time Summary' and 'Yearly Stats'. 'Time Tracking' is where user data is entered, 'Time Summary' is a pivot table for 'Time Tracking'; and 'Yearly Stats' shows long-term progress.

Time Summary (running off some test data) looks a bit like this:

       |Column A (Weeks)       | ... |Column M (Total Words)
-------+-----------------------+-----+----------------------
Row 7  |02/10/17 - 08/10/17    |     |3500
Row 8  |13/11/17 - 19/11/17    |     |2300
Row 9  |30/04/18 - 06/05/18    |     |1000
Row 10 |30/10/17 - 05/11/17    |     |700

Yearly Stats looks like this:

       |A                   |B       |C
-------+--------------------+--------+----
Row 1  |                    |2017    |2018
Row 2  |Total Words         |6500    |1000
...
Row 7  |Max Words (Week)    |3500    |3500

The formula for 'Yearly Stats'.B7:C7 is currently =MAX($'Time Summary'.$M$7:$M$10), but I need to modify it to filter by the year on the column heading.

https://ask.libreoffice.org/en/question/62260/minif-and-maxif-function-in-calc/ looked to be useful, but when I tried it, the MAX from the formula was returning the MAX of ROW - being 10 - rather than ROW returning the position of the MAX value - even though it seems to work in the example file from the link.

The example formula is:

=IFERROR(INDEX($Sheet1.$J$2:$J$13,MAX(ROW($Sheet1.$J$2:$J$13)*($Sheet1.$A$2:$A$13=A2))-1,1),NA())

My formula uses RIGHT() to compare the last two characters of the column heading with the last two chars of the week in $'Time Summary':$A$7:$A$10 and is:

=IFERROR(INDEX($'Time Summary'.$M$7:$M$10,MAX(ROW('Time Summary'.$M$7:$M$10)*(RIGHT($'Time Summary'.$A7:$A$10,2)=RIGHT(B1,2)))-6,1),NA())

I have, of course, remembered to press CTRL+SHIFT+ENTER as the instructions say, to get the array in the formula to work.

So that's the explanation of my problem. What is it that I'm getting wrong?

Body:
Ok, this is a bit long-winded, but I've managed to solve the problem by using the following formula:

=IF(MAX(IF(RIGHT(INDIRECT(CONCATENATE("$'Time Summary'.$A7:$A$",COUNTIF($'Time Summary'.$A:$A,"<>''")+2)),2)=RIGHT(B1,2),INDIRECT(CONCATENATE("$'Time Summary'.$Q$",ROW(INDIRECT(CONCATENATE("$'Time Summary'.$Q7:$Q$",COUNTIF($'Time Summary'.$Q:$Q,"<>''")+5))))),0))>0,MAX(IF(RIGHT(INDIRECT(CONCATENATE("$'Time Summary'.$A$7:$A$",COUNTIF($'Time Summary'.$A:$A,"<>''")+2)),2)=RIGHT(B1,2),INDIRECT(CONCATENATE("'Time Summary'.$Q",ROW(INDIRECT(CONCATENATE("$'Time Summary'.$Q$7:$Q$",COUNTIF($'Time Summary'.$Q:$Q,"<>''")+5))))),0)),NA())

It is wrapped in an IF that replaces any 0 result with '#NA' (just for neatness of output).
Also the right half of the ranges specified make use of a calculation to figure out where the bottom row is, leaving out the total, so that's another reason it's so huge.


问:
Get all EoL Windows Computer in AD With Powershell
I have to create a script to get all EoL Windows computers in our AD.

This is my Code right now:

```<code>$getad = Get-ADComputer -Filter {
OperatingSystem -like "Windows 10*"
-or
OperatingSystem -like "*Windows Vista*"
-or
OperatingSystem -like "*Windows XP*"
-or
OperatingSystem -like "*95*"
-or
OperatingSystem -like "*94*"
-or
OperatingSystem -like "*Windows 8*"
-or
OperatingSystem -like "*Windows 8.1*"
-or
OperatingSystem -like "*2000 Professional*"
-or
OperatingSystem -like "*2000 Server*"
-or
OperatingSystem -like "*2003*"
-or
OperatingSystem -like "*Windows NT*"
-or
OperatingSystem -like "*Windows 7*"
-and
#Windows8
OperatingSystemVersion -notlike "*6.3.9600*"
-and
#Windows7 SP1
OperatingSystemVersion -notlike "*6.1.7601*"
-and
#Windows10
OperatingSystemVersion -notlike "*16299*"
-and
#Windows10
OperatingSystemVersion -notlike "*14393*"
-and
#Windows10
OperatingSystemVersion -notlike "*15063*"
} -Properties ('Name', 'operatingsystem', 'DistinguishedName',
'description', 'lastlogondate', 'OperatingsystemVersion')
$selectobj = $getad | Select-Object Name, Operatingsystem,
DistinguishedName, Description, Lastlogondate, OperatingSystemVersion
$selectobj
</code>```

The problem: The part with -notlike is not applied. I get computers with the versions I do not want to see.

I need all EoL Computers in one variable so i can work with them.

答:
The problem is one of logic with your combination of or and and, but don't use -like and -notlike they don't work the way you think. Use the regular expression switches -imatch and -inotmatch like this:

```<code>OperatingSystem -imatch "Windows 10|Windows Vista|Windows XP|95|94|Windows 8|2000|2003|Windows NT|Windows 7"
-and OperatingSystemVersion -inotmatch "6.3.9600|6.1.7601|16299|14393"
</code>```

Body:
I have to create a script to get all EoL Windows computers in our AD.

This is my Code right now:

$getad = Get-ADComputer -Filter {
OperatingSystem -like "Windows 10*"
-or
OperatingSystem -like "*Windows Vista*"
-or
OperatingSystem -like "*Windows XP*"
-or
OperatingSystem -like "*95*"
-or
OperatingSystem -like "*94*"
-or
OperatingSystem -like "*Windows 8*"
-or
OperatingSystem -like "*Windows 8.1*"
-or
OperatingSystem -like "*2000 Professional*"
-or
OperatingSystem -like "*2000 Server*"
-or
OperatingSystem -like "*2003*"
-or
OperatingSystem -like "*Windows NT*"
-or
OperatingSystem -like "*Windows 7*"
-and
#Windows8
OperatingSystemVersion -notlike "*6.3.9600*"
-and
#Windows7 SP1
OperatingSystemVersion -notlike "*6.1.7601*"
-and
#Windows10
OperatingSystemVersion -notlike "*16299*"
-and
#Windows10
OperatingSystemVersion -notlike "*14393*"
-and
#Windows10
OperatingSystemVersion -notlike "*15063*"
} -Properties ('Name', 'operatingsystem', 'DistinguishedName',
'description', 'lastlogondate', 'OperatingsystemVersion')
$selectobj = $getad | Select-Object Name, Operatingsystem,
DistinguishedName, Description, Lastlogondate, OperatingSystemVersion
$selectobj

The problem: The part with -notlike is not applied. I get computers with the versions I do not want to see.

I need all EoL Computers in one variable so i can work with them.

Body:
The problem is one of logic with your combination of or and and, but don't use -like and -notlike they don't work the way you think. Use the regular expression switches -imatch and -inotmatch like this:

OperatingSystem -imatch "Windows 10|Windows Vista|Windows XP|95|94|Windows 8|2000|2003|Windows NT|Windows 7"
-and OperatingSystemVersion -inotmatch "6.3.9600|6.1.7601|16299|14393"


问:
Task and Parallel.Invoke in a library, is it a bad idea to use it?
I have read that to do a fake async method in this way it is a bad idea:

```<code>public int myMethodSyn()
{
    //sync operations

    return result;
}

public async int myMethodAsync()
{
    return await Task.Run(myMethodSync);
}
</code>```

One of the reasons that I have read it is because for example, ASP can have scalability problems with this kind of libraries because tasks use the thread pool and ASP need the thread pool to attend each call. So the library can consume all the threads of the thread pool al block ASP. SO it is better allow to the client decides how to use the thread pool.

If am not wrong, Parallel.Invoke use the thread pool too to run methods in parallel, so I guess that if I use a method in my library that uses parallel.Invoke, or parallel.Foreach or any of this ways to run code in parallel, I would have the same problem. Is it true?

My idea is to run two mthods in parallel because they are indepent and I could get a better performance if I run them in parallel. So I would have somthing like that:

```<code>public int myMainMethodSync()
{
    int result01 = myMethod01Sync();
    int result02 = myMethod02Sync();
    return result01 + result02;
}

private void myMethod01Sync()
{
}

private void myMethod02Sync()
{
}

public int myMainMethodAsync()
{
    Task myTsk01 = Task.Run(myMethod01Sync);
    Task myTsk02 = Task.Run(myMethod02Sync);
    Task.WhenAll(myTsk01, myTsk02);

    return myTsk01.Result + myTsk02.Result;
}

public int Task myMainMethodParallel()
{
    int result01;
    int result02;
    Parallel.Invoke(() => result01 = myMethod01Sync(),
                    () => result02 = myMethod02Sync());

    return result01 + result02;
}
</code>```

The idea is it to have a sync method that run the two methods in sync. So the client who use the library knows that the method will not use thread pool.

Later I have two options to run the methods at the same time, with tasks or with parallel.Invoke.

In the case of the tasks, I am using a fake async methods because I am wraping the sync method inside a task, that use two threads from the threadpool. If I am not wrong, this is not recommended.

The other option it is to use Parallel.Invoke, that uses threads from thread pool too, so I guess it has the same problem that with tasks, so I guess that it is not recommended too.

In my case I would prefer to use task, because I can decide with a condition when to run the method02Sync for example, according to some condiciotion, so I could save the cost to assign a thread to run the second method if I know that it is not needed in some cases. I guess in parallel.Invoke this is not possible.

However, I think that in this case, how I implement a sync method too, I let the client to choose the method that it considerates better in its case, so really it is a bad option to use tasks in the async method?

If both solutions are bad, tasks and Parallel.Invloke, then it is not recommended to run parallel code in libraries and only use it in the top level, in the UI or client of the library? Because I guess that in this case the use of parallel is very restrictive, because in the top level, in the UI, it is not possible to use parallel if it decides it is possible because tell to library use threads or not, because it wouldn't have parallel methods.

In sumary, is my solution, expose sync and async methods a bad idea? is it bad idea to use task or parallel code in the libraries? If one of them it is better option, which one?

Thanks.

答:
is my solution, expose sync and async methods a bad idea?

Let me reformulate the question to make it more general:

Is it a good idea to expose two versions of a method with different performance characteristics?

I think that most of the time, it is a bad idea. The API of your library should be clear, you should not make the users of your library constantly keep choosing between the two options. I think it's your responsibility as a library author to make the decision, even if it's going to be the wrong one for some of your users.

If the differences between the two options are dramatic, you could consider some approach that lets your users to choose between them. But I think having two separate methods is the wrong choice, something like an optional parameter would be a better approach, because it means there is a clear default.

The one exception I can think of is if the signatures of the two methods are different, like with truly async methods. But I don't think that applies to your use of Tasks to parallelize CPU-bound methods.

Is it bad idea to use task or parallel code in the libraries?

I think you should use them cautiously. You are right that your users might not be happy if your library uses more resources (here, threads) to make itself faster. On the other hand, most methods of parallelizing code are smart enough that if the amount of available thread pool threads is limited, they will still work fine. So, if you measured that the speedup gained by parallelizing your code is significant, I think it's okay to do it.

If one of them it is better option, which one?

I think this is more a matter of which one you prefer as a matter of code style. The performance characteristics of Parallel.Invoke() with two actions and synchronously waiting for two Tasks should be comparable.

Though keep in mind that your call to Task.WhenAll doesn't really do anything, since WhenAll returns a Task that completes when all its component Tasks complete. You could instead use Task.WaitAll, but I'm not sure what would be the point, since you're already implicitly waiting for both Tasks by acessing their Results.

Body:
I have read that to do a fake async method in this way it is a bad idea:

public int myMethodSyn()
{
    //sync operations

    return result;
}

public async int myMethodAsync()
{
    return await Task.Run(myMethodSync);
}

One of the reasons that I have read it is because for example, ASP can have scalability problems with this kind of libraries because tasks use the thread pool and ASP need the thread pool to attend each call. So the library can consume all the threads of the thread pool al block ASP. SO it is better allow to the client decides how to use the thread pool.

If am not wrong, Parallel.Invoke use the thread pool too to run methods in parallel, so I guess that if I use a method in my library that uses parallel.Invoke, or parallel.Foreach or any of this ways to run code in parallel, I would have the same problem. Is it true?

My idea is to run two mthods in parallel because they are indepent and I could get a better performance if I run them in parallel. So I would have somthing like that:

public int myMainMethodSync()
{
    int result01 = myMethod01Sync();
    int result02 = myMethod02Sync();
    return result01 + result02;
}

private void myMethod01Sync()
{
}

private void myMethod02Sync()
{
}

public int myMainMethodAsync()
{
    Task myTsk01 = Task.Run(myMethod01Sync);
    Task myTsk02 = Task.Run(myMethod02Sync);
    Task.WhenAll(myTsk01, myTsk02);

    return myTsk01.Result + myTsk02.Result;
}

public int Task myMainMethodParallel()
{
    int result01;
    int result02;
    Parallel.Invoke(() => result01 = myMethod01Sync(),
                    () => result02 = myMethod02Sync());

    return result01 + result02;
}

The idea is it to have a sync method that run the two methods in sync. So the client who use the library knows that the method will not use thread pool.

Later I have two options to run the methods at the same time, with tasks or with parallel.Invoke.

In the case of the tasks, I am using a fake async methods because I am wraping the sync method inside a task, that use two threads from the threadpool. If I am not wrong, this is not recommended.

The other option it is to use Parallel.Invoke, that uses threads from thread pool too, so I guess it has the same problem that with tasks, so I guess that it is not recommended too.

In my case I would prefer to use task, because I can decide with a condition when to run the method02Sync for example, according to some condiciotion, so I could save the cost to assign a thread to run the second method if I know that it is not needed in some cases. I guess in parallel.Invoke this is not possible.

However, I think that in this case, how I implement a sync method too, I let the client to choose the method that it considerates better in its case, so really it is a bad option to use tasks in the async method?

If both solutions are bad, tasks and Parallel.Invloke, then it is not recommended to run parallel code in libraries and only use it in the top level, in the UI or client of the library? Because I guess that in this case the use of parallel is very restrictive, because in the top level, in the UI, it is not possible to use parallel if it decides it is possible because tell to library use threads or not, because it wouldn't have parallel methods.

In sumary, is my solution, expose sync and async methods a bad idea? is it bad idea to use task or parallel code in the libraries? If one of them it is better option, which one?

Thanks.


问:
How to store user defined data structures?
I'm building a mobile application that records information about items and then outputs an automatically generated report.

Each Item may be of various types, each type requires different information to be recorded. The user needs to be able to specify what is to be stored for each type.

Is there a "best" way to store this type of information in a relational database?

My current plan is to have a Type table that maps Types to Attributes that need to be recorded for that Type. Does this sound sensible? I imagine that it may get messy when I come to produce reports from this data.

I guess I need a way of generalising the information that needs to be recorded?

I think I just need some pointers in the right direction.

Thanks!

答:
Only a suggestion, might not be an answer... use JSON and go for no-sql database. Today it is more convenient to operate and play around with data in not strictly relational database format.

That way you can define a model(s), or create you own data structure as mentioned and store it easily as a collection of documents of that model. Also no-sql allows structure changes without obligating you to define entire "column" for all "rows" present there ;)

Check this out about MongoDB and NoSQL explanation.

This is also a beatiful post that i love about data modeling in
NoSQL.


问:
Link to form with Button selected as primary
I am trying to link to a page on a different site that contains three buttons in a form. When I link to the page xyz.com/form , by default the 'Highlighted' button is checked since it contains the btn-primary class. How can I create a link from my site linking to xyz.com/form with the btn-primary class selected for 'Link One' or 'Link Two' rather than 'Highlighted'?</p>

```<code><form>
<div class="col-xs-12">
<a class="btn btn-block btn-default btn-primary">Highlighted</a>
<a class="btn btn-block btn-default">Link One</a>
<a class="btn btn-block btn-default">Link Two</a>
</div>
</form>
</code>```

答:
You can't.

It isn't possible to make arbitrary changes to the HTML of an arbitrary site through the URL.

(If it was, you could watch as I linked to your bank's online banking service with a link that changed their login form to point to my own, malicious, site).

You would have to make the changes on the site hosting the HTML you want to change.

Ideally, you would create different pages representing each version of the page. You could do this dynamically using server-side code which (for instance) paid attention to the query string.

You could also use JavaScript (in the page) to examine the URL and modify the DOM based on it.

Body:
I am trying to link to a page on a different site that contains three buttons in a form. When I link to the page xyz.com/form , by default the 'Highlighted' button is checked since it contains the btn-primary class. How can I create a link from my site linking to xyz.com/form with the btn-primary class selected for 'Link One' or 'Link Two' rather than 'Highlighted'?

<form>

Highlighted
Link One
Link Two

</form>


答:
Your status is not visible in the second then. You can just get the two properties in the single then.

json() returns a new Promise to you, so you need to create your object inside the then of the result of that function. If you return a Promise from a function, it will be fulfilled and will return the result of the fulfillment - in our case the object.

fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(r =>  r.json().then(data => ({status: r.status, body: data})))
.then(obj => console.log(obj));```

Title: fetch response.json() and response.status


问:
Using Spring Batch to parse date from file into LocalDateTime
I'm trying to read a CSV file with dates with Spring Batch, but I am having trouble parsing a date into a LocalDateTime Object:

Field error in object 'target' on field 'date': rejected value [2017-07-20 04:15:25.0]; codes [typeMismatch.target.date,typeMismatch.date,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'date': no matching editors or conversion strategy found]

Main.java:

```<code>public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringBatchDateParseConfig.class);

        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        Job job = context.getBean("job", Job.class);

        JobParameters jobParameters = new JobParametersBuilder().toJobParameters();

        try {
            JobExecution jobExecution = jobLauncher.run(job, jobParameters);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }
}
</code>```

SpringBatchDateParseConfig.java:

```<code>@Configuration
@EnableBatchProcessing
public class SpringBatchDateParseConfig {
    @Inject
    private JobBuilderFactory jobBuilderFactory;

    @Inject
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                                 .<TestClass, TestClass>chunk(2)
                                 .reader(testClassItemReader())
                                 .writer(testClassItemWriter())
                                 .build();
    }

    @Bean
    public Job job(Step step1) {
        return jobBuilderFactory.get("job")
                .start(step1)
                .build();
    }

    @Bean
    FlatFileItemReader<TestClass> testClassItemReader() {
        FlatFileItemReader<TestClass> flatFileItemReader = new FlatFileItemReader<>();
        flatFileItemReader.setResource(new ClassPathResource("test.csv"));
        flatFileItemReader.setLinesToSkip(1);
        DefaultLineMapper defaultLineMapper = new DefaultLineMapper();
        DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer();
        delimitedLineTokenizer.setNames(new String[]{"foo", "bar", "date"});

        BeanWrapperFieldSetMapper<TestClass> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
        fieldSetMapper.setTargetType(TestClass.class);

        defaultLineMapper.setLineTokenizer(delimitedLineTokenizer);
        defaultLineMapper.setFieldSetMapper(fieldSetMapper);
        flatFileItemReader.setLineMapper(defaultLineMapper);

        return flatFileItemReader;

    }

    @Bean
    ItemWriter<TestClass> testClassItemWriter() {
        return new ItemWriter<TestClass>() {
            @Override
            public void write(List<? extends TestClass> items) throws Exception {
                for (TestClass TestClass : items) {
                    System.out.println(TestClass.toString());
                }
            }
        };
    }
}
</code>```

TestClass.java:

```<code>public class TestClass {

    private String foo;
    private String bar;
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME, pattern = "yyyy-MM-dd H:m:s.S")
    private LocalDateTime date;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

    public LocalDateTime getDate() {
        return date;
    }

    public void setDate(LocalDateTime date) {
        this.date = date;
    }
}
</code>```

test.csv:

```<code>foo,bar,date
asdf,fdsa,2017-07-20 04:15:25.0
qwerty,ytrewq,2017-07-20 04:15:25.0
</code>```

Am I missing something?

答:
You can override method initBinder of BeanWrapperFieldSetMapper<T>:

```<code>public class BeanWrapperFieldSetMapperCustom<T> extends BeanWrapperFieldSetMapper<T> {

    @Override
    protected void initBinder(DataBinder binder) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StringUtils.isNotEmpty(text)) {
                    setValue(LocalDate.parse(text, formatter));
                } else {
                    setValue(null);
                }
            }

            @Override
            public String getAsText() throws IllegalArgumentException {
                Object date = getValue();
                if (date != null) {
                    return formatter.format((LocalDate) date);
                } else {
                    return "";
                }
            }
        });
    }
}
</code>```

Body:
I'm trying to read a CSV file with dates with Spring Batch, but I am having trouble parsing a date into a LocalDateTime Object:

Field error in object 'target' on field 'date': rejected value [2017-07-20 04:15:25.0]; codes [typeMismatch.target.date,typeMismatch.date,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'date': no matching editors or conversion strategy found]

Main.java:

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringBatchDateParseConfig.class);

        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        Job job = context.getBean("job", Job.class);

        JobParameters jobParameters = new JobParametersBuilder().toJobParameters();

        try {
            JobExecution jobExecution = jobLauncher.run(job, jobParameters);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }
}

SpringBatchDateParseConfig.java:

@Configuration
@EnableBatchProcessing
public class SpringBatchDateParseConfig {
    @Inject
    private JobBuilderFactory jobBuilderFactory;

    @Inject
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                                 .<TestClass, TestClass>chunk(2)
                                 .reader(testClassItemReader())
                                 .writer(testClassItemWriter())
                                 .build();
    }

    @Bean
    public Job job(Step step1) {
        return jobBuilderFactory.get("job")
                .start(step1)
                .build();
    }

    @Bean
    FlatFileItemReader<TestClass> testClassItemReader() {
        FlatFileItemReader<TestClass> flatFileItemReader = new FlatFileItemReader<>();
        flatFileItemReader.setResource(new ClassPathResource("test.csv"));
        flatFileItemReader.setLinesToSkip(1);
        DefaultLineMapper defaultLineMapper = new DefaultLineMapper();
        DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer();
        delimitedLineTokenizer.setNames(new String[]{"foo", "bar", "date"});

        BeanWrapperFieldSetMapper<TestClass> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
        fieldSetMapper.setTargetType(TestClass.class);

        defaultLineMapper.setLineTokenizer(delimitedLineTokenizer);
        defaultLineMapper.setFieldSetMapper(fieldSetMapper);
        flatFileItemReader.setLineMapper(defaultLineMapper);

        return flatFileItemReader;

    }

    @Bean
    ItemWriter<TestClass> testClassItemWriter() {
        return new ItemWriter<TestClass>() {
            @Override
            public void write(List<? extends TestClass> items) throws Exception {
                for (TestClass TestClass : items) {
                    System.out.println(TestClass.toString());
                }
            }
        };
    }
}

TestClass.java:

public class TestClass {

    private String foo;
    private String bar;
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME, pattern = "yyyy-MM-dd H:m:s.S")
    private LocalDateTime date;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

    public LocalDateTime getDate() {
        return date;
    }

    public void setDate(LocalDateTime date) {
        this.date = date;
    }
}

test.csv:

foo,bar,date
asdf,fdsa,2017-07-20 04:15:25.0
qwerty,ytrewq,2017-07-20 04:15:25.0

Am I missing something?

Body:
You can override method initBinder of BeanWrapperFieldSetMapper<T>:

public class BeanWrapperFieldSetMapperCustom<T> extends BeanWrapperFieldSetMapper<T> {

    @Override
    protected void initBinder(DataBinder binder) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StringUtils.isNotEmpty(text)) {
                    setValue(LocalDate.parse(text, formatter));
                } else {
                    setValue(null);
                }
            }

            @Override
            public String getAsText() throws IllegalArgumentException {
                Object date = getValue();
                if (date != null) {
                    return formatter.format((LocalDate) date);
                } else {
                    return "";
                }
            }
        });
    }
}

ContentLicense: CC BY-SA 4.0


问:
Why does my merge function output an array that is not ordered?
I built a simple function that, given two arrays aa[5] = {5, 4, 9, -1, 3} and bb[2] = {16, -11}, orders them in a third array cc[7].

```<code>#include<stdio.h>
void merge(int *, int *, int *, int, int);

int main(){
    int aa[5] = {5, 4, 9, -1, 3};
    int bb[2] = {16, -11};
    int cc[7];

    merge(aa, bb, cc, 5, 2);

    return 0;
}

void merge(int *aa, int *bb, int *cc, int m, int n){

    int i = 0, j = 0, k = 0;

    while(i < m && j < n){
        if(aa[i] < bb[j])
            cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
        else
            cc[k++] = bb[j++];
    }

    while(i < m)              /*Transfer the remaining part of longest array*/
        cc[k++] = aa[i++];

    while(j < n)
        cc[k++] = bb[j++];
}
</code>```

The cc array is correctly filled, but the values are not ordered. Instead of the expected cc = {-11, -1, 3, 4, 5, 9, 16} it returns cc = {5, 4, 9, -1, 3, 16, 11}.
Like the assignments cc[k++] = aa[i++] and cc[k++] = bb[j++] do not work, somehow, or the logical test if aa[i] < bb[j] goes ignored.

I hypothesized operators priority problems, hence I tested with two different standard, with no differences:

```<code>gcc main.c -o main.x -Wall
gcc main.c -o main.x -Wall -std=c89
</code>```

I checked the code many times, unable to find any relevant error. Any suggestion at this point would be appreciated.

答:
If your program works fine, you can sort in O(N) by comparison. As it is not possible and mentioned in comments by @Karzes, your program works fine just for the sorted sub arrays. Hence, if you want to implement merge function for the merge sort, you should try your program for these two inputs:

```<code>int aa[5] = {-1, 3, 4, 5, 9};
int bb[2] = {-11, 16};
</code>```

Body:
I built a simple function that, given two arrays aa[5] = {5, 4, 9, -1, 3} and bb[2] = {16, -11}, orders them in a third array cc[7].

#include<stdio.h>
void merge(int *, int *, int *, int, int);

int main(){
    int aa[5] = {5, 4, 9, -1, 3};
    int bb[2] = {16, -11};
    int cc[7];

    merge(aa, bb, cc, 5, 2);

    return 0;
}

void merge(int *aa, int *bb, int *cc, int m, int n){

    int i = 0, j = 0, k = 0;

    while(i < m && j < n){
        if(aa[i] < bb[j])
            cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
        else
            cc[k++] = bb[j++];
    }

    while(i < m)              /*Transfer the remaining part of longest array*/
        cc[k++] = aa[i++];

    while(j < n)
        cc[k++] = bb[j++];
}

The cc array is correctly filled, but the values are not ordered. Instead of the expected cc = {-11, -1, 3, 4, 5, 9, 16} it returns cc = {5, 4, 9, -1, 3, 16, 11}.
Like the assignments cc[k++] = aa[i++] and cc[k++] = bb[j++] do not work, somehow, or the logical test if aa[i] < bb[j] goes ignored.

I hypothesized operators priority problems, hence I tested with two different standard, with no differences:

gcc main.c -o main.x -Wall
gcc main.c -o main.x -Wall -std=c89

I checked the code many times, unable to find any relevant error. Any suggestion at this point would be appreciated.

Body:
If your program works fine, you can sort in O(N) by comparison. As it is not possible and mentioned in comments by @Karzes, your program works fine just for the sorted sub arrays. Hence, if you want to implement merge function for the merge sort, you should try your program for these two inputs:

int aa[5] = {-1, 3, 4, 5, 9};
int bb[2] = {-11, 16};


问:
Collecting data for two columns
I am trying to use data from ‘NCR’ on two columns in my CSV. However it overrides each other and only presented the data in the column called ‘YesterdayTime’.

Is there a way to use the data from ‘NCR’ in both columns called ’ExTime’ and ‘YesterdayTime’?

My Code

```<code>from datetime import datetime
from elasticsearch import Elasticsearch
import csv

es = Elasticsearch(["9200"])

res = es.search(index="search", body=
                {
                    "_source": ["VT","NCR","N","DT","RD"],
                    "query": {

                        "bool": {
                            "must": [{"range": {"VT": {
                                            "gte": "now/d",
                                            "lte": "now+1d/d"}}},

                                {"wildcard": {"user": "mike*"}},
                                {"wildcard": {"user": "jane*"}},
                                {"wildcard": {"user": "kate*"}},
                                {"wildcard": {"user": "dave*"}},
                                {"wildcard": {"user": "rich*"}}

]}}},size=10)

csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv'

header_names = { 'VT': 'Date',  'NCR': 'ExTime', 'NCR': 'YesterdayTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'}

with open(csv_file, 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore')
    w.writerow(header_names,)
    for doc in res['hits']['hits']:
        my_dict = doc['_source']

             w.writerow(my_dict)
</code>```

Output - EX time is being replaced with YesterdayTime.

```<code>DATE         YesterdayTime      Name   Party   Period

20170512    12/05/2017 15:39    1001    0        0

20170512    12/05/2017 15:39    1001    0        0

20170908    08/09/2017 02:42    1001    0        0

20170908    08/09/2017 06:30    1001    0        0
</code>```

The correct Output that i want:

```<code>DATE       YesterdayTime     YesterdayTime       Name   Party   Period

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170908  08/09/2017 02:42   08/09/2017 02:42    1001     0        0

20170908  08/09/2017 06:30   08/09/2017 06:30    1001     0        0
</code>```

答:
You could assign fieldnames with a list containing duplicates.

```<code>with open('test.csv', 'w') as f:
    csv_file = csv.DictWriter(f, fieldnames=['foo', 'bar', 'bar', 'bar'])
    csv_file.writeheader()
    csv_file.writerow({'foo':1, 'bar':2})
</code>```

test.csv contains:

```<code>foo,bar,bar,bar
1,2,2,2
</code>```

However that does not fix the problem if you want different header names...

Title: Collecting data for two columns

Body:
I am trying to use data from ‘NCR’ on two columns in my CSV. However it overrides each other and only presented the data in the column called ‘YesterdayTime’.

Is there a way to use the data from ‘NCR’ in both columns called ’ExTime’ and ‘YesterdayTime’?

My Code

from datetime import datetime
from elasticsearch import Elasticsearch
import csv

es = Elasticsearch(["9200"])

res = es.search(index="search", body=
                {
                    "_source": ["VT","NCR","N","DT","RD"],
                    "query": {

                        "bool": {
                            "must": [{"range": {"VT": {
                                            "gte": "now/d",
                                            "lte": "now+1d/d"}}},

                                {"wildcard": {"user": "mike*"}},
                                {"wildcard": {"user": "jane*"}},
                                {"wildcard": {"user": "kate*"}},
                                {"wildcard": {"user": "dave*"}},
                                {"wildcard": {"user": "rich*"}}

]}}},size=10)

csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv'

header_names = { 'VT': 'Date',  'NCR': 'ExTime', 'NCR': 'YesterdayTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'}

with open(csv_file, 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore')
    w.writerow(header_names,)
    for doc in res['hits']['hits']:
        my_dict = doc['_source']

             w.writerow(my_dict)

Output - EX time is being replaced with YesterdayTime.

DATE         YesterdayTime      Name   Party   Period

20170512    12/05/2017 15:39    1001    0        0

20170512    12/05/2017 15:39    1001    0        0

20170908    08/09/2017 02:42    1001    0        0

20170908    08/09/2017 06:30    1001    0        0

The correct Output that i want:

DATE       YesterdayTime     YesterdayTime       Name   Party   Period

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170908  08/09/2017 02:42   08/09/2017 02:42    1001     0        0

20170908  08/09/2017 06:30   08/09/2017 06:30    1001     0        0

Body:
You could assign fieldnames with a list containing duplicates.

with open('test.csv', 'w') as f:
    csv_file = csv.DictWriter(f, fieldnames=['foo', 'bar', 'bar', 'bar'])
    csv_file.writeheader()
    csv_file.writerow({'foo':1, 'bar':2})

test.csv contains:

foo,bar,bar,bar
1,2,2,2

However that does not fix the problem if you want different header names...


问:
Connect to RavenDB using nodejs
I am using node to connect to RavenDB
https://www.npmjs.com/package/ravendb

but when try to create a connection, at this step
https://i.stack.imgur.com/fcFZ9.png

I dont know what to put in database url and default database name
and I put

database url=localhost:5000

default database name=test (my db name is test)

and the console show this error Failed to load http://localhost:5000/topology?name=test
how can I create this connection.

EDIT
I config the program

this is my file app.js

const DocumentStore = require('ravendb').default;
const store = DocumentStore.create('localhost:5000', 'test');
store.initialize();
const session = store.openSession();

when I run this file with node, it show the error: (but it will compile fine if I delete the line
const session = store.openSession(); so I think the problem is somewhere around the session.

Error log:

"C:\Program Files\JetBrains\WebStorm 2017.2\bin\runnerw.exe" D:\nodejs\node.exe D:\nodeProject\demoraven\app.js
Unhandled rejection ee: Node localhost:5000 is down
    at d.finally.catch.e (D:\nodeProject\demoraven\node_modules\ravendb\lib\ravendb-node.js:2:52762)
    at tryCatcher (D:\nodeProject\demoraven\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:689:18)
    at Async._drainQueue (D:\nodeProject\demoraven\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (D:\nodeProject\demoraven\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (D:\nodeProject\demoraven\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)

答:
I dont know what to put in database url and default database name and
  I put

Database URL is the HTTP address where you're running a Raven Server. You can download Raven and run it locally. Or if you're just testing, you can connect to the playground server located at http://4.live-test.ravendb.net

For DefaultDatabase, that's the database you want to connect to. If you already have created a database, use that name. Otherwise, put in any name, and it will be created for you.

So, to sum up, your code should look like this:

```<code>const dbUrl = "http://4.live-test.ravendb.net"; // Alternately, if you're running Raven Server locally, use http://localhost:8080
const store = DocumentStore.create(dbUrl, "MyTestingDatabase");
store.initialize();
</code>```

Title: Connect to RavenDB using nodejs

Body:
I dont know what to put in database url and default database name and
  I put

Database URL is the HTTP address where you're running a Raven Server. You can download Raven and run it locally. Or if you're just testing, you can connect to the playground server located at http://4.live-test.ravendb.net

For DefaultDatabase, that's the database you want to connect to. If you already have created a database, use that name. Otherwise, put in any name, and it will be created for you.

So, to sum up, your code should look like this:

const dbUrl = "http://4.live-test.ravendb.net"; // Alternately, if you're running Raven Server locally, use http://localhost:8080
const store = DocumentStore.create(dbUrl, "MyTestingDatabase");
store.initialize();


问:
How to ensure fluency in a frequently refreshed TableView?
there has a tableView Who refreshed every 0.5 seconds;

i uesd tableView reloadData or reloadSections: withRowAnimation:

Both of them cause FPS decrease

what can i do for it?

the tableView has new data every 0.5 seconds

and need display new data immediately

code:

```<code>- (void)registerTableViewCells {
    [self.tableView registerClass:[UITableViewCell1 class] forCellReuseIdentifier: UITableViewCell1Identifier];
    [self.tableView registerClass:[UITableViewCell2 class] forCellReuseIdentifier: UITableViewCell2Identifier];
    [self.tableView registerClass:[UITableViewCell3 class] forCellReuseIdentifier: UITableViewCell3Identifier];
}

- (void)makeUpDisplaySource {
    NSMutableArray *arrM = [NSMutableArray array];
    [arrM addObject:@[UITableViewCell1Identifier, @(60), @(1)]];
    [arrM addObject:@[UITableViewCell2Identifier, @(55), @(10)]];
    [arrM addObject:@[UITableViewCell3Identifier, @(30), @(10+_fortySeat*30)]];
    // _fortySeat is  boolValue
    self.displaySource = arrM;
}
</code>```

tableView delegate

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *dataArr = self.displaySource[indexPath.section];
    NSString *identifier = dataArr[0];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([NSStringFromClass(cell.class) isEqualToString:@"UITableViewCell1"]) {
        UITableViewCell1 *newcell = (UITableViewCell1 *)cell;
        [newcell  updatCellUI];
    }
    else if ([NSStringFromClass(cell.class) isEqualToString:@"UITableViewCell2"]) {
        UITableViewCell2 *newcell = (UITableViewCell2 *)cell;
        [newcell updatCellUIBuy: model1 sell: model2];
    }
    else if ([NSStringFromClass(cell.class) isEqualToString:@"UITableViewCell3"]){
        cell.backgroundColor = GL_CELL_BACKGROUD_COLOR;
        [cell addSubview:self.someView];// someView is a lazy property
    }
}
</code>```

答:
If you are not using reusable cells, of course, reload the data every 0.5 seconds may cause FPS problems beacause you'll reload the data of all the cells present in your TableView.

Also even if you are reloading data with reloadSections:, you'll have problems if you are reloading all the modified cells. Even those who are not visible. -- And this may cause problems.

In that case I suggest you to :

Use : [self.tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:@"CellID"];

This will register your tableView under a xib file and the cells under an ID.

In cellForRowAtIndexPath: load your cell using this ID :
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];

Using reusable cells you will increase the speed of loading your TableView and it may help you while refreshing it.

If you are already using reusable cells I suggest you to let people know it in your question.
Even if your are using reusable cells you could simply decrease a bit the interval time between 2 reloads if you still have problems with FPS.

I might not have completly understood your question and I might be wrong on certains points. Of course do not hesitate to let me know/edit my answer, I will apreciate it.

Body:
there has a tableView Who refreshed every 0.5 seconds;

i uesd tableView reloadData or reloadSections: withRowAnimation:

Both of them cause FPS decrease

what can i do for it?

the tableView has new data every 0.5 seconds

and need display new data immediately

code:

- (void)registerTableViewCells {
    [self.tableView registerClass:[UITableViewCell1 class] forCellReuseIdentifier: UITableViewCell1Identifier];
    [self.tableView registerClass:[UITableViewCell2 class] forCellReuseIdentifier: UITableViewCell2Identifier];
    [self.tableView registerClass:[UITableViewCell3 class] forCellReuseIdentifier: UITableViewCell3Identifier];
}

- (void)makeUpDisplaySource {
    NSMutableArray *arrM = [NSMutableArray array];
    [arrM addObject:@[UITableViewCell1Identifier, @(60), @(1)]];
    [arrM addObject:@[UITableViewCell2Identifier, @(55), @(10)]];
    [arrM addObject:@[UITableViewCell3Identifier, @(30), @(10+_fortySeat*30)]];
    // _fortySeat is  boolValue
    self.displaySource = arrM;
}

tableView delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *dataArr = self.displaySource[indexPath.section];
    NSString *identifier = dataArr[0];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([NSStringFromClass(cell.class) isEqualToString:@"UITableViewCell1"]) {
        UITableViewCell1 *newcell = (UITableViewCell1 *)cell;
        [newcell  updatCellUI];
    }
    else if ([NSStringFromClass(cell.class) isEqualToString:@"UITableViewCell2"]) {
        UITableViewCell2 *newcell = (UITableViewCell2 *)cell;
        [newcell updatCellUIBuy: model1 sell: model2];
    }
    else if ([NSStringFromClass(cell.class) isEqualToString:@"UITableViewCell3"]){
        cell.backgroundColor = GL_CELL_BACKGROUD_COLOR;
        [cell addSubview:self.someView];// someView is a lazy property
    }
}


问:
UICollectionView display 3 items per row
I have a UICollectionView created from storyboard,

I want to have 3 items per row in the view. I managed to do that using the following:

```<code>    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(collectionView.frame.size.width/3.6 , (collectionView.frame.size.height-100)/2);
}
</code>```

However, if i have 6 items, i got 2 rows with 3 items each.
But when i have 4 items, it will display  2 rows with 2 items each.

Is it possible to display them in 2 rows, the first with 3 items and the second contains only 1?

答:
```<code>- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.collectionView.bounds.size.width/3, self.collectionView.bounds.size.width/3);
}
</code>```

Most important thing need to do as well is in size inspector of collectionView set up the minimum spacing for cell & line to 0

Body:
I have a UICollectionView created from storyboard,

I want to have 3 items per row in the view. I managed to do that using the following:

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(collectionView.frame.size.width/3.6 , (collectionView.frame.size.height-100)/2);
}

However, if i have 6 items, i got 2 rows with 3 items each.
But when i have 4 items, it will display  2 rows with 2 items each.

Is it possible to display them in 2 rows, the first with 3 items and the second contains only 1?

Body:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.collectionView.bounds.size.width/3, self.collectionView.bounds.size.width/3);
}

Most important thing need to do as well is in size inspector of collectionView set up the minimum spacing for cell & line to 0


问:
How can I get a link to a Facebook or Twitter avatar by username?
How can I get a link to a Facebook or Twitter avatar by username?</p>

答:
Some programming paradigms (Razor in ASP.NET or ASP.NET MVC 3, for example) have their own helpers to work with social media. If the paradigm you are programming in does not have helpers, you will have to access the FaceBook and/or Twitter APIs and use them to get the "avatar".

I have not played with Facebook, but the Twitter avatar link is provided on the user's profile, when you get it.