问:
Does Tensorflow Lite support the TimeDistributed layer?
I'm currently working with a Keras model with TimeDistributed, Conv2D and Bidirectional(LSTM) layers (code example below) and I'm trying to convert to TF Lite.

```<code>x = TimeDistributed(Conv2D(16, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(input_a)
x = TimeDistributed(Conv2D(32, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(x)
x = TimeDistributed(Conv2D(64, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(x)
x = TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(1,1)))(x)
x = TimeDistributed(Flatten())(x)
x = Model(inputs=input_a, outputs=x)

y = TimeDistributed(Conv2D(16, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(input_b)
y = TimeDistributed(Conv2D(32, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(y)
y = TimeDistributed(Conv2D(64, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(y)
y = TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(1,1)))(y)
y = TimeDistributed(Flatten())(y)
y = Model(inputs=input_b, outputs=y)

combined = concatenate([x.output, y.output])

z = Bidirectional(LSTM(512))(combined)
z = Dense(5, activation='softmax')(z)
</code>```

The conversion is actually successful (code below), but I experience a strong accuracy drop when testing the TF Lite model.

```<code>def representative_data_gen():
  for input_value in tf.data.Dataset.from_tensor_slices(predictors_train).batch(1).take(100):
    input_value_1 = numpy.array(input_value[:,:,:4,:], dtype=numpy.float32)
    input_value_2 = numpy.array(input_value[:,:,4:,:], dtype=numpy.float32)
    yield [input_value_1, input_value_2]

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_data_gen

converter.experimental_new_converter=True
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS, tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter._experimental_lower_tensor_list_ops = False

converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

tflite_model_quant = converter.convert()
</code>```

Since I can't find the TimeDistributed layer on the supported operation list but the conversion is successful anyway, I asked myself if this layer could actually be the problem.

Any hint or insight would be appreciated.

答:
Try first a float version without quantization to see if accuracy is good. If there is a drop  even with float, then file a github issue for TFLite team.

If the drop is in the quantized version, then you can start by inspecting which layer(s) are the culprit by using the QuantizationDebugger.

Body:
I'm currently working with a Keras model with TimeDistributed, Conv2D and Bidirectional(LSTM) layers (code example below) and I'm trying to convert to TF Lite.

