问:
How to know the if remainder of a division is 0 in SQL
Hello I am trying to know iF a year iS a leap-year, because i only want leap years to be inserted on the table olympics, but an error keeps coming up.

This is my attempt in SQL:

```<code>ALTER TABLE OLYMPICS
ADD CONSTRAINT LEAP_YEAR
CHECK((YEAR%4)=0);
</code>```

And this is the error:

00000 -  "invalid character"
*Cause:    identifiers may not start with any ASCII character other than
       letters and numbers.  $#_ are also allowed after the first
       character.  Identifiers enclosed by doublequotes may contain
       any character other than a doublequote.  Alternative quotes
       (q'#...#') cannot use spaces, tabs, or carriage returns as
       delimiters.  For all other contexts, consult the SQL Language
       Reference Manual.

答:
In mysql you could do something like this

```<code>  DAYOFYEAR(CONCAT(YEARVARIABLE,'-12-31'))
</code>```

And then determine if it is 366 or 365 days

```<code>  Select DAYOFYEAR(CONCAT(2016,'-12-31'))
  Result = 366  (yes leap year)

  Select DAYOFYEAR(CONCAT(2015,'-12-31'))
  Result = 365 (no leap year)
</code>```

The devided by 4 does not work, because not every year devided by 4 is a leap year

Body:
Hello I am trying to know iF a year iS a leap-year, because i only want leap years to be inserted on the table olympics, but an error keeps coming up.

This is my attempt in SQL:

ALTER TABLE OLYMPICS
ADD CONSTRAINT LEAP_YEAR
CHECK((YEAR%4)=0);

And this is the error:

00000 -  "invalid character"
*Cause:    identifiers may not start with any ASCII character other than
       letters and numbers.  $#_ are also allowed after the first
       character.  Identifiers enclosed by doublequotes may contain
       any character other than a doublequote.  Alternative quotes
       (q'#...#') cannot use spaces, tabs, or carriage returns as
       delimiters.  For all other contexts, consult the SQL Language
       Reference Manual.

Body:
In mysql you could do something like this

  DAYOFYEAR(CONCAT(YEARVARIABLE,'-12-31'))

And then determine if it is 366 or 365 days

  Select DAYOFYEAR(CONCAT(2016,'-12-31'))
  Result = 366  (yes leap year)

  Select DAYOFYEAR(CONCAT(2015,'-12-31'))
  Result = 365 (no leap year)

The devided by 4 does not work, because not every year devided by 4 is a leap year


来源: stackexchange

问:
Firebase Invites for React Native
We are currently using Firestack on a React Native project which is great, however we also need the features available via Firebase's "Invites" capability.

Is anyone aware of a React Native module (eg on github) for Firebase Invites, iOS and Android ?

Or alternatively - is there another service/API that can provide similar app invite management for mobile (ideally w/ React Native support but we can always bridge if needed) ?

Many thanks.

答:
Firebase invites is based on Firebase dynamic links: Firebase Invites

React-Native-Firebase is a great open source library to use Firebase with react native. React-Native-Firebase

The library supports Dynamic Links so with a little work you can use it to enable the Firebase Invites feature.

React-Native-Firebase (Dynamic Links)

ContentLicense: CC BY-SA 3.0

Title: Firebase Invites for React Native


问:
Mutating a Vue prop (Vue2 + Laravel)
I have the following setup on my project:

```<code>window.school = {
    "id": 1,
    "users": [
        {
            "id": 0,
            "name": "Adam Carter",
            "work": "Unilogic",
            "email": "adam.carter@unilogic.com",
            "dob": "1978",
            "address": "83 Warner Street",
            "city": "Boston",
            "optedin": true
        },
        {
            "id": 1,
            "name": "Leanne Brier",
            "work": "Connic",
            "email": "leanne.brier@connic.org",
            "dob": "13/05/1987",
            "address": "9 Coleman Avenue",
            "city": "Toronto",
            "optedin": false
        }
    ],
    "images": [
        "img0.png",
        "img1.png",
        "img2.png"
    ],
    "coordinates": {
        "x": 35.12,
        "y": -21.49
    },
    "price": "$59,395"
}
const app = new Vue({
    router,
    el: '#app',
    data: {
        school: school,
    }
});
</code>```

And one of my vue components is as School.vue

```<code><template>
    <div>
        <input type="button" value="Update school data" v-on:click="update()">
    </div>
</template>

<script>
    export default {
        props:[
            'school',
        ],
        methods: {
            update: function() {
                let url = `/api/v1/school/${this.school.id}/update`;
                this.axios.get(url, this.decisions)
                  .then((res) => {
                      // WARNING IS THROWN IN HERE
                      this.school = res.data.school;
                  })
                  .catch((error) => {
                      console.log(error);
                  });
            }
        },
    }
</script>
</code>```

But I get the following warning: warning: Avoid mutating a prop directly

So the question is, how can I update the app "school" information from a Vue Component? I'm not very familiar with Vue and I don't know if I'm following an antipattern or something else, thanks a lot for your help.

答:
In parent-child relation the data flows only from parent to child through props. So, you can't directly change parent data from child. You must just emit particular event for which you let the parent listen.

In parent context where you using component School, use it with additional directive:

```<code><div id="app">
  <school v-on:update="updateSchool"></school>
</div>
</code>```

Add particular method to parent:

```<code>const app = new Vue({
  router,
  el: '#app',
  data: {
    school: school,
  },
  methods: {
    updateSchool (data) {
      this.school = data
    }
  }
})
</code>```

And edit School.vue script:

```<code><script>
  export default {
    props:[
      'school',
    ],
    methods: {
      update: function() {
        let url = `/api/v1/school/${this.school.id}/update`;
        this.axios.get(url, this.decisions)
          .then((res) => {
            this.$emit('update', res.data.school);
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
  }
</script>
</code>```

Title: Mutating a Vue prop (Vue2 + Laravel)

Body:
I have the following setup on my project:

window.school = {
    "id": 1,
    "users": [
        {
            "id": 0,
            "name": "Adam Carter",
            "work": "Unilogic",
            "email": "adam.carter@unilogic.com",
            "dob": "1978",
            "address": "83 Warner Street",
            "city": "Boston",
            "optedin": true
        },
        {
            "id": 1,
            "name": "Leanne Brier",
            "work": "Connic",
            "email": "leanne.brier@connic.org",
            "dob": "13/05/1987",
            "address": "9 Coleman Avenue",
            "city": "Toronto",
            "optedin": false
        }
    ],
    "images": [
        "img0.png",
        "img1.png",
        "img2.png"
    ],
    "coordinates": {
        "x": 35.12,
        "y": -21.49
    },
    "price": "$59,395"
}
const app = new Vue({
    router,
    el: '#app',
    data: {
        school: school,
    }
});

And one of my vue components is as School.vue

<template>

        <input type="button" value="Update school data" v-on:click="update()">

</template>

But I get the following warning: warning: Avoid mutating a prop directly

So the question is, how can I update the app "school" information from a Vue Component? I'm not very familiar with Vue and I don't know if I'm following an antipattern or something else, thanks a lot for your help.

Body:
In parent-child relation the data flows only from parent to child through props. So, you can't directly change parent data from child. You must just emit particular event for which you let the parent listen.

In parent context where you using component School, use it with additional directive:

<div id="app">
  <school v-on:update="updateSchool"></school>
</div>

Add particular method to parent:

const app = new Vue({
  router,
  el: '#app',
  data: {
    school: school,
  },
  methods: {
    updateSchool (data) {
      this.school = data
    }
  }
})

And edit School.vue script:

