问:
Mapping items in an array
Hoping this is a nice easy one, but I just can't see how to do it.

I am wanting to with rego map items in an array to a cleaner version. For example from the data below

```<code>data = [
  {
    "some": "value",
    "another": "mvalue",
    "dont": "want"
  },
  {
    "some": "value1",
    "another": "mvalue1",
    "dont": "want1"
  },
  {
    "some": "value2",
    "another": "mvalue2",
    "dont": "want2"
  }
]
</code>```

I want to turn data into

```<code>result = [
  {
    "some": "value",
    "another": "mvalue"
  },
  {
    "some": "value1",
    "another": "mvalue1"
  },
  {
    "some": "value2",
    "another": "mvalue2"
  }
]
</code>```

The two closest I think I've got is

```<code>result1 = cleaned {
    cleaned := {d |
        d := {
            "some": data[_].some,
            "another": data[_].another
        }
    }
}

result2 = cleaned {
    d := data[_]
    cleaned := {
        "some": p.some,
        "another": p.another
    }
}
</code>```

答:
TLDR; If the fields are static and you can easily enumerate them, both of your solutions is almost correct (see below for explanation of why they are incorrect.) Here's the right way to do that:

```<code>result = [
  mapped |
    original := data[_]
    mapped := {"some": original["some"], "another": original.another}
]
</code>```

A slightly more elegant option is to define the fields to include or exclude like in @eephillip's example. For instance:

```<code>result = [
  mapped |
    original := data[_]
    mapped := {k: v |
      some k
      v := original[k]
      not exclude[k]}
]

exclude = {"dont", "dont2"}  # defines a SET of keys to exclude
</code>```

Of course you could generalize it even more by making the inner comprehension invoke a function that implements other filters.

Here's an interactive example: https://play.openpolicyagent.org/p/P6wPd3rudJ

Two notes about the original solution.

1. result1 does not iterate over data correctly

```<code>{d |
  d := {
    "some": data[_].some,        # problem: _ is a different variable in each expression
    "another": data[_].another
  }
}
</code>```

Conceptually each occurrence of _ is a unique variable. If you explicitly declare the variables, the problem is more obvious:

```<code># note: this is still wrong
{d |
  some i, j
  d := {
    "some": data[i]["some"],
    "another": data[j].another
  }
}
</code>```

If you run this, you'll discover that it produces a cross-product (which is not what you want). You want the "some" and "another" fields to be selected from the same object like this:

```<code>{d |
  some i
  d := {
    "some": data[i]["some"],
    "another": data[i].another
  }
}
</code>```

Of course, coming up with unique variable names can be a pain, so you can use _. Just do not mistake multiple _ variables as referring to the same value. We can rewrite the statement to use _ as follows:

```<code>{d |
  obj := data[_]
  d := {
    "some": obj["some"],
    "another": obj.another
  }
}
</code>```

result2 is close but may assign multiple values (which should be avoided)

```<code>result2 = cleaned {
    d := data[_]
    cleaned := {               # problem: there could be multiple values for 'cleaned'
        "some": d["some"],
        "another": d.another
    }
}
</code>```

Rules of the form NAME = VALUE { BODY } assign VALUE to NAME if the statements in BODY are satisfied. If you omit BODY, i.e., you write NAME = VALUE, then BODY defaults to true (which is always satisfied.)

In your above example:

NAME is result2

VALUE is cleaned

BODY is d := data[_]; cleaned := {...}

In Rego, we call these rules "complete rules". Complete rules are just IF-THEN statements that assign a single value to a variable. The "IF" portion is the rule body and the "THEN" portion is the assignment. You should avoid writing rules that may assign MULTIPLE values to the same variable because that may result in an evaluation time error. For example:

```<code># do not do this
result = v {
   v := data[_]   # if 'data' is [1,2,3] then what is the value of 'result'? Hint: There is more than one answer.
}
</code>```

If you want to assign MULTIPLE values to a variable then you can define a "partial rule" For example:

```<code>result[v] {       # result is a SET.
   v := data[_]
}
</code>```

Title: Mapping items in an array

Body:
Hoping this is a nice easy one, but I just can't see how to do it.

I am wanting to with rego map items in an array to a cleaner version. For example from the data below

data = [
  {
    "some": "value",
    "another": "mvalue",
    "dont": "want"
  },
  {
    "some": "value1",
    "another": "mvalue1",
    "dont": "want1"
  },
  {
    "some": "value2",
    "another": "mvalue2",
    "dont": "want2"
  }
]

I want to turn data into

result = [
  {
    "some": "value",
    "another": "mvalue"
  },
  {
    "some": "value1",
    "another": "mvalue1"
  },
  {
    "some": "value2",
    "another": "mvalue2"
  }
]

The two closest I think I've got is

result1 = cleaned {
    cleaned := {d |
        d := {
            "some": data[_].some,
            "another": data[_].another
        }
    }
}

result2 = cleaned {
    d := data[_]
    cleaned := {
        "some": p.some,
        "another": p.another
    }
}

Body:
TLDR; If the fields are static and you can easily enumerate them, both of your solutions is almost correct (see below for explanation of why they are incorrect.) Here's the right way to do that:

result = [
  mapped |
    original := data[_]
    mapped := {"some": original["some"], "another": original.another}
]

A slightly more elegant option is to define the fields to include or exclude like in @eephillip's example. For instance:

result = [
  mapped |
    original := data[_]
    mapped := {k: v |
      some k
      v := original[k]
      not exclude[k]}
]

exclude = {"dont", "dont2"}  # defines a SET of keys to exclude

Of course you could generalize it even more by making the inner comprehension invoke a function that implements other filters.

Here's an interactive example: https://play.openpolicyagent.org/p/P6wPd3rudJ

Two notes about the original solution.

1. result1 does not iterate over data correctly

{d |
  d := {
    "some": data[_].some,        # problem: _ is a different variable in each expression
    "another": data[_].another
  }
}

Conceptually each occurrence of _ is a unique variable. If you explicitly declare the variables, the problem is more obvious:

# note: this is still wrong
{d |
  some i, j
  d := {
    "some": data[i]["some"],
    "another": data[j].another
  }
}

If you run this, you'll discover that it produces a cross-product (which is not what you want). You want the "some" and "another" fields to be selected from the same object like this:

{d |
  some i
  d := {
    "some": data[i]["some"],
    "another": data[i].another
  }
}

Of course, coming up with unique variable names can be a pain, so you can use _. Just do not mistake multiple _ variables as referring to the same value. We can rewrite the statement to use _ as follows:

{d |
  obj := data[_]
  d := {
    "some": obj["some"],
    "another": obj.another
  }
}

result2 is close but may assign multiple values (which should be avoided)

result2 = cleaned {
    d := data[_]
    cleaned := {               # problem: there could be multiple values for 'cleaned'
        "some": d["some"],
        "another": d.another
    }
}

Rules of the form NAME = VALUE { BODY } assign VALUE to NAME if the statements in BODY are satisfied. If you omit BODY, i.e., you write NAME = VALUE, then BODY defaults to true (which is always satisfied.)

In your above example:

NAME is result2

VALUE is cleaned

BODY is d := data[_]; cleaned := {...}

In Rego, we call these rules "complete rules". Complete rules are just IF-THEN statements that assign a single value to a variable. The "IF" portion is the rule body and the "THEN" portion is the assignment. You should avoid writing rules that may assign MULTIPLE values to the same variable because that may result in an evaluation time error. For example:

# do not do this
result = v {
   v := data[_]   # if 'data' is [1,2,3] then what is the value of 'result'? Hint: There is more than one answer.
}

If you want to assign MULTIPLE values to a variable then you can define a "partial rule" For example:

result[v] {       # result is a SET.
   v := data[_]
}


来源: stackexchange

问:
Visual basic function for intermittent antibiotic dosing
I am a beginner in VB. I wrote a little program to simulate dosing regimens of antibiotics using some exponential equations and pharmacokinetic data.

The problem I have is that I want to display on a graph the following mathematical function:

That simulates the  concentration variation at different intervals of time:

Where:

b(t) is the concentration at time t that will be plotted as Y axis, t is time (plotted on the x-axis).

b(0) is the concentration at time 0 and it is a known variable.

u(t-a1) is a function that has the value u(t-a1)=b(o) if t=a1 or 0 if t<>a1

a1 is the time at which a next dose is given.

alpha is the elimination rate constant, a variable that is known.

What I have so far:

```<code>Dim y, x As Double

For x = 0 To 24 Step 1

    For n As Double = 1 To 24 / tau

        y = (1 - test_condition(n * tau, x)) * css * Math.Exp(-ke * x) + test_condition(n * tau, x) * css * Math.Exp(-ke * (x - n * tau))

        Chart1.Series("Concentratie1").Points.AddXY(x, y)
    Next
Next
</code>```

The test_condition:

```<code>if x=tau then test_condition= 1 else 0
</code>```

It is close but I don't get an exponential decay after a dose ... don't know how to make that happen.

This works!! for tau (dosing interval) every 4 hours. Can it be rearranged somehow because the tau (dosing interval) will vary (sometimes 4 hours, sometimes every 6 hours)?:

```<code>    Dim y, x, y2, x2, y3, x3, y4, x4, x5, x6, y5, y6 As Double

    For x = 0 To tau Step 1

        y = exponential_decay(css, ke, x) + test_condition(tau, x) * (css - Val(mic))

        Chart1.Series("Bolus 1").Points.AddXY(x, y)

    Next

    For x2 = tau To 2 * tau Step 1

        y2 = exponential_decay(css, ke, x2 - tau) + test_condition(2 * tau, x2) * (css - Val(mic))

        Chart1.Series("Bolus 2").Points.AddXY(x2, y2)
    Next

    For x3 = 2 * tau To 3 * tau Step 1

        y3 = exponential_decay(css, ke, x3 - 2 * tau) + test_condition(3 * tau, x3) * (css - Val(mic))

        Chart1.Series("Bolus 3").Points.AddXY(x3, y3)
    Next

    For x4 = 3 * tau To 4 * tau Step 1

        y4 = exponential_decay(css, ke, x4 - 3 * tau) + test_condition(4 * tau, x4) * (css - Val(mic))

        Chart1.Series("Bolus 4").Points.AddXY(x4, y4)
    Next

    For x5 = 4 * tau To 5 * tau Step 1

        y5 = exponential_decay(css, ke, x5 - 4 * tau) + test_condition(5 * tau, x5) * (css - Val(mic))

        Chart1.Series("Bolus 4").Points.AddXY(x5, y5)
    Next

    For x6 = 5 * tau To 32 Step 1

        y6 = exponential_decay(css, ke, x6 - 5 * tau)

        Chart1.Series("Bolus 4").Points.AddXY(x6, y6)
    Next

End Sub
</code>```

答:
I managed to solve the problem:
this function f relates time (t) to dosing interval (tau)

```<code>Private Function f(ByVal t As Double, ByVal tau As Double)
    Dim n As Integer

    For n = 0 To 24 / tau

        If t = n * tau Then
            f = n * tau
        ElseIf t < tau Then
            f = 0
        ElseIf t > n * tau And t < (n + 1) * tau Then
            f = n * tau
        ElseIf t >= (n + 1) * tau Then
            f = n * tau

        End If
    Next
End Function
</code>```

And this is what I draw on the chart:

