问:
How to add signature to email in google apps script generated email with proper formatting
I have an email sender linked to a google sheets file as follows:

```<code>function sendEmail(form) {
const sSheet = SpreadsheetApp.getActiveSpreadsheet();
const file = DriveApp.getFileById(sSheet.getId());
const documentUrl = file.getUrl();

var toEmail = form.toAddress;
var ccEmail = form.ccAddress;
var subject = form.subject;
var message = form.message;

const folderId = "";
const ssId = sSheet.getId();
const returnFlag= 'blob';

if (form.process == "sendHotelRegistration"){
var fileName = "Hotel Registration Form";
var sheetId = sSheet.getSheetByName("Hotel Registration form").getSheetId();
var sheet= sSheet.getSheetByName("Hotel Registration form");
sheet.showSheet();
} else if (form.process == "updateRegistry"){
var fileName = "Hotel Contract Document";
var sheetId = "All";
}

var pdfFile = createPDF(folderId, ssId, fileName, sheetId, returnFlag);

MailApp.sendEmail({
    to:toEmail,
    cc:ccEmail,
    subject:subject,
    body:message,
    attachments:[pdfFile]
    });
}
</code>```

I have 2 issues:

1- I want to add a signature including a logo to the email. So I need the company name in bold and the logo. I cannot work out how to insert an image or to have formatted text. I have read through a lot of posts and the following google documentation: https://developers.google.com/apps-script/reference/mail/mail-app

And I have tried to implement this in my code but I cannot get it to work.

Secondly, I have a variable set in my email body which retrieves a value from my google sheet document as follows:

```<code>html.contractorName = data.contractorName.toLowerCase();
</code>```

However, I don't actually want lower case, I want title / proper case. I cannot though work out how to implement this, particularly bearing in mind that the contractor name may be two, three, four names long.

Thanks

答: You're seeing the Reference error because you don't have the Gmail API enabled. You can enable the API in the developer console. You will then have to enable it for the individual script you're working on. Clicking Resources > Advanced Google services then flip the on-switch next to Gmail API

Body:
I have an email sender linked to a google sheets file as follows:

function sendEmail(form) {
const sSheet = SpreadsheetApp.getActiveSpreadsheet();
const file = DriveApp.getFileById(sSheet.getId());
const documentUrl = file.getUrl();

var toEmail = form.toAddress;
var ccEmail = form.ccAddress;
var subject = form.subject;
var message = form.message;

const folderId = "";
const ssId = sSheet.getId();
const returnFlag= 'blob';

if (form.process == "sendHotelRegistration"){
var fileName = "Hotel Registration Form";
var sheetId = sSheet.getSheetByName("Hotel Registration form").getSheetId();
var sheet= sSheet.getSheetByName("Hotel Registration form");
sheet.showSheet();
} else if (form.process == "updateRegistry"){
var fileName = "Hotel Contract Document";
var sheetId = "All";
}

var pdfFile = createPDF(folderId, ssId, fileName, sheetId, returnFlag);

MailApp.sendEmail({
    to:toEmail,
    cc:ccEmail,
    subject:subject,
    body:message,
    attachments:[pdfFile]
    });
}

I have 2 issues:

1- I want to add a signature including a logo to the email. So I need the company name in bold and the logo. I cannot work out how to insert an image or to have formatted text. I have read through a lot of posts and the following google documentation: https://developers.google.com/apps-script/reference/mail/mail-app

And I have tried to implement this in my code but I cannot get it to work.

Secondly, I have a variable set in my email body which retrieves a value from my google sheet document as follows:

html.contractorName = data.contractorName.toLowerCase();

However, I don't actually want lower case, I want title / proper case. I cannot though work out how to implement this, particularly bearing in mind that the contractor name may be two, three, four names long.

Thanks


来源: stackexchange

问:
Grep for value in string over x milliseconds
I know how to grep and find all the lines in a file that contain a simple string:

```<code>cat my_log.log | grep 'Completed 200 OK in'
</code>```

That returns results similar to the following:

```<code>various info... Completed 200 OK in 250ms various info...
various info... Completed 200 OK in 112ms various info...
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...
various info... Completed 200 OK in 33ms various info...
various info... Completed 200 OK in 100ms various info...
</code>```

I'd like to take it a step further and only return the lines where the milliseconds (ms) is over 1000.

Is this possible with grep?  Other posts suggest using sed but I'm curious if it is possible to do this with grep.

答:
The right way to do this is awk for both a regexp and arithmetic comparison, e.g. with GNU awk for the 3rd arg to match():

```<code>$ awk 'match($0,/Completed 200 OK in ([0-9]+)/,a) && (a[1] > 1000)' file
various info... Completed 200 OK in 6000ms various info...

$ awk 'match($0,/Completed 200 OK in ([0-9]+)/,a) && (a[1] >= 1000)' file
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...

$ awk 'match($0,/Completed 200 OK in ([0-9]+)/,a) && (a[1] >= 112)' file
various info... Completed 200 OK in 250ms various info...
various info... Completed 200 OK in 112ms various info...
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...
</code>```

or if you don't have GNU awk then with any awk:

```<code>$ awk '{ms=$0} sub(/.*Completed 200 OK in /,"",ms) && (ms+0 > 1000)' file
various info... Completed 200 OK in 6000ms various info...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know how to grep and find all the lines in a file that contain a simple string:

cat my_log.log | grep 'Completed 200 OK in'

That returns results similar to the following:

various info... Completed 200 OK in 250ms various info...
various info... Completed 200 OK in 112ms various info...
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...
various info... Completed 200 OK in 33ms various info...
various info... Completed 200 OK in 100ms various info...

I'd like to take it a step further and only return the lines where the milliseconds (ms) is over 1000.

Is this possible with grep?  Other posts suggest using sed but I'm curious if it is possible to do this with grep.

Body:
The right way to do this is awk for both a regexp and arithmetic comparison, e.g. with GNU awk for the 3rd arg to match():

$ awk 'match($0,/Completed 200 OK in ([0-9]+)/,a) && (a[1] > 1000)' file
various info... Completed 200 OK in 6000ms various info...

$ awk 'match($0,/Completed 200 OK in ([0-9]+)/,a) && (a[1] >= 1000)' file
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...

$ awk 'match($0,/Completed 200 OK in ([0-9]+)/,a) && (a[1] >= 112)' file
various info... Completed 200 OK in 250ms various info...
various info... Completed 200 OK in 112ms various info...
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...

or if you don't have GNU awk then with any awk:

$ awk '{ms=$0} sub(/.*Completed 200 OK in /,"",ms) && (ms+0 > 1000)' file
various info... Completed 200 OK in 6000ms various info...


问:
listen to events from dynamic vue components
How would you listen to an event emitted by a dynamically created component instance?

In the example, the top component is added in the DOM, while the second is dynamically created in javascript.

Vue.component("button-counter", {
  data: function() {
    return {
      count: this.initial_count
    }
  },
  props: ['initial_count'],
  methods: {
    add: function() {
      this.count++
        this.$emit('myevent', this.count)
    }
  },
  template: '<button v-on:click="add">You clicked me {{ count }} times.</button>'
})

let app = new Vue({
  el: "#app",
  data() {
    return {
      initial_count: 10,
    }
  },
  mounted: function() {
    let initial_count = this.initial_count

    let ButtonCounterComponentClass = Vue.extend({
      data: function() {
        return {}
      },
      render(h) {
        return h("button-counter", {
          props: {
            initial_count: initial_count
          }
        })
      }
    })
    let button_counter_instance = new ButtonCounterComponentClass()
    button_counter_instance.$mount()
    button_counter_instance.$on('myevent', function(count) {
      console.log('listened!')
      this.say(count)
    })
    this.$refs.container.appendChild(button_counter_instance.$el)
  },
  methods: {
    say: function(message) {
      alert(message)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>

<div id="app">
    <button-counter initial_count=20 v-on:myevent="say"></button-counter>
    <div ref='container'></div>
</div></code>```

答:
If I've understood what you want then you just need to listen for the event on the inner component and pass it on.

I've used arrow functions in a couple of places to avoid problems with this bindings. Otherwise I've tried to leave your code unchanged as much as possible. Changes marked with ****.

Vue.component("button-counter", {
  data: function() {
    return {
      count: this.initial_count
    }
  },
  props: ['initial_count'],
  methods: {
    add: function() {
      this.count++
        this.$emit('myevent', this.count)
    }
  },
  template: '<button v-on:click="add">You clicked me {{ count }} times.</button>'
})