<script>
  export default {
    props:[
      'school',
    ],
    methods: {
      update: function() {
        let url = `/api/v1/school/${this.school.id}/update`;
        this.axios.get(url, this.decisions)
          .then((res) => {
            this.$emit('update', res.data.school);
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
  }
</script>


问:
Downloding a video after payment has been received
I have a web page that I would like to add a new feature.
customers will pay in order to download some video files.

Video files will be stored in amazon S3 (will be about 150GB per year). When a user pays through paypal for example, then a mail will be sent with an amazon s3 url link for the user to download.

but then he/she could pass this video link to other users who haven't paid but can access amazon s3 since the file is public. If the video was in my server I know how I could check if the user has paid, and server the file.

But now that it will be on an external server how could this be done?

How site delivering paid contact avoid this thing?

thanks

答: Well, you have to log, if an user have downloaded the complete file. You have to write some kind of servercode, what will measure, if all the content habe been delivered. Or you can make some kind of key, which is only valid for 24h. After that time it becomes invalid. </p>

ContentLicense: CC BY-SA 2.5


问:
Initialize Vue app after Firebase auth state changed

I have a bit of a conundrum in my Vue/vuex/vue-router + Firebase app. The bootstrap code is supposed to initialize Firebase, as well as the signed in user (if any) in Vuex:

new Vue({
  el: '#app', router, store, template: '<App/>', components: { App },
  beforeCreate() {
    firebase.initializeApp(firebaseConfig)
      // Because the code below is async, the app gets created before user is returned...
      .auth().onAuthStateChanged(user => {
        this.$store.commit('syncAuthUser', user) // this executes too late...
      })
  }
})
```

<p>In my routes, I have </p>

<pre class="lang-js prettyprint-override"><code>{ path: '/home', name: 'Home', component: Home, meta: { requiresAuth: true } }
</code>```

as well as

router.beforeEach((to, from, next) => {
  let authUser = store.getters.authUser // this is not set just yet...

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!authUser) {
      next('signin') // /home will always hit here...
    }
    next()
  }
  else {
    next()
  }
})
```

Problem

As mentioned in the comments, the app gets the authenticated user too late. So, when you go to /home while logged in, the app will run the beforeEachcheck in the routes... And the user instance will not be available just yet, so it will think that you are not logged in, when in fact you are (it's clear from my computed properties that are properly updated a few moments later).

Question

So, how do I change my code, so that the Vue app gets initialized only after Firebase returns the user and after that user is passed to the Vuex store? Plese let me know if I am doing something completely wrong.

Attempts

I tried the "unsubscribe" approach; however, its problem is that the onAuthStateChanged would only be triggered once. So, if I put my crucial this.$store.commit('syncAuthUser', user) there, then that code would only execute when the app is created, and not when the user logs out for example.

I also tried a better approach here. I did work for me, but I felt bad wrapping onAuthStateChanged in another Promise, for sure there must be a better way; plus, it seems wrong to place the auth user initialization login in the routes file.

答:
EXAMPLE

./App.vue

```<code>created: function() {
  auth.onAuthStateChanged(user => {

    this.$store.dispatch("SET_USER", user)

    user.getIdToken().then( token => {
      this.$store.dispatch("SET_TOKEN", token)
    })
}
</code>```

./store.js (mutations)

```<code>export default {
  SET_USER(state, user) {
    state.authenticated = !!user
    state.user = {
      email: user ? user.email : null,
      displayName: user ? user.displayName : null,
      photoURL: user ? user.photoURL : null,
    }
  }
  SET_TOKEN(state, payload) {
    state.token = payload
  }
}
</code>```

OVERVIEW

LifeCycle

This example works using Vue's created: lifecycle hook. Within created: we use auth.onAuthStateChanged to spin up an event listener. Your app is now listening for auth changes from firebase.

```<code>auth.onAuthStateChanged(user => { ...listening for user objects... })
</code>```

The user object is returned whenever Firebase notices an auth state change. Use its properties and methods for authentication and authorization.

Property: user.emailVerfied

Method: user.getIdToken()

TL;DR

When using Firebase onAuthStateChanged, you must implement Observable and Subscriptions objects. An RxJS Observable is asynchronous like a promise, and it will help you wait for the auth response from Firebase.

See the first argument, nextOrObserver from the documentation:

```<code>onAuthStateChanged(nextOrObserver, error, completed) returns function()
</code>```

The Observable design pattern, (i.e., asynchronous, push, multicast) is documented here.

Body:
I have a bit of a conundrum in my Vue/vuex/vue-router + Firebase app. The bootstrap code is supposed to initialize Firebase, as well as the signed in user (if any) in Vuex:

new Vue({
  el: '#app', router, store, template: '<App/>', components: { App },
  beforeCreate() {
    firebase.initializeApp(firebaseConfig)
      // Because the code below is async, the app gets created before user is returned...
      .auth().onAuthStateChanged(user => {
        this.$store.commit('syncAuthUser', user) // this executes too late...
      })
  }
})

In my routes, I have

{ path: '/home', name: 'Home', component: Home, meta: { requiresAuth: true } }

as well as

router.beforeEach((to, from, next) => {
  let authUser = store.getters.authUser // this is not set just yet...

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!authUser) {
      next('signin') // /home will always hit here...
    }
    next()
  }
  else {
    next()
  }
})

Problem

As mentioned in the comments, the app gets the authenticated user too late. So, when you go to /home while logged in, the app will run the beforeEachcheck in the routes... And the user instance will not be available just yet, so it will think that you are not logged in, when in fact you are (it's clear from my computed properties that are properly updated a few moments later).

Question

So, how do I change my code, so that the Vue app gets initialized only after Firebase returns the user and after that user is passed to the Vuex store? Plese let me know if I am doing something completely wrong.

Attempts

I tried the "unsubscribe" approach; however, its problem is that the onAuthStateChanged would only be triggered once. So, if I put my crucial this.$store.commit('syncAuthUser', user) there, then that code would only execute when the app is created, and not when the user logs out for example.

I also tried a better approach here. I did work for me, but I felt bad wrapping onAuthStateChanged in another Promise, for sure there must be a better way; plus, it seems wrong to place the auth user initialization login in the routes file.

Body:
EXAMPLE

./App.vue

created: function() {
  auth.onAuthStateChanged(user => {

    this.$store.dispatch("SET_USER", user)

    user.getIdToken().then( token => {
      this.$store.dispatch("SET_TOKEN", token)
    })
}

./store.js (mutations)

export default {
  SET_USER(state, user) {
    state.authenticated = !!user
    state.user = {
      email: user ? user.email : null,
      displayName: user ? user.displayName : null,
      photoURL: user ? user.photoURL : null,
    }
  }
  SET_TOKEN(state, payload) {
    state.token = payload
  }
}

OVERVIEW

LifeCycle

This example works using Vue's created: lifecycle hook. Within created: we use auth.onAuthStateChanged to spin up an event listener. Your app is now listening for auth changes from firebase.

auth.onAuthStateChanged(user => { ...listening for user objects... })

The user object is returned whenever Firebase notices an auth state change. Use its properties and methods for authentication and authorization.

Property: user.emailVerfied

Method: user.getIdToken()

TL;DR

When using Firebase onAuthStateChanged, you must implement Observable and Subscriptions objects. An RxJS Observable is asynchronous like a promise, and it will help you wait for the auth response from Firebase.

See the first argument, nextOrObserver from the documentation:

onAuthStateChanged(nextOrObserver, error, completed) returns function()

The Observable design pattern, (i.e., asynchronous, push, multicast) is documented here.


问:
How to position 3 buttons in StackLayout equal width
Anyone know how to position 3 buttons in StackLayout with equal width?  I have it working with Grid with

```<code><Grid x:Name="MyGrid" Grid.Row="0" BindingContext="{x:Reference Name=Button1}"  HeightRequest="{Binding Width}">
</code>```

I would like to find a way to show 3 buttons on same line  with same width equally without a Grid
For example all 3 buttons of equal length fitting across horizontally in StackLayout

[   Button 1   ]  [   Button 222   ]  [   Button 333333   ]

答:
Still using Grid, just specify width of columns in percent (col spacing set for fun):

```<code>    <Grid
     ColumnDefinitions="33.33*, 33.33*, 33.33*"
     ColumnSpacing="8"
     HorizontalOptions="FillAndExpand">
        <Button Text="1" Grid.Column="0" HorizontalOptions="FillAndExpand"/>
        <Button Text="2" Grid.Column="1" HorizontalOptions="FillAndExpand"/>
        <Button Text="3" Grid.Column="2" HorizontalOptions="FillAndExpand"/>
     </Grid>
</code>```

Updated: use one-line ColumnDefinitions property in Xamarin.Forms 4.8

ContentLicense: CC BY-SA 4.0

Body:
Anyone know how to position 3 buttons in StackLayout with equal width?  I have it working with Grid with

<Grid x:Name="MyGrid" Grid.Row="0" BindingContext="{x:Reference Name=Button1}"  HeightRequest="{Binding Width}">

I would like to find a way to show 3 buttons on same line  with same width equally without a Grid
For example all 3 buttons of equal length fitting across horizontally in StackLayout

[   Button 1   ]  [   Button 222   ]  [   Button 333333   ]

Body:
Still using Grid, just specify width of columns in percent (col spacing set for fun):

    <Grid
     ColumnDefinitions="33.33*, 33.33*, 33.33*"
     ColumnSpacing="8"
     HorizontalOptions="FillAndExpand">
        <Button Text="1" Grid.Column="0" HorizontalOptions="FillAndExpand"/>
        <Button Text="2" Grid.Column="1" HorizontalOptions="FillAndExpand"/>
        <Button Text="3" Grid.Column="2" HorizontalOptions="FillAndExpand"/>
     </Grid>

Updated: use one-line ColumnDefinitions property in Xamarin.Forms 4.8


问:
Wordpress multisite disable all default widgets on site creation
I'm unable to find how to disable the default widgets on site creation. By this I mean when I create a site within a Wordpress multisite network, it does not create the sidebar widgets such as "meta" automatically.

I see plugins that haven't been updated in two plus years that may help me with this, but I don't want to download anything that old.

Does anyone know how to do this?

答:
The default widgets are created by a call to update_option() in wp_install_defaults() in wp-admin/includes/upgrade.php.

After wp_install_defaults() has been called by wpmu_create_blog() in wp-includes/ms-functions.php, the action wpmu_new_blog is fired.

You can, therefore, hook into wpmu_new_blog and remove the default widgets by calling update_option() again, this time with an empty array for sidebar-1.

```<code>add_action('wpmu_new_blog', function($blog_id){
    switch_to_blog($blog_id);
    update_option('sidebars_widgets',
        ['wp_inactive_widgets' => [], 'sidebar-1' => [], 'sidebar-2' => [],
         'sidebar-3' => [], 'array_version' => 3]);
    restore_current_blog();
});
</code>```

Body:
The default widgets are created by a call to update_option() in wp_install_defaults() in wp-admin/includes/upgrade.php.

After wp_install_defaults() has been called by wpmu_create_blog() in wp-includes/ms-functions.php, the action wpmu_new_blog is fired.

You can, therefore, hook into wpmu_new_blog and remove the default widgets by calling update_option() again, this time with an empty array for sidebar-1.

add_action('wpmu_new_blog', function($blog_id){
    switch_to_blog($blog_id);
    update_option('sidebars_widgets',
        ['wp_inactive_widgets' => [], 'sidebar-1' => [], 'sidebar-2' => [],
         'sidebar-3' => [], 'array_version' => 3]);
    restore_current_blog();
});


问:
STM32F3 Discovery board ADC DMA transfer not working
I'm using the STM32F303 (Discovery board) and trying to trigger an ADC conversion externally from a timer signal TRGO2 and store it to a buffer through DMA.  However, it doesn't appear that anything is being written to that buffer.  Could someone please look through my initialization code and let me know if I'm messing something up during the initialization?  I know that the timer triggering works because I am able to read the ADC values when I enable the ADC interrupt.

```<code>void InitADC(void)
{
     int i;
     ADC_InitTypeDef       ADC_InitStructure;
     ADC_CommonInitTypeDef ADC_CommonInitStructure;
     GPIO_InitTypeDef    GPIO_InitStructure;
     NVIC_InitTypeDef    NVIC_InitStructure;
     DMA_InitTypeDef         DMA_InitStructure;

     RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);

     DMA_DeInit(DMA1_Channel1);

     DMA_InitStructure.DMA_BufferSize = 2;
     DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
     DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
     DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)adcBuffer;
     DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
     DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
     DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
     DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&ADC2->DR;
     DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
     DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
     DMA_InitStructure.DMA_Priority = DMA_Priority_High;
     DMA_Init(DMA1_Channel1, &DMA_InitStructure);

     DMA_Cmd(DMA1_Channel1, ENABLE);

     /* Configure the ADC clock */
     RCC_ADCCLKConfig(RCC_ADC12PLLCLK_Div2);

     /* Enable ADC12 clock */
     RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ADC12, ENABLE);

     ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
     ADC_CommonInitStructure.ADC_Clock = ADC_Clock_SynClkModeDiv1;
     ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_1;
     ADC_CommonInitStructure.ADC_DMAMode = ADC_DMAMode_OneShot;
     ADC_CommonInitStructure.ADC_TwoSamplingDelay = 0;

     ADC_CommonInit(ADC2, &ADC_CommonInitStructure);

     /* GPIOA Periph clock enable */
     RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

     /* Configure ADC2 Channel1 as analog input */
     GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
     GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
     GPIO_Init(GPIOA, &GPIO_InitStructure);

     ADC_StructInit(&ADC_InitStructure);

     /* Calibration procedure */
     ADC_VoltageRegulatorCmd(ADC2, ENABLE);
     for(i = 0; i < 1000; i++) {}

     ADC_SelectCalibrationMode(ADC2, ADC_CalibrationMode_Single);
     ADC_StartCalibration(ADC2);

     while(ADC_GetCalibrationStatus(ADC2) != RESET );

     ADC_InitStructure.ADC_ContinuousConvMode = ADC_ContinuousConvMode_Disable;
     ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
     ADC_InitStructure.ADC_ExternalTrigConvEvent = ADC_ExternalTrigConvEvent_10;
     ADC_InitStructure.ADC_ExternalTrigEventEdge = ADC_ExternalTrigEventEdge_RisingEdge;
     ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
     ADC_InitStructure.ADC_OverrunMode = ADC_OverrunMode_Disable;
     ADC_InitStructure.ADC_AutoInjMode = ADC_AutoInjec_Disable;
     ADC_InitStructure.ADC_NbrOfRegChannel = 2;
     ADC_Init(ADC2, &ADC_InitStructure);

     /* ADC2 regular channel1 configuration */
     ADC_RegularChannelConfig(ADC2, ADC_Channel_1, 1, ADC_SampleTime_7Cycles5);
     ADC_RegularChannelConfig(ADC2, ADC_Channel_2, 2, ADC_SampleTime_7Cycles5);

     /* Configure and enable DMA interrupt */
     NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel1_IRQn;
     NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
     NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
     NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
     NVIC_Init(&NVIC_InitStructure);

     /* Enable interrupt */
     7DMA_ITConfig(DMA1_Channel1, DMA1_IT_TC1, ENABLE);

     /* Configures the ADC DMA */
     ADC_DMAConfig(ADC2, ADC_DMAMode_Circular);
     /* Enable the ADC DMA */
     ADC_DMACmd(ADC2, ENABLE);

     /* Enable ADC2 */
     ADC_Cmd(ADC2, ENABLE);
     ADC_DMACmd(ADC2, ENABLE);

     /* wait for ADRDY */
     while(!ADC_GetFlagStatus(ADC2, ADC_FLAG_RDY));

     /* Start ADC2 Software Conversion */
     ADC_StartConversion(ADC2);
}

void DMA1_Channel1_IRQHandler(void)
{
     if (DMA_GetFlagStatus(DMA1_FLAG_TC1) != RESET)
     {
         DMA_ClearITPendingBit(DMA1_FLAG_TC1);
         adcBuffer[0] = (adcBuffer[0] * ADC_VREF) >> 12;
         adcBuffer[1] = (adcBuffer[1] * ADC_VREF) >> 12;
     }
}
</code>```

Here's the relevant ADC and DMA register content:

ADC2 CR: 0x10000005

ADC2 CFGR: 0x00000683

DMA1_CH1 CCR: 0x000025A3

DMA1_CH1 CNDTR: 0x00000002

DMA1_CH1 CPAR: 0x50000140

DMA1_CH1 CMAR: 0x2000001C

答:
I appear to have solved the issue. Looking further in the datasheet I realized that ADC2 was not connected to DMA1 channel 1:

The correct DMA connection to ADC2 is DMA2 Channel 1:

Body:
I'm using the STM32F303 (Discovery board) and trying to trigger an ADC conversion externally from a timer signal TRGO2 and store it to a buffer through DMA.  However, it doesn't appear that anything is being written to that buffer.  Could someone please look through my initialization code and let me know if I'm messing something up during the initialization?  I know that the timer triggering works because I am able to read the ADC values when I enable the ADC interrupt.

void InitADC(void)
{
     int i;
     ADC_InitTypeDef       ADC_InitStructure;
     ADC_CommonInitTypeDef ADC_CommonInitStructure;
     GPIO_InitTypeDef    GPIO_InitStructure;
     NVIC_InitTypeDef    NVIC_InitStructure;
     DMA_InitTypeDef         DMA_InitStructure;

     RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);

     DMA_DeInit(DMA1_Channel1);

     DMA_InitStructure.DMA_BufferSize = 2;
     DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
     DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
     DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)adcBuffer;
     DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
     DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
     DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
     DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&ADC2->DR;
     DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
     DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
     DMA_InitStructure.DMA_Priority = DMA_Priority_High;
     DMA_Init(DMA1_Channel1, &DMA_InitStructure);

     DMA_Cmd(DMA1_Channel1, ENABLE);

     /* Configure the ADC clock */
     RCC_ADCCLKConfig(RCC_ADC12PLLCLK_Div2);

     /* Enable ADC12 clock */
     RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ADC12, ENABLE);

     ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
     ADC_CommonInitStructure.ADC_Clock = ADC_Clock_SynClkModeDiv1;
     ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_1;
     ADC_CommonInitStructure.ADC_DMAMode = ADC_DMAMode_OneShot;
     ADC_CommonInitStructure.ADC_TwoSamplingDelay = 0;

     ADC_CommonInit(ADC2, &ADC_CommonInitStructure);

     /* GPIOA Periph clock enable */
     RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

     /* Configure ADC2 Channel1 as analog input */
     GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
     GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
     GPIO_Init(GPIOA, &GPIO_InitStructure);

     ADC_StructInit(&ADC_InitStructure);

     /* Calibration procedure */
     ADC_VoltageRegulatorCmd(ADC2, ENABLE);
     for(i = 0; i < 1000; i++) {}

     ADC_SelectCalibrationMode(ADC2, ADC_CalibrationMode_Single);
     ADC_StartCalibration(ADC2);

     while(ADC_GetCalibrationStatus(ADC2) != RESET );

     ADC_InitStructure.ADC_ContinuousConvMode = ADC_ContinuousConvMode_Disable;
     ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
     ADC_InitStructure.ADC_ExternalTrigConvEvent = ADC_ExternalTrigConvEvent_10;
     ADC_InitStructure.ADC_ExternalTrigEventEdge = ADC_ExternalTrigEventEdge_RisingEdge;
     ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
     ADC_InitStructure.ADC_OverrunMode = ADC_OverrunMode_Disable;
     ADC_InitStructure.ADC_AutoInjMode = ADC_AutoInjec_Disable;
     ADC_InitStructure.ADC_NbrOfRegChannel = 2;
     ADC_Init(ADC2, &ADC_InitStructure);

     /* ADC2 regular channel1 configuration */
     ADC_RegularChannelConfig(ADC2, ADC_Channel_1, 1, ADC_SampleTime_7Cycles5);
     ADC_RegularChannelConfig(ADC2, ADC_Channel_2, 2, ADC_SampleTime_7Cycles5);

     /* Configure and enable DMA interrupt */
     NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel1_IRQn;
     NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
     NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
     NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
     NVIC_Init(&NVIC_InitStructure);

     /* Enable interrupt */
     7DMA_ITConfig(DMA1_Channel1, DMA1_IT_TC1, ENABLE);

     /* Configures the ADC DMA */
     ADC_DMAConfig(ADC2, ADC_DMAMode_Circular);
     /* Enable the ADC DMA */
     ADC_DMACmd(ADC2, ENABLE);

     /* Enable ADC2 */
     ADC_Cmd(ADC2, ENABLE);
     ADC_DMACmd(ADC2, ENABLE);

     /* wait for ADRDY */
     while(!ADC_GetFlagStatus(ADC2, ADC_FLAG_RDY));

     /* Start ADC2 Software Conversion */
     ADC_StartConversion(ADC2);
}

void DMA1_Channel1_IRQHandler(void)
{
     if (DMA_GetFlagStatus(DMA1_FLAG_TC1) != RESET)
     {
         DMA_ClearITPendingBit(DMA1_FLAG_TC1);
         adcBuffer[0] = (adcBuffer[0] * ADC_VREF) >> 12;
         adcBuffer[1] = (adcBuffer[1] * ADC_VREF) >> 12;
     }
}

Here's the relevant ADC and DMA register content:

ADC2 CR: 0x10000005

ADC2 CFGR: 0x00000683

DMA1_CH1 CCR: 0x000025A3

DMA1_CH1 CNDTR: 0x00000002

DMA1_CH1 CPAR: 0x50000140

DMA1_CH1 CMAR: 0x2000001C


问:
ModelState.Isvalid not work for default value of boolean field
WEB API --->

```<code>public async Task<IHttpActionResult> CreatePost(ChildClient c)
{

if(!ModelState.IsValid)  {
throw ...
}
..

}
 public class Client
    {
        [Required]
        public bool HasBaseValue { get; set; } = true;
        [Required]
        public string Name { get; set; } = "stringvalue";
    }
    public class ChildClient : Client
    {
        [Required]
        public bool HasFieldValue { get; set; } = true;
        [Required]
        public string Name1 { get; set; } = "stringvalue";
    }
</code>```

ModelState.Keys gives following errors: HasBaseValue,HasFieldValue if both fields are not supplied.
why it still shows in error field even though default value is set.
NOTE: default values are already populated in 'c object' when I debug and check by breakpoint.

答: Achieve by skipping those fields from ModelState.IsValid to validate. As those default values fields are not posted so, ModelState.IsValid considering as invalid.(because, default value populate from API but ModelState.IsValid only validate posted value).</p>

Body:
WEB API --->

public async Task<IHttpActionResult> CreatePost(ChildClient c)
{

if(!ModelState.IsValid)  {
throw ...
}
..

}
 public class Client
    {
        [Required]
        public bool HasBaseValue { get; set; } = true;
        [Required]
        public string Name { get; set; } = "stringvalue";
    }
    public class ChildClient : Client
    {
        [Required]
        public bool HasFieldValue { get; set; } = true;
        [Required]
        public string Name1 { get; set; } = "stringvalue";
    }

ModelState.Keys gives following errors: HasBaseValue,HasFieldValue if both fields are not supplied.
why it still shows in error field even though default value is set.
NOTE: default values are already populated in 'c object' when I debug and check by breakpoint.


问:
Haskell Couldn't match type ‘String -> [Int]’ with ‘[a0]’
I want to create a program counting occurrence of all elements in a list and return max sequence. I have a problem with my input part.

The input consists of several test cases. Each test case starts with a line containing two integers n and q (1 ≤ n, q ≤ 100000). The next line contains n integers a1 , ... , an (-100000 ≤ ai ≤ 100000

I want readNQ to get n and q as [int] then pass to readArray that will read n element and assign to [int] as following

```<code>module Main where

import Text.Printf
import Data.List

main :: IO()
main = interact (showResults . maxSeqLength . readArray. readNQ)

readNQ :: String -> [Int]
readNQ =  take 2 . (map read) . words

readArray :: [Int] -> String -> [Int]
readArray (n:xs) = take n . (map read) . words

showResults ::  Int -> String
showResults x = printf "\n %d" x

maxSeqLength :: Eq a => [a] -> Int
maxSeqLength [] = 0
maxSeqLength xs = (maximum . map length . group) xs
</code>```

However, there is an error.

frequent.hs:13:47: error:

```<code>• Couldn't match type ‘String -> [Int]’ with ‘[a0]’
  Expected type: String -> [a0]
    Actual type: String -> String -> [Int]
• Probable cause: ‘(.)’ is applied to too few arguments
  In the second argument of ‘(.)’, namely ‘readArray . readNQ’
  In the second argument of ‘(.)’, namely
    ‘maxSeqLength . readArray . readNQ’
  In the first argument of ‘interact’, namely
    ‘(showResults . maxSeqLength . readArray . readNQ)’
</code>```

what is wrong with the type of readNQ and readArray?

答:
```<code>readArray :: [Int] -> String -> [Int]
</code>```

This takes a [Int] and returns a function String -> [Int]

```<code>maxSeqLength :: Eq a => [a] -> Int
</code>```

This accepts a list [a] and returns an Int.

Since a function String -> [Int] is not a list [a], you can't compose them using (.).

Error aside, also note that

```<code>readNQ =  take 2 . (map read) . words
</code>```

reads the first two ints from the input, and discard the rest. It's gone. The next function in your function chain (... . fun . readNQ) can not access what was thrown away from the first function.

You need to rework your readNQ so that it returns a pair ([n1,n2], restOfTheInput) if you want the next function to use it.

Probably, the code will become too complex to be expressed in pointfree style, but that's OK. Further, interact quickly starts being unusable for large tasks.

Body:
I want to create a program counting occurrence of all elements in a list and return max sequence. I have a problem with my input part.

The input consists of several test cases. Each test case starts with a line containing two integers n and q (1 ≤ n, q ≤ 100000). The next line contains n integers a1 , ... , an (-100000 ≤ ai ≤ 100000

I want readNQ to get n and q as [int] then pass to readArray that will read n element and assign to [int] as following

module Main where

import Text.Printf
import Data.List

main :: IO()
main = interact (showResults . maxSeqLength . readArray. readNQ)

readNQ :: String -> [Int]
readNQ =  take 2 . (map read) . words

readArray :: [Int] -> String -> [Int]
readArray (n:xs) = take n . (map read) . words

showResults ::  Int -> String
showResults x = printf "\n %d" x

maxSeqLength :: Eq a => [a] -> Int
maxSeqLength [] = 0
maxSeqLength xs = (maximum . map length . group) xs

However, there is an error.

frequent.hs:13:47: error:

• Couldn't match type ‘String -> [Int]’ with ‘[a0]’
  Expected type: String -> [a0]
    Actual type: String -> String -> [Int]
• Probable cause: ‘(.)’ is applied to too few arguments
  In the second argument of ‘(.)’, namely ‘readArray . readNQ’
  In the second argument of ‘(.)’, namely
    ‘maxSeqLength . readArray . readNQ’
  In the first argument of ‘interact’, namely
    ‘(showResults . maxSeqLength . readArray . readNQ)’

what is wrong with the type of readNQ and readArray?

Body:
readArray :: [Int] -> String -> [Int]

This takes a [Int] and returns a function String -> [Int]

maxSeqLength :: Eq a => [a] -> Int

This accepts a list [a] and returns an Int.

Since a function String -> [Int] is not a list [a], you can't compose them using (.).

Error aside, also note that

readNQ =  take 2 . (map read) . words

reads the first two ints from the input, and discard the rest. It's gone. The next function in your function chain (... . fun . readNQ) can not access what was thrown away from the first function.

You need to rework your readNQ so that it returns a pair ([n1,n2], restOfTheInput) if you want the next function to use it.

Probably, the code will become too complex to be expressed in pointfree style, but that's OK. Further, interact quickly starts being unusable for large tasks.


答:
That's because you have a type error in the function readArray :: [Int] -> String -> [Int] , it should have the type readArray :: [Int] -> String if you want that this expression works:

```<code>(showResults . maxSeqLength . readArray . readNQ)
</code>```

Title: Haskell Couldn't match type ‘String -> [Int]’ with ‘[a0]’

Body:
That's because you have a type error in the function readArray :: [Int] -> String -> [Int] , it should have the type readArray :: [Int] -> String if you want that this expression works:

(showResults . maxSeqLength . readArray . readNQ)


问:
How to run Node.js as a background process and never die?
I connect to the linux server via putty SSH. I tried to run it as a background process like this:

```<code>$ node server.js &
</code>```

However, after 2.5 hrs the terminal becomes inactive and the process dies.  Is there anyway I can keep the process alive even with the terminal disconnected?

Edit 1

Actually, I tried nohup, but as soon as I close the Putty SSH terminal or unplug my internet, the server process stops right away.

Is there anything I have to do in Putty?

Edit 2 (on Feb, 2012)

There is a node.js module, forever. It will run node.js server as daemon service.

答: Apart from cool solutions above I'd mention also about supervisord and monit tools which allow to start process, monitor its presence and start it if it died. With 'monit' you can also run some active checks like check if process responds for http request</p>

Body:
I connect to the linux server via putty SSH. I tried to run it as a background process like this:

$ node server.js &

However, after 2.5 hrs the terminal becomes inactive and the process dies.  Is there anyway I can keep the process alive even with the terminal disconnected?

Edit 1

Actually, I tried nohup, but as soon as I close the Putty SSH terminal or unplug my internet, the server process stops right away.

Is there anything I have to do in Putty?

Edit 2 (on Feb, 2012)

There is a node.js module, forever. It will run node.js server as daemon service.


问:
Porting C++ to C# - templates
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

```<code>template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
</code>```

Clearly for this example I could do:

```<code>public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}
</code>```

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.

答:
Unfortunately .Net generics can only accept types.  C++ Templates take other values that are considered constant expressions by the compiler, because they are effectively just macros that expand to more code.

This means that your idea of turning the code into a method call is the best bet.  You could make the method call return a type with a .Value Property (following your example) thus keeping the ported code similar to the template:

```<code>return Factorial(N-1).Value;
</code>```

Title: Porting C++ to C# - templates

Body:
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Clearly for this example I could do:

public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.

Body:
Unfortunately .Net generics can only accept types.  C++ Templates take other values that are considered constant expressions by the compiler, because they are effectively just macros that expand to more code.

This means that your idea of turning the code into a method call is the best bet.  You could make the method call return a type with a .Value Property (following your example) thus keeping the ported code similar to the template:

return Factorial(N-1).Value;


问:
Pasting selected cells within a loop statement to a new worksheet
I'm looking to have a loop run through a list and if any cells in Column E contain a "Y", copy the data in that row and paste it to the next empty row on the next worksheet.

```<code>Private Sub CommandButton1_Click()

