问:
I am getting a white empty page when opening this vue view (HTML)
I am working on a simple ToDo List.
I have a problem: When opening the EditAssignee.vue in the browser I am getting an empty, white page. Only my header is displayed. Can anyone tell me, where the problem is? Is there something wrong with my router?
Be warned: I'm pretty new to this...
Thank you!

EditAssignee.vue

```<code><template>
  <div>
    <h1>Edit Assignee</h1>
<!--    <h2>{{ this.assignee.prename }} {{ this.assignee.name }}</h2>-->
<!--    <p>{{ this.assignee.email }}</p>-->
    <br>
    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    <b-button size="sm" variant="primary" v-on:click="updateAssignee">Save Changes</b-button>
  </div>

</template>

<script>
import axios from "axios";
import config from "@/config";

export default {
  name: "EditAssignee",
  data() {
    return {
      assignee: null,
      id: this.$route.params.id,
      prename: this.$route.params.prename,
      email: this.$route.params.email,
      name: this.$route.params.name,
      assignees: []
    }
  },

  methods: {
    getAssignee: function () {
      axios.get(`${config.apiBaseUrl}/assignees/${this.$route.params.id}`).then((response) => {
        // log response data to the browser console
        console.log(response.data);
        // assign response to data variable
        this.assignee = response.data;
      });
    },
    updateAssignee: function () {
      axios.put(`${config.apiBaseUrl}/assignees/${this.$route.params.id}`, {
        prename: this.prename,
        name: this.name,
        email: this.email
      })
          .then(response => {
            this.fetchAllAssignees();

            console.log(response)
          })
          .catch(error => console.log(error))
    },

    created: function () {
      this.getAssignee()
    }
  }
}
</script>

<style scoped>

</style>

</code>```

Assignee.vue (Here's the button to the EditAssignee page)

```<code><template>
  <div>
    <h1>Assignees</h1>

    <p>Please fill in all fields to create a new assignee. Please note that the assignee needs an email with the domain
      <i>.uni-stuttgart.de.</i></p>
    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    <b-button variant="primary" size="sm" v-on:click="createAssignee"
    >Create new Assignee
    </b-button>
    <br><br>

    <b-alert v-bind:show="assignees.length === 0" variant="warning">
      No assignee available on the server...
    </b-alert>

    <div class="assigneeBox" v-for="assignee in assignees" v-bind:key="assignee.id">
      <h3>{{ assignee.prename }} {{ assignee.name }}</h3>
      <p>E-Mail: {{ assignee.email }}, ID: {{ assignee.id }}</p>

      <div>
        <b-button
            size="sm"
            variant="outline-danger"
            v-on:click="deleteAssignee(assignee.id)"
        >
          <b-icon-trash></b-icon-trash>
          Delete
        </b-button>

        <b-button size="sm" variant="primary" :to="`/assignees/${assignee.id}`"><b-icon-pencil></b-icon-pencil>
          Details & Edit
        </b-button>

        <hr>
      </div>

    </div>
  </div>
</template>

<script>
// import configuration with API url; @ refers to the src directory
import config from "@/config";
// import library for HTTP requests
import axios from "axios";

export default {
  name: "Assignees",
  data() {
    return {
      assignees: [],
      prename: this.$route.params.prename,
      email: this.$route.params.email,
      name: this.$route.params.name,
      deleteMessage: ""
    };
  },
  methods: {
    // send GET request to API to fetch all assignees
    fetchAllAssignees: function () {
      axios.get(`${config.apiBaseUrl}/assignees`).then((response) => {
        // log response data to the browser console
        console.log(response.data);
        // assign response to data variable
        this.assignees = response.data;
      });
    },
    deleteAssignee: function (id) {
      // send DELETE request to API to delete a specific assignee by ID
      axios.delete(`${config.apiBaseUrl}/assignees/${id}`).then(() => {
        // update view by removing deleted assignee
        this.assignees = this.assignees.filter((assignee) => assignee.id !== id);
        // show success message using BootstrapVue toast component
        this.showToastMessage(
            "Alert",
            `Successfully deleted assignee with ID ${id}!`,
            "success"
        );
      });
    },
    createAssignee() {
      axios.post(`${config.apiBaseUrl}/assignees`, {prename: this.prename, name: this.name, email: this.email})
          .then(response => {
            this.fetchAllAssignees()
            this.showToastMessage(
                "Created",
                `${this.prename} ${this.name} has been created`,
                "success"
            );
            console.log(response)
          })
          .catch(error => console.log(error))
    },
    showToastMessage(title, msg, variant) {
      this.$bvToast.toast(msg, {
        title: title,
        variant: variant,
        solid: true,
        toaster: "b-toaster-top-center",
        autoHideDelay: 4000,
        appendToast: true
      });
    }
  },
  // executed after the component has been started
  created: function () {
    this.fetchAllAssignees();
  }
};
</script>

<style>
.assigneesBox {
  padding: 10px;
  margin: 3px;
  border: 1px solid #42b983;
  float: left;
  min-width: 250px;
  text-align: center;
}

.assigneesLogo {
  height: 200px;
}

.assigneeBox button {
  margin: 5px;
}
</style>
</code>```

Errors:

```<code>vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read properties of null (reading 'prename')"

found in

---> <EditAssignee> at src/views/EditAssignee.vue
       <App> at src/App.vue
         <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1893
globalHandleError @ vue.runtime.esm.js?2b0e:1888
handleError @ vue.runtime.esm.js?2b0e:1848
Vue._render @ vue.runtime.esm.js?2b0e:3571
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
Watcher @ vue.runtime.esm.js?2b0e:4484
mountComponent @ vue.runtime.esm.js?2b0e:4088
Vue.$mount @ vue.runtime.esm.js?2b0e:8459
init @ vue.runtime.esm.js?2b0e:3137
merged @ vue.runtime.esm.js?2b0e:3322
createComponent @ vue.runtime.esm.js?2b0e:6022
createElm @ vue.runtime.esm.js?2b0e:5969
updateChildren @ vue.runtime.esm.js?2b0e:6260
patchVnode @ vue.runtime.esm.js?2b0e:6363
updateChildren @ vue.runtime.esm.js?2b0e:6237
patchVnode @ vue.runtime.esm.js?2b0e:6363
patch @ vue.runtime.esm.js?2b0e:6526
Vue._update @ vue.runtime.esm.js?2b0e:3963
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
run @ vue.runtime.esm.js?2b0e:4570
flushSchedulerQueue @ vue.runtime.esm.js?2b0e:4326
eval @ vue.runtime.esm.js?2b0e:1989
flushCallbacks @ vue.runtime.esm.js?2b0e:1915
Promise.then (async)
timerFunc @ vue.runtime.esm.js?2b0e:1942
nextTick @ vue.runtime.esm.js?2b0e:1999
queueWatcher @ vue.runtime.esm.js?2b0e:4418
update @ vue.runtime.esm.js?2b0e:4560
notify @ vue.runtime.esm.js?2b0e:730
reactiveSetter @ vue.runtime.esm.js?2b0e:1055
eval @ vue-router.esm.js?8c4f:3003
eval @ vue-router.esm.js?8c4f:3002
updateRoute @ vue-router.esm.js?8c4f:2414
eval @ vue-router.esm.js?8c4f:2263
eval @ vue-router.esm.js?8c4f:2402
step @ vue-router.esm.js?8c4f:2001
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
eval @ vue-router.esm.js?8c4f:2397
step @ vue-router.esm.js?8c4f:2001
eval @ vue-router.esm.js?8c4f:2005
eval @ vue-router.esm.js?8c4f:2384
eval @ vue-router.esm.js?8c4f:2162
iterator @ vue-router.esm.js?8c4f:2362
step @ vue-router.esm.js?8c4f:2004
step @ vue-router.esm.js?8c4f:2008
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
confirmTransition @ vue-router.esm.js?8c4f:2392
transitionTo @ vue-router.esm.js?8c4f:2260
push @ vue-router.esm.js?8c4f:2715
push @ vue-router.esm.js?8c4f:3037
handler @ vue-router.esm.js?8c4f:1139
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961
28 weitere Frames anzeigen
vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of null (reading 'prename')
    at Proxy.render (EditAssignee.vue?be9f:11:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4081:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at new Watcher (vue.runtime.esm.js?2b0e:4484:1)
    at mountComponent (vue.runtime.esm.js?2b0e:4088:1)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8459:1)
    at init (vue.runtime.esm.js?2b0e:3137:1)
    at merged (vue.runtime.esm.js?2b0e:3322:1)
    at createComponent (vue.runtime.esm.js?2b0e:6022:1)
</code>```

答:
Assignee.vue

```<code><script>
export default {
  name: "EditAssignee",
  data() {
    return {
      assignee: null,
      id: this.$route.params.id,
      assignees: [],
      prename:undefined //Add this.
    }
  },
}
</script>
</code>```

Body:
I am working on a simple ToDo List.
I have a problem: When opening the EditAssignee.vue in the browser I am getting an empty, white page. Only my header is displayed. Can anyone tell me, where the problem is? Is there something wrong with my router?
Be warned: I'm pretty new to this...
Thank you!

EditAssignee.vue

<template>

Edit Assignee

    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    Save Changes

</template>

Assignee.vue (Here's the button to the EditAssignee page)

<template>

Assignees

Please fill in all fields to create a new assignee. Please note that the assignee needs an email with the domain
      .uni-stuttgart.de.

    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    Create new Assignee

      No assignee available on the server...

{{ assignee.prename }} {{ assignee.name }}

E-Mail: {{ assignee.email }}, ID: {{ assignee.id }}

          Delete

        <b-button size="sm" variant="primary" :to="`/assignees/${assignee.id}`">
          Details & Edit

</template>

Errors:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read properties of null (reading 'prename')"

found in

---> <EditAssignee> at src/views/EditAssignee.vue
       <App> at src/App.vue
         <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1893
globalHandleError @ vue.runtime.esm.js?2b0e:1888
handleError @ vue.runtime.esm.js?2b0e:1848
Vue._render @ vue.runtime.esm.js?2b0e:3571
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
Watcher @ vue.runtime.esm.js?2b0e:4484
mountComponent @ vue.runtime.esm.js?2b0e:4088
Vue.$mount @ vue.runtime.esm.js?2b0e:8459
init @ vue.runtime.esm.js?2b0e:3137
merged @ vue.runtime.esm.js?2b0e:3322
createComponent @ vue.runtime.esm.js?2b0e:6022
createElm @ vue.runtime.esm.js?2b0e:5969
updateChildren @ vue.runtime.esm.js?2b0e:6260
patchVnode @ vue.runtime.esm.js?2b0e:6363
updateChildren @ vue.runtime.esm.js?2b0e:6237
patchVnode @ vue.runtime.esm.js?2b0e:6363
patch @ vue.runtime.esm.js?2b0e:6526
Vue._update @ vue.runtime.esm.js?2b0e:3963
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
run @ vue.runtime.esm.js?2b0e:4570
flushSchedulerQueue @ vue.runtime.esm.js?2b0e:4326
eval @ vue.runtime.esm.js?2b0e:1989
flushCallbacks @ vue.runtime.esm.js?2b0e:1915
Promise.then (async)
timerFunc @ vue.runtime.esm.js?2b0e:1942
nextTick @ vue.runtime.esm.js?2b0e:1999
queueWatcher @ vue.runtime.esm.js?2b0e:4418
update @ vue.runtime.esm.js?2b0e:4560
notify @ vue.runtime.esm.js?2b0e:730
reactiveSetter @ vue.runtime.esm.js?2b0e:1055
eval @ vue-router.esm.js?8c4f:3003
eval @ vue-router.esm.js?8c4f:3002
updateRoute @ vue-router.esm.js?8c4f:2414
eval @ vue-router.esm.js?8c4f:2263
eval @ vue-router.esm.js?8c4f:2402
step @ vue-router.esm.js?8c4f:2001
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
eval @ vue-router.esm.js?8c4f:2397
step @ vue-router.esm.js?8c4f:2001
eval @ vue-router.esm.js?8c4f:2005
eval @ vue-router.esm.js?8c4f:2384
eval @ vue-router.esm.js?8c4f:2162
iterator @ vue-router.esm.js?8c4f:2362
step @ vue-router.esm.js?8c4f:2004
step @ vue-router.esm.js?8c4f:2008
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
confirmTransition @ vue-router.esm.js?8c4f:2392
transitionTo @ vue-router.esm.js?8c4f:2260
push @ vue-router.esm.js?8c4f:2715
push @ vue-router.esm.js?8c4f:3037
handler @ vue-router.esm.js?8c4f:1139
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961
28 weitere Frames anzeigen
vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of null (reading 'prename')
    at Proxy.render (EditAssignee.vue?be9f:11:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4081:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at new Watcher (vue.runtime.esm.js?2b0e:4484:1)
    at mountComponent (vue.runtime.esm.js?2b0e:4088:1)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8459:1)
    at init (vue.runtime.esm.js?2b0e:3137:1)
    at merged (vue.runtime.esm.js?2b0e:3322:1)
    at createComponent (vue.runtime.esm.js?2b0e:6022:1)

Body:
Assignee.vue

<script>
export default {
  name: "EditAssignee",
  data() {
    return {
      assignee: null,
      id: this.$route.params.id,
      assignees: [],
      prename:undefined //Add this.
    }
  },
}
</script>


来源: stackexchange

问:
Run task every minute in Flutter
I'm very beginner in mobile development.
I want to create an android app with flutter which send a GET request to my server every minutes even if the app is in background or screen is off. I did it with the Cron plugin but when the app is no more in foreground, the data are not sent to my server.
Can you please help me to know which plugin need I to use ?
I tried with android_workmanager_plus but periodically wasn't seem to work :/

this is how it's implemented for the moment

```<code>TextButton(
                onPressed: () {
                  var cron =  Cron();
                  cron.schedule(Schedule.parse('*/1 * * * *'), () async {
                  BlocProvider.of<TestCubit>(context).validate();
                  });
                },
</code>```

and this is my method in my cubit file

```<code>validate() async{

    var battery = Battery();
    var batlevel = await battery.batteryLevel;
    state.status = Colors.blue;
    emit(state);
    try{
      final batt = await repo.getBattery(batlevel.toString());
      print(batt);
      //print(state.path);

    }catch(e){
      print(e);
    }
    state.status = Colors.green;
    emit(state);
  }
}
</code>```

Thanks for your future help :)

答:
You don't need any plugins to repeat something every second, however I doubt this works when the app is not open, it works when the app is open and backgrounded</p>
```<code>t = Timer.periodic(Duration(seconds: 1), (Timer timer) => yourFunction());
</code>```

ContentLicense: CC BY-SA 4.0

Title: Run task every minute in Flutter

Body:
I'm very beginner in mobile development.
I want to create an android app with flutter which send a GET request to my server every minutes even if the app is in background or screen is off. I did it with the Cron plugin but when the app is no more in foreground, the data are not sent to my server.
Can you please help me to know which plugin need I to use ?
I tried with android_workmanager_plus but periodically wasn't seem to work :/

this is how it's implemented for the moment

TextButton(
                onPressed: () {
                  var cron =  Cron();
                  cron.schedule(Schedule.parse('*/1 * * * *'), () async {
                  BlocProvider.of<TestCubit>(context).validate();
                  });
                },

and this is my method in my cubit file

validate() async{

    var battery = Battery();
    var batlevel = await battery.batteryLevel;
    state.status = Colors.blue;
    emit(state);
    try{
      final batt = await repo.getBattery(batlevel.toString());
      print(batt);
      //print(state.path);

    }catch(e){
      print(e);
    }
    state.status = Colors.green;
    emit(state);
  }
}

Thanks for your future help :)