```<code>For x = 0 To 36 Step 0.5

        y = exponential_decay(css, ke, x - f(x, tau))

        Chart1.Series("Intermitent Dosage").Points.AddXY(x, y)
    Next
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner in VB. I wrote a little program to simulate dosing regimens of antibiotics using some exponential equations and pharmacokinetic data.

The problem I have is that I want to display on a graph the following mathematical function:

That simulates the  concentration variation at different intervals of time:

Where:

b(t) is the concentration at time t that will be plotted as Y axis, t is time (plotted on the x-axis).

b(0) is the concentration at time 0 and it is a known variable.

u(t-a1) is a function that has the value u(t-a1)=b(o) if t=a1 or 0 if t<>a1

a1 is the time at which a next dose is given.

alpha is the elimination rate constant, a variable that is known.

What I have so far:

Dim y, x As Double

For x = 0 To 24 Step 1

    For n As Double = 1 To 24 / tau

        y = (1 - test_condition(n * tau, x)) * css * Math.Exp(-ke * x) + test_condition(n * tau, x) * css * Math.Exp(-ke * (x - n * tau))

        Chart1.Series("Concentratie1").Points.AddXY(x, y)
    Next
Next

The test_condition:

if x=tau then test_condition= 1 else 0

It is close but I don't get an exponential decay after a dose ... don't know how to make that happen.

This works!! for tau (dosing interval) every 4 hours. Can it be rearranged somehow because the tau (dosing interval) will vary (sometimes 4 hours, sometimes every 6 hours)?:

    Dim y, x, y2, x2, y3, x3, y4, x4, x5, x6, y5, y6 As Double

    For x = 0 To tau Step 1

        y = exponential_decay(css, ke, x) + test_condition(tau, x) * (css - Val(mic))

        Chart1.Series("Bolus 1").Points.AddXY(x, y)

    Next

    For x2 = tau To 2 * tau Step 1

        y2 = exponential_decay(css, ke, x2 - tau) + test_condition(2 * tau, x2) * (css - Val(mic))

        Chart1.Series("Bolus 2").Points.AddXY(x2, y2)
    Next

    For x3 = 2 * tau To 3 * tau Step 1

        y3 = exponential_decay(css, ke, x3 - 2 * tau) + test_condition(3 * tau, x3) * (css - Val(mic))

        Chart1.Series("Bolus 3").Points.AddXY(x3, y3)
    Next

    For x4 = 3 * tau To 4 * tau Step 1

        y4 = exponential_decay(css, ke, x4 - 3 * tau) + test_condition(4 * tau, x4) * (css - Val(mic))

        Chart1.Series("Bolus 4").Points.AddXY(x4, y4)
    Next

    For x5 = 4 * tau To 5 * tau Step 1

        y5 = exponential_decay(css, ke, x5 - 4 * tau) + test_condition(5 * tau, x5) * (css - Val(mic))

        Chart1.Series("Bolus 4").Points.AddXY(x5, y5)
    Next

    For x6 = 5 * tau To 32 Step 1

        y6 = exponential_decay(css, ke, x6 - 5 * tau)

        Chart1.Series("Bolus 4").Points.AddXY(x6, y6)
    Next

End Sub

Body:
I managed to solve the problem:
this function f relates time (t) to dosing interval (tau)

Private Function f(ByVal t As Double, ByVal tau As Double)
    Dim n As Integer

    For n = 0 To 24 / tau

        If t = n * tau Then
            f = n * tau
        ElseIf t < tau Then
            f = 0
        ElseIf t > n * tau And t < (n + 1) * tau Then
            f = n * tau
        ElseIf t >= (n + 1) * tau Then
            f = n * tau

        End If
    Next
End Function

And this is what I draw on the chart:

For x = 0 To 36 Step 0.5

        y = exponential_decay(css, ke, x - f(x, tau))

        Chart1.Series("Intermitent Dosage").Points.AddXY(x, y)
    Next


问:
Web firebase.messaging().onMessage not fired, but background notification perfectly fired
I want to reload or trigger some event in foregrounf if push message is sent with firebase.messaging().onMessage, but it not fired. I'm using firebase.mesaging.sw.js with background notification and it works correctly what is wrong with my code?

firebase.js

```<code>const config = {
  apiKey: "x",
  projectId: "x",
  storageBucket: "x",
  messagingSenderId: "x"
};

firebase.initializeApp(config);

const msg = firebase.messaging()
msg.requestPermission()
  .then(() => {
    return msg.getToken()
  })
  .then((token) => {
  })
  .catch((err) => {
  })

msg.onMessage(function(payload) {
  alert("Foreground message fired!")
  console.log(payload)
});
</code>```

firebase.messaging.sw.js

```<code>importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-messaging.js");

const config = {
  apiKey: "x",
  projectId: "x",
  storageBucket: 'x',
  messagingSenderId: "x"
};

firebase.initializeApp(config);
const msg = firebase.messaging()

msg.setBackgroundMessageHandler(function(payload) {
  let options = {
    body: payload.data.body,
    icon: payload.data.icon
  }

  return self.registration.showNotification(payload.data.title, options);

});
</code>```

I don't know what is wrong with my code

答:
For anyone else with this problem, I finally solved it by:

Upgrading the Firebase SDK version in both header-included JS files and the SW JS file to latest (currently, that would be 7.8.1).

Adding the entire firebaseConfig array to the SW firebase.initializeApp(), as the previous answer suggests.

Cleaning the Chrome cache from the Application > Clear Storage section in the Developer Tools.

Deleting the previous registration token from my database.

Blocking and unblocking notifications from the browser to force a new token generation.

Basically, a total fresh start with updated Firebase SDK seems to fix issues like this.

Body:
I want to reload or trigger some event in foregrounf if push message is sent with firebase.messaging().onMessage, but it not fired. I'm using firebase.mesaging.sw.js with background notification and it works correctly what is wrong with my code?

firebase.js

const config = {
  apiKey: "x",
  projectId: "x",
  storageBucket: "x",
  messagingSenderId: "x"
};

firebase.initializeApp(config);

const msg = firebase.messaging()
msg.requestPermission()
  .then(() => {
    return msg.getToken()
  })
  .then((token) => {
  })
  .catch((err) => {
  })

msg.onMessage(function(payload) {
  alert("Foreground message fired!")
  console.log(payload)
});

firebase.messaging.sw.js

importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-messaging.js");

const config = {
  apiKey: "x",
  projectId: "x",
  storageBucket: 'x',
  messagingSenderId: "x"
};

firebase.initializeApp(config);
const msg = firebase.messaging()

msg.setBackgroundMessageHandler(function(payload) {
  let options = {
    body: payload.data.body,
    icon: payload.data.icon
  }

  return self.registration.showNotification(payload.data.title, options);

});

I don't know what is wrong with my code


问:
Invoking a Lambda function every 5 seconds

My problem

I'd like to invoke an AWS Lambda function every 5 seconds, for some monitoring purposes.

According to the docs,

Rate frequencies of less than one minute are not supported.

What have I tried

STFW.

My Question

Can I autonomously invoke an AWS Lambda function every 5 seconds?

答: you can use step functions and lambda for that - look at https://aws.amazon.com/blogs/architecture/a-serverless-solution-for-invoking-aws-lambda-at-a-sub-minute-frequency/</p>

ContentLicense: CC BY-SA 3.0


问:
How do you add !important to a CSS-in-JS (JSS) class property?
I am trying to use some CSS-in-JS classes from this answer with a material UI component in my React project. I need to override the CSS coming from Bootstrap so I want to use the !important modifier, I've only used this in .css files before and I'm unsure how to do it in CSS-in-JS. My styles object to be passed into the Material-UI withStyles function looks like the following, how do I add !important to the fontSize attribute? I've tried 30 !important and a few other things but nothing seems to work.

Thanks

```<code>const styles = {
  labelRoot: {
    fontSize: 30
  }
}
</code>```

答:
You can use the array-based syntax for space and comma separated values.

Just do this:

```<code>const styles = {
  labelRoot: {
    fontSize: [[30], '!important'],
    margin: [[5, 10], '!important']
  }
}
</code>```

Body:
I am trying to use some CSS-in-JS classes from this answer with a material UI component in my React project. I need to override the CSS coming from Bootstrap so I want to use the !important modifier, I've only used this in .css files before and I'm unsure how to do it in CSS-in-JS. My styles object to be passed into the Material-UI withStyles function looks like the following, how do I add !important to the fontSize attribute? I've tried 30 !important and a few other things but nothing seems to work.

Thanks

const styles = {
  labelRoot: {
    fontSize: 30
  }
}

Body:
You can use the array-based syntax for space and comma separated values.

Just do this:

const styles = {
  labelRoot: {
    fontSize: [[30], '!important'],
    margin: [[5, 10], '!important']
  }
}


问:
Using mosquitto in a shell script using a pipe
I'm using mosquitto on an openWRT device to receive some data from a server and then send this same data to a local printer to print this data.

I'm using this script to receive the data

```<code>mosquitto_sub -h "${HOST}" -k 30 -c -p 8883 -t "${TOPIC}" -u "${USERNAME}" -P "${PASSWORD}" --id "${ID}" | /bin/sh /bin/printer_execute "${TOPIC}" "${PRINTER}" "${USERNAME}" "${PASSWORD}"
</code>```

And the printer_execute code:

```<code>    #!/bin/sh

TOPIC="${1}"
PRINTER="${2}"
USERNAME="${3}"
PASSWORD="${4}"

while read MSG
  do
    echo "input: ${MSG}"
      echo "INPUT MSG: " "${MSG}" >> /root/log
      RES=`curl -m 2 --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction: ''" --header "If-Modified-Since: Thu, 01 Jan 1970 00:00:00 GMT" --data "${MSG}" "http://${PRINTER}/cgi-bin/epos/service.cgi?devid=local_printer&timeout=5000"`
      mosquitto_pub -h ${HOST_PLACEHOLDER} -p 8883 -t "${TOPIC}-response" -m "${RES}" -u "${USERNAME}" -P "${PASSWORD}"
    echo "RESULT CURL: " "${RES}" >> /root/log
done
</code>```

This solution works with a relatively low messages per second, but when the volume is too high the printer_execute code stop working. I'm pretty new to shell scripting and I guess the problem could be caused by the pipe and while read pattern or by the while exit condition, but i'm not really sure.

Anyone has some idea or found a similar problem and know how to solve this?

EDIT:
In light of the answers i have tried to do this:

EDIT2: Sorry in the first edit i just added what i modified but the entire script is like that and the scope should be correct for the variables.

```<code>#!/bin/sh
TOPIC="${1}"
PRINTER="${2}"
USERNAME="${3}"
PASSWORD="${4}"
PrintOne(){
    MSG="${1}"
    RES=$(curl [params])
    mosquitto_pub -h [host] -p 8883 -d -t "${TOPIC}-response" -m "${RES}" -u "${USERNAME}" -P "${PASSWORD}"
    echo "RESULT CURL: " "${RES}" >> /root/log
}

while read msg ; do
        PrintOne "$msg" &
done
</code>```

With the printone and the appersand this take one message and stop working, without the & it's just like it was before.

答:
You could try making a function to handle one message and calling that in the background (by appending an ampersand) so that you can respond quickly and in parallel - and that will allow you to take longer to handle each message... for a period. If your messages continually arrive faster than you can handle them, there will inevitably be a backlog.

Something like this:

```<code>#!/bin/bash