Dim Rec As Object
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

Set copySheet = Worksheets("Estimate")
Set pasteSheet = Worksheets("ACV & Supplement")
Set Rec = Range("E:E")

For Each cell In Rec
    If cell.Value = "Y" Then
        cell.Activate
        Range("B" & ActiveCell.Row & ":H" & ActiveCell.Row).Copy
        pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    End If
Next

End Sub
</code>```

Everything works the way I expect until the pasteSheet.Cells..... line.

答:
Instead of a loop (which can be very resource hungry) consider using an autofilter:</p>

```<code>Dim copySheet As Worksheet: Set copySheet = Worksheets("Estimate")
Dim pasteSheet As Worksheet: Set pasteSheet = Worksheets("ACV & Supplement")

'Filter the sheet by Column E. Showing only rows where E has a "Y" value
copySheet.Range("E1:E99999").AutoFilter Field:=1, Criteria1:="Y", VisibleDropDown:=False

'Copy the worksheet
copySheet.Cells.SpecialCells(xlCellTypeVisible).Copy

'Paste the values
pasteSheet.Range("A1").PasteSpecial xlPasteValues

'Undo the filtering
copySheet.AutoFilterMode = False

'Get rid of the marching ants
Application.CutCopyMode = False
</code>```

Body:
I'm looking to have a loop run through a list and if any cells in Column E contain a "Y", copy the data in that row and paste it to the next empty row on the next worksheet.

Private Sub CommandButton1_Click()

Dim Rec As Object
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

Set copySheet = Worksheets("Estimate")
Set pasteSheet = Worksheets("ACV & Supplement")
Set Rec = Range("E:E")

For Each cell In Rec
    If cell.Value = "Y" Then
        cell.Activate
        Range("B" & ActiveCell.Row & ":H" & ActiveCell.Row).Copy
        pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    End If
Next

End Sub

Everything works the way I expect until the pasteSheet.Cells..... line.

Body:
Instead of a loop (which can be very resource hungry) consider using an autofilter:

Dim copySheet As Worksheet: Set copySheet = Worksheets("Estimate")
Dim pasteSheet As Worksheet: Set pasteSheet = Worksheets("ACV & Supplement")

'Filter the sheet by Column E. Showing only rows where E has a "Y" value
copySheet.Range("E1:E99999").AutoFilter Field:=1, Criteria1:="Y", VisibleDropDown:=False

'Copy the worksheet
copySheet.Cells.SpecialCells(xlCellTypeVisible).Copy

'Paste the values
pasteSheet.Range("A1").PasteSpecial xlPasteValues

'Undo the filtering
copySheet.AutoFilterMode = False

'Get rid of the marching ants
Application.CutCopyMode = False


问:
Is it possible to detect if Android codec is hardware or software?
As of title, I can programmatically get a lot of data about MediaCodecInfo in my Android app, but I cannot find a way to detect if a given codec is a hardware or software codec.

I usually assume that codec name like OMX.google.* are software codecs, but how can I be sure if a codec is an hardware one?

EDIT To give more context to the question, I am trying to analyze all the codecs supported by a mobile device.

答:
Andrea did you try to pass the accessory method  getCodecInfo()?

there is the official documentation that explains how to use it


问:
Spring storing data in session
Maybe it is obvious, but I am not 100% sure that I'm correct and I need confirmation.

Let's assume I want to store some data in session(using Spring Framework).
I understand that there are two different approaches and I want to know that I know the difference between them.

Creating a field in class annotated by @Component

I understand that class annotated by @Component is by default singleton. It means that it is created once per container. So it is shared between users/sessions, right?

Creating a field in class annotated @Component and scope set to session

Data is "remembered" only per one session.

答:
I understand that class annotated by @Component is by default singleton. It means that it is created once per container. So it is shared between users/sessions, right?

Yes, singleton in scope of application.

Creating a field in class annotated @Component and scope set to session - Data is "remembered" only per one session.

Depends on what you mean by that. But in general @SessionScope beans are created for every user session, and are singletos  in scope of that session, not application like in default scope. They are discarded once session is invalidated.

In order to keep something during session, use @SessionScope

I understand that there are two different approaches and I want to know that I know the difference between them.

I belive that scopes should be self explainatory to you by now:)

Title: Spring storing data in session


问:
How to generate a random convex polygon?
I'm trying to devise a method for generating random 2D convex polygons. It has to have the following properties:

coordinates should be integers;

the polygon should lie inside a square with corners (0, 0) and (C, C), where C is given;

the polygon should have number of vertices close to a given number N.

For example, generate random polygons that have 10 vertices and lie inside square [0..100]x[0..100].

What makes this task hard, is the fact that the coordinates should be integers.

The approach I tried was to generate random set of points in the given square and compute the convex hull of these points. But the resultant convex hull is very little vertices compared to N.

Any ideas?

答:
Here is the fastest algorithm I know that generates each convex polygon with equal probability. The output has exactly N vertices, and the running time is O(N log N), so it can generate even large polygons very quickly.

Generate two lists, X and Y, of N random integers between 0 and C. Make sure there are no duplicates.

Sort X and Y and store their maximum and minimum elements.

Randomly divide the other (not max or min) elements into two groups: X1 and X2, and Y1 and Y2.

Re-insert the minimum and maximum elements at the start and end of these lists (minX at the start of X1 and X2, maxX at the end, etc.).

Find the consecutive differences (X1[i + 1] - X1[i]), reversing the order for the second group (X2[i] - X2[i + 1]). Store these in lists XVec and YVec.

Randomize (shuffle) YVec and treat each pair XVec[i] and YVec[i] as a 2D vector.

Sort these vectors by angle and then lay them end-to-end to form a polygon.

Move the polygon to the original min and max coordinates.

An animation and Java implementation is available here: Generating Random Convex Polygons.

This algorithm is based on a paper by Pavel Valtr: “Probability that n random points are in convex position.” Discrete & Computational Geometry 13.1 (1995): 637-643.


问:
VBA - destroy a modeless UserForm instance properly
Intro:

I am aware that - showing UserForms - it's best practice to

handle QueryClose within the userform code (If CloseMode = vbFormControlMenu ...)

doing no Unload Me therein, just a timid Me.Hide instruction
(after preventing [x]-itting and eventual self-destruction via Cancel = True )

setting a related variable/[property] within the [class] code (e.g. .IsCancelled=True)

in order to be able to have the UF unloaded by the calling code.

Useful link

An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/
as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).

Further selection (►edit as of 5/1 2019)

Disadvantages in putting code into userforms instead of modules

Passing variable from form to module

Apply logic for userform dialog (Rubberduck)

The perfect userform (Vitosh academy)

1) Working examples for modal UserForms

As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:

Case 1a) .. with a local variable for the UF instance, as often seen:

```<code>Public Sub ShowFormA
  Dim ufA As UserForm1
  Set ufA = New UserForm1