let app = new Vue({
  el: "#app",
  data() {
    return {
      initial_count: 10,
    }
  },
  mounted: function() {
    let initial_count = this.initial_count

    let ButtonCounterComponentClass = Vue.extend({
      data: function() {
        return {}
      },
      render(h) {
        return h("button-counter", {
          props: {
            initial_count: initial_count
          },
          // **** Added this ****
          on: {
            myevent: count => {
              this.$emit('myevent', count);
            }
          }
          // ****
        })
      }
    })
    let button_counter_instance = new ButtonCounterComponentClass()
    button_counter_instance.$mount()
    // **** Changed the next line ****
    button_counter_instance.$on('myevent', count => {
      console.log('listened!')
      this.say(count)
    })
    this.$refs.container.appendChild(button_counter_instance.$el)
  },
  methods: {
    say: function(message) {
      alert(message)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>

<div id="app">
    <button-counter initial_count=20 v-on:myevent="say"></button-counter>
    <div ref='container'></div>
</div></code>```

It's important to understand that button_counter_instance is not an instance of your button-counter component. You've wrapped it in another component, albeit a component that doesn't add any extra DOM nodes. So listening on the wrapper component is not the same as listening on button-counter.

Docs for what you can pass to h: https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth

Body:
How would you listen to an event emitted by a dynamically created component instance?

In the example, the top component is added in the DOM, while the second is dynamically created in javascript.

Vue.component("button-counter", {
  data: function() {
    return {
      count: this.initial_count
    }
  },
  props: ['initial_count'],
  methods: {
    add: function() {
      this.count++
        this.$emit('myevent', this.count)
    }
  },
  template: '<button v-on:click="add">You clicked me {{ count }} times.</button>'
})

let app = new Vue({
  el: "#app",
  data() {
    return {
      initial_count: 10,
    }
  },
  mounted: function() {
    let initial_count = this.initial_count

    let ButtonCounterComponentClass = Vue.extend({
      data: function() {
        return {}
      },
      render(h) {
        return h("button-counter", {
          props: {
            initial_count: initial_count
          }
        })
      }
    })
    let button_counter_instance = new ButtonCounterComponentClass()
    button_counter_instance.$mount()
    button_counter_instance.$on('myevent', function(count) {
      console.log('listened!')
      this.say(count)
    })
    this.$refs.container.appendChild(button_counter_instance.$el)
  },
  methods: {
    say: function(message) {
      alert(message)
    }
  }
})

    <button-counter initial_count=20 v-on:myevent="say"></button-counter>

Body:
If I've understood what you want then you just need to listen for the event on the inner component and pass it on.

I've used arrow functions in a couple of places to avoid problems with this bindings. Otherwise I've tried to leave your code unchanged as much as possible. Changes marked with ****.

Vue.component("button-counter", {
  data: function() {
    return {
      count: this.initial_count
    }
  },
  props: ['initial_count'],
  methods: {
    add: function() {
      this.count++
        this.$emit('myevent', this.count)
    }
  },
  template: '<button v-on:click="add">You clicked me {{ count }} times.</button>'
})

let app = new Vue({
  el: "#app",
  data() {
    return {
      initial_count: 10,
    }
  },
  mounted: function() {
    let initial_count = this.initial_count

    let ButtonCounterComponentClass = Vue.extend({
      data: function() {
        return {}
      },
      render(h) {
        return h("button-counter", {
          props: {
            initial_count: initial_count
          },
          // **** Added this ****
          on: {
            myevent: count => {
              this.$emit('myevent', count);
            }
          }
          // ****
        })
      }
    })
    let button_counter_instance = new ButtonCounterComponentClass()
    button_counter_instance.$mount()
    // **** Changed the next line ****
    button_counter_instance.$on('myevent', count => {
      console.log('listened!')
      this.say(count)
    })
    this.$refs.container.appendChild(button_counter_instance.$el)
  },
  methods: {
    say: function(message) {
      alert(message)
    }
  }
})

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>

<div id="app">
    <button-counter initial_count=20 v-on:myevent="say"></button-counter>
    <div ref='container'></div>
</div>

It's important to understand that button_counter_instance is not an instance of your button-counter component. You've wrapped it in another component, albeit a component that doesn't add any extra DOM nodes. So listening on the wrapper component is not the same as listening on button-counter.

Docs for what you can pass to h: https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth


问:
RegEx for an autocomplete feature
I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.

Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)

I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.

This is the expression I have come up with.

```<code>const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/
</code>```

It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last * in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."

The pattern I have in my head written in words is:

group of one or more characters/digits/spaces/quotation marks

followed by a colon

followed by an optional space

followed by another group of one or more characters/digits/space/quotation marks

followed by a space (after the value)

followed by one or more characters (this is the operator)

How do I solve this problem?

Title: RegEx for an autocomplete feature

Body:
I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.

Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)

I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.

This is the expression I have come up with.

const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/

It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last * in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."

The pattern I have in my head written in words is:

group of one or more characters/digits/spaces/quotation marks

followed by a colon

followed by an optional space

followed by another group of one or more characters/digits/space/quotation marks

followed by a space (after the value)

followed by one or more characters (this is the operator)

How do I solve this problem?

Body:
Here you go, try this out

^(?:"[^"]*"|[^\s:]+):[ ](?:"[^"]*"|[^\s:]+)[ ](?:A(?:N(?:D(?:[ ](*SKIP)(?!))?)?)?|O(?:R(?:[ ](*SKIP)(?!))?)?)?

https://regex101.com/r/neUQ0g/1

Explained

 ^                             # BOS
 (?:                           # Attribute
      "
      [^"]*
      "
   |
      [^\s:]+
 )
 :
 [ ]
 (?:                           # Value
      "
      [^"]*
      "
   |
      [^\s:]+
 )
 [ ]                           # Start matching after Attribute: Value + space
 (?:                           # Operator
      A
      (?:
           N
           (?:
                D
                (?:                           # Stop matching after 'AND '
                     [ ]
                     (*SKIP)
                     (?!)
                )?
           )?
      )?
   |
      O
      (?:
           R
           (?:                           # Stop matching after 'OR '
                [ ]
                (*SKIP)
                (?!)
           )?
      )?
 )?


问:
How to fix 'Failure loading test' in TeamCity Flutter build
I'm trying to build a CICD instance of TeamCity for a Flutter project. Currently I have the command scripts to clone the Flutter repository and run Flutter doctor. However, my last step is not working -- running Flutter test.

Prior to the infinite loading attempt of the default widget_test.dart, a stacktrace comes out:

```<code>[19:05:51]  [Step 2/2] Shell: #0      _WebSocketImpl.connect.<anonymous closure>.error (dart:_http/websocket_impl.dart:1049:9)
[19:05:51]  [Step 2/2] Shell: #1      _WebSocketImpl.connect.<anonymous closure> (dart:_http/websocket_impl.dart:1058:14)
[19:05:51]  [Step 2/2] Shell: #2      _rootRunUnary (dart:async/zone.dart:1132:38)
[19:05:51]  [Step 2/2] Shell: #3      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
[19:05:51]  [Step 2/2] Shell: #4      _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
[19:05:51]  [Step 2/2] Shell: #5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
[19:05:51]  [Step 2/2] Shell: #6      Future._propagateToListeners (dart:async/future_impl.dart:668:32)
[19:05:51]  [Step 2/2] Shell: #7      Future._completeWithValue (dart:async/future_impl.dart:483:5)
[19:05:51]  [Step 2/2] Shell: #8      Future.wait.<anonymous closure> (dart:async/future.dart:400:22)
[19:05:51]  [Step 2/2] Shell: #9      _rootRunUnary (dart:async/zone.dart:1132:38)
[19:05:51]  [Step 2/2] Shell: #10     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
[19:05:51]  [Step 2/2] Shell: #11     _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
[19:05:51]  [Step 2/2] Shell: #12     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
[19:05:51]  [Step 2/2] Shell: #13     Future._propagateToListeners (dart:async/future_impl.dart:668:32)
[19:05:51]  [Step 2/2] Shell: #14     Future._completeWithValue (dart:async/future_impl.dart:483:5)
[19:05:51]  [Step 2/2] Shell: #15     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:513:7)
[19:05:51]  [Step 2/2] Shell: #16     _rootRun (dart:async/zone.dart:1124:13)
[19:05:51]  [Step 2/2] Shell: #17     _CustomZone.run (dart:async/zone.dart:1021:19)
[19:05:51]  [Step 2/2] Shell: #18     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
[19:05:51]  [Step 2/2] Shell: #19     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
[19:05:51]  [Step 2/2] Shell: #20     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
[19:05:51]  [Step 2/2] Shell: #21     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
</code>```

The final error is

```<code>Failed to load "/root/TeamCity/buildAgent/work/700f5361a835c53d/test/widget_test.dart":
[19:10:50]  [Step 2/2]   Test never connected to test harness.
[19:10:50]  [Step 2/2]   Test: /root/TeamCity/buildAgent/work/700f5361a835c53d/test/widget_test.dart
[19:10:50]  [Step 2/2]   Shell: /root/TeamCity/buildAgent/work/700f5361a835c53d/flutter/bin/cache/artifacts/engine/linux-x64/flutter_tester
</code>```

Anyone run into a fix for this: Flutter is still pretty new and there aren't many documents on how to set this up.

Any help is greatly appreciated. Thanks

This is for a new TeamCity build. I've added the environment variable below as the proxy bit of flutter doctor was complaining:

env.NO_PROXY=localhost,127.0.0.1

答:
My teams default agent was overriding the variable env variable no_proxy
Within the command script I simply appended the 127.0.0.1 to the existing env variable and it worked.

Body:
I'm trying to build a CICD instance of TeamCity for a Flutter project. Currently I have the command scripts to clone the Flutter repository and run Flutter doctor. However, my last step is not working -- running Flutter test.

Prior to the infinite loading attempt of the default widget_test.dart, a stacktrace comes out:

[19:05:51]  [Step 2/2] Shell: #0      _WebSocketImpl.connect.<anonymous closure>.error (dart:_http/websocket_impl.dart:1049:9)
[19:05:51]  [Step 2/2] Shell: #1      _WebSocketImpl.connect.<anonymous closure> (dart:_http/websocket_impl.dart:1058:14)
[19:05:51]  [Step 2/2] Shell: #2      _rootRunUnary (dart:async/zone.dart:1132:38)
[19:05:51]  [Step 2/2] Shell: #3      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
[19:05:51]  [Step 2/2] Shell: #4      _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
[19:05:51]  [Step 2/2] Shell: #5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
[19:05:51]  [Step 2/2] Shell: #6      Future._propagateToListeners (dart:async/future_impl.dart:668:32)
[19:05:51]  [Step 2/2] Shell: #7      Future._completeWithValue (dart:async/future_impl.dart:483:5)
[19:05:51]  [Step 2/2] Shell: #8      Future.wait.<anonymous closure> (dart:async/future.dart:400:22)
[19:05:51]  [Step 2/2] Shell: #9      _rootRunUnary (dart:async/zone.dart:1132:38)
[19:05:51]  [Step 2/2] Shell: #10     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
[19:05:51]  [Step 2/2] Shell: #11     _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
[19:05:51]  [Step 2/2] Shell: #12     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
[19:05:51]  [Step 2/2] Shell: #13     Future._propagateToListeners (dart:async/future_impl.dart:668:32)
[19:05:51]  [Step 2/2] Shell: #14     Future._completeWithValue (dart:async/future_impl.dart:483:5)
[19:05:51]  [Step 2/2] Shell: #15     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:513:7)
[19:05:51]  [Step 2/2] Shell: #16     _rootRun (dart:async/zone.dart:1124:13)
[19:05:51]  [Step 2/2] Shell: #17     _CustomZone.run (dart:async/zone.dart:1021:19)
[19:05:51]  [Step 2/2] Shell: #18     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
[19:05:51]  [Step 2/2] Shell: #19     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
[19:05:51]  [Step 2/2] Shell: #20     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
[19:05:51]  [Step 2/2] Shell: #21     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)

The final error is

Failed to load "/root/TeamCity/buildAgent/work/700f5361a835c53d/test/widget_test.dart":
[19:10:50]  [Step 2/2]   Test never connected to test harness.
[19:10:50]  [Step 2/2]   Test: /root/TeamCity/buildAgent/work/700f5361a835c53d/test/widget_test.dart
[19:10:50]  [Step 2/2]   Shell: /root/TeamCity/buildAgent/work/700f5361a835c53d/flutter/bin/cache/artifacts/engine/linux-x64/flutter_tester

Anyone run into a fix for this: Flutter is still pretty new and there aren't many documents on how to set this up.

Any help is greatly appreciated. Thanks

This is for a new TeamCity build. I've added the environment variable below as the proxy bit of flutter doctor was complaining:

env.NO_PROXY=localhost,127.0.0.1


问:
How to use optimisticResponse in Apollo Angular with refetchQueries
I'm trying to utilize Apollo's Optimistic UI but I can't get it to work as expected. To test it I've set up a breakpoint on the server so the response can be stalled. I would expect to see mutation result in changes in the list, but the whole thing waits for the response from the server. What am I doing wrong?

This is Angular 7, Apollo-angular client 2.4.0 for Angular:

```<code>"apollo-angular": "^1.5.0",
    "apollo-angular-link-http": "^1.6.0",
    "apollo-cache-inmemory": "^1.3.2",
    "apollo-client": "^2.4.0",
    "apollo-link": "^1.2.11",
    "apollo-link-error": "^1.1.10",
</code>```

To see if the item is in the cache I've called this first and it returns an ID as expected:

```<code>let testID = defaultDataIdFromObject(mail);
console.log('found in cache: ', testID); // outputs the correct ID
(e.g. found in cache)
</code>```

Console output:

Email:Cl4weDliM2QyZjQ1OTU2ZTZlMmZmOTAyMjRkYTkxNmE2MjI1ZDk2NWM3MDcAAAFrAUPhyTB4OWIzZDJmNDU5NTZlNmUyZmY5MDIyNGRhOTE2YTYyMjVkOTY1YzcwNzVB

This is the complete query:

```<code>this.trashEmailGQL.mutate({
      id: mail.id,
      table: Table.ARCHIVE
    },{
      refetchQueries: [{
        query: this.getEmailsGQL.document,
        variables: {table: Table.ARCHIVE}
      },
      {
        query: this.getEmailsGQL.document,
        variables: {table: Table.TRASH}
      }],
      optimisticResponse:{
        __typename:'Mutation',
        trashEmail:{
          __typename:"Email",
          id:mail.id,
          fromEmail:mail.fromEmail,
          fromName:mail.fromName,
          fromAddress:mail.fromAddress,
          cc: mail.cc,
          bcc: [],
          replyTo:mail.replyTo,
          body:mail.body,
          contentType:mail.contentType,
          draftId:"",
          read:mail.read,
          inReplyTo:mail.inReplyTo,
          inReferences:mail.inReferences,
          created:mail.created
        }
      }
    }).subscribe(({data}) => {
      console.log('Trashed email response: ', data);
    }, (err) => {
      this.errorService.handleError(err);
    });
</code>```

I would expect that Apollo would return results from the cache and update the table before the server returns any response.

答:
Finally figured it out. Apollo 2.x doesn't support delete mutations out of the box. So manual deletion from cache needs to be performed. The solution doesn't look too good (code explosion) but it's currently better than having a rock thrown in your back. </p>

<p>Supposedly version 3.x should address this issue but currently, this is the solution I found works one would expect. </p>

```<code>this.trashEmailGQL.mutate({
      id: mail.id,
      table: Table.ARCHIVE
    },
    {
        refetchQueries: [{
          query: this.getEmailsGQL.document,
          variables: {table: Table.ARCHIVE}
        },
        {
          query: this.getEmailsGQL.document,
          variables: {table: Table.TRASH}
        }],
        optimisticResponse:{
          __typename:'Mutation',
          trashEmail:{
            __typename:"Email",
            id:mail.id,
            fromEmail:mail.fromEmail,
            fromName:mail.fromName,
            fromAddress:mail.fromAddress,
            cc: mail.cc,
            bcc: [],
            replyTo:mail.replyTo,
            body:mail.body,
            contentType:mail.contentType,
            draftId:"",
            read:mail.read,
            inReplyTo:mail.inReplyTo,
            inReferences:mail.inReferences,
            created:mail.created
          }
        },
        update: (store, {data :{trashedEmail}}) => {
          const data = store.readQuery({query: this.getEmailsGQL.document, variables: {table: Table.ARCHIVE}});
          if (data && data.hasOwnProperty('getEmails')) {
            let cacheList:Email[] = data['getEmails'];
            let foundItemIndex = cacheList.findIndex(i => i.id === mail.id);
            if (foundItemIndex > -1) {
              cacheList.splice(foundItemIndex,1)
              data['getEmails'] = cacheList
              store.writeQuery({query: this.getEmailsGQL.document, variables: {table: Table.ARCHIVE}, data:data});
            }
          }
        }
      }
     ).subscribe(({data}) => {
      console.log('Trashed email response: ', data);
    }, (err) => {
      this.errorService.handleError(err);
    });
</code>```

Body:
I'm trying to utilize Apollo's Optimistic UI but I can't get it to work as expected. To test it I've set up a breakpoint on the server so the response can be stalled. I would expect to see mutation result in changes in the list, but the whole thing waits for the response from the server. What am I doing wrong?

This is Angular 7, Apollo-angular client 2.4.0 for Angular:

"apollo-angular": "^1.5.0",
    "apollo-angular-link-http": "^1.6.0",
    "apollo-cache-inmemory": "^1.3.2",
    "apollo-client": "^2.4.0",
    "apollo-link": "^1.2.11",
    "apollo-link-error": "^1.1.10",

To see if the item is in the cache I've called this first and it returns an ID as expected:

let testID = defaultDataIdFromObject(mail);
console.log('found in cache: ', testID); // outputs the correct ID
(e.g. found in cache)

Console output:

Email:Cl4weDliM2QyZjQ1OTU2ZTZlMmZmOTAyMjRkYTkxNmE2MjI1ZDk2NWM3MDcAAAFrAUPhyTB4OWIzZDJmNDU5NTZlNmUyZmY5MDIyNGRhOTE2YTYyMjVkOTY1YzcwNzVB

This is the complete query:

this.trashEmailGQL.mutate({
      id: mail.id,
      table: Table.ARCHIVE
    },{
      refetchQueries: [{
        query: this.getEmailsGQL.document,
        variables: {table: Table.ARCHIVE}
      },
      {
        query: this.getEmailsGQL.document,
        variables: {table: Table.TRASH}
      }],
      optimisticResponse:{
        __typename:'Mutation',
        trashEmail:{
          __typename:"Email",
          id:mail.id,
          fromEmail:mail.fromEmail,
          fromName:mail.fromName,
          fromAddress:mail.fromAddress,
          cc: mail.cc,
          bcc: [],
          replyTo:mail.replyTo,
          body:mail.body,
          contentType:mail.contentType,
          draftId:"",
          read:mail.read,
          inReplyTo:mail.inReplyTo,
          inReferences:mail.inReferences,
          created:mail.created
        }
      }
    }).subscribe(({data}) => {
      console.log('Trashed email response: ', data);
    }, (err) => {
      this.errorService.handleError(err);
    });

I would expect that Apollo would return results from the cache and update the table before the server returns any response.

Body:
Finally figured it out. Apollo 2.x doesn't support delete mutations out of the box. So manual deletion from cache needs to be performed. The solution doesn't look too good (code explosion) but it's currently better than having a rock thrown in your back.

Supposedly version 3.x should address this issue but currently, this is the solution I found works one would expect.

this.trashEmailGQL.mutate({
      id: mail.id,
      table: Table.ARCHIVE
    },
    {
        refetchQueries: [{
          query: this.getEmailsGQL.document,
          variables: {table: Table.ARCHIVE}
        },
        {
          query: this.getEmailsGQL.document,
          variables: {table: Table.TRASH}
        }],
        optimisticResponse:{
          __typename:'Mutation',
          trashEmail:{
            __typename:"Email",
            id:mail.id,
            fromEmail:mail.fromEmail,
            fromName:mail.fromName,
            fromAddress:mail.fromAddress,
            cc: mail.cc,
            bcc: [],
            replyTo:mail.replyTo,
            body:mail.body,
            contentType:mail.contentType,
            draftId:"",
            read:mail.read,
            inReplyTo:mail.inReplyTo,
            inReferences:mail.inReferences,
            created:mail.created
          }
        },
        update: (store, {data :{trashedEmail}}) => {
          const data = store.readQuery({query: this.getEmailsGQL.document, variables: {table: Table.ARCHIVE}});
          if (data && data.hasOwnProperty('getEmails')) {
            let cacheList:Email[] = data['getEmails'];
            let foundItemIndex = cacheList.findIndex(i => i.id === mail.id);
            if (foundItemIndex > -1) {
              cacheList.splice(foundItemIndex,1)
              data['getEmails'] = cacheList
              store.writeQuery({query: this.getEmailsGQL.document, variables: {table: Table.ARCHIVE}, data:data});
            }
          }
        }
      }
     ).subscribe(({data}) => {
      console.log('Trashed email response: ', data);
    }, (err) => {
      this.errorService.handleError(err);
    });


问:
Android videoview - immersive - overlapping controllers
I have a videoview on my app and Im using gogole as a reference to make the video player full screen:

https://developer.android.com/training/system-ui/immersive#java

I was following the instruccion from the above website and i was able to make the videoplayer full screen but I gt a weird problem with my media controller and the  device controller(they overlp) and don't know how to fixed any ideas what is the problem.

```<code>public class VideoPlayer extends AppCompatActivity {

    VideoView videoView;
    MediaController mediaController;
    private String TAG = VideoPlayer.class.getSimpleName();
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_player_activity);

        videoView = (VideoView) findViewById(R.id.videoView);
        mediaController = new MediaController(this);
        videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.video1);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.start();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }

    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                            | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
    private void showSystemUI() {
        Log.e(TAG, "111");
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }
}
</code>```

答:
I think the following might be happening:

From https://developer.android.com/training/system-ui/immersive#EnableFullscreen

Note: When you use the SYSTEM_UI_FLAG_IMMERSIVE_STICKY flag, a swipe causes the system UI > to temporarily appear in a semi-transparent state, but no flags are cleared and your
system UI visibility change listeners are not triggered.

From https://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_IMMERSIVE_STICKY

When system bars are hidden in immersive mode, they can be revealed temporarily with system gestures, such as swiping from the top of the screen. These transient system bars will overlay app’s content, may have some degree of transparency, and will automatically hide after a short timeout.

From https://developer.android.com/training/system-ui/immersive#leanback

The lean back mode is for fullscreen experiences in which users won't be interacting heavily with the screen, such as while watching a video.

When users want to bring back the system bars, they simply tap the screen anywhere.

To enable lean back mode, call setSystemUiVisibility() and pass SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION.

Based on the preceding information I think removing the SYSTEM_UI_FLAG_IMMERSIVE_STICKY might help. I have not actually tried using this code but I hope this information helped.

Body:
I have a videoview on my app and Im using gogole as a reference to make the video player full screen:

https://developer.android.com/training/system-ui/immersive#java

I was following the instruccion from the above website and i was able to make the videoplayer full screen but I gt a weird problem with my media controller and the  device controller(they overlp) and don't know how to fixed any ideas what is the problem.

public class VideoPlayer extends AppCompatActivity {

    VideoView videoView;
    MediaController mediaController;
    private String TAG = VideoPlayer.class.getSimpleName();
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_player_activity);

        videoView = (VideoView) findViewById(R.id.videoView);
        mediaController = new MediaController(this);
        videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.video1);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.start();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }

    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                            | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
    private void showSystemUI() {
        Log.e(TAG, "111");
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }
}


问:
pdflatex hang after large number of figures
I have a script that generates a number of figures and puts them in the appendix of a report, e.g.

```<code>Appendix
********

.. figure:: images/generated/image_1.png
.. figure:: images/generated/image_2.png
.. figure:: images/generated/image_3.png
... etc
</code>```

It looks like after a large number (~50) of images, my pdflatex command will hang, and point to one of the graphics in my .tex file around here

```<code>...
\begin(figure)[htbp]
\centering
\noindent\sphinxincludegraphics{{image_49}.png}
\end{figure}

\begin(figure)[htbp]
\centering
\noindent\sphinxincludegraphics{{image_50}.png} <--- here
\end{figure}

\begin(figure)[htbp]
\centering
\noindent\sphinxincludegraphics{{image_51}.png}
\end{figure}
...
</code>```

When pdflatex fails I can't really figure out what to make from the console output, I get a number of these lines which seem to be good news

```<code><image_48.png, id=451, 411.939pt x 327.3831pt>
File: image_48.png Graphic file (type png)
<use image_48.png>
Package pdftex.def Info: image_48.png  used on input line 1251.
(pdftex.def)             Requested size: 411.93797pt x 327.3823pt.

<image_49.png, id=452, 411.939pt x 327.3831pt>
File: image_49.png Graphic file (type png)
<use image_49.png>
Package pdftex.def Info: image_49.png  used on input line 1257.
(pdftex.def)             Requested size: 411.93797pt x 327.3823pt.
</code>```

Then after the last successful image (~50) it starts outputting

```<code>! Output loop---100 consecutive dead cycles.
\end@float ...loatpenalty <-\@Mii \penalty -\@Miv
                                                  \@tempdima \prevdepth \vbo...
l.1258 \end{figure}

I've concluded that your \output is awry; it never does a
\shipout, so I'm shipping \box255 out myself. Next time
increase \maxdeadcycles if you want me to be more patient!

[9
! Undefined control sequence.
\reserved@a ->\@nil

l.1258 \end{figure}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.
</code>```

If all I do is reduce the number of figures, it will run and produce a pdf without issue. Is there a hard limit to the number of images a section can have? Is there somewhere else I can look in the build log to narrow down why this is happening?

答:
I had this problem and the above suggestions did not work. I was however able to get it to run just fine by inserting subsections which may or may not compatible with your objectives. The script generates code as follows which is then input into another code snippet to preview the generated images,
( I'm generating svg plots from c++, converting to png, and previewing essentially raw data for selection into later plots that go into an actual document not just a collection of images )</p>

```<code>\subsection{svghappy2.tyrosine.png}
\begin{figure}[htbp]
\testplot{svghappy2_tyrosine.png}
\caption{svghappy2.tyrosine.png}
\end{figure}

\subsection{svghappy2.valine.png}
\begin{figure}[htbp]
\testplot{svghappy2_valine.png}
\caption{svghappy2.valine.png}
\end{figure}
</code>```

Body:
I have a script that generates a number of figures and puts them in the appendix of a report, e.g.

Appendix
********

.. figure:: images/generated/image_1.png
.. figure:: images/generated/image_2.png
.. figure:: images/generated/image_3.png
... etc

It looks like after a large number (~50) of images, my pdflatex command will hang, and point to one of the graphics in my .tex file around here

...
\begin(figure)[htbp]
\centering
\noindent\sphinxincludegraphics{{image_49}.png}
\end{figure}

\begin(figure)[htbp]
\centering
\noindent\sphinxincludegraphics{{image_50}.png} <--- here
\end{figure}

\begin(figure)[htbp]
\centering
\noindent\sphinxincludegraphics{{image_51}.png}
\end{figure}
...

When pdflatex fails I can't really figure out what to make from the console output, I get a number of these lines which seem to be good news

<image_48.png, id=451, 411.939pt x 327.3831pt>
File: image_48.png Graphic file (type png)
<use image_48.png>
Package pdftex.def Info: image_48.png  used on input line 1251.
(pdftex.def)             Requested size: 411.93797pt x 327.3823pt.

<image_49.png, id=452, 411.939pt x 327.3831pt>
File: image_49.png Graphic file (type png)
<use image_49.png>
Package pdftex.def Info: image_49.png  used on input line 1257.
(pdftex.def)             Requested size: 411.93797pt x 327.3823pt.

Then after the last successful image (~50) it starts outputting

! Output loop---100 consecutive dead cycles.
\end@float ...loatpenalty <-\@Mii \penalty -\@Miv
                                                  \@tempdima \prevdepth \vbo...
l.1258 \end{figure}

I've concluded that your \output is awry; it never does a
\shipout, so I'm shipping \box255 out myself. Next time
increase \maxdeadcycles if you want me to be more patient!

[9
! Undefined control sequence.
\reserved@a ->\@nil

l.1258 \end{figure}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

If all I do is reduce the number of figures, it will run and produce a pdf without issue. Is there a hard limit to the number of images a section can have? Is there somewhere else I can look in the build log to narrow down why this is happening?

Body:
I had this problem and the above suggestions did not work. I was however able to get it to run just fine by inserting subsections which may or may not compatible with your objectives. The script generates code as follows which is then input into another code snippet to preview the generated images,
( I'm generating svg plots from c++, converting to png, and previewing essentially raw data for selection into later plots that go into an actual document not just a collection of images )

\subsection{svghappy2.tyrosine.png}
\begin{figure}[htbp]
\testplot{svghappy2_tyrosine.png}
\caption{svghappy2.tyrosine.png}
\end{figure}

\subsection{svghappy2.valine.png}
\begin{figure}[htbp]
\testplot{svghappy2_valine.png}
\caption{svghappy2.valine.png}
\end{figure}


问:
Display Vuetify tooltip on disabled button
I am having difficulty displaying a tooltip on a button that is disabled with Vuetify.

I've made sure the tooltip can be displayed when the button is enabled, this works as expected. I think that this question is related, but I'm not well-versed enough to know if this applies to a v-btn. I attempted to create a custom class and add that to the specific v-btn element but I did not have any luck.

Example HTML

  <v-app id="inspire">
    <v-container fluid class="text-xs-center">
      <v-layout
        flex
        justify-space-between
        row
        wrap
      >
        <v-flex xs12>
          <v-btn @click="show = !show">toggle</v-btn>
        </v-flex>

        <v-flex xs12 class="mt-5">
          <v-tooltip v-model="show" top>
            <template v-slot:activator="{ on }">
              <v-btn disabled icon v-on="on">
                <v-icon color="grey lighten-1">shopping_cart</v-icon>
              </v-btn>
            </template>
            Programmatic tooltip
          </v-tooltip>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>

```

<h1>Example JavaScript</h1>

```new Vue({
  el: '#app',
  data () {
    return {
      show: false
    }
  }
})
```

https://codepen.io/anon/pen/ZNqpOW?editors=1010

I'm expecting that the tooltip can be displayed when hovering over a disabled button. I'm hoping to use this to explain why the button is disabled.

答:
Not sure if this is the absolute best way but I was able to get a tooltip on a disabled button by wrapping it in a div tag:

Codepen

<v-tooltip v-model="show" top>
  <template v-slot:activator="{ on }">

      <v-btn disabled icon>
        <v-icon color="grey lighten-1">shopping_cart</v-icon>
      </v-btn>

  </template>
  Programmatic tooltip
</v-tooltip>
```

Body:
I am having difficulty displaying a tooltip on a button that is disabled with Vuetify.

I've made sure the tooltip can be displayed when the button is enabled, this works as expected. I think that this question is related, but I'm not well-versed enough to know if this applies to a v-btn. I attempted to create a custom class and add that to the specific v-btn element but I did not have any luck.

Example HTML

  <v-app id="inspire">
    <v-container fluid class="text-xs-center">
      <v-layout
        flex
        justify-space-between
        row
        wrap
      >
        <v-flex xs12>
          <v-btn @click="show = !show">toggle</v-btn>
        </v-flex>

        <v-flex xs12 class="mt-5">
          <v-tooltip v-model="show" top>
            <template v-slot:activator="{ on }">
              <v-btn disabled icon v-on="on">
                <v-icon color="grey lighten-1">shopping_cart</v-icon>
              </v-btn>
            </template>
            Programmatic tooltip
          </v-tooltip>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>

Example JavaScript

new Vue({
  el: '#app',
  data () {
    return {
      show: false
    }
  }
})

https://codepen.io/anon/pen/ZNqpOW?editors=1010

I'm expecting that the tooltip can be displayed when hovering over a disabled button. I'm hoping to use this to explain why the button is disabled.

Body:
Not sure if this is the absolute best way but I was able to get a tooltip on a disabled button by wrapping it in a div tag:

Codepen

<v-tooltip v-model="show" top>
  <template v-slot:activator="{ on }">
    <div v-on="on">
      <v-btn disabled icon>
        <v-icon color="grey lighten-1">shopping_cart</v-icon>
      </v-btn>
    </div>
  </template>
  <span>Programmatic tooltip</span>
</v-tooltip>


问:
du summary isn't equal to sum of the elements
The directory contains normal files in normal directories, no symlinks and remote fs (it's actually a maildir++ storage, so not even sparse files are expected). I don't readily see how it's possible that the summary of the directory sizes is significantly larger than the total du provides:

```<code>$ du * .[a-zA-Z]* -bsc | tail -n1
2722800257      total

$ du * .[a-zA-Z]* -b | awk '{sum+=$1} END {print sum}'
3341577554
</code>```

Reality seems to match the larger number.

答:
Your second command du -b ... | awk ... is overstating the total because it counts subdirectory sizes multiple times.  Each subdirectory size is counted on its own, then counted again as part of the size of each of its ancestor directories.

It's easier to see what's happening in a small example like this, on a filesystem where an empty directory happens to consume 4KB:

```<code>$ mkdir -p foo/bar/baz

$ du -bsc foo
12288   foo
12288   total

$ du -b foo
4096    foo/bar/baz
8192    foo/bar
12288   foo

$ du -b foo | awk '{t += $1} END {print t}'
24576
</code>```

Body:
The directory contains normal files in normal directories, no symlinks and remote fs (it's actually a maildir++ storage, so not even sparse files are expected). I don't readily see how it's possible that the summary of the directory sizes is significantly larger than the total du provides:

$ du * .[a-zA-Z]* -bsc | tail -n1
2722800257      total

$ du * .[a-zA-Z]* -b | awk '{sum+=$1} END {print sum}'
3341577554

Reality seems to match the larger number.

Body:
Your second command du -b ... | awk ... is overstating the total because it counts subdirectory sizes multiple times.  Each subdirectory size is counted on its own, then counted again as part of the size of each of its ancestor directories.

It's easier to see what's happening in a small example like this, on a filesystem where an empty directory happens to consume 4KB:

$ mkdir -p foo/bar/baz

$ du -bsc foo
12288   foo
12288   total

$ du -b foo
4096    foo/bar/baz
8192    foo/bar
12288   foo

$ du -b foo | awk '{t += $1} END {print t}'
24576


问:
How to efficiently find a specific substring in PHP?
OK, I know how to do this but I'm interested in better/more elegant solutions (if any) for this problem.

Imagine I have the following string :

Mozilla/4.0 (compatible; MSIE 7.0;
  Windows NT 5.1; Trident/4.0; GTB6.6;
  Mozilla/4.0 (compatible; MSIE 6.0;
  Windows NT 5.1; SV1) ; .NET CLR
  1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)

I'm interested to find the highest MSIE version in that string (in that case 7.0).

Currently I use explode and preg_match a couple of times in combination with str_replace then I loop between matches and then compare the version string. It works but it's far from elegant. Any ideas on how to improve this?

Keep in mind that:

The string can have any number of MSIE occurrences (or even none)

MSIE is case insensitive

MSIE is followed by a white space (space, tab...) then by the version. The version can contain number letters and dots. The version string is ended by either a white space, a ; or the end of the line.

Thanks!

答: If you are trying to implement browser detection, it's a lot more complex than this.</p>

ContentLicense: CC BY-SA 3.0


问:
Is it possible to use xpath with nested loops?
So i am trying to parse some html with xpath.Here is how my page looks like

```<code><area id="a_0_0" alt="asd">
<area id="a_0_1" alt="asd">
<area id="a_1_0" alt="asd">
<area id="a_1_1" alt="asd">
</code>```

so is it possible to parse it with xpath ? or do i need to use something else ? I am a bit new to xpath here is what i've tried

```<code>doc.DocumentNode.SelectSingleNode("//area[@id='a_0_0']").Attributes["alt"].Value;//this is works

doc.DocumentNode.SelectSingleNode("//area[@id='a_0_[position() >=0 and position() <=1]']").Attributes["alt"].Value
doc.DocumentNode.SelectSingleNode("//area[@id='a_[position() >=0 and position() <=1]']_[position() >=0 and position() <=1]']").Attributes["alt"].Value
</code>```

答:
You can parse your xml to XDocument and benefit from linq.</p>

```<code>XDocument.Parse(xmlstring)
</code>```

Body:
So i am trying to parse some html with xpath.Here is how my page looks like

<area id="a_0_0" alt="asd">
<area id="a_0_1" alt="asd">
<area id="a_1_0" alt="asd">
<area id="a_1_1" alt="asd">

so is it possible to parse it with xpath ? or do i need to use something else ? I am a bit new to xpath here is what i've tried

doc.DocumentNode.SelectSingleNode("//area[@id='a_0_0']").Attributes["alt"].Value;//this is works

doc.DocumentNode.SelectSingleNode("//area[@id='a_0_[position() >=0 and position() <=1]']").Attributes["alt"].Value
doc.DocumentNode.SelectSingleNode("//area[@id='a_[position() >=0 and position() <=1]']_[position() >=0 and position() <=1]']").Attributes["alt"].Value

Body:
You can parse your xml to XDocument and benefit from linq.

XDocument.Parse(xmlstring)


问:
How to get online and offline device status in azure iot Hub using azure functions
get online and offline device status in azure iot Hub using azure functions</p>

答:
First configure which events to publish from your IoT hub.More specifically DeviceConnected and DeviceDisconnected event will solve your purpose.

Then finally implement EventHub Trigger in Azure function to get the events.


问:
Can TestFlight's "What to test" field be edited before the build is submitted?
This may be an obvious "No", but here goes...

I'm using TestFlight, and I like to add build notes in the "What to test" field on the TestFlight page in iTunes Connect. However, the only way any users will actually see those notes is if you're able to slip them in and hit "Save" before the build finishes processing. If you add them after that point, the users don't ever know "What to test" because neither the email notification nor the TestFlight app itself will show the notes! This is absolutely ridiculous, of course, so is there another way? It'd be great if you could add a build the way you add an app (i.e. before you actually submit anything).

答: You can change What to Test by simply created a new test group, changing the text, and clicking the Save button.  You will get a new public link to send out.</p>


问:
How to select number content in element and add commas with jquery or js
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

```<code><script type="text/javascript">
   $(document).ready(function () {
      // $("#price").toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      $('#price').html.toLocaleString('en');
   });
</script>
</code>```

Here's my element:

```<code><strong id="price"><%# Eval("OfferPrice") %></strong>
</code>```

Everything seems ok, can anyone help please. Thanks a lot!

答:
From MDN documentation :

```<code>parseFloat($('#price')).toLocaleString('en-US');
</code>```

You need to specify that the value of #price is of type number (float), then you can apply toLocalString() function with your desired formatting country.

Body:
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

Here's my element:

<%# Eval("OfferPrice") %>

Everything seems ok, can anyone help please. Thanks a lot!

Body:
From MDN documentation :

parseFloat($('#price')).toLocaleString('en-US');

You need to specify that the value of #price is of type number (float), then you can apply toLocalString() function with your desired formatting country.


问:
Storing word documents
I'm working on job site (using asp.net 3.5) in which a user can upload one or more resumes.
Database is sql server 2005.
Whats the recommendation regarding storage of these documents?
Shall i store it as a blob in the database or just store the path in database and keep the document in the physical folder?
Can someone please mention the pros and cons of each wrt performance and scalability?

Thanks!

答:
Storing files in the database gives you:

(+) easier house-keeping, no orphaned files on the disk

(+) consistent programming and access model (authorization)

(-) Database grows exorbitantly, which will increase backup time and disk space use to hold backup files

I don't think that either option scales better than the other. If you expect very large numbers of documents, you will hit limits regarding the number of files in a directory (either as an absolute limit, or because directory lookups begin to perform very poorly at a certain point).

OwnerDisplayName: Patrick

ContentLicense: CC BY-SA 2.5

Title: Storing word documents

OwnerDisplayName: cdonner

LastEditorDisplayName: cdonner


问:
C - read specific line from file
I'm trying to read a specific line from a file and I can get the line number but I'm not sure how to go about doing it, this is what I have so far:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
  FILE *file;
  file = fopen("temp.txt","r");
  char tmp[256]={0x0};
  char *tmpline;
  int numline = 1;
  while(file != NULL && fgets(tmp, sizeof(tmp),file) !=NULL)
  {
    tmpline = strstr(tmp,"status:green");

    if(tmpline) {
      printf("%d - %s", numline, tmpline);
    }

    numline++;
  }
  if (file != NULL) fclose(file);

  return 0;
}
</code>```

The test file looks like:

```<code>s1.server.com
127.0.0.1
status:green

s2.server.com
127.0.0.1
status:red

s3.server.com
127.0.0.1
status:red

s4.server.com
127.0.0.1
status:green
</code>```

The output that I have is:

```<code>3 - status:green
15 - status:green
</code>```

But what I really want it to show is:

```<code>s1.server.com
s4.server.com
</code>```

I want it to search for "status:green" then go back a few lines to show which server it belongs to

答:
If the test file (and production file) is well-formed then you can do something like the following (error checking left out for brevity!):

```<code>typedef struct _SERVERSTATUS
{
    char* name;
    char* ip;
    char* status;
} SERVERSTATUS;

SERVERSTATUS ss;

ss.name = calloc(256);
ss.ip = calloc(256);
ss.status = calloc(256);

while (!feof(file))
{
    fgets(ss.name, file);
    fgets(ss.ip, file);
    fgets(ss.status, file);

    if (!strcmp(ss.status, "status:green"))
       printf("%s\n", ss.name);
}

free(ss.name);
free(ss.ip);
free(ss.status);
</code>```

Edit: You also have to handle the whitespace between the file entries! That's, um, left as an exercise for the questioner

Title: C - read specific line from file

Body:
I'm trying to read a specific line from a file and I can get the line number but I'm not sure how to go about doing it, this is what I have so far:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
  FILE *file;
  file = fopen("temp.txt","r");
  char tmp[256]={0x0};
  char *tmpline;
  int numline = 1;
  while(file != NULL && fgets(tmp, sizeof(tmp),file) !=NULL)
  {
    tmpline = strstr(tmp,"status:green");

    if(tmpline) {
      printf("%d - %s", numline, tmpline);
    }

    numline++;
  }
  if (file != NULL) fclose(file);

  return 0;
}

The test file looks like:

s1.server.com
127.0.0.1
status:green

s2.server.com
127.0.0.1
status:red

s3.server.com
127.0.0.1
status:red

s4.server.com
127.0.0.1
status:green

The output that I have is:

3 - status:green
15 - status:green

But what I really want it to show is:

s1.server.com
s4.server.com

I want it to search for "status:green" then go back a few lines to show which server it belongs to

Body:
If the test file (and production file) is well-formed then you can do something like the following (error checking left out for brevity!):

typedef struct _SERVERSTATUS
{
    char* name;
    char* ip;
    char* status;
} SERVERSTATUS;

SERVERSTATUS ss;

ss.name = calloc(256);
ss.ip = calloc(256);
ss.status = calloc(256);

while (!feof(file))
{
    fgets(ss.name, file);
    fgets(ss.ip, file);
    fgets(ss.status, file);

    if (!strcmp(ss.status, "status:green"))
       printf("%s\n", ss.name);
}

free(ss.name);
free(ss.ip);
free(ss.status);

Edit: You also have to handle the whitespace between the file entries! That's, um, left as an exercise for the questioner


问:
Parse this CSV file and create without using Pandas?
I was able to figure out how to do this with Pandas, but without, I'm totally lost: I'm given two CSV files:

order_products:

```<code>order_id,product_id,add_to_cart_order,reordered
2,33120,1,1
2,28985,2,1
2,9327,3,0
2,45918,4,1
3,17668,1,1
3,46667,2,1
3,17461,4,1
3,32665,3,1
4,46842,1,0
</code>```

products:

```<code>product_id,product_name,aisle_id,department_id
9327,Garlic Powder,104,13
17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12
17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16
28985,Michigan Organic Kale,83,4
32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3
33120,Organic Egg Whites,86,16
45918,Coconut Butter,19,13
46667,Organic Ginger Root,83,4
46842,Plain Pre-Sliced Bagels,93,3
</code>```

I'm to then create a new table that lists for each department, the number of orders created for this department, the number of first orders, and the ratio of (number of first orders / number of orders) for that department

So the resulting table would look like:

```<code>department_id,number_of_orders,number_of_first_orders,percentage
3,2,1,0.50
4,2,0,0.00
12,1,0,0.00
13,2,1,0.50
16,2,0,0.00
</code>```

My solution involving Pandas:

```<code>orders = pd.read_csv("../insight_testsuite/tests/test_1/input/order_products.csv")
products = pd.read_csv("../insight_testsuite/tests/test_1/input/products.csv")

orders.drop(['add_to_cart_order'], axis=1, inplace=True)
products.drop(['aisle_id', 'product_name'], axis=1, inplace=True)

dep = pd.merge(orders, products)

dep = (dep.groupby('department_id')['reordered']
         .agg([('number_of_orders','size'),
               ('number_of_first_orders', lambda x: x.eq(0).sum())
               ])
         .reset_index())

dep['percentage'] = ("%.2f" %
   round((dep['number_of_first_orders'] / dep['number_of_orders']), 2))
</code>```

But with regular Python, AFAIK, you can only go through the CSV file line by line and evaluate from there. So I'm not sure how you can perform that kind of analysis without using Pandas.

Body:
I was able to figure out how to do this with Pandas, but without, I'm totally lost: I'm given two CSV files:

order_products:

order_id,product_id,add_to_cart_order,reordered
2,33120,1,1
2,28985,2,1
2,9327,3,0
2,45918,4,1
3,17668,1,1
3,46667,2,1
3,17461,4,1
3,32665,3,1
4,46842,1,0

products:

product_id,product_name,aisle_id,department_id
9327,Garlic Powder,104,13
17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12
17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16
28985,Michigan Organic Kale,83,4
32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3
33120,Organic Egg Whites,86,16
45918,Coconut Butter,19,13
46667,Organic Ginger Root,83,4
46842,Plain Pre-Sliced Bagels,93,3

I'm to then create a new table that lists for each department, the number of orders created for this department, the number of first orders, and the ratio of (number of first orders / number of orders) for that department

So the resulting table would look like:

department_id,number_of_orders,number_of_first_orders,percentage
3,2,1,0.50
4,2,0,0.00
12,1,0,0.00
13,2,1,0.50
16,2,0,0.00

My solution involving Pandas:

orders = pd.read_csv("../insight_testsuite/tests/test_1/input/order_products.csv")
products = pd.read_csv("../insight_testsuite/tests/test_1/input/products.csv")

orders.drop(['add_to_cart_order'], axis=1, inplace=True)
products.drop(['aisle_id', 'product_name'], axis=1, inplace=True)

dep = pd.merge(orders, products)

dep = (dep.groupby('department_id')['reordered']
         .agg([('number_of_orders','size'),
               ('number_of_first_orders', lambda x: x.eq(0).sum())
               ])
         .reset_index())

dep['percentage'] = ("%.2f" %
   round((dep['number_of_first_orders'] / dep['number_of_orders']), 2))

But with regular Python, AFAIK, you can only go through the CSV file line by line and evaluate from there. So I'm not sure how you can perform that kind of analysis without using Pandas.

Body:
Well, you can. It just takes a lot of work:

from collections import defaultdict
import pandas as pd

s1 = '''order_id,product_id,add_to_cart_order,reordered
2,33120,1,1
2,28985,2,1
2,9327,3,0
2,45918,4,1
3,17668,1,1
3,46667,2,1
3,17461,4,1
3,32665,3,1
4,46842,1,0'''
s2 = '''product_id,product_name,aisle_id,department_id
9327,Garlic Powder,104,13
17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12
17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16
28985,Michigan Organic Kale,83,4
32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3
33120,Organic Egg Whites,86,16
45918,Coconut Butter,19,13
46667,Organic Ginger Root,83,4
46842,Plain Pre-Sliced Bagels,93,3'''
result = '''department_id,number_of_orders,number_of_first_orders,percentage
3,2,1,0.50
4,2,0,0.00
12,1,0,0.00
13,2,1,0.50
16,2,0,0.00'''

lines = s1.split('\n')
# lines
# ['order_id,product_id,add_to_cart_order,reordered', '2,33120,1,1', '2,28985,2,1', '2,9327,3,0', '2,45918,4,1',
#  '3,17668,1,1', '3,46667,2,1', '3,17461,4,1', '3,32665,3,1', '4,46842,1,0']

splitlines = [x.split(',') for x in lines]
# splitlines
# [['order_id', 'product_id', 'add_to_cart_order', 'reordered'], ['2', '33120', '1', '1'], ['2', '28985', '2', '1'],
#  ['2', '9327', '3', '0'], ['2', '45918', '4', '1'], ['3', '17668', '1', '1'], ['3', '46667', '2', '1'],
#  ['3', '17461', '4', '1'], ['3', '32665', '3', '1'], ['4', '46842', '1', '0']]

orders = {}
for j, k in enumerate(splitlines[0]):
    orders[k] = [int(splitlines[i][j]) for i in range(1, len(splitlines))]

# orders
# {'order_id': [2, 2, 2, 2, 3, 3, 3, 3, 4], 'product_id': [33120, 28985, 9327, 45918, 17668, 46667, 17461, 32665, 46842],
#  'add_to_cart_order': [1, 2, 3, 4, 1, 2, 4, 3, 1], 'reordered': [1, 1, 0, 1, 1, 1, 1, 1, 0]}

lines = s2.split('\n')
# lines
# ['product_id,product_name,aisle_id,department_id', '9327,Garlic Powder,104,13',
#  '17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12',
#  '17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16', '28985,Michigan Organic Kale,83,4',
#  '32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3', '33120,Organic Egg Whites,86,16', '45918,Coconut Butter,19,13',
#  '46667,Organic Ginger Root,83,4', '46842,Plain Pre-Sliced Bagels,93,3']
splitlines = [x.split(',') for x in lines]
# splitlines
# [['product_id', 'product_name', 'aisle_id', 'department_id'], ['9327', 'Garlic Powder', '104', '13'],
#  ['17461', 'Air Chilled Organic Boneless Skinless Chicken Breasts', '35', '12'],
#  ['17668', 'Unsweetened Chocolate Almond Breeze Almond Milk', '91', '16'],
#  ['28985', 'Michigan Organic Kale', '83', '4'], ['32665', 'Organic Ezekiel 49 Bread Cinnamon Raisin', '112', '3'],
#  ['33120', 'Organic Egg Whites', '86', '16'], ['45918', 'Coconut Butter', '19', '13'],
#  ['46667', 'Organic Ginger Root', '83', '4'], ['46842', 'Plain Pre-Sliced Bagels', '93', '3']]
products = {}
for j, k in enumerate(splitlines[0]):
    products[k] = [splitlines[i][j] for i in range(1, len(splitlines))]

# products
# {'product_id': ['9327', '17461', '17668', '28985', '32665', '33120', '45918', '46667', '46842'],
#  'product_name': ['Garlic Powder', 'Air Chilled Organic Boneless Skinless Chicken Breasts',
#                   'Unsweetened Chocolate Almond Breeze Almond Milk', 'Michigan Organic Kale',
#                   'Organic Ezekiel 49 Bread Cinnamon Raisin', 'Organic Egg Whites', 'Coconut Butter',
#                   'Organic Ginger Root', 'Plain Pre-Sliced Bagels'],
#  'aisle_id': ['104', '35', '91', '83', '112', '86', '19', '83', '93'],
#  'department_id': ['13', '12', '16', '4', '3', '16', '13', '4', '3']}

departments = list(set(products['department_id']))
# departments
# ['13', '16', '12', '3', '4']

order_counts = defaultdict(int)
for thing in products['department_id']:
    order_counts[thing] += 1

# order_counts
# defaultdict( < class 'int'>, {'13': 2, '12': 1, '16': 2, '4': 2, '3': 2})

report = {}
departments.sort(key=lambda x: int(x))
# departments
# ['3', '4', '12', '13', '16']
report['department_id'] = departments
report['number_of_orders'] = [order_counts[dep] for dep in report['department_id']]
# report
# {'department_id': ['3', '4', '12', '13', '16'], 'number_of_orders': [2, 2, 1, 2, 2]}
first_order_count = defaultdict(int)
department_product = defaultdict(list)
for i in range(len(products['product_id'])):
    if products['department_id'][i] in departments:
        department_product[products['department_id'][i]].append(products['product_id'][i])

# department_product
# defaultdict( <class 'list'>, {'13': ['9327', '45918'], '12': ['17461'], '16': ['17668', '33120'], '4': ['28985', '46667'], '3': ['32665', '46842']})

order_first_counts = defaultdict(int)

product_department = {}
for dep, prodlist in department_product.items():
    for prod in prodlist:
        product_department[prod] = dep

# product_department
# {'9327': '13', '45918': '13', '17461': '12', '17668': '16', '33120': '16', '28985': '4', '46667': '4', '32665': '3',
#  '46842': '3'}

first_order_count = defaultdict(int)
for prod, reordered in zip(orders['product_id'], orders['reordered']):
    if product_department[str(prod)] in departments and int(reordered) == 0:
        first_order_count[product_department[str(prod)]] += 1
# first_order_count
# defaultdict(<class 'int'>, {'13': 1, '3': 1})

report['number_of_first_orders'] = [first_order_count[dep] for dep in report['department_id']]
report['first_order_ratio'] = [q[0] / q[1] for q in zip(report['number_of_first_orders'], report['number_of_orders'])]
# report
# {'department_id': ['3', '4', '12', '13', '16'], 'number_of_orders': [2, 2, 1, 2, 2],
#  'number_of_first_orders': [1, 0, 0, 1, 0], 'first_order_ratio': [0.5, 0.0, 0.0, 0.5, 0.0]}
reportdf = pd.DataFrame.from_dict(report)

#   department_id  number_of_orders  number_of_first_orders  first_order_ratio
# 0             3                 2                       1                0.5
# 1             4                 2                       0                0.0
# 2            12                 1                       0                0.0
# 3            13                 2                       1                0.5
# 4            16                 2                       0                0.0

Presented for your amusement. I may come back and put some strategic comments in where I built dictionaries to represent FKeys and so on

Cheers!


问:
Hive: Regex for backslash
I need to query for all rows that have a backslash character in between. This is the query I wrote:

select *  from table where A = '2014-10-30' and B rlike '.asterisk\.asterisk'

(Had to manually type asterisk. The query had the symbol itself)

It is returning the entire table whether or not column B has backslash.

'.\\.' returned no rows even though there are rows where B has a backslash character.

Sample B -  Hi can check the details for you/

答:
This question well explained in this blogpost.

https://www.themarketingtechnologist.co/slashception-with-regexp_extract-in-hive/.

In short, the answer is:

Use 4 backslashes.

Title: Hive: Regex for backslash


问:
Function that stars all but first 3 chars of a word and removes blank space in separate .txt file
takes a copy of a .txt file (the file_name) and then copies but replaces all but the first 3 characters of every word with the character '*' in the destination .txt file. How do I replace all whitespace so each word is followed by a singular space also?

```<code>def speed_reader(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        output = ""
        for word in word_list:
            output += word[:3] + ("*" * (len(word)-3))

    with open(destination, "w") as writefile:
        writefile.write(''.join(output))
</code>```

this is what I have so far.

edit: I just realized I haven't done it correctly looking at the output .txt file.

答:
You were pretty close.  It would be easier to create a new list of truncated words, then join them all with a space just before writing the output.</p>

```<code>def speed_reader(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        out = [w[:3]+('*' * (len(w)-3)) for w in word_list]

    with open(destination, "w") as writefile:
        writefile.write(' '.join(out))
</code>```

Body:
takes a copy of a .txt file (the file_name) and then copies but replaces all but the first 3 characters of every word with the character '*' in the destination .txt file. How do I replace all whitespace so each word is followed by a singular space also?

def speed_reader(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        output = ""
        for word in word_list:
            output += word[:3] + ("*" * (len(word)-3))

    with open(destination, "w") as writefile:
        writefile.write(''.join(output))

this is what I have so far.

edit: I just realized I haven't done it correctly looking at the output .txt file.

Body:
You were pretty close.  It would be easier to create a new list of truncated words, then join them all with a space just before writing the output.

def speed_reader(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        out = [w[:3]+('*' * (len(w)-3)) for w in word_list]

    with open(destination, "w") as writefile:
        writefile.write(' '.join(out))


问:
Typescript: Get the type of the last parameter of a function type
Assume I have a function type, e.g.

```<code>type somefntype = (a: number, b: string, c: boolean) => void
</code>```

I need the type of that function types last parameter:

```<code>type lastparamtype = LastParameter<somefntype> // lastparamtype == boolean
</code>```

How do I define LastParameter?

答:
Update: TypeScript 4.0 introduced variadic tuple types, which means that Last can now be implemented simply as

```<code>type Last<T extends any[]> = T extends [...infer I, infer L] ? L : never;
</code>```

And the rest works as normal:

```<code>type LastParameter<F extends (...args: any)=>any> = Last<Parameters<F>>;
type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter<somefntype> // boolean
</code>```

Playground link to code

TypeScript 3.0 introduced tuple types in rest and spread expressions, specifically to allow programmatic conversion between the types of function parameter lists and tuples.  There's a type alias called Parameters<F> defined in the standard library that returns the parameter list of a function as a tuple.

It's annoying but possible to get the last element of a tuple type with a fixed but arbitrary length:

```<code>// Tail<T> returns a tuple with the first element removed
// so Tail<[1, 2, 3]> is [2, 3]
// (works by using rest tuples)
type Tail<T extends any[]> =
  ((...t: T)=>void) extends ((h: any, ...r: infer R)=>void) ? R : never;

// Last<T> returns the last element of the tuple
// (works by finding the one property key in T which is not in Tail<T>)
type Last<T extends any[]> = T[Exclude<keyof T, keyof Tail<T>>];
</code>```

Putting those together you get

```<code>type LastParameter<F extends (...args: any)=>any> = Last<Parameters<F>>;
</code>```

And we can test it:

```<code>type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter<somefntype> // boolean
</code>```

Looks good to me.  Link to code

Body:
Assume I have a function type, e.g.

type somefntype = (a: number, b: string, c: boolean) => void

I need the type of that function types last parameter:

type lastparamtype = LastParameter<somefntype> // lastparamtype == boolean

How do I define LastParameter?

Body:
Update: TypeScript 4.0 introduced variadic tuple types, which means that Last can now be implemented simply as

type Last<T extends any[]> = T extends [...infer I, infer L] ? L : never;

And the rest works as normal:

type LastParameter<F extends (...args: any)=>any> = Last<Parameters<F>>;
type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter<somefntype> // boolean

Playground link to code

TypeScript 3.0 introduced tuple types in rest and spread expressions, specifically to allow programmatic conversion between the types of function parameter lists and tuples.  There's a type alias called Parameters<F> defined in the standard library that returns the parameter list of a function as a tuple.

It's annoying but possible to get the last element of a tuple type with a fixed but arbitrary length:

// Tail<T> returns a tuple with the first element removed
// so Tail<[1, 2, 3]> is [2, 3]
// (works by using rest tuples)
type Tail<T extends any[]> =
  ((...t: T)=>void) extends ((h: any, ...r: infer R)=>void) ? R : never;

// Last<T> returns the last element of the tuple
// (works by finding the one property key in T which is not in Tail<T>)
type Last<T extends any[]> = T[Exclude<keyof T, keyof Tail<T>>];

Putting those together you get

type LastParameter<F extends (...args: any)=>any> = Last<Parameters<F>>;

And we can test it:

type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter<somefntype> // boolean

Looks good to me.  Link to code


问:
Is there a way to generate URLs for local files?
I'm trying to create a Viber chat-bot that is able to send some pictures. I am required to send URL of an image as a parameter, but the images I want to send are on my desktop and I do not know how to get their URLs.

I tried using requests:

image = {  "media": open('test_image.jpg', 'rb')}

payload = {
  "auth_token": "my token",
  "receiver": "my chat id",
  "type": "picture",
  "text": "some text",
}

requests.post("https://chatapi.viber.com/pa/send_message", json=image, file=image)
```
<p>I also tried using <code>imgur API</code> but it is a pain getting "pin" authentication all the time using selenium.</p>
<p>Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>from viberbot import Api
from viberbot.api.bot_configuration import BotConfiguration

from viberbot.api.messages.picture_message import PictureMessage
from viberbot.api.viber_requests import ViberMessageRequest

from flask import Flask, request, Response

app = Flask(__name__)

bot_configuration = BotConfiguration(
    name='name',
    avatar='http://viber.com/avatar.jpg',
    auth_token='token'
)
viber = Api(bot_configuration)

@app.route('/', methods=['POST'])
def index():
  viber_request = viber.parse_request(request.get_data())

  if isinstance(viber_request, ViberMessageRequest):
    message = viber_request.message

    if message.text == "/pic":

      viber.send_messages(viber_request.sender.id, [
        PictureMessage(media="image url", text="Some text")
      ])

  return Response(status=200)

if __name__ == '__main__':
  app.run(debug=True)
</code>```

To sum up:
In picture message object PictureMessage(media="image url", text="Some text") "media" has to be URL of image (only JPEG supported).
How would you turn images on your desktop into URLs?

答:
Generate a file URI such as file:///C:/Users/bob/Desktop/avatar.jpg .

How you generate that whole path depends on where you expect these files to be. But this is the syntax:

https://en.wikipedia.org/wiki/File_URI_scheme

You should read it and note the 3 slashes before the path, and understand why (because it's shorthand for file://localhost/C:/Users/bob/Desktop/avatar.jpg).

Body:
I'm trying to create a Viber chat-bot that is able to send some pictures. I am required to send URL of an image as a parameter, but the images I want to send are on my desktop and I do not know how to get their URLs.

I tried using requests:

image = {  "media": open('test_image.jpg', 'rb')}

payload = {
  "auth_token": "my token",
  "receiver": "my chat id",
  "type": "picture",
  "text": "some text",
}

requests.post("https://chatapi.viber.com/pa/send_message", json=image, file=image)

I also tried using imgur API but it is a pain getting "pin" authentication all the time using selenium.

Here is my code:

from viberbot import Api
from viberbot.api.bot_configuration import BotConfiguration

from viberbot.api.messages.picture_message import PictureMessage
from viberbot.api.viber_requests import ViberMessageRequest

from flask import Flask, request, Response

app = Flask(__name__)

bot_configuration = BotConfiguration(
    name='name',
    avatar='http://viber.com/avatar.jpg',
    auth_token='token'
)
viber = Api(bot_configuration)

@app.route('/', methods=['POST'])
def index():
  viber_request = viber.parse_request(request.get_data())

  if isinstance(viber_request, ViberMessageRequest):
    message = viber_request.message

    if message.text == "/pic":

      viber.send_messages(viber_request.sender.id, [
        PictureMessage(media="image url", text="Some text")
      ])

  return Response(status=200)

if __name__ == '__main__':
  app.run(debug=True)

To sum up:
In picture message object PictureMessage(media="image url", text="Some text") "media" has to be URL of image (only JPEG supported).
How would you turn images on your desktop into URLs?


问:
Creating responsive nav that aligns to the right on mobile but snaps to the center on larger screens
I'm trying to create a nav with a logo and links. I want the logo to always remain in the same position, vertically centered on the left, but I want the link items to change depending on the screen size.

On small screens, I want a small font size with the links aligned to the right
2.On medium screens, I want a medium font size with the links aligned in the center

On large screens, I want a larger font size with the links aligned in the center

Ideally, I want the changes to happen whenever the text is right about to hit the logo.

Here's a link to what I'm picturing.

答:
What you need is called breakpoints - it changes CSS styling when viewport size changes. The syntax looks like this:

```<code>@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}
</code>```

You can read about it here: https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Body:
What you need is called breakpoints - it changes CSS styling when viewport size changes. The syntax looks like this:

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

You can read about it here: https://www.w3schools.com/css/css_rwd_mediaqueries.asp


问:
Is there way to give input as normal expression to Z3 Solver?
The Z3 input format is an extension of the one defined by SMT-LIB 2.0 standard. The input expressions need to write in prefix form. As for example rise4fun,

x + (y * 2) = 20 needs to be given input in the form of " (= (+ x (* 2 y)) 20)) ".

Z3 supports JAVA API. As for example, let us consider the below code which evaluates and checks satisfiability expressions: x+y = 500 and x + (y * 2) = 20.

```<code>final Context ctx = new Context();
final Solver solver = ctx.mkSimpleSolver();

IntExpr x = ctx.mkIntConst("x");
IntExpr y = ctx.mkIntConst("y");
IntExpr th = ctx.mkInt(500);
IntExpr th1 = ctx.mkInt(2);
IntExpr th2 = ctx.mkInt(20);
BoolExpr t1 = ctx.mkEq(ctx.mkAdd(x,y), th);
BoolExpr t2 = ctx.mkEq(ctx.mkAdd(x,ctx.mkMul(th1, y)), th2);
solver.add(t1);
solver.add(t2);
solver.check()
</code>```

The problem is if an external user wants to give input to the solver, he cannot give it in the form of the general formula as " x+y = 500, x + (y * 2) = 20 ".
The input needs to be parsed and then should be written manually using JAVA API in prefix form (Note BoolExpr t2 in above code) to give the final expressions to Solver.

Is there any parser/library/API (Preferably JAVA or in any other language) which parses the general expressions with arithmetic operators(+, -, <, >, =), propositional logic connectors (And, OR), Quantifiers(ForAll, Exists) and then gives input to the Z3 Solvers ?

Please suggest and help.

答:
This is precisely why people build high-level interfaces to SMT solvers. There are many choices here for z3:

Official Python interface to z3: https://ericpony.github.io/z3py-tutorial/guide-examples.htm This is supported by Microsoft directly, and is probably the easiest to use.

PySMT, which aims to cover as many SMT solvers as they can: https://github.com/pysmt/pysmt

Scala bindings: https://github.com/epfl-lara/ScalaZ3

Haskell SBV: http://hackage.haskell.org/package/sbv

Many others at various maturity levels for Racket, Go, Lisp.. You name it. You can find many of them on github.

The goal of these "wrappers" is to precisely save the end-user from all the details of intricate bindings, and provide something much easier and less-error prone to use. On the flip side, they require you to learn yet another library. In my experience, if the host language of your choice has such an implementation, it'd pay off nicely to use it. If not, you should build one!

Body:
The Z3 input format is an extension of the one defined by SMT-LIB 2.0 standard. The input expressions need to write in prefix form. As for example rise4fun,

x + (y * 2) = 20 needs to be given input in the form of " (= (+ x (* 2 y)) 20)) ".

Z3 supports JAVA API. As for example, let us consider the below code which evaluates and checks satisfiability expressions: x+y = 500 and x + (y * 2) = 20.

final Context ctx = new Context();
final Solver solver = ctx.mkSimpleSolver();

IntExpr x = ctx.mkIntConst("x");
IntExpr y = ctx.mkIntConst("y");
IntExpr th = ctx.mkInt(500);
IntExpr th1 = ctx.mkInt(2);
IntExpr th2 = ctx.mkInt(20);
BoolExpr t1 = ctx.mkEq(ctx.mkAdd(x,y), th);
BoolExpr t2 = ctx.mkEq(ctx.mkAdd(x,ctx.mkMul(th1, y)), th2);
solver.add(t1);
solver.add(t2);
solver.check()

The problem is if an external user wants to give input to the solver, he cannot give it in the form of the general formula as " x+y = 500, x + (y * 2) = 20 ".
The input needs to be parsed and then should be written manually using JAVA API in prefix form (Note BoolExpr t2 in above code) to give the final expressions to Solver.

Is there any parser/library/API (Preferably JAVA or in any other language) which parses the general expressions with arithmetic operators(+, -, <, >, =), propositional logic connectors (And, OR), Quantifiers(ForAll, Exists) and then gives input to the Z3 Solvers ?

Please suggest and help.


问:
ruby exact number log (logarithm) function
As the base 10 logarithm of 1000 is 3 you might expect Math::log(1000, 10) to return 3. Instead it returns 2.9999999999999996.

This is due to the fact floats in Ruby are not exact numbers as discussed for example here:

Float isn't an exact number representation, as stated in the ruby
  docs:

Float objects represent inexact real numbers using the native architecture's double-precision floating point representation.

This not ruby fault, as floats can only be represented by a fixed
  number of bytes and therefor cannot store decimal numbers correctly.

Alternatively, you can use ruby Rational or BigDecimal

Sadly when calling Math::log(BigDecimal('1000'), BigDecimal('10')) the result is exactly the same. Same goes for Math::log(Rational('1000'), Rational('10')). There is also a BigMath::log which does something completely different.

Now the big question is: how can we calculate the base 10 logarithm of 1000 such that we get the exact result: 3?

答:
You have encountered a limitation of floating point numbers here. Floats typically have a precision of 15 decimal places in Ruby, but the value 2.9999999999999996 shows 16 decimal places of (unreliable) precision.

To get back to a reliable precision, round to 15 decimal places:

```<code>>> Math::log(1000, 10)
=> 2.9999999999999996
>> Math::log(1000, 10).round(15)
=> 3.0
</code>```

The C language specification only requires 10 significant decimal places for a double, so it is possible that a Ruby implementation would have Floats with fewer than 15 significant decimal places, but still it is much more common to see 15 significant decimal places here.

Body:
You have encountered a limitation of floating point numbers here. Floats typically have a precision of 15 decimal places in Ruby, but the value 2.9999999999999996 shows 16 decimal places of (unreliable) precision.

To get back to a reliable precision, round to 15 decimal places:

>> Math::log(1000, 10)
=> 2.9999999999999996
>> Math::log(1000, 10).round(15)
=> 3.0

The C language specification only requires 10 significant decimal places for a double, so it is possible that a Ruby implementation would have Floats with fewer than 15 significant decimal places, but still it is much more common to see 15 significant decimal places here.


问:
Wrong color legends with two plots overlay in ggplot2
I'm trying to give a combined color scheme in spatial plot using ggplot2 this way:

A Factor (2 levels) variable is used to select the tint (in my case, orange or blue)

A continuous variable is used to select the saturation

I found no easier way to do that than stacking two plots, the upper one a grey gradient to simulate saturation:

```<code>    ggplot(data = italian.regions) +
  geom_sf(fill = c("#BFD6FF", "#FFEBBF")[as.numeric(as.factor(regions.lookup$`engine.top`))], lwd = .2) +
  geom_sf(aes(fill = regions.lookup$`engine.diff`), lwd = .2, alpha = .3) +
  scale_fill_gradient(high = "#666666", low = "#EFEFEF")
</code>```

I use the aestethic to fill the gradient and this works. This is an example plot:

But (of course) the color legend refers to the aesthetic but it should be much more meaningful to have one describing the discrete values in 'engine.top'.

Is it possible to do so? is there an easier way to have a two-tonal, gradient color scheme without stacking two plots?

答:
My prefered method is to use scale_fill_identity() and hcl(). See if this works for you

library(sf)
library(tidyverse)

# this file is already on your computer
nc <- st_read(system.file("shape/nc.shp", package="sf"))

nc_colors <-
  nc %>%
  mutate(
    # 220 = blue and # 40 = orange
    hue = ifelse(str_detect(CNTY_ID, "^18"), 220, 40),
    light = AREA/max(AREA)*100,
    # the hcl function returns a hex code
    hex = hcl(h = hue, l = light)
  )

ggplot() +
  geom_sf(data = nc_colors, aes(fill = hex)) +
  scale_fill_identity()
```

Another solution you can use is to do something like aes(...fill = hue, alpha = AREA) then use scale_fill_manual()

Body:
I'm trying to give a combined color scheme in spatial plot using ggplot2 this way:

A Factor (2 levels) variable is used to select the tint (in my case, orange or blue)

A continuous variable is used to select the saturation

I found no easier way to do that than stacking two plots, the upper one a grey gradient to simulate saturation:

    ggplot(data = italian.regions) +
  geom_sf(fill = c("#BFD6FF", "#FFEBBF")[as.numeric(as.factor(regions.lookup$`engine.top`))], lwd = .2) +
  geom_sf(aes(fill = regions.lookup$`engine.diff`), lwd = .2, alpha = .3) +
  scale_fill_gradient(high = "#666666", low = "#EFEFEF")

I use the aestethic to fill the gradient and this works. This is an example plot:

But (of course) the color legend refers to the aesthetic but it should be much more meaningful to have one describing the discrete values in 'engine.top'.

Is it possible to do so? is there an easier way to have a two-tonal, gradient color scheme without stacking two plots?

Body:
My prefered method is to use scale_fill_identity() and hcl(). See if this works for you

library(sf)
library(tidyverse)

# this file is already on your computer
nc <- st_read(system.file("shape/nc.shp", package="sf"))

nc_colors <-
  nc %>%
  mutate(
    # 220 = blue and # 40 = orange
    hue = ifelse(str_detect(CNTY_ID, "^18"), 220, 40),
    light = AREA/max(AREA)*100,
    # the hcl function returns a hex code
    hex = hcl(h = hue, l = light)
  )

ggplot() +
  geom_sf(data = nc_colors, aes(fill = hex)) +
  scale_fill_identity()

Another solution you can use is to do something like aes(...fill = hue, alpha = AREA) then use scale_fill_manual()


问:
Having trouble with precise positioning of Vaadin components
I am spending alot of time positioning my Vaadin components and was wondering what other people's experiences when developing their own Vaadin applications was when layout out their GUIs.</p>

答:
Coming from desktop world the AbsoluteLayout using pixel positions and sizes has proven very straight-forward way to do component layouts.

That is a bit trade-off between Java-only layout and powerful web-style layout mechanism you get with CssLayout and CustomLayout, but you should get quite far by smartly mixing of these.


问:
OpenCV Brightness & Contrast like in Gimp
I want adjust the contrast in Python's OpenCV like in Gimp. I want do this:

In Gimp it is simple. I just use Colors->Brightness & Contrast, and set contrast to 127.
But I don't know how to do this in Python and I cannot find any solution to this problem.

答:
The formula for contrast and brightness used by GIMP is defined in this file : https://github.com/GNOME/gimp/blob/GIMP_2_10_10/app/operations/gimpoperationbrightnesscontrast.c

```<code>  if (brightness < 0.0)
    value = value * (1.0 + brightness);
  else
    value = value + ((1.0 - value) * brightness);

  value = (value - 0.5) * slant + 0.5;
</code>```

Where

```<code>  brightness = config->brightness / 2.0;
  slant = tan ((config->contrast + 1) * G_PI_4);
</code>```

Assuming the image was normalized to the [0, 1] range beforehand.

Body:
The formula for contrast and brightness used by GIMP is defined in this file : https://github.com/GNOME/gimp/blob/GIMP_2_10_10/app/operations/gimpoperationbrightnesscontrast.c

  if (brightness < 0.0)
    value = value * (1.0 + brightness);
  else
    value = value + ((1.0 - value) * brightness);

  value = (value - 0.5) * slant + 0.5;

Where

  brightness = config->brightness / 2.0;
  slant = tan ((config->contrast + 1) * G_PI_4);

Assuming the image was normalized to the [0, 1] range beforehand.