问:
Caesar in CBC / How to XOR in Java?
I have been trying out to ''improve'' the simple Caesar encryption by encrypting in the CBC mode.

As I understand, the first character has to be XORed by an initialization vector and then by the key, the output then is the first character of the encrypted text. This will then be XORed by the second char, then again XORed by the key, … and so forth.

I don't quite understand how the XORing should work.

Let us have the translation table given (only space and A-Z):
/s: 0, A: 1, B: 2, …, Z: 26,
key: 1,
Init.vector: 5

Using the simple Caesar, ''HELLO'' -> {8,5,12,12,20} -> {9,6,13,13,21} -> ''IFMMP''

But how would I get to encrypt using CBC?

It'd be especially helpful if you could show me how to implement it in Java. Thanks!

答:
Hmm I interpret your question like you think you want to xor by the key to your cipher, this is wrong:

You xor by the previous result from the cipher. Something like this:

```<code>// Untested code
// The code below need to be adjusted for it to print meaningful
// characters in the encrypted string as the xor function produces
// integers outside the range of standard ascii characters

private void cbcCaesar(){

    int key = 1;
    String message = "java";
    int initialisationVector = 5; // the IV is not super necessarily hidden from an attacker but should be different for each message

    StringBuilder encryptedMessageBuilder = new StringBuilder();

    char[] charArray = message.toCharArray();

    int encryptedLetter = initialisationVector;
    for (int letter : charArray){
        int xorApplied = letter ^ encryptedLetter;
        encryptedLetter = applyCaesarCipher(xorApplied, key);
        encryptedMessageBuilder.append((char) encryptedLetter);
    }

    System.out.println(encryptedMessageBuilder.toString());
}

private int applyCaesarCipher(int xorApplied, int key) {
    return (xorApplied+ key) % 26;
}
</code>```

The easiest way to convert the above snippet to something usable would be to map letters to the numbers 0-26 and use that instead of the char's ascii encoding

I found this resource to be pretty good https://www.youtube.com/watch?v=0D7OwYp6ZEc

Title: Caesar in CBC / How to XOR in Java?

Body:
Hmm I interpret your question like you think you want to xor by the key to your cipher, this is wrong:

You xor by the previous result from the cipher. Something like this:

// Untested code
// The code below need to be adjusted for it to print meaningful
// characters in the encrypted string as the xor function produces
// integers outside the range of standard ascii characters

private void cbcCaesar(){

    int key = 1;
    String message = "java";
    int initialisationVector = 5; // the IV is not super necessarily hidden from an attacker but should be different for each message

    StringBuilder encryptedMessageBuilder = new StringBuilder();

    char[] charArray = message.toCharArray();

    int encryptedLetter = initialisationVector;
    for (int letter : charArray){
        int xorApplied = letter ^ encryptedLetter;
        encryptedLetter = applyCaesarCipher(xorApplied, key);
        encryptedMessageBuilder.append((char) encryptedLetter);
    }

    System.out.println(encryptedMessageBuilder.toString());
}

private int applyCaesarCipher(int xorApplied, int key) {
    return (xorApplied+ key) % 26;
}

The easiest way to convert the above snippet to something usable would be to map letters to the numbers 0-26 and use that instead of the char's ascii encoding

I found this resource to be pretty good https://www.youtube.com/watch?v=0D7OwYp6ZEc


来源: stackexchange

问:
android widget button on press event
I'm trying to create a widget button to run an application activity directly through the home screen.
the widget change the image when i press it according to the my_button.xml file.
but i can't create an event when i click on it.

i need to know how to call "onPress" event (for example) in order to call a method inside my main activity.
I would appreciate your help

i attached the relevant files.

widget.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_height="wrap_content" android:layout_width="wrap_content">

  <Button
        android:id="@+id/button_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@drawable/my_button" />
</LinearLayout>
</code>```

my_button.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btn1"
          android:state_pressed="true" />
    <item android:drawable="@drawable/btn2"
          android:state_focused="true" />
    <item android:drawable="@drawable/btn3" />
</selector>
</code>```

myWidgetProvider.java

```<code>package com.callsift.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MyWidgetProvider extends AppWidgetProvider {

    public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
    public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";

        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
            Toast.makeText(context, "onUpdate", Toast.LENGTH_SHORT).show();

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
            Intent configIntent = new Intent(context, CallSift.class);
            configIntent.setAction(ACTION_WIDGET_CONFIGURE);

            Intent active = new Intent(context, MyWidgetProvider.class);
            active.setAction(ACTION_WIDGET_RECEIVER);
            active.putExtra("msg", "Message for Button 1");

            //PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
            PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);

        //  remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
            remoteViews.setOnClickPendingIntent(R.id.button_one, configPendingIntent);

            appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
        }

        @Override

        public void onReceive(Context context, Intent intent) {

            // v1.5 fix that doesn't call onDelete Action
            final String action = intent.getAction();
            if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
                final int appWidgetId = intent.getExtras().getInt(
                        AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                    this.onDeleted(context, new int[] { appWidgetId });
                }
            } else {
                // check, if our Action was called
                if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
                    Toast.makeText(context, "blblbl", Toast.LENGTH_SHORT).show();
                    String msg = "null";
                    try {
                        msg = intent.getStringExtra("msg");

                    //  Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();

                    } catch (NullPointerException e) {
                        Log.e("Error", "msg = null");
                    }
                    Toast.makeText(context, "ttttt", Toast.LENGTH_SHORT).show();

                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
                    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification noty = new Notification(R.drawable.icon, "Button 1 clicked", System.currentTimeMillis());

                    noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
                    notificationManager.notify(1, noty);

                } else {
                    // do nothing
                }

                super.onReceive(context, intent);
            }
        }
    }
</code>```

androidmainfast.xml - Relavent part

```<code>        <!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".MyWidgetProvider" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        <!-- Broadcast Receiver that will also process our self created action -->
            <action android:name="com.callsift.activity.MyWidgetProvider.ACTION_WIDGET_RECEIVER"/>
    </intent-filter>
    <meta-data android:name="android.appwidget.provider" android:resource="@xml/button_widget_provider" />
</receiver>
</code>```

答:
You can launch the new activity like this by changing your code on OnReceive Like this.

```<code>  if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {

      Intent newIntent = new Intent("YOUR_INTENT_ACTION");
       newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(newIntent);
</code>```

}

ContentLicense: CC BY-SA 2.5

Title: android widget button on press event

Body:
I'm trying to create a widget button to run an application activity directly through the home screen.
the widget change the image when i press it according to the my_button.xml file.
but i can't create an event when i click on it.

i need to know how to call "onPress" event (for example) in order to call a method inside my main activity.
I would appreciate your help

i attached the relevant files.

widget.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_height="wrap_content" android:layout_width="wrap_content">

  <Button
        android:id="@+id/button_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@drawable/my_button" />
</LinearLayout>

my_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btn1"
          android:state_pressed="true" />
    <item android:drawable="@drawable/btn2"
          android:state_focused="true" />
    <item android:drawable="@drawable/btn3" />
</selector>

myWidgetProvider.java

package com.callsift.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MyWidgetProvider extends AppWidgetProvider {

    public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
    public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";

        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
            Toast.makeText(context, "onUpdate", Toast.LENGTH_SHORT).show();

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
            Intent configIntent = new Intent(context, CallSift.class);
            configIntent.setAction(ACTION_WIDGET_CONFIGURE);

            Intent active = new Intent(context, MyWidgetProvider.class);
            active.setAction(ACTION_WIDGET_RECEIVER);
            active.putExtra("msg", "Message for Button 1");

            //PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
            PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);

        //  remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
            remoteViews.setOnClickPendingIntent(R.id.button_one, configPendingIntent);

            appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
        }

        @Override

        public void onReceive(Context context, Intent intent) {

            // v1.5 fix that doesn't call onDelete Action
            final String action = intent.getAction();
            if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
                final int appWidgetId = intent.getExtras().getInt(
                        AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                    this.onDeleted(context, new int[] { appWidgetId });
                }
            } else {
                // check, if our Action was called
                if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
                    Toast.makeText(context, "blblbl", Toast.LENGTH_SHORT).show();
                    String msg = "null";
                    try {
                        msg = intent.getStringExtra("msg");

                    //  Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();

                    } catch (NullPointerException e) {
                        Log.e("Error", "msg = null");
                    }
                    Toast.makeText(context, "ttttt", Toast.LENGTH_SHORT).show();

                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
                    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification noty = new Notification(R.drawable.icon, "Button 1 clicked", System.currentTimeMillis());

                    noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
                    notificationManager.notify(1, noty);

                } else {
                    // do nothing
                }

                super.onReceive(context, intent);
            }
        }
    }

androidmainfast.xml - Relavent part

<receiver android:name=".MyWidgetProvider" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />

            <action android:name="com.callsift.activity.MyWidgetProvider.ACTION_WIDGET_RECEIVER"/>
    </intent-filter>
    <meta-data android:name="android.appwidget.provider" android:resource="@xml/button_widget_provider" />
</receiver>

Body:
You can launch the new activity like this by changing your code on OnReceive Like this.

  if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {

      Intent newIntent = new Intent("YOUR_INTENT_ACTION");
       newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(newIntent);

}