' show userform
  ufA.Show          ' equivalent to: ufA.Show vbModal

' handle data after user okay
  If Not ufA.IsCancelled Then
      '  do something ...
  End If

' >> object reference destroyed expressly (as seen in some examples)
  unload ufA
End Sub
</code>```

Case 1b) .. without a local variable, but using a With New codeblock:

```<code>' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
'    as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
  With New UserForm1
      .Show         ' equivalent to: ufA.Show vbModal

    ' handle data after user okay
      If Not .IsCancelled Then
      '  do something ...
      End If
  End With
</code>```

2) Problem

Problems arise using a MODELESS UserForm instance.

Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:

```<code>  With New UserForm1
      .Show vbModeless  ' << show modeless uf
  End With
</code>```

If I try, however to

a) get information about a possible user cancelling as well as

b) to Unload a form if baptized using a local variable (e.g. "ufA") after the Show instruction,

all code lines will be executed at once for precisely the reason that the form is MODELESS:

code shows the form, the next moment ..

code finds no user cancelling, as there was no time for any user action, the next moment ..

[code unloads the form if using a local variable for the userform]

3) Question

How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?

答:
Indeed, I've been focusing quite a lot on modal forms - because that's what's most commonly used. Thanks for the feedback on that article!

The principles are the same for non-modal forms though: simply expand on the Model-View-Presenter pattern roughly outlined in the linked article and here.

The difference is that a non-modal form needs a paradigm shift: you're no longer responding to a preset sequence of events - rather, you need to respond to some asynchronous events that may happen at any given time, or not.

When handling a modal form, there's a "before showing" and then an "after hiding" that runs immediately after the form is hidden. You can handle anything that happens "while showing" using events.

When handling a non-modal form, there's a "before showing", and then "while showing" and "after showing" both need to be handled through events.

Make your presenter class module responsible for holding the UserForm instance, at module-level and WithEvents:

```<code>Option Explicit
Private WithEvents myModelessForm As UserForm1
</code>```

The presenter's Show method will Set the form instance and display it:

```<code>Public Sub Show()
    'If Not myModelessForm Is Nothing Then
    '    myModelessForm.Visible = True 'just to ensure visibility & honor the .Show call
    '    Exit Sub
    'End If
    Set myModelessForm = New UserForm1
    '...
    myModelessForm.Show vbModeless