PrintOne(){
   echo "Received $1"
   curl ...
   mosquitto_pub ...
   echo $RESULT
}

while read msg ; do
    PrintOne "$msg" &
done
</code>```

If you want a little example. change the code to this and save it as go, and make it executable with chmod +x go

```<code>#!/bin/bash

PrintOne(){
   echo "Received $1"
   sleep 2
   echo "Finished $1"
}

while read msg ; do
    PrintOne "$msg" &
done
</code>```

Now send it 10 lines:

```<code>seq 10 | ./go
</code>```

Then remove the ampersand, and do exactly the same thing again and you will see the difference.

A more complete version of my answer is as follows:

```<code>#!/bin/bash

PrintOne(){
   TOPIC="${1}"
   PRINTER="${2}"
   USERNAME="${3}"
   PASSWORD="${4}"
   curl ...
   mosquitto_pub ...
   echo $RESULT
}

while read msg ; do
    PrintOne "${1}" "${2}" "${3}" "${4}" &
done
</code>```

Body:
I'm using mosquitto on an openWRT device to receive some data from a server and then send this same data to a local printer to print this data.

I'm using this script to receive the data

mosquitto_sub -h "${HOST}" -k 30 -c -p 8883 -t "${TOPIC}" -u "${USERNAME}" -P "${PASSWORD}" --id "${ID}" | /bin/sh /bin/printer_execute "${TOPIC}" "${PRINTER}" "${USERNAME}" "${PASSWORD}"

And the printer_execute code:

    #!/bin/sh

TOPIC="${1}"
PRINTER="${2}"
USERNAME="${3}"
PASSWORD="${4}"

while read MSG
  do
    echo "input: ${MSG}"
      echo "INPUT MSG: " "${MSG}" >> /root/log
      RES=`curl -m 2 --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction: ''" --header "If-Modified-Since: Thu, 01 Jan 1970 00:00:00 GMT" --data "${MSG}" "http://${PRINTER}/cgi-bin/epos/service.cgi?devid=local_printer&timeout=5000"`
      mosquitto_pub -h ${HOST_PLACEHOLDER} -p 8883 -t "${TOPIC}-response" -m "${RES}" -u "${USERNAME}" -P "${PASSWORD}"
    echo "RESULT CURL: " "${RES}" >> /root/log
done

This solution works with a relatively low messages per second, but when the volume is too high the printer_execute code stop working. I'm pretty new to shell scripting and I guess the problem could be caused by the pipe and while read pattern or by the while exit condition, but i'm not really sure.

Anyone has some idea or found a similar problem and know how to solve this?

EDIT:
In light of the answers i have tried to do this:

EDIT2: Sorry in the first edit i just added what i modified but the entire script is like that and the scope should be correct for the variables.

#!/bin/sh
TOPIC="${1}"
PRINTER="${2}"
USERNAME="${3}"
PASSWORD="${4}"
PrintOne(){
    MSG="${1}"
    RES=$(curl [params])
    mosquitto_pub -h [host] -p 8883 -d -t "${TOPIC}-response" -m "${RES}" -u "${USERNAME}" -P "${PASSWORD}"
    echo "RESULT CURL: " "${RES}" >> /root/log
}

while read msg ; do
        PrintOne "$msg" &
done

With the printone and the appersand this take one message and stop working, without the & it's just like it was before.

Body:
You could try making a function to handle one message and calling that in the background (by appending an ampersand) so that you can respond quickly and in parallel - and that will allow you to take longer to handle each message... for a period. If your messages continually arrive faster than you can handle them, there will inevitably be a backlog.

Something like this:

#!/bin/bash

PrintOne(){
   echo "Received $1"
   curl ...
   mosquitto_pub ...
   echo $RESULT
}

while read msg ; do
    PrintOne "$msg" &
done

If you want a little example. change the code to this and save it as go, and make it executable with chmod +x go

#!/bin/bash

PrintOne(){
   echo "Received $1"
   sleep 2
   echo "Finished $1"
}

while read msg ; do
    PrintOne "$msg" &
done

Now send it 10 lines:

seq 10 | ./go

Then remove the ampersand, and do exactly the same thing again and you will see the difference.

A more complete version of my answer is as follows:

#!/bin/bash

PrintOne(){
   TOPIC="${1}"
   PRINTER="${2}"
   USERNAME="${3}"
   PASSWORD="${4}"
   curl ...
   mosquitto_pub ...
   echo $RESULT
}

while read msg ; do
    PrintOne "${1}" "${2}" "${3}" "${4}" &
done


问:
ADXL345 Accelerometer data use on I2C (Beaglebone Black)
Background Information

I am trying to make sure I will be able to run two ADXL345 Accelerometers on the same I2C Bus.

To my understanding, the bus can transmit up to 400k bits/s on fast mode.

In order to send 1 byte of data, there are 20 extra bits of overhead.

There are 6 bytes per accelerometer reading (XLow, XHigh, YLow, YHigh, ZLow, ZHigh)

I need to do 1000 readings per second with both accelerometers

Thus,
My total data used per second is 336k bits/s which is within my limit of 400k bits/s.

I am not sure if I am doing these calculations correctly.

Question:

How much data am I transmitting per second with two accelerometers reading 1000 times per second on i2c?

答:
Your math seems to be a bit off; for this accelerometer (from the datasheet: https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf), in order to read the 6 bytes of XYZ sample data, you need to perform a 6-byte burst read of the registers. What this means in terms of data transfer is a write of the register address to the accelerometer (0x31) then a burst read of 6 bytes continuously. Each of these two transfers requires sending first the I2C device address and the R/W bit, as well as an ACK/NAK per byte, including the address bytes, as well as START/REPEAT START/STOP conditions. So, over all, an individual transfer to get a single sample (ie, a single XYZ acceleration vector) is as follows:

```<code>Start (*) | Device Address: 0x1D (7) | Write: 0 (1) | ACK (1) | Register Address: 0x31 (8) | ACK (1) | Repeat Start (*) | Device Address: 0x1D (7) | Read: 1 (1) | ACK (1) | DATA0 (8) | ACK(1) | DATA1 (8) | ACK (1) | ... | DATA5 (8) | NAK (1) | Stop (*)
</code>```