问:
SQL - How can I use UNION to join three INNER JOIN results into a single results table?
For the table:

```<code>assistants_rating(
id INT PRIMARY KEY auto_increment,
assistant_id INT(11),
rating INT(1)
)
</code>```

And another table of assistants which contains a name. My query goes as follows:

```<code>(SELECT assistants.name AS assist_name , count(rating) AS OneStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 1)

UNION

(SELECT assistants.name AS assist_name , count(rating) AS TwoStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 2)

UNION

(SELECT assistants.name AS assist_name , count(rating) AS ThreeStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 3)

GROUP BY assistants.name,OneStar,TwoStar,ThreeStar;
</code>```

Let's say I have the assistants named Bob and Sophie, the query should return:

```<code>assist_name   OneStar    TwoStar    ThreeStar

  Bob            9         18          52

 Sophie          15        8           61
</code>```

But instead I'm getting a SQL syntax error, which is weird because when I do each of them alone , they work properly and that leads me to believe that my syntax is good. Not only that, but my queries with the UNION work if I only do TwoStar and ThreeStar together but not with OneStar and TwoStar.

I'm so confused; why doesn't this work?

答:
UNION doesn't help here anyway. It does a different thing.

The query you need is something along the lines of:

```<code>SELECT
    assistants.name AS assist_name,
    SUM(IF(rating = 1, 1, 0)) AS OneStar,
    SUM(IF(rating = 2, 1, 0)) AS TwoStar,
    SUM(IF(rating = 3, 1, 0)) AS ThreeStar
FROM assistants_rating
    INNER JOIN assistants ON assistants.assistant_id = assistants_rating.assistant_id
GROUP BY assistants.name
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For the table:

assistants_rating(
id INT PRIMARY KEY auto_increment,
assistant_id INT(11),
rating INT(1)
)

And another table of assistants which contains a name. My query goes as follows:

(SELECT assistants.name AS assist_name , count(rating) AS OneStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 1)

UNION

(SELECT assistants.name AS assist_name , count(rating) AS TwoStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 2)

UNION

(SELECT assistants.name AS assist_name , count(rating) AS ThreeStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 3)

GROUP BY assistants.name,OneStar,TwoStar,ThreeStar;

Let's say I have the assistants named Bob and Sophie, the query should return:

assist_name   OneStar    TwoStar    ThreeStar

  Bob            9         18          52

 Sophie          15        8           61

But instead I'm getting a SQL syntax error, which is weird because when I do each of them alone , they work properly and that leads me to believe that my syntax is good. Not only that, but my queries with the UNION work if I only do TwoStar and ThreeStar together but not with OneStar and TwoStar.

I'm so confused; why doesn't this work?

Body:
UNION doesn't help here anyway. It does a different thing.

The query you need is something along the lines of:

SELECT
    assistants.name AS assist_name,
    SUM(IF(rating = 1, 1, 0)) AS OneStar,
    SUM(IF(rating = 2, 1, 0)) AS TwoStar,
    SUM(IF(rating = 3, 1, 0)) AS ThreeStar
FROM assistants_rating
    INNER JOIN assistants ON assistants.assistant_id = assistants_rating.assistant_id
GROUP BY assistants.name


问:
Scala get next index in the list from current item
Say for example I am mapping one list to the next, and in the map I want to do some calculation with the current item in the list with the next item in the list.

```<code>def someFunc(L: List[Integer]) : List[Integer] = {
    L.collect {
        case k if (k != L(L.length-1)) //do something with k and the next element
    }
}
</code>```

A simple example is I want to go through this List of Integers, and map each number onto the next number in the list divided by it.

E.g. (1,2,3) -> (2/1, 3/2) == (2, 1.5)

I had thought about doing this using indexOf but I don't think that is efficient having to search the whole list for the current element even though I am already traversing each element in the list anyway.

答:
Use .sliding for this:

```<code>scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.sliding(2).toList
res0: List[List[Int]] = List(List(1, 2), List(2, 3))

scala> l.sliding(2).collect { case x::y::Nil if y != 0 => x / y.toDouble }.toList
res1: List[Double] = List(0.5, 0.6666666666666666)
</code>```

Body:
Say for example I am mapping one list to the next, and in the map I want to do some calculation with the current item in the list with the next item in the list.

def someFunc(L: List[Integer]) : List[Integer] = {
    L.collect {
        case k if (k != L(L.length-1)) //do something with k and the next element
    }
}

A simple example is I want to go through this List of Integers, and map each number onto the next number in the list divided by it.

E.g. (1,2,3) -> (2/1, 3/2) == (2, 1.5)

I had thought about doing this using indexOf but I don't think that is efficient having to search the whole list for the current element even though I am already traversing each element in the list anyway.

Body:
Use .sliding for this:

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.sliding(2).toList
res0: List[List[Int]] = List(List(1, 2), List(2, 3))

scala> l.sliding(2).collect { case x::y::Nil if y != 0 => x / y.toDouble }.toList
res1: List[Double] = List(0.5, 0.6666666666666666)


问:
Angular 4 - Scroll To item in list based on search input
I can do this with custom javascript but was wondering if there is anything built into Angular 4 that I might be able to make use of.  I have a list of checkboxes that can be scrolled through and a search input above.  I want to be able to jump to a section in the list as a user types in the search input. My HTML:

```<code><!-- Sold To -->
<div class="col-md-12 input-container">
    <div class="checkbox-group">
        <input type="search" placeholder="Jump to Soldto...">
        <div class="checkbox-wrap">
            <mat-checkbox *ngFor="let option of soldToOptions">
                {{ option }}
            </mat-checkbox>
        </div>
    </div>
</div>
</code>```

And a sample list of the array that I am looping through for the checkboxes (there will actually be about 300 entries in this array)...

```<code>soldToOptions = [
 '1028341000-MITSUBISHI WONOKE MENTOR-DALLAS',
 '1018551000-ADVANCE STARTER TEST-CINCINNATI',
 '1030591000-AMERICAN JOYRIDE CARTHAGE-SAN FRANCISCO',
 '1023221000-TESTING GENERAL OAKLAND-OAKLAND'
];
</code>```

I will first need to order these alphabetically based on the the first part of the string after the initial '-'.  Just wondering if there is anything built in to Angular 4 that would allow me to match the user's input string to the value from the array and jump to that section in the scrollable checkboxes.  I strictly do not want to filter the list, just move the the proper place in the list. Any help is much appreciated.

答: ngx-page-scroll should be able to meet your needs. You would just need a way to dynamically add the markup to identify each element generated.</p>

Body:
I can do this with custom javascript but was wondering if there is anything built into Angular 4 that I might be able to make use of.  I have a list of checkboxes that can be scrolled through and a search input above.  I want to be able to jump to a section in the list as a user types in the search input. My HTML:

        <input type="search" placeholder="Jump to Soldto...">

            <mat-checkbox *ngFor="let option of soldToOptions">
                {{ option }}
            </mat-checkbox>

And a sample list of the array that I am looping through for the checkboxes (there will actually be about 300 entries in this array)...

soldToOptions = [
 '1028341000-MITSUBISHI WONOKE MENTOR-DALLAS',
 '1018551000-ADVANCE STARTER TEST-CINCINNATI',
 '1030591000-AMERICAN JOYRIDE CARTHAGE-SAN FRANCISCO',
 '1023221000-TESTING GENERAL OAKLAND-OAKLAND'
];

I will first need to order these alphabetically based on the the first part of the string after the initial '-'.  Just wondering if there is anything built in to Angular 4 that would allow me to match the user's input string to the value from the array and jump to that section in the scrollable checkboxes.  I strictly do not want to filter the list, just move the the proper place in the list. Any help is much appreciated.


问:
Python List of users
I want to learn how to create an API, so I want to create an empty dictionary where the first key is Names. Names will be a dictionary with the names of the users the system will have.

How do I actually do it with python?

People = [{}]

I want it to be something like:

```<code>People = [Names:["name1", "name2"... "nameN"]]
</code>```

later on, I want to add more information like for example:

```<code>People[Names:[], Age:["1","2"]..]
</code>```

I want at some stage be able to relate any name to any other key correctly.
name1 has age 1 and next key...

How do I declare this dictionary?

答:
What I was trying to do:</p>

```<code>person = {
          "name":
                {
                    "title":"Herr","first":"foo","last":"bar"
                },
          "email":"bar@foo.de",
          "password":"123",
          "property":"value"
         }