End Sub
</code>```

You don't want the form instance to be local to the procedure here, so a local variable or a With block can't work: the object will be out of scope before you mean it to. That's why you store the instance in a private field, at module level: now the form lives as long as the presenter instance does.

Now, you need to make the form "talk" to the presenter - the easiest way is to expose events in the UserForm1 code-behind - for example if we want the user to confirm cancellation, we'll add a ByRef parameter to the event, so the handler in the presenter can pass the information back to the event source (i.e. back to the form code):

```<code>Option Explicit
'...private fields, model, etc...
Public Event FormConfirmed()
Public Event FormCancelled(ByRef Cancel as Boolean)

'returns True if cancellation was cancelled by handler
Private Function OnCancel() As Boolean
    Dim cancelCancellation As Boolean
    RaiseEvent FormCancelled(cancelCancellation)
    If Not cancelCancellation Then Me.Hide
    OnCancel = cancelCancellation
End Function

Private Sub CancelButton_Click()
    OnCancel
End Sub

Private Sub OkButton_Click()
    Me.Hide
    RaiseEvent FormConfirmed
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = Not OnCancel
    End If
End Sub
</code>```

Now the presenter can handle that FormCancelled event:

```<code>Private Sub myModelessForm_FormCancelled(ByRef Cancel As Boolean)
    'setting Cancel to True will leave the form open
    Cancel = MsgBox("Cancel this operation?", vbYesNo + vbExclamation) = vbNo
    If Not Cancel Then
        ' modeless form was cancelled and is now hidden.
        ' ...
        Set myModelessForm = Nothing
    End If
End Sub

Private Sub myModelessForm_FormConfirmed()
    'form was okayed and is now hidden.
    '...
    Set myModelessForm = Nothing
End Sub
</code>```

A non-modal form wouldn't typically have "ok" and "cancel" buttons though. Rather, you'd have a number of functionalities exposed, for example one that brings up some modal dialog UserForm2 that does something else - again, you just expose an event for it, and handle it in the presenter:

```<code>Public Event ShowGizmo()

Private Sub ShowGizmoButton_Click()
    RaiseEvent ShowGizmo
End Sub
</code>```

And the presenter goes:

```<code>Private Sub myModelessForm_ShowGizmo()
    With New GizmoPresenter
        .Show
    End With