If we add all that up, we get 81+3 bits of data that need to be transmitted. Note first that the START, REPEAT START and STOP might not actually take a bits worth of time each but for simplicity we can assume they do. Note also that while the device address is only 7 bits, you always need to postpend the READ/WRITE bit, so an I2C transaction is always 8 bits + ACK/NAK, so 9 bits in total. Note also, the I2C max transfer rate really defines the max SCK speed the device can handle, so in fast mode, the SCK is at most 400KHz (thus 400Kbps at most, but because of the protocol, you'll get less in real data). Thus, 84 bits at 400KHz means that we can transfer a sample in 0.21 ms or ~4700 samples/sec assuming no gaps or breaks in transmission.

Since you need to read 2 samples every 1ms (2 accelerometers, so 84 bits * 2 = 164 bits/sample or 164Kbps at 1KHz sampling rate), this should at least be possible for fast mode I2C. However, you will need to be careful that you are taking full use of the I2C controller. Depending on the software layer you are working on, it might be difficult to issue I2C burst reads fast enough (ie, 2 burst read transactions within 1ms). Using the FIFO on the accelerometer would significantly help the latency requirement, meaning instead of having 1ms to issue two burst reads, you can delay up to 32ms to issue 64 burst reads (since you have 2 accelerometers); but since you need to issue a new burst read to read the next sample, you'll have to be careful about the delay introduced by software between calls to whatever API youre using to perform the I2C transactions.

Body:
Your math seems to be a bit off; for this accelerometer (from the datasheet: https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf), in order to read the 6 bytes of XYZ sample data, you need to perform a 6-byte burst read of the registers. What this means in terms of data transfer is a write of the register address to the accelerometer (0x31) then a burst read of 6 bytes continuously. Each of these two transfers requires sending first the I2C device address and the R/W bit, as well as an ACK/NAK per byte, including the address bytes, as well as START/REPEAT START/STOP conditions. So, over all, an individual transfer to get a single sample (ie, a single XYZ acceleration vector) is as follows:

Start (*) | Device Address: 0x1D (7) | Write: 0 (1) | ACK (1) | Register Address: 0x31 (8) | ACK (1) | Repeat Start (*) | Device Address: 0x1D (7) | Read: 1 (1) | ACK (1) | DATA0 (8) | ACK(1) | DATA1 (8) | ACK (1) | ... | DATA5 (8) | NAK (1) | Stop (*)

If we add all that up, we get 81+3 bits of data that need to be transmitted. Note first that the START, REPEAT START and STOP might not actually take a bits worth of time each but for simplicity we can assume they do. Note also that while the device address is only 7 bits, you always need to postpend the READ/WRITE bit, so an I2C transaction is always 8 bits + ACK/NAK, so 9 bits in total. Note also, the I2C max transfer rate really defines the max SCK speed the device can handle, so in fast mode, the SCK is at most 400KHz (thus 400Kbps at most, but because of the protocol, you'll get less in real data). Thus, 84 bits at 400KHz means that we can transfer a sample in 0.21 ms or ~4700 samples/sec assuming no gaps or breaks in transmission.

Since you need to read 2 samples every 1ms (2 accelerometers, so 84 bits * 2 = 164 bits/sample or 164Kbps at 1KHz sampling rate), this should at least be possible for fast mode I2C. However, you will need to be careful that you are taking full use of the I2C controller. Depending on the software layer you are working on, it might be difficult to issue I2C burst reads fast enough (ie, 2 burst read transactions within 1ms). Using the FIFO on the accelerometer would significantly help the latency requirement, meaning instead of having 1ms to issue two burst reads, you can delay up to 32ms to issue 64 burst reads (since you have 2 accelerometers); but since you need to issue a new burst read to read the next sample, you'll have to be careful about the delay introduced by software between calls to whatever API youre using to perform the I2C transactions.


问:
How to do sampling in sql query to get dataframe with pandas
Note my question is a bit different here:

I am working with pandas on a dataset that has a lot of data (10M+):

```<code>q = "SELECT COUNT(*) as total FROM `<public table>`"
df = pd.read_gbq(q, project_id=project, dialect='standard')
</code>```

I know I can do with pandas function with a frac option like

```<code>df_sample = df.sample(frac=0.01)
</code>```

however, I do not want to generate the original df with that size. I wonder what is the best practice to generate a dataframe with data already sampled.

I've read some sql posts showing the sample data was generated from a slice, that is absolutely not accepted in my case. The sample data needs to be evenly distributed as much as possible.

Can anyone shed me with more light?

Thank you very much.

UPDATE:

Below is a table showing how the data looks like:

Reputation is the field I am working on. You can see majority records have a very small reputation.

I don't want to work with a dataframe with all the records, I want the sampled data also looks like the un-sampled data, for example, similar histogram, that's what I meant "evenly".

I hope this clarifies a bit.

答:
A simple random sample can be performed using the following syntax:

```<code>select * from mydata where rand()>0.9
</code>```

This gives each row in the table a 10% chance of being selected. It doesn't guarantee a certain sample size or guarantee that every bin is represented (that would require a stratified sample). Here's a fiddle of this approach

http://sqlfiddle.com/#!9/21d1ee/2

On average, random sampling will provide a distribution the same as that of the underlying data, so meets your requirement. However if you want to 'force' the sample to be more representative or force it to be a certain size we need to look at something a little more advanced.

Body:
Note my question is a bit different here:

I am working with pandas on a dataset that has a lot of data (10M+):

q = "SELECT COUNT(*) as total FROM `<public table>`"
df = pd.read_gbq(q, project_id=project, dialect='standard')

I know I can do with pandas function with a frac option like

df_sample = df.sample(frac=0.01)

however, I do not want to generate the original df with that size. I wonder what is the best practice to generate a dataframe with data already sampled.

I've read some sql posts showing the sample data was generated from a slice, that is absolutely not accepted in my case. The sample data needs to be evenly distributed as much as possible.

Can anyone shed me with more light?

Thank you very much.

UPDATE:

Below is a table showing how the data looks like:

Reputation is the field I am working on. You can see majority records have a very small reputation.

I don't want to work with a dataframe with all the records, I want the sampled data also looks like the un-sampled data, for example, similar histogram, that's what I meant "evenly".

I hope this clarifies a bit.

Body:
A simple random sample can be performed using the following syntax:

select * from mydata where rand()>0.9

This gives each row in the table a 10% chance of being selected. It doesn't guarantee a certain sample size or guarantee that every bin is represented (that would require a stratified sample). Here's a fiddle of this approach

http://sqlfiddle.com/#!9/21d1ee/2

On average, random sampling will provide a distribution the same as that of the underlying data, so meets your requirement. However if you want to 'force' the sample to be more representative or force it to be a certain size we need to look at something a little more advanced.


问:
ASP.NET Setup Project - how to include static files not in VS?
I am working on an ASP.NET MVC web application, and am working on the Web Setup portion. We are using SVN for version control. One of the issues is that the we are currently having is that the web designers modify and add a lot of html, css and js files that end up in the Content folders, but they don't add them to the VS project, so the new files don't get included in the installer.

One option is that we have to try to teach them to always go into VS and manually add the files, but we're on a large project and it's getting down to crunch time, so trying to get people to learn something new in a technology that they don't know will result in too many mistakes, so I'd like to work around that if possible.

Is there some way to get the setup project just to include files from a folder on the file system, instead of a project's designated content files?

Thanks!

答:
Right click on the folder in the File System view of the Web Setup project, and select Add, File...

It doesn't look like you can add an entire folder this way though, so you would have to add every file individually to the Setup program.

EDIT:

Aren't all files from your project folder included in a WebSite project in Visual Studio?  Then it's just a case of having your WebSite project and Web Setup project in the same solution, then right-click on the Web Application Folder in the Web Setup project, select Add, Project Output... and then select the WebSite Project in the drop down and Content Files from the list box and click OK.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Patrick McDonald

LastEditorDisplayName: Patrick McDonald


问:
Returning a list of words in alphabetical order - reading from files
For this code, I need to return a list of all unique words (words that only appear once in the file). Here is some of my code:

```<code>    words = []
    with open(self.filepath, 'r') as f:
        for l in f:
            new_word = l.split()

            words.append(new_word)
    return words
</code>```

A word is defined as any text that is separated by whitespace (spaces, newlines, or tabs). In addition to adding unique words to a list, I need to have them all made lowercase and in alphabetical order. I'm stuck on how I should do this. We do not have access to the file.

答:
Dedup by storing to a set, and only convert to a sorted list at the end:

```<code>def load_words(self):
    words = set()  # Use set for accumulation without dups
    with open(self.filepath) as f:
        for l in f:
            new_words = l.lower().split()  # Convert to lowercase before splitting

            words.update(new_words)  # Add all new words in bulk as individual words, not single list of words for line
    return sorted(words)  # Convert unordered set to sorted list of words
</code>```

Body:
For this code, I need to return a list of all unique words (words that only appear once in the file). Here is some of my code:

    words = []
    with open(self.filepath, 'r') as f:
        for l in f:
            new_word = l.split()

            words.append(new_word)
    return words

A word is defined as any text that is separated by whitespace (spaces, newlines, or tabs). In addition to adding unique words to a list, I need to have them all made lowercase and in alphabetical order. I'm stuck on how I should do this. We do not have access to the file.

Body:
Dedup by storing to a set, and only convert to a sorted list at the end:

def load_words(self):
    words = set()  # Use set for accumulation without dups
    with open(self.filepath) as f:
        for l in f:
            new_words = l.lower().split()  # Convert to lowercase before splitting

            words.update(new_words)  # Add all new words in bulk as individual words, not single list of words for line
    return sorted(words)  # Convert unordered set to sorted list of words


问:
python set vs tuple lookup. is Lookup in Tuple O(1)?
recently i saw a question here on python here

1: Python If statement and logical operator issue. There was someone in comments who gave an answer that it can be done like this:

1 in (1, 2, 3) to check if 1 is in present in a collection of items.but according to me this should be much faster 1 in {1, 2, 3}. as you can see there in discussions ,someone of high reputation goes on saying that ( ) is faster for fixed size input. and has faster lookup than { }. i am asking it here because i want to know for my own understanding which  one is correct and also i do not get the idea of ( ) being fiexd-size or variable size. i just asked for a refrence in that original question so i can correct myself if i am wrong but the user insits upon clearing my basics of computer science knowledge without givin g a single refrence to his argument that lookup in Tuple is O(1).so i am asking it here.

答:
The case for set has been improved in python 3.5 (perhaps earlier). Here is my test function:

```<code>def is_valid(x):
  return x in ('name', 'known_as')
</code>```

The code generated is:

```<code>  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               3 (('name', 'known_as'))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE
</code>```

Changing the tuple to a set generates this code:

```  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               3 (frozenset({'name', 'known_as'}))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE
```

Python 3.7 and 3.8 generate the same code for both cases. The timing results are:

```
$ python3.5 -m timeit -s "def is_valid(x): return x in {'name', 'known_as'}" "is_valid('')"
10000000 loops, best of 3: 0.0815 usec per loop
$ python3.5 -m timeit -s "def is_valid(x): return x in ('name', 'known_as')" "is_valid('')"
10000000 loops, best of 3: 0.0997 usec per loop
```

Passing 'name' to is_valid for the tuple case runs in 0.0921 usec per loop, still slower than set.

Body:
The case for set has been improved in python 3.5 (perhaps earlier). Here is my test function:

def is_valid(x):
  return x in ('name', 'known_as')

The code generated is:

  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               3 (('name', 'known_as'))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE

Changing the tuple to a set generates this code:

  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               3 (frozenset({'name', 'known_as'}))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE

Python 3.7 and 3.8 generate the same code for both cases. The timing results are:

$ python3.5 -m timeit -s "def is_valid(x): return x in {'name', 'known_as'}" "is_valid('')"
10000000 loops, best of 3: 0.0815 usec per loop
$ python3.5 -m timeit -s "def is_valid(x): return x in ('name', 'known_as')" "is_valid('')"
10000000 loops, best of 3: 0.0997 usec per loop

Passing 'name' to is_valid for the tuple case runs in 0.0921 usec per loop, still slower than set.


问:
Java Implement locking mechanism with persistent storage
I have implemented Groovy / Java JAR file with methods to install apps on mobile devices as well as get properties of the apps installed on a mobile device and the properties of a device.

I would like to implement a read and write locking mechanism that allows only a certain number of users access to a device. The write lock would be: 1 request per mobile device and for a read lock 10 requests per mobile device.

Java Semaphore seems like a good way to solve this allowing a number of requests allocated for a read and write lock. But I also need to store the states of each lock acquired against each device persistently.

Any advice on how to do this even without Semaphores would be appreciated. I anticipate less than 50 devices and less than 100 concurrent user requests.

答:
You can use ReentrantReadWriteLock with BlockingQueue. ReentrantReadWriteLock is used to allow one writer, while BlockingQueue limits N readers to read at the same time. Something like this:

```<code>import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class DeviceHandler
{
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private BlockingQueue<Object> readersQueue = new ArrayBlockingQueue<>(10);

    public void read() throws InterruptedException
    {
        // if queue is full, this blocks until another thread removes an object
        readersQueue.put(new Object());
        // this blocks if another thread acquires the write lock
        reentrantReadWriteLock.readLock().lock();

        // do read action

        reentrantReadWriteLock.readLock().unlock();
        readersQueue.take();
    }

    public void write()
    {
        // this blocks if the read lock is acquired by other threads
        reentrantReadWriteLock.writeLock().lock();

        // do write action

        reentrantReadWriteLock.writeLock().unlock();
    }
}
</code>```

Body:
You can use ReentrantReadWriteLock with BlockingQueue. ReentrantReadWriteLock is used to allow one writer, while BlockingQueue limits N readers to read at the same time. Something like this:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class DeviceHandler
{
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private BlockingQueue<Object> readersQueue = new ArrayBlockingQueue<>(10);

    public void read() throws InterruptedException
    {
        // if queue is full, this blocks until another thread removes an object
        readersQueue.put(new Object());
        // this blocks if another thread acquires the write lock
        reentrantReadWriteLock.readLock().lock();

        // do read action

        reentrantReadWriteLock.readLock().unlock();
        readersQueue.take();
    }

    public void write()
    {
        // this blocks if the read lock is acquired by other threads
        reentrantReadWriteLock.writeLock().lock();

        // do write action

        reentrantReadWriteLock.writeLock().unlock();
    }
}


问:
SQL Server Insert Row: Inserting a row per "group"
I am wanting to insert multiple rows into a table based on the "Material" column. Attached below is a snippet of the table:

```<code>+----------+---------+-----------+
| Material | Station | BuildTime |
+----------+---------+-----------+
| ABC      |    #1   |         5 |
| ABC      |    #2   |        10 |
| ABC      |    #3   |        15 |
| DEF      |    #1   |         7 |
| DEF      |    #2   |        12 |
| DEF      |    #3   |        19 |
| GHI      |    #1   |        11 |
| GHI      |    #2   |        24 |
| GHI      |    #3   |        13 |
+----------+---------+-----------+
</code>```

As you can see, there are three types of material here at three different stations - making for a total of 9 entries. Let's say I wanted to add a "Station #4" row for each type of material. How can I insert per material "group"?

In my specific case, the "buildtime" value of Station #4 will all be identical with a value of 50.

This seems simple if there were truly only three material groups, but in the actual case, there are hundreds. Is there a way to parse through them and insert a row per group?

Thanks in advance.

答:
You can use insert:

```<code>insert into t (material, station, buildtime)
   select distinct material, '#4', 50
   from t;
</code>```

Body:
I am wanting to insert multiple rows into a table based on the "Material" column. Attached below is a snippet of the table:

+----------+---------+-----------+
| Material | Station | BuildTime |
+----------+---------+-----------+
| ABC      |    #1   |         5 |
| ABC      |    #2   |        10 |
| ABC      |    #3   |        15 |
| DEF      |    #1   |         7 |
| DEF      |    #2   |        12 |
| DEF      |    #3   |        19 |
| GHI      |    #1   |        11 |
| GHI      |    #2   |        24 |
| GHI      |    #3   |        13 |
+----------+---------+-----------+

As you can see, there are three types of material here at three different stations - making for a total of 9 entries. Let's say I wanted to add a "Station #4" row for each type of material. How can I insert per material "group"?

In my specific case, the "buildtime" value of Station #4 will all be identical with a value of 50.

This seems simple if there were truly only three material groups, but in the actual case, there are hundreds. Is there a way to parse through them and insert a row per group?

Thanks in advance.

Body:
You can use insert:

insert into t (material, station, buildtime)
   select distinct material, '#4', 50
   from t;


问:
How to use grep function to separate multiple column with common name in R?
For the following data set, I would like to separate columns with beta1 only.

```<code>mydata
         beta1_C1 beta2_C2 beta1_C2 beta2_C1 beta3_C1 beta4_C2 beta4_C1 beta21_C1 beta21_C2 beta10_C1
    [1,]        1        9       17       25       33       41       49        57        65        73
    [2,]        2       10       18       26       34       42       50        58        66        74
    [3,]        3       11       19       27       35       43       51        59        67        75
    [4,]        4       12       20       28       36       44       52        60        68        76
    [5,]        5       13       21       29       37       45       53        61        69        77
    [6,]        6       14       22       30       38       46       54        62        70        78
    [7,]        7       15       23       31       39       47       55        63        71        79
    [8,]        8       16       24       32       40       48       56        64        72        80
</code>```

I am using the following code but beta10 is showing in the output which I do not want. In my expected data, I should have only beta1_C1 and beta1_C2 columns.

```<code> dat1=mydata[,grep("beta1",colnames(mydata))]
 dat1
         beta1_C1 beta1_C2 beta10_C1
    [1,]        1       17        73
    [2,]        2       18        74
    [3,]        3       19        75
    [4,]        4       20        76
    [5,]        5       21        77
    [6,]        6       22        78
    [7,]        7       23        79
    [8,]        8       24        80
</code>```

Any help is appreciated.

答:
We can use tidyverse

```<code>library(dplyr)
mydata %>%
      select(starts_with('beta1_C'))
</code>```

Or with matches

```<code>mydata %>%
     select(matches('^beta1_C\\d+'))
</code>```

Body:
For the following data set, I would like to separate columns with beta1 only.

mydata
         beta1_C1 beta2_C2 beta1_C2 beta2_C1 beta3_C1 beta4_C2 beta4_C1 beta21_C1 beta21_C2 beta10_C1
    [1,]        1        9       17       25       33       41       49        57        65        73
    [2,]        2       10       18       26       34       42       50        58        66        74
    [3,]        3       11       19       27       35       43       51        59        67        75
    [4,]        4       12       20       28       36       44       52        60        68        76
    [5,]        5       13       21       29       37       45       53        61        69        77
    [6,]        6       14       22       30       38       46       54        62        70        78
    [7,]        7       15       23       31       39       47       55        63        71        79
    [8,]        8       16       24       32       40       48       56        64        72        80

I am using the following code but beta10 is showing in the output which I do not want. In my expected data, I should have only beta1_C1 and beta1_C2 columns.

 dat1=mydata[,grep("beta1",colnames(mydata))]
 dat1
         beta1_C1 beta1_C2 beta10_C1
    [1,]        1       17        73
    [2,]        2       18        74
    [3,]        3       19        75
    [4,]        4       20        76
    [5,]        5       21        77
    [6,]        6       22        78
    [7,]        7       23        79
    [8,]        8       24        80

Any help is appreciated.

Body:
We can use tidyverse

library(dplyr)
mydata %>%
      select(starts_with('beta1_C'))

Or with matches

mydata %>%
     select(matches('^beta1_C\\d+'))


问:
Monosnap on Windows - Shortcut key setting to copy to clipboard
In MacOS, I will modify my screenshot key to use monosnap and then after no modifications or minor ones, I will then use a shortcut key to place it in my clipboard.  I am trying to make the same workflow in the windows version.

Here is what I see:

I do not see a setting to "Copy image to clipboard":

If there another way to achieve my goal, please share.  Oh btw, I would rather not require the option to upload my images to an external service.  Thank you!

答:
Pretty much the same:
 1. Focus your Monosnap Editor
 2. Press Ctrl+C

Now you have your edited image in clipboard.


问:
Python string format x or less digits
Is there a easy one-liner in python 3.x to print a number with x or less decimal places?

I want

```<code>numbers = [7, 7.7, 7.77, 7.777]

for number in numbers:
    print("{:.less than 3}".format(number))
</code>```

to return

```<code>7
7.7
7.77
7.78
</code>```

答:
```<code>for number in numbers:
    print('%.3g' % number)

</code>```

Title: Python string format x or less digits

Body:
Is there a easy one-liner in python 3.x to print a number with x or less decimal places?

I want

numbers = [7, 7.7, 7.77, 7.777]

for number in numbers:
    print("{:.less than 3}".format(number))

to return

7
7.7
7.77
7.78


问:
How to remove invalid database connection from pool
I am using connection pooling of tomcat with oracle database. It is working fine, but when i use my application after a long time it is giving error that "connection reset". I am getting this error because of physical connection at oracle server closed before logical connection closed at tomcat datasource. So before getting the connection from datasource i am checking the connection validity with isValid(0) method of connection object which gives false if the physical connection was closed. But i don't know how to remove that invalid connection object from the pool.

答: Try closing it and opening it if it's invalid. I mean u would reinitialize it in this way so u won't need to remove it from the pool and reuse it.</p>


问:
Cythonize python modules with same name under different packages
I am cythonizing some of my python modules within a project.

python 3.7.*

Ubuntu (different versions depending on docker images and dev environments)

Cython==0.29.14

I'm running into an issue where if I have modules with the same name in different packages all of them get transpiled to .c but <s>only one of them gets compiled with resulting .so file.</s> for one of them the .so file is generated in the current directory instead of --inplace alongside the source file.

Folder structure:

```<code>    .
    ├── my_pkg
    │   ├── training
    │   │   └── util.py
    │   └── validation
    │       └── util.py
    └── compile.py
</code>```

compile.py looks like this:

from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension

ext_modules = [
    Extension("*",
        ["./my_pgk/*/*.py"]
    )
]

setup(
    name="my_project",
    ext_modules=cythonize(
        ext_modules,
        compiler_directives={'language_level' : "3"}),
)
```

<p>Execution:</p>

```python compile.py build_ext --inplace
```

<p><strong>EDIT</strong>:
Looking at (part of) the command log I notice that for one module the .so file is actually generated but not "--inplace" alongside the source python&c files but rather in the current directory. Tried it with more than two modules and indeed for all but the last one the .so is placed correctly but for the last one it is in the current directory.</p>

<p>Output:</p>

```building 'my_pgk.training.utils' extension
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.7/./src/app/training/utils.o -o ./my_pgk/training/utils.cpython-37m-x86_64-linux-gnu.so

building 'utils' extension
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.7/./my_pgk/validation/utils.o -o ./utils.cpython-37m-x86_64-linux-gnu.so
```

<p>Folder structure after run:</p>

```    .
    ├── my_pkg
    │   ├── training
    │   │   ├── util.py
    │   │   ├── util.c
    │   │   └── utils.cpython-37m-x86_64-linux-gnu.so
    │   └── validation
    │       ├── util.py
    │       └── util.c
    ├── compile.py
EDIT└── utils.cpython-37m-x86_64-linux-gnu.so // this is misplaced
```

This would generate a .c and an .so file alongside the original .py file except when there are modules with the same name even though they are in different packages.

I want to have the .so files for all .py files, obviously

I've tried listing them explicitly by name in the ext_modules list instead of a glob but that didn't do it either.

For now what I end up doing is run <s>cythonize more than once with different ext_module lists that don't include duplicate module names</s>, specifying the modules individually with intended target locations, but that's not sustainable.

How should I specify my modules and/or what options should I include to get all the .so files generated in one run? I imagine I am doling something wrong because there's no requirement for global module-name uniqueness among all (sub)packages and so it should be a usecase that is supported.

答:
Looking at the code for cythonize at the cython repo on github I realized what was happening.

Basically, if the --inplace flag is used and if the target location/name of the module is not recognized as a package, i.e. a folder that contains an __init__.py[c|x|d] file, then cythonize walks up the supplied target path string until it finds a package or until the path is "exhausted" in which case it just saves the generated file in the current directory.

So what happened was indeed that in one particular package I was missing a __init__.py file and that's why the .so was "misplaced". I just failed to recognize that it was always the same module that was failing.

The simplified example that I provided above was not reflecting the actual situation since no init files were present

Body:
I am cythonizing some of my python modules within a project.

python 3.7.*

Ubuntu (different versions depending on docker images and dev environments)

Cython==0.29.14

I'm running into an issue where if I have modules with the same name in different packages all of them get transpiled to .c but <s>only one of them gets compiled with resulting .so file.</s> for one of them the .so file is generated in the current directory instead of --inplace alongside the source file.

Folder structure:

    .
    ├── my_pkg
    │   ├── training
    │   │   └── util.py
    │   └── validation
    │       └── util.py
    └── compile.py

compile.py looks like this:

from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension

ext_modules = [
    Extension("*",
        ["./my_pgk/*/*.py"]
    )
]

setup(
    name="my_project",
    ext_modules=cythonize(
        ext_modules,
        compiler_directives={'language_level' : "3"}),
)

Execution:

python compile.py build_ext --inplace

EDIT:
Looking at (part of) the command log I notice that for one module the .so file is actually generated but not "--inplace" alongside the source python&c files but rather in the current directory. Tried it with more than two modules and indeed for all but the last one the .so is placed correctly but for the last one it is in the current directory.

Output:

building 'my_pgk.training.utils' extension
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.7/./src/app/training/utils.o -o ./my_pgk/training/utils.cpython-37m-x86_64-linux-gnu.so

building 'utils' extension
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.7/./my_pgk/validation/utils.o -o ./utils.cpython-37m-x86_64-linux-gnu.so

Folder structure after run:

    .
    ├── my_pkg
    │   ├── training
    │   │   ├── util.py
    │   │   ├── util.c
    │   │   └── utils.cpython-37m-x86_64-linux-gnu.so
    │   └── validation
    │       ├── util.py
    │       └── util.c
    ├── compile.py
EDIT└── utils.cpython-37m-x86_64-linux-gnu.so // this is misplaced

This would generate a .c and an .so file alongside the original .py file except when there are modules with the same name even though they are in different packages.

I want to have the .so files for all .py files, obviously

I've tried listing them explicitly by name in the ext_modules list instead of a glob but that didn't do it either.

For now what I end up doing is run <s>cythonize more than once with different ext_module lists that don't include duplicate module names</s>, specifying the modules individually with intended target locations, but that's not sustainable.

How should I specify my modules and/or what options should I include to get all the .so files generated in one run? I imagine I am doling something wrong because there's no requirement for global module-name uniqueness among all (sub)packages and so it should be a usecase that is supported.


问:
How to convert strings of Year-Mon to the correct date format when exporting data in R?
I'm trying to ensure that the As_of_Dt converts to date correctly when I export the data from R as a csv. Currently, when I export the data to excel. It converts the As_of_Dt incorrectly. The month basically stays the same but the year becomes the day and the year becomes the current year (2020). If the as_of_dt is 18-Jan it becomes 1/18/20 in excel. I'm trying to prevent this from happening.

I would like this column to export like:
1/1/18 when the string is "18-Jan"

Currently, I tried

```<code>Data$As_of_Dt2<- zoo::as.Date(zoo::as.yearmon(Data$As_of_Dt, "%y-%b"))
</code>```

But there were some values that were NA in this new column I made.

Below you will find all the possible dates for the column As_of_Dt.

Update: I figured out that the date can sometimes be Jan-2018 or 2018-Jan. Is there a function that can convert these two situations into 1/1/18?

Body:
I'm trying to ensure that the As_of_Dt converts to date correctly when I export the data from R as a csv. Currently, when I export the data to excel. It converts the As_of_Dt incorrectly. The month basically stays the same but the year becomes the day and the year becomes the current year (2020). If the as_of_dt is 18-Jan it becomes 1/18/20 in excel. I'm trying to prevent this from happening.

I would like this column to export like:
1/1/18 when the string is "18-Jan"

Currently, I tried

Data$As_of_Dt2<- zoo::as.Date(zoo::as.yearmon(Data$As_of_Dt, "%y-%b"))

But there were some values that were NA in this new column I made.

Below you will find all the possible dates for the column As_of_Dt.

Update: I figured out that the date can sometimes be Jan-2018 or 2018-Jan. Is there a function that can convert these two situations into 1/1/18?

Body:
You may use strptime.

strptime(dat, "%d-%b")
# [1] "2020-11-20 CET"  "2020-11-15 CET"  "2020-01-20 CET"  "2020-06-20 CEST"
# [5] "2020-02-20 CET"  "2020-04-19 CEST" "2020-12-16 CET"  "2020-08-20 CEST"
# [9] "2020-01-17 CET"  "2020-01-16 CET"  "2020-10-17 CEST" "2020-06-19 CEST"
# [13] "2020-08-17 CEST" "2020-05-16 CEST" "2020-10-16 CEST" "2020-08-18 CEST"
# [17] "2020-11-19 CET"  "2020-01-15 CET"  "2020-12-17 CET"  "2020-11-18 CET"

Data:

dat <- c("20-Nov", "15-Nov", "20-Jan", "20-Jun", "20-Feb", "19-Apr",
"16-Dec", "20-Aug", "17-Jan", "16-Jan", "17-Oct", "19-Jun", "17-Aug",
"16-May", "16-Oct", "18-Aug", "19-Nov", "15-Jan", "17-Dec", "18-Nov")


问:
Indirect reference to range in other sheet using VBA
In Sheet1 of my Excel file I have the following input:

```<code>           A              B
1   'Sheet2'!J:O
2
</code>```

In Cell A1 is the range that should be hidden in Sheet2 when I run this VBA:

```<code>Sub Hiding_Columns()
Sheet1.Range(Range("A1")).EntireColumn.Hidden = True
End Sub
</code>```

However, with this code I  get runtime error 1004.

What do I need to change to make it work?

答:
Perhaps the following:

```<code>Range(Sheet1.Range("A1").Value).EntireColumn.Hidden = True
</code>```

The way you have it is (when Sheet1 is the active sheet) equivalent to:

```<code>Sheet1.Range("'Sheet2'!J:O").EntireColumn.Hidden = True
</code>```

and that won't work because you've got the sheets mixed together.

Body:
In Sheet1 of my Excel file I have the following input:

           A              B
1   'Sheet2'!J:O
2

In Cell A1 is the range that should be hidden in Sheet2 when I run this VBA:

Sub Hiding_Columns()
Sheet1.Range(Range("A1")).EntireColumn.Hidden = True
End Sub

However, with this code I  get runtime error 1004.

What do I need to change to make it work?

Body:
Perhaps the following:

Range(Sheet1.Range("A1").Value).EntireColumn.Hidden = True

The way you have it is (when Sheet1 is the active sheet) equivalent to:

Sheet1.Range("'Sheet2'!J:O").EntireColumn.Hidden = True

and that won't work because you've got the sheets mixed together.


问:
How to prevent unwanted tooltip pop-up in Infragistics ComboBoxTool on ribbon control (winforms)
I have a ComboBoxTool on an UltraToolbarsManager implementing a ribbon control. No matter what I set the ToolTipText to it always displays a tooltip:

[e.g. mousing over the gdg combo show this]

I have tried setting all the other tooltip related attributes (ToolTipTextFormatted, ToolTipTitle) to null but this doesn't help.

If a non-zero length tooltip text is specified then this shows as expected

The ribbon child controls are all added programatically

The other controls on the ribbon do not have this issue

I have also tried setting-up a very simple ribbon on a dummy project and that does not exhibit this strange behaviour. So it is something else that is effecting this.

答:
Infragistics supplied an answer:

Add your own CreationFilter to the ToolbarsManager

ultraToolbarsManager1.CreationFilter = new MyCreation();

Catch the tool creation and replace the tooltip with your own implementation

```<code>public class MyCreation : IUIElementCreationFilter  {

    private readonly int max;

    public MyCreation()
    {
    }

    public MyCreation(int toolTipMaxWidth)
    {
        max = toolTipMaxWidth;
    }

    public void AfterCreateChildElements(UIElement parent)
    {
        parent.ToolTipItem = new MyToolTipItem(max);
    }

    public bool BeforeCreateChildElements(UIElement parent)
    {
        return false;
    }
}

public class MyToolTipItem : IToolTipItem   {
    private readonly int max;

    public MyToolTipItem(int maxWidth)
    {
        max = maxWidth;
    }

    public MyToolTipItem()
    {
    }

    public ToolTipInfo GetToolTipInfo(Point mousePosition, UIElement element, UIElement previousToolTipElement,
                                  ToolTipInfo toolTipInfoDefault)
    {
        // set tooltip info for ribbon ApplicationMenuButton
        var app = element as ApplicationMenuButtonUIElement;
        if (app != null)
        {
            var appmenu = ((UltraToolbarsDockAreaUIElement) ((app.Parent).Parent)).ToolbarsManager.Ribbon.ApplicationMenu;
            if (max > 0)
                toolTipInfoDefault.MaxWidth = max;
            toolTipInfoDefault.Title = appmenu.ToolTipTitle;

            string tooltiptex = appmenu.ToolTipText;
            if (!string.IsNullOrEmpty(appmenu.ToolTipTextFormatted))
            {
                toolTipInfoDefault.ToolTipTextStyle = ToolTipTextStyle.Formatted;
                tooltiptex = appmenu.ToolTipTextFormatted;
            }
            toolTipInfoDefault.ToolTipText = tooltiptex;
        }

        // set tooltip info for tools
        if (element.ToolTipItem != null && UIElement.IsContextOfType(element.GetContext(), typeof (ToolBase)))
        {
            var tool = (ToolBase) element.GetContext(typeof (ToolBase));
            var loc = tool.ToolbarsManager.DockWithinContainer.PointToScreen(new Point(0, 0));
        loc.Offset(tool.UIElement.Rect.Location.X, 185);

            if (max > 0)
                toolTipInfoDefault.MaxWidth = max;
        toolTipInfoDefault.Title = tool.SharedProps.ToolTipTitle;
        string tooltiptex = tool.SharedProps.ToolTipText;
            if (!string.IsNullOrEmpty(tool.SharedProps.ToolTipTextFormatted))
            {
                toolTipInfoDefault.ToolTipTextStyle = ToolTipTextStyle.Formatted;
                tooltiptex = tool.SharedProps.ToolTipTextFormatted;
            }
            toolTipInfoDefault.ToolTipText = tooltiptex;
            toolTipInfoDefault.DisplayStyle = Infragistics.Win.ToolTipDisplayStyle.Office2007;
            toolTipInfoDefault.Location = loc;
        }
        return toolTipInfoDefault;
    }
</code>```

Required a bit of tweaking to get the tooltip in the right place and pick-up the tooltip text from TooltipTextResolved.

Body:
Infragistics supplied an answer:

Add your own CreationFilter to the ToolbarsManager

ultraToolbarsManager1.CreationFilter = new MyCreation();

Catch the tool creation and replace the tooltip with your own implementation

public class MyCreation : IUIElementCreationFilter  {

    private readonly int max;

    public MyCreation()
    {
    }

    public MyCreation(int toolTipMaxWidth)
    {
        max = toolTipMaxWidth;
    }

    public void AfterCreateChildElements(UIElement parent)
    {
        parent.ToolTipItem = new MyToolTipItem(max);
    }

    public bool BeforeCreateChildElements(UIElement parent)
    {
        return false;
    }
}

public class MyToolTipItem : IToolTipItem   {
    private readonly int max;

    public MyToolTipItem(int maxWidth)
    {
        max = maxWidth;
    }

    public MyToolTipItem()
    {
    }

    public ToolTipInfo GetToolTipInfo(Point mousePosition, UIElement element, UIElement previousToolTipElement,
                                  ToolTipInfo toolTipInfoDefault)
    {
        // set tooltip info for ribbon ApplicationMenuButton
        var app = element as ApplicationMenuButtonUIElement;
        if (app != null)
        {
            var appmenu = ((UltraToolbarsDockAreaUIElement) ((app.Parent).Parent)).ToolbarsManager.Ribbon.ApplicationMenu;
            if (max > 0)
                toolTipInfoDefault.MaxWidth = max;
            toolTipInfoDefault.Title = appmenu.ToolTipTitle;

            string tooltiptex = appmenu.ToolTipText;
            if (!string.IsNullOrEmpty(appmenu.ToolTipTextFormatted))
            {
                toolTipInfoDefault.ToolTipTextStyle = ToolTipTextStyle.Formatted;
                tooltiptex = appmenu.ToolTipTextFormatted;
            }
            toolTipInfoDefault.ToolTipText = tooltiptex;
        }

        // set tooltip info for tools
        if (element.ToolTipItem != null && UIElement.IsContextOfType(element.GetContext(), typeof (ToolBase)))
        {
            var tool = (ToolBase) element.GetContext(typeof (ToolBase));
            var loc = tool.ToolbarsManager.DockWithinContainer.PointToScreen(new Point(0, 0));
        loc.Offset(tool.UIElement.Rect.Location.X, 185);

            if (max > 0)
                toolTipInfoDefault.MaxWidth = max;
        toolTipInfoDefault.Title = tool.SharedProps.ToolTipTitle;
        string tooltiptex = tool.SharedProps.ToolTipText;
            if (!string.IsNullOrEmpty(tool.SharedProps.ToolTipTextFormatted))
            {
                toolTipInfoDefault.ToolTipTextStyle = ToolTipTextStyle.Formatted;
                tooltiptex = tool.SharedProps.ToolTipTextFormatted;
            }
            toolTipInfoDefault.ToolTipText = tooltiptex;
            toolTipInfoDefault.DisplayStyle = Infragistics.Win.ToolTipDisplayStyle.Office2007;
            toolTipInfoDefault.Location = loc;
        }
        return toolTipInfoDefault;
    }

Required a bit of tweaking to get the tooltip in the right place and pick-up the tooltip text from TooltipTextResolved.


问:
Prepopulate HTML form based on previous field
I currently have a very simple HTML form that looks something like this:

```<code><form>
   <label for="faccountNumber">Account Number</label>
   <input type="number" class="form-control" id="faccountNumber"><br><br>
   <label for="ffirstName">First Name</label>
   <input type="text" class="form-control" id="ffirstName"><br><br>
   <label for="fsurname">Surname</label>
   <input type="text" class="form-control" id="fsurname"><br><br>
</form>
</code>```

I would like to prepopulate some values dependent on the account number entered. This is just for a mockup & so I just want to hardcode in a few examples.

For example, if the account number 1789was entered I would like to automatically prepopulate the first name as John & the surname as Smith. How can I do this?

答:
I assume the page is in an authenticated context, otherwise you'll have security problems.

The task should be done in a php page.

```<code>/*
 - get the user id from $_GET or anywhere you hold that info
 - query the database for name and surname, filtering with the retrieved id
 - assign values to $name and $surname variables
*/
<form>
   <label for="faccountNumber">Account Number</label>
   <input type="number" class="form-control" id="faccountNumber"><br><br>
   <label for="ffirstName">First Name</label>
   <input type="text" value="<?php echo $surname;?>" class="form-control" id="ffirstName"><br><br>
   <label for="fsurname">Surname</label>
   <input type="text" value="<?php echo $surname;?>" class="form-control" id="fsurname"><br><br>
</form>
</code>```

Body:
I currently have a very simple HTML form that looks something like this:

<form>
   Account Number
   <input type="number" class="form-control" id="faccountNumber">

   First Name
   <input type="text" class="form-control" id="ffirstName">

   Surname
   <input type="text" class="form-control" id="fsurname">

</form>

I would like to prepopulate some values dependent on the account number entered. This is just for a mockup & so I just want to hardcode in a few examples.

For example, if the account number 1789was entered I would like to automatically prepopulate the first name as John & the surname as Smith. How can I do this?

Body:
I assume the page is in an authenticated context, otherwise you'll have security problems.

The task should be done in a php page.

/*
 - get the user id from $_GET or anywhere you hold that info
 - query the database for name and surname, filtering with the retrieved id
 - assign values to $name and $surname variables
*/
<form>
   <label for="faccountNumber">Account Number</label>
   <input type="number" class="form-control" id="faccountNumber"><br><br>
   <label for="ffirstName">First Name</label>
   <input type="text" value="<?php echo $surname;?>" class="form-control" id="ffirstName"><br><br>
   <label for="fsurname">Surname</label>
   <input type="text" value="<?php echo $surname;?>" class="form-control" id="fsurname"><br><br>
</form>


问:
C File handling - load function keeps getting the same data from the file
whenever I load the data, the program only retrieve the first line of the file and then it loops. It looks like the problem lies within the load function and insert function because that's where the code loads the data from the file and where the data loaded insert to the array of the code, I tried adding a sign if the code really loops the, and it really did loop. I think the problem is !feof int the load function but i don't know if it really is.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <stdbool.h>
#define MAX 10

//Variables
int Ident[MAX];
float grade[MAX];
char name[MAX][20];
int last;

//Functions
int GetRec();
float ComputeGrade(int q1, int q2);
void display();
void EmpList();
int IsEmpty();
int IsFull();
int DelRec();
int menu();
void CheckID(int x);
void save();
void load();
void insert(int x, char n[], float a);

int main(){
    EmpList();
    load();
    menu();
}
void EmpList(){
    last = -1;
}
int IsFull(){
    return (last==MAX - 1);
}
int IsEmpty(){
    return (last==-1);
}
int menu(){
    int Opt;
    do{
        system("cls");
        printf("[1] Insert\n");
        printf("[2] Delete\n");
        printf("[3] Display\n");
        printf("[4] Exit\n");
        scanf("%d", &Opt);
        switch(Opt){
            case 1: system("cls");
                    GetRec();break;
            case 2: DelRec();
                    break;
            case 3: system("cls");
                    display();
                    break;
            case 4: save();
                    return 0;
                    break;
            default:menu();
                    break;
        }
    }while(1);
}
int GetRec(){
    char NameTemp[20];
    int quiz_1, quiz_2, Idtemp;
    float ave;
        printf("Insert Mode\n");
        printf("Input ID no:");
        scanf("%d", &Idtemp);
        printf("Input name: ");
        scanf("%s", &NameTemp);
        printf("Input quiz 1: ");
        scanf("%d", &quiz_1);
        printf("Input quiz 2: ");
        scanf("%d", &quiz_2);
        ave = ComputeGrade(quiz_1, quiz_2);
        CheckID(Idtemp);
        insert(Idtemp, NameTemp, ave);
}
void CheckID(int x){
    for(int check = 0; check <= last; check++){
        if(x == Ident[check]){
            printf("Id already exist\nTry another one.");
            getch();
            system("cls");
            GetRec();
        }
    }
}
void insert(int x, char n[], float a){
    char *ptr;
    if (IsFull()){
        printf("Full.");
        getch();
        menu();
    }
    else if(x == -1){
            EmpList();
        }
    else{
        last++;
        printf("%d", last);
        Ident[last] = x;
        grade[last] = a;
        ptr = n;
        strcpy(name[last], n);
    }
}
float ComputeGrade(int q1, int q2){
    float ave;
    ave = (q1 + q2) / 2.0;
    return ave;
}
int DelRec(){
    printf("Delete Mode\n");
    printf("Input Id no: ");
    getch();
    main();
}
void display(){
    if(IsEmpty()){
        printf("Empty");
        getch();
        menu();
    }
    else{
        for(int counter = 0; counter <= last; counter++){
            printf("[%d]%s\t%.2f\n", Ident[counter], name[counter], grade[counter]);
        }getch();
    }
}
void save(){
    FILE *fp;
    fp=fopen("database.dbf","w+");
    for(int counter = 0; counter <= last; counter++){
       fprintf(fp, "%d %s %.2f\n", Ident[counter], name[counter], grade[counter]);
    }
    fclose(fp);
}
void load(){
    FILE *fp;
    int id = -1,grd = 0;
    char nm[20];
    fp=fopen("database.dbf","r+");
    while(!feof(fp)){
        fscanf(fp,"%d %s %d", &id, &nm, &grd);
        insert(id, nm, grd);
    }
    fclose(fp);
}
</code>```

答: Your load() function always does insert(-1, ...) and insert() tests for -1 and does something you don't want it to do.

Body:
whenever I load the data, the program only retrieve the first line of the file and then it loops. It looks like the problem lies within the load function and insert function because that's where the code loads the data from the file and where the data loaded insert to the array of the code, I tried adding a sign if the code really loops the, and it really did loop. I think the problem is !feof int the load function but i don't know if it really is.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <stdbool.h>
#define MAX 10

//Variables
int Ident[MAX];
float grade[MAX];
char name[MAX][20];
int last;

//Functions
int GetRec();
float ComputeGrade(int q1, int q2);
void display();
void EmpList();
int IsEmpty();
int IsFull();
int DelRec();
int menu();
void CheckID(int x);
void save();
void load();
void insert(int x, char n[], float a);

int main(){
    EmpList();
    load();
    menu();
}
void EmpList(){
    last = -1;
}
int IsFull(){
    return (last==MAX - 1);
}
int IsEmpty(){
    return (last==-1);
}
int menu(){
    int Opt;
    do{
        system("cls");
        printf("[1] Insert\n");
        printf("[2] Delete\n");
        printf("[3] Display\n");
        printf("[4] Exit\n");
        scanf("%d", &Opt);
        switch(Opt){
            case 1: system("cls");
                    GetRec();break;
            case 2: DelRec();
                    break;
            case 3: system("cls");
                    display();
                    break;
            case 4: save();
                    return 0;
                    break;
            default:menu();
                    break;
        }
    }while(1);
}
int GetRec(){
    char NameTemp[20];
    int quiz_1, quiz_2, Idtemp;
    float ave;
        printf("Insert Mode\n");
        printf("Input ID no:");
        scanf("%d", &Idtemp);
        printf("Input name: ");
        scanf("%s", &NameTemp);
        printf("Input quiz 1: ");
        scanf("%d", &quiz_1);
        printf("Input quiz 2: ");
        scanf("%d", &quiz_2);
        ave = ComputeGrade(quiz_1, quiz_2);
        CheckID(Idtemp);
        insert(Idtemp, NameTemp, ave);
}
void CheckID(int x){
    for(int check = 0; check <= last; check++){
        if(x == Ident[check]){
            printf("Id already exist\nTry another one.");
            getch();
            system("cls");
            GetRec();
        }
    }
}
void insert(int x, char n[], float a){
    char *ptr;
    if (IsFull()){
        printf("Full.");
        getch();
        menu();
    }
    else if(x == -1){
            EmpList();
        }
    else{
        last++;
        printf("%d", last);
        Ident[last] = x;
        grade[last] = a;
        ptr = n;
        strcpy(name[last], n);
    }
}
float ComputeGrade(int q1, int q2){
    float ave;
    ave = (q1 + q2) / 2.0;
    return ave;
}
int DelRec(){
    printf("Delete Mode\n");
    printf("Input Id no: ");
    getch();
    main();
}
void display(){
    if(IsEmpty()){
        printf("Empty");
        getch();
        menu();
    }
    else{
        for(int counter = 0; counter <= last; counter++){
            printf("[%d]%s\t%.2f\n", Ident[counter], name[counter], grade[counter]);
        }getch();
    }
}
void save(){
    FILE *fp;
    fp=fopen("database.dbf","w+");
    for(int counter = 0; counter <= last; counter++){
       fprintf(fp, "%d %s %.2f\n", Ident[counter], name[counter], grade[counter]);
    }
    fclose(fp);
}
void load(){
    FILE *fp;
    int id = -1,grd = 0;
    char nm[20];
    fp=fopen("database.dbf","r+");
    while(!feof(fp)){
        fscanf(fp,"%d %s %d", &id, &nm, &grd);
        insert(id, nm, grd);
    }
    fclose(fp);
}


问:
How do I pass an object to a button click event handler in WPF? C#
I'm building out a simple ToDoList app using C# and WPF.
The goal is that when the button is clicked. The text in a TextBox will be added as a new element in a List which is an existing object instance.

To do this I've updated the Button click event handler's signature to include a parameter to pass the List object.
When I compile this code I get an error thrown from my XAML file at the line which contains the Click="AddTaskButton_Click"

Error: No overload for 'AddTaskButton_Click' matches delegate 'RoutedEventHandler'

What could be throwing this error? I've seen other code samples where this compiles fine.
Is there another way to accomplish passing "data" or an object to an event handler in WPF? I'm new to WPF.

XAML

```<code><Button
x:Name="AddTaskButton"  Content="+ Add"
Click="AddTaskButton_Click">
</Button>
</code>```

Backend C#

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<string> taskList = new Tasklist {"Task A", "Task B", "Task C"}

        AddTaskButton.Click += (object sender, RoutedEventArgs e) => { AddTaskButton_Click(sender, e, taskList); };
    }

    private void AddTaskButton_Click(object sender, RoutedEventArgs e, List<string> taskList)
    {
        // do something
    }
}
</code>```

答:
Use this XAML code

<Button
x:Name="AddTaskButton"  Content="+ Add" >
</Button>
```

You've added an eventhander on the XAML code too. You can only add event handlers with 2 parameters: an object and a RoutedEventArgs. Your XAML code adds an other event handler to AddTaskButton_Click witch has a 3th parameter type of List<string>.

Keep the C# code as is. It adds also an event handler on the correct way using the lambda expression at the constructor. But add a semicolon where you declare taskList and change Tasklist (with a capital T and a little l) to List<string>.

Body:
I'm building out a simple ToDoList app using C# and WPF.
The goal is that when the button is clicked. The text in a TextBox will be added as a new element in a List which is an existing object instance.

To do this I've updated the Button click event handler's signature to include a parameter to pass the List object.
When I compile this code I get an error thrown from my XAML file at the line which contains the Click="AddTaskButton_Click"

Error: No overload for 'AddTaskButton_Click' matches delegate 'RoutedEventHandler'

What could be throwing this error? I've seen other code samples where this compiles fine.
Is there another way to accomplish passing "data" or an object to an event handler in WPF? I'm new to WPF.

XAML

<Button
x:Name="AddTaskButton"  Content="+ Add"
Click="AddTaskButton_Click">
</Button>

Backend C#

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<string> taskList = new Tasklist {"Task A", "Task B", "Task C"}

        AddTaskButton.Click += (object sender, RoutedEventArgs e) => { AddTaskButton_Click(sender, e, taskList); };
    }

    private void AddTaskButton_Click(object sender, RoutedEventArgs e, List<string> taskList)
    {
        // do something
    }
}