Body:
You don't need any plugins to repeat something every second, however I doubt this works when the app is not open, it works when the app is open and backgrounded

t = Timer.periodic(Duration(seconds: 1), (Timer timer) => yourFunction());


问:
R : How to iterate sum across multiple columns?
I am trying to iterate/loop a sum across multiple non-consecutive columns. My objective is to compute the subscale score of multiple questionnaires measured repeatedly across time.

Dataset for one questionnaire of x items and n time-points:

```<code>df <- tibble(
  ID = 1:5,
  itemA_1 = sample(100, 5, TRUE),
  itemB_1 = sample(100, 5, TRUE),
  itemC_1 = sample(100, 5, TRUE),
  itemD_1 = sample(100, 5, TRUE),
  itemx_1 = sample(100, 5, TRUE),
  itemA_3 = sample(100, 5, TRUE),
  itemB_3 = sample(100, 5, TRUE),
  itemC_3 = sample(100, 5, TRUE),
  itemD_3 = sample(100, 5, TRUE),
  itemx_3 = sample(100, 5, TRUE),
  itemA_n = sample(100, 5, TRUE),
  itemB_n = sample(100, 5, TRUE),
  itemC_n = sample(100, 5, TRUE),
  itemD_n = sample(100, 5, TRUE),
  itemx_n = sample(100, 5, TRUE),
)
</code>```

The sum for one specific time point works just fine:

```<code>df %>% mutate(total_1 = sum(c(itemA_1, itemC_1, itemD_1))
</code>```

This loop does not work:

```<code>for (i in c(1, 3, n)) {
    df %>% mutate(total_i = sum(c(itemA_i, itemC_i, itemD_i))
    }
</code>```

What am I doing wrong?

Body:
I am trying to iterate/loop a sum across multiple non-consecutive columns. My objective is to compute the subscale score of multiple questionnaires measured repeatedly across time.

Dataset for one questionnaire of x items and n time-points:

df <- tibble(
  ID = 1:5,
  itemA_1 = sample(100, 5, TRUE),
  itemB_1 = sample(100, 5, TRUE),
  itemC_1 = sample(100, 5, TRUE),
  itemD_1 = sample(100, 5, TRUE),
  itemx_1 = sample(100, 5, TRUE),
  itemA_3 = sample(100, 5, TRUE),
  itemB_3 = sample(100, 5, TRUE),
  itemC_3 = sample(100, 5, TRUE),
  itemD_3 = sample(100, 5, TRUE),
  itemx_3 = sample(100, 5, TRUE),
  itemA_n = sample(100, 5, TRUE),
  itemB_n = sample(100, 5, TRUE),
  itemC_n = sample(100, 5, TRUE),
  itemD_n = sample(100, 5, TRUE),
  itemx_n = sample(100, 5, TRUE),
)

The sum for one specific time point works just fine:

df %>% mutate(total_1 = sum(c(itemA_1, itemC_1, itemD_1))

This loop does not work:

for (i in c(1, 3, n)) {
    df %>% mutate(total_i = sum(c(itemA_i, itemC_i, itemD_i))
    }

What am I doing wrong?

Body:
Another possible solution, based on purrr::map_dfc:

library(tidyverse)

map_dfc(c("1","3","n"),~ data.frame(apply(select(df, ends_with(.x)), 1, sum)) %>%
    set_names(str_c("Total_",.x))) %>% bind_cols(df, .)

#>   ID itemA_1 itemB_1 itemC_1 itemD_1 itemx_1 itemA_3 itemB_3 itemC_3 itemD_3
#> 1  1      89      33      84      15      86       8       9      18      98
#> 2  2      37       2      32      52      37      79      37      31      57
#> 3  3       5      21      54      58      25      74      43       7      14
#> 4  4      19      76      71      84      75      34      72     100      33
#> 5  5      78      52      58      42       5      28      90      21      95
#>   itemx_3 itemA_n itemB_n itemC_n itemD_n itemx_n Total_1 Total_3 Total_n
#> 1      78       5      52       4      73      88     307     211     222
#> 2      82      88      78       3       3      69     160     286     241
#> 3      41      60      73      59      32      87     163     179     311
#> 4      97      86      33      81      44      22     325     336     266
#> 5      37       4       9      35       5      38     235     271      91


问:
returning empty object Nodejs adding attributes to twilio conversations API
I am using twilio conversations Api to create a little sms chat app. I need to set an attributes object , but when I set it like below it just returns empty. Any twilio experts out there know how to solve this?

NOTE from docs :

Attributes -

An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. Note that if the attributes are not set "{}" will be returned.

```<code>  await subClient.conversations.services(convoServiceSid)
        .conversations
        .create({
            attributes: {read: "false"}  // when I fetch conversation, this attributes is empty object....
        })
        .then(conversation => console.log(conversation.sid));
</code>```

答:
So, in the docs it says The string value must contain STRUCTURALLY VALID JSON

the Solution is as follows

```<code> await subClient.conversations.services(convoServiceSid)
        .conversations
        .create({
            attributes: '{"read": "false"}'  <-- needed to wrap object in quotes, also need to wrap key in quotes! success!
        })
        .then(conversation => console.log(conversation.sid));

</code>```

Body:
I am using twilio conversations Api to create a little sms chat app. I need to set an attributes object , but when I set it like below it just returns empty. Any twilio experts out there know how to solve this?

NOTE from docs :

Attributes -

An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. Note that if the attributes are not set "{}" will be returned.

  await subClient.conversations.services(convoServiceSid)
        .conversations
        .create({
            attributes: {read: "false"}  // when I fetch conversation, this attributes is empty object....
        })
        .then(conversation => console.log(conversation.sid));

Body:
So, in the docs it says The string value must contain STRUCTURALLY VALID JSON

the Solution is as follows

 await subClient.conversations.services(convoServiceSid)
        .conversations
        .create({
            attributes: '{"read": "false"}'  <-- needed to wrap object in quotes, also need to wrap key in quotes! success!
        })
        .then(conversation => console.log(conversation.sid));


问:
How to identify unique people in a MySQL table using more than one criteria
I have a ~200k record table dat of people with their identifying data as well as a test date and result, here's a dummy version:

```<code>+----+---------+----------+------------+----------+------------+--------+
| id | surname | forename | dob        | SchoolID | testDate   | result |
+----+---------+----------+------------+----------+------------+--------+
|  1 | Smith   | Mary     | 1980-04-11 | NULL     | 2005-10-12 |  14.32 |
|  2 | Smith   | Mary     | 1980-04-11 | 1234     | 2007-03-02 |   18.1 |
|  3 | Jones   | Kim      | 1978-10-24 | 4657     | 2002-04-14 |  24.31 |
|  4 | Jones   | Kim      | NULL       | 4567     | 2002-10-08 |  19.02 |
|  5 | Roberts | Kim      | 1978-10-24 | 4567     | 2003-12-18 |  14.19 |
|  6 | Roberts | Kim      | 1978-10-24 | 4567     | 2005-02-11 |  18.26 |
+----+---------+----------+------------+----------+------------+--------+
</code>```

I would like to identify people who have had more than one test, and create a new column uniqueID that gives unique people a new id. Sadly, my database is not very tidy so I need to use several criteria to separate these records into unique individuals:

surname, forename and dob are the same (since SchoolID is often missing or wrong)

surname, forename and SchoolID are the same (since D.O.B. is sometimes not entered, or
entered wrong)

forename, dob and SchoolID are the same (people sometimes get married)

etc.

In the example above, there are just two unique people in the table Mary Smith and Kim Roberts nee Jones, so this uniqueID column should end up being:

```<code>+----+----------+
| id | uniqueID |
+----+----------+
|  1 |        1 |
|  2 |        1 |
|  3 |        2 |
|  4 |        2 |
|  5 |        2 |
|  6 |        2 |
+----+----------+
</code>```

Although I've been dabbled a bit with MySQL for a few years I'm still a beginner. I've been searching and trying things for a few days, and so far I have managed this:

```<code>SELECT surname, forename, SchoolID
   FROM dat
   GROUP BY CONCAT(surname, forename, SchoolID);
</code>```

which is the second criterion, for example, (that I was planning to give an auto incrementing key to in a new table, then join back in as the unique ID), but I'm not getting very with these multiple criteria, so any help much appreciated!

Thanks
Nick

答:
You can do this through self joins. I'd do it in multiple steps, though - from best to weakest match.

So, assuming schoolID is reliable when present, this is how you find the duplicates:

```<code>select *
from   dat parent,
       dat child
where  parent.id      <> child.id
and    parent.schoolid =  child.schoolid
</code>```

(Apologies for antediluvian join syntax).

Run that, and see if you get any oddities; if you like it, turn it into an update. Updates with a self join are a little painful in MySQL, and the simplest way is to create a view to join.

```<code>create view dupes as

select   min(parent.id) as uniqueid, child.id
from     dat parent,
         dat child
where    parent.schoolid =  child.schoolid
group by child.id

update  ignore dat, dupes
set     dat.uniqueid =   dupes.uniqueid
where    dat.id      = dupes.id
</code>```

Now, you go to the second strongest link, something like:

```<code>    select *
    from   dat parent,
           dat child
    where  parent.id      <> child.id
    and    parent.uniqueID is  null
    and    child.uniqueID  is  null
    and    parent.forename = child.forename
    and    parent.surname  = child.surname
    and    parent.dob      = child.dob
</code>```

Again, run it, check the data for oddities, turn into an update statement.

Next, relax the restrictions - it's okay if we have previously matched the parent to another record, so we can remove the check for null:

```<code>select *
from   dat parent,
       dat child
where  parent.id      <> child.id
and    child.uniqueID  is  null
and    parent.forename = child.forename
and    parent.surname  = child.surname
and    parent.dob      = child.dob
</code>```

And so on, and so forth.
By working from strongest likelihood down, you reduce the risk of a fairly tenuous similarity overriding a clear link (e.g. two people called "Kim" who happened to be born on 1978-10-24,

By running selects first, and turning them into updates second, you avoid human error.

ContentLicense: CC BY-SA 3.0

Body:
I have a ~200k record table dat of people with their identifying data as well as a test date and result, here's a dummy version:

+----+---------+----------+------------+----------+------------+--------+
| id | surname | forename | dob        | SchoolID | testDate   | result |
+----+---------+----------+------------+----------+------------+--------+
|  1 | Smith   | Mary     | 1980-04-11 | NULL     | 2005-10-12 |  14.32 |
|  2 | Smith   | Mary     | 1980-04-11 | 1234     | 2007-03-02 |   18.1 |
|  3 | Jones   | Kim      | 1978-10-24 | 4657     | 2002-04-14 |  24.31 |
|  4 | Jones   | Kim      | NULL       | 4567     | 2002-10-08 |  19.02 |
|  5 | Roberts | Kim      | 1978-10-24 | 4567     | 2003-12-18 |  14.19 |
|  6 | Roberts | Kim      | 1978-10-24 | 4567     | 2005-02-11 |  18.26 |
+----+---------+----------+------------+----------+------------+--------+

I would like to identify people who have had more than one test, and create a new column uniqueID that gives unique people a new id. Sadly, my database is not very tidy so I need to use several criteria to separate these records into unique individuals:

surname, forename and dob are the same (since SchoolID is often missing or wrong)

surname, forename and SchoolID are the same (since D.O.B. is sometimes not entered, or
entered wrong)

forename, dob and SchoolID are the same (people sometimes get married)

etc.

In the example above, there are just two unique people in the table Mary Smith and Kim Roberts nee Jones, so this uniqueID column should end up being:

+----+----------+
| id | uniqueID |
+----+----------+
|  1 |        1 |
|  2 |        1 |
|  3 |        2 |
|  4 |        2 |
|  5 |        2 |
|  6 |        2 |
+----+----------+

Although I've been dabbled a bit with MySQL for a few years I'm still a beginner. I've been searching and trying things for a few days, and so far I have managed this:

SELECT surname, forename, SchoolID
   FROM dat
   GROUP BY CONCAT(surname, forename, SchoolID);

which is the second criterion, for example, (that I was planning to give an auto incrementing key to in a new table, then join back in as the unique ID), but I'm not getting very with these multiple criteria, so any help much appreciated!

Thanks
Nick

Body:
You can do this through self joins. I'd do it in multiple steps, though - from best to weakest match.

So, assuming schoolID is reliable when present, this is how you find the duplicates:

select *
from   dat parent,
       dat child
where  parent.id      <> child.id
and    parent.schoolid =  child.schoolid

(Apologies for antediluvian join syntax).

Run that, and see if you get any oddities; if you like it, turn it into an update. Updates with a self join are a little painful in MySQL, and the simplest way is to create a view to join.

create view dupes as

select   min(parent.id) as uniqueid, child.id
from     dat parent,
         dat child
where    parent.schoolid =  child.schoolid
group by child.id

update  ignore dat, dupes
set     dat.uniqueid =   dupes.uniqueid
where    dat.id      = dupes.id

Now, you go to the second strongest link, something like:

    select *
    from   dat parent,
           dat child
    where  parent.id      <> child.id
    and    parent.uniqueID is  null
    and    child.uniqueID  is  null
    and    parent.forename = child.forename
    and    parent.surname  = child.surname
    and    parent.dob      = child.dob

Again, run it, check the data for oddities, turn into an update statement.

Next, relax the restrictions - it's okay if we have previously matched the parent to another record, so we can remove the check for null:

select *
from   dat parent,
       dat child
where  parent.id      <> child.id
and    child.uniqueID  is  null
and    parent.forename = child.forename
and    parent.surname  = child.surname
and    parent.dob      = child.dob

And so on, and so forth.
By working from strongest likelihood down, you reduce the risk of a fairly tenuous similarity overriding a clear link (e.g. two people called "Kim" who happened to be born on 1978-10-24,

By running selects first, and turning them into updates second, you avoid human error.


问:
Unable to mock ThreadLocalRandom.current().nextFloat()
I wanted to unit test shouldEnforce method in Enforcer class by faking the out of ThreadLocalRandom.current().nextFloat() to some predetermined values. But I keep getting this error in the terminal.

Why am I getting this error and how can I fix it?

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

```<code>public class Enforcer {
  private static final ThreadLocalRandom random = ThreadLocalRandom.current();
  private double ratio;
  public Enforcer(double ratio) {
    if (ratio < 0 || ratio > 1) {
      return;
    }
    this.ratio = ratio;
  }

  public boolean shouldEnforce() {
    float randomValue = random.nextFloat();
    return (randomValue < ratio);
  }
}
</code>```

Here is my unit test in a separate file,

```<code>@PrepareForTest({ Enforcer.class}) // <- not sure if needed. Please comment
public class TestEnforcement {
  private static ThreadLocalRandom random;

  @Before
  public void setup() throws Exception {
    random = mock(ThreadLocalRandom.class);
    PowerMockito.mockStatic(ThreadLocalRandom.class);
    when(ThreadLocalRandom.current()).thenReturn(random);
  }

  @Test
  public void testEnforcer() {
    when(random.nextFloat()).thenReturn((float) 0.5);
    Enforcer enforcer = new Enforcer(0.51);
    assertTrue(enforcer.shouldEnforce());
  }
}
</code>```

The above error is caused by the when statement in @Before method. But if I take out that line, the assertion will fail when nextFloat() generates values that are greater than 0.51, so random object is being mocked out.

Update: I was able to fix the error by adding the correct anotation in the unit test.

```<code>@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class)
@PrepareForTest({Enforcer.class})
public class TestEnforcement {
...
}
</code>```

答:
Your need to prepare test case for working with PowerMockito by applying the following two annotations:

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({ Enforcer.class})
public class TestEnforcement {

}
</code>```

Without these annotations mocking will not work.

You have missed: @RunWith(PowerMockRunner.class)

Classes needed to be defined using @PrepareForTest annotation are typically those that needs to be byte-code manipulated. This includes final classes, classes with final, private, static or native methods that should be mocked and also classes that should be return a mock object upon instantiation.

Enforcer class is using static mock, so @PrepareForTest is required.

According to documentation:

https://www.javadoc.io/doc/org.powermock/powermock-core/1.6.5/org/powermock/core/classloader/annotations/PrepareForTest.html

Please note, if you are using junit3 @RunWith(PowerMockRunner.class) annotation should be replaced with:

```<code> public static TestSuite suite() throws Exception {
     return new PowerMockSuite(TestEnforcement.class);
 }
</code>```

Body:
I wanted to unit test shouldEnforce method in Enforcer class by faking the out of ThreadLocalRandom.current().nextFloat() to some predetermined values. But I keep getting this error in the terminal.

Why am I getting this error and how can I fix it?

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

public class Enforcer {
  private static final ThreadLocalRandom random = ThreadLocalRandom.current();
  private double ratio;
  public Enforcer(double ratio) {
    if (ratio < 0 || ratio > 1) {
      return;
    }
    this.ratio = ratio;
  }

  public boolean shouldEnforce() {
    float randomValue = random.nextFloat();
    return (randomValue < ratio);
  }
}

Here is my unit test in a separate file,

@PrepareForTest({ Enforcer.class}) // <- not sure if needed. Please comment
public class TestEnforcement {
  private static ThreadLocalRandom random;

  @Before
  public void setup() throws Exception {
    random = mock(ThreadLocalRandom.class);
    PowerMockito.mockStatic(ThreadLocalRandom.class);
    when(ThreadLocalRandom.current()).thenReturn(random);
  }

  @Test
  public void testEnforcer() {
    when(random.nextFloat()).thenReturn((float) 0.5);
    Enforcer enforcer = new Enforcer(0.51);
    assertTrue(enforcer.shouldEnforce());
  }
}

The above error is caused by the when statement in @Before method. But if I take out that line, the assertion will fail when nextFloat() generates values that are greater than 0.51, so random object is being mocked out.

Update: I was able to fix the error by adding the correct anotation in the unit test.

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class)
@PrepareForTest({Enforcer.class})
public class TestEnforcement {
...
}

Body:
Your need to prepare test case for working with PowerMockito by applying the following two annotations:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Enforcer.class})
public class TestEnforcement {

}

Without these annotations mocking will not work.

You have missed: @RunWith(PowerMockRunner.class)

Classes needed to be defined using @PrepareForTest annotation are typically those that needs to be byte-code manipulated. This includes final classes, classes with final, private, static or native methods that should be mocked and also classes that should be return a mock object upon instantiation.

Enforcer class is using static mock, so @PrepareForTest is required.

According to documentation:

https://www.javadoc.io/doc/org.powermock/powermock-core/1.6.5/org/powermock/core/classloader/annotations/PrepareForTest.html

Please note, if you are using junit3 @RunWith(PowerMockRunner.class) annotation should be replaced with:

 public static TestSuite suite() throws Exception {
     return new PowerMockSuite(TestEnforcement.class);
 }


问:
Tailwind (v.2) Flex Width Not Growing or Shrinking
I have a series of elements that I am attempting to fit into a panel, arranged in rows of 3, like so:

They should grow and shrink depending on screen width. Despite the parent having a class of flex & and the elements in question having classes of flex-grow, they are not adapting to the screen width and I can't figure out why. My code is as follows:

```<code>   <React.Fragment>
       <div className="flex">
           <className="flex flex-grow items-center justify-center w-20 h-8 mx-1 rounded-md border border-black-16 font-medium"/>
           <className="flex flex-grow items-center justify-center w-20 h-8 mx-1 rounded-md border border-black-16 font-medium"/>
           <className="flex flex-grow items-center justify-center w-20 h-8 mx-1 rounded-md border border-black-16 font-medium"/>
       </div>
   </React.Fragment>
</code>```

答:
use width-full in root elemment or width-8/12 if you dont want full width then it will adapt according to screen size

i have created two examples with flex and grid take a look this might help

or you can check here tailwind play

with flex

each

each

each

each

each

each

each

each

each

with grid

each

each

each

each

each

each

each

each

each

```

Body:
I have a series of elements that I am attempting to fit into a panel, arranged in rows of 3, like so:

They should grow and shrink depending on screen width. Despite the parent having a class of flex & and the elements in question having classes of flex-grow, they are not adapting to the screen width and I can't figure out why. My code is as follows:

   <React.Fragment>

           <className="flex flex-grow items-center justify-center w-20 h-8 mx-1 rounded-md border border-black-16 font-medium"/>
           <className="flex flex-grow items-center justify-center w-20 h-8 mx-1 rounded-md border border-black-16 font-medium"/>
           <className="flex flex-grow items-center justify-center w-20 h-8 mx-1 rounded-md border border-black-16 font-medium"/>

   </React.Fragment>

Body:
use width-full in root elemment or width-8/12 if you dont want full width then it will adapt according to screen size

i have created two examples with flex and grid take a look this might help

or you can check here tailwind play

<script src="https://cdn.tailwindcss.com"></script>

<h2 class="font-semibold mx-auto w-full text-center p-3 capitalize border-b">with flex</h2>
<div class="w-full mx-auto flex flex-wrap text-center">
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>
    <div class="each-wrap w-4/12">
        <div class="each m-4 p-3 rounded-md border hover:bg-gray-200 cursor-pointer shadow-md border-gray-300">each</div>
    </div>

</div>

<h2 class="font-semibold mx-auto w-full text-center p-3 capitalize border-b">with grid</h2>
<div class="grid grid-cols-3 text-center">
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
    <div class="each cursor-pointer hover:bg-gray-200 border p-3 rounded-md border-gray-300 shadow-md m-5">each</div>
</div>


问:
For the same set of values, how do I pull just one value from a different column in Excel?
For each set of PPIDs that has a “Delete” value and no “Reassign”, how would I populate the Intended Result column. In this example, I only need to populate “Delete” for PPIDS 123 and 789 because there is no “Reassign” value

答:
Well, you may try using the below formula as well in cell C2

```<code>=IF(AND($B2="Delete",COUNTIFS($A$2:$A$8,A2,$B$2:$B$8,"Reassign")=0),"Delete","")
</code>```

Body:
Well, you may try using the below formula as well in cell C2

=IF(AND($B2="Delete",COUNTIFS($A$2:$A$8,A2,$B$2:$B$8,"Reassign")=0),"Delete","")


问:
Xcode giving warning when using await UIApplication.shared.open(settingsURL) in Swift async function
I am calling await UIApplication.shared.open(settingsURL) inside a Swift Task but I am getting an Xcode runtime warning:

UIApplication.open(_:options:completionHandler:) must be used from the main thread only

```<code>Task {
    guard let settingsURL = await URL(string: UIApplication.openSettingsURLString) else {
        return
    }
    await UIApplication.shared.open(settingsURL) // <-- runtime warning when called
}
</code>```

The SDK shows these methods:

```<code>@available(iOS 10.0, *)
open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil)

@available(iOS 10.0, *)
open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:]) async -> Bool
</code>```

The error message implies that it thinks I'm using the first, non-async one (because of the mention of the completion handler), but I'm not. UIApplication is marked with MainActor so my understanding is everything called via an instance of UIApplication is run on the main thread automatically. This works just fine for other things I've called on UIApplication elsewhere such as isRegisteredForRemoteNotifications.

The app runs fine, no crashes or anything, just the warning from Xcode.

Is Xcode just confused here or am I actually doing something wrong?

Screenshot:

EDIT: for those confused about MainActor, this is a useful read: https://www.swiftbysundell.com/articles/the-main-actor-attribute/

I can just wrap UIApplication.shared.open(settingsURL) in await MainActor.run but I'm still confused why MainActor doesn't work here / why Xcode thinks the wrong method is being called.

答:
The error indicates you may be using Task {...} somewhere in your code that is not on the main thread.
With the following test code, I could not replicate your issue, using  macos 12.3 Beta, Xcode 13.3,
targets ios 15 and macCatalyst 12. Tested on real devices, not Preview. It may be different on older systems.

This is the code I used in my tests:

```<code>struct ContentView: View {
    var body: some View {
        Text("testing")
            .onAppear {
                Task {
                    guard let settingsURL = URL(string: "https://duckduckgo.com") else { return }
                    await UIApplication.shared.open(settingsURL) // <-- NO runtime warning when called
                }
            }
    }
}
</code>```

Does this code give you the same warning?

EDIT-1: this also works for me.

```<code>struct ContentView: View {
    var body: some View {
        Text("testing")
            .onAppear {
                DispatchQueue.global(qos: .background).async {
                    Task {
                        guard let settingsURL = URL(string: "https://duckduckgo.com") else { return }
                        await UIApplication.shared.open(settingsURL)
                    }
                }
            }
    }
}
</code>```

Body:
I am calling await UIApplication.shared.open(settingsURL) inside a Swift Task but I am getting an Xcode runtime warning:

UIApplication.open(_:options:completionHandler:) must be used from the main thread only

Task {
    guard let settingsURL = await URL(string: UIApplication.openSettingsURLString) else {
        return
    }
    await UIApplication.shared.open(settingsURL) // <-- runtime warning when called
}

The SDK shows these methods:

@available(iOS 10.0, *)
open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil)

@available(iOS 10.0, *)
open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:]) async -> Bool

The error message implies that it thinks I'm using the first, non-async one (because of the mention of the completion handler), but I'm not. UIApplication is marked with MainActor so my understanding is everything called via an instance of UIApplication is run on the main thread automatically. This works just fine for other things I've called on UIApplication elsewhere such as isRegisteredForRemoteNotifications.

The app runs fine, no crashes or anything, just the warning from Xcode.

Is Xcode just confused here or am I actually doing something wrong?

Screenshot:

EDIT: for those confused about MainActor, this is a useful read: https://www.swiftbysundell.com/articles/the-main-actor-attribute/

I can just wrap UIApplication.shared.open(settingsURL) in await MainActor.run but I'm still confused why MainActor doesn't work here / why Xcode thinks the wrong method is being called.

Body:
The error indicates you may be using Task {...} somewhere in your code that is not on the main thread.
With the following test code, I could not replicate your issue, using  macos 12.3 Beta, Xcode 13.3,
targets ios 15 and macCatalyst 12. Tested on real devices, not Preview. It may be different on older systems.

This is the code I used in my tests:

struct ContentView: View {
    var body: some View {
        Text("testing")
            .onAppear {
                Task {
                    guard let settingsURL = URL(string: "https://duckduckgo.com") else { return }
                    await UIApplication.shared.open(settingsURL) // <-- NO runtime warning when called
                }
            }
    }
}

Does this code give you the same warning?

EDIT-1: this also works for me.

struct ContentView: View {
    var body: some View {
        Text("testing")
            .onAppear {
                DispatchQueue.global(qos: .background).async {
                    Task {
                        guard let settingsURL = URL(string: "https://duckduckgo.com") else { return }
                        await UIApplication.shared.open(settingsURL)
                    }
                }
            }
    }
}


问:
Propositional calculus in python
I'm looking for a propositional calculus module that works in python.

My users need to input a formula in a text area, then I have to check whether it's correct or not.

I cannot directly test if the input text equals the correct one as it didn't take permutations or such things into account.

Does such a module exist ?

- EDIT -

Here is a screenshot of the project (design not complete) :

答:
This isn't too hard. All you need to do is to either (a) find or (b) write a utility that takes in an arbitrary proposition and produces a truth table. Then, for two propositions, all you need to do is to generate two truth tables and check that the the atomic variables and last column match in all rows.

This is O(2^n) in the number of atomic variables, and assumes that each proposition contains the same number of atomic variables. If extra useless atomic variables may be included (like a OR (b or NOT b) is equivalent to a), you will need to pad the truth tables of the simpler proposition in order to get the same number of rows. If different atomic variables are allowed to be used, then this gets even harder.

You cannot do better than O(2^n), assuming P != NP, since a polynomial solution would solve the general satisfiability problem over propositional calculus.

To generate a truth table, you need to (a) generate a list of all 2^n permutations of truth values of the atomic variables (lots of ways to do this), and (b) evaluate propositions for arbitary assignments to the truth values of atomic variables. Then just make both tables and compare. Voila!

Title: Propositional calculus in python


问:
Identifying changes over time
No doubt a similar question has come up before, but I haven't been able to locate it by searching...

I have a raw dataset with time series data including 'from' and 'to' date fields.

The problem is, when data is loaded, new records have been created ('to' date added to old record, new record 'from' load date) even where no values have changed.
I want to convert this to a table which just shows a row for each genuine change - and the from/ to dates reflecting this.

By way of example, the source data looks like this:

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/06/2020

Test2
1
2
3
01/07/2020
30/09/2020

Test2
3
2
1
01/10/2020
31/12/9999

The first two records for Test2 (rows 2 and 3) are essentially the same - there was no change when the second row was loaded on 01/07/2020. I want a single row for the period 01/01/2020 - 30/09/2020 for which there was no change:

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/09/2020

Test2
3
2
1
01/10/2020
31/12/9999

For this simplified example, I can achieve that by grouping by each column (apart from dates) and using the MIN from date/ MAX end date:

```<code>SELECT
ID, Col1, Col2, Col3, MIN(From) AS From, MAX(To) as TO
FROM TABLE
GROUP BY ID, Col1, Col2, Col3
</code>```

However, this won't work if a value changes then subsequently changes back to what it was before eg

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/04/2020

Test2
1
2
3
01/05/2020
30/06/2020

Test2
3
2
1
01/07/2020
30/10/2020

Test2
1
2
3
01/11/2020
31/12/9999

Simply using MIN/ MAX in the code above would return this - so it looks like both sets of values were valid for the period from 01/07/2020 - 30/10/2020:

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
31/12/9999

Test2
3
2
1
01/07/2020
30/10/2020

Whereas actually the first set of values were valid before and after that period, but not during.
It should return a single row for instead of two for the period from 01/01/2020 - 30/06/2020 when there were no changes for this ID, but then another row for the period when the values were different, and then another row where it reverted to the initial values, but with a new From date.

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/06/2020

Test2
3
2
1
01/07/2020
30/10/2020

Test2
1
2
3
01/11/2020
31/12/9999

I'm struggling to conceptualise how to approach this.
I'm guessing I need to use LAG somehow but not sure how to apply it - eg  rank everything in a staging table first, then use LAG to compare a concatenation of the whole row?

I'm sure I could find a fudged way eventually, but I've no doubt this problem has been solved many times before so hoping somebody can point me to a simpler/ neater solution than I'd inevitably come up with...

答:
Advanced Gaps and Islands

I believe this is an advanced "gaps and islands" problem. Use that as a search term and you'll find plenty of literature on the subject. Only difference is normally only one column is being tracked, but you have 3.

No Gaps Assumption

One major assumption of this script is there is no gap in the overlapping dates, or in other words, it assumes the previous rows ToDate = current FromDate - 1 day.
Not sure if you need to account for gaps, would be simple just add criteria to IsChanged to check for that

Multi-Column Gaps and Islands Solution

```<code>DROP TABLE IF EXISTS #Grouping
DROP TABLE IF EXISTS #Test
CREATE TABLE #Test (ID INT IDENTITY(1,1),TestName Varchar(10),Col1 INT,Col2 INT,Col3 INT,FromDate Date,ToDate DATE)

INSERT INTO #Test VALUES
('Test1',1,1,1,'2020-01-01','9999-12-31')
,('Test2',1,2,3,'2020-01-01','2020-04-30')
,('Test2',1,2,3,'2020-05-01','2020-06-30')
,('Test2',3,2,1,'2020-07-01','2020-10-30')
,('Test2',1,2,3,'2020-11-01','9999-12-31')

;WITH cte_Prev AS (
    SELECT *
    ,PrevCol1 = LAG(Col1) OVER (PARTITION BY TestName       ORDER BY FromDate)
    ,PrevCol2 = LAG(Col2) OVER (PARTITION BY TestName       ORDER BY FromDate)
    ,PrevCol3 = LAG(Col3) OVER (PARTITION BY TestName       ORDER BY FromDate)
    FROM #Test
), cte_Compare AS (
    SELECT *
    ,IsChanged = CASE
        WHEN Col1 = PrevCol1
            AND Col2 = PrevCol2
            AND Col3 = PrevCol3
        THEN 0 /*No change*/
        ELSE 1 /*Iterate so new group created */
    END
    FROM cte_Prev
)

SELECT *,GroupID = SUM(IsChanged) OVER (PARTITION BY TestName ORDER BY ID)
INTO #Grouping
FROM cte_Compare

/*Raw unformatted data so you can see how it works*/
SELECT *
FROM #Grouping

/*Aggregated results*/
SELECT GroupID,TestName,Col1,Col2,Col3
    ,FromDate = MIN(FromDate)
    ,ToDate = MAX(ToDate)
    ,NumberOfRowsCollapsedIntoOneRow = COUNT(*)
FROM #Grouping
GROUP BY GroupID,TestName,Col1,Col2,Col3
</code>```

Title: Identifying changes over time

Body:
No doubt a similar question has come up before, but I haven't been able to locate it by searching...

I have a raw dataset with time series data including 'from' and 'to' date fields.

The problem is, when data is loaded, new records have been created ('to' date added to old record, new record 'from' load date) even where no values have changed.
I want to convert this to a table which just shows a row for each genuine change - and the from/ to dates reflecting this.

By way of example, the source data looks like this:

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/06/2020

Test2
1
2
3
01/07/2020
30/09/2020

Test2
3
2
1
01/10/2020
31/12/9999

The first two records for Test2 (rows 2 and 3) are essentially the same - there was no change when the second row was loaded on 01/07/2020. I want a single row for the period 01/01/2020 - 30/09/2020 for which there was no change:

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/09/2020

Test2
3
2
1
01/10/2020
31/12/9999

For this simplified example, I can achieve that by grouping by each column (apart from dates) and using the MIN from date/ MAX end date:

SELECT
ID, Col1, Col2, Col3, MIN(From) AS From, MAX(To) as TO
FROM TABLE
GROUP BY ID, Col1, Col2, Col3

However, this won't work if a value changes then subsequently changes back to what it was before eg

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/04/2020

Test2
1
2
3
01/05/2020
30/06/2020

Test2
3
2
1
01/07/2020
30/10/2020

Test2
1
2
3
01/11/2020
31/12/9999

Simply using MIN/ MAX in the code above would return this - so it looks like both sets of values were valid for the period from 01/07/2020 - 30/10/2020:

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
31/12/9999

Test2
3
2
1
01/07/2020
30/10/2020

Whereas actually the first set of values were valid before and after that period, but not during.
It should return a single row for instead of two for the period from 01/01/2020 - 30/06/2020 when there were no changes for this ID, but then another row for the period when the values were different, and then another row where it reverted to the initial values, but with a new From date.

ID
Col1
Col2
Col3
From
To

Test1
1
1
1
01/01/2020
31/12/9999

Test2
1
2
3
01/01/2020
30/06/2020

Test2
3
2
1
01/07/2020
30/10/2020

Test2
1
2
3
01/11/2020
31/12/9999

I'm struggling to conceptualise how to approach this.
I'm guessing I need to use LAG somehow but not sure how to apply it - eg  rank everything in a staging table first, then use LAG to compare a concatenation of the whole row?

I'm sure I could find a fudged way eventually, but I've no doubt this problem has been solved many times before so hoping somebody can point me to a simpler/ neater solution than I'd inevitably come up with...

Body:
Advanced Gaps and Islands

I believe this is an advanced "gaps and islands" problem. Use that as a search term and you'll find plenty of literature on the subject. Only difference is normally only one column is being tracked, but you have 3.

No Gaps Assumption

One major assumption of this script is there is no gap in the overlapping dates, or in other words, it assumes the previous rows ToDate = current FromDate - 1 day.
Not sure if you need to account for gaps, would be simple just add criteria to IsChanged to check for that

Multi-Column Gaps and Islands Solution

DROP TABLE IF EXISTS #Grouping
DROP TABLE IF EXISTS #Test
CREATE TABLE #Test (ID INT IDENTITY(1,1),TestName Varchar(10),Col1 INT,Col2 INT,Col3 INT,FromDate Date,ToDate DATE)

INSERT INTO #Test VALUES
('Test1',1,1,1,'2020-01-01','9999-12-31')
,('Test2',1,2,3,'2020-01-01','2020-04-30')
,('Test2',1,2,3,'2020-05-01','2020-06-30')
,('Test2',3,2,1,'2020-07-01','2020-10-30')
,('Test2',1,2,3,'2020-11-01','9999-12-31')

;WITH cte_Prev AS (
    SELECT *
    ,PrevCol1 = LAG(Col1) OVER (PARTITION BY TestName       ORDER BY FromDate)
    ,PrevCol2 = LAG(Col2) OVER (PARTITION BY TestName       ORDER BY FromDate)
    ,PrevCol3 = LAG(Col3) OVER (PARTITION BY TestName       ORDER BY FromDate)
    FROM #Test
), cte_Compare AS (
    SELECT *
    ,IsChanged = CASE
        WHEN Col1 = PrevCol1
            AND Col2 = PrevCol2
            AND Col3 = PrevCol3
        THEN 0 /*No change*/
        ELSE 1 /*Iterate so new group created */
    END
    FROM cte_Prev
)

SELECT *,GroupID = SUM(IsChanged) OVER (PARTITION BY TestName ORDER BY ID)
INTO #Grouping
FROM cte_Compare

/*Raw unformatted data so you can see how it works*/
SELECT *
FROM #Grouping

/*Aggregated results*/
SELECT GroupID,TestName,Col1,Col2,Col3
    ,FromDate = MIN(FromDate)
    ,ToDate = MAX(ToDate)
    ,NumberOfRowsCollapsedIntoOneRow = COUNT(*)
FROM #Grouping
GROUP BY GroupID,TestName,Col1,Col2,Col3


问:
Trying to multiply a certain data cell by another certain data cell in pandas
Due to misunderstanding using my real scenario I am going to create one.

Here is the DataFrame.

```<code>import pandas as pd
num1df = pd.DataFrame({'Number 1': [1, 4, 3, 2, 100]})
num2df = pd.DataFrame({'Number 2': [1, 2, 'NaN', 4, 5]})
num3df = pd.DataFrame({'Number 3': [1, 2, 3, 1000, 0]})
numsdf = pd.concat([num1df, num2df, num3df], axis=1, join="inner")
print(numsdf)
</code>```
```<code>   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3      NaN         3
3         2        4      1000
4       100        5         0
</code>```

I want to be able to do the follow addition. Column Number 1 row 4 plus column Number 3 row 3 = Column Number 2 row 2. 100 + 1000 = 1100 (the answer should be in place of the NaN)

This should be the expected outcome:

```<code>   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3     1100         3
3         2        4      1000
4       100        5         0
</code>```

How would I do that? I cannot figure it out.

答:
```<code>foo = numsdf.iloc[4, 0]
bar = numsdf.iloc[3, 2]
numsdf.at[2, 'Number 2'] = foo + bar
</code>```

Output:

```<code>   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3     1100         3
3         2        4      1000
4       100        5         0
</code>```

Body:
Due to misunderstanding using my real scenario I am going to create one.

Here is the DataFrame.

import pandas as pd
num1df = pd.DataFrame({'Number 1': [1, 4, 3, 2, 100]})
num2df = pd.DataFrame({'Number 2': [1, 2, 'NaN', 4, 5]})
num3df = pd.DataFrame({'Number 3': [1, 2, 3, 1000, 0]})
numsdf = pd.concat([num1df, num2df, num3df], axis=1, join="inner")
print(numsdf)

   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3      NaN         3
3         2        4      1000
4       100        5         0

I want to be able to do the follow addition. Column Number 1 row 4 plus column Number 3 row 3 = Column Number 2 row 2. 100 + 1000 = 1100 (the answer should be in place of the NaN)

This should be the expected outcome:

   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3     1100         3
3         2        4      1000
4       100        5         0

How would I do that? I cannot figure it out.

Body:
foo = numsdf.iloc[4, 0]
bar = numsdf.iloc[3, 2]
numsdf.at[2, 'Number 2'] = foo + bar

Output:

   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3     1100         3
3         2        4      1000
4       100        5         0


问:
tidyverse , plyr and dplyr
I used to use dplyr everywhere, but have included some plyr functions . To be honest I do not know what the difference is or why things have changed . The same code results in different dataframes depending on whether I have imported plyr or tidyverse .
What I wanted to have is a dataframe named newborn_stat  containing unique pids in each row  and a new c_pos column.

```<code>raw_file_contents<- data.frame( pid=c(1,2,2,3,3), C_SYMP=c("Y","N","Y","N","N"))
newborn_stat<- raw_file_contents %>%
        group_by(pid) %>%
        summarise(c_pos= any( C_SYMP == "Y", na.rm = TRUE))
</code>```

instead I would get a data frame ,newborn_stat, of 1 rows
with c_pos equal to TRUE.
If I use dplyr::  with the group_by and summarise , I think I get the right answer.
Why does this happen?
I have been using a Rmd notebook, so when I tried to run the previous chunk containing this line, things didn't work.

答:
Exactly as you explain in your answer, the issue is the difference in the behavior of plyr::summarize() and dplyr::summarize(). To make this clear I've just put the results of your example here.

library(plyr)
library(dplyr)

data.frame(pid = c(1, 2, 2, 3, 3),
           C_SYMP = c("Y", "N", "Y", "N", "N")) %>%
  dplyr::group_by(pid) %>%
  plyr::summarise(c_pos = any(C_SYMP == "Y", na.rm = TRUE))
#>   c_pos
#> 1  TRUE

data.frame(pid = c(1, 2, 2, 3, 3),
           C_SYMP = c("Y", "N", "Y", "N", "N")) %>%
  dplyr::group_by(pid) %>%
  dplyr::summarise(c_pos = any(C_SYMP == "Y", na.rm = TRUE))
#> # A tibble: 3 x 2
#>     pid c_pos
#>   <dbl> <lgl>
#> 1     1 TRUE
#> 2     2 TRUE
#> 3     3 FALSE
```

Created on 2022-02-11 by the reprex package (v2.0.1)

Title: tidyverse , plyr and dplyr

Body:
I used to use dplyr everywhere, but have included some plyr functions . To be honest I do not know what the difference is or why things have changed . The same code results in different dataframes depending on whether I have imported plyr or tidyverse .
What I wanted to have is a dataframe named newborn_stat  containing unique pids in each row  and a new c_pos column.

raw_file_contents<- data.frame( pid=c(1,2,2,3,3), C_SYMP=c("Y","N","Y","N","N"))
newborn_stat<- raw_file_contents %>%
        group_by(pid) %>%
        summarise(c_pos= any( C_SYMP == "Y", na.rm = TRUE))

instead I would get a data frame ,newborn_stat, of 1 rows
with c_pos equal to TRUE.
If I use dplyr::  with the group_by and summarise , I think I get the right answer.
Why does this happen?
I have been using a Rmd notebook, so when I tried to run the previous chunk containing this line, things didn't work.

Body:
Exactly as you explain in your answer, the issue is the difference in the behavior of plyr::summarize() and dplyr::summarize(). To make this clear I've just put the results of your example here.

library(plyr)
library(dplyr)

data.frame(pid = c(1, 2, 2, 3, 3),
           C_SYMP = c("Y", "N", "Y", "N", "N")) %>%
  dplyr::group_by(pid) %>%
  plyr::summarise(c_pos = any(C_SYMP == "Y", na.rm = TRUE))
#>   c_pos
#> 1  TRUE

data.frame(pid = c(1, 2, 2, 3, 3),
           C_SYMP = c("Y", "N", "Y", "N", "N")) %>%
  dplyr::group_by(pid) %>%
  dplyr::summarise(c_pos = any(C_SYMP == "Y", na.rm = TRUE))
#> # A tibble: 3 x 2
#>     pid c_pos
#>   <dbl> <lgl>
#> 1     1 TRUE
#> 2     2 TRUE
#> 3     3 FALSE

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
ChromeDriver console application hide
I have created a player which will automate chrome using selenium and ChromeDriver in C#. It's working fine.

Issue what I am facing is, when it creates an object for ChromDriver, it will start ChromeDriver application, which gets pop up and then Chrome will load. It's perfect as that application is loading that chrome for me.

Is there anyway, that I can open that ChromeDriver hidden?

答:
If you want to hide the console that is opened when launching chrome, firefox, etc.. you will need a helper class like this:

static class WindowsUtils
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);

```<code>[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

// Delegate to filter which windows to include
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

/// <summary> Get the text for the window pointed to by hWnd </summary>
public static string GetWindowText(IntPtr hWnd)
{
    int size = GetWindowTextLength(hWnd);
    if (size > 0)
    {
        var builder = new StringBuilder(size + 1);
        GetWindowText(hWnd, builder, builder.Capacity);
        return builder.ToString();
    }

    return String.Empty;
}

/// <summary> Find all windows that match the given filter </summary>
/// <param name="filter"> A delegate that returns true for windows
///    that should be returned and false for windows that should
///    not be returned </param>
public static IEnumerable<IntPtr> FindWindows(EnumWindowsProc filter)
{
    IntPtr found = IntPtr.Zero;
    List<IntPtr> windows = new List<IntPtr>();

    EnumWindows(delegate (IntPtr wnd, IntPtr param)
    {
        if (filter(wnd, param))
        {
            // only add the windows that pass the filter
            windows.Add(wnd);
        }

        // but return true here so that we iterate all windows
        return true;
    }, IntPtr.Zero);

    return windows;
}

/// <summary> Find all windows that contain the given title text </summary>
/// <param name="titleText"> The text that the window title must contain. </param>
public static IEnumerable<IntPtr> FindWindowsWithText(string titleText)
{
    return FindWindows(delegate (IntPtr wnd, IntPtr param)
    {
        return GetWindowText(wnd).Contains(titleText);
    });
}
</code>```

}

An then you can create your Selenium driver like this (also hidding the Firefox window).. If you want to use Chrome only have to do some minor changes... I prefreer Firefox because Chrome sometimes don't work with headless option:

```<code>    FirefoxOptions options = new FirefoxOptions();
    options.SetPreference("permissions.default.image", 2); //prevent download images
    options.AddArguments(new string[] { "--headless", "'--disable-gpu'" }); //no window, no gpu
    driver = new FirefoxDriver(options);
    WindowsUtils.ShowWindow(WindowsUtils.FindWindowsWithText("geckodriver.exe").FirstOrDefault(), 0); //0 to hide, 1 to show
</code>```

Title: ChromeDriver console application hide

Body:
If you want to hide the console that is opened when launching chrome, firefox, etc.. you will need a helper class like this:

static class WindowsUtils
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

// Delegate to filter which windows to include
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

/// <summary> Get the text for the window pointed to by hWnd </summary>
public static string GetWindowText(IntPtr hWnd)
{
    int size = GetWindowTextLength(hWnd);
    if (size > 0)
    {
        var builder = new StringBuilder(size + 1);
        GetWindowText(hWnd, builder, builder.Capacity);
        return builder.ToString();
    }

    return String.Empty;
}

/// <summary> Find all windows that match the given filter </summary>
/// <param name="filter"> A delegate that returns true for windows
///    that should be returned and false for windows that should
///    not be returned </param>
public static IEnumerable<IntPtr> FindWindows(EnumWindowsProc filter)
{
    IntPtr found = IntPtr.Zero;
    List<IntPtr> windows = new List<IntPtr>();

    EnumWindows(delegate (IntPtr wnd, IntPtr param)
    {
        if (filter(wnd, param))
        {
            // only add the windows that pass the filter
            windows.Add(wnd);
        }

        // but return true here so that we iterate all windows
        return true;
    }, IntPtr.Zero);

    return windows;
}

/// <summary> Find all windows that contain the given title text </summary>
/// <param name="titleText"> The text that the window title must contain. </param>
public static IEnumerable<IntPtr> FindWindowsWithText(string titleText)
{
    return FindWindows(delegate (IntPtr wnd, IntPtr param)
    {
        return GetWindowText(wnd).Contains(titleText);
    });
}

}

An then you can create your Selenium driver like this (also hidding the Firefox window).. If you want to use Chrome only have to do some minor changes... I prefreer Firefox because Chrome sometimes don't work with headless option:

    FirefoxOptions options = new FirefoxOptions();
    options.SetPreference("permissions.default.image", 2); //prevent download images
    options.AddArguments(new string[] { "--headless", "'--disable-gpu'" }); //no window, no gpu
    driver = new FirefoxDriver(options);
    WindowsUtils.ShowWindow(WindowsUtils.FindWindowsWithText("geckodriver.exe").FirstOrDefault(), 0); //0 to hide, 1 to show


问:
Recursive division over a list
I'm looking to divide every element of an list recursivly like this.

a_list = [1, 2, 3, 4, 5]
so the returns would be 1/(2/(3/(4/5)))

```<code>def c(y):

    if not y:
        return 1  # division by 1 don't matter

    return c(y[1:])[0] / c(y[2:])[1]  # Not allowed
</code>```

答:
Yours fixed and some mostly non-recursive alternatives (@9769953's fixed, and some by me):

```<code>for y in [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]:
    print(y)

    def c(y):
        if not y:
            return 1
        return y[0] / c(y[1:])
    print(c(y))

    from functools import reduce
    print(reduce(lambda a, b: b / a, reversed(y)))

    from math import prod
    print(prod(y[::2]) / prod(y[1::2]))

    z = 1
    for x in reversed(y):
        z = x / z
    print(z)

    def d(y):
        y = iter(y)
        try:
            return next(y) / d(y)
        except StopIteration:
            return 1
    print(d(y))

    print()
</code>```

Output showing the two test cases and the results of the five solutions (Try it online!):

```<code>[1, 2, 3, 4, 5]
1.875
1.875
1.875
1.875
1.875

[1, 2, 3, 4, 5, 6]
0.3125
0.3125
0.3125
0.3125
0.3125
</code>```

Title: Recursive division over a list

Body:
I'm looking to divide every element of an list recursivly like this.

a_list = [1, 2, 3, 4, 5]
so the returns would be 1/(2/(3/(4/5)))

def c(y):

    if not y:
        return 1  # division by 1 don't matter

    return c(y[1:])[0] / c(y[2:])[1]  # Not allowed

Body:
Yours fixed and some mostly non-recursive alternatives (@9769953's fixed, and some by me):

for y in [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]:
    print(y)

    def c(y):
        if not y:
            return 1
        return y[0] / c(y[1:])
    print(c(y))

    from functools import reduce
    print(reduce(lambda a, b: b / a, reversed(y)))

    from math import prod
    print(prod(y[::2]) / prod(y[1::2]))

    z = 1
    for x in reversed(y):
        z = x / z
    print(z)

    def d(y):
        y = iter(y)
        try:
            return next(y) / d(y)
        except StopIteration:
            return 1
    print(d(y))

    print()

Output showing the two test cases and the results of the five solutions (Try it online!):

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

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


问:
flutter app (android) builds app bundle, but there are some warnings
flutter buid appbundle suceeds, but there are some warnings:

Note: /Users/mateus/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_analytics-9.1.0/android/src/main/java/io/flutter/plugins/firebase/analytics/FlutterFirebaseAnalyticsPlugin.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

Note: /Users/mateus/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_analytics-9.1.0/android/src/main/java/io/flutter/plugins/firebase/analytics/FlutterFirebaseAnalyticsPlugin.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

How can I correct them? I tried to recompile as suggested but wasn't able

答:
Those errors are from the firebase analytics plugin and have nothing to do with your code.

Here are the issues you can follow, when there's a fix you'll hear about it there:
Issue one, Issue two and Issue three.


问:
strtok never gets NULL value, and ignores code after the while loop
I am writing a program right now that tokenizes multiple strings from a text file.

I have a while loop that continues to run until the end of the file. And nested in that loop, I have another while loop using strtok() to tokenize strings.

But, in my nested while loop with strtok(), I test with an if statement to see if I get NULL at the end of a string, but I never receive the NULL value. After the nested loop, it seems to break out of both loops, and also skips code outside of the main while loop, and ends my program with return 0;.

```<code>#include<iostream>
#include<fstream>
#include<string.h>
#include<iomanip>

using namespace std;

int main(int argc, char* argv[])
{
    //variable declarations
    ifstream inputfile;
    ofstream outputfile;
    char line[100];
    char* ptr;

    //check how many arguments in command line
    cout << "argc: " << argc << endl << endl;

    //check if there is input and output command line argument
    if (argc < 3)
    {
        cout << "missing input and output files";
    }
    cout << argv[1] << endl;
    cout << argv[2] << endl << endl;
    //cout <<"Null: " << NULL << endl;

    //opens input file from command line argument
    inputfile.open(argv[1]);

    //opens output file from command line argument
    outputfile.open(argv[2]);

    //check if input file is open
    if (!inputfile)
    {
        cout << "file not open"<< endl;
    }

    //check for input
    while (!inputfile.eof())
    {

        //inputfile = input, getline, line = output, 100 = delimiter
        //grabs the line.
        inputfile.getline(line, 100);

        //check for line
        cout << line << endl;

        //grabs first word
        ptr = strtok(line, " ");
        cout << ptr << endl;

        //loops until null
        while(ptr!=NULL)
        {
            //grabs other words until end of line
            ptr = strtok(NULL, " ");
            cout << ptr << endl;

            if (ptr==NULL)
            {
                cout << "hit NULL" << endl;
            }

        }

        cout << "afterloop" << endl;

    }

    cout << "end";

    return 0;
}
</code>```

答:
In:

```<code>cout << ptr << endl;

//loops until null
while(ptr!=NULL)
</code>```

And again in:

```<code>cout << ptr << endl;

if (ptr==NULL)
</code>```

You're printing ptr before checking if it's null. It's undefined behaviour to hand operator<< a null character pointer. Rather, it assumes that the pointer points to a valid null-terminated string.

You cannot rely on any behaviour that comes out of this. The program is free to crash, pretend to work, or anywhere in between. The compiler is free to assume this doesn't happen, which can lead to it marking code as unreachable, among other optimizations, meaning you can see some unintuitive results.

While I would suggest using a better string-splitting approach, you can fix what you have by rearranging your code a bit:

```<code>//grabs first word
ptr = strtok(line, " ");

//loops until null
while(ptr!=NULL)
{
    // +++ We know we have a word, now we can print it.
    cout << ptr << endl;

    //grabs other words until end of line
    ptr = strtok(NULL, " ");
    // +++ We can remove the print from here because it will be printed on the next iteration if we have another word.

    if (ptr==NULL)
    {
        cout << "hit NULL" << endl;
    }
}
</code>```

Body:
I am writing a program right now that tokenizes multiple strings from a text file.

I have a while loop that continues to run until the end of the file. And nested in that loop, I have another while loop using strtok() to tokenize strings.

But, in my nested while loop with strtok(), I test with an if statement to see if I get NULL at the end of a string, but I never receive the NULL value. After the nested loop, it seems to break out of both loops, and also skips code outside of the main while loop, and ends my program with return 0;.

#include<iostream>
#include<fstream>
#include<string.h>
#include<iomanip>

using namespace std;

int main(int argc, char* argv[])
{
    //variable declarations
    ifstream inputfile;
    ofstream outputfile;
    char line[100];
    char* ptr;

    //check how many arguments in command line
    cout << "argc: " << argc << endl << endl;

    //check if there is input and output command line argument
    if (argc < 3)
    {
        cout << "missing input and output files";
    }
    cout << argv[1] << endl;
    cout << argv[2] << endl << endl;
    //cout <<"Null: " << NULL << endl;

    //opens input file from command line argument
    inputfile.open(argv[1]);

    //opens output file from command line argument
    outputfile.open(argv[2]);

    //check if input file is open
    if (!inputfile)
    {
        cout << "file not open"<< endl;
    }

    //check for input
    while (!inputfile.eof())
    {

        //inputfile = input, getline, line = output, 100 = delimiter
        //grabs the line.
        inputfile.getline(line, 100);

        //check for line
        cout << line << endl;

        //grabs first word
        ptr = strtok(line, " ");
        cout << ptr << endl;

        //loops until null
        while(ptr!=NULL)
        {
            //grabs other words until end of line
            ptr = strtok(NULL, " ");
            cout << ptr << endl;

            if (ptr==NULL)
            {
                cout << "hit NULL" << endl;
            }

        }

        cout << "afterloop" << endl;

    }

    cout << "end";

    return 0;
}

Body:
In:

cout << ptr << endl;

//loops until null
while(ptr!=NULL)

And again in:

cout << ptr << endl;

if (ptr==NULL)

You're printing ptr before checking if it's null. It's undefined behaviour to hand operator<< a null character pointer. Rather, it assumes that the pointer points to a valid null-terminated string.

You cannot rely on any behaviour that comes out of this. The program is free to crash, pretend to work, or anywhere in between. The compiler is free to assume this doesn't happen, which can lead to it marking code as unreachable, among other optimizations, meaning you can see some unintuitive results.

While I would suggest using a better string-splitting approach, you can fix what you have by rearranging your code a bit:

//grabs first word
ptr = strtok(line, " ");

//loops until null
while(ptr!=NULL)
{
    // +++ We know we have a word, now we can print it.
    cout << ptr << endl;

    //grabs other words until end of line
    ptr = strtok(NULL, " ");
    // +++ We can remove the print from here because it will be printed on the next iteration if we have another word.

    if (ptr==NULL)
    {
        cout << "hit NULL" << endl;
    }
}


问:
How to convert mixed time formats with strings to military time?
I have a variable that needs to be converted to military time. This variable is very messy because it lacks consistency in the format.

Here is an example of what might be found in the variable.

```<code>x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")
</code>```

So far I had some success in getting everything in a more consistent format with RegEx:

```<code>x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")
</code>```

As you can see I get: "0.9305555555555547", "1520", "1000", "0.125", "1525"

The problem is the decimals need to be multiplied by 2400 to get back to military time but I also don't want to multiply integers (since those are already in military time).

x is essentially a variable in a dataframe.

I was thinking about using if/else logic but I don't know how to implement that.

To clarify, I want:

Input: "0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 15:25"

Output: "2233", "1520", "1000", "0300", "1525"

答:
After the pre-processing you did with your regexes, you can implement if/else logic here by using str_detect()

```<code>x <- ifelse(str_detect(x, "\\."),
            as.integer(as.numeric(x) * 2400),
            as.integer(x)) %>%
  sprintf("%04d", .)
</code>```

This will return your desired output as character

Then you could do something like this to parse it to POSIXct

```<code>x <- as.POSIXct(x,
         format = "%H%M",
         origin = "1970-01-01",
         tz = "UTC")
</code>```

Body:
I have a variable that needs to be converted to military time. This variable is very messy because it lacks consistency in the format.

Here is an example of what might be found in the variable.

x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")

So far I had some success in getting everything in a more consistent format with RegEx:

x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")

As you can see I get: "0.9305555555555547", "1520", "1000", "0.125", "1525"

The problem is the decimals need to be multiplied by 2400 to get back to military time but I also don't want to multiply integers (since those are already in military time).

x is essentially a variable in a dataframe.

I was thinking about using if/else logic but I don't know how to implement that.

To clarify, I want:

Input: "0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 15:25"

Output: "2233", "1520", "1000", "0300", "1525"

Body:
After the pre-processing you did with your regexes, you can implement if/else logic here by using str_detect()

x <- ifelse(str_detect(x, "\\."),
            as.integer(as.numeric(x) * 2400),
            as.integer(x)) %>%
  sprintf("%04d", .)

This will return your desired output as character

Then you could do something like this to parse it to POSIXct

x <- as.POSIXct(x,
         format = "%H%M",
         origin = "1970-01-01",
         tz = "UTC")


问:
Azure File Share - Recursive Directory Search like os.walk
I am writing a Python script to download files from Azure File Share. The structure of the File Share is as below:

```<code>/analytics/Part1/file1.txt
/analytics/Part1/file2.txt
/analytics/mainfile.txt
/analytics/Part1/Part1_1/file11.txt
</code>```

I tried to use the following lines in my script but it looks for files and directories only at the root directory level.

fileshareclient = ShareClient(
    account_url=args.get('AccountURL'),
    credential=args.get('SASKey'),
    share_name=args.get('FileShare')
)

fileLst = list(
    fileshareclient.list_directories_and_files('analytics')
)
```
<p>The output is:</p>
```/analytics/mainfile.txt  --> File
/analytics/Part1 --> Dir
```

But, I am looking for something like os.walk() function in Python here to achieve this recursive directory walk. Any idea if such function is available in Azure File Service Python API?

答:
Honestly, I find it a bit confusing having to deal with two different methods to do "the same thing". I prefer to instantiate the directory client via the from_connection_string method, as in the following approach.

Python Requirements

```<code>pip install azure-storage-file-share==12.6.0
</code>```

Python Script

FileShare file listing:

```<code>from azure.storage.fileshare import ShareServiceClient, ShareDirectoryClient, ShareFileClient
from typing import Iterator, Union
import os

def list_files(
    dir_path: str,
    share_name: str,
    connection_string: str,
    include_properties: bool = False,
    recursive: bool = True
) -> Iterator[Union[str, dict]]:
    """
    List files from FileShare on Azure Storage Account.

    Parameters
    ----------
    dir_path: str
        Directory path to list files from.
    share_name: str
        FileShare name.
    connection_string: str
        Connection string.
    include_properties: bool
        Specifies that file properties to be returned in the response.
    recursive: bool
        Specifies whether to list files recursively.

    Returns
    -------
    files_list: Iterator[Union[str, dict]]
        List of filepaths from FileShare.
        Returns a list of strings (Iterator[str]) if 'include_properties' is false.
        Otherwise, return a list of dictionaries (Iterator[dict]).

    Notes
    -----
    This method only lists files, ignoring empty directories.

    References
    ----------
    .. [1] Method 'list_files': https://stackoverflow.com/a/71088269/16109419
    .. [2] Recursive files listing: https://stackoverflow.com/a/66543222/16109419
    """
    dir_client = ShareDirectoryClient.from_connection_string(
        conn_str=connection_string,
        share_name=share_name,
        directory_path=dir_path
    )

    # Listing files from current directory path:
    for file in dir_client.list_directories_and_files():
        name, is_directory = file['name'], file['is_directory']
        path = os.path.join(dir_path, name)

        if is_directory:
            if recursive:
                # Listing files recursively:
                childrens = list_files(
                    dir_path=path,
                    share_name=share_name,
                    connection_string=connection_string,
                    include_properties=include_properties,
                    recursive=recursive
                )

                for child in childrens:
                    yield child
        else:
            if include_properties:
                file_client = ShareFileClient.from_connection_string(
                    conn_str=connection_string,
                    share_name=share_name,
                    file_path=path
                )

                yield file_client.get_file_properties()
            else:
                yield path
</code>```

FileShare file listing example:

```<code>def main() -> None:
    connection_string = "<your-conn-str>"
    share_name = "<your-share-name>"
    dir_path = ""  # Leave it empty to list files from root directory.

    files_list = list_files(
        dir_path=dir_path,
        share_name=share_name,
        connection_string=connection_string,
        include_properties=False,
        recursive=True
    )

    for i, f in enumerate(files_list, start=1):
        print(i, f)

if __name__ == '__main__':
    main()
</code>```

Body:
I am writing a Python script to download files from Azure File Share. The structure of the File Share is as below:

/analytics/Part1/file1.txt
/analytics/Part1/file2.txt
/analytics/mainfile.txt
/analytics/Part1/Part1_1/file11.txt

I tried to use the following lines in my script but it looks for files and directories only at the root directory level.

fileshareclient = ShareClient(
    account_url=args.get('AccountURL'),
    credential=args.get('SASKey'),
    share_name=args.get('FileShare')
)

fileLst = list(
    fileshareclient.list_directories_and_files('analytics')
)

The output is:

/analytics/mainfile.txt  --> File
/analytics/Part1 --> Dir

But, I am looking for something like os.walk() function in Python here to achieve this recursive directory walk. Any idea if such function is available in Azure File Service Python API?

Body:
Honestly, I find it a bit confusing having to deal with two different methods to do "the same thing". I prefer to instantiate the directory client via the from_connection_string method, as in the following approach.

Python Requirements

pip install azure-storage-file-share==12.6.0

Python Script

FileShare file listing:

from azure.storage.fileshare import ShareServiceClient, ShareDirectoryClient, ShareFileClient
from typing import Iterator, Union
import os

def list_files(
    dir_path: str,
    share_name: str,
    connection_string: str,
    include_properties: bool = False,
    recursive: bool = True
) -> Iterator[Union[str, dict]]:
    """
    List files from FileShare on Azure Storage Account.

    Parameters
    ----------
    dir_path: str
        Directory path to list files from.
    share_name: str
        FileShare name.
    connection_string: str
        Connection string.
    include_properties: bool
        Specifies that file properties to be returned in the response.
    recursive: bool
        Specifies whether to list files recursively.

    Returns
    -------
    files_list: Iterator[Union[str, dict]]
        List of filepaths from FileShare.
        Returns a list of strings (Iterator[str]) if 'include_properties' is false.
        Otherwise, return a list of dictionaries (Iterator[dict]).

    Notes
    -----
    This method only lists files, ignoring empty directories.

    References
    ----------
    .. [1] Method 'list_files': https://stackoverflow.com/a/71088269/16109419
    .. [2] Recursive files listing: https://stackoverflow.com/a/66543222/16109419
    """
    dir_client = ShareDirectoryClient.from_connection_string(
        conn_str=connection_string,
        share_name=share_name,
        directory_path=dir_path
    )

    # Listing files from current directory path:
    for file in dir_client.list_directories_and_files():
        name, is_directory = file['name'], file['is_directory']
        path = os.path.join(dir_path, name)

        if is_directory:
            if recursive:
                # Listing files recursively:
                childrens = list_files(
                    dir_path=path,
                    share_name=share_name,
                    connection_string=connection_string,
                    include_properties=include_properties,
                    recursive=recursive
                )

                for child in childrens:
                    yield child
        else:
            if include_properties:
                file_client = ShareFileClient.from_connection_string(
                    conn_str=connection_string,
                    share_name=share_name,
                    file_path=path
                )

                yield file_client.get_file_properties()
            else:
                yield path

FileShare file listing example:

def main() -> None:
    connection_string = "<your-conn-str>"
    share_name = "<your-share-name>"
    dir_path = ""  # Leave it empty to list files from root directory.

    files_list = list_files(
        dir_path=dir_path,
        share_name=share_name,
        connection_string=connection_string,
        include_properties=False,
        recursive=True
    )

    for i, f in enumerate(files_list, start=1):
        print(i, f)

if __name__ == '__main__':
    main()


问:
HMAC-SHA1 in Rust
I'm trying to apply HMAC-SHA1 in order to check some content but I'm unable to make it work.

These are the tests I have:

```<code>#[cfg(test)]
mod tests {

    use crypto::hmac::Hmac;
    use crypto::mac::Mac;

    use crypto::sha1::Sha1;
    use std::str::from_utf8;

    const BODY_CONTENT: &'static str = r#"bodystring"#;
    const KEY: &[u8] = b"secret_key";
    const COMPUTED_HMAC: &'static str = "97049623b0e5d20bf6beb5313d80600e3d6abe56";

    #[test]
    fn test_hmac_sha1() {
        let mut mac= Hmac::new(Sha1::new(), KEY);
        mac.input(BODY_CONTENT.as_bytes());
        let result = mac.result();
        let code = result.code();
        assert_eq!(COMPUTED_HMAC.as_bytes(), code);
        assert_eq!(COMPUTED_HMAC, from_utf8(&code).unwrap_or("failed"));
    }

    #[test]
    fn test_hmac_sha1_direct() {
        let hash = hmacsha1::hmac_sha1(KEY, BODY_CONTENT.as_bytes());
        assert_eq!(COMPUTED_HMAC.as_bytes(), hash);
        assert_eq!(COMPUTED_HMAC, from_utf8(&hash).unwrap_or("failed"));
    }
}
</code>```

I've used this website in order to get the COMPUTED_HMAC by using one string (BODY_CONTENT) and a secret key (KEY).

As you can see, I'm trying to leverage both rust-crypto and hmac-sha1 crates and I obtain the same result with both of them.

The thing is that this result doesn't match with what I get in the website (97049623b0e5d20bf6beb5313d80600e3d6abe56) and the tests fail. You may think that the website is wrong but that's not the case as I'm using it to validate some other hashes generated by Github (I'm working in a Github App) and it works.

Then, obviously, I'm missing some step here but I'm unable to figure it out and I would really appreciate your help.

答:
Thanks Francis and Robert, this code works for me.

```<code>code.iter().map(|b| format!("{:02x}", b)).collect::<Vec<_>>().join("")
</code>```

That line returns: "97049623b0e5d20bf6beb5313d80600e3d6abe56" as String

Title: HMAC-SHA1 in Rust

Body:
I'm trying to apply HMAC-SHA1 in order to check some content but I'm unable to make it work.

These are the tests I have:

#[cfg(test)]
mod tests {

    use crypto::hmac::Hmac;
    use crypto::mac::Mac;

    use crypto::sha1::Sha1;
    use std::str::from_utf8;

    const BODY_CONTENT: &'static str = r#"bodystring"#;
    const KEY: &[u8] = b"secret_key";
    const COMPUTED_HMAC: &'static str = "97049623b0e5d20bf6beb5313d80600e3d6abe56";

    #[test]
    fn test_hmac_sha1() {
        let mut mac= Hmac::new(Sha1::new(), KEY);
        mac.input(BODY_CONTENT.as_bytes());
        let result = mac.result();
        let code = result.code();
        assert_eq!(COMPUTED_HMAC.as_bytes(), code);
        assert_eq!(COMPUTED_HMAC, from_utf8(&code).unwrap_or("failed"));
    }

    #[test]
    fn test_hmac_sha1_direct() {
        let hash = hmacsha1::hmac_sha1(KEY, BODY_CONTENT.as_bytes());
        assert_eq!(COMPUTED_HMAC.as_bytes(), hash);
        assert_eq!(COMPUTED_HMAC, from_utf8(&hash).unwrap_or("failed"));
    }
}

I've used this website in order to get the COMPUTED_HMAC by using one string (BODY_CONTENT) and a secret key (KEY).

As you can see, I'm trying to leverage both rust-crypto and hmac-sha1 crates and I obtain the same result with both of them.

The thing is that this result doesn't match with what I get in the website (97049623b0e5d20bf6beb5313d80600e3d6abe56) and the tests fail. You may think that the website is wrong but that's not the case as I'm using it to validate some other hashes generated by Github (I'm working in a Github App) and it works.

Then, obviously, I'm missing some step here but I'm unable to figure it out and I would really appreciate your help.

Body:
Thanks Francis and Robert, this code works for me.

code.iter().map(|b| format!("{:02x}", b)).collect::<Vec<_>>().join("")

That line returns: "97049623b0e5d20bf6beb5313d80600e3d6abe56" as String