End Sub
</code>```

Note that the modal UserForm2 is a concern of a separate presenter class.

Body:
Intro:

I am aware that - showing UserForms - it's best practice to

handle QueryClose within the userform code (If CloseMode = vbFormControlMenu ...)

doing no Unload Me therein, just a timid Me.Hide instruction
(after preventing [x]-itting and eventual self-destruction via Cancel = True )

setting a related variable/[property] within the [class] code (e.g. .IsCancelled=True)

in order to be able to have the UF unloaded by the calling code.

Useful link

An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/
as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).

Further selection (►edit as of 5/1 2019)

Disadvantages in putting code into userforms instead of modules

Passing variable from form to module

Apply logic for userform dialog (Rubberduck)

The perfect userform (Vitosh academy)

1) Working examples for modal UserForms

As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:

Case 1a) .. with a local variable for the UF instance, as often seen:

Public Sub ShowFormA
  Dim ufA As UserForm1
  Set ufA = New UserForm1
' show userform
  ufA.Show          ' equivalent to: ufA.Show vbModal

' handle data after user okay
  If Not ufA.IsCancelled Then
      '  do something ...
  End If

' >> object reference destroyed expressly (as seen in some examples)
  unload ufA
End Sub

Case 1b) .. without a local variable, but using a With New codeblock:

' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
'    as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
  With New UserForm1
      .Show         ' equivalent to: ufA.Show vbModal

    ' handle data after user okay
      If Not .IsCancelled Then
      '  do something ...
      End If
  End With

2) Problem

Problems arise using a MODELESS UserForm instance.

Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:

  With New UserForm1
      .Show vbModeless  ' << show modeless uf
  End With

If I try, however to

a) get information about a possible user cancelling as well as

b) to Unload a form if baptized using a local variable (e.g. "ufA") after the Show instruction,

all code lines will be executed at once for precisely the reason that the form is MODELESS:

code shows the form, the next moment ..

code finds no user cancelling, as there was no time for any user action, the next moment ..

[code unloads the form if using a local variable for the userform]

3) Question

How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?

Body:
Indeed, I've been focusing quite a lot on modal forms - because that's what's most commonly used. Thanks for the feedback on that article!

The principles are the same for non-modal forms though: simply expand on the Model-View-Presenter pattern roughly outlined in the linked article and here.

The difference is that a non-modal form needs a paradigm shift: you're no longer responding to a preset sequence of events - rather, you need to respond to some asynchronous events that may happen at any given time, or not.

When handling a modal form, there's a "before showing" and then an "after hiding" that runs immediately after the form is hidden. You can handle anything that happens "while showing" using events.

When handling a non-modal form, there's a "before showing", and then "while showing" and "after showing" both need to be handled through events.

Make your presenter class module responsible for holding the UserForm instance, at module-level and WithEvents:

Option Explicit
Private WithEvents myModelessForm As UserForm1

The presenter's Show method will Set the form instance and display it:

Public Sub Show()
    'If Not myModelessForm Is Nothing Then
    '    myModelessForm.Visible = True 'just to ensure visibility & honor the .Show call
    '    Exit Sub
    'End If
    Set myModelessForm = New UserForm1
    '...
    myModelessForm.Show vbModeless
End Sub

You don't want the form instance to be local to the procedure here, so a local variable or a With block can't work: the object will be out of scope before you mean it to. That's why you store the instance in a private field, at module level: now the form lives as long as the presenter instance does.

Now, you need to make the form "talk" to the presenter - the easiest way is to expose events in the UserForm1 code-behind - for example if we want the user to confirm cancellation, we'll add a ByRef parameter to the event, so the handler in the presenter can pass the information back to the event source (i.e. back to the form code):

Option Explicit
'...private fields, model, etc...
Public Event FormConfirmed()
Public Event FormCancelled(ByRef Cancel as Boolean)

'returns True if cancellation was cancelled by handler
Private Function OnCancel() As Boolean
    Dim cancelCancellation As Boolean
    RaiseEvent FormCancelled(cancelCancellation)
    If Not cancelCancellation Then Me.Hide
    OnCancel = cancelCancellation
End Function

Private Sub CancelButton_Click()
    OnCancel
End Sub

Private Sub OkButton_Click()
    Me.Hide
    RaiseEvent FormConfirmed
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = Not OnCancel
    End If
End Sub

Now the presenter can handle that FormCancelled event:

Private Sub myModelessForm_FormCancelled(ByRef Cancel As Boolean)
    'setting Cancel to True will leave the form open
    Cancel = MsgBox("Cancel this operation?", vbYesNo + vbExclamation) = vbNo
    If Not Cancel Then
        ' modeless form was cancelled and is now hidden.
        ' ...
        Set myModelessForm = Nothing
    End If
End Sub

Private Sub myModelessForm_FormConfirmed()
    'form was okayed and is now hidden.
    '...
    Set myModelessForm = Nothing
End Sub

A non-modal form wouldn't typically have "ok" and "cancel" buttons though. Rather, you'd have a number of functionalities exposed, for example one that brings up some modal dialog UserForm2 that does something else - again, you just expose an event for it, and handle it in the presenter:

Public Event ShowGizmo()

Private Sub ShowGizmoButton_Click()
    RaiseEvent ShowGizmo
End Sub

And the presenter goes:

Private Sub myModelessForm_ShowGizmo()
    With New GizmoPresenter
        .Show
    End With
End Sub

Note that the modal UserForm2 is a concern of a separate presenter class.


问:
Firebase Performance of Hashmap versus TreeMap
In my Android app, I am using Firebase Database to store the data. There are some values that I want to store in the Firebase Database as a Map<String, Integer>.

When retrieving my data for display on the Android UI, I mostly need data  "sorted by key".

My question is from a performance viewpoint whether I should declare the Map as a Hashmap or a Treemap? For e.g. like

```<code>Map<String, Integer> myData = new Hashmap<>();
</code>```

or

```<code>Map<String, Integer> myData = new Treemap<>();
</code>```

Of the above 2 options, which would give me a better performance for retrieval of data. Each Map size is expected to be in range of 0 to 10,000 entries. And there could be anywhere between 5-11 such Maps in my database for each user.

My question is specifically to target understanding performance of Firebase and not a general question about the difference between 2 map types.

答:
Both classes, Hashmap and Treemap implement the Map interface. Both classes offer mostly the same functionality but the most important difference between this classes is the order in which iteration through the entries will happen.

HashMap offers no guarantees about the iteration order and it can also change completely when new elements are added/deleted. Lookup-array structure, based on hashCode(), equals() implementations, O(1) runtime complexity for inserting and searching, unsorted.

TreeMap will iterate according to the natural ordering of the containing keys according to their compareTo() method. This can also be accomplished with an external Comparator. It also implements the SortedMap interface. Tree structure, based on compareTo() implementation, O(log(N)) runtime complexity for inserting and searching, sorted.

Use a HashMap unless you have some need for ordering. HashMap is faster!. But as you said that you mostly need your data "sorted by key", just use the TreeMap.

Body:
In my Android app, I am using Firebase Database to store the data. There are some values that I want to store in the Firebase Database as a Map<String, Integer>.

When retrieving my data for display on the Android UI, I mostly need data  "sorted by key".

My question is from a performance viewpoint whether I should declare the Map as a Hashmap or a Treemap? For e.g. like

Map<String, Integer> myData = new Hashmap<>();

or

Map<String, Integer> myData = new Treemap<>();

Of the above 2 options, which would give me a better performance for retrieval of data. Each Map size is expected to be in range of 0 to 10,000 entries. And there could be anywhere between 5-11 such Maps in my database for each user.

My question is specifically to target understanding performance of Firebase and not a general question about the difference between 2 map types.


问:
Can't seem to load the AngularJS CDN?
So I'm following a Udemy tutorial to learn AngularJS (1) this is what I have for my HTML file:

```<code><!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
    <head>
        <title>Learn and Understand AngularJS</title>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <meta charset="UTF-8">

        <!-- load bootstrap and fontawesome via CDN -->
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
        <!-- load angular via CDN -->
        <script src="//code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
        <script src="app.js"></script>
    </head>
    <body>
    <div class="container">
        <div ng-controller="mainController">
           <h1>Hello world!</h1>
        </div>
    </div>
</html>
</code>```

and my app.js file:

```<code>var myApp = angular.module('myApp', []);

myApp.controller('mainController', function($scope) {
    console.log($scope);
});
</code>```

I'm trying to console $scope but I'm getting the following error:

GET file:///Users/carlosgrijalva/Code/Angular/Code-The-Scope->Service/Starter/code.angularjs.org/1.3.0-rc.1/angular.min.js >net::ERR_FILE_NOT_FOUND

The cdn link seems to be working fine on my browser and this is basically the template provided by the tutorial. I can't really figure out what it's not working. Anyone have any ideas?

答:
Try updating your script tag to be:

```<code><script src="https://code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
</code>```

If you provide just forwardslashes javascript will start looking through your own filepath.

Title: Can't seem to load the AngularJS CDN?

Body:
So I'm following a Udemy tutorial to learn AngularJS (1) this is what I have for my HTML file:

<!DOCTYPE html>

        <title>Learn and Understand AngularJS</title>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <meta charset="UTF-8">

        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />

Hello world!

and my app.js file:

var myApp = angular.module('myApp', []);

myApp.controller('mainController', function($scope) {
    console.log($scope);
});

I'm trying to console $scope but I'm getting the following error:

GET file:///Users/carlosgrijalva/Code/Angular/Code-The-Scope->Service/Starter/code.angularjs.org/1.3.0-rc.1/angular.min.js >net::ERR_FILE_NOT_FOUND

The cdn link seems to be working fine on my browser and this is basically the template provided by the tutorial. I can't really figure out what it's not working. Anyone have any ideas?

Body:
Try updating your script tag to be:

<script src="https://code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>

If you provide just forwardslashes javascript will start looking through your own filepath.


问:
Fill an array with random numbers
I need to create an array using a constructor, add a method to print the array as a sequence and a method to fill the array with random numbers of the type double.

Here's what I've done so far:

```<code>import java.util.Random;

public class NumberList {
    private static double[] anArray;

    public static double[] list() {
        return new double[10];
    }

    public static void print(){
        System.out.println(String.join(" ", anArray);
    }

    public static double randomFill() {
        return (new Random()).nextInt();
    }

    public static void main(String args[]) {
        // TODO
    }
}
</code>```

I'm struggling to figure out how to fill the array with the random numbers I have generated in the randomFill method. Thanks!

答:
This will give you an array with 50 random numbers and display the smallest number in the array. I did it for an assignment in my programming class.

```<code>public static void main(String args[]) {
    // TODO Auto-generated method stub

    int i;
    int[] array = new int[50];
    for(i = 0; i <  array.length; i++) {
        array[i] = (int)(Math.random() * 100);
        System.out.print(array[i] + "  ");

        int smallest = array[0];

        for (i=1; i<array.length; i++)
        {
        if (array[i]<smallest)
        smallest = array[i];
        }

    }

}
</code>```

}`

Title: Fill an array with random numbers

Body:
I need to create an array using a constructor, add a method to print the array as a sequence and a method to fill the array with random numbers of the type double.

Here's what I've done so far:

import java.util.Random;

public class NumberList {
    private static double[] anArray;

    public static double[] list() {
        return new double[10];
    }

    public static void print(){
        System.out.println(String.join(" ", anArray);
    }

    public static double randomFill() {
        return (new Random()).nextInt();
    }

    public static void main(String args[]) {
        // TODO
    }
}

I'm struggling to figure out how to fill the array with the random numbers I have generated in the randomFill method. Thanks!

Body:
This will give you an array with 50 random numbers and display the smallest number in the array. I did it for an assignment in my programming class.

public static void main(String args[]) {
    // TODO Auto-generated method stub

    int i;
    int[] array = new int[50];
    for(i = 0; i <  array.length; i++) {
        array[i] = (int)(Math.random() * 100);
        System.out.print(array[i] + "  ");

        int smallest = array[0];

        for (i=1; i<array.length; i++)
        {
        if (array[i]<smallest)
        smallest = array[i];
        }

    }

}

}`


问:
What is the best way of testing private methods with GoogleTest?
I would like to test some private methods using GoogleTest.

class Foo
{
private:
    int bar(...)
}
```

<p>GoogleTest allows a couple of ways of doing this.</p>

<p><strong>OPTION 1</strong></p>

<p>With <em>FRIEND_TEST</em>:</p>

<pre class="lang-c++ prettyprint-override"><code>class Foo
{
private:
    FRIEND_TEST(Foo, barReturnsZero);
    int bar(...);
}

TEST(Foo, barReturnsZero)
{
    Foo foo;
    EXPECT_EQ(foo.bar(...), 0);
}
</code>```

This implies to include "gtest/gtest.h" in the production source file.

OPTION 2

Declare a test fixture as a friend to the class and define accessors in the fixture:

class Foo
{
    friend class FooTest;
private:
    int bar(...);
}

class FooTest : public ::testing::Test
{
protected:
    int bar(...) { foo.bar(...); }
private:
    Foo foo;
}

TEST_F(FooTest, barReturnsZero)
{
    EXPECT_EQ(bar(...), 0);
}
```

OPTION 3

The Pimpl idiom.

For details: Google Test: Advanced guide.

Are there any other ways to test private methods? What are some pros and cons of each option?

答:
There are at least two more options. I'll list out some other options you should consider by explaining a certain situation.

Option 4:

Consider refactoring your code so that the part you want to test is public in another class. Typically when you're tempted to test a class's private method, it's a sign of bad design. One of the most common (anti)paterns that I see is what Michael Feathers calls an "Iceberg" class. "Iceberg" classes have one public method, and the rest are private (which is why it's tempting to test the private methods). It might look something like this:

For example, you might want to test GetNextToken() by calling it on a string successively and seeing that it returns the expected result. A function like this does warrant a test: that behavior isn't trivial, especially if your tokenizing rules are complex. Let's pretend it's not all that complex, and we just want to rope in tokens delimited by space. So you write a test, maybe it looks something like this:

```<code>TEST(RuleEvaluator, canParseSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    RuleEvaluator re = RuleEvaluator(input_string);
    EXPECT_EQ(re.GetNextToken(), "1");
    EXPECT_EQ(re.GetNextToken(), "2");
    EXPECT_EQ(re.GetNextToken(), "test");
    EXPECT_EQ(re.GetNextToken(), "bar");
    EXPECT_EQ(re.HasMoreTokens(), false);
}
</code>```

Well, that actually looks pretty nice. We'd want to make sure we maintain this behavior as we make changes. But GetNextToken() is a private function! So we can't test it like this, because it wont even compile. But what about changing the RuleEvaluator class to follow the Single Responsibility Principle (Single Responsibility Principle)? For instance, we seem to have a parser, tokenizer, and evaluator jammed into one class. Wouldn't it be better to just separate those responsibilities? On top of that, if you create a Tokenizer class, then it's public methods would be HasMoreTokens() and GetNextTokens(). The RuleEvaluator class could have a Tokenizer object as a member. Now, we can keep the same test as above, except we are testing the Tokenizer class instead of the RuleEvaluator class.

Here's what it might look like in UML:

Note that this new design increases modularity, so you could potentially re-use these classes in other parts of your system (before you couldn't, private methods aren't reusable by definition). This is main advantage of breaking the RuleEvaluator down, along with increased understandability/locality.

The test would look extremely similar, except it would actually compile this time since the GetNextToken() method is now public on the Tokenizer class:

```<code>TEST(Tokenizer, canParseSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    Tokenizer tokenizer = Tokenizer(input_string);
    EXPECT_EQ(tokenizer.GetNextToken(), "1");
    EXPECT_EQ(tokenizer.GetNextToken(), "2");
    EXPECT_EQ(tokenizer.GetNextToken(), "test");
    EXPECT_EQ(tokenizer.GetNextToken(), "bar");
    EXPECT_EQ(tokenizer.HasMoreTokens(), false);
}
</code>```

Option 5

Just don't test the private functions. Sometimes they aren't worth testing because they will be tested through the public interface. A lot of times what I see is tests that look very similar, but test two different functions/methods. What ends up happening is that when requirements change (and they always do), you now have 2 broken tests instead of 1. And if you really tested all your private methods, you might have more like 10 broken tests instead of 1. In short, testing private functions (by using FRIEND_TEST or making them public) that could otherwise be tested through a public interface cause test duplication. You really don't want this, because nothing hurts more than your test suite slowing you down. It's supposed to decrease development time and decrease maintenance costs! If you test private methods that are otherwise tested through a public interface, the test suite may very well do the opposite, and actively increase maintenance costs and increase development time. When you make a private function public, or if you use something like FRIEND_TEST, you'll usually end up regretting it.

Consider the following possible implementation of the Tokenizer class:

Let's say that SplitUpByDelimiter() is responsible for returning a std::vector<std::string> such that each element in the vector is a token. Furthermore, let's just say that GetNextToken() is simply an iterator over this vector. So your tests might look this:

```<code>TEST(Tokenizer, canParseSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    Tokenizer tokenizer = Tokenizer(input_string);
    EXPECT_EQ(tokenizer.GetNextToken(), "1");
    EXPECT_EQ(tokenizer.GetNextToken(), "2");
    EXPECT_EQ(tokenizer.GetNextToken(), "test");
    EXPECT_EQ(tokenizer.GetNextToken(), "bar");
    EXPECT_EQ(tokenizer.HasMoreTokens(), false);
}

// Pretend we have some class for a FRIEND_TEST
TEST_F(TokenizerTest, canGenerateSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    Tokenizer tokenizer = Tokenizer(input_string);
    std::vector<std::string> result = tokenizer.SplitUpByDelimiter(" ");
    EXPECT_EQ(result.size(), 4);
    EXPECT_EQ(result[0], "1");
    EXPECT_EQ(result[1], "2");
    EXPECT_EQ(result[2], "test");
    EXPECT_EQ(result[3], "bar");
}
</code>```

Well, now let's say the requirements change, and you're now expected to parse by a "," instead of a space. Naturally, you're going to expect one test to break, but the pain increases when you test private functions. IMO, google test should not allow FRIEND_TEST. It is almost never what you want to do. Michael Feathers refers to things like FRIEND_TEST as a "groping tool", since it's trying to touch someone else's private parts.

I recommend avoiding option 1 and 2 when you can, as it typically causes "test duplication", and as a consequence, many more tests than necessary will break when requirements change. Use them as a last resort. Option 1 and 2 are the fastest ways to "test private methods" for here and now (as in the fastest to implement), but they'll really hurt productivity in the long run.

PIMPL can make sense too, but it still allows for some pretty bad design. Be careful with it.

I'd recommend Option 4 (refactoring into smaller testable components) as the right place to start, but sometimes what you really want is Option 5 (testing the private functions through the public interface).

P.S. Here's the relevant lecture about iceberg classes: https://www.youtube.com/watch?v=4cVZvoFGJTU

P.S.S. As for everything in software, the answer is it depends. There is no one size fits all. The option that solves your problem will depend on your specific circumstances.

Body:
I would like to test some private methods using GoogleTest.

class Foo
{
private:
    int bar(...)
}

GoogleTest allows a couple of ways of doing this.

OPTION 1

With FRIEND_TEST:

class Foo
{
private:
    FRIEND_TEST(Foo, barReturnsZero);
    int bar(...);
}

TEST(Foo, barReturnsZero)
{
    Foo foo;
    EXPECT_EQ(foo.bar(...), 0);
}

This implies to include "gtest/gtest.h" in the production source file.

OPTION 2

Declare a test fixture as a friend to the class and define accessors in the fixture:

class Foo
{
    friend class FooTest;
private:
    int bar(...);
}

class FooTest : public ::testing::Test
{
protected:
    int bar(...) { foo.bar(...); }
private:
    Foo foo;
}

TEST_F(FooTest, barReturnsZero)
{
    EXPECT_EQ(bar(...), 0);
}

OPTION 3

The Pimpl idiom.

For details: Google Test: Advanced guide.

Are there any other ways to test private methods? What are some pros and cons of each option?

Body:
There are at least two more options. I'll list out some other options you should consider by explaining a certain situation.

Option 4:

Consider refactoring your code so that the part you want to test is public in another class. Typically when you're tempted to test a class's private method, it's a sign of bad design. One of the most common (anti)paterns that I see is what Michael Feathers calls an "Iceberg" class. "Iceberg" classes have one public method, and the rest are private (which is why it's tempting to test the private methods). It might look something like this:

For example, you might want to test GetNextToken() by calling it on a string successively and seeing that it returns the expected result. A function like this does warrant a test: that behavior isn't trivial, especially if your tokenizing rules are complex. Let's pretend it's not all that complex, and we just want to rope in tokens delimited by space. So you write a test, maybe it looks something like this:

TEST(RuleEvaluator, canParseSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    RuleEvaluator re = RuleEvaluator(input_string);
    EXPECT_EQ(re.GetNextToken(), "1");
    EXPECT_EQ(re.GetNextToken(), "2");
    EXPECT_EQ(re.GetNextToken(), "test");
    EXPECT_EQ(re.GetNextToken(), "bar");
    EXPECT_EQ(re.HasMoreTokens(), false);
}

Well, that actually looks pretty nice. We'd want to make sure we maintain this behavior as we make changes. But GetNextToken() is a private function! So we can't test it like this, because it wont even compile. But what about changing the RuleEvaluator class to follow the Single Responsibility Principle (Single Responsibility Principle)? For instance, we seem to have a parser, tokenizer, and evaluator jammed into one class. Wouldn't it be better to just separate those responsibilities? On top of that, if you create a Tokenizer class, then it's public methods would be HasMoreTokens() and GetNextTokens(). The RuleEvaluator class could have a Tokenizer object as a member. Now, we can keep the same test as above, except we are testing the Tokenizer class instead of the RuleEvaluator class.

Here's what it might look like in UML:

Note that this new design increases modularity, so you could potentially re-use these classes in other parts of your system (before you couldn't, private methods aren't reusable by definition). This is main advantage of breaking the RuleEvaluator down, along with increased understandability/locality.

The test would look extremely similar, except it would actually compile this time since the GetNextToken() method is now public on the Tokenizer class:

TEST(Tokenizer, canParseSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    Tokenizer tokenizer = Tokenizer(input_string);
    EXPECT_EQ(tokenizer.GetNextToken(), "1");
    EXPECT_EQ(tokenizer.GetNextToken(), "2");
    EXPECT_EQ(tokenizer.GetNextToken(), "test");
    EXPECT_EQ(tokenizer.GetNextToken(), "bar");
    EXPECT_EQ(tokenizer.HasMoreTokens(), false);
}

Option 5

Just don't test the private functions. Sometimes they aren't worth testing because they will be tested through the public interface. A lot of times what I see is tests that look very similar, but test two different functions/methods. What ends up happening is that when requirements change (and they always do), you now have 2 broken tests instead of 1. And if you really tested all your private methods, you might have more like 10 broken tests instead of 1. In short, testing private functions (by using FRIEND_TEST or making them public) that could otherwise be tested through a public interface cause test duplication. You really don't want this, because nothing hurts more than your test suite slowing you down. It's supposed to decrease development time and decrease maintenance costs! If you test private methods that are otherwise tested through a public interface, the test suite may very well do the opposite, and actively increase maintenance costs and increase development time. When you make a private function public, or if you use something like FRIEND_TEST, you'll usually end up regretting it.

Consider the following possible implementation of the Tokenizer class:

Let's say that SplitUpByDelimiter() is responsible for returning a std::vector<std::string> such that each element in the vector is a token. Furthermore, let's just say that GetNextToken() is simply an iterator over this vector. So your tests might look this:

TEST(Tokenizer, canParseSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    Tokenizer tokenizer = Tokenizer(input_string);
    EXPECT_EQ(tokenizer.GetNextToken(), "1");
    EXPECT_EQ(tokenizer.GetNextToken(), "2");
    EXPECT_EQ(tokenizer.GetNextToken(), "test");
    EXPECT_EQ(tokenizer.GetNextToken(), "bar");
    EXPECT_EQ(tokenizer.HasMoreTokens(), false);
}

// Pretend we have some class for a FRIEND_TEST
TEST_F(TokenizerTest, canGenerateSpaceDelimtedTokens)
{
    std::string input_string = "1 2 test bar";
    Tokenizer tokenizer = Tokenizer(input_string);
    std::vector<std::string> result = tokenizer.SplitUpByDelimiter(" ");
    EXPECT_EQ(result.size(), 4);
    EXPECT_EQ(result[0], "1");
    EXPECT_EQ(result[1], "2");
    EXPECT_EQ(result[2], "test");
    EXPECT_EQ(result[3], "bar");
}

Well, now let's say the requirements change, and you're now expected to parse by a "," instead of a space. Naturally, you're going to expect one test to break, but the pain increases when you test private functions. IMO, google test should not allow FRIEND_TEST. It is almost never what you want to do. Michael Feathers refers to things like FRIEND_TEST as a "groping tool", since it's trying to touch someone else's private parts.

I recommend avoiding option 1 and 2 when you can, as it typically causes "test duplication", and as a consequence, many more tests than necessary will break when requirements change. Use them as a last resort. Option 1 and 2 are the fastest ways to "test private methods" for here and now (as in the fastest to implement), but they'll really hurt productivity in the long run.

PIMPL can make sense too, but it still allows for some pretty bad design. Be careful with it.

I'd recommend Option 4 (refactoring into smaller testable components) as the right place to start, but sometimes what you really want is Option 5 (testing the private functions through the public interface).

P.S. Here's the relevant lecture about iceberg classes: https://www.youtube.com/watch?v=4cVZvoFGJTU

P.S.S. As for everything in software, the answer is it depends. There is no one size fits all. The option that solves your problem will depend on your specific circumstances.


问:
Compute data from an array with VueJS
I want to compute data from my json with vueJS

The data are like this

json from my api

```<code>[
    {
        "id": 4,
        "votes": 0
    },
    {
        "id": 3,
        "votes": 1
    },
]
</code>```

To fetch and render this data I am using this vueJS file

app.js

```<code>const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});
</code>```

Now I want to create a vue variable to display the total of votes in my index.html

index.html

```<code><div v-for="result in results">
    <p>Votes {{ result.votes }}.</p>
    <p>Id : {{ result.id }}</p>
</div>
<div>
    <p>Total of votes : {{ resultsVotes }}</p>
</div>
</code>```

答:
You can just reduce the sum of votes in the then function

```<code>axios.get("http://example.com/votes.json")
    .then(response => {
         this.results = response.data;
         this.resultsVotes = this.results.reduce((sum, curr) => sum + curr.votes, 0);
    });
</code>```

Title: Compute data from an array with VueJS

Body:
I want to compute data from my json with vueJS

The data are like this

json from my api

[
    {
        "id": 4,
        "votes": 0
    },
    {
        "id": 3,
        "votes": 1
    },
]

To fetch and render this data I am using this vueJS file

app.js

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});

Now I want to create a vue variable to display the total of votes in my index.html

index.html

Votes {{ result.votes }}.

Id : {{ result.id }}

Total of votes : {{ resultsVotes }}

Body:
You can just reduce the sum of votes in the then function

axios.get("http://example.com/votes.json")
    .then(response => {
         this.results = response.data;
         this.resultsVotes = this.results.reduce((sum, curr) => sum + curr.votes, 0);
    });


问:
Query to update data in MYSQL database, search in table 1 , update in table 2, how?
I am trying to figure out how to quickly change some stuff in a large wordpress database, doing through the GUI takes forever, i think executing this direclty on the database would be much more efficient as it's a one time thing.

I have the follow tables involved:

```<code>wp_posts
--------
ID
post_status

wp_termrelationships
--------------------
object_id
term_taxonomy_id
</code>```

I need to execute a mysql query that looks for term_taxonomy_id '8232' in the table wp_termrelationships , if there's a match for term_taxonomy_id '8232' then take the object_id for that match and use that data to search table wp_posts column ID for a match. When matches are found in table wp_posts column ID update the post_status for each post to 'publish'

No changes is made to anything except the post_status in the table wp_posts.

To me this query is very complex, any ideas?

答:
Lets deconstruct your requirement, and build the queries:

I need to execute a mysql query that looks for term_taxonomy_id '8232' in the table wp_termrelationships

```<code>SELECT object_id
FROM wp_termrelationships
WHERE term_taxonomy_id = 8232
</code>```

if there's a match for term_taxonomy_id '8232' then take the object_id for that match and use that to search table wp_posts column ID for the data gotten from the match in the object_id

Here I use a sub-query:

```<code>SELECT *
FROM wp_posts
WHERE ID IN (SELECT object_id
             FROM wp_termrelationships
             WHERE term_taxonomy_id = 8232)
</code>```

when those matches are found update the post_status for each matched post in table wp_posts to 'publish'

```<code>UPDATE wp_posts
SET post_status = 'publish'
WHERE ID IN (SELECT object_id
             FROM wp_termrelationships
             WHERE term_taxonomy_id = 8232)
</code>```

Here I take for granted that term_taxonomy_id is an integer.

Body:
I am trying to figure out how to quickly change some stuff in a large wordpress database, doing through the GUI takes forever, i think executing this direclty on the database would be much more efficient as it's a one time thing.

I have the follow tables involved:

wp_posts
--------
ID
post_status

wp_termrelationships
--------------------
object_id
term_taxonomy_id

I need to execute a mysql query that looks for term_taxonomy_id '8232' in the table wp_termrelationships , if there's a match for term_taxonomy_id '8232' then take the object_id for that match and use that data to search table wp_posts column ID for a match. When matches are found in table wp_posts column ID update the post_status for each post to 'publish'

No changes is made to anything except the post_status in the table wp_posts.

To me this query is very complex, any ideas?

Body:
Lets deconstruct your requirement, and build the queries:

I need to execute a mysql query that looks for term_taxonomy_id '8232' in the table wp_termrelationships

SELECT object_id
FROM wp_termrelationships
WHERE term_taxonomy_id = 8232

if there's a match for term_taxonomy_id '8232' then take the object_id for that match and use that to search table wp_posts column ID for the data gotten from the match in the object_id

Here I use a sub-query:

SELECT *
FROM wp_posts
WHERE ID IN (SELECT object_id
             FROM wp_termrelationships
             WHERE term_taxonomy_id = 8232)

when those matches are found update the post_status for each matched post in table wp_posts to 'publish'

UPDATE wp_posts
SET post_status = 'publish'
WHERE ID IN (SELECT object_id
             FROM wp_termrelationships
             WHERE term_taxonomy_id = 8232)

Here I take for granted that term_taxonomy_id is an integer.


问:
Collatz sequence using linq c#
Good afternoon guys, I have a following problem of the school to solve, being it in relation to Collatz Problem, where I need to develop an application that will find out the starting number between 1 and 1 million that produces the largest sequence.

I made the following code without applying LINQ, and would like to know how to use linq in this situation.

```<code>var sequence_size = 0;
        var best_number = 0;
        var sequence = 0;

        for (var i = 0; i <= 1000000; i ++)
        {
            var size_ = 1;
            sequence = i;

            while (sequence! = 1)
            {

                sequence = sequence% 2 == 0? sequence / 2: sequence * 3 + 1;
                size ++;
            }

            if (size> size)
            {
                size_sequence = size;
                best_number = i;
            }
        }
</code>```

答:
Create an extension function to find the maximum of a sequence using a function on each element:

```<code>public static class Ext {
    public static T MaxBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> key, Comparer<TKey> keyComparer = null) {
        keyComparer = keyComparer ?? Comparer<TKey>.Default;
         return src.Aggregate((a,b) => keyComparer.Compare(key(a), key(b)) > 0 ? a : b);
    }
}
</code>```

Create a function to return the Collatz length of a number:

```<code>public long Collatz(long seq) {
    long len = 0;

    while (seq != 1) {
        if (seq % 2 == 0) {
            seq /= 2;
            ++len;
        }
        else {
            seq = (3 * seq + 1) / 2;
            len += 2;
        }
    }
    return len;
}
</code>```

Then you can use these and LINQ to computer the answer for a range:

```<code>var maxn = Enumerable.Range(2, 1000000-2).Select(n => new { n, Collatz = Collatz(n) }).MaxBy(nc => nc.Collatz).n;
</code>```

Title: Collatz sequence using linq c#

Body:
Good afternoon guys, I have a following problem of the school to solve, being it in relation to Collatz Problem, where I need to develop an application that will find out the starting number between 1 and 1 million that produces the largest sequence.

I made the following code without applying LINQ, and would like to know how to use linq in this situation.

var sequence_size = 0;
        var best_number = 0;
        var sequence = 0;

        for (var i = 0; i <= 1000000; i ++)
        {
            var size_ = 1;
            sequence = i;

            while (sequence! = 1)
            {

                sequence = sequence% 2 == 0? sequence / 2: sequence * 3 + 1;
                size ++;
            }

            if (size> size)
            {
                size_sequence = size;
                best_number = i;
            }
        }

Body:
Create an extension function to find the maximum of a sequence using a function on each element:

public static class Ext {
    public static T MaxBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> key, Comparer<TKey> keyComparer = null) {
        keyComparer = keyComparer ?? Comparer<TKey>.Default;
         return src.Aggregate((a,b) => keyComparer.Compare(key(a), key(b)) > 0 ? a : b);
    }
}

Create a function to return the Collatz length of a number:

public long Collatz(long seq) {
    long len = 0;

    while (seq != 1) {
        if (seq % 2 == 0) {
            seq /= 2;
            ++len;
        }
        else {
            seq = (3 * seq + 1) / 2;
            len += 2;
        }
    }
    return len;
}

Then you can use these and LINQ to computer the answer for a range:

var maxn = Enumerable.Range(2, 1000000-2).Select(n => new { n, Collatz = Collatz(n) }).MaxBy(nc => nc.Collatz).n;