问:
How to get opposite of a regex to find all content outside of any kind of matching quotes (ignoring escaped quotes and the 1st arg of ".replace()"
I have a regex that works, as seen in https://stackoverflow.com/a/74576808/1432181.

```<code>\(\s*/.*?/\w*\h*,(*SKIP)(*F)|(?|(")[^"\\]*(?:\\.[^"\\]*)*"|(')[^'\\]*(?:\\.[^'\\]*)*')
</code>```

This selects any kinds of content inside matching quotes, ignoring escaped quotes, ignoring when in the first argument of a .replace() [which may be things like .replace(/'/g, ...)

(See https://regex101.com/r/42rHQx/1)

But how can I get the opposite of this (i.e. where it's blue in the regex101, I want it not selected - and where it was previously not selected I want it blue)?

(I need to use this in a preg_replace so that I can only replace things outside of the shown selected [quoted] content)

Body:
I have a regex that works, as seen in https://stackoverflow.com/a/74576808/1432181.

\(\s*/.*?/\w*\h*,(*SKIP)(*F)|(?|(")[^"\\]*(?:\\.[^"\\]*)*"|(')[^'\\]*(?:\\.[^'\\]*)*')

This selects any kinds of content inside matching quotes, ignoring escaped quotes, ignoring when in the first argument of a .replace() [which may be things like .replace(/'/g, ...)

(See https://regex101.com/r/42rHQx/1)

But how can I get the opposite of this (i.e. where it's blue in the regex101, I want it not selected - and where it was previously not selected I want it blue)?

(I need to use this in a preg_replace so that I can only replace things outside of the shown selected [quoted] content)


来源: stackexchange

问:
How to create a keras layer with a custom gradient *and learnable parameters* in TF2.0?
this is a similar question to: How to create a keras layer with a custom gradient in TF2.0?

Only, I would like to introduce a learnable parameter into the custom layer that I am training.

Here's a toy example of my current approach here:

# Method for calculation custom gradient
@tf.custom_gradient
def scaler(x, s):
  def grad(upstream):
    dy_dx = s
    dy_ds = x
    return dy_dx, dy_ds
  return x * s, grad

# Keras Layer with trainable parameter
class TestLayer(tf.keras.layers.Layer):
  def build(self, input_shape):
    self.scale = self.add_weight("scale",
                                 shape=[1,],
                                 initializer=tf.keras.initializers.Constant(value=2.0),
                                 trainable=True)
  def call(self, inputs):
    return scaler(inputs, self.scale)

# Creates Keras Model that uses the layer
def Model():
  x_in = tf.keras.layers.Input(shape=(1,))
  x_out = TestLayer()(x_in)
  return tf.keras.Model(inputs=x_in, outputs=x_out, name="fp8_test")

# Create toy dataset, want to learn `scale` such to satisfy 5 = 2 * scale (i.e, `scale` should learn ~2.5)
def Dataset():
  inps = tf.ones(shape=(10**5,)) * 2 # inputs
  expected = tf.ones(shape=(10**5,)) * 5 # targets
  data_in = tf.data.Dataset.from_tensors(inps)
  data_exp = tf.data.Dataset.from_tensors(expected)
  dataset = tf.data.Dataset.zip((data_in, data_exp))
  return dataset

model = Model()
model.summary()

dataset = Dataset()

# Use `MSE` loss and `SGD` optimizer
model.compile(
    loss=tf.keras.losses.MSE,
    optimizer=tf.keras.optimizers.SGD(),
)

model.fit(dataset, epochs=100)
```
<p>This is failing with the following shape related error in the optimizer:</p>
<pre class="lang-bash prettyprint-override"><code>ValueError: Shapes must be equal rank, but are 1 and 2 for '{{node SGD/SGD/update/ResourceApplyGradientDescent}} = ResourceApplyGradientDescent[T=DT_FLOAT, use_locking=true](fp8_test/test_layer_1/ReadVariableOp/resource, SGD/Identity, SGD/IdentityN)' with input shapes: [], [], [100000,1].
</code>```

I've been staring at the docs for a while, I'm a bit stumped as to why this isn't working, I would really appreciate any input on how to fix this toy example.

Thanks in advance.

ContentLicense: CC BY-SA 4.0

Body:
this is a similar question to: How to create a keras layer with a custom gradient in TF2.0?

Only, I would like to introduce a learnable parameter into the custom layer that I am training.

Here's a toy example of my current approach here:

# Method for calculation custom gradient
@tf.custom_gradient
def scaler(x, s):
  def grad(upstream):
    dy_dx = s
    dy_ds = x
    return dy_dx, dy_ds
  return x * s, grad

# Keras Layer with trainable parameter
class TestLayer(tf.keras.layers.Layer):
  def build(self, input_shape):
    self.scale = self.add_weight("scale",
                                 shape=[1,],
                                 initializer=tf.keras.initializers.Constant(value=2.0),
                                 trainable=True)
  def call(self, inputs):
    return scaler(inputs, self.scale)

# Creates Keras Model that uses the layer
def Model():
  x_in = tf.keras.layers.Input(shape=(1,))
  x_out = TestLayer()(x_in)
  return tf.keras.Model(inputs=x_in, outputs=x_out, name="fp8_test")

# Create toy dataset, want to learn `scale` such to satisfy 5 = 2 * scale (i.e, `scale` should learn ~2.5)
def Dataset():
  inps = tf.ones(shape=(10**5,)) * 2 # inputs
  expected = tf.ones(shape=(10**5,)) * 5 # targets
  data_in = tf.data.Dataset.from_tensors(inps)
  data_exp = tf.data.Dataset.from_tensors(expected)
  dataset = tf.data.Dataset.zip((data_in, data_exp))
  return dataset

model = Model()
model.summary()

dataset = Dataset()

# Use `MSE` loss and `SGD` optimizer
model.compile(
    loss=tf.keras.losses.MSE,
    optimizer=tf.keras.optimizers.SGD(),
)

model.fit(dataset, epochs=100)

This is failing with the following shape related error in the optimizer:

ValueError: Shapes must be equal rank, but are 1 and 2 for '{{node SGD/SGD/update/ResourceApplyGradientDescent}} = ResourceApplyGradientDescent[T=DT_FLOAT, use_locking=true](fp8_test/test_layer_1/ReadVariableOp/resource, SGD/Identity, SGD/IdentityN)' with input shapes: [], [], [100000,1].

I've been staring at the docs for a while, I'm a bit stumped as to why this isn't working, I would really appreciate any input on how to fix this toy example.

Thanks in advance.


问:
Why do I get only web service output not web service input when I create inference pipeline in ml azure?

what I have done wrong here? web service input not created automatically. Kindly help me to understand the issue.


问:
Unable to Serilize Response Data
I am developing an action filter using ASP.NET MVC. Now I am trying to serialize response data through below code, but I am getting null returned. So how to serialize the response from filter context into JSON?

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
   object ResponseData;
   var result = filterContext.Result;
   var queryString = filterContext.HttpContext.Request.QueryString.Value;
   var RequestMethod = filterContext.HttpContext.Request.Method;
   var RequestUrl = $"{filterContext.HttpContext.Request.Scheme}://{filterContext.HttpContext.Request.Host}{filterContext.HttpContext.Request.PathBase}{filterContext.HttpContext.Request.Path}{filterContext.HttpContext.Request.QueryString}";

    if (result is ObjectResult objectResult)
    {
      object x = objectResult.Value;
      if (x != null)
      {
        var Value = JsonConvert.SerializeObject(x);
        var value2 =  JsonConvert.SerializeObject(x, new JsonSerializerSettings() { Culture = CultureInfo.InvariantCulture, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

        var DesValue = JsonConvert.DeserializeObject<Response>(Value);
        if (DesValue.code != 1)
        {
          ResponseData = JsonConvert.SerializeObject(DesValue);

          LogContext.PushProperty("RequestEndTime", DateTime.Now);

          LogContext.PushProperty("ResponseHTTPCode", filterContext.HttpContext.Response.StatusCode);

 LogContext.PushProperty("ResponseData", result);

          _logger.Debug("Response Wrapper Not Found Data {RequestMethod} {RequestUrl} {RequestData} {ResponseData} {StatusCode} Information", RequestMethod, RequestUrl, ResponseData, filterContext.HttpContext.Response.StatusCode);
        }
        else
        {
          LogContext.PushProperty("RequestEndTime", DateTime.Now);
LogContext.PushProperty("ResponseHTTPCode", filterContext.HttpContext.Response.StatusCode);

LogContext.PushProperty("ResponseData", JsonConvert.SerializeObject(DesValue));

          _logger.Debug("Response Wrapper {RequestMethod} {RequestUrl} {RequestData} {ResponseData} {StatusCode} Information", RequestMethod, RequestUrl, JsonConvert.SerializeObject(DesValue), filterContext.HttpContext.Response.StatusCode);
      }
    }
  }

  base.OnActionExecuted(filterContext);
}
```

Title: Unable to Serilize Response Data


问:
Unable to publish package to pub dev
I have been trying to publish my package on pub dev but I am always receiving this error:

```<code>Connection closed before full header was received
pub finished with exit code 69
</code>```

I can't figure out what is wrong. I checked with the --dry-run command but there are no errors.

I don't know how to fix this issue please help.

Title: Unable to publish package to pub dev

Body:
I have been trying to publish my package on pub dev but I am always receiving this error:

Connection closed before full header was received
pub finished with exit code 69

I can't figure out what is wrong. I checked with the --dry-run command but there are no errors.

I don't know how to fix this issue please help.


问:
Integrating protoc/protobuf-cpp into a cmake project as "vendored dependency"
In a hobby C++ project, I use protobuf/protoc and the CMake function

```<code>find_package(Protobuf REQUIRED)

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS
"prj/proto/foo.proto"
)
</code>```

to generate the C++ code from a .proto file.

I do not have a global installation of protoc, instead I use conan and a CMake module to obtain protobuf/3.11.4 from ConanCenter and compile it for the target architecture (if there is no suitable binary on CC already).

Now I would like to get rid of conan and supply protobuf sources directly with the project.
Naively, one could imagine to put the source folder in an "external" directory:

```<code>CMakeLists.txt
src\proto\foo.proto
src\main.cpp
external\protobuf-3.11.4
external\CMakeLists.txt
</code>```

Where CMakeLists.txt contains

```<code>add_subdirectory(external)
</code>```

and external\CMakeLists.txt contains

```<code>add_subdirectory(protobuf-3.11.4)
</code>```

This apparently creates some chicken and egg problem, because the protobuf-config.cmake and protobuf-module.cmake files which provide protobuf_generate_cpp are not available prior the compilation of this external submodule and the cmake complains about not finding protobuf_generate_cpp.

I played a bit around with some hacks, but wonder what would be an appropriate way to solve this issue?

Body:
In a hobby C++ project, I use protobuf/protoc and the CMake function

find_package(Protobuf REQUIRED)

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS
"prj/proto/foo.proto"
)

to generate the C++ code from a .proto file.

I do not have a global installation of protoc, instead I use conan and a CMake module to obtain protobuf/3.11.4 from ConanCenter and compile it for the target architecture (if there is no suitable binary on CC already).

Now I would like to get rid of conan and supply protobuf sources directly with the project.
Naively, one could imagine to put the source folder in an "external" directory:

CMakeLists.txt
src\proto\foo.proto
src\main.cpp
external\protobuf-3.11.4
external\CMakeLists.txt

Where CMakeLists.txt contains

add_subdirectory(external)

and external\CMakeLists.txt contains

add_subdirectory(protobuf-3.11.4)

This apparently creates some chicken and egg problem, because the protobuf-config.cmake and protobuf-module.cmake files which provide protobuf_generate_cpp are not available prior the compilation of this external submodule and the cmake complains about not finding protobuf_generate_cpp.

I played a bit around with some hacks, but wonder what would be an appropriate way to solve this issue?


问:
Logic App Std For Each Loop Changing Valid true boolean to Invalid True
I have a simple Logic App standard workflow:

A boolean value retrieved from the table is the valid JSON values true/false, until within the "For each" loop, where it becomes True/False - invalid JSON.

[Output] Get resubmission details = "Resubmission": true

[Output] Parse table entries = "Resubmission": true

[Input] For each resubmission entry... = "Resubmission": True,

Is this a Logic App bug or a misunderstanding?

Posted here too: https://learn.microsoft.com/en-us/answers/questions/1131737/logic-app-std-for-each-loop-changing-valid-true-bo.html?childToView=1134186#answer-1134186


问:
web console for spring boot 3.0.0
I need a simple web console that allows to use rest services on spring boot 3.0.0 .

I have known for some time that swagger is stuck with developments and it is increasingly difficult to install it inside the spring boot.

I wonder if there is an alternative to swagger on spring boot 3.0.0 . Maybe spring boot has its own web console? What is recommended to use?

I'm trying to install swagger but I find it quite complicated

Title: web console for spring boot 3.0.0


问:
State processing in pyspark structured settlement
I am running a simple logic in pyspark structured streaming.

I have n events for each id
These events come in or out of order and continuously from a kafka topic.

I have to apply a logic where if event of id '123' comes check if it is final event, if it is final then process all events with that id. I need to wait for all the events of this id to perform calculation.

Sample Dataset:

Id
eventtype
value

123
load
22

123
data
32

123
unload
20

I have to group by id 123 and result should have average of all events. But I need to wait for unload event .

Result:

Id
eventtype
value

123
aggregate
24.75

How can I achieve this
Using a state store?
Using some window?

Please explain the approach with an example.


问:
Set-cookie header not available in javascript even if SameSite=None is set
I am trying to authenticate to a Drupal backend from a Cordova app. I have installed Cookie Same Site support in order to have SameSite=None in the Set-Cookie header. From my app I do the following:

```<code>async function login() {
    const response = await fetch("http://www.example.com/drupal/user/login?_format=json",
        {
            method: "POST",
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                name: 'my_username',
                pass: '...'
            })
        }) ;
    const content = await response.json() ;
    response.headers.forEach((value, key) => console.log(`${key} => ${value}`)) ;
    console.log("content" + JSON.stringify(content)) ;
}
</code>```

In the console I see

```<code>cache-control => must-revalidate, no-cache, private index.js:49:54
content-language => it index.js:49:54
content-type => application/json index.js:49:54
expires => Sun, 19 Nov 1978 05:00:00 GMT index.js:49:54
content{"current_user":{"uid":"7","roles":["authenticated"],"name":"my_username"},"csrf_token":"bpLzMVp_[...]sQM","logout_token":"9TO-gfUE[...]T7RBHicru62Qey8"}
</code>```

and in the network console

```<code>Set-Cookie: SESS6ddb039f0d9fe38fef2cae3b56a2a64f=1%2COLeo4LC4OFibbgDinG8oZF3XWGm17ROsKSNJkBnmkTRJgD;
expires=Sat, 07-Jan-2023 12:47:53 GMT; Max-Age=2000000; path=/; domain=.www.example.com;
HttpOnly; SameSite=None
Set-Cookie: SESS6ddb039f0d9fe38fef2cae3b56a2a64f-legacy=1%2COLeo4LC4OFibbgDinG8oZF3XWGm17ROsKSNJkBnmkTRJgD;
expires=Sat, 07-Jan-2023 12:47:53 GMT; Max-Age=2000000; path=/; domain=.www.example.com;
HttpOnly
</code>```

So, I see no set-cookie in the response available to Javascript, in spite of the fact that the module adds a second instance of the header with SameSite=None set. This seems to be on purpose, since in modules/contrib/cookie_samesite_support/src/Session/CookieSameSiteSupportSessionManager.php I see

```<code>    if ($original) {
      if (stripos($original, 'SameSite') === FALSE) {
        $original .= '; SameSite=None';
      }

      // Add the original cookie as per new browser expectations back.
      header($original, FALSE);

      // Add the legacy cookie.
      $legacy = str_replace($name, $name . self::LEGACY_SUFFIX, $original);
      $legacy = str_ireplace('; SameSite=None', '', $legacy);
      header($legacy, FALSE);
    }
</code>```

I don't understand the comment on "browser expectations"; still, I had the feeling that the double instance of the cookie may cause the problem, so I commented the second header. In this way in the response I got only the Set-Cookie with SameSite=None, but from the Javascript loop on headers I still do not obtain the set-cookie header.

I I have no further idea, any suggestion is highly welcome.

EDIT: Of course, I don't care to grab the cookie if I can attach it to the requests that follow – I tried to make a subsequent POST to the same site from my Javascript, and the cookie is NOT attached.

Body:
I am trying to authenticate to a Drupal backend from a Cordova app. I have installed Cookie Same Site support in order to have SameSite=None in the Set-Cookie header. From my app I do the following:

async function login() {
    const response = await fetch("http://www.example.com/drupal/user/login?_format=json",
        {
            method: "POST",
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                name: 'my_username',
                pass: '...'
            })
        }) ;
    const content = await response.json() ;
    response.headers.forEach((value, key) => console.log(`${key} => ${value}`)) ;
    console.log("content" + JSON.stringify(content)) ;
}

In the console I see

cache-control => must-revalidate, no-cache, private index.js:49:54
content-language => it index.js:49:54
content-type => application/json index.js:49:54
expires => Sun, 19 Nov 1978 05:00:00 GMT index.js:49:54
content{"current_user":{"uid":"7","roles":["authenticated"],"name":"my_username"},"csrf_token":"bpLzMVp_[...]sQM","logout_token":"9TO-gfUE[...]T7RBHicru62Qey8"}

and in the network console

Set-Cookie: SESS6ddb039f0d9fe38fef2cae3b56a2a64f=1%2COLeo4LC4OFibbgDinG8oZF3XWGm17ROsKSNJkBnmkTRJgD;
expires=Sat, 07-Jan-2023 12:47:53 GMT; Max-Age=2000000; path=/; domain=.www.example.com;
HttpOnly; SameSite=None
Set-Cookie: SESS6ddb039f0d9fe38fef2cae3b56a2a64f-legacy=1%2COLeo4LC4OFibbgDinG8oZF3XWGm17ROsKSNJkBnmkTRJgD;
expires=Sat, 07-Jan-2023 12:47:53 GMT; Max-Age=2000000; path=/; domain=.www.example.com;
HttpOnly

So, I see no set-cookie in the response available to Javascript, in spite of the fact that the module adds a second instance of the header with SameSite=None set. This seems to be on purpose, since in modules/contrib/cookie_samesite_support/src/Session/CookieSameSiteSupportSessionManager.php I see

    if ($original) {
      if (stripos($original, 'SameSite') === FALSE) {
        $original .= '; SameSite=None';
      }

      // Add the original cookie as per new browser expectations back.
      header($original, FALSE);

      // Add the legacy cookie.
      $legacy = str_replace($name, $name . self::LEGACY_SUFFIX, $original);
      $legacy = str_ireplace('; SameSite=None', '', $legacy);
      header($legacy, FALSE);
    }

I don't understand the comment on "browser expectations"; still, I had the feeling that the double instance of the cookie may cause the problem, so I commented the second header. In this way in the response I got only the Set-Cookie with SameSite=None, but from the Javascript loop on headers I still do not obtain the set-cookie header.

I I have no further idea, any suggestion is highly welcome.

EDIT: Of course, I don't care to grab the cookie if I can attach it to the requests that follow – I tried to make a subsequent POST to the same site from my Javascript, and the cookie is NOT attached.


问:
TypeError: Cannot read properties of null (reading 'url') Nextjs
I'm studying from https://www.youtube.com/watch?v=Dc7LAgqy1_E

I got this problem
I use hygraph to connect my blog website and at coverPhoto is a mistake

I tried to fix this as
t think my hygraph is not published but I already published it
also I copy API from youtube tutorial and it working for me
but my API is not working

```<code><Image  src={coverPhoto.url} alt=""/>
</code>```

and I use `` for coverPhoto.url image is not sent error but does not show image too.

I want the image to be shown on the website.

this is my API playground

```<code> query{
  posts{
    title,
    datePublished
    coverPhoto{
      url
    }
  }
}
</code>```

Body:
I'm studying from https://www.youtube.com/watch?v=Dc7LAgqy1_E

I got this problem
I use hygraph to connect my blog website and at coverPhoto is a mistake

I tried to fix this as
t think my hygraph is not published but I already published it
also I copy API from youtube tutorial and it working for me
but my API is not working

<Image  src={coverPhoto.url} alt=""/>

and I use `` for coverPhoto.url image is not sent error but does not show image too.

I want the image to be shown on the website.

this is my API playground

 query{
  posts{
    title,
    datePublished
    coverPhoto{
      url
    }
  }
}


问:
Using 301 redirects at server config level on NGINX to avoid suspected WP issues?
OK, our old website is Wordpress installed on a NGINX bitnami distribution in AWS.

Our new website is on managed hosting on a new domain name.

For the migration, we'd used the plugin 'Simple 301 redirects' to map each page to the new site structure.

However, for reasons we can't fathom and have only just spotted, all the redirects are reporting as 302 - which is hurting our SEO.

Our theory is that re-implementing the 301s but at server level config on the NGINX server will be used before it hits the WP installation, and hopefully achieve an actual 301 redirect.

I can find a number of support articles that might help us: https://www.digitalocean.com/community/tutorials/how-to-create-temporary-and-permanent-redirects-with-nginx although this article suggests using return instead of rewrite: https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/?highlight=rewrite#taxing-rewrites

If our theory is correct, we'll create a new server config that redirects each individual page (we need to do this, as the site structure has changed in some cases - it is about 250 pages FYI).

Would somebody be able to offer any additional advice on this?

We're still baffled as to why it is returning 302 redirects rather than 301...!

Greatly appreciated!


问:
flutter_widget_from_html tags cannot using custom Styles Builder
I am using flutter_widget_from_html: 0.9.0+1. Faced a problem, some widgets do not use customStyleBuilder and do not use TextStyle. Who creates a solution to the problem. Thanks in advance.

Its HTML string doesnt work

```<code>String value1 = '''
<p class=\"\">
  <span style=\"font-family: 'OpenSans-Semibold'; font-size: 56px; line-height: 64px;\">
    Hello World Not Working
  </span>
</p>
</code>```

But this HTML string is working

```<code>String value = '''
<p class=\"\">
   <span style=\"font-family: OpenSans-Semibold; font-size: 56px; line-height: 64px;\">
     <strong>
       Hello World Working
     </strong>
    </span>
</p>''';
</code>```

Flutter Widget Code

```<code>HtmlWidget(
        value,
        textStyle: TextStyle(
          fontFamily: 'Arial',
          fontSize: 20,
        ),
        customStylesBuilder: (element) {
          return {
            'font-size': '20px',
          };
        },
</code>```

`

Thanks everyone for the help

I tried many different solutions but nothing worked. But i need use only flutter_widget_from_html, flutter_html not suitableю

Body:
I am using flutter_widget_from_html: 0.9.0+1. Faced a problem, some widgets do not use customStyleBuilder and do not use TextStyle. Who creates a solution to the problem. Thanks in advance.

Its HTML string doesnt work

String value1 = '''

    Hello World Not Working

But this HTML string is working

String value = '''

       Hello World Working

''';

Flutter Widget Code

HtmlWidget(
        value,
        textStyle: TextStyle(
          fontFamily: 'Arial',
          fontSize: 20,
        ),
        customStylesBuilder: (element) {
          return {
            'font-size': '20px',
          };
        },

`

Thanks everyone for the help

I tried many different solutions but nothing worked. But i need use only flutter_widget_from_html, flutter_html not suitableю


问:
Spring Data ElasticSearch: Save document where some fields are dynamic
I have a document I need to save in elastic search where some fields are dynamic, in a HashMap, and some fields I know in advance and can annotate with @Field and so on.

So something like this:

```<code>public MyClass {
    private String fieldA;
    private String fieldB;
    private Map<String, Object> dynamicFields;

}
</code>```

How would I do this? I don't know in advance, which keys will be contained in dynamicFields.

I would also like to define the mapping for the values in dynamicFields, so for instance save dates as dates and not as timestamps.

Is dynamic field mapping the way to go? If so, where can I find examples for that?

Body:
I have a document I need to save in elastic search where some fields are dynamic, in a HashMap, and some fields I know in advance and can annotate with @Field and so on.

So something like this:

public MyClass {
    private String fieldA;
    private String fieldB;
    private Map<String, Object> dynamicFields;

}

How would I do this? I don't know in advance, which keys will be contained in dynamicFields.

I would also like to define the mapping for the values in dynamicFields, so for instance save dates as dates and not as timestamps.

Is dynamic field mapping the way to go? If so, where can I find examples for that?


问:
How to check input and output from stdin/stdout in JavaScript(node.js)?
I solve training problems for admission to an internship program in one of the companies.

I need to write solution by stdin\stdout for automate testing on a site.

Input example:

```<code>5 5

1  4  9  16  25

2
</code>```

Output example:

```<code>24
</code>```

I try to apply stdin according to example on the site.

```<code>var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let total = 0;
process.stdin.on('end', () => { console.log(total); process.exit(0); });
rl.on('line', function (data) {
        data = data.split(' ');

        //I consider that every variable is an array
        const countAndTime = parseInt(data[0]) || 0
        const floors = parseInt(data[1]) || 0
        const outgoing = parseInt(data[2]) || 0

        const howMuchMinutes = (countAndTime, floors, outgoing) => {
            let maxTime

            //Solution is here

            return maxTime
        }

        total = howMuchMinutes(countAndTime, floors, outgoing)
});
</code>```

I get response "Partial Solution" as result.

By the way, this response I get with any tasks that I tried to do on this site.

If I am solving this problem in my VS Code and printing response in console averything works correctly.

I don't understand, the problem is in my solution or I just write stdin\stdout by a wrong way?

Is here a way to check input and output datas of stdin/stdout? May be there is any site, that do such testing and print not only short response "Partial Solution", but data from stdout too? Or maybe it possible to write such test themselve?

If I wrote stdin\stdout incorrectly for getting arrays in my solution, I would be grateful if you write right way to use it.

Body:
I solve training problems for admission to an internship program in one of the companies.

I need to write solution by stdin\stdout for automate testing on a site.

Input example:

5 5

1  4  9  16  25

2

Output example:

24

I try to apply stdin according to example on the site.

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let total = 0;
process.stdin.on('end', () => { console.log(total); process.exit(0); });
rl.on('line', function (data) {
        data = data.split(' ');

        //I consider that every variable is an array
        const countAndTime = parseInt(data[0]) || 0
        const floors = parseInt(data[1]) || 0
        const outgoing = parseInt(data[2]) || 0

        const howMuchMinutes = (countAndTime, floors, outgoing) => {
            let maxTime

            //Solution is here

            return maxTime
        }

        total = howMuchMinutes(countAndTime, floors, outgoing)
});

I get response "Partial Solution" as result.

By the way, this response I get with any tasks that I tried to do on this site.

If I am solving this problem in my VS Code and printing response in console averything works correctly.

I don't understand, the problem is in my solution or I just write stdin\stdout by a wrong way?

Is here a way to check input and output datas of stdin/stdout? May be there is any site, that do such testing and print not only short response "Partial Solution", but data from stdout too? Or maybe it possible to write such test themselve?

If I wrote stdin\stdout incorrectly for getting arrays in my solution, I would be grateful if you write right way to use it.


问:
d3.js scatter plot point error: condition add
Add the condition issuse

<!DOCTYPE html>
<meta charset="utf-8">

```
</div>
</div>
</p>
<p><strong>Not add condition look fine</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v5.min.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>

    // set the dimensions and margins of the graph
    const margin = { top: 10, right: 30, bottom: 30, left: 60 },
        width = 460 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    // append the svg object to the body of the page
    const svg = d3.select("#my_dataviz")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", `translate(${margin.left}, ${margin.top})`);

    //Read the data
    d3.csv("https://gist.githubusercontent.com/FANJIYU0825/5626c7449001fc46895412fda1b5c139/raw/9e996d1edec867b2f590285c4e1e769dd482b91c/clean_data").then(function (data) {

        // Add X axis
        const x = d3.scaleLinear()
            .domain([d3.min(data, (d) => d.Rating) - 0.1, d3.max(data, (d) => d.Rating),])
            .range([0, width]);
        svg.append("g")
            .attr("transform", `translate(0, ${height})`)
            .call(d3.axisBottom(x));

        // Add Y axis
        const y = d3.scaleLinear()
            .domain([d3.min(data, (d) => d.Size) - 5, d3.max(data, (d) => d.Size) + 20])
            .range([height, 0]);
        svg.append("g")
            .call(d3.axisLeft(y));

        // Add dots
        svg.append('g')
            .selectAll("dot")
            .data(data)
            .join("circle")
            .attr("cx", (d, i) => { return x(d.Rating); })
            .attr("cy", (d, i) => { return y(d.Size); })
            .attr("r", 7)
            .style("fill", "#69b3a2")

    })
</script></code>```

I get confused becasuse the last part of csv data get wrong position
I am not so sure why the data scale wrong other  poitn position is fine but the last data erro no matter what the data is. The scale will show at the part of the top.
At the time  that I add the condition.
Other is not different from the sample of
enter link description here
enter image description here

Body:
Add the condition issuse

<!DOCTYPE html>
<meta charset="utf-8">

Not add condition look fine

<!DOCTYPE html>
<meta charset="utf-8">

I get confused becasuse the last part of csv data get wrong position
I am not so sure why the data scale wrong other  poitn position is fine but the last data erro no matter what the data is. The scale will show at the part of the top.
At the time  that I add the condition.
Other is not different from the sample of
enter link description here
enter image description here


问:
Caching by a custom interface from IDistributedCache
I want to implement a custom interface from IDistributedCache and create a dynamic key for all queries in my services but I have a problem.

When I have an Id in GET(Id), I can create a unique key by Id but when my query is Getall(), I don't have an input to create a unique key.

How can I create a unique key for all queries without hard-coding it in the project?

Please help me

i use this interface but i dont know how it work!!!!!

```<code>    /// <summary>
    /// Represents a manager for caching between HTTP requests (long term caching)
    /// </summary>
    public interface IStaticCacheManager : IDisposable
    {
        /// <summary>
        /// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
        /// </summary>
        /// <param name="key">A string identifying the requested value.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
        Task RefreshAsync(CacheKey key);

        /// <summary>
        /// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
        /// </summary>
        /// <param name="key">A string identifying the requested value.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
        void Refresh(CacheKey key);

        /// <summary>
        /// Get a cached item. If it's not in the cache yet, then load and cache it
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the cached value associated with the specified key
        /// </returns>
        Task<T> GetAsync<T>(CacheKey key, Func<Task<T>> acquire);

        /// <summary>
        /// Get a cached item. If it's not in the cache yet, then load and cache it
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task r
        ///
        ///
        /// esult contains the cached value associated with the specified key
        /// </returns>
        Task<T> GetAsync<T>(CacheKey key, Func<T> acquire);

        /// <summary>
        /// Get a cached item. If it's not in the cache yet, then load and cache it
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <returns>The cached value associated with the specified key</returns>
        T Get<T>(CacheKey key, Func<T> acquire);

        /// <summary>
        /// Remove the value with the specified key from the cache
        /// </summary>
        /// <param name="cacheKey">Cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        Task RemoveAsync(CacheKey cacheKey, params object[] cacheKeyParameters);

        /// <summary>
        /// Remove the value with the specified key from the cache
        /// </summary>
        /// <param name="cacheKey">Cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        void Remove(CacheKey cacheKey, params object[] cacheKeyParameters);

        /// <summary>
        /// Add the specified key and object to the cache
        /// </summary>
        /// <param name="key">Key of cached item</param>
        /// <param name="data">Value for caching</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        Task SetAsync(CacheKey key, object data);

        /// <summary>
        /// Add the specified key and object to the cache
        /// </summary>
        /// <param name="key">Key of cached item</param>
        /// <param name="data">Value for caching</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        void Set(CacheKey key, object data);

        /// <summary>
        /// Remove items by cache key prefix
        /// </summary>
        /// <param name="prefix">Cache key prefix</param>
        /// <param name="prefixParameters">Parameters to create cache key prefix</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        Task RemoveByPrefixAsync(string prefix, params object[] prefixParameters);

        /// <summary>
        /// Clear all cache data
        /// </summary>
        /// <returns>A task that represents the asynchronous operation</returns>
        Task ClearAsync();

        /// <summary>
        /// Clear all cache data
        /// </summary>
        /// <returns>A task that represents the asynchronous operation</returns>
        void Clear();

        #region Cache key

        /// <summary>
        /// Create a copy of cache key and fills it by passed parameters
        /// </summary>
        /// <param name="cacheKey">Initial cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>Cache key</returns>
        CacheKey PrepareKey(CacheKey cacheKey, params object[] cacheKeyParameters);

        /// <summary>
        /// Create a copy of cache key using the default cache time and fills it by passed parameters
        /// </summary>
        /// <param name="cacheKey">Initial cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>Cache key</returns>
        CacheKey PrepareKeyForDefaultCache(CacheKey cacheKey, params object[] cacheKeyParameters);

        /// <summary>
        /// Create a copy of cache key using the short cache time and fills it by passed parameters
        /// </summary>
        /// <param name="cacheKey">Initial cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>Cache key</returns>
        CacheKey PrepareKeyForShortTermCache(CacheKey cacheKey, params object[] cacheKeyParameters);

        #endregion
    }

    /// <summary>
    /// Represents key for caching objects
    /// </summary>
    public partial class CacheKey
    {
        #region Ctor

        /// <summary>
        /// Initialize a new instance with key and prefixes
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="prefixes">Prefixes for remove by prefix functionality</param>
        public CacheKey(string key, params string[] prefixes)
        {
            Key = key;
            Prefixes.AddRange(prefixes.Where(prefix => !string.IsNullOrEmpty(prefix)));
        }

        #endregion

        #region Methods

        /// <summary>
        /// Create a new instance from the current one and fill it with passed parameters
        /// </summary>
        /// <param name="createCacheKeyParameters">Function to create parameters</param>
        /// <param name="keyObjects">Objects to create parameters</param>
        /// <returns>Cache key</returns>
        public virtual CacheKey Create(Func<object, object> createCacheKeyParameters, params object[] keyObjects)
        {
            var cacheKey = new CacheKey(Key, Prefixes.ToArray());

            if (!keyObjects.Any())
                return cacheKey;

            cacheKey.Key = string.Format(cacheKey.Key, keyObjects.Select(createCacheKeyParameters).ToArray());

            for (var i = 0; i < cacheKey.Prefixes.Count; i++)
                cacheKey.Prefixes[i] = string.Format(cacheKey.Prefixes[i], keyObjects.Select(createCacheKeyParameters).ToArray());

            return cacheKey;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets a cache key
        /// </summary>
        public string Key { get; protected set; }

        /// <summary>
        /// Gets or sets prefixes for remove by prefix functionality
        /// </summary>
        public List<string> Prefixes { get; protected set; } = new List<string>();

        /// <summary>
        /// Gets or sets a cache time in minutes
        /// </summary>
        public DistributedCacheEntryOptions CacheTime { get; set; } //= Singleton<AppSettings>.Instance.Get<CacheConfig>().DefaultCacheTime;

        #endregion
    }
</code>```

Body:
I want to implement a custom interface from IDistributedCache and create a dynamic key for all queries in my services but I have a problem.

When I have an Id in GET(Id), I can create a unique key by Id but when my query is Getall(), I don't have an input to create a unique key.

How can I create a unique key for all queries without hard-coding it in the project?

Please help me

i use this interface but i dont know how it work!!!!!

    ///
    /// Represents a manager for caching between HTTP requests (long term caching)
    ///
    public interface IStaticCacheManager : IDisposable
    {
        ///
        /// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
        ///
        /// <param name="key">A string identifying the requested value.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
        Task RefreshAsync(CacheKey key);

        ///
        /// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
        ///
        /// <param name="key">A string identifying the requested value.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
        void Refresh(CacheKey key);

        ///
        /// Get a cached item. If it's not in the cache yet, then load and cache it
        ///
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the cached value associated with the specified key
        /// </returns>
        Task<T> GetAsync<T>(CacheKey key, Func<Task<T>> acquire);

        ///
        /// Get a cached item. If it's not in the cache yet, then load and cache it
        ///
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task r
        ///
        ///
        /// esult contains the cached value associated with the specified key
        /// </returns>
        Task<T> GetAsync<T>(CacheKey key, Func<T> acquire);

        ///
        /// Get a cached item. If it's not in the cache yet, then load and cache it
        ///
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <returns>The cached value associated with the specified key</returns>
        T Get<T>(CacheKey key, Func<T> acquire);

        ///
        /// Remove the value with the specified key from the cache
        ///
        /// <param name="cacheKey">Cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        Task RemoveAsync(CacheKey cacheKey, params object[] cacheKeyParameters);

        ///
        /// Remove the value with the specified key from the cache
        ///
        /// <param name="cacheKey">Cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        void Remove(CacheKey cacheKey, params object[] cacheKeyParameters);

        ///
        /// Add the specified key and object to the cache
        ///
        /// <param name="key">Key of cached item</param>
        /// <param name="data">Value for caching</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        Task SetAsync(CacheKey key, object data);

        ///
        /// Add the specified key and object to the cache
        ///
        /// <param name="key">Key of cached item</param>
        /// <param name="data">Value for caching</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        void Set(CacheKey key, object data);

        ///
        /// Remove items by cache key prefix
        ///
        /// <param name="prefix">Cache key prefix</param>
        /// <param name="prefixParameters">Parameters to create cache key prefix</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        Task RemoveByPrefixAsync(string prefix, params object[] prefixParameters);

        ///
        /// Clear all cache data
        ///
        /// <returns>A task that represents the asynchronous operation</returns>
        Task ClearAsync();

        ///
        /// Clear all cache data
        ///
        /// <returns>A task that represents the asynchronous operation</returns>
        void Clear();

        #region Cache key

        ///
        /// Create a copy of cache key and fills it by passed parameters
        ///
        /// <param name="cacheKey">Initial cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>Cache key</returns>
        CacheKey PrepareKey(CacheKey cacheKey, params object[] cacheKeyParameters);

        ///
        /// Create a copy of cache key using the default cache time and fills it by passed parameters
        ///
        /// <param name="cacheKey">Initial cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>Cache key</returns>
        CacheKey PrepareKeyForDefaultCache(CacheKey cacheKey, params object[] cacheKeyParameters);

        ///
        /// Create a copy of cache key using the short cache time and fills it by passed parameters
        ///
        /// <param name="cacheKey">Initial cache key</param>
        /// <param name="cacheKeyParameters">Parameters to create cache key</param>
        /// <returns>Cache key</returns>
        CacheKey PrepareKeyForShortTermCache(CacheKey cacheKey, params object[] cacheKeyParameters);

        #endregion
    }

    ///
    /// Represents key for caching objects
    ///
    public partial class CacheKey
    {
        #region Ctor

        ///
        /// Initialize a new instance with key and prefixes
        ///
        /// <param name="key">Key</param>
        /// <param name="prefixes">Prefixes for remove by prefix functionality</param>
        public CacheKey(string key, params string[] prefixes)
        {
            Key = key;
            Prefixes.AddRange(prefixes.Where(prefix => !string.IsNullOrEmpty(prefix)));
        }

        #endregion

        #region Methods

        ///
        /// Create a new instance from the current one and fill it with passed parameters
        ///
        /// <param name="createCacheKeyParameters">Function to create parameters</param>
        /// <param name="keyObjects">Objects to create parameters</param>
        /// <returns>Cache key</returns>
        public virtual CacheKey Create(Func<object, object> createCacheKeyParameters, params object[] keyObjects)
        {
            var cacheKey = new CacheKey(Key, Prefixes.ToArray());

            if (!keyObjects.Any())
                return cacheKey;

            cacheKey.Key = string.Format(cacheKey.Key, keyObjects.Select(createCacheKeyParameters).ToArray());

            for (var i = 0; i < cacheKey.Prefixes.Count; i++)
                cacheKey.Prefixes[i] = string.Format(cacheKey.Prefixes[i], keyObjects.Select(createCacheKeyParameters).ToArray());

            return cacheKey;
        }

        #endregion

        #region Properties

        ///
        /// Gets or sets a cache key
        ///
        public string Key { get; protected set; }

        ///
        /// Gets or sets prefixes for remove by prefix functionality
        ///
        public List<string> Prefixes { get; protected set; } = new List<string>();

        ///
        /// Gets or sets a cache time in minutes
        ///
        public DistributedCacheEntryOptions CacheTime { get; set; } //= Singleton<AppSettings>.Instance.Get<CacheConfig>().DefaultCacheTime;

        #endregion
    }


问:
ValueError: Found input variables with inconsistent numbers of samples: [137, 68]
I encountered an error while building a linear regression model. Judging by their shape, it seems appropriate.

X = df_one_hot[features]
y = df_one_hot["price"]

X_train, y_train, X_test, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)
model = LinearRegression().fit(X_train,y_train)
y_pred = model.predict(X_test)
RMSE = np.sqrt(mean_squared_error(y_test, y_pred))
print("RMSE: ", RMSE)
```
<p>X.shape</p>
<pre class="lang-py prettyprint-override"><code>(205, 46)
</code>```

y.shape

(205,)
```
<p>X_train.shape</p>
<pre class="lang-py prettyprint-override"><code>(137, 46)
</code>```

y_train.shape

(68, 46)
```
<p>This is the error:</p>
<pre class="lang-py prettyprint-override"><code>ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_7740\1016843113.py in <module>
      1 X_train, y_train, X_test, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)
----> 2 model = LinearRegression().fit(X_train,y_train)
      3 y_pred = model.predict(X_test)
      4 RMSE = np.sqrt(mean_squared_error(y_test, y_pred))
      5 print("RMSE: ", RMSE)

~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py in fit(self, X, y, sample_weight)
    660         accept_sparse = False if self.positive else ["csr", "csc", "coo"]
    661
--> 662         X, y = self._validate_data(
    663             X, y, accept_sparse=accept_sparse, y_numeric=True, multi_output=True
    664         )

~\anaconda3\lib\site-packages\sklearn\base.py in _validate_data(self, X, y, reset, validate_separately, **check_params)
    579                 y = check_array(y, **check_y_params)
    580             else:
--> 581                 X, y = check_X_y(X, y, **check_params)
    582             out = X, y
    583

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
    979     y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric)
    980
--> 981     check_consistent_length(X, y)
    982
    983     return X, y

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
    330     uniques = np.unique(lengths)
    331     if len(uniques) > 1:
--> 332         raise ValueError(
    333             "Found input variables with inconsistent numbers of samples: %r"
    334             % [int(l) for l in lengths]

ValueError: Found input variables with inconsistent numbers of samples: [137, 68]
</code>```

I can't build a linear regression model despite all I've tried

Body:
I encountered an error while building a linear regression model. Judging by their shape, it seems appropriate.

X = df_one_hot[features]
y = df_one_hot["price"]

X_train, y_train, X_test, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)
model = LinearRegression().fit(X_train,y_train)
y_pred = model.predict(X_test)
RMSE = np.sqrt(mean_squared_error(y_test, y_pred))
print("RMSE: ", RMSE)

X.shape

(205, 46)

y.shape

(205,)

X_train.shape

(137, 46)

y_train.shape

(68, 46)

This is the error:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_7740\1016843113.py in <module>
      1 X_train, y_train, X_test, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)
----> 2 model = LinearRegression().fit(X_train,y_train)
      3 y_pred = model.predict(X_test)
      4 RMSE = np.sqrt(mean_squared_error(y_test, y_pred))
      5 print("RMSE: ", RMSE)

~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py in fit(self, X, y, sample_weight)
    660         accept_sparse = False if self.positive else ["csr", "csc", "coo"]
    661
--> 662         X, y = self._validate_data(
    663             X, y, accept_sparse=accept_sparse, y_numeric=True, multi_output=True
    664         )

~\anaconda3\lib\site-packages\sklearn\base.py in _validate_data(self, X, y, reset, validate_separately, **check_params)
    579                 y = check_array(y, **check_y_params)
    580             else:
--> 581                 X, y = check_X_y(X, y, **check_params)
    582             out = X, y
    583

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
    979     y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric)
    980
--> 981     check_consistent_length(X, y)
    982
    983     return X, y

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
    330     uniques = np.unique(lengths)
    331     if len(uniques) > 1:
--> 332         raise ValueError(
    333             "Found input variables with inconsistent numbers of samples: %r"
    334             % [int(l) for l in lengths]

ValueError: Found input variables with inconsistent numbers of samples: [137, 68]

I can't build a linear regression model despite all I've tried


问:
Swift AVAudioUnitReverb's bypass property works incorrectly
Looks like bypass property for AVAudioUnitReverb works incorrectly.

If AVAudioUnitReverb.bypass is set to true - it's switch off whole graph and no sound produced from the engine's output node.
 It is incorrect behaviour, since it should switch off only AVAudioUnitReverb node and ignoring it during playback.

bypass property of other AVAudioUnitEffect (e.g. AVAudioUnitDelay, AVAudioUnitDistortion) works correctly and switch off only effect node.

Example graph:

AVAudioPlayerNode -> AVAudioUnitReverb -> engine.mainMixerNode

so in this example if AVAudioUnitReverb.bypass is set to true - it will switch off all sound and nothing will be produced from engine's output. But according to documentation is should switch only AVAudioUnitReverb effect, so engine's output would be whatever is scheduled to play on AVAudioPlayerNode.

Example code:

```<code>let engine = AVAudioEngine()
let player = AVAudioPlayerNode()
let reverb = AVAudioUnitReverb()
var file: AVAudioFile // load some sound file
let format = file.processingFormat

engine.attach(player)
engine.attach(reverb)
engine.connect(player, to: reverb, format: format)
engine.connect(reverb, to: engine.mainMixerNode, format: format)

engine.prepare()
engine.start()

reverb.bypass = false // if set to true - no sound will be produced at all
reverb.wetDryMix = 100
reverb.loadFactoryPreset(AVAudioUnitReverbPreset.largeHall2)

player.scheduleFile(file, at: nil)
player.play()
</code>```

I am not understand why it's behave like this and I don't know how to debug it or fix it. Also I can't find any related information regarding this issue.

Any help would be appreciated.

Thanks!

Body:
Looks like bypass property for AVAudioUnitReverb works incorrectly.

If AVAudioUnitReverb.bypass is set to true - it's switch off whole graph and no sound produced from the engine's output node.
 It is incorrect behaviour, since it should switch off only AVAudioUnitReverb node and ignoring it during playback.

bypass property of other AVAudioUnitEffect (e.g. AVAudioUnitDelay, AVAudioUnitDistortion) works correctly and switch off only effect node.

Example graph:

AVAudioPlayerNode -> AVAudioUnitReverb -> engine.mainMixerNode

so in this example if AVAudioUnitReverb.bypass is set to true - it will switch off all sound and nothing will be produced from engine's output. But according to documentation is should switch only AVAudioUnitReverb effect, so engine's output would be whatever is scheduled to play on AVAudioPlayerNode.

Example code:

let engine = AVAudioEngine()
let player = AVAudioPlayerNode()
let reverb = AVAudioUnitReverb()
var file: AVAudioFile // load some sound file
let format = file.processingFormat

engine.attach(player)
engine.attach(reverb)
engine.connect(player, to: reverb, format: format)
engine.connect(reverb, to: engine.mainMixerNode, format: format)

engine.prepare()
engine.start()

reverb.bypass = false // if set to true - no sound will be produced at all
reverb.wetDryMix = 100
reverb.loadFactoryPreset(AVAudioUnitReverbPreset.largeHall2)

player.scheduleFile(file, at: nil)
player.play()

I am not understand why it's behave like this and I don't know how to debug it or fix it. Also I can't find any related information regarding this issue.

Any help would be appreciated.

Thanks!


问:
Using a pointer to a hashmap
I'm working on a game engine. I have a loading class that loads every single texture, audio, and music file before the game starts up into a shared ptr that goes into a hashmap.Specific datatype:

std::unordered_map<std::string, std::shared_ptr<Texture2D> >

I have an Entity class which has a textureMap of the following dataType:

std::shared_ptr <std::unordered_map<std::string, std::shared_ptr<Texture2D> >>

I'm using raylib for graphics and DrawTexture takes Texture2D as a parameter, not Texture2D pointer. I'm confused about how to go from the ptr to the map to the ptr and then dereference the texture, as it doesn't work to just do this:

DrawTexture(*textureMap->find("Entity"),100, 100, WHITE);

I get the following error from that line:

no suitable user-defined conversion from "std::pair<const std::string, std::shared_ptr<Texture2D>>" to "Texture2D" exists

What am I doing wrong?

I looked through the C++ docs. No C++ std call that might help worked.

```<code>/* loader */

class loaderTemp {
    std::unordered_map<std::string, std::shared_ptr<Texture2D>> textureMap;

    loaderTemp() {
        this->textureMap["Entity"] = std::make_shared<Texture2D>(LoadTexture("resources/KeplerEngineLogo.png"));
    }
};

loaderTemp tempLoader();

/* entity */

class entityTemp {
    std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Texture2D>>> textureMap;
    entityTemp(std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Texture2D>>> textureMapArg) {

        textureMap = textureMapArg;

        DrawTexture(*textureMap->find("Entity"), 100, 100, WHITE);
    }
};

Entity testentity(std::make_shared<std::unordered_map<std::string, std::shared_ptr<Texture2D>>>(tempLoader.textureMap)); // Constructor
</code>```

Keep in mind this is using raylib, so some functions are just unreproducable.

What I want to come out is of course a derefrencing of texture2D from the loader class inside of the entity class.

Title: Using a pointer to a hashmap

Body:
I'm working on a game engine. I have a loading class that loads every single texture, audio, and music file before the game starts up into a shared ptr that goes into a hashmap.Specific datatype:

std::unordered_map<std::string, std::shared_ptr<Texture2D> >

I have an Entity class which has a textureMap of the following dataType:

std::shared_ptr <std::unordered_map<std::string, std::shared_ptr<Texture2D> >>

I'm using raylib for graphics and DrawTexture takes Texture2D as a parameter, not Texture2D pointer. I'm confused about how to go from the ptr to the map to the ptr and then dereference the texture, as it doesn't work to just do this:

DrawTexture(*textureMap->find("Entity"),100, 100, WHITE);

I get the following error from that line:

no suitable user-defined conversion from "std::pair<const std::string, std::shared_ptr<Texture2D>>" to "Texture2D" exists

What am I doing wrong?

I looked through the C++ docs. No C++ std call that might help worked.

/* loader */

class loaderTemp {
    std::unordered_map<std::string, std::shared_ptr<Texture2D>> textureMap;

    loaderTemp() {
        this->textureMap["Entity"] = std::make_shared<Texture2D>(LoadTexture("resources/KeplerEngineLogo.png"));
    }
};

loaderTemp tempLoader();

/* entity */

class entityTemp {
    std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Texture2D>>> textureMap;
    entityTemp(std::shared_ptr<std::unordered_map<std::string, std::shared_ptr<Texture2D>>> textureMapArg) {

        textureMap = textureMapArg;

        DrawTexture(*textureMap->find("Entity"), 100, 100, WHITE);
    }
};

Entity testentity(std::make_shared<std::unordered_map<std::string, std::shared_ptr<Texture2D>>>(tempLoader.textureMap)); // Constructor

Keep in mind this is using raylib, so some functions are just unreproducable.

What I want to come out is of course a derefrencing of texture2D from the loader class inside of the entity class.


问:
How to get the accuracy using Gradient Descent on iris dataset
I have to get the prediction of the iris dataset using GD and Logistic regression. I have done that part and the code is given below. What I want to know is how to do this using the OneHot function. (That is also given at the end)

```<code>import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn.preprocessing import normalize
import pandas as pd

iris = datasets.load_iris()
X, y = iris.data, iris.target
# As this is a training model, need only the first 100 data for X axis
list(iris.keys())
X = iris['data']
X = X[0:99]
# As there are many empty fields and the data are not in accurate values, Fix them by
#normalizing the X
X = normalize(X, norm='l2')
y = iris['target']
# print(y)
y = np.reshape(y, (1, 150))
# To get the first 100 values easily
y = y.T
y = y[0:99]
y = normalize(y, norm='l2')
enter code here
# Logistic function
def sigmoidFunction(x):
   return 1 / (1 + np.exp(-x))
# Predict Y
def predictYValue(X, weights, intercept):
   y_hat = np.dot(X, weights) + intercept
   predictedYValues = sigmoidFunction(y_hat)
   return predictedYValues
# Using Gradient Descent with Sigmoid Function
def GDWithSigmoid(X, y, weights, intercept):
   for _ in range(maxIterations):
      predictedYValues = predictYValue(X, weights, intercept)
      wDerivative = (1 / noRecords) * np.dot(X.T, (predictedYValues - y))
      bDerivative = (1 / noRecords) * np.sum(predictedYValues - y)

      weights -= alpha * wDerivative
      intercept -= alpha * bDerivative
# Initializing all the necessaries
noRecords = X.shape[0]
noAttributes = X.shape[1]
alpha = 0.001
maxIterations = 1000
weights = np.zeros(noAttributes)
intercept = 0
y = y.flatten()
enter code here
# Running GD Function
GDWithSigmoid(X, y, weights, intercept)
enter code here
# Predict class (0 or 1)
def predictYClasses(X):
   predictedYValues = predictYValue(X, weights, intercept)
   predictYClass = [0 if i<=0.5 else 1 for i in  predictedYValues]
   return predictYClass
enter code here
# Predict Class
predictions = predictYClasses(X)
def calculateAccuracy(actualYValues, predictedYValues):
   count = 0
   for i in range(len(predictedYValues)):
      if predictedYValues[i] == actualYValues[i]:
          count += 1
      acc = count / len(actualYValues)
   return acc
results = pd.DataFrame({'Actual Y Value': y, 'Predicted Y Value': predictions})
print(results)
enter code here
print("\n----------------------------------------")
print("\nPREDICTION ACCURACY:", calculateAccuracy(y, predictions))
print("\n----------------------------------------")
</code>```

I got the correct output from this. But now, what I want is, to implement this using One Hot.

```<code>def oneHotIt(Y):
   m = Y.shape[0]
   OHX = scipy.sparse.csr_matrix((np.ones(m),
   (Y, np.array(range(m)))))
   OHX = np.array(OHX.todense()).T
   return OHX
</code>```

The problem is how to combine the upper part and this as X and Y have two different shapes.

Body:
I have to get the prediction of the iris dataset using GD and Logistic regression. I have done that part and the code is given below. What I want to know is how to do this using the OneHot function. (That is also given at the end)

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn.preprocessing import normalize
import pandas as pd

iris = datasets.load_iris()
X, y = iris.data, iris.target
# As this is a training model, need only the first 100 data for X axis
list(iris.keys())
X = iris['data']
X = X[0:99]
# As there are many empty fields and the data are not in accurate values, Fix them by
#normalizing the X
X = normalize(X, norm='l2')
y = iris['target']
# print(y)
y = np.reshape(y, (1, 150))
# To get the first 100 values easily
y = y.T
y = y[0:99]
y = normalize(y, norm='l2')
enter code here
# Logistic function
def sigmoidFunction(x):
   return 1 / (1 + np.exp(-x))
# Predict Y
def predictYValue(X, weights, intercept):
   y_hat = np.dot(X, weights) + intercept
   predictedYValues = sigmoidFunction(y_hat)
   return predictedYValues
# Using Gradient Descent with Sigmoid Function
def GDWithSigmoid(X, y, weights, intercept):
   for _ in range(maxIterations):
      predictedYValues = predictYValue(X, weights, intercept)
      wDerivative = (1 / noRecords) * np.dot(X.T, (predictedYValues - y))
      bDerivative = (1 / noRecords) * np.sum(predictedYValues - y)

      weights -= alpha * wDerivative
      intercept -= alpha * bDerivative
# Initializing all the necessaries
noRecords = X.shape[0]
noAttributes = X.shape[1]
alpha = 0.001
maxIterations = 1000
weights = np.zeros(noAttributes)
intercept = 0
y = y.flatten()
enter code here
# Running GD Function
GDWithSigmoid(X, y, weights, intercept)
enter code here
# Predict class (0 or 1)
def predictYClasses(X):
   predictedYValues = predictYValue(X, weights, intercept)
   predictYClass = [0 if i<=0.5 else 1 for i in  predictedYValues]
   return predictYClass
enter code here
# Predict Class
predictions = predictYClasses(X)
def calculateAccuracy(actualYValues, predictedYValues):
   count = 0
   for i in range(len(predictedYValues)):
      if predictedYValues[i] == actualYValues[i]:
          count += 1
      acc = count / len(actualYValues)
   return acc
results = pd.DataFrame({'Actual Y Value': y, 'Predicted Y Value': predictions})
print(results)
enter code here
print("\n----------------------------------------")
print("\nPREDICTION ACCURACY:", calculateAccuracy(y, predictions))
print("\n----------------------------------------")

I got the correct output from this. But now, what I want is, to implement this using One Hot.

def oneHotIt(Y):
   m = Y.shape[0]
   OHX = scipy.sparse.csr_matrix((np.ones(m),
   (Y, np.array(range(m)))))
   OHX = np.array(OHX.todense()).T
   return OHX

The problem is how to combine the upper part and this as X and Y have two different shapes.


问:
Odoo 13 POS - Auto select invoice button
how can I make this invoice button auto-select? Some users miss clicking this and it doesn't create invoice.

How can I make this button auto-selected before validating?


问:
Why does filtering return copy and slicing return view?
I'm exploring pandas and notice that filtering returns a copy and slicing returns a view.

Why is that so?


问:
Weird behaviour with htaccess RewriteRule (puts ?url= at the end in the address bar)
Currently i'm working on a webpage for my upcoming twitch bot. While doing this, i encountered a somewhat weird problem, or at least a behaviour i didn't expect and which i investigated the last 24 hours to narrow it down.

I have an .htaccess file in my webpage root folder, which contains

```<code>AddDefaultCharset utf-8

php_flag display_errors on

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</code>```

and its totally working fine, when entering an url into the address bar. But when i click a link on my webpage, it strangely appends ?url= to the address. So if i enter 'https://blockinfo.thatsnasu.dev/docs/' manually, it loads the page and i'm happy. But if i just click on the link on the main page https://blockinfo.thatsnasu.dev (which is just a

Documentation
```

it transforms the url in the address bar to 'https://blockinfo.thatsnasu.dev/docs/?url=docs' and i dont know really why. Like i said, i investigated this, and what i found out so far is that it only happens, if a folder with the same name as the target address exists in the root dir of my websource. In my source all links look like the stated above, so thats not the issue. I tried adding a dummy link without a corresponding folder, clicked it, address looks fine. After adding a folder with the same name, the ?url= appending happens, so my bet is, that something with my rewrite rule seems to be off. Sure, i could fix that by just renaming the folders to something different, so there would be no folder that has the same name as the link target, but i'd rather like to understand why this happens and how i can fix it cleanly. I never encountered this issue with RewriteRules before, since i normally would make seperate vhosts in apache for the different sections of the page (one vhost for the normal webpage, one for the documentation under https://docs.domain/ and one for the api, sitting under https://api.domain/), but since this project is rather small i wanted to pack it all up in one vhost, since everything else seemed overkill to me.

For anyone who has questions about my code: the source is public on my github ( https://github.com/thatsnasu/blockinfo-web )

Oh quick sidenote: on my Ubuntu laptop this strange behaviour does not occur. But i guess thats not related to this problem, since on the Ubuntu Laptop of one of my friends it happens, on the Windows machine of another friend it happens, on my windows tower it happens and on several mobile devices it also happens. So i just accept that my laptop seems to be a special snowflake.

Thanks for reading this far c:

Edit: changed the pseudo links to actual links, so anyone helping me investigate this has the possibility to take a look at the actual page and its behaviour.

Body:
Currently i'm working on a webpage for my upcoming twitch bot. While doing this, i encountered a somewhat weird problem, or at least a behaviour i didn't expect and which i investigated the last 24 hours to narrow it down.

I have an .htaccess file in my webpage root folder, which contains

AddDefaultCharset utf-8

php_flag display_errors on

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

and its totally working fine, when entering an url into the address bar. But when i click a link on my webpage, it strangely appends ?url= to the address. So if i enter 'https://blockinfo.thatsnasu.dev/docs/' manually, it loads the page and i'm happy. But if i just click on the link on the main page https://blockinfo.thatsnasu.dev (which is just a

Documentation

it transforms the url in the address bar to 'https://blockinfo.thatsnasu.dev/docs/?url=docs' and i dont know really why. Like i said, i investigated this, and what i found out so far is that it only happens, if a folder with the same name as the target address exists in the root dir of my websource. In my source all links look like the stated above, so thats not the issue. I tried adding a dummy link without a corresponding folder, clicked it, address looks fine. After adding a folder with the same name, the ?url= appending happens, so my bet is, that something with my rewrite rule seems to be off. Sure, i could fix that by just renaming the folders to something different, so there would be no folder that has the same name as the link target, but i'd rather like to understand why this happens and how i can fix it cleanly. I never encountered this issue with RewriteRules before, since i normally would make seperate vhosts in apache for the different sections of the page (one vhost for the normal webpage, one for the documentation under https://docs.domain/ and one for the api, sitting under https://api.domain/), but since this project is rather small i wanted to pack it all up in one vhost, since everything else seemed overkill to me.

For anyone who has questions about my code: the source is public on my github ( https://github.com/thatsnasu/blockinfo-web )

Oh quick sidenote: on my Ubuntu laptop this strange behaviour does not occur. But i guess thats not related to this problem, since on the Ubuntu Laptop of one of my friends it happens, on the Windows machine of another friend it happens, on my windows tower it happens and on several mobile devices it also happens. So i just accept that my laptop seems to be a special snowflake.

Thanks for reading this far c:

Edit: changed the pseudo links to actual links, so anyone helping me investigate this has the possibility to take a look at the actual page and its behaviour.


问:
How to make QHeaderView item selected when clicked?
Currently it only be highlighted when mouse over.
I want it behaves like windows task manager:

one can select header item by clicking,

and pop-up context menu when right clicking on the item.


问:
How make a certain routers inaccessible without a specific http token using nextjs middleware?
I want to achieve 2 things using my middleware :

1- any page that's not /login or /register to be inaccessible without a token

2- if there's a token  and user tries to go to /login , user will be redirected to /

my middleware function is this :

```<code>import { NextResponse } from "next/server";

export function middleware(request) {
  const token = request.cookies?.get("cookieToken")?.value;
  const url = request.nextUrl.clone();

  if (url.href.endsWith("/register" || url.href.endsWidth("/login"))) {
    return;
  } else if (!url.href.endsWith("/")) {
    if (!token) {
      url.pathname = "/login";
      return NextResponse.redirect(url);
    }
  } else {
    if (!token) {
      url.pathname = "/login";
      return NextResponse.redirect(url);
    }
  }

  if (url.pathname == "/login" && token) {
    url.pathname = "/";
    return NextResponse.redirect(url);
  }
}

export const config = {
  matcher: ["/"],
};
</code>```

to save my token i'm using js-cookie library , I set the token like this :

```<code>  Cookies.set("cookieToken", d?.access_token);
</code>```

they only part that works is number 2 , number 1 doesn't work even if there's no token saved for the user he'll be able to access all page routes

any help on what I can do in this case and on how to write my middleware function to be cleaner not a bunch of if and else ifs ?

Body:
I want to achieve 2 things using my middleware :

1- any page that's not /login or /register to be inaccessible without a token

2- if there's a token  and user tries to go to /login , user will be redirected to /

my middleware function is this :

import { NextResponse } from "next/server";

export function middleware(request) {
  const token = request.cookies?.get("cookieToken")?.value;
  const url = request.nextUrl.clone();

  if (url.href.endsWith("/register" || url.href.endsWidth("/login"))) {
    return;
  } else if (!url.href.endsWith("/")) {
    if (!token) {
      url.pathname = "/login";
      return NextResponse.redirect(url);
    }
  } else {
    if (!token) {
      url.pathname = "/login";
      return NextResponse.redirect(url);
    }
  }

  if (url.pathname == "/login" && token) {
    url.pathname = "/";
    return NextResponse.redirect(url);
  }
}

export const config = {
  matcher: ["/"],
};

to save my token i'm using js-cookie library , I set the token like this :

  Cookies.set("cookieToken", d?.access_token);

they only part that works is number 2 , number 1 doesn't work even if there's no token saved for the user he'll be able to access all page routes

any help on what I can do in this case and on how to write my middleware function to be cleaner not a bunch of if and else ifs ?


问:
FluentValidation.DependencyInjectionExtensions not working
I am developing dotnetcore web api project (There are 4 layers).

The validator does not work when I use the FluentValidation.DependencyInjectionExtensions package.

It works when I use the FluentValidation.AspNetCore package instead.

I couldn't understand if it is a bug with my application or a package error here.

This is project github link.

In Business layer,

```<code><PackageReference Include="FluentValidation" Version="11.4.0" />
</code>```

Validation Model

```<code>namespace Business.Validations.User
{
    public class UserLoginRequestDtoValidation : AbstractValidator<UserLoginRequestDto>
    {
        public UserLoginRequestDtoValidation()
        {
            RuleFor(x => x.Username)
                .NotEmpty()
                .WithMessage("Username cannot be left !")
                .NotNull()
                .WithMessage("Username cannot be left !");
        }
    }
}
</code>```

```<code>When I try with FluentValidation.DependencyInjectionExtensions package. Validator is not working.
</code>```

In Template.API layer,

Adding validators to service in Program.cs

```<code>builder.Services.AddValidatorsFromAssemblyContaining<UserLoginRequestDtoValidation>();
</code>```

Payload

```<code>{
  "username": "",
  "password": "string"
}
</code>```

```<code>When I try with FluentValidation.AspNetCore package. Validator is working.
</code>```

In Template.API layer,

Adding validators to service in Program.cs

```<code>builder.Services.AddControllers()
    .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<UserLoginRequestDtoValidation>());
</code>```

Response model

```<code>{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-c983073976163f3e77542be0aacb9d22-06c414453afd57b5-00",
  "errors": {
    "Username": [
      "Username cannot be left !"
    ]
  }
}
</code>```

Body:
I am developing dotnetcore web api project (There are 4 layers).

The validator does not work when I use the FluentValidation.DependencyInjectionExtensions package.

It works when I use the FluentValidation.AspNetCore package instead.

I couldn't understand if it is a bug with my application or a package error here.

This is project github link.

In Business layer,

<PackageReference Include="FluentValidation" Version="11.4.0" />

Validation Model

namespace Business.Validations.User
{
    public class UserLoginRequestDtoValidation : AbstractValidator<UserLoginRequestDto>
    {
        public UserLoginRequestDtoValidation()
        {
            RuleFor(x => x.Username)
                .NotEmpty()
                .WithMessage("Username cannot be left !")
                .NotNull()
                .WithMessage("Username cannot be left !");
        }
    }
}

When I try with FluentValidation.DependencyInjectionExtensions package. Validator is not working.

In Template.API layer,

Adding validators to service in Program.cs

builder.Services.AddValidatorsFromAssemblyContaining<UserLoginRequestDtoValidation>();

Payload

{
  "username": "",
  "password": "string"
}

When I try with FluentValidation.AspNetCore package. Validator is working.

In Template.API layer,

Adding validators to service in Program.cs

builder.Services.AddControllers()
    .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<UserLoginRequestDtoValidation>());

Response model

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-c983073976163f3e77542be0aacb9d22-06c414453afd57b5-00",
  "errors": {
    "Username": [
      "Username cannot be left !"
    ]
  }
}


问:
Firebase Auth v9 : linking / merging accounts using the signinWithRedirect method
I'm using firebase auth to sign in users using Facebook, Google and Email/Pass methods. For the federated providers (Google and Facebook), I'm using the signInWithRedirect method.
Currently, a user can sign in using one of these methods without issue.

The problem occurs when a user previously authenticated with one provider, comes back later and choose to sign-in using another provider. Then I get the famous AuthError below:

auth/account-exists-with-different-credential

My understanding is that I must link the accounts.

After a few attempts, I've found this answer about the same issue, but it's implemented using Firebase auth v8, not v9 so it works differently (no credential property in the error object for example).

So, I understand that once a user successfully signs in, I must store it as a User object with the associated OAuthCredential in the sessionStorage. What must happens next, I don't get it ...

Here's how the code looks like up to now ...

Login part

export function loginWithGoogle() {
  try {
    let provider = new GoogleAuthProvider();
    provider.addScope("email");
    signInWithRedirect(auth, provider);
  } catch(e){
    // ...
  }
}

export function loginWithFacebook() {
  try {
    let provider = new FacebookAuthProvider();
    provider.addScope("email");
    signInWithRedirect(auth, provider);
  } catch(e){
    // ...
  }
}
```
<h2>Handling Redirection Part</h2>
<pre class="lang-js prettyprint-override"><code>import { credStore } from "$lib/stores/cred.js";

let cred; // cred holds the credStore value
$: if (credStore) {
  credStore.subscribe((value) => {
    cred = value;
  });
}

let unsubAuthObserver;

export const auth = getFirebaseAuth();

function getFirebaseAuth() {
  let auth = getAuth(getFirebaseApp());
  auth.useDeviceLanguage(); // use the default browser language

  // see https://firebase.google.com/docs/reference/js/auth.md#onauthstatechanged
  unsubAuthObserver = onAuthStateChanged(auth, (authUser) =>
    handleRedirect(authUser)
  );
  return auth;
}

async function handleRedirect(authUser) {
  try {
    const rResult = await getRedirectResult(auth); // see https://firebase.google.com/docs/reference/js/auth.usercredential
    if (rResult && rResult?.user) {
      // user signed-in
      const cred = OAuthProvider.credentialFromResult(rResult);
      // save the user and credential in a sessionStorage store
      credStore.set({ cred: cred, user: auth.currentUser });
      // get info from DB for that user
      getUserFromDB(rResult?.user, redir);
    }
  } catch (err) {
    // user tried to sign in using a different method
    if (err.code === "auth/account-exists-with-different-credential") {
      // if something is in the cred store
      if (cred?.cred && cred?.user) {
      // HERE I'M LOST
      // tried to sign in the user with the stored cred from the previous successful attempt
      const result = await signInWithCredential(auth, cred.cred);
                        // ˆ ERROR: credential._getIdTokenResponse is not a function

      // get the credential used with the new Provider
      // const credential = OAuthProvider.credentialFromResult(result);
      // console.log(credential);
      // const linkResult = await linkWithCredential(cred.user, credential);
      // console.log(linkResult);
      // Sign in with the newly linked credential
      // const linkCredential = OAuthProvider.credentialFromResult(linkResult);
      // const signInResult = signInWithCredential(auth, linkCredential);
      // console.log(signInResult);
      // console.log(signInResult.user);
      // TODO: Save the merged data to the new user
    } else console.error(err);
  }
}

[...]

export async function signOutOfFirebase() {
  try {
    unsubAuthObserver();
    await signOut(auth);
  } catch (error) {
    console.error(error);
  }
}
</code>```

Thank you so much

Edit 20/12/2022

Just saw that there's a sveltekit-auth out there. I'll give it a try so see if I can manage user auth without Firebase. Taking a step back, Firebase auth is the only service I use from Firebase, so maybe I can manage these cases when a user authenticate using different providers by myself. I'll comment in a few days here.

Edit 27/12/2022

For those interested here's a simple implementation with Google and Facebook sveltekit-auth. You'll see that there's an account linking option called allowDangerousEmailAccountLinking. It can freak you out but it all depends on the providers you're using. The problem resides in the case when an attacker creates a social account tied to an email that it doesn't own. With account linking, he would be granted the same access as the email victim. That's why account linking is not an option enabled by default. https://next-auth.js.org/configuration/providers/oauth#allowdangerousemailaccountlinking-option. sveltekit-auth is still experimental, this means that I can't use it right now. In other words, if I want to get rid of Firebase, I would need to manually implement FB, GG and login/pass auth by myself ...

Body:
I'm using firebase auth to sign in users using Facebook, Google and Email/Pass methods. For the federated providers (Google and Facebook), I'm using the signInWithRedirect method.
Currently, a user can sign in using one of these methods without issue.

The problem occurs when a user previously authenticated with one provider, comes back later and choose to sign-in using another provider. Then I get the famous AuthError below:

auth/account-exists-with-different-credential

My understanding is that I must link the accounts.

After a few attempts, I've found this answer about the same issue, but it's implemented using Firebase auth v8, not v9 so it works differently (no credential property in the error object for example).

So, I understand that once a user successfully signs in, I must store it as a User object with the associated OAuthCredential in the sessionStorage. What must happens next, I don't get it ...

Here's how the code looks like up to now ...

Login part

export function loginWithGoogle() {
  try {
    let provider = new GoogleAuthProvider();
    provider.addScope("email");
    signInWithRedirect(auth, provider);
  } catch(e){
    // ...
  }
}

export function loginWithFacebook() {
  try {
    let provider = new FacebookAuthProvider();
    provider.addScope("email");
    signInWithRedirect(auth, provider);
  } catch(e){
    // ...
  }
}

Handling Redirection Part

import { credStore } from "$lib/stores/cred.js";

let cred; // cred holds the credStore value
$: if (credStore) {
  credStore.subscribe((value) => {
    cred = value;
  });
}

let unsubAuthObserver;

export const auth = getFirebaseAuth();

function getFirebaseAuth() {
  let auth = getAuth(getFirebaseApp());
  auth.useDeviceLanguage(); // use the default browser language

  // see https://firebase.google.com/docs/reference/js/auth.md#onauthstatechanged
  unsubAuthObserver = onAuthStateChanged(auth, (authUser) =>
    handleRedirect(authUser)
  );
  return auth;
}

async function handleRedirect(authUser) {
  try {
    const rResult = await getRedirectResult(auth); // see https://firebase.google.com/docs/reference/js/auth.usercredential
    if (rResult && rResult?.user) {
      // user signed-in
      const cred = OAuthProvider.credentialFromResult(rResult);
      // save the user and credential in a sessionStorage store
      credStore.set({ cred: cred, user: auth.currentUser });
      // get info from DB for that user
      getUserFromDB(rResult?.user, redir);
    }
  } catch (err) {
    // user tried to sign in using a different method
    if (err.code === "auth/account-exists-with-different-credential") {
      // if something is in the cred store
      if (cred?.cred && cred?.user) {
      // HERE I'M LOST
      // tried to sign in the user with the stored cred from the previous successful attempt
      const result = await signInWithCredential(auth, cred.cred);
                        // ˆ ERROR: credential._getIdTokenResponse is not a function

      // get the credential used with the new Provider
      // const credential = OAuthProvider.credentialFromResult(result);
      // console.log(credential);
      // const linkResult = await linkWithCredential(cred.user, credential);
      // console.log(linkResult);
      // Sign in with the newly linked credential
      // const linkCredential = OAuthProvider.credentialFromResult(linkResult);
      // const signInResult = signInWithCredential(auth, linkCredential);
      // console.log(signInResult);
      // console.log(signInResult.user);
      // TODO: Save the merged data to the new user
    } else console.error(err);
  }
}

[...]

export async function signOutOfFirebase() {
  try {
    unsubAuthObserver();
    await signOut(auth);
  } catch (error) {
    console.error(error);
  }
}

Thank you so much

Edit 20/12/2022

Just saw that there's a sveltekit-auth out there. I'll give it a try so see if I can manage user auth without Firebase. Taking a step back, Firebase auth is the only service I use from Firebase, so maybe I can manage these cases when a user authenticate using different providers by myself. I'll comment in a few days here.

Edit 27/12/2022

For those interested here's a simple implementation with Google and Facebook sveltekit-auth. You'll see that there's an account linking option called allowDangerousEmailAccountLinking. It can freak you out but it all depends on the providers you're using. The problem resides in the case when an attacker creates a social account tied to an email that it doesn't own. With account linking, he would be granted the same access as the email victim. That's why account linking is not an option enabled by default. https://next-auth.js.org/configuration/providers/oauth#allowdangerousemailaccountlinking-option. sveltekit-auth is still experimental, this means that I can't use it right now. In other words, if I want to get rid of Firebase, I would need to manually implement FB, GG and login/pass auth by myself ...


问:
Occasionally, there is a problem with Android getting the screen height, and other mobile phones will occasionally have similar problems
I get the height of the screen in the following way

```<code>DisplayMetrics metric = new DisplayMetrics();
android.view.WindowManager wm = (android.view.WindowManager) mContext.
        getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metric);
mScreenWidth = metric.widthPixels;
mScreenHeight = metric.heightPixels;
</code>```

Normally, the value I got should be 3007, but when I was online, I accidentally re-wired it during the debugging process, and the value I got was 1384. Have you encountered this?
Kill the app and restart the cold start to get the value to return to normal

Body:
I get the height of the screen in the following way

DisplayMetrics metric = new DisplayMetrics();
android.view.WindowManager wm = (android.view.WindowManager) mContext.
        getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metric);
mScreenWidth = metric.widthPixels;
mScreenHeight = metric.heightPixels;

Normally, the value I got should be 3007, but when I was online, I accidentally re-wired it during the debugging process, and the value I got was 1384. Have you encountered this?
Kill the app and restart the cold start to get the value to return to normal


问:
DLToolkit.Forms.FlowListView for Maui
I'm currently migrating a Xamarin.Forms app to .net Maui, the package DLToolkit.Forms has probably not been maintained since 2018 and I can't use it anymore. Does anyone know of a similar tool?</p>

Title: DLToolkit.Forms.FlowListView for Maui


问:
Keras, get the output of final layer to feed a random forest model in R
all! I am trying to train a CNN for image classification in R and I am willing to feed my final layer where image are transformed in vector to ML classification model (i.e. random forest, logistic regression)

This is the code I am using and I was assuming to give the max pooling layer output as input to a new model by creating a custom random forest layer to predict.

I have found many contribution for python language but none for R.

Can someone help/support on the best way to do it?

Thank you very much!

```<code>model2 <- keras_model_sequential() %>%
  layer_conv_2d(filters = 32, kernel_size = c(3, 3), activation = "relu",
                input_shape = c(150, 150, 3)) %>%
  layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  layer_conv_2d(filters = 64, kernel_size = c(3, 3), activation = "relu") %>% layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  layer_conv_2d(filters = 128, kernel_size = c(3, 3), activation = "relu") %>% layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  layer_conv_2d(filters = 128, kernel_size = c(3, 3), activation = "relu") %>% layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  #immagine trasformata in vettore da dare in pasto ad altro modello eg random forest
  layer_flatten() %>%
  layer_dense(units = 512, activation = "relu") %>%
  layer_dense(units = 1, activation = "sigmoid")

</code>```
```<code>Model: "sequential_3"
_____________________________________________________________________________________________
 Layer (type)                            Output Shape                          Param #
=============================================================================================
 conv2d_11 (Conv2D)                      (None, 148, 148, 32)                  896
 max_pooling2d_11 (MaxPooling2D)         (None, 74, 74, 32)                    0
 conv2d_10 (Conv2D)                      (None, 72, 72, 64)                    18496
 max_pooling2d_10 (MaxPooling2D)         (None, 36, 36, 64)                    0
 conv2d_9 (Conv2D)                       (None, 34, 34, 128)                   73856
 max_pooling2d_9 (MaxPooling2D)          (None, 17, 17, 128)                   0
 conv2d_8 (Conv2D)                       (None, 15, 15, 128)                   147584
 max_pooling2d_8 (MaxPooling2D)          (None, 7, 7, 128)                     0
 flatten_2 (Flatten)                     (None, 6272)                          0
 dense_7 (Dense)                         (None, 512)                           3211776
 dense_6 (Dense)                         (None, 1)                             513
=============================================================================================
Total params: 3,453,121
Trainable params: 3,453,121
Non-trainable params: 0
__________________________
</code>```

I have also been trying to translate this from python in R language but with no success

feature_vectors_model = Model(model.input, model.get_layer('dense_7').output)
dtc_features = feature_vectors_model.predict(your_X_data)  # fit your decision tree on this data

Body:
all! I am trying to train a CNN for image classification in R and I am willing to feed my final layer where image are transformed in vector to ML classification model (i.e. random forest, logistic regression)

This is the code I am using and I was assuming to give the max pooling layer output as input to a new model by creating a custom random forest layer to predict.

I have found many contribution for python language but none for R.

Can someone help/support on the best way to do it?

Thank you very much!

model2 <- keras_model_sequential() %>%
  layer_conv_2d(filters = 32, kernel_size = c(3, 3), activation = "relu",
                input_shape = c(150, 150, 3)) %>%
  layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  layer_conv_2d(filters = 64, kernel_size = c(3, 3), activation = "relu") %>% layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  layer_conv_2d(filters = 128, kernel_size = c(3, 3), activation = "relu") %>% layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  layer_conv_2d(filters = 128, kernel_size = c(3, 3), activation = "relu") %>% layer_max_pooling_2d(pool_size = c(2, 2)) %>%
  #immagine trasformata in vettore da dare in pasto ad altro modello eg random forest
  layer_flatten() %>%
  layer_dense(units = 512, activation = "relu") %>%
  layer_dense(units = 1, activation = "sigmoid")

Model: "sequential_3"
_____________________________________________________________________________________________
 Layer (type)                            Output Shape                          Param #
=============================================================================================
 conv2d_11 (Conv2D)                      (None, 148, 148, 32)                  896
 max_pooling2d_11 (MaxPooling2D)         (None, 74, 74, 32)                    0
 conv2d_10 (Conv2D)                      (None, 72, 72, 64)                    18496
 max_pooling2d_10 (MaxPooling2D)         (None, 36, 36, 64)                    0
 conv2d_9 (Conv2D)                       (None, 34, 34, 128)                   73856
 max_pooling2d_9 (MaxPooling2D)          (None, 17, 17, 128)                   0
 conv2d_8 (Conv2D)                       (None, 15, 15, 128)                   147584
 max_pooling2d_8 (MaxPooling2D)          (None, 7, 7, 128)                     0
 flatten_2 (Flatten)                     (None, 6272)                          0
 dense_7 (Dense)                         (None, 512)                           3211776
 dense_6 (Dense)                         (None, 1)                             513
=============================================================================================
Total params: 3,453,121
Trainable params: 3,453,121
Non-trainable params: 0
__________________________

I have also been trying to translate this from python in R language but with no success

feature_vectors_model = Model(model.input, model.get_layer('dense_7').output)
dtc_features = feature_vectors_model.predict(your_X_data)  # fit your decision tree on this data