Body:
Use this XAML code

<Button
x:Name="AddTaskButton"  Content="+ Add" >
</Button>

You've added an eventhander on the XAML code too. You can only add event handlers with 2 parameters: an object and a RoutedEventArgs. Your XAML code adds an other event handler to AddTaskButton_Click witch has a 3th parameter type of List<string>.

Keep the C# code as is. It adds also an event handler on the correct way using the lambda expression at the constructor. But add a semicolon where you declare taskList and change Tasklist (with a capital T and a little l) to List<string>.


问:
Testing the availability of std::byte
I'd like to use C++17's std::byte type if it's available, and fall back to using unsigned char if not, i.e. something along the lines of

```<code>#include <cstddef>

namespace my {
#if SOMETHING
using byte = std::byte;
#else
using byte = unsigned char;
#endif
}
</code>```

Unfortunately it seems that std::byte didn't come come with the usual feature test macro, so it's not obvious what SOMETHING above should be. (AFAIK the value of __cplusplus for '17 hasn't been set yet, so I can't test for that either.)

So, does anybody know of a way to detect whether std::byte is available on the big three compilers?

答:
If you want to test availability of std::byte introduced by C++17, you should use __cpp_lib_byte macro (full list of feature testing macros is here).

The sample usage:

#include <iostream>
#include <cstddef>

#if __cpp_lib_byte
using byte = std::byte;
#else
using byte = unsigned char;
#endif

int main() {
    return 0;
}
```

Title: Testing the availability of std::byte

Body:
I'd like to use C++17's std::byte type if it's available, and fall back to using unsigned char if not, i.e. something along the lines of

#include <cstddef>

namespace my {
#if SOMETHING
using byte = std::byte;
#else
using byte = unsigned char;
#endif
}

Unfortunately it seems that std::byte didn't come come with the usual feature test macro, so it's not obvious what SOMETHING above should be. (AFAIK the value of __cplusplus for '17 hasn't been set yet, so I can't test for that either.)

So, does anybody know of a way to detect whether std::byte is available on the big three compilers?


问:
Get DownloadURL from an uploaded File
I want to know how to get the getDownloadURL() when i uploaded an file. I want to upload an file and get the downloadURL for the file and then store it the Database.
Can you give an example how to do it in one function?

答:
```<code>String filePath = "videoTitle.mp4";
    StorageReference ref = FirebaseStorage.instance.ref().child(filePath);
    StorageUploadTask uploadTask =
        ref.putFile(video, StorageMetadata(contentType: "video/mp4"));

    await uploadTask.onComplete;
    if (uploadTask.isComplete) {
      String downloadUrl = await ref.getDownloadURL();
      return downloadUrl;
    }
</code>```

Title: Get DownloadURL from an uploaded File


问:
How to colour the branches of an unrooted tree using a variable in R
I would like to generated unrooted neighbour joining trees from input haplotype data, and then colour the branches of the trees based on a variable.
I am using the packages Ape and ggtree.
The haplotypes and co-variables (metadata) are on two separate files with matching sample names.
I have been able to produce trees and colour the tips of the trees by variables, but not the tree branches.

Using mock data -

```<code># Packages
library('ggplot2')
library('ape')
library('phangorn')
library('dplyr')
library('ggtree')
library('phylobase')

# Generate haplotype dataframe
Sample <- c('Sample_A', 'Sample_B', 'Sample_C', 'Sample_D', 'Sample_E', 'Sample_F')
SNP_A <- c(0, 1, 1, 0, 1, 1)
SNP_B <- c(0, 1, 1, 0, 1, 1)
SNP_C <- c(0, 0, 1, 1, 1, 0)
SNP_D <- c(1, 1, 0, 0, 1, 0)
SNP_E <- c(0, 0, 1, 1, 0, 1)
SNP_F <- c(0, 0, 1, 1, 0, 1)
df = data.frame(Sample, SNP_A, SNP_B, SNP_C, SNP_D, SNP_E, SNP_F, row.names=c(1))
df

# Metadata
Factor_A <- c('a', 'a', 'b', 'c', 'a', 'b')
Factor_B <- c('d', 'e', 'd', 'd', 'e', 'd')
df2 = data.frame(Sample, Factor_A, Factor_B)
df2

# Generate Euclidian pairwise distance matrix
pdist = dist(as.matrix(df), method = "euclidean")

# Turn pairwise distance matrix into phylo via neighbour joining method
phylo_nj <- nj(pdist)
</code>```

I can plot the tree in Ape:

```<code># Example tree plot using Ape
plot(unroot(phylo_nj),
     type="unrooted",
     cex=1,
     use.edge.length=TRUE,
     show.tip.label = TRUE,
     lab4ut="axial",
     edge.width=1.5)
</code>```

And I can plot the tree in ggtree, adding variables to tip points by colour/ shape:

```<code># Plotting in ggtree
mytree <- ggtree(phylo_nj, layout="equal_angle", size=0.5, linetype=1)
mytree

# Adding metadata variables to tree plot
mytree2 <- mytree %<+% df2 + geom_tippoint(aes(shape = Factor_A,
                                               colour = Factor_B),
                                               size = 9,
                                           alpha=0.7)
mytree2
</code>```

But I can't work out how to make the branches coloured by a variable (rather than tip points), in either Ape or ggtree. I only want terminal branches coloured, not all of the lines of the tree. My aim is to display two (categorical) variables - one by the branch colour and one by the shape (or colour) of the tip. A crude version of what I'm after would look something like the image below (with Factor_A coded by tip shape (neutral colour as shown) and Factor_B coded by the branch colour.

Thanks in advance for the help.

答:
You can use the function ape::edges after you plot the tree using ape::plot.phylo for colouring specific edges by giving the start/end node making the edge to colour.

```<code>## Colouring the first edge with a red dashed line
plot(unroot(phylo_nj), type = "unrooted")
edges(7, 8, col = "red", lty = 2)
</code>```

Or you can provide a vector of colours directly in the ape::plot.phylo function:

```<code>## Making rainbow edges
plot(unroot(phylo_nj), type = "unrooted", edge.color = rainbow(9))
</code>```

You can find out which edges to colour from your data frame by using the edge table in the phylo object (phylo_nj$edge). For example:

```<code>## Which labels have level "a"
labels_a <- df2$Factor_A %in% "a"

## Which edges connect to these labels?
edge_a <- phylo_nj$edge[,2] %in% match(phylo_nj$tip.label, df2$Sample[labels_a])

## Plotting the factors with the labels a coerced as numeric
plot(unroot(phylo_nj), type = "unrooted", edge.color = c("blue", "orange")[edge_a+1])
</code>```

You can of course expand that to multiple levels by following this method to detect which edge leads to a tip with any factor level.

Body:
I would like to generated unrooted neighbour joining trees from input haplotype data, and then colour the branches of the trees based on a variable.
I am using the packages Ape and ggtree.
The haplotypes and co-variables (metadata) are on two separate files with matching sample names.
I have been able to produce trees and colour the tips of the trees by variables, but not the tree branches.

Using mock data -

# Packages
library('ggplot2')
library('ape')
library('phangorn')
library('dplyr')
library('ggtree')
library('phylobase')

# Generate haplotype dataframe
Sample <- c('Sample_A', 'Sample_B', 'Sample_C', 'Sample_D', 'Sample_E', 'Sample_F')
SNP_A <- c(0, 1, 1, 0, 1, 1)
SNP_B <- c(0, 1, 1, 0, 1, 1)
SNP_C <- c(0, 0, 1, 1, 1, 0)
SNP_D <- c(1, 1, 0, 0, 1, 0)
SNP_E <- c(0, 0, 1, 1, 0, 1)
SNP_F <- c(0, 0, 1, 1, 0, 1)
df = data.frame(Sample, SNP_A, SNP_B, SNP_C, SNP_D, SNP_E, SNP_F, row.names=c(1))
df

# Metadata
Factor_A <- c('a', 'a', 'b', 'c', 'a', 'b')
Factor_B <- c('d', 'e', 'd', 'd', 'e', 'd')
df2 = data.frame(Sample, Factor_A, Factor_B)
df2

# Generate Euclidian pairwise distance matrix
pdist = dist(as.matrix(df), method = "euclidean")

# Turn pairwise distance matrix into phylo via neighbour joining method
phylo_nj <- nj(pdist)

I can plot the tree in Ape:

# Example tree plot using Ape
plot(unroot(phylo_nj),
     type="unrooted",
     cex=1,
     use.edge.length=TRUE,
     show.tip.label = TRUE,
     lab4ut="axial",
     edge.width=1.5)

And I can plot the tree in ggtree, adding variables to tip points by colour/ shape:

# Plotting in ggtree
mytree <- ggtree(phylo_nj, layout="equal_angle", size=0.5, linetype=1)
mytree

# Adding metadata variables to tree plot
mytree2 <- mytree %<+% df2 + geom_tippoint(aes(shape = Factor_A,
                                               colour = Factor_B),
                                               size = 9,
                                           alpha=0.7)
mytree2

But I can't work out how to make the branches coloured by a variable (rather than tip points), in either Ape or ggtree. I only want terminal branches coloured, not all of the lines of the tree. My aim is to display two (categorical) variables - one by the branch colour and one by the shape (or colour) of the tip. A crude version of what I'm after would look something like the image below (with Factor_A coded by tip shape (neutral colour as shown) and Factor_B coded by the branch colour.

Thanks in advance for the help.

Body:
You can use the function ape::edges after you plot the tree using ape::plot.phylo for colouring specific edges by giving the start/end node making the edge to colour.

## Colouring the first edge with a red dashed line
plot(unroot(phylo_nj), type = "unrooted")
edges(7, 8, col = "red", lty = 2)

Or you can provide a vector of colours directly in the ape::plot.phylo function:

## Making rainbow edges
plot(unroot(phylo_nj), type = "unrooted", edge.color = rainbow(9))

You can find out which edges to colour from your data frame by using the edge table in the phylo object (phylo_nj$edge). For example:

## Which labels have level "a"
labels_a <- df2$Factor_A %in% "a"

## Which edges connect to these labels?
edge_a <- phylo_nj$edge[,2] %in% match(phylo_nj$tip.label, df2$Sample[labels_a])

## Plotting the factors with the labels a coerced as numeric
plot(unroot(phylo_nj), type = "unrooted", edge.color = c("blue", "orange")[edge_a+1])

You can of course expand that to multiple levels by following this method to detect which edge leads to a tip with any factor level.