x = TimeDistributed(Conv2D(16, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(input_a)
x = TimeDistributed(Conv2D(32, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(x)
x = TimeDistributed(Conv2D(64, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(x)
x = TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(1,1)))(x)
x = TimeDistributed(Flatten())(x)
x = Model(inputs=input_a, outputs=x)

y = TimeDistributed(Conv2D(16, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(input_b)
y = TimeDistributed(Conv2D(32, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(y)
y = TimeDistributed(Conv2D(64, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(y)
y = TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(1,1)))(y)
y = TimeDistributed(Flatten())(y)
y = Model(inputs=input_b, outputs=y)

combined = concatenate([x.output, y.output])

z = Bidirectional(LSTM(512))(combined)
z = Dense(5, activation='softmax')(z)

The conversion is actually successful (code below), but I experience a strong accuracy drop when testing the TF Lite model.

def representative_data_gen():
  for input_value in tf.data.Dataset.from_tensor_slices(predictors_train).batch(1).take(100):
    input_value_1 = numpy.array(input_value[:,:,:4,:], dtype=numpy.float32)
    input_value_2 = numpy.array(input_value[:,:,4:,:], dtype=numpy.float32)
    yield [input_value_1, input_value_2]

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_data_gen

converter.experimental_new_converter=True
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS, tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter._experimental_lower_tensor_list_ops = False

converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

tflite_model_quant = converter.convert()

Since I can't find the TimeDistributed layer on the supported operation list but the conversion is successful anyway, I asked myself if this layer could actually be the problem.

Any hint or insight would be appreciated.


来源: stackexchange

问:
Typescript higher order function preserve overload types
I'm trying to create a higher order function that can attach a primitive watcher to a method. It's working great as long as the input function is not overloaded, but I'm running into issues with overloads. I would like to find a way to pass all overloads through the higher order function so the returned function can behave just like the original. This is what I have so far:

I build a watcher with a function like this, giving me a simple way to track statistics of function use.

function makeWatcher() {
  let _callCount = 0;

  function countCall() {
    _callCount = _callCount + 1;
  }
  function getCallCount() {
    return _callCount;
  }

  return {
    countCall,
    getCallCount,
  };
}
```
<p>I then have a higher order function that takes a function and a watcher as input, and returns a function that interacts with the watcher and then runs the original function.</p>
<pre class="lang-js prettyprint-override"><code>// Generic type assures method signature is inferred.
function watchMethod<T extends (...args: any[]) => any>(
  func: T,
  watcher: Watcher
): (...funcArgs: Parameters<T>) => ReturnType<T> {

  // Return a new function that has same signature as input function,
  // with added watcher interaction when called
  return (...args: Parameters<T>): ReturnType<T> => {

    // Interact with watcher
    watcher.countCall();

    // execute original function and return results
    const results = func(...args);
    return results;
  };
}
</code>```

The last step is to compose these together to give me a method that has properties I can interact with, like so:

function buildWatchedMethod<T extends (...args: any[]) => any>(inputFunction: T) {

  // get a watcher
  const watcher = makeWatcher();

  // set up method watching
  const watchedMethod= watchMethod(inputFunction, watcher);

  // list out properties that should be public
  const externalProperties = {
    getCallCount: watcher.getCallCount
  }

  // assign properties to method
  return Object.assign(watchedMethod, externalProperties);
}
```
<p>I can then add watchers to methods like this:</p>
<pre class="lang-js prettyprint-override"><code>function method(input: string){
  console.log(input);
}

const watchedMethod = buildWatchedMethod(method);

watchedMethod("Hello World"); // logs "Hello World"
watchedMethod.getCallCount(); // returns 1 - method was called once
watchedMethod("Hello again"); // logs "Hello Again"
watchedMethod.getCallCount(); // returns 2
watchedMethod.countCall(); // error - not available from outside function
</code>```

This works beautifully, function signatures are preserved, type safety is preserved - until buildWatchedMethod is called with an overloaded method. It still works, but the overloads of the watched methods aren't preserved through the process, which makes typescript complain.

This appears to be expected behavior as outlined in the accepted answer of this post, but is there any way to carry the overload signatures through the higher order function?

Where the issue comes up most often is when I use libraries where overloads are common. (I'm looking at you, Mongoose!) I'm also trying to avoid mocking libraries like Sinon because a) they can be painful to use with typescript sometimes, and b) my needs for this use case are very minimal, and third party libraries tend to have a lot more involved than what I need.

Any suggestions are appreciated!

答:
I believe there's a way to make this work.

The problem is the watchMethod return type... representing the original function type using Parameters<T> doesn't appear to capture the overloads (since Parameters only returns a single parameter list). However, if we return T directly, the overloads can make it through. The only catch is that Typescript will complain about the return type, so you're going to have to use a type assertion. If you're willing to do that, then the following modification should solve your problem:

function watchMethod<T extends (...args: any[]) => any>(
  func: T,
  watcher: Watcher
): T {

  // Return a new function that has same signature as input function,
  // with added watcher interaction when called
  return ((...args: Parameters<T>): ReturnType<T> => {

    // Interact with watcher
    watcher.countCall();

    // execute original function and return results
    const results = func(...args);
    return results;
  }) as T;
}
```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a higher order function that can attach a primitive watcher to a method. It's working great as long as the input function is not overloaded, but I'm running into issues with overloads. I would like to find a way to pass all overloads through the higher order function so the returned function can behave just like the original. This is what I have so far:

I build a watcher with a function like this, giving me a simple way to track statistics of function use.

function makeWatcher() {
  let _callCount = 0;

  function countCall() {
    _callCount = _callCount + 1;
  }
  function getCallCount() {
    return _callCount;
  }

  return {
    countCall,
    getCallCount,
  };
}

I then have a higher order function that takes a function and a watcher as input, and returns a function that interacts with the watcher and then runs the original function.

// Generic type assures method signature is inferred.
function watchMethod<T extends (...args: any[]) => any>(
  func: T,
  watcher: Watcher
): (...funcArgs: Parameters<T>) => ReturnType<T> {

  // Return a new function that has same signature as input function,
  // with added watcher interaction when called
  return (...args: Parameters<T>): ReturnType<T> => {

    // Interact with watcher
    watcher.countCall();

    // execute original function and return results
    const results = func(...args);
    return results;
  };
}

The last step is to compose these together to give me a method that has properties I can interact with, like so:

function buildWatchedMethod<T extends (...args: any[]) => any>(inputFunction: T) {

  // get a watcher
  const watcher = makeWatcher();

  // set up method watching
  const watchedMethod= watchMethod(inputFunction, watcher);

  // list out properties that should be public
  const externalProperties = {
    getCallCount: watcher.getCallCount
  }

  // assign properties to method
  return Object.assign(watchedMethod, externalProperties);
}

I can then add watchers to methods like this:

function method(input: string){
  console.log(input);
}

const watchedMethod = buildWatchedMethod(method);

watchedMethod("Hello World"); // logs "Hello World"
watchedMethod.getCallCount(); // returns 1 - method was called once
watchedMethod("Hello again"); // logs "Hello Again"
watchedMethod.getCallCount(); // returns 2
watchedMethod.countCall(); // error - not available from outside function

This works beautifully, function signatures are preserved, type safety is preserved - until buildWatchedMethod is called with an overloaded method. It still works, but the overloads of the watched methods aren't preserved through the process, which makes typescript complain.

This appears to be expected behavior as outlined in the accepted answer of this post, but is there any way to carry the overload signatures through the higher order function?

Where the issue comes up most often is when I use libraries where overloads are common. (I'm looking at you, Mongoose!) I'm also trying to avoid mocking libraries like Sinon because a) they can be painful to use with typescript sometimes, and b) my needs for this use case are very minimal, and third party libraries tend to have a lot more involved than what I need.

Any suggestions are appreciated!


问:
All the connections are in use: Execution halted
I'm using getYahooData() function in TTR package quite intensely.

I have this piece of code:

```<code>for(i in 1:nrow(symbol)){
    tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
                                    type="price"),
             warning=function(e) continue <- 0)
    if (continue==0) next
}
</code>```

This loop is long I get this error:

Error in file(file, "rt") : all connections are in use Calls: tryCatch
  ... doTryCatch -> getYahooData -> getYahooData -> read.table -> file
  Execution halted

What can I do?

UPDATE:

If i use closeAllConnections() I get:

```<code> I get: *** caught segfault *** address (nil), cause 'memory not mapped' Traceback: 1: getConnection(set[i]) 2: close(getConnection(set[i])) 3: closeAllConnections() aborting ...
</code>```

答:
First : do not ever in your life use that continue construct again. It's of no use. tryCatch() will continue if you defined a handler for an error or a warning. It will use that one instead of the "default" error=function(e) stop(e). This one will stop your function. If you define a handler (either warning= or error= ), your script will not be stopped, so that continue is not necessary.

This said : The correct use of tryCatch in this case would be :

```<code>for(i in 1:nrow(symbol)){

tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
                                    type="price"), error = function(e){})

}
</code>```

or, if you use it in a script and want to go to the next loop when an error occurs, you can simply use :

```<code>for(i in 1:nrow(symbol)){

    prices <- try(getYahooData(symbol$symbol[i], from, to, freq="daily",
                                    type="price"), silent=TRUE)

    if(inherits(prices,"try-error")) { next } # only true if an error occurs
    ... # rest of calculations
}
</code>```

If you would have used this way of tryCatch or try, you wouldn't have had the problems you report here.

Now I could reproduce your case, if I use nonexistent symbols. Your erroneous use of tryCatch() function is causing you trouble. read.table returns an error (Error in file(file, "rt") : cannot open the connection). This is an error, not a warning. You get an additional warning saying that a 404 File not found was returned.

When a warning is issued together with an error, the handler function for the warning is dealt with first. That's because a warning has to be thrown before the function can be stopped. So it won't handle the error you get, <s>which means that the on.exit(close(file)) in read.table() will not to be called. Hence, the connection is not closed correctly and still considered open, although it can't be found anymore by R (showAllConnections() shows nothing).</s> As the error is not dealt with, something goes wrong in the registration of the connections. As the connection couldn't be opened, the on.exit(close(...)) will have no effect. showConnections() doesn't show the connection, but somehow R still thinks it's there.  Hence, all hell breaks loose and you crash your R.

thanks for the corrections to @Tommy

A simple code example to illustrate this :

```<code>myfun <- function(x){
   if(x>1) warning("aWarning")
   stop("aStop")
   x
}

tryCatch(myfun(0.5),
          warning=function(w)print("warning"),
          error=function(e) print("stop"))
[1] "stop"

tryCatch(myfun(1.5),
          warning=function(w)print("warning"),
          error=function(e) print("stop"))
[1] "warning"
</code>```

In summary :

check the symbols you use. They're probably wrong.

do not ever again use a warning handler if you expect errors.

And as an extra: your loop will only return the result of the last call, as you overwrite prices every time you go through the loop, in case you would have used correct symbols.

Edit : in case you want to continue the action

ContentLicense: CC BY-SA 3.0

Body:
I'm using getYahooData() function in TTR package quite intensely.

I have this piece of code:

for(i in 1:nrow(symbol)){
    tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
                                    type="price"),
             warning=function(e) continue <- 0)
    if (continue==0) next
}

This loop is long I get this error:

Error in file(file, "rt") : all connections are in use Calls: tryCatch
  ... doTryCatch -> getYahooData -> getYahooData -> read.table -> file
  Execution halted

What can I do?

UPDATE:

If i use closeAllConnections() I get:

 I get: *** caught segfault *** address (nil), cause 'memory not mapped' Traceback: 1: getConnection(set[i]) 2: close(getConnection(set[i])) 3: closeAllConnections() aborting ...

Body:
First : do not ever in your life use that continue construct again. It's of no use. tryCatch() will continue if you defined a handler for an error or a warning. It will use that one instead of the "default" error=function(e) stop(e). This one will stop your function. If you define a handler (either warning= or error= ), your script will not be stopped, so that continue is not necessary.

This said : The correct use of tryCatch in this case would be :

for(i in 1:nrow(symbol)){

tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
                                    type="price"), error = function(e){})

}

or, if you use it in a script and want to go to the next loop when an error occurs, you can simply use :

for(i in 1:nrow(symbol)){

    prices <- try(getYahooData(symbol$symbol[i], from, to, freq="daily",
                                    type="price"), silent=TRUE)

    if(inherits(prices,"try-error")) { next } # only true if an error occurs
    ... # rest of calculations
}

If you would have used this way of tryCatch or try, you wouldn't have had the problems you report here.

Now I could reproduce your case, if I use nonexistent symbols. Your erroneous use of tryCatch() function is causing you trouble. read.table returns an error (Error in file(file, "rt") : cannot open the connection). This is an error, not a warning. You get an additional warning saying that a 404 File not found was returned.

When a warning is issued together with an error, the handler function for the warning is dealt with first. That's because a warning has to be thrown before the function can be stopped. So it won't handle the error you get, <s>which means that the on.exit(close(file)) in read.table() will not to be called. Hence, the connection is not closed correctly and still considered open, although it can't be found anymore by R (showAllConnections() shows nothing).</s> As the error is not dealt with, something goes wrong in the registration of the connections. As the connection couldn't be opened, the on.exit(close(...)) will have no effect. showConnections() doesn't show the connection, but somehow R still thinks it's there.  Hence, all hell breaks loose and you crash your R.

thanks for the corrections to @Tommy

A simple code example to illustrate this :

myfun <- function(x){
   if(x>1) warning("aWarning")
   stop("aStop")
   x
}

tryCatch(myfun(0.5),
          warning=function(w)print("warning"),
          error=function(e) print("stop"))
[1] "stop"

tryCatch(myfun(1.5),
          warning=function(w)print("warning"),
          error=function(e) print("stop"))
[1] "warning"

In summary :

check the symbols you use. They're probably wrong.

do not ever again use a warning handler if you expect errors.

And as an extra: your loop will only return the result of the last call, as you overwrite prices every time you go through the loop, in case you would have used correct symbols.

Edit : in case you want to continue the action


问:
Override functions in Solidity
I try to make a smart contract with a child contract and override another function that derived from another interface.

This is an example code:

```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

interface Base1 {
    function h() external public {}
}

interface Base2 {
    function f() external public {}
}

contract Inherited is Base1 {
    function h() external override {}
    function f() external override {}
}
</code>```

And I got this error: "TypeError: Function has override specified but does not override anything." in function f().

I know that could be solved by adding Base2 to the contract (contract Inherited is Base1, Base2) and specifying the interface in each function. But, is there another way to override function f() without adding Base2?

答: That is because you need to add some functionality to the overriding function.</p>

Title: Override functions in Solidity

Body:
I try to make a smart contract with a child contract and override another function that derived from another interface.

This is an example code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

interface Base1 {
    function h() external public {}
}

interface Base2 {
    function f() external public {}
}

contract Inherited is Base1 {
    function h() external override {}
    function f() external override {}
}

And I got this error: "TypeError: Function has override specified but does not override anything." in function f().

I know that could be solved by adding Base2 to the contract (contract Inherited is Base1, Base2) and specifying the interface in each function. But, is there another way to override function f() without adding Base2?


问:
Are there penalties for just using the new keyword instead of creating a class variable before calling the class method?
Example

(1)

```<code>var classVar = new class();

classVar.Method();
</code>```

(2)

```<code>new class().Method();
</code>```

I like the second way, less wordy.

Is there a performance difference?

Is it considered bad coding practice?

答:
in your case Method seems to be static (ie there is no useful data stored inside the instance of 'class' (note I am ignoring all the invalid / not recommended name issues). Assuming this is c# but all languages have the same ideas, you would go

```<code>public class class{ // ugh
   public void static Method(){
       Console.WriteLine("I am Method");
   }
}
</code>```

now you can go

```<code> class.Method();
</code>```

so the code is neatly filed away inside 'class' but you dont have to pay any overhead.

If you really need to instantiate 'class' then presumably you need to do more than just call one method on it. In which case

```<code>new class().Method();
</code>```

makes no sense, since you call create it, call a method and destroy it.

Really a more concrete example is needed

Body:
Example

(1)

var classVar = new class();

classVar.Method();

(2)

new class().Method();

I like the second way, less wordy.

Is there a performance difference?

Is it considered bad coding practice?

Body:
in your case Method seems to be static (ie there is no useful data stored inside the instance of 'class' (note I am ignoring all the invalid / not recommended name issues). Assuming this is c# but all languages have the same ideas, you would go

public class class{ // ugh
   public void static Method(){
       Console.WriteLine("I am Method");
   }
}

now you can go

 class.Method();

so the code is neatly filed away inside 'class' but you dont have to pay any overhead.

If you really need to instantiate 'class' then presumably you need to do more than just call one method on it. In which case

new class().Method();

makes no sense, since you call create it, call a method and destroy it.

Really a more concrete example is needed


问:
SQL Error [1265] [01000]: Data truncated for column 'descval'
I'm getting this error but I do not have a column titled 'descval' so I'm not even sure where to begin looking for problem.  I'm sure this is a data problem but the error log in DBeaver offers very little to go on.

Below is the table that I am inserting the data into as well as the query that I'm using to do the insertion.  As you'll see, there is no descval column and yet that is what the error indicates.

```<code>Table that I'm inserting into:
Call_Date (date)
Call_Time (time)
Call_Type (varchar(20))
ANI (varchar(20))
Acct_Key_Lookup (varchar(50))
Call_Disposition (varchar(100))
Result (varchar(100))
Inbound_Group_Name (varchar(100))
Inbound_Number (varchar(100))
Talk_Time (bigint)
Hold_Time (bigint)
Wrap_Time (bigint)
Client (varchar(20))
Acct_Key_TCN (varchar(100))
Description (varchar(100))
DataSource (varchar(100))
Debtor_Key_Lookup (varchar(50))
agent_hunt_group (varchar(100))
Agent_ID (varchar(50))

Query:
insert into `default`.tcn_meduit_calls (Call_Date, Call_Time,
Call_Type, ANI, Acct_Key_Lookup, Call_Disposition, `Result`,
Inbound_Group_Name,
Inbound_Number, Talk_Time, Hold_Time, Wrap_Time, Client,
Acct_Key_TCN, Description, DataSource, Debtor_Key_Lookup,
agent_hunt_group, Agent_ID)
select
convert(concat(substr(tmcs.`date`,7,2),'-',substr(tmcs.`date`,1,2),'-
',substr(tmcs.`date`,4,2)),date),
convert(concat(
case when right(tmcs.`time`,2) = 'AM' or left(tmcs.`time`,2) = '12'
then
    left(tmcs.`time`,locate(':',tmcs.`time`)-1)
else
    left(tmcs.`time`,length(tmcs.`time`)-
(locate(':',tmcs.`time`)-1))+12 end, ':',
substr(tmcs.`time`,locate(':',tmcs.`time`)+1,2),':','00'),Time),
substr(tmcs.`call type`,1,20),
coalesce(tmcs.`dialed number`,tmcs.`tcn dialed number`,tmcs.`phone
number`),
case when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'inbound' then
(select tppl.Account_Number
from `default`.tcn_pmab_phone_lookup tppl where tmcs.`phone number` =
tppl.Phone_Number order by tppl.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'manual' then
(select tppl2.Account_Number
from `default`.tcn_pmab_phone_lookup tppl2 where tmcs.`tcn dialed
number` = tppl2.Phone_Number order by tppl2.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'outbound' then
(select tppl3.Account_Number
from `default`.tcn_pmab_phone_lookup tppl3 where tmcs.`dialed number`
= tppl3.Phone_Number and tmcs.`debtor number` = tppl3.Debtor_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'inbound' then
(select tppl4.Account_Number
from `default`.tcn_pcb_phone_lookup tppl4 where tmcs.`phone number` =
tppl4.Phone_Number order by tppl4.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'manual' then
(select tppl5.Account_Number
from `default`.tcn_pcb_phone_lookup tppl5 where tmcs.`tcn dialed
number` = tppl5.Phone_Number order by tppl5.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'outbound' then
(select tppl6.Account_Number
from `default`.tcn_pcb_phone_lookup tppl6 where tmcs.`dialed number`
= tppl6.Phone_Number and tmcs.`debtor number` = tppl6.Account_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'inbound' then
(select tapl.EncounterID
from `default`.tcn_ahc_phone_lookup tapl where tapl.PhoneNumber =
tmcs.`phone number` order by tapl.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'manual' then
(select tapl2.EncounterID
from `default`.tcn_ahc_phone_lookup tapl2 where tapl2.PhoneNumber =
tmcs.`tcn dialed number` order by tapl2.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'outbound' then
(select tapl3.EncounterID
from `default`.tcn_ahc_phone_lookup tapl3 where tapl3.PhoneNumber =
tmcs.`dialed number` order by tapl3.EncounterID limit 1)
else 'UNKNOWN' end,
tmcs.`call disposition`, tmcs.`result`, tmcs.`inbound group name`,
trim(leading '+' from tmcs.`inbound number`),
case when tmcs.`agent call talk duration` = '' then cast(0 as
unsigned) else cast(tmcs.`agent call talk duration` as unsigned) end,
case when tmcs.`linkback duration` = '' then cast(0 as unsigned) else
(cast(tmcs.`linkback duration` as unsigned)) -
(case when tmcs.`agent call talk duration` = '' then 0 else
cast(tmcs.`agent call talk duration` as unsigned) end) end,
case when tmcs.`agent call wrap up duration` = '' then cast(0 as
unsigned) else cast(tmcs.`agent call wrap up duration` as unsigned)
end,
case when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'inbound' then
(select tppl.Client_Number
from `default`.tcn_pmab_phone_lookup tppl where tmcs.`phone number` =
tppl.Phone_Number order by tppl.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'manual' then
(select tppl2.Client_Number
from `default`.tcn_pmab_phone_lookup tppl2 where tmcs.`tcn dialed
number` = tppl2.Phone_Number order by tppl2.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'outbound' then
(select tppl3.Client_Number
from `default`.tcn_pmab_phone_lookup tppl3 where tmcs.`dialed number`
= tppl3.Phone_Number and tmcs.`debtor number` = tppl3.Debtor_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'inbound' then
(select tppl4.Client_ID
from `default`.tcn_pcb_phone_lookup tppl4 where tmcs.`phone number` =
tppl4.Phone_Number order by tppl4.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'manual' then
(select tppl5.Client_ID
from `default`.tcn_pcb_phone_lookup tppl5 where tmcs.`tcn dialed
number` = tppl5.Phone_Number order by tppl5.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'outbound' then
(select tppl6.Client_ID
from `default`.tcn_pcb_phone_lookup tppl6 where tmcs.`dialed number`
= tppl6.Phone_Number and tmcs.`debtor number` = tppl6.Account_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'inbound' then
(select tapl.ClientID
from `default`.tcn_ahc_phone_lookup tapl where tapl.PhoneNumber =
tmcs.`phone number` order by tapl.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'manual' then
(select tapl2.ClientID
from `default`.tcn_ahc_phone_lookup tapl2 where tapl2.PhoneNumber =
tmcs.`tcn dialed number` order by tapl2.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'outbound' then
(select tapl3.ClientID
from `default`.tcn_ahc_phone_lookup tapl3 where tapl3.PhoneNumber =
tmcs.`dialed number` order by tapl3.EncounterID limit 1)
else 'UNKNOWN' end,
substr(tmcs.`debtor number`,1,100),
substr(tmcs.description,1,100),
case when `default`.id_datasource(tmcs.description) = 'NA' then
`default`.id_datasource(tmcs.`agent's hunt group`) else
`default`.id_datasource(tmcs.description) end,
case when `default`.id_datasource(tmcs.description) = 'CLT' and
tmcs.`call type` = 'inbound' then
(select tppl.Debtor_Number
from `default`.tcn_pmab_phone_lookup tppl where tmcs.`phone number` =
tppl.Phone_Number order by tppl.Account_Number limit 1)
when `default`.id_datasource(tmcs.description) = 'CLT' and tmcs.`call
type` = 'manual' then
(select tppl2.Debtor_Number
from `default`.tcn_pmab_phone_lookup tppl2 where tmcs.`tcn dialed
number` = tppl2.Phone_Number order by tppl2.Account_Number limit 1)
when `default`.id_datasource(tmcs.description) = 'CLT' and tmcs.`call
type` = 'outbound' then
(select tppl3.Debtor_Number
from `default`.tcn_pmab_phone_lookup tppl3 where tmcs.`dialed number`
= tppl3.Phone_Number and tmcs.`debtor number` = tppl3.Debtor_Number
limit 1)
else '' end,
tmcs.`agent's hunt group`,
substr(tmcs.`partner agent id`,1,50)
from `default`.tcn_meduit_calls_staging tmcs
where tmcs.transform_status is null
</code>```

My query above calls the a function I created and that is where the descval exists.  My function is named id.datasource (code below).  In the source table, the source field is varchar(200) and, initially, I did declare descval as varchar(100) but I've changed it since to varchar(200) and, yet, I still get the error.

```<code>DELIMITER $$

create function `default`.id_datasource (descval varchar(200))
returns varchar(10)
begin
    declare datasource varchar(10) default '';
    SET datasource =
        case
            when descval like '%CLT%' then 'CLT'
            when descval like '%PCB%' then 'PCB'
            when descval like '%SAR%' then 'SAR'
            when descval like '%GAI%' then 'SAR'
            else 'NA'
        end;
    return datasource;
end
$$

DELIMITER ;
</code>```

答: The source field (description) that I was using within the body of my query was defined as varchar(200) but I was calling a function that I created that declares the same variable as varchar(100).  I need to change the function to declare it as varchar(200), drop the function and then re-create it.</p>

Body:
I'm getting this error but I do not have a column titled 'descval' so I'm not even sure where to begin looking for problem.  I'm sure this is a data problem but the error log in DBeaver offers very little to go on.

Below is the table that I am inserting the data into as well as the query that I'm using to do the insertion.  As you'll see, there is no descval column and yet that is what the error indicates.

Table that I'm inserting into:
Call_Date (date)
Call_Time (time)
Call_Type (varchar(20))
ANI (varchar(20))
Acct_Key_Lookup (varchar(50))
Call_Disposition (varchar(100))
Result (varchar(100))
Inbound_Group_Name (varchar(100))
Inbound_Number (varchar(100))
Talk_Time (bigint)
Hold_Time (bigint)
Wrap_Time (bigint)
Client (varchar(20))
Acct_Key_TCN (varchar(100))
Description (varchar(100))
DataSource (varchar(100))
Debtor_Key_Lookup (varchar(50))
agent_hunt_group (varchar(100))
Agent_ID (varchar(50))

Query:
insert into `default`.tcn_meduit_calls (Call_Date, Call_Time,
Call_Type, ANI, Acct_Key_Lookup, Call_Disposition, `Result`,
Inbound_Group_Name,
Inbound_Number, Talk_Time, Hold_Time, Wrap_Time, Client,
Acct_Key_TCN, Description, DataSource, Debtor_Key_Lookup,
agent_hunt_group, Agent_ID)
select
convert(concat(substr(tmcs.`date`,7,2),'-',substr(tmcs.`date`,1,2),'-
',substr(tmcs.`date`,4,2)),date),
convert(concat(
case when right(tmcs.`time`,2) = 'AM' or left(tmcs.`time`,2) = '12'
then
    left(tmcs.`time`,locate(':',tmcs.`time`)-1)
else
    left(tmcs.`time`,length(tmcs.`time`)-
(locate(':',tmcs.`time`)-1))+12 end, ':',
substr(tmcs.`time`,locate(':',tmcs.`time`)+1,2),':','00'),Time),
substr(tmcs.`call type`,1,20),
coalesce(tmcs.`dialed number`,tmcs.`tcn dialed number`,tmcs.`phone
number`),
case when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'inbound' then
(select tppl.Account_Number
from `default`.tcn_pmab_phone_lookup tppl where tmcs.`phone number` =
tppl.Phone_Number order by tppl.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'manual' then
(select tppl2.Account_Number
from `default`.tcn_pmab_phone_lookup tppl2 where tmcs.`tcn dialed
number` = tppl2.Phone_Number order by tppl2.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'outbound' then
(select tppl3.Account_Number
from `default`.tcn_pmab_phone_lookup tppl3 where tmcs.`dialed number`
= tppl3.Phone_Number and tmcs.`debtor number` = tppl3.Debtor_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'inbound' then
(select tppl4.Account_Number
from `default`.tcn_pcb_phone_lookup tppl4 where tmcs.`phone number` =
tppl4.Phone_Number order by tppl4.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'manual' then
(select tppl5.Account_Number
from `default`.tcn_pcb_phone_lookup tppl5 where tmcs.`tcn dialed
number` = tppl5.Phone_Number order by tppl5.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'outbound' then
(select tppl6.Account_Number
from `default`.tcn_pcb_phone_lookup tppl6 where tmcs.`dialed number`
= tppl6.Phone_Number and tmcs.`debtor number` = tppl6.Account_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'inbound' then
(select tapl.EncounterID
from `default`.tcn_ahc_phone_lookup tapl where tapl.PhoneNumber =
tmcs.`phone number` order by tapl.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'manual' then
(select tapl2.EncounterID
from `default`.tcn_ahc_phone_lookup tapl2 where tapl2.PhoneNumber =
tmcs.`tcn dialed number` order by tapl2.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'outbound' then
(select tapl3.EncounterID
from `default`.tcn_ahc_phone_lookup tapl3 where tapl3.PhoneNumber =
tmcs.`dialed number` order by tapl3.EncounterID limit 1)
else 'UNKNOWN' end,
tmcs.`call disposition`, tmcs.`result`, tmcs.`inbound group name`,
trim(leading '+' from tmcs.`inbound number`),
case when tmcs.`agent call talk duration` = '' then cast(0 as
unsigned) else cast(tmcs.`agent call talk duration` as unsigned) end,
case when tmcs.`linkback duration` = '' then cast(0 as unsigned) else
(cast(tmcs.`linkback duration` as unsigned)) -
(case when tmcs.`agent call talk duration` = '' then 0 else
cast(tmcs.`agent call talk duration` as unsigned) end) end,
case when tmcs.`agent call wrap up duration` = '' then cast(0 as
unsigned) else cast(tmcs.`agent call wrap up duration` as unsigned)
end,
case when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'inbound' then
(select tppl.Client_Number
from `default`.tcn_pmab_phone_lookup tppl where tmcs.`phone number` =
tppl.Phone_Number order by tppl.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'manual' then
(select tppl2.Client_Number
from `default`.tcn_pmab_phone_lookup tppl2 where tmcs.`tcn dialed
number` = tppl2.Phone_Number order by tppl2.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'CLT' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'CLT') and
tmcs.`call type` = 'outbound' then
(select tppl3.Client_Number
from `default`.tcn_pmab_phone_lookup tppl3 where tmcs.`dialed number`
= tppl3.Phone_Number and tmcs.`debtor number` = tppl3.Debtor_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'inbound' then
(select tppl4.Client_ID
from `default`.tcn_pcb_phone_lookup tppl4 where tmcs.`phone number` =
tppl4.Phone_Number order by tppl4.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'manual' then
(select tppl5.Client_ID
from `default`.tcn_pcb_phone_lookup tppl5 where tmcs.`tcn dialed
number` = tppl5.Phone_Number order by tppl5.Account_Number limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'PCB') and
tmcs.`call type` = 'outbound' then
(select tppl6.Client_ID
from `default`.tcn_pcb_phone_lookup tppl6 where tmcs.`dialed number`
= tppl6.Phone_Number and tmcs.`debtor number` = tppl6.Account_Number
limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'inbound' then
(select tapl.ClientID
from `default`.tcn_ahc_phone_lookup tapl where tapl.PhoneNumber =
tmcs.`phone number` order by tapl.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'manual' then
(select tapl2.ClientID
from `default`.tcn_ahc_phone_lookup tapl2 where tapl2.PhoneNumber =
tmcs.`tcn dialed number` order by tapl2.EncounterID limit 1)
when (`default`.id_datasource(tmcs.description) = 'PCB' or
`default`.id_datasource(tmcs.`agent's hunt group`) = 'SAR') and
tmcs.`call type` = 'outbound' then
(select tapl3.ClientID
from `default`.tcn_ahc_phone_lookup tapl3 where tapl3.PhoneNumber =
tmcs.`dialed number` order by tapl3.EncounterID limit 1)
else 'UNKNOWN' end,
substr(tmcs.`debtor number`,1,100),
substr(tmcs.description,1,100),
case when `default`.id_datasource(tmcs.description) = 'NA' then
`default`.id_datasource(tmcs.`agent's hunt group`) else
`default`.id_datasource(tmcs.description) end,
case when `default`.id_datasource(tmcs.description) = 'CLT' and
tmcs.`call type` = 'inbound' then
(select tppl.Debtor_Number
from `default`.tcn_pmab_phone_lookup tppl where tmcs.`phone number` =
tppl.Phone_Number order by tppl.Account_Number limit 1)
when `default`.id_datasource(tmcs.description) = 'CLT' and tmcs.`call
type` = 'manual' then
(select tppl2.Debtor_Number
from `default`.tcn_pmab_phone_lookup tppl2 where tmcs.`tcn dialed
number` = tppl2.Phone_Number order by tppl2.Account_Number limit 1)
when `default`.id_datasource(tmcs.description) = 'CLT' and tmcs.`call
type` = 'outbound' then
(select tppl3.Debtor_Number
from `default`.tcn_pmab_phone_lookup tppl3 where tmcs.`dialed number`
= tppl3.Phone_Number and tmcs.`debtor number` = tppl3.Debtor_Number
limit 1)
else '' end,
tmcs.`agent's hunt group`,
substr(tmcs.`partner agent id`,1,50)
from `default`.tcn_meduit_calls_staging tmcs
where tmcs.transform_status is null

My query above calls the a function I created and that is where the descval exists.  My function is named id.datasource (code below).  In the source table, the source field is varchar(200) and, initially, I did declare descval as varchar(100) but I've changed it since to varchar(200) and, yet, I still get the error.

DELIMITER $$

create function `default`.id_datasource (descval varchar(200))
returns varchar(10)
begin
    declare datasource varchar(10) default '';
    SET datasource =
        case
            when descval like '%CLT%' then 'CLT'
            when descval like '%PCB%' then 'PCB'
            when descval like '%SAR%' then 'SAR'
            when descval like '%GAI%' then 'SAR'
            else 'NA'
        end;
    return datasource;
end
$$

DELIMITER ;


问:
No major tick marks showing using seaborn white style and cannot restore
When I generate plots using the seaborn "white" style I see major tick labels but I don't see any major tick marks.

Setting major tick marks to be bigger using...

```<code>%matplotlib inline

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style('white', {'axes.linewidth': 0.5})
plt.rcParams['xtick.major.size'] = 20
plt.rcParams['xtick.major.width'] = 4

fig, ax = plt.subplots()
plt.show()
</code>```

...has no effect.

I can't find any option that would make the tick marks visible/invisible.

Anybody have any clues?

答:
Use the 'ticks' style

This is a built-in style for the exact purpose of having 'white' style with tick marks:

```<code>sns.set_style('ticks')  # white style with tick marks
</code>```

If you really want to use the 'white' style or just want to modify tick params, it's simplest to pass an rc dict:

```<code>sns.set_style('white', rc={
    'xtick.bottom': True,
    'ytick.left': True,
})
</code>```

Body:
When I generate plots using the seaborn "white" style I see major tick labels but I don't see any major tick marks.

Setting major tick marks to be bigger using...

%matplotlib inline

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style('white', {'axes.linewidth': 0.5})
plt.rcParams['xtick.major.size'] = 20
plt.rcParams['xtick.major.width'] = 4

fig, ax = plt.subplots()
plt.show()

...has no effect.

I can't find any option that would make the tick marks visible/invisible.

Anybody have any clues?

Body:
Use the 'ticks' style

This is a built-in style for the exact purpose of having 'white' style with tick marks:

sns.set_style('ticks')  # white style with tick marks

If you really want to use the 'white' style or just want to modify tick params, it's simplest to pass an rc dict:

sns.set_style('white', rc={
    'xtick.bottom': True,
    'ytick.left': True,
})


问:
What is a BLAT file (.blat extension)?
I am building a Blazor WASM application and noticed a file with a ".blat" extension (dotnet.timezones.blat). The file is readable in a text editor and contains coded timezones and geographic information. I can infer the purpose of the file but am wondering what the meaning of BLAT is in this context. I have searched online and have only been able to learn that it is a new extension in .NET 5.0+. Any insights?

(Note: I am assuming it is unrelated to the email console utility.)

答:
From what I can see, blat is a format specifically made for blazor. My guess as to the naming is it stands for BLAzor Time zones. As far as the file format, it contains timezone data read from tz database.
You could think of it like a tar file, a bunch of tz files packaged together for distribution.
Here is an old repository showing the creation of the file. (The file extension changed from dat to blat, so the current format is probably different.)

However, from what I can see, currently the blat file is now loaded into the mono runtime from the blazor side as a resource.

Here is the code on the mono side.

Here is the calling code on the blazor side.

Currently blazor uses ICU under the hood, I heard they are considering other options though to try get the binary size down in the future.

Title: What is a BLAT file (.blat extension)?


问:
Why isn't there a "Gaussian Elimination" function in languages such as Julia or NumPy/Python?
Why isn't there a Gaussian Elimination function in packages such as NumPy or Julia?

I know about LU decomposition

I know about the \ (backslash) operator

I still think it would be nice to perform Gaussian Elimination. For example, the following matrix:

```<code>[
4 -1 1 0
1  1 0 1
]
</code>```

答:
We can solve it with the backslash by:

```<code>[
4 -1
1  1
] \ [
1 0
0 1
]
</code>```

The result will be the right two columns of the RREFed matrix (the left two columns will be the 2x2 identity, but the result of this code won't show the left two columns).

The general rule is for an m x n matrix, put m columns on the left side of the backslash, and the remaining n - m columns on the right. So if we wanted to perform Gaussian Elimination on the following matrix:

```<code>[
1 2 7 0 0 0
2 8 0 1 0 0
2 4 1 0 1 0
2 2 3 0 0 1
]
</code>```

We would do

```<code>A = [
1 2 7 0
2 8 0 1
2 4 1 0
2 2 3 0
]
B = [
0 0
0 0
1 0
0 1
]
x = A \ B
</code>```

And just as before, it will give us the resulting rightmost n - m columns of the RREFed matrix, and you assume the left m (which it does not show) are the m x m identity matrix.

Lastly, if we want to check how good our answer is (i.e. determine if it's exact or least squares), we can now run

```<code>norm(A * x - B)
</code>```

to see how close we are to the 0 matrix.

Body:
Why isn't there a Gaussian Elimination function in packages such as NumPy or Julia?

I know about LU decomposition

I know about the \ (backslash) operator

I still think it would be nice to perform Gaussian Elimination. For example, the following matrix:

[
4 -1 1 0
1  1 0 1
]

Body:
We can solve it with the backslash by:

[
4 -1
1  1
] \ [
1 0
0 1
]

The result will be the right two columns of the RREFed matrix (the left two columns will be the 2x2 identity, but the result of this code won't show the left two columns).

The general rule is for an m x n matrix, put m columns on the left side of the backslash, and the remaining n - m columns on the right. So if we wanted to perform Gaussian Elimination on the following matrix:

[
1 2 7 0 0 0
2 8 0 1 0 0
2 4 1 0 1 0
2 2 3 0 0 1
]

We would do

A = [
1 2 7 0
2 8 0 1
2 4 1 0
2 2 3 0
]
B = [
0 0
0 0
1 0
0 1
]
x = A \ B

And just as before, it will give us the resulting rightmost n - m columns of the RREFed matrix, and you assume the left m (which it does not show) are the m x m identity matrix.

Lastly, if we want to check how good our answer is (i.e. determine if it's exact or least squares), we can now run

norm(A * x - B)

to see how close we are to the 0 matrix.


问:
How to choose 'module' instead of 'main' file in package.json
I have created some npm modules and compile them to:

commonJS (using exports.default =) and

esm (using export default)

I set up my package.json like so:

```<code>main: "index.cjs.js",
module: "index.esm.js"
</code>```

When I npm install the package and I simple import it like:

```<code>import myPackage from 'my-package'
</code>```

It will automatically choose the main file, not the module.

My question:

Is there a way to import the module file instead when doing import myPackage from 'my-package' in a JavaScript file?

Why I choose the commonJS file for "main":

I noticed that using Node, importing an esm file is not possible because of export default, it has to be commonJS. I have some simple helper JS functions like this and this, and I would want them to be usable to the widest audience. That's why I chose cjs for the "main" path in package.json.

Why I define a separate "module" in package.json:

Lots of famous libraries like Vue.js are already doing this. See further information on this Stackoverflow thread:

What is the "module" package.json field for?

Why do I want to be able to import the "module" file instead of the "main" file:

There is currently a bug in Rollup where it will not properly show JSDoc comments when coding after having imported a cjs file, but it does work when importing a es file.

The workaround I want to avoid:

Just set "main" to the esm file in package.json, right? But then all users who are using my packages in Node apps will not be able to use it anymore...

→　I'm really confused about all this as well, but I think I did enough research to make sense of all it. That being said, if anyone knows a better approach or any other advice, please do tell me in the comments down below!!

答:
Nodejs does not support "module" but does support the newer "exports" spec.

https://nodejs.org/api/packages.html#exports

https://github.com/nodejs/node/blob/v16.14.0/lib/internal/modules/esm/resolve.js#L910

```<code>  "exports": {
    "import": "./main-module.js",
    "require": "./main-require.cjs"
  },
</code>```

Body:
I have created some npm modules and compile them to:

commonJS (using exports.default =) and

esm (using export default)

I set up my package.json like so:

main: "index.cjs.js",
module: "index.esm.js"

When I npm install the package and I simple import it like:

import myPackage from 'my-package'

It will automatically choose the main file, not the module.

My question:

Is there a way to import the module file instead when doing import myPackage from 'my-package' in a JavaScript file?

Why I choose the commonJS file for "main":

I noticed that using Node, importing an esm file is not possible because of export default, it has to be commonJS. I have some simple helper JS functions like this and this, and I would want them to be usable to the widest audience. That's why I chose cjs for the "main" path in package.json.

Why I define a separate "module" in package.json:

Lots of famous libraries like Vue.js are already doing this. See further information on this Stackoverflow thread:

What is the "module" package.json field for?

Why do I want to be able to import the "module" file instead of the "main" file:

There is currently a bug in Rollup where it will not properly show JSDoc comments when coding after having imported a cjs file, but it does work when importing a es file.

The workaround I want to avoid:

Just set "main" to the esm file in package.json, right? But then all users who are using my packages in Node apps will not be able to use it anymore...

→　I'm really confused about all this as well, but I think I did enough research to make sense of all it. That being said, if anyone knows a better approach or any other advice, please do tell me in the comments down below!!

Body:
Nodejs does not support "module" but does support the newer "exports" spec.

https://nodejs.org/api/packages.html#exports

https://github.com/nodejs/node/blob/v16.14.0/lib/internal/modules/esm/resolve.js#L910

  "exports": {
    "import": "./main-module.js",
    "require": "./main-require.cjs"
  },


问:
How to use pandas .describe()
I have used pandas in the past but I have recently run into a problem where my code is not displaying the .head() or the .describe() function. I have copied my code below from another website and it is still not displaying. Any help is appreciated.</p>
```<code>import pandas as pd
import tensorflow as tf
from matplotlib import pyplot as plt

pd.options.display.max_rows = 10
pd.options.display.float_format = "{:.1f}".format

training_df = pd.read_csv(filepath_or_buffer="california_housing_train.csv")

training_df["median_house_value"] /= 1000.0

training_df.describe(include = 'all')
</code>```

答: Your answer will work in a notebook or REPL, but doesn't actually print. Make sure to call the print() function to output while running.

Title: How to use pandas .describe()

Body:
I have used pandas in the past but I have recently run into a problem where my code is not displaying the .head() or the .describe() function. I have copied my code below from another website and it is still not displaying. Any help is appreciated.

import pandas as pd
import tensorflow as tf
from matplotlib import pyplot as plt

pd.options.display.max_rows = 10
pd.options.display.float_format = "{:.1f}".format

training_df = pd.read_csv(filepath_or_buffer="california_housing_train.csv")

training_df["median_house_value"] /= 1000.0

training_df.describe(include = 'all')


问:
mypy doesn't complain when class doesn't implement protocol
I have the following code. Class A contains a function f. Class B inherits from A and overrides this function. I also have protocol SupportsG which acts as a structural supertype to all classes implementing a function g. I have class B explicitly inherit this protocol:

```<code>from typing import Protocol

class SupportsG(Protocol):
  def g(self) -> str: ...

class A:
  def f(self) -> str:
    return ""

class B(A, SupportsG):
  def f(self) -> str:
    return "test"

if __name__ == "__main__":
  b = B()
</code>```

My expectation here is that mypy would throw an error, because class B doesn't implement function g. However, if I run mypy --strict I get no errors.

What is the gap in my understanding here?

答:
Protocol is for use in structural typing to define input types, not in inheritance.

You should be using ABC instead of Protocol; it does exactly what you want.

Body:
I have the following code. Class A contains a function f. Class B inherits from A and overrides this function. I also have protocol SupportsG which acts as a structural supertype to all classes implementing a function g. I have class B explicitly inherit this protocol:

from typing import Protocol

class SupportsG(Protocol):
  def g(self) -> str: ...

class A:
  def f(self) -> str:
    return ""

class B(A, SupportsG):
  def f(self) -> str:
    return "test"

if __name__ == "__main__":
  b = B()

My expectation here is that mypy would throw an error, because class B doesn't implement function g. However, if I run mypy --strict I get no errors.

What is the gap in my understanding here?


问:
Next - router.replace: how to give it a redirect instruction
I'm trying to learn Next.js.

I have a login handler with:

```<code>import { LOGIN_TOKEN_KEY,REDIRECT_PATH } from "lib/config"

function Login() {
  const client = useApolloClient()
  const [login, { loading }] = useLoginMutation()
  const router = useRouter()
  const redirect = router.query[REDIRECT_PATH] as string | undefined

const onSubmit = (data: LoginInput) => {
    return form.handler(() => login({ variables: { data } }), {
      onSuccess: async (data) => {
        await fetch("/api/login", {
          method: "post",
          body: JSON.stringify({ [LOGIN_TOKEN_KEY]: data.login.token }),
        })
        client.writeQuery<MeQuery>({ query: MeDocument, data: { me: data.login.user } })
        router.replace(redirect || "/dashboard")
      },
    })
  }
</code>```

Inside lib/config, REDIRECT_PATH is defined as:

```<code>export const REDIRECT_PATH = "redirect"
</code>```

What I am trying to achieve, is that on login, the redirect points to a dashboard. Currently, I have a file called pages/dashboard/index.tsx.

In that page, I have:

```<code>import * as React from "react"
import { Text } from "@chakra-ui/react"

import { UserDashboardLayout } from "components/UserDashboardLayout"

export default function DashboardHome() {
  return (
    <Text>test route redirect</Text>
  )
}

DashboardHome.getLayout = (page: React.ReactNode) => <UserDashboardLayout>{page}</UserDashboardLayout>
</code>```

I have a layout that I'm trying to use as follows:

```<code>import * as React from "react"
import {
  Box,
  Flex,
  Link,
  LinkProps,
  Spinner,
  Stack,
  Text,} from "@chakra-ui/react"
import NextLink from "next/link"
import { useRouter } from "next/router"

// import { Role } from "lib/graphql"
import { useLogout } from "lib/hooks/useLogout"
import { useMe } from "lib/hooks/useMe"
import { Nav } from 'components/Nav'

interface Props {
  children: React.ReactNode
}
export function UserDashboardLayout(props: Props) {
  const { colorMode, toggleColorMode } = useColorMode()
  const isDark = colorMode === "dark"

  const logout = useLogout()
  const { me, loading } = useMe()
  const router = useRouter()

  React.useEffect(() => {
    if (loading) return
    if (!me ) {
      router.replace(`/`)
    }
  }, [loading, me, router])

  const homeLinkColor = useColorModeValue("black", "white")
  const bg = useColorModeValue("white", "gray.900")
  const borderColor = useColorModeValue("gray.100", "gray.900")
  if (loading || !me ) {

    return (
      <Center minH="100vh">
        <Spinner />
      </Center>
    )
  }
  return (

    <>
    <Nav  />
    <Flex w="100vw" h="100vh" overflow="hidden">
      <Flex
        flexDir="column"
        justify="space-between"
        w={{ base: "70px", md: "200px" }}
        p={{ base: 4, md: 8 }}
        py={8}
        h="100vh"
        bg={bg}
        borderRight="1px solid"
        borderColor={borderColor}
      >

        <Stack spacing={4}>

          <SidebarLink href="/dashboard" icon={<Box boxSize="18px" as={CgHome} />} color={homeLinkColor}>
            Home
          </SidebarLink>
          <SidebarLink href="/u/testcontentloads" >
            test layout loads
          </SidebarLink>

        </Stack>
        <Stack>

          <Button variant="outline" onClick={() => logout()} size="sm">
            <Icon boxSize="20px" as={CgExternal} mr={{ base: 0, md: 2 }} />
            <Text d={{ base: "none", md: "block" }}>Logout</Text>
          </Button>
        </Stack>
      </Flex>
      <Box
        w={{ base: "calc(100vw - 70px)", md: "calc(100vw - 200px)" }}
        px={{ base: 4, md: 10 }}
        py={8}
        overflow="scroll"
      >
        {props.children}
      </Box>
    </Flex>
    </>
  )
}

interface SidebarLinkProps extends LinkProps {
  href: string
  icon: React.ReactNode
  children: string
}

function SidebarLink({ href, icon, ...props }: SidebarLinkProps) {
  const router = useRouter()
  const isActive = router.asPath.includes(href)
  return (
    <NextLink passHref href={href}>
      <Link
        display="flex"
        alignItems="center"
        justifyContent={{ base: "center", md: "flex-start" }}
        fontWeight="300"
        color={isActive ? "teal" : undefined}
        {...props}
      >
        <Center w="26px">{icon}</Center>
        <Text ml={2} d={{ base: "none", md: "block" }}>
          {props.children}
        </Text>
      </Link>
    </NextLink>
  )
}
</code>```

I have 2 pages in my test. The first is saved in a file at pages/admin/users/index.tsx. It says "home page at basic localhost3000 url". The second is saved at pages/dashboard/index.tsx. It says "test route redirect for dashboard url extension".

I expect, the on success handler of the login page to send me to the the dashboard page. it doesn't. It sends me to the first page. I know the route to the dashboard page works, because I can add a link to it from the nav bar when the page has loaded. i just can't figure out how to get the login handler to redirect to it on success.

I can't find what I need to do to get the login redirect to accept the page, wrapped inside the UserDashboardLayout. It is loading a page, and it does use the same text, but it does not load the layout until I give the browser the url extension.

I can't see what I've done wrong with this redirect request in the login success handler - I've made the best sense of [this documentation][1] as I can manage, but I'm lost for what to try next.

When I try to console log the redirect inside the login success handler, I get undefined back.

when I remove the redirect portion of that line, so that the redirect just says:

```<code> router.replace("/dashboard")
        // router.replace('/dashboard')
        console.log(redirect, REDIRECT_PATH)
</code>```

the page at localhost3000 loads without the /dashboard extension.

When i console log REDIRECT_PATH, it returns redirect.

When I console log redirect, it returns undefined.

I don't understand how to give next an instruction for how to redirect on successful login and am stuck for ideas to research what's going wrong.
[1]: https://nextjs.org/docs/api-reference/next/router#routerreplace

答:
 Redirect query parameter

Let's assume that a user from page /posts/12 wants to write some comments and he/she goes throw the login form but after authorization, he/she gets to the dashboard page. Now the user needs to browse again that post page to write the comment. But what if we redirect the user back to the page where he/she was before the authorization.

For that, we should add redirect params to URL: /login?redirect=post%2F123.

If we do not assign the redirect query parameter in the URL we get an undefined value:

const redirect = router.query[REDIRECT_PATH] as string | undefined
```
<p>Since the redirect is undefined the redirection will be to the home page <code>/</code>:</p>
<pre class="lang-js prettyprint-override"><code>router.replace(redirect || "/")
</code>```

Try to do something like this in order to get the dashboard:

router.replace(redirect || "/dashboard")
```

Body:
I'm trying to learn Next.js.

I have a login handler with:

import { LOGIN_TOKEN_KEY,REDIRECT_PATH } from "lib/config"

function Login() {
  const client = useApolloClient()
  const [login, { loading }] = useLoginMutation()
  const router = useRouter()
  const redirect = router.query[REDIRECT_PATH] as string | undefined

const onSubmit = (data: LoginInput) => {
    return form.handler(() => login({ variables: { data } }), {
      onSuccess: async (data) => {
        await fetch("/api/login", {
          method: "post",
          body: JSON.stringify({ [LOGIN_TOKEN_KEY]: data.login.token }),
        })
        client.writeQuery<MeQuery>({ query: MeDocument, data: { me: data.login.user } })
        router.replace(redirect || "/dashboard")
      },
    })
  }

Inside lib/config, REDIRECT_PATH is defined as:

export const REDIRECT_PATH = "redirect"

What I am trying to achieve, is that on login, the redirect points to a dashboard. Currently, I have a file called pages/dashboard/index.tsx.

In that page, I have:

import * as React from "react"
import { Text } from "@chakra-ui/react"

import { UserDashboardLayout } from "components/UserDashboardLayout"

export default function DashboardHome() {
  return (
    <Text>test route redirect</Text>
  )
}

DashboardHome.getLayout = (page: React.ReactNode) => <UserDashboardLayout>{page}</UserDashboardLayout>

I have a layout that I'm trying to use as follows:

import * as React from "react"
import {
  Box,
  Flex,
  Link,
  LinkProps,
  Spinner,
  Stack,
  Text,} from "@chakra-ui/react"
import NextLink from "next/link"
import { useRouter } from "next/router"

// import { Role } from "lib/graphql"
import { useLogout } from "lib/hooks/useLogout"
import { useMe } from "lib/hooks/useMe"
import { Nav } from 'components/Nav'

interface Props {
  children: React.ReactNode
}
export function UserDashboardLayout(props: Props) {
  const { colorMode, toggleColorMode } = useColorMode()
  const isDark = colorMode === "dark"

  const logout = useLogout()
  const { me, loading } = useMe()
  const router = useRouter()

  React.useEffect(() => {
    if (loading) return
    if (!me ) {
      router.replace(`/`)
    }
  }, [loading, me, router])

  const homeLinkColor = useColorModeValue("black", "white")
  const bg = useColorModeValue("white", "gray.900")
  const borderColor = useColorModeValue("gray.100", "gray.900")
  if (loading || !me ) {

    return (

        <Spinner />

    )
  }
  return (

    <>

    <Flex w="100vw" h="100vh" overflow="hidden">
      <Flex
        flexDir="column"
        justify="space-between"
        w={{ base: "70px", md: "200px" }}
        p={{ base: 4, md: 8 }}
        py={8}
        h="100vh"
        bg={bg}
        borderRight="1px solid"
        borderColor={borderColor}
      >

        <Stack spacing={4}>

          <SidebarLink href="/dashboard" icon={<Box boxSize="18px" as={CgHome} />} color={homeLinkColor}>
            Home
          </SidebarLink>
          <SidebarLink href="/u/testcontentloads" >
            test layout loads
          </SidebarLink>

        </Stack>
        <Stack>

          <Button variant="outline" onClick={() => logout()} size="sm">
            <Icon boxSize="20px" as={CgExternal} mr={{ base: 0, md: 2 }} />
            <Text d={{ base: "none", md: "block" }}>Logout</Text>
          </Button>
        </Stack>
      </Flex>
      <Box
        w={{ base: "calc(100vw - 70px)", md: "calc(100vw - 200px)" }}
        px={{ base: 4, md: 10 }}
        py={8}
        overflow="scroll"
      >
        {props.children}
      </Box>
    </Flex>
    </>
  )
}

interface SidebarLinkProps extends LinkProps {
  href: string
  icon: React.ReactNode
  children: string
}

function SidebarLink({ href, icon, ...props }: SidebarLinkProps) {
  const router = useRouter()
  const isActive = router.asPath.includes(href)
  return (
    <NextLink passHref href={href}>
      <Link
        display="flex"
        alignItems="center"
        justifyContent={{ base: "center", md: "flex-start" }}
        fontWeight="300"
        color={isActive ? "teal" : undefined}
        {...props}
      >
        {icon}
        <Text ml={2} d={{ base: "none", md: "block" }}>
          {props.children}
        </Text>
      </Link>
    </NextLink>
  )
}

I have 2 pages in my test. The first is saved in a file at pages/admin/users/index.tsx. It says "home page at basic localhost3000 url". The second is saved at pages/dashboard/index.tsx. It says "test route redirect for dashboard url extension".

I expect, the on success handler of the login page to send me to the the dashboard page. it doesn't. It sends me to the first page. I know the route to the dashboard page works, because I can add a link to it from the nav bar when the page has loaded. i just can't figure out how to get the login handler to redirect to it on success.

I can't find what I need to do to get the login redirect to accept the page, wrapped inside the UserDashboardLayout. It is loading a page, and it does use the same text, but it does not load the layout until I give the browser the url extension.

I can't see what I've done wrong with this redirect request in the login success handler - I've made the best sense of [this documentation][1] as I can manage, but I'm lost for what to try next.

When I try to console log the redirect inside the login success handler, I get undefined back.

when I remove the redirect portion of that line, so that the redirect just says:

 router.replace("/dashboard")
        // router.replace('/dashboard')
        console.log(redirect, REDIRECT_PATH)

the page at localhost3000 loads without the /dashboard extension.

When i console log REDIRECT_PATH, it returns redirect.

When I console log redirect, it returns undefined.

I don't understand how to give next an instruction for how to redirect on successful login and am stuck for ideas to research what's going wrong.
[1]: https://nextjs.org/docs/api-reference/next/router#routerreplace

Body:
 Redirect query parameter

Let's assume that a user from page /posts/12 wants to write some comments and he/she goes throw the login form but after authorization, he/she gets to the dashboard page. Now the user needs to browse again that post page to write the comment. But what if we redirect the user back to the page where he/she was before the authorization.

For that, we should add redirect params to URL: /login?redirect=post%2F123.

If we do not assign the redirect query parameter in the URL we get an undefined value:

const redirect = router.query[REDIRECT_PATH] as string | undefined

Since the redirect is undefined the redirection will be to the home page /:

router.replace(redirect || "/")

Try to do something like this in order to get the dashboard:

router.replace(redirect || "/dashboard")


问:
Get value from html input in antd form
I want to get value from custom HTML input in AntDesign, onFinish function of the form not getting the description value, I have attached the sample below.

```<code><Form.Item
    label="description"
    name="description"
    rules={[
        {
            required: true,
            message: 'description is required',
        },
    ]}
>
    <CustomInput type="text" />
</Form.Item>
</code>```
```<code>const CustomInput = () => {
   return <input type="text" />;
}

export default CustomInput;
</code>```

答:
In my case, I just need to pass custom component all props, because Form.Item pass to their onChange and value props

```<code>const CustomInput = ({ ...restProps }) => {
   return <input type="text" {...restProps} />;
}

export default CustomInput;
</code>```

Title: Get value from html input in antd form

Body:
I want to get value from custom HTML input in AntDesign, onFinish function of the form not getting the description value, I have attached the sample below.

<Form.Item
    label="description"
    name="description"
    rules={[
        {
            required: true,
            message: 'description is required',
        },
    ]}
>
    <CustomInput type="text" />
</Form.Item>

const CustomInput = () => {
   return <input type="text" />;
}

export default CustomInput;

Body:
In my case, I just need to pass custom component all props, because Form.Item pass to their onChange and value props

const CustomInput = ({ ...restProps }) => {
   return <input type="text" {...restProps} />;
}

export default CustomInput;


问:
calculating counts and percentages of a variable
I am trying to create a count of the number of observations and extract percentages from those counts.

I have data that looks like this:

```<code>UserID              substance_use
43124                       0
43124                       1
43124                       0
43124                       0
43124                       1
215                         1
215                         1

</code>```

I want a count of the total observations of substance use like this:

```<code>UserID             substance_use                                 count
43124                       0                                        5
43124                       1                                        5
43124                       0                                        5
43124                       0                                        5
43124                       1                                        5
215                         1                                        2
215                         1                                        2

</code>```

And then, I want the % of visits that participants said yes and no, like this:

```<code>UserID      substance_use      count      percent_yes       percent_no
43124        0                  5            40%               60%
43124        1                  5            40%               60%
43124        0                  5            40%               60%
43124        0                  5            40%               60%
43124        1                  5            40%              0%
215          1                  2            100%              0
215          1                  2            100%              0%
</code>```

I tried using the count function for the first part, but it's not taking into account the 0's. Any help would be greatly appreciated.

答:
Another possible solution:

library(tidyverse)

df <- structure(list(UserID = c(43124, 43124, 43124, 43124, 43124,
215, 215), substance_use = c(0, 1, 0, 0, 1, 1, 1)), row.names = c(NA,
-7L), class = "data.frame")

df %>%
  mutate(count = ave(UserID, UserID, FUN = length),
    percent_yes = ave(substance_use, UserID, FUN = \(x) 100*sum(x)/length(x)),
    percent_no = 100 - percent_yes)

#>   UserID substance_use count percent_yes percent_no
#> 1  43124             0     5          40         60
#> 2  43124             1     5          40         60
#> 3  43124             0     5          40         60
#> 4  43124             0     5          40         60
#> 5  43124             1     5          40         60
#> 6    215             1     2         100          0
#> 7    215             1     2         100          0
```

Body:
I am trying to create a count of the number of observations and extract percentages from those counts.

I have data that looks like this:

UserID              substance_use
43124                       0
43124                       1
43124                       0
43124                       0
43124                       1
215                         1
215                         1

I want a count of the total observations of substance use like this:

UserID             substance_use                                 count
43124                       0                                        5
43124                       1                                        5
43124                       0                                        5
43124                       0                                        5
43124                       1                                        5
215                         1                                        2
215                         1                                        2

And then, I want the % of visits that participants said yes and no, like this:

UserID      substance_use      count      percent_yes       percent_no
43124        0                  5            40%               60%
43124        1                  5            40%               60%
43124        0                  5            40%               60%
43124        0                  5            40%               60%
43124        1                  5            40%              0%
215          1                  2            100%              0
215          1                  2            100%              0%

I tried using the count function for the first part, but it's not taking into account the 0's. Any help would be greatly appreciated.


问:
What does this declaration in C# .net mean?
I have the following declaration in .NET. I want to know what exactly this declaration mean (the second line), especially the DoConsoleCancelEvent

```<code>delegate void InternalCancelHandler;

static readonly InternalCancelHandler cancel_handler =
    new InternalCancelHandler (DoConsoleCancelEvent);
</code>```

The DoConsoleCancelEvent is declared as:

```<code>internal static void DoConsoleCancelEvent{...}
</code>```

What is the term used in .NET? Is it .NET reflection?

答:
InternalCancelHandler is a delegate.

According to a Mono commit, this is what it says about DoConsoleCancelEvent:

Adds a call to the Win32 function SetConsoleCtrlHandler for Windows,
  which adds the DoWindowsConsoleCancelEvent wrapper for
  DoConsoleCancelEvent to the Ctrl-C handler when an event handler is
  added, and removes the handler once all event handlers are removed.

Body:
I have the following declaration in .NET. I want to know what exactly this declaration mean (the second line), especially the DoConsoleCancelEvent

delegate void InternalCancelHandler;

static readonly InternalCancelHandler cancel_handler =
    new InternalCancelHandler (DoConsoleCancelEvent);

The DoConsoleCancelEvent is declared as:

internal static void DoConsoleCancelEvent{...}

What is the term used in .NET? Is it .NET reflection?


问:
rJava installation ld:library not found for -lpcre2-8
Trying to use rJava and have it use java version 11.

Currently it uses a previous installation I had of version 17.

When I run R CMD javareconf most of the settings look right.

```<code>Java interpreter : /Users/adam/.jenv/shims/java
Java version     : 11.0.13
Java home path   : /Library/Java/JavaVirtualMachines/zulu11.52.13-ca-jdk11.0.13-macosx_aarch64/zulu-11.jdk/Contents/Home
Java compiler    : /Users/adam/.jenv/shims/javac
Java headers gen.: /Users/adam/.jenv/shims/javah
Java archive tool: /Users/adam/.jenv/shims/jar
...
</code>```

and yet when I call rJava::.jcall("java.lang.System","S","getProperty","java.version") I still get version 17.

Consequently I've tried re-installing rJava from source. When I do this the installation recognizes Java 11 as the "default" java installation to use, but I run into a problem with my cpp compiler, as I see the error

```<code>ld: library not found for -lpcre2-8
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [libjri.jnilib] Error 1
make[1]: *** [src/JRI.jar] Error 2
make: *** [jri] Error 2
ERROR: compilation failed for package ‘rJava’
</code>```

when I run install.packages("rJava",type="source").

Other questions(1,2,3) have similar issues but my attempts to replicate the installation of the linker libraries, libpcre2-dev libbz2-dev zlib1g-dev as recommended to an ubuntu user did not work for me – I have not been able to find out how I might install the library as a Mac user . Furthermore, I'm not exactly sure if the "linkages" are setup appropriately in such cases.

Question
How/Where can I find and install the -lpcre2-8 package for the mac version specified below and ensure that the appropriate linkages are in place for the rJava compilation?

Details
I'm working on a Mac OS v12.0.1 (M1 chip), R v.4.1.2 using Rstudio v1.4.1717 to run R.

答:
First, re-compiling won't have any effect. The Java version used on macOS is governed by:

the JAVA_HOME environment variable

system Java selection (see /usr/libexec/java_home)

Normally, JAVA_HOME is not set, so your macOS system setting is used. You can see your installed Java versions with /usr/libexec/java_home -V including which is selected:

```<code>$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    17, x86_64: "Java SE 17"    /Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home
    1.8.0_252, x86_64:  "AdoptOpenJDK 8"    /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home
</code>```

If you want to change the default, you can set JAVA_HOME to the preferred value. For example:

```<code>## use Java 1.8
$ JAVA_HOME=`/usr/libexec/java_home -v 1.8` Rscript -e \
  'print(rJava::J("java.lang.System")$getProperty("java.version"))'
[1] "1.8.0_252"

## use Java 17
$ JAVA_HOME=`/usr/libexec/java_home -v 17` Rscript -e \
  'print(rJava::J("java.lang.System")$getProperty("java.version"))'
[1] "17"

</code>```

Second, if you want to re-compile rJava, you will need all libraries used to build R. For CRAN R build those are provided in https://mac.r-project.org/bin/, but I would not recommend going there unless you want to modify rJava. You can make your life easier by not compiling JRI (embedding R in Java) support, i.e. adding --disable-jri since it's that part which requires the libraries used by R. Just the rJava package itself doesn't need it.

Finally, it's usually a lot faster to ask on the support page rJava Discussion.

Body:
Trying to use rJava and have it use java version 11.

Currently it uses a previous installation I had of version 17.

When I run R CMD javareconf most of the settings look right.

Java interpreter : /Users/adam/.jenv/shims/java
Java version     : 11.0.13
Java home path   : /Library/Java/JavaVirtualMachines/zulu11.52.13-ca-jdk11.0.13-macosx_aarch64/zulu-11.jdk/Contents/Home
Java compiler    : /Users/adam/.jenv/shims/javac
Java headers gen.: /Users/adam/.jenv/shims/javah
Java archive tool: /Users/adam/.jenv/shims/jar
...

and yet when I call rJava::.jcall("java.lang.System","S","getProperty","java.version") I still get version 17.

Consequently I've tried re-installing rJava from source. When I do this the installation recognizes Java 11 as the "default" java installation to use, but I run into a problem with my cpp compiler, as I see the error

ld: library not found for -lpcre2-8
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [libjri.jnilib] Error 1
make[1]: *** [src/JRI.jar] Error 2
make: *** [jri] Error 2
ERROR: compilation failed for package ‘rJava’

when I run install.packages("rJava",type="source").

Other questions(1,2,3) have similar issues but my attempts to replicate the installation of the linker libraries, libpcre2-dev libbz2-dev zlib1g-dev as recommended to an ubuntu user did not work for me – I have not been able to find out how I might install the library as a Mac user . Furthermore, I'm not exactly sure if the "linkages" are setup appropriately in such cases.

Question
How/Where can I find and install the -lpcre2-8 package for the mac version specified below and ensure that the appropriate linkages are in place for the rJava compilation?

Details
I'm working on a Mac OS v12.0.1 (M1 chip), R v.4.1.2 using Rstudio v1.4.1717 to run R.

Body:
First, re-compiling won't have any effect. The Java version used on macOS is governed by:

the JAVA_HOME environment variable

system Java selection (see /usr/libexec/java_home)

Normally, JAVA_HOME is not set, so your macOS system setting is used. You can see your installed Java versions with /usr/libexec/java_home -V including which is selected:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    17, x86_64: "Java SE 17"    /Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home
    1.8.0_252, x86_64:  "AdoptOpenJDK 8"    /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home

If you want to change the default, you can set JAVA_HOME to the preferred value. For example:

## use Java 1.8
$ JAVA_HOME=`/usr/libexec/java_home -v 1.8` Rscript -e \
  'print(rJava::J("java.lang.System")$getProperty("java.version"))'
[1] "1.8.0_252"

## use Java 17
$ JAVA_HOME=`/usr/libexec/java_home -v 17` Rscript -e \
  'print(rJava::J("java.lang.System")$getProperty("java.version"))'
[1] "17"

Second, if you want to re-compile rJava, you will need all libraries used to build R. For CRAN R build those are provided in https://mac.r-project.org/bin/, but I would not recommend going there unless you want to modify rJava. You can make your life easier by not compiling JRI (embedding R in Java) support, i.e. adding --disable-jri since it's that part which requires the libraries used by R. Just the rJava package itself doesn't need it.

Finally, it's usually a lot faster to ask on the support page rJava Discussion.


问:
Calculating the amount of energy used for a charging session
I'm feeding the current (I in Ampere) and voltage (U in Volt) of a wallbox every 10 seconds into a prometheus instance. The wallbox naturally reports higher current when it is plugged into an electric vehicle and a lower current when its not (some baseline current still persists of course for the wallbox' connectivity functionality).

Now I'm quite new to Prometheus and PromQL and was wondering how I'd go on and actually get aggregated data out from these single points in time, namely I want to get Watt Hours and aggregate further on those.

IIRC electrical work is calculated by W = U x I x t, so my idea was to somehow sum up the individual values up until a total value for an hour, like so:

```<code>// somehow get t(0), the first timestamp where values have been reported
// now for each data point we expect that U and I have been constant up until
// this point for simplicity
W(1) = U(1) x I(1) x (t(1) - t(0))
W(2) = U(2) x I(2) x (t(2) - t(1))
W(3) = U(3) x I(3) x (t(3) - t(2))
...
// one hour is comprised of 360 individual values (6 values per minute, 60 minutes per hour)
W(1..360) = W(1) + W(2) + ... W(360)
</code>```

I guess I need some integral function for that, but I'm unsure if I'm doing the right thing:

```<code>sum_over_time(current[10s]) * sum_over_time(voltage[10s])
</code>```

This gives me basically the same value like current * voltage, so a single electrical work value, but I have no idea how I'd aggregate this further properly.

Any ideas?

答:
The following query should return energy consumption during last hour if current and voltage metrics are collected every 10 seconds:

```<code>sum_over_time(
  (last_over_time(current[20s]) * last_over_time(voltage[20s]))[1h:10s]
) * 10
</code>```

The 10 multiplier is needed in order to calculate the consumed energy per each 10 second interval.

This promql query uses subquery feature.

Update:
The query returns the energy in Joules, not kWh. The resulting value must be divided by (3600*1000) in order to convert the consumed energy to kWh:

```<code>sum_over_time(
  (last_over_time(current[20s]) * last_over_time(voltage[20s]))[1h:10s]
) * 10 / (3600*1000)
</code>```

Body:
I'm feeding the current (I in Ampere) and voltage (U in Volt) of a wallbox every 10 seconds into a prometheus instance. The wallbox naturally reports higher current when it is plugged into an electric vehicle and a lower current when its not (some baseline current still persists of course for the wallbox' connectivity functionality).

Now I'm quite new to Prometheus and PromQL and was wondering how I'd go on and actually get aggregated data out from these single points in time, namely I want to get Watt Hours and aggregate further on those.

IIRC electrical work is calculated by W = U x I x t, so my idea was to somehow sum up the individual values up until a total value for an hour, like so:

// somehow get t(0), the first timestamp where values have been reported
// now for each data point we expect that U and I have been constant up until
// this point for simplicity
W(1) = U(1) x I(1) x (t(1) - t(0))
W(2) = U(2) x I(2) x (t(2) - t(1))
W(3) = U(3) x I(3) x (t(3) - t(2))
...
// one hour is comprised of 360 individual values (6 values per minute, 60 minutes per hour)
W(1..360) = W(1) + W(2) + ... W(360)

I guess I need some integral function for that, but I'm unsure if I'm doing the right thing:

sum_over_time(current[10s]) * sum_over_time(voltage[10s])

This gives me basically the same value like current * voltage, so a single electrical work value, but I have no idea how I'd aggregate this further properly.

Any ideas?

Body:
The following query should return energy consumption during last hour if current and voltage metrics are collected every 10 seconds:

sum_over_time(
  (last_over_time(current[20s]) * last_over_time(voltage[20s]))[1h:10s]
) * 10

The 10 multiplier is needed in order to calculate the consumed energy per each 10 second interval.

This promql query uses subquery feature.

Update:
The query returns the energy in Joules, not kWh. The resulting value must be divided by (3600*1000) in order to convert the consumed energy to kWh:

sum_over_time(
  (last_over_time(current[20s]) * last_over_time(voltage[20s]))[1h:10s]
) * 10 / (3600*1000)