</code>```

Title: Python List of users

Body:
I want to learn how to create an API, so I want to create an empty dictionary where the first key is Names. Names will be a dictionary with the names of the users the system will have.

How do I actually do it with python?

People = [{}]

I want it to be something like:

People = [Names:["name1", "name2"... "nameN"]]

later on, I want to add more information like for example:

People[Names:[], Age:["1","2"]..]

I want at some stage be able to relate any name to any other key correctly.
name1 has age 1 and next key...

How do I declare this dictionary?

Body:
What I was trying to do:

person = {
          "name":
                {
                    "title":"Herr","first":"foo","last":"bar"
                },
          "email":"bar@foo.de",
          "password":"123",
          "property":"value"
         }


问:
Vue.js - Vuexx : state value undefined
After user login authentication  ( LoginPage component ) the currentUserId is set in the store, but trying to get it later in another component ( ShoppingLists ) gives an undefined value ... what's wrong with my flow ?

here is my store.js

```<code>    import Vue from 'vue'
    import Vuex from 'vuex'
    import getters from '@/vuex/getters'
    import actions from '@/vuex/actions'
    import mutations from '@/vuex/mutations'

    import vueAuthInstance from '../services/auth.js'

    Vue.use(Vuex)

    const state = {
      shoppinglists: [],
      isAuthenticated: vueAuthInstance.isAuthenticated(),
      currentUserId: ''
    }

    export default new Vuex.Store({
      state,
      mutations,
      getters,
      actions
    })
</code>```

Here are the console.log output with related pieces of code

// LoginPage component submit button fires the login action

```<code>  methods: _.extend({}, mapActions(['login']), {
    clearErrorMessage () {
      this.hasError = false
    },
    submit () {
      return this.login({user: { email: this.email, password: this.password }})
      .then((logged) => {
        if (logged) {
          this.$router.push('shoppinglists')
        } else {
          this.hasError = true
        }
      })
    }
  }),
</code>```

action.js

```<code>  login: ({ commit }, payload) => {
    payload = payload || {}
    return vueAuthInstance.login(payload.user, payload.requestOptions)
    .then((response) => {
     // check response user or empty
      if (JSON.stringify(response.data) !== '{}') {
        commit(IS_AUTHENTICATED, { isAuthenticated: true })
        commit(CURRENT_USER_ID, { currentUserId: response.data.id })
        return true
      } else {
        commit(IS_AUTHENTICATED, { isAuthenticated: false })
        commit(CURRENT_USER_ID, { currentUserId: '' })
        return false
      }
    })
  },
</code>```

console.log
        mutations.js?d9b0:23
            state isAuthenticated:  true
        mutations.js?d9b0:27
            committed state currentUserId:  1

At this point the store should be updated ....

// then the LoginPage component push the ShoppingListsPage
when mounted it shoudl populates the shoppinglists

```<code>methods: _.extend({}, mapActions(['populateShoppingLists', 'createShoppingList']), {
  addShoppingList () {
    let list = { title: 'New Shopping List', items: [] }
    this.createShoppingList(list)
  }
}),
store,
mounted: function () {
  this.$nextTick(function () {
    console.log('GOING TO POPULATE STORE SHOPPINGLISTS FOR CURRENT USER')
    this.populateShoppingLists()
  })
}
</code>```

console.log
        ShoppingListsPage.vue?88a1:52
            GOING TO POPULATE STORE SHOPPINGLISTS FOR CURRENT USER

```<code>    actions.js?a7ea:9
        TRYING TO GET currentUserId with GETTERS

        populateShoppingLists: ({ commit }) => {
          console.log('TRYING TO GET currentUserId with GETTERS')
          const currentUserId = getters.getCurrentUserId({ commit })
          console.log('ACTIONS: populateShoppingLists for user: ', currentUserId)
          return api.fetchShoppingLists(currentUserId)
          .then(response => {
            commit(POPULATE_SHOPPING_LISTS, response.data)
            return response
          })
          .catch((error) => {
            throw error
          })
        },
</code>```

console.log

```<code>    getters.js?d717:9
        GETTERS: currentUserId:  undefined
</code>```

Getters returning an undefined value from the store

```<code>      getCurrentUserId: (state) => {
        console.log('GETTERS: currentUserId: ', state.currentUserId)
        return state.currentUserId
      },
</code>```

UPDATE

mutations.js

```<code>    import * as types from './mutation_types'
    import getters from './getters'
    import _ from 'underscore'

    export default {
      [types.POPULATE_SHOPPING_LISTS] (state, lists) {
        state.shoppinglists = lists
      },
      [types.IS_AUTHENTICATED]  (state, payload) {
        console.log('committed state isAuthenticated: ', payload.isAuthenticated)
        state.isAuthenticated = payload.isAuthenticated
      },
      [types.CURRENT_USER_ID]  (state, payload) {
        console.log('committed state currentUserId: ', payload.currentUserId)
        state.currentUserId = payload.currentUserId
      }
    }
</code>```

mutation_types

```<code>    export const POPULATE_SHOPPING_LISTS = 'POPULATE_SHOPPING_LISTS'
    export const IS_AUTHENTICATED = 'IS_AUTHENTICATED'
    export const CURRENT_USER_ID = 'CURRENT_USER_ID'
</code>```

答:
I solved the issue , modifying the action populateShoppingLists
Need to pass the state as a parameter with the commit , so I can use the getters inside my action</p>

```<code>populateShoppingLists: ({ commit, state }) => {
    let currentUserId = getters.currentUserId(state)
    console.log('currentUserId: ', currentUserId). // => userId: 1 Ok
    return api.fetchShoppingLists(currentUserId)
</code>```

Title: Vue.js - Vuexx : state value undefined

Body:
After user login authentication  ( LoginPage component ) the currentUserId is set in the store, but trying to get it later in another component ( ShoppingLists ) gives an undefined value ... what's wrong with my flow ?

here is my store.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    import getters from '@/vuex/getters'
    import actions from '@/vuex/actions'
    import mutations from '@/vuex/mutations'

    import vueAuthInstance from '../services/auth.js'

    Vue.use(Vuex)

    const state = {
      shoppinglists: [],
      isAuthenticated: vueAuthInstance.isAuthenticated(),
      currentUserId: ''
    }

    export default new Vuex.Store({
      state,
      mutations,
      getters,
      actions
    })

Here are the console.log output with related pieces of code

// LoginPage component submit button fires the login action

  methods: _.extend({}, mapActions(['login']), {
    clearErrorMessage () {
      this.hasError = false
    },
    submit () {
      return this.login({user: { email: this.email, password: this.password }})
      .then((logged) => {
        if (logged) {
          this.$router.push('shoppinglists')
        } else {
          this.hasError = true
        }
      })
    }
  }),

action.js

  login: ({ commit }, payload) => {
    payload = payload || {}
    return vueAuthInstance.login(payload.user, payload.requestOptions)
    .then((response) => {
     // check response user or empty
      if (JSON.stringify(response.data) !== '{}') {
        commit(IS_AUTHENTICATED, { isAuthenticated: true })
        commit(CURRENT_USER_ID, { currentUserId: response.data.id })
        return true
      } else {
        commit(IS_AUTHENTICATED, { isAuthenticated: false })
        commit(CURRENT_USER_ID, { currentUserId: '' })
        return false
      }
    })
  },

console.log
        mutations.js?d9b0:23
            state isAuthenticated:  true
        mutations.js?d9b0:27
            committed state currentUserId:  1

At this point the store should be updated ....

// then the LoginPage component push the ShoppingListsPage
when mounted it shoudl populates the shoppinglists

methods: _.extend({}, mapActions(['populateShoppingLists', 'createShoppingList']), {
  addShoppingList () {
    let list = { title: 'New Shopping List', items: [] }
    this.createShoppingList(list)
  }
}),
store,
mounted: function () {
  this.$nextTick(function () {
    console.log('GOING TO POPULATE STORE SHOPPINGLISTS FOR CURRENT USER')
    this.populateShoppingLists()
  })
}

console.log
        ShoppingListsPage.vue?88a1:52
            GOING TO POPULATE STORE SHOPPINGLISTS FOR CURRENT USER

    actions.js?a7ea:9
        TRYING TO GET currentUserId with GETTERS

        populateShoppingLists: ({ commit }) => {
          console.log('TRYING TO GET currentUserId with GETTERS')
          const currentUserId = getters.getCurrentUserId({ commit })
          console.log('ACTIONS: populateShoppingLists for user: ', currentUserId)
          return api.fetchShoppingLists(currentUserId)
          .then(response => {
            commit(POPULATE_SHOPPING_LISTS, response.data)
            return response
          })
          .catch((error) => {
            throw error
          })
        },

console.log

    getters.js?d717:9
        GETTERS: currentUserId:  undefined

Getters returning an undefined value from the store

      getCurrentUserId: (state) => {
        console.log('GETTERS: currentUserId: ', state.currentUserId)
        return state.currentUserId
      },

UPDATE

mutations.js

    import * as types from './mutation_types'
    import getters from './getters'
    import _ from 'underscore'

    export default {
      [types.POPULATE_SHOPPING_LISTS] (state, lists) {
        state.shoppinglists = lists
      },
      [types.IS_AUTHENTICATED]  (state, payload) {
        console.log('committed state isAuthenticated: ', payload.isAuthenticated)
        state.isAuthenticated = payload.isAuthenticated
      },
      [types.CURRENT_USER_ID]  (state, payload) {
        console.log('committed state currentUserId: ', payload.currentUserId)
        state.currentUserId = payload.currentUserId
      }
    }

mutation_types

    export const POPULATE_SHOPPING_LISTS = 'POPULATE_SHOPPING_LISTS'
    export const IS_AUTHENTICATED = 'IS_AUTHENTICATED'
    export const CURRENT_USER_ID = 'CURRENT_USER_ID'

Body:
I solved the issue , modifying the action populateShoppingLists
Need to pass the state as a parameter with the commit , so I can use the getters inside my action

populateShoppingLists: ({ commit, state }) => {
    let currentUserId = getters.currentUserId(state)
    console.log('currentUserId: ', currentUserId). // => userId: 1 Ok
    return api.fetchShoppingLists(currentUserId)


问:
VBA deleting a duplicate copy of chart object fails in Excel 2013
I have a VBA code that is intended to copy the contents of a range into a chart, to be able to export it to a PNG file (+some post-processing using an external command). Here is the relevant part:

```<code>Sub GenererImage()  ' Entry point
    getparams    ' Collect parameters and define global variables
    MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen,Format:=xlPicture
    Application.DisplayAlerts = False

    With ObjetGraphique.Duplicate
        .Chart.Paste
        .Chart.Export Filename:=CheminImage, Filtername:="PNG"
        .Select
        .Delete
    End With
    Application.DisplayAlerts = True
End Sub
</code>```

The getparams procedure called in there is just collecting some parameters from another worksheet to define:

"MiseEnPage": reference to the worksheet object where the range I want to copy exists,

"ZoneImage" is set to the "B4:F11" string (refers to the range address),

"ObjetGraphique" is a reference to a ChartObject inside the "MiseEnPage" sheet. This ChartObject is an empty container (I am mainly using it to easily set the width and height).

"CheminImage" is a string containing the path to the picture filename on disk.

This code used to work perfectly in Excel 2010. Now my company has deployed Excel 2013 and my code now fails on the .Delete line, leaving the copy of the ChartObject (with the range picture pasted inside it) on the sheet and stopping macro execution.

I have tried activating the worksheet first, selecting the duplicate prior to deleting it and other things, to no avail. When tracing the execution in the debugger it chokes on the delete line with error 1004.

I am frustratingly stuck. Any clue?

答:
OK after fiddling a lot with the object model, here is (the relevant part of) my final solution. Many thanks to HarassedDad for the clues.

```<code>Sub GenererImage()  ' Point d'entrée
    getparams
    MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen, Format:=xlPicture
    Application.DisplayAlerts = False
    With ObjetGraphique
        .Chart.Paste
        .Chart.Export filename:=CheminImage, Filtername:="PNG"
        .Chart.Shapes(1).Delete
    End With

    Application.DisplayAlerts = True
End Sub
</code>```

What seems to happen is that the .Paste method of the Chart object creates a Shape in the .Shapes collection of this object. I can delete this Shape, but not the Chart itself or the ChartObject. Excel 2010 would allow that, but not Excel 2013.

I still do not understand the reasons, but at least I have something that works (until the next excel update probably...).

Body:
I have a VBA code that is intended to copy the contents of a range into a chart, to be able to export it to a PNG file (+some post-processing using an external command). Here is the relevant part:

Sub GenererImage()  ' Entry point
    getparams    ' Collect parameters and define global variables
    MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen,Format:=xlPicture
    Application.DisplayAlerts = False

    With ObjetGraphique.Duplicate
        .Chart.Paste
        .Chart.Export Filename:=CheminImage, Filtername:="PNG"
        .Select
        .Delete
    End With
    Application.DisplayAlerts = True
End Sub

The getparams procedure called in there is just collecting some parameters from another worksheet to define:

"MiseEnPage": reference to the worksheet object where the range I want to copy exists,

"ZoneImage" is set to the "B4:F11" string (refers to the range address),

"ObjetGraphique" is a reference to a ChartObject inside the "MiseEnPage" sheet. This ChartObject is an empty container (I am mainly using it to easily set the width and height).

"CheminImage" is a string containing the path to the picture filename on disk.

This code used to work perfectly in Excel 2010. Now my company has deployed Excel 2013 and my code now fails on the .Delete line, leaving the copy of the ChartObject (with the range picture pasted inside it) on the sheet and stopping macro execution.

I have tried activating the worksheet first, selecting the duplicate prior to deleting it and other things, to no avail. When tracing the execution in the debugger it chokes on the delete line with error 1004.

I am frustratingly stuck. Any clue?

Body:
OK after fiddling a lot with the object model, here is (the relevant part of) my final solution. Many thanks to HarassedDad for the clues.

Sub GenererImage()  ' Point d'entrée
    getparams
    MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen, Format:=xlPicture
    Application.DisplayAlerts = False
    With ObjetGraphique
        .Chart.Paste
        .Chart.Export filename:=CheminImage, Filtername:="PNG"
        .Chart.Shapes(1).Delete
    End With

    Application.DisplayAlerts = True
End Sub

What seems to happen is that the .Paste method of the Chart object creates a Shape in the .Shapes collection of this object. I can delete this Shape, but not the Chart itself or the ChartObject. Excel 2010 would allow that, but not Excel 2013.

I still do not understand the reasons, but at least I have something that works (until the next excel update probably...).


问:
VBA: Excel macro code correction
I am looking for a VBA code that can help me to click a button from a web page. I got the below VBA from one of the sites which works as expected.

```<code>Sub followWebsiteLink()

Dim ie As InternetExplorer
Dim html As HTMLDocument
Dim Link As Object
Dim ElementCol As Object

Application.ScreenUpdating = False

Set ie = New InternetExplorer
ie.Visible = True

ie.navigate "https://www.google.co.in"

Do While ie.readyState <> READYSTATE_COMPLETE
Application.StatusBar = "Loading website…"
DoEvents
Loop

Set html = ie.document
Set ElementCol = html.getElementsByTagName("a")

For Each Link In ElementCol
If Link.innerHTML = "Google Pixel 2" _ 'Or u can use "Advertising"
Then
Link.Click
End If
Next Link

Set ie = Nothing
Application.StatusBar = ""
Application.ScreenUpdating = True
End Sub
</code>```

But if I replace it with the site name I want, it wont work.

**The changes I made are as follows **

```<code>ie.navigate "https://www.flipkart.com/"

For Each Link In ElementCol
If Link.innerHTML = "Log In" _
And Link.getElementsByClassName = "_2k0gmP" _
Then
Link.Click
End If
Next Link
</code>```

答:
Try this code, worked for me to click on Log In

Code

```<code>#If VBA7 Then
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Sub test()
Dim IE As Object
Dim htmlDoc As Object
Dim sURL As String

' CREATING OBJECT
Set IE = CreateObject("internetexplorer.application")

sURL = "https://www.flipkart.com/"
' WEBPAGE NAVIGATION
With IE
.navigate (sURL)
.Visible = True
End With

WaitIE IE, 2000

' CLICK ON LOG IN
Set htmlDoc = IE.document
Set buttonclick = htmlDoc.getElementsByClassName("_2k0gmP")

buttonclick(7).Click
WaitIE IE, 5000

'IE.Quit
'Set IE = Nothing
End Sub

Sub WaitIE(IE As Object, Optional time As Long = 250)
'Code from: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
    Sleep time
    Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.readyState = 4) & _
                vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
    i = i + 1
Loop Until IE.readyState = 4 Or Not IE.Busy
End Sub
</code>```

Edit

You can use this code to get the href:

```<code>For Each Element In buttonclick
Debug.Print Element.href
Next
</code>```

Or to get the InnerText:

```<code>For Each Element In buttonclick
Debug.Print Element.innerText & " " & i
i = i + 1
Next
'Where i is the number of the item
</code>```

Then you can use conditional such as:

```<code>For Each Element In buttonclick
If Element.href = "href_link" Then Element.Click
Next
</code>```

OR

```<code>For Each Element In buttonclick
If Element.innerText = "Log In" Then Element.Click
Next
</code>```

Title: VBA: Excel macro code correction

Body:
I am looking for a VBA code that can help me to click a button from a web page. I got the below VBA from one of the sites which works as expected.

Sub followWebsiteLink()

Dim ie As InternetExplorer
Dim html As HTMLDocument
Dim Link As Object
Dim ElementCol As Object

Application.ScreenUpdating = False

Set ie = New InternetExplorer
ie.Visible = True

ie.navigate "https://www.google.co.in"

Do While ie.readyState <> READYSTATE_COMPLETE
Application.StatusBar = "Loading website…"
DoEvents
Loop

Set html = ie.document
Set ElementCol = html.getElementsByTagName("a")

For Each Link In ElementCol
If Link.innerHTML = "Google Pixel 2" _ 'Or u can use "Advertising"
Then
Link.Click
End If
Next Link

Set ie = Nothing
Application.StatusBar = ""
Application.ScreenUpdating = True
End Sub

But if I replace it with the site name I want, it wont work.

**The changes I made are as follows **

ie.navigate "https://www.flipkart.com/"

For Each Link In ElementCol
If Link.innerHTML = "Log In" _
And Link.getElementsByClassName = "_2k0gmP" _
Then
Link.Click
End If
Next Link

Body:
Try this code, worked for me to click on Log In

Code

#If VBA7 Then
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Sub test()
Dim IE As Object
Dim htmlDoc As Object
Dim sURL As String

' CREATING OBJECT
Set IE = CreateObject("internetexplorer.application")

sURL = "https://www.flipkart.com/"
' WEBPAGE NAVIGATION
With IE
.navigate (sURL)
.Visible = True
End With

WaitIE IE, 2000

' CLICK ON LOG IN
Set htmlDoc = IE.document
Set buttonclick = htmlDoc.getElementsByClassName("_2k0gmP")

buttonclick(7).Click
WaitIE IE, 5000

'IE.Quit
'Set IE = Nothing
End Sub

Sub WaitIE(IE As Object, Optional time As Long = 250)
'Code from: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
    Sleep time
    Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.readyState = 4) & _
                vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
    i = i + 1
Loop Until IE.readyState = 4 Or Not IE.Busy
End Sub

Edit

You can use this code to get the href:

For Each Element In buttonclick
Debug.Print Element.href
Next

Or to get the InnerText:

For Each Element In buttonclick
Debug.Print Element.innerText & " " & i
i = i + 1
Next
'Where i is the number of the item

Then you can use conditional such as:

For Each Element In buttonclick
If Element.href = "href_link" Then Element.Click
Next

OR

For Each Element In buttonclick
If Element.innerText = "Log In" Then Element.Click
Next


问:
Grunt: minify js across project of multiple dirs, so that the contents of each dir flattens to a single minified file
I have a project, with javascript files structured something like this:

My goal: I would like to minify/uglify these javascript files in the build output, such as there is 1 minified file per each directory.    So for example, if I'm storing the js in my build output in bld/js, then in bld/js, I would end up with files: dir1.min.js (result of concatenating and minifying fileA.js, fileB.js, and all the other js files in /src/js/dir1/), dir2.min.js (result of concatenating and minifying fileG.js and fileN.js, and all the other js files in /src/dir2/), and so on.

Now - I am using the grunt framework to generate the build, and must do this within a grunt file.  I am new to grunt, node.js, and javascript.  I wanted to explain my thought process towards solving this problem, and am wondering if someone more familiar with these frameworks can tell me if my approach/thinking towards this is what is wrong.

So as I understand, the main way to do things in grunt, is to use plugins.  And so my first thought was to use a plugin to accomplish this task.  There is a plugin called 'npm-contrib-uglify', which is used specifically for minification.  https://github.com/gruntjs/grunt-contrib-uglify  The problem is - my understanding is that to do what I'm hoping to do here (1 min.js file per each directory), I would need to create specific tasks for each directory.  so the init looking something like this:

```<code> grunt.initConfig({
      uglify: {
        dir1: {
          files: {
            'dest/js/dir1.min.js': ['src/js/dir1/**.js']
          }
        },
        dir2: {
          files: {
            'dest/js/dir2.min.js': ['src/js/dir2/**.js']
          }
        },
...
        dirN: {
          files: {
            'dest/js/dirN.min.js': ['src/js/dirN/**.js']
          }
        },
      }
    });
</code>```

If I only had one or two dirs, and the project format was going to stay relatively the same - I guess I could live with this.  But there are many dirs in this project, and more importantly, the project structure will be changing; I'd like to be able to add dirs to my project, and not have to update the grunt file each time as a result by adding a new target.  I hoped for a way to parameterize the task - meaning, have a single generic target that says 'for some dir, minify all the .js files in that dir to some .min.js file' and then I could invoke the target programmatically for each dir - but this doesn't seem possible.

So I decided to avoid the plugin, and just rely on node.js.  There is an npm module called 'npm-uglify.  https://www.npmjs.com/package/uglify-js .  I thought I can make my own custom grunt task, which loops through the source directory, and calls uglify-js on each nested dir.  Here is an example (note I am using pseudocode in a couple places, particularly, for getting the dir listing, as I do not have access to a machine, and do not have the syntax committed to memory.  But this should give the idea of what I mean to do:)

```<code>var fs = require('fs');
var uglifyJs = require('uglify-js');
</code>```

...

```<code>grunt.registerTask('minifyMyJs', function(myJsSrcDir) { // myJsSrcDir is an abs. path to the src dir

    for (dir in myJsSrcDir): // go through all the dirs.. realize I should use fs.readdir, but just use pseudocode here to give the idea
        var minifiedOutputFileName = fs.basename(dir); // to get dir1 from /src/js/dir1
        var minified = uglifyJs.Minify(["**.js"]);
        fs.writeFile(minifiedOutputFileNam, result.code, function(err)) {
           if(err) {
              ... error checking...
           }
        }
    }
}
</code>```

Now - I'm not asking for you to solve this problem for me, and I know the above would not compile.  Rather my question is - am I just thinking about this in the completely wrong way?  Is the whole point of grunt to avoid coding things like this in node.js (and so I'm defeating the purpose by doing this?)  Is it that you really can parameterize the targets of the grunt plugins such as grunt-contrib-uglify?  I am running in to this same issue with many plugins, where I have some task I need to repeat over and over across many different dirs/files but in the exact same way, and so I'd like to be able to configure a general target I can call programmatically for different values (rather than hardcoding tons of targets for specific directory or filenames which could change often).  But this doesn't seem possible, and so I keep just implementing in node.js instead.  Is there something fundamentally flawed with the way I am approaching grunt?  And if so - can you offer some alternate perspective?

答:
Thoughts

am I just thinking about this in the completely wrong way?

No, I don't think you are thinking about this in the wrong way. It's always a good thing to question the why/how for any development [period]. This is what makes us better developers long-term.

Whichever solution/tools you choose to utilize for your build process, whether that be a dedicated task runner such as grunt or gulp, or a higher level solution such as nodejs perhaps combined with npm-scripts, you still have to craft some code. Of course, the commonality between all those approaches mentioned is that you have to code using JavaScript.

Is the whole point of grunt to avoid coding things like this in node.js (and so I'm defeating the purpose by doing this?

It's not for me to say which solution/tool is better to use than another (that would be too opinionated) and personally I have had experience developing build processes using all those tools mentioned. Typically though I often find my development time for handling builds is reduced when using a dedicated task runner (grunt or gulp) than when using a more custom approach such as npm-scripts combined with nodejs.

Often, I too find a really great plug-in for grunt (such as grunt-contrib-uglify) to then discover after some tinkering that it meets 90% of my requirements, yet fails miserably for the remaining 10%. However, that's often the case when utilizing/integrating any open sourced package/module... You still have to fill the gaps so to speak!

Grunts lesser known gems

Before ditching gruntjs and going into nodejs only development mode just yet, (and again to reiterate I have no bias towards any of the approaches), I recommend that you check-out some of grunts features such as:

custom-tasks

grunt.file.expand

grunt.config

grunt.task.run

There has been may scenarios when using grunt that I've found utlizing the features listed above has helped me to address that remaining 10% of the requirement that I mentioned previously. The custom-tasks feature in particular has proved very useful many times.

Solution

It's worth noting that grunt-contrib-uglify is a multi-task plugin. I.e. It allows you to configure multiple Targets as you have demonstrated in the your uglify configuration in your question. You have included three Targets named dir1, dir2, and dirN.

With the fact that grunt-contrib-uglify is multi-task and keeping in mind the grunt features I listed previously... One approach to meet your requirement using grunt is to:

Use a custom Task to dynamically configure and run the uglify task.

Utilize grunt.file.expandto get the paths to the parent folder of each .js file.

filter paths Array to only unique directory paths.

Dynamically create the files configuration for each Target of the uglify task.

Configure the uglify task with multiple Targets using grunt.config and then run the task using grunt-task.run.

Grunfile.js

module.exports = function (grunt) {

  'use strict';

  grunt.initConfig({
    uglify: {
      // <-- Intentionally blank, will be dynamically generated.
    }
  });

  /**
   * 1. Helper custom Task to dynamically configure and run the uglify task.
   */
  grunt.registerTask('myUglify', 'Configures uglify task', function () {
    var srcDirGlob = 'src/js/**/*.js';
    var destDir = 'dist/js/';
    var config = {};

    // 2. Get the paths to the parent diretory of each .js file.
    var paths = grunt.file.expand({ filter: 'isFile' }, srcDirGlob)
        .map(function (_path) {
          return _path.substring(0, _path.lastIndexOf("/"));
        });

    // 3. Filter paths Array to only unique directory paths.
    paths.filter(function(_path, pos){
          return paths.indexOf(_path) === pos;
        })

        // 4. Dynamically create the `files` configuration for each Target.
        .forEach(function(_path, index) {
          var dirName = _path.substring(_path.lastIndexOf('/') + 1);
          var destPath = destDir + dirName + '.min.js';
          var srcGlob = _path + '/*.js';

          config[index] = {
            files: {}
          }

          config[index].files[destPath] = srcGlob;
        });

    // NOTE: The dynamically created `config` object is now something like this:
    //
    //    config: {
    //      0: {
    //        files: {
    //          'dist/js/dir1.min.js': 'src/js/dir1/**.js'
    //        }
    //      },
    //      1: {
    //        files: {
    //          'dist/js/dir2.min.js': 'src/js/dir2/**.js'
    //        }
    //      },
    //      ...
    //    }

    // 5. Configure the uglify task with multiple Targets
    //    (i.e. the `config` object) and then run the Task.
    grunt.config('uglify', config);
    grunt.task.run(['uglify']);
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.registerTask('default', ["myUglify"]);
};
```
<p><strong>Results</strong></p>
<p>Running <code>$ grunt</code> via your CLI using the <code>Gruntfile.js</code> above with a <code>src</code> directory as follows:</p>
```.
└── src
    └── js
        ├── dir1
        │   ├── fileA.js
        │   └── fileB.js
        ├── dir2
        │   ├── fileG.js
        │   └── fileN.js
        └── dir3
            ├── fileQ.js
            └── fileR.js`
```
<p>..will concatenate and <code>uglify</code> the <code>.js</code> files producing a directory structure as follows:</p>
```.
└── dist
    └── js
        ├── dir1.min.js
        ├── dir2.min.js
        └── dir3.min.js`
```

Note: The parent folder name of the source .js file is used for the name of the resultant concatenated/uglified .js file.

Summary

The pattern/approach utilized in the Gruntfile.js (above) can be modified as necessary for many of the the plug-ins available.

As long as the plugin itself supports Multi-Tasks then consider utlizing a grunt Custom Task to fill in the gaps.

I hope this helps you.

Body:
I have a project, with javascript files structured something like this:

My goal: I would like to minify/uglify these javascript files in the build output, such as there is 1 minified file per each directory.    So for example, if I'm storing the js in my build output in bld/js, then in bld/js, I would end up with files: dir1.min.js (result of concatenating and minifying fileA.js, fileB.js, and all the other js files in /src/js/dir1/), dir2.min.js (result of concatenating and minifying fileG.js and fileN.js, and all the other js files in /src/dir2/), and so on.

Now - I am using the grunt framework to generate the build, and must do this within a grunt file.  I am new to grunt, node.js, and javascript.  I wanted to explain my thought process towards solving this problem, and am wondering if someone more familiar with these frameworks can tell me if my approach/thinking towards this is what is wrong.

So as I understand, the main way to do things in grunt, is to use plugins.  And so my first thought was to use a plugin to accomplish this task.  There is a plugin called 'npm-contrib-uglify', which is used specifically for minification.  https://github.com/gruntjs/grunt-contrib-uglify  The problem is - my understanding is that to do what I'm hoping to do here (1 min.js file per each directory), I would need to create specific tasks for each directory.  so the init looking something like this:

 grunt.initConfig({
      uglify: {
        dir1: {
          files: {
            'dest/js/dir1.min.js': ['src/js/dir1/**.js']
          }
        },
        dir2: {
          files: {
            'dest/js/dir2.min.js': ['src/js/dir2/**.js']
          }
        },
...
        dirN: {
          files: {
            'dest/js/dirN.min.js': ['src/js/dirN/**.js']
          }
        },
      }
    });

If I only had one or two dirs, and the project format was going to stay relatively the same - I guess I could live with this.  But there are many dirs in this project, and more importantly, the project structure will be changing; I'd like to be able to add dirs to my project, and not have to update the grunt file each time as a result by adding a new target.  I hoped for a way to parameterize the task - meaning, have a single generic target that says 'for some dir, minify all the .js files in that dir to some .min.js file' and then I could invoke the target programmatically for each dir - but this doesn't seem possible.

So I decided to avoid the plugin, and just rely on node.js.  There is an npm module called 'npm-uglify.  https://www.npmjs.com/package/uglify-js .  I thought I can make my own custom grunt task, which loops through the source directory, and calls uglify-js on each nested dir.  Here is an example (note I am using pseudocode in a couple places, particularly, for getting the dir listing, as I do not have access to a machine, and do not have the syntax committed to memory.  But this should give the idea of what I mean to do:)

var fs = require('fs');
var uglifyJs = require('uglify-js');

...

grunt.registerTask('minifyMyJs', function(myJsSrcDir) { // myJsSrcDir is an abs. path to the src dir

    for (dir in myJsSrcDir): // go through all the dirs.. realize I should use fs.readdir, but just use pseudocode here to give the idea
        var minifiedOutputFileName = fs.basename(dir); // to get dir1 from /src/js/dir1
        var minified = uglifyJs.Minify(["**.js"]);
        fs.writeFile(minifiedOutputFileNam, result.code, function(err)) {
           if(err) {
              ... error checking...
           }
        }
    }
}

Now - I'm not asking for you to solve this problem for me, and I know the above would not compile.  Rather my question is - am I just thinking about this in the completely wrong way?  Is the whole point of grunt to avoid coding things like this in node.js (and so I'm defeating the purpose by doing this?)  Is it that you really can parameterize the targets of the grunt plugins such as grunt-contrib-uglify?  I am running in to this same issue with many plugins, where I have some task I need to repeat over and over across many different dirs/files but in the exact same way, and so I'd like to be able to configure a general target I can call programmatically for different values (rather than hardcoding tons of targets for specific directory or filenames which could change often).  But this doesn't seem possible, and so I keep just implementing in node.js instead.  Is there something fundamentally flawed with the way I am approaching grunt?  And if so - can you offer some alternate perspective?

Body:
Thoughts

am I just thinking about this in the completely wrong way?

No, I don't think you are thinking about this in the wrong way. It's always a good thing to question the why/how for any development [period]. This is what makes us better developers long-term.

Whichever solution/tools you choose to utilize for your build process, whether that be a dedicated task runner such as grunt or gulp, or a higher level solution such as nodejs perhaps combined with npm-scripts, you still have to craft some code. Of course, the commonality between all those approaches mentioned is that you have to code using JavaScript.

Is the whole point of grunt to avoid coding things like this in node.js (and so I'm defeating the purpose by doing this?

It's not for me to say which solution/tool is better to use than another (that would be too opinionated) and personally I have had experience developing build processes using all those tools mentioned. Typically though I often find my development time for handling builds is reduced when using a dedicated task runner (grunt or gulp) than when using a more custom approach such as npm-scripts combined with nodejs.

Often, I too find a really great plug-in for grunt (such as grunt-contrib-uglify) to then discover after some tinkering that it meets 90% of my requirements, yet fails miserably for the remaining 10%. However, that's often the case when utilizing/integrating any open sourced package/module... You still have to fill the gaps so to speak!

Grunts lesser known gems

Before ditching gruntjs and going into nodejs only development mode just yet, (and again to reiterate I have no bias towards any of the approaches), I recommend that you check-out some of grunts features such as:

custom-tasks

grunt.file.expand

grunt.config

grunt.task.run

There has been may scenarios when using grunt that I've found utlizing the features listed above has helped me to address that remaining 10% of the requirement that I mentioned previously. The custom-tasks feature in particular has proved very useful many times.

Solution

It's worth noting that grunt-contrib-uglify is a multi-task plugin. I.e. It allows you to configure multiple Targets as you have demonstrated in the your uglify configuration in your question. You have included three Targets named dir1, dir2, and dirN.

With the fact that grunt-contrib-uglify is multi-task and keeping in mind the grunt features I listed previously... One approach to meet your requirement using grunt is to:

Use a custom Task to dynamically configure and run the uglify task.

Utilize grunt.file.expandto get the paths to the parent folder of each .js file.

filter paths Array to only unique directory paths.

Dynamically create the files configuration for each Target of the uglify task.

Configure the uglify task with multiple Targets using grunt.config and then run the task using grunt-task.run.

Grunfile.js

module.exports = function (grunt) {

  'use strict';

  grunt.initConfig({
    uglify: {
      // <-- Intentionally blank, will be dynamically generated.
    }
  });

  /**
   * 1. Helper custom Task to dynamically configure and run the uglify task.
   */
  grunt.registerTask('myUglify', 'Configures uglify task', function () {
    var srcDirGlob = 'src/js/**/*.js';
    var destDir = 'dist/js/';
    var config = {};

    // 2. Get the paths to the parent diretory of each .js file.
    var paths = grunt.file.expand({ filter: 'isFile' }, srcDirGlob)
        .map(function (_path) {
          return _path.substring(0, _path.lastIndexOf("/"));
        });

    // 3. Filter paths Array to only unique directory paths.
    paths.filter(function(_path, pos){
          return paths.indexOf(_path) === pos;
        })

        // 4. Dynamically create the `files` configuration for each Target.
        .forEach(function(_path, index) {
          var dirName = _path.substring(_path.lastIndexOf('/') + 1);
          var destPath = destDir + dirName + '.min.js';
          var srcGlob = _path + '/*.js';

          config[index] = {
            files: {}
          }

          config[index].files[destPath] = srcGlob;
        });

    // NOTE: The dynamically created `config` object is now something like this:
    //
    //    config: {
    //      0: {
    //        files: {
    //          'dist/js/dir1.min.js': 'src/js/dir1/**.js'
    //        }
    //      },
    //      1: {
    //        files: {
    //          'dist/js/dir2.min.js': 'src/js/dir2/**.js'
    //        }
    //      },
    //      ...
    //    }

    // 5. Configure the uglify task with multiple Targets
    //    (i.e. the `config` object) and then run the Task.
    grunt.config('uglify', config);
    grunt.task.run(['uglify']);
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.registerTask('default', ["myUglify"]);
};

Results

Running $ grunt via your CLI using the Gruntfile.js above with a src directory as follows:

.
└── src
    └── js
        ├── dir1
        │   ├── fileA.js
        │   └── fileB.js
        ├── dir2
        │   ├── fileG.js
        │   └── fileN.js
        └── dir3
            ├── fileQ.js
            └── fileR.js`

..will concatenate and uglify the .js files producing a directory structure as follows:

.
└── dist
    └── js
        ├── dir1.min.js
        ├── dir2.min.js
        └── dir3.min.js`

Note: The parent folder name of the source .js file is used for the name of the resultant concatenated/uglified .js file.

Summary

The pattern/approach utilized in the Gruntfile.js (above) can be modified as necessary for many of the the plug-ins available.

As long as the plugin itself supports Multi-Tasks then consider utlizing a grunt Custom Task to fill in the gaps.

I hope this helps you.


问:
OAuth2ClientAuthenticationProcessingFilter is not called after first authentication
I'm facing an issue with spring security oauth 2, at first connexion I'm getting my token and refresh token, everything is ok.

but it's seems the token is never checked, when it expire no refresh request is made, nothing happen and i'm still authenticated.

I debugged the issue and i noticed that my OAuth2ClientAuthenticationProcessingFilter is never called after first authentication.

here is how i define this filter :

```<code>@Bean
    public OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationProcessingFilter(){
        OAuth2ClientAuthenticationProcessingFilter filter =  new OAuth2ClientAuthenticationProcessingFilter("/myApp/**|/api/**");
        filter.setRestTemplate(oAuth2RestTemplate);
        filter.setTokenServices(tokenService);
        return filter;
    }
</code>```

any help would be welcome, it's  acouple of hours i'm struggling on this one

答:
Once a user has been authenticated to your application (i.e. the authentication is set to SecurityContext), it will remain authenticated until the http session is expired. It doesn't matter whether it has been authenticated by OAuth2ClientAuthenticationProcessingFilter or BasicAuthenticationFilter or any other authentication filter.

For example:-
If you have set session expiration to 30 min. And if a user logs in to your application from a browser and is authenticated to your application via OAuth 2 authentication. Now the next requests from the browser will have JSESSIONID set in the cookie and the server will identify from the security context that the session is already authenticated and not ask for further authentication.
Now if the user goes to the Auth providing server and revokes the token before the session is expired on your application server, it won't affect authentication on you application. And the user will remain logged in to your application until the session is expired (due to 30 min inactivity or by clearing the security context or possibly any other means like clearing cookies etc.).

Body:
I'm facing an issue with spring security oauth 2, at first connexion I'm getting my token and refresh token, everything is ok.

but it's seems the token is never checked, when it expire no refresh request is made, nothing happen and i'm still authenticated.

I debugged the issue and i noticed that my OAuth2ClientAuthenticationProcessingFilter is never called after first authentication.

here is how i define this filter :

@Bean
    public OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationProcessingFilter(){
        OAuth2ClientAuthenticationProcessingFilter filter =  new OAuth2ClientAuthenticationProcessingFilter("/myApp/**|/api/**");
        filter.setRestTemplate(oAuth2RestTemplate);
        filter.setTokenServices(tokenService);
        return filter;
    }

any help would be welcome, it's  acouple of hours i'm struggling on this one


问:
Data access with VS2010 IDE?
I'm working on my first C# project which is a small patience management system. I used SQL compact edition as my database. All of the contactings with SQLCE, I did them through the VS2010 IDE which automatically create connection string, manipulating dataset, so forth.
Although it's very convenient to program like this, it's hard for me to modify the data displayed(through datagridview) on the form as I like. So, I want to know where VS2010 store the connection string or query so that I can modify it? It seems to me that VS2010 hide all the details.
P/S: I used ADO.NET to access the database
Thanks all.</p>

答: The ConnectionString is stored in the app.Config or web.Config file.  As for how the data is queryed, that depends on what framework you are using, for example, Entity Frameworks etc.

Title: Data access with VS2010 IDE?


问:
Choose folder or folder directory inside shiny app
I have a problem using shiny. I want to choose the folder where all the files I want to use in my app are saved either 1) by setting the working directory to that folderpath or 2) by uploading all csv data inside this folder to my app for further processing. for 1) I found the shinyFiles package but it is very very slow -not due to my PC- as well as giving me the error:

```<code>Warning: Error in dir.create: invalid 'path' argument
Stack trace (innermost first):
    59: dir.create
    58: dirCreate
    57: observerFunc
     2: runApp
     1: shinyFilesExample
</code>```

when I selected a folder and the create folder button becomes clickable and I am putting a name of the new folder into it and clicking on the "+" beneath that panel. Anybody knows why? Despite that this method works but is very very slow. code below:

```<code>library(shiny)
library(shinyFiles)

ui<-fluidPage(sidebarLayout(

  sidebarPanel(
    shinyDirButton("dir", "Chose directory", "Upload")
  ),

  mainPanel(
    h4("output$dir"),
    verbatimTextOutput("dir"), br()

  )

))

server <- function(input,output,session){

  # dir
  shinyDirChoose(input, 'dir', roots = getVolumes())
  dir <- reactive(input$dir)
  output$dir <- renderPrint(dir())

}
shinyApp(ui = ui, server = server)
</code>```

Is there another option? Maybe to upload all csv data via the fileInput function? Or another way? It should not work only locally but on a server so choose.dir might be not the right way.
Many thanks

答:
so far, shinyfiles is the only way to input folders, as far as I know. It cannot work on a server, because browsers are not allowed to select folders (for security reasons).

The zipping way might be the only way to go if you want it to be working on a server (but I have no clue if it can actually be done)

ContentLicense: CC BY-SA 4.0

Body:
I have a problem using shiny. I want to choose the folder where all the files I want to use in my app are saved either 1) by setting the working directory to that folderpath or 2) by uploading all csv data inside this folder to my app for further processing. for 1) I found the shinyFiles package but it is very very slow -not due to my PC- as well as giving me the error:

Warning: Error in dir.create: invalid 'path' argument
Stack trace (innermost first):
    59: dir.create
    58: dirCreate
    57: observerFunc
     2: runApp
     1: shinyFilesExample

when I selected a folder and the create folder button becomes clickable and I am putting a name of the new folder into it and clicking on the "+" beneath that panel. Anybody knows why? Despite that this method works but is very very slow. code below:

library(shiny)
library(shinyFiles)

ui<-fluidPage(sidebarLayout(

  sidebarPanel(
    shinyDirButton("dir", "Chose directory", "Upload")
  ),

  mainPanel(
    h4("output$dir"),
    verbatimTextOutput("dir"), br()

  )

))

server <- function(input,output,session){

  # dir
  shinyDirChoose(input, 'dir', roots = getVolumes())
  dir <- reactive(input$dir)
  output$dir <- renderPrint(dir())

}
shinyApp(ui = ui, server = server)

Is there another option? Maybe to upload all csv data via the fileInput function? Or another way? It should not work only locally but on a server so choose.dir might be not the right way.
Many thanks


问:
Creating a new matrix by adjusting values within an old matrix through a for loop
I'd like to adjust certain values once they exceed a threshold of 180.  Here is a sample of the code:

```<code>mxn = Lon.shape
lon = []

for i in range(mxn[0]):
     for j in range(mxn[1]):
          if Lon[i,j]>180:
               lon.append(Lon[i,j]-360)
          elif Lon[i,j]<=180:
               lon.append(Lon[i,j])
</code>```

Essentially, I'd like to adjust the longitude from 0-360 to -180 to 180.  When performing this loop however, it returns a single array rather than a matrix that matches the size of Lon, the original matrix.  I know there is a way to do it but I'm having a difficult time finding a good resource showing how to do it.  Thanks in advance

答:
You are just appending all the values to a single array. Try making a sub-array in the nested for loop and then append that to lon.

```<code>for i in range(mxn[0]):
    sub = []
    for j in range(mxn[0])
        ....<append the values to sub>
    lon.append(sub)
</code>```

Body:
I'd like to adjust certain values once they exceed a threshold of 180.  Here is a sample of the code:

mxn = Lon.shape
lon = []

for i in range(mxn[0]):
     for j in range(mxn[1]):
          if Lon[i,j]>180:
               lon.append(Lon[i,j]-360)
          elif Lon[i,j]<=180:
               lon.append(Lon[i,j])

Essentially, I'd like to adjust the longitude from 0-360 to -180 to 180.  When performing this loop however, it returns a single array rather than a matrix that matches the size of Lon, the original matrix.  I know there is a way to do it but I'm having a difficult time finding a good resource showing how to do it.  Thanks in advance

Body:
You are just appending all the values to a single array. Try making a sub-array in the nested for loop and then append that to lon.

for i in range(mxn[0]):
    sub = []
    for j in range(mxn[0])
        ....<append the values to sub>
    lon.append(sub)


问:
DataContractSerializer works on Project A but Fails on Project B on Same Machine why?
I have a library which calls a DataContractSerializer.  I have been using it for many months in a ConsoleApp and a Windows Service App.  These were both created in Visual Studio 2015.

This week I created a new Win Forms App (in visual studio 2017) and I consume that .dll code.  Same code, same classes, same files - The 2 older projects still work, the new one throws this error.

Note: I am not using an app.config so all existing posts with that topic don't apply.  Also, I do not have a configSections or configuation node in my file, so those answers don't apply.

{System.Configuration.ConfigurationErrorsException: Configuration
  system failed to initialize --->
  System.Configuration.ConfigurationErrorsException: Only one
   element allowed per config file and if present must
  be the first child of the root  element.

The machine config's are the same cause they are all running on my machine.  So, I have no idea what else it might be.  Any ideas?

File which works correctly in my existing 2 projects starts with:

```<code>> <SettingsModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
> xmlns="http://schemas.datacontract.org/2004/07/Model">   <SettingsList
> xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
>     <d2p1:KeyValueOfstringSettingsOFv3k_StQ>
</code>```

Deserialization code which works for first 2 projects:

```<code> using (Stream stream = new MemoryStream())
 {
     byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
     stream.Write(data, 0, data.Length);
     stream.Position = 0;
     DataContractSerializer deserializer = new DataContractSerializer(typeof(GatewaySettingsModel));
     return deserializer.ReadObject(stream) as GatewaySettingsModel;
  }
</code>```

Edit

Config File for working app

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <appSettings>
    <add key="DataOption" value="5" />
  </appSettings>
  <entityFramework>
</code>```

Config file for non-working app

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="..." connectionString="..." />
    <add name="..." connectionString="..." providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
</code>```

As per the comment below and error text, the 'startup' tag had to be moved after the 'configurations' tag.  I don't understand why this error only was thrown for the DataContract Serialization, but this was the case.

答:
As per configSections Element (General Settings Schema) documentation

the configSections element is in a configuration file, the configSections element must be the first child element of the configuration element.

As a configuration file is configurable (you can add many sections and custom sections), the serializer needs to be able to understand these configuration sections, this requirement (that is first) removes problems like using a section before it handler is defined.

Body:
I have a library which calls a DataContractSerializer.  I have been using it for many months in a ConsoleApp and a Windows Service App.  These were both created in Visual Studio 2015.

This week I created a new Win Forms App (in visual studio 2017) and I consume that .dll code.  Same code, same classes, same files - The 2 older projects still work, the new one throws this error.

Note: I am not using an app.config so all existing posts with that topic don't apply.  Also, I do not have a configSections or configuation node in my file, so those answers don't apply.

{System.Configuration.ConfigurationErrorsException: Configuration
  system failed to initialize --->
  System.Configuration.ConfigurationErrorsException: Only one
   element allowed per config file and if present must
  be the first child of the root  element.

The machine config's are the same cause they are all running on my machine.  So, I have no idea what else it might be.  Any ideas?

File which works correctly in my existing 2 projects starts with:

> <SettingsModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
> xmlns="http://schemas.datacontract.org/2004/07/Model">   <SettingsList
> xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
>     <d2p1:KeyValueOfstringSettingsOFv3k_StQ>

Deserialization code which works for first 2 projects:

 using (Stream stream = new MemoryStream())
 {
     byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
     stream.Write(data, 0, data.Length);
     stream.Position = 0;
     DataContractSerializer deserializer = new DataContractSerializer(typeof(GatewaySettingsModel));
     return deserializer.ReadObject(stream) as GatewaySettingsModel;
  }

Edit

Config File for working app

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <appSettings>
    <add key="DataOption" value="5" />
  </appSettings>
  <entityFramework>

Config file for non-working app

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="..." connectionString="..." />
    <add name="..." connectionString="..." providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

As per the comment below and error text, the 'startup' tag had to be moved after the 'configurations' tag.  I don't understand why this error only was thrown for the DataContract Serialization, but this was the case.


问:
How to put a border around a google map
How to put a border around a google map? I have used:

```<code>mapcanvas.style.style='border:10px solid #0b0';
</code>```

Is this correct? I am new to Google maps.

I think I have found the reason for it not displaying but can any one have a look and let me know the correct format.

```<code><section id="wrapper">
Click the allow button on the top of the page to let the browser find your location.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<article>
</article>
<script>
function initialize() {
  var mapOptions = {
    zoom: 12,
    center: new google.maps.LatLng(-28.643387, 153.612224),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: true,
    mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
        position: google.maps.ControlPosition.BOTTOM_CENTER
    },
    panControl: true,
    panControlOptions: {
        position: google.maps.ControlPosition.TOP_RIGHT
    },
    zoomControl: true,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.LEFT_CENTER
    },
    scaleControl: true,
    scaleControlOptions: {
        position: google.maps.ControlPosition.TOP_LEFT
    },
    streetViewControl: true,
    streetViewControlOptions: {
        position: google.maps.ControlPosition.LEFT_TOP
    }
  }
  var map = new google.maps.Map(document.getElementById("map-canvas"),
      mapOptions);
}
function success(position) {
  var mapcanvas = document.createElement('div');
  mapcanvas.id = 'mapcontainer';
  mapcanvas.style.height = '250px';
  mapcanvas.style.width = 'auto';
  mapcanvas.style.style='border:10px solid #0b0';
  document.querySelector('article').appendChild(mapcanvas);
  var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  var options = {
    zoom: 15,
    center: coords,
    mapTypeControl: true,
    navigationControlOptions: {
        style: google.maps.NavigationControlStyle.SMALL
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
  var marker = new google.maps.Marker({
      position: coords,
      map: map,
      title:"You are here!"
  });
}
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(success);
} else {
  error('Geo Location is not supported');
}
</script>
</section>
</code>```

答:
super late to the party, but there is no doubt in my mind that the actual correct way to do this is by simply stylizing the wrapper with some basic css.

```<code>#wrapper{
  border:10px solid #0b0;
  min-height:250px;
  height:100%;
  width: 100%;
}
</code>```

Put #wrapper inside a specific height & width element to make the map fit specific dimensions.

Title: How to put a border around a google map

Body:
How to put a border around a google map? I have used:

mapcanvas.style.style='border:10px solid #0b0';

Is this correct? I am new to Google maps.

I think I have found the reason for it not displaying but can any one have a look and let me know the correct format.

Click the allow button on the top of the page to let the browser find your location.

Body:
super late to the party, but there is no doubt in my mind that the actual correct way to do this is by simply stylizing the wrapper with some basic css.

#wrapper{
  border:10px solid #0b0;
  min-height:250px;
  height:100%;
  width: 100%;
}

Put #wrapper inside a specific height & width element to make the map fit specific dimensions.


问:
Golang: How to capture panic and log this error to original log file?
I tried to capture panic and log the error:

```<code>func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    defer func() {
        if err := recover(); err != nil {
            glog.Errorf("Recovered from err: %v", err)
        }
    }()
    panic("TISH IS A PANIC")
    return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
</code>```

But to my surprise, the "Recovered from err: " never occurs in my log file, instead, it occurs in /var/log/messages.

How can I log that error in my original log file?

[Updated]

If there is no panic, glog.Errorf will log correctly to its log dir; when there is panic, it just can't:

```<code>// this glog will log correctly, unless uncomment the panic below
glog.Errorf("This is a normal log: %v", err)
// panic("TISH IS A PANIC")
</code>```

Maybe this is impossible, since that's what crash means?

答:
You need to call glog.Flush() in your deferred function. From the documentation of glog:

Log output is buffered and written periodically using Flush. Programs
  should call Flush before exiting to guarantee all log output is
  written.

https://godoc.org/github.com/golang/glog

Body:
I tried to capture panic and log the error:

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    defer func() {
        if err := recover(); err != nil {
            glog.Errorf("Recovered from err: %v", err)
        }
    }()
    panic("TISH IS A PANIC")
    return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

But to my surprise, the "Recovered from err: " never occurs in my log file, instead, it occurs in /var/log/messages.

How can I log that error in my original log file?

[Updated]

If there is no panic, glog.Errorf will log correctly to its log dir; when there is panic, it just can't:

// this glog will log correctly, unless uncomment the panic below
glog.Errorf("This is a normal log: %v", err)
// panic("TISH IS A PANIC")

Maybe this is impossible, since that's what crash means?


问:
Plyer notification click event - Tkinter Python
Not finding a way to use a system tray for my python script, I've found an easy work around with plyer, having the wanted effect with the following code :

```<code>from plyer import notification
notif = notification.notify(
            title='Setting system tray',
            message='Double click to show',
            app_name='To do list',
            app_icon='icone.ico',
            timeout=999999
        )
</code>```

I've put timeout to 999999 for a 11days long system tray which I think is a good solution for my cheap trick.
However, I wanted to be able to add events linked to clicks with that icon. Is there a way to link mouse events to a plyer notification icon ?

答: I don't think it is possible to that with plyer now, I have glanced through the source code and i dont see any implementation as such.</p>

Body:
Not finding a way to use a system tray for my python script, I've found an easy work around with plyer, having the wanted effect with the following code :

from plyer import notification
notif = notification.notify(
            title='Setting system tray',
            message='Double click to show',
            app_name='To do list',
            app_icon='icone.ico',
            timeout=999999
        )

I've put timeout to 999999 for a 11days long system tray which I think is a good solution for my cheap trick.
However, I wanted to be able to add events linked to clicks with that icon. Is there a way to link mouse events to a plyer notification icon ?