问:
Calculate Median Sales for each Customer in Array of Customers (Neophyte)
I have an array of customer objects generated from a csv file:

Date, Name, Sales

03/01, Alpha, 110

03/23, Alpha, 25

01/02, Beta, 135

...

and require an efficient way to create a new array of unique customers with median sales and export them back to csv. There could be as many as 500,000 records and 100,000 unique customers!

答:
In cases like this I would use:

```<code>Dictionary<string, List<int>> dict;
</code>```

The keys are the customer names (assuming they are unique, otherwise assign a unique ID of some sort?)
The values are lists of sales for each customer. After you have filled this array you may procceed in either sorting and getting the middle element (as mentioned above) or summing and dividing by the number of elements to get the median. (this is wrong)

Sorting (using a method which compares) takes O(nlog n) time where n is the length of the list to be sorted.

There are selection algorithms which can return the kth smallest value in O(n), check wikipedia link below

Body:
In cases like this I would use:

Dictionary<string, List<int>> dict;

The keys are the customer names (assuming they are unique, otherwise assign a unique ID of some sort?)
The values are lists of sales for each customer. After you have filled this array you may procceed in either sorting and getting the middle element (as mentioned above) or summing and dividing by the number of elements to get the median. (this is wrong)

Sorting (using a method which compares) takes O(nlog n) time where n is the length of the list to be sorted.

There are selection algorithms which can return the kth smallest value in O(n), check wikipedia link below


来源: stackexchange

问:
How can I find which operating system my Ruby program is running on?
I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?</p>

答:
Using the os gem, when loading different binaries for IMGKit

# frozen_string_literal: true
IMGKit.configure do |config|
  if OS.linux? && OS.host_cpu == "x86_64"
    config.wkhtmltoimage =
      Rails.root.join("bin", "wkhtmltoimage-linux-amd64").to_s
  elsif OS.mac? && OS.host_cpu == "x86_64"
    config.wkhtmltoimage =
      Rails.root.join("bin", "wkhtmltoimage-macos-amd64").to_s
  else
    puts OS.report
    abort "You need to add a binary for wkhtmltoimage for your OS and CPU"
  end
end
```

OwnerDisplayName: Huluk

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to extract layer shape and type from ONNX / PyTorch?
I would like to 'translate' a PyTorch model to another framework (non-tf/keras).

I'm trying to take a pytorch model, and automate the translation to the other framework, which contains similar types of layers (i.e. conv2d, dense,...).

Is there a way from pytorch directly, or through onnx to retrieve a models layers, their types, shapes and connections ? (Weights are not important so far)

答:
From discussion in comments on your question:

each node in onnx has a list of named inputs and a list of named outputs.

For the input list accessed with node.input you have for each input index either the graph input_name that feeds that input or the name of a previous output that feeds that input. There are also initializers which are onnx parameters.

```<code># model is an onnx model
graph = model.graph
# graph inputs
for input_name in graph.input:
    print(input_name)
# graph parameters
for init in graph.init:
    print(init.name)
# graph outputs
for output_name in graph.output:
    print(output_name)
# iterate over nodes
for node in graph.node:
    # node inputs
    for idx, node_input_name in enumerate(node.input):
        print(idx, node_input_name)
    # node outputs
    for idx, node_output_name in enumerate(node.output):
        print(idx, node_output_name)
</code>```

Shape inference is talked about here and for python here

The gist for python is found here

Reproducing the gist from 3:

```<code>from onnx import shape_inference
inferred_model = shape_inference.infer_shapes(original_model)
</code>```

and find the shape info in inferred_model.graph.value_info.

You can also use netron or from GitHub to have a visual representation of that information.

Body:
From discussion in comments on your question:

each node in onnx has a list of named inputs and a list of named outputs.

For the input list accessed with node.input you have for each input index either the graph input_name that feeds that input or the name of a previous output that feeds that input. There are also initializers which are onnx parameters.

# model is an onnx model
graph = model.graph
# graph inputs
for input_name in graph.input:
    print(input_name)
# graph parameters
for init in graph.init:
    print(init.name)
# graph outputs
for output_name in graph.output:
    print(output_name)
# iterate over nodes
for node in graph.node:
    # node inputs
    for idx, node_input_name in enumerate(node.input):
        print(idx, node_input_name)
    # node outputs
    for idx, node_output_name in enumerate(node.output):
        print(idx, node_output_name)

Shape inference is talked about here and for python here

The gist for python is found here

Reproducing the gist from 3:

from onnx import shape_inference
inferred_model = shape_inference.infer_shapes(original_model)

and find the shape info in inferred_model.graph.value_info.

You can also use netron or from GitHub to have a visual representation of that information.


问:
c++ passing a pointer to a template function as template
I have this iter function that takes a pointer to value_type, a size_type, and a function pointer fun_type that is supposed to take a value_type& as parameter:

template <
    class value_type,
    class size_type,
    class fun_type
> void  iter(value_type *arr, size_type size, fun_type function)
{ while (size--) function(arr[size]); }
```
<p>It works fine until we have a function that has a template, let's say for example we want to use this function:</p>
<pre class="lang-cpp prettyprint-override"><code>template <
   class T
> void print(const T &value) { std::cout << value << std::endl; }
</code>```

Then we get this compilation error:

```<code>main.cpp:35:1: error: no matching function for call to 'iter'
iter( tab, 5, print );
^~~~
./iter.hpp:17:8: note: candidate template ignored: couldn't infer template argument 'fun_type'
> void  iter(value_type *arr, size_type size, fun_type function)
        ^
main.cpp:36:1: error: no matching function for call to 'iter'
iter( tab2, 5, print );
^~~~
./iter.hpp:17:8: note: candidate template ignored: couldn't infer template argument 'fun_type'
> void  iter(value_type *arr, size_type size, fun_type function)
</code>```

How could I make fun_type work with every function no matter the template and the return type of the function?

答:
Your iter function template requires a function for its third template parameter; but print (on its own) is not a function – it's a function template, and the compiler simply cannot deduce what template parameter to use in order to actually create a function … so you need to tell it! Just add the type of the tab array/pointer as that template parameter:

int main()
{
    int tab[] = { 5,4,3,2,1 };
    iter(tab, 5, print<int>);
    return 0;
}
```

Body:
I have this iter function that takes a pointer to value_type, a size_type, and a function pointer fun_type that is supposed to take a value_type& as parameter:

template <
    class value_type,
    class size_type,
    class fun_type
> void  iter(value_type *arr, size_type size, fun_type function)
{ while (size--) function(arr[size]); }

It works fine until we have a function that has a template, let's say for example we want to use this function:

template <
   class T
> void print(const T &value) { std::cout << value << std::endl; }

Then we get this compilation error:

main.cpp:35:1: error: no matching function for call to 'iter'
iter( tab, 5, print );
^~~~
./iter.hpp:17:8: note: candidate template ignored: couldn't infer template argument 'fun_type'
> void  iter(value_type *arr, size_type size, fun_type function)
        ^
main.cpp:36:1: error: no matching function for call to 'iter'
iter( tab2, 5, print );
^~~~
./iter.hpp:17:8: note: candidate template ignored: couldn't infer template argument 'fun_type'
> void  iter(value_type *arr, size_type size, fun_type function)

How could I make fun_type work with every function no matter the template and the return type of the function?


问:
AWS beanstalk fails installing pip requisites when downloading tensorflow==2.4.0
I'm trying to deploy a flask app that predicts whether a lung x-ray picture is COVID-19 positive using a Tensorflow CNN. It is running on python 3.7

This is my requirements.txt

```<code>tensorflow==2.4.0
Flask==1.1.2
Keras==2.4.3
numpy==1.19.5
Pillow==8.3.1
</code>```

After deployment it, the environment's health status is labelled severe with a '502 Bad gateway' error.

These are the errors in the eb-engine.log

```<code>2021/08/23 10:47:40.676374 [INFO] Installing dependencies with requirements.txt by using Pip
2021/08/23 10:47:40.676387 [INFO] Running command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt
2021/08/23 10:47:48.296114 [INFO] Collecting tensorflow==2.4.0
  Downloading tensorflow-2.4.0-cp38-cp38-manylinux2010_x86_64.whl (394.8 MB)

2021/08/23 10:47:48.300932 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 2. Stderr:ERROR: Exception:
Traceback (most recent call last):
  File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 180, in _main
    status = self.run(options, args)
</code>```

File "... repeats itself until here:

```<code> File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 896, in _pack
    return self._buffer.write(obj)
MemoryError

2021/08/23 10:47:48.300957 [INFO] Executing cleanup logic
2021/08/23 10:47:48.309000 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed to install application dependencies. The deployment failed.","timestamp":1629715668,"severity":"ERROR"},{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1629715668,"severity":"ERROR"}]}]}

2021/08/23 10:47:48.312983 [INFO] Platform Engine finished execution on command: app-deploy

2021/08/23 12:34:34.689865 [INFO] Starting...
2021/08/23 12:34:34.689926 [INFO] Starting EBPlatform-PlatformEngine
2021/08/23 12:34:34.689965 [INFO] reading event message file
2021/08/23 12:34:34.690627 [INFO] no eb envtier info file found, skip loading env tier info.
2021/08/23 12:34:34.690716 [INFO] Engine received EB command cfn-hup-exec
</code>```

why is AWS-Beanstalk failing to install Tensorflow?

答:
I changed the environment EC2 capacity from t2.small to c5.xlarge and the problem was solved.
Your application needs more memory space.</p>

Body:
I'm trying to deploy a flask app that predicts whether a lung x-ray picture is COVID-19 positive using a Tensorflow CNN. It is running on python 3.7

This is my requirements.txt

tensorflow==2.4.0
Flask==1.1.2
Keras==2.4.3
numpy==1.19.5
Pillow==8.3.1

After deployment it, the environment's health status is labelled severe with a '502 Bad gateway' error.

These are the errors in the eb-engine.log

2021/08/23 10:47:40.676374 [INFO] Installing dependencies with requirements.txt by using Pip
2021/08/23 10:47:40.676387 [INFO] Running command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt
2021/08/23 10:47:48.296114 [INFO] Collecting tensorflow==2.4.0
  Downloading tensorflow-2.4.0-cp38-cp38-manylinux2010_x86_64.whl (394.8 MB)

2021/08/23 10:47:48.300932 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 2. Stderr:ERROR: Exception:
Traceback (most recent call last):
  File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 180, in _main
    status = self.run(options, args)

File "... repeats itself until here:

 File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 896, in _pack
    return self._buffer.write(obj)
MemoryError

2021/08/23 10:47:48.300957 [INFO] Executing cleanup logic
2021/08/23 10:47:48.309000 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed to install application dependencies. The deployment failed.","timestamp":1629715668,"severity":"ERROR"},{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1629715668,"severity":"ERROR"}]}]}

2021/08/23 10:47:48.312983 [INFO] Platform Engine finished execution on command: app-deploy

2021/08/23 12:34:34.689865 [INFO] Starting...
2021/08/23 12:34:34.689926 [INFO] Starting EBPlatform-PlatformEngine
2021/08/23 12:34:34.689965 [INFO] reading event message file
2021/08/23 12:34:34.690627 [INFO] no eb envtier info file found, skip loading env tier info.
2021/08/23 12:34:34.690716 [INFO] Engine received EB command cfn-hup-exec

why is AWS-Beanstalk failing to install Tensorflow?


问:
Why will there be no native properties in Java 7?
Is there any rational reason, why native properties will not be part of Java 7?</p>

答:
There are some high-level reasons related to schedule and resources of course.  Implementation of properties and understanding all of the ramifications and intersections with other language features is a large task similar to the size of various Java 5 language changes.

But I think the real reason Sun is not pushing properties is the same as closures:

1) There is no consensus on what the implementation should look like.  Or rather, there are many competing alternatives and people who are passionate about properties disagree about crucial parts of the implementation.

2) Perhaps more importantly, there is a significant lack of consensus about whether the feature is wanted at all.  While many people want properties, there are also many people that don't think it's necessary or useful (in particular, I think server-side people see properties as far less crucial to their daily life than swing programmers).

Properties history here:

http://tech.puredanger.com/java7#property

OwnerDisplayName: bwalliser

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Alex Miller

LastEditorDisplayName: Alex Miller


问:
computed property names and this - JS
Can i use this in computed property name ?
something like this:

```<code>class User {
  constructor(username) {
    this._username = username;
  }

  [this._username + "Print"]() {
    console.log(this._username);
  }
}

const u = new User("MORA");
u.moraPrint(); // ?
</code>```

And i know that it is useless in this case.

答:
If you define your function in your constructor, it can be done:

class User {
  constructor(username) {
    this._username = username;
    this[username + "Print"] = function () {
    console.log(this._username);

    }
  }
}

const u = new User("mora");
u.moraPrint(); // ?```
</div>
</div>
</p>
<p>A class function can be created with computed property name, but as mentioned in comment <code>this</code> would not have been initialized by then, because there is no object instance.</p>
<p>You can check that by running this (pun intended) code :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>item = 'hey'
class User {
  constructor(username) {
    this._username = username;
  }

  [this.item + "hello"]() {
    console.log('hello ' + this._username);
  }
}

const u = new User("MORA");
u.heyhello(); // ?</code>```

The value of this is different because at the time code is run, the context is different.

Title: computed property names and this - JS

Body:
Can i use this in computed property name ?
something like this:

class User {
  constructor(username) {
    this._username = username;
  }

  [this._username + "Print"]() {
    console.log(this._username);
  }
}

const u = new User("MORA");
u.moraPrint(); // ?

And i know that it is useless in this case.

Body:
If you define your function in your constructor, it can be done:

class User {
  constructor(username) {
    this._username = username;
    this[username + "Print"] = function () {
    console.log(this._username);

    }
  }
}

const u = new User("mora");
u.moraPrint(); // ?

A class function can be created with computed property name, but as mentioned in comment this would not have been initialized by then, because there is no object instance.

You can check that by running this (pun intended) code :

item = 'hey'
class User {
  constructor(username) {
    this._username = username;
  }

  [this.item + "hello"]() {
    console.log('hello ' + this._username);
  }
}

const u = new User("MORA");
u.heyhello(); // ?

The value of this is different because at the time code is run, the context is different.


问:
Get current desktop wallpaper in ctypes
I try to get path to current wallpaper in Python using ctypes module. But as a result program returns value 1.</p>
```<code>import ctypes

SPI_GETDESKWALLPAPER = 0x0073

path = ctypes.create_unicode_buffer(260)
a = ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, 100, path, 0)
print(a)
</code>```

答:
The value is returned in path.  a in your example is the return code (1=success).  It's also a good habit to define the argument types and return type so ctypes doesn't have to guess when converting parameters from Python to C and vice versa.

import ctypes as ct
from ctypes import wintypes as w

SPI_GETDESKWALLPAPER = 0x0073

dll = ct.WinDLL('user32')
dll.SystemParametersInfoW.argtypes = w.UINT,w.UINT,w.LPVOID,w.UINT
dll.SystemParametersInfoW.restype = w.BOOL

path = ct.create_unicode_buffer(260)
result = dll.SystemParametersInfoW(SPI_GETDESKWALLPAPER, ct.sizeof(path), path, 0)
print(result, path.value)
```

Title: Get current desktop wallpaper in ctypes

Body:
I try to get path to current wallpaper in Python using ctypes module. But as a result program returns value 1.

import ctypes

SPI_GETDESKWALLPAPER = 0x0073

path = ctypes.create_unicode_buffer(260)
a = ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, 100, path, 0)
print(a)


问:
Get all objects in an array for same property value from an array of data
data Array

```<code>let data = [
{name: "ABC", email: "abc@gamil.com"},
{name: "xyz", email: "xyz@gamil.com"},
{name: "different name", email: "abc@gamil.com"},
{name: "xyz", email: "cde@gamil.com"}
]
</code>```

I need result where all objects from an array having same email gets combined into one array as an value and key should be the email.
for example the answer of above email should be:

```<code>[{
"abc@gmail.com": [
{name: "ABC", email: "abc@gamil.com"},
{name: "different name", email: "abc@gamil.com"}]
},
{"xyz@gamil.com": [
{name: "xyz", email: "xyz@gamil.com"}]
},
{"cde@gamil.com": [
{name: "xyz", email: "cde@gamil.com"}]
}
]
</code>```

Objective is to get all the duplicate data on the base of email from the available data.

答:
const data = [
  { name: 'ABC', email: 'abc@gamil.com' },
  { name: 'xyz', email: 'xyz@gamil.com' },
  { name: 'different name', email: 'abc@gamil.com' },
  { name: 'xyz', email: 'cde@gamil.com' },
];
const result = data.reduce((acc, curr) => {
  const key = curr.email;
  if (acc[key]) {
    acc[key].push(curr);
  } else {
    acc[key] = [curr];
  }
  return acc;
}
  , {});
console.log(result);```

Body:
data Array

let data = [
{name: "ABC", email: "abc@gamil.com"},
{name: "xyz", email: "xyz@gamil.com"},
{name: "different name", email: "abc@gamil.com"},
{name: "xyz", email: "cde@gamil.com"}
]

I need result where all objects from an array having same email gets combined into one array as an value and key should be the email.
for example the answer of above email should be:

[{
"abc@gmail.com": [
{name: "ABC", email: "abc@gamil.com"},
{name: "different name", email: "abc@gamil.com"}]
},
{"xyz@gamil.com": [
{name: "xyz", email: "xyz@gamil.com"}]
},
{"cde@gamil.com": [
{name: "xyz", email: "cde@gamil.com"}]
}
]

Objective is to get all the duplicate data on the base of email from the available data.


问:
NestJS/Mongoose: serialization does not exclude properties in plain output
I've started to play with NestJS, migrating from my old express/mongoose project and immediately crashed into a fence, just following MongoDB/serializations chapters from NestJS docs. I've prepared following schema

```<code>/////// schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Exclude, Expose } from 'class-transformer';

export type UserDocument = User & mongoose.Document;

@Schema()
export class User {
    @Prop()
    @Exclude()
    _id: String

    @Expose()
    get id(): String { return this._id ? `${this._id}` : undefined }

    @Prop()
    name: string

    @Prop({ unique: true })
    login: string

    @Exclude()
    @Prop()
    password: string
}

export const UserSchema = SchemaFactory.createForClass(User);
</code>```

registered it in app.module

```<code>MongooseModule.forRoot('mongodb://localhost/old_project'),
MongooseModule.forFeature([ { name: User.name, schema: UserSchema } ]),
</code>```

and tried following calls, expecting no password property revealed in results

```<code>/////// controller
  @UseInterceptors(ClassSerializerInterceptor)
  @Get('default')
  async default(): Promise<User> {
    let u = new User();
    u.name = 'Kos';
    u.password = "secret";
    u.login = 'k@o.s'

    return u;
  }

  // returns
  // {"name":"Kos","login":"k@o.s"}

  @Get('first_raw')
  async firstRaw(): Promise<User> {
    return this.userModel.findOne()
  }

  @Get('first_lean')
  async firstLean(): Promise<User> {
    return this.userModel.findOne().lean()
  }

  //both return
  // {"_id":"5f8731a36fc003421db08921","name":"Kos","login":"kos","password":"secret","__v":0}

  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first_raw_stripped')
  async firstRawStripped(): Promise<User> {
    return this.userModel.findOne()
  }

  //returns
  // {"$__":{"strictMode":true,"selected":{},"getters":{},"_id":"5f8731a36fc003421db08921","wasPopulated":false,"activePaths":{"paths":{"_id":"init","name":"init","login":"init","password":"init","__v":"init"},"states":{"ignore":{},"default":{},"init":{"_id":true,"name":true,"login":true,"password":true,"__v":true},"modify":{},"require":{}},"stateNames":["require","modify","init","default","ignore"]},"pathsToScopes":{},"cachedRequired":{},"$setCalled":[],"emitter":{"_events":{},"_eventsCount":0,"_maxListeners":0},"$options":{"skipId":true,"isNew":false,"willInit":true,"defaults":true}},"isNew":false,"$locals":{},"$op":null,"_doc":{"_id":"5f8731a36fc003421db08921","name":"Kos","login":"kos","password":"secret","__v":0},"$init":true}

  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first_lean_stripped')
  async firstLeanStripped(): Promise<User> {
    return this.userModel.findOne().lean()
  }

  //returns
  // {"_id":"5f8731a36fc003421db08921","name":"Kos","login":"kos","password":"secret","__v":0}
</code>```

Finally I've found that only manual instantiation of User class does somehow what it should do, so I've added constructor to User class

```<code>constructor(partial?: Partial<User>) {
    if (partial)
        Object.assign(this, partial);
}
</code>```

and then it finally returned what was expected - no password prop in result

```<code>  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first')
  async first(): Promise<User> {
    return new User(await this.userModel.findOne().lean());
  }

  //finally returns what's expected
  // {"name":"Kos","login":"kos","__v":0,"id":"5f8731a36fc003421db08921"}
</code>```

Am I missing something? Somehow it seems a bit overwhelming...

UPDATE: it is either question about NestJS mongoose and serialization coupling - why this

```<code>  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first')
  async first(): Promise<User> {
    return await this.userModel.findOne().lean();
  }
</code>```

doesn't work and this

```<code>  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first')
  async first(): Promise<User> {
    return new User(await this.userModel.findOne().lean());
  }
</code>```

works (which also means for each result enumerable map with entity creations required)

答:
As explained by @Ali Sherafat, unfortunately solution didn't worked for me.

The Mongoose library that we use for connecting to MongoDB and
fetching entities does not return instances of our User class.
Therefore, the ClassSerializerInterceptor won’t work out of the box.

Definitely we would be requiring interceptor for mongoose serialization. So, I came up with one more similar solution with modifications.

Create interceptor for mongoose serialization as:

```<code>import {
    CallHandler,
    ExecutionContext,
    NestInterceptor,
    UseInterceptors,
} from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { map, Observable } from 'rxjs';

interface ClassConstructor {
    new ( ...args: any[ ] ): { };
}

export function MongooseClassSerializerInterceptor( dto: any ) {
    return UseInterceptors( new SerializeInterceptor( dto ) );
}

export class SerializeInterceptor implements NestInterceptor {
    constructor( private dto: any ) { }
    intercept( context: ExecutionContext, handler: CallHandler ): Observable< any > {

        return handler.handle( ).pipe(
            map( ( data: any ) => {
                return plainToClass( this.dto, data, {
                    excludeExtraneousValues: true
                } )
            } )
        )
    }
}
</code>```

Create user dto as, this way you can use it for different role. So, for normal user we can expose required things:

```<code>import { Expose } from "class-transformer";

    export class UserDto {

        @Expose( )
        id: number;

        @Expose( )
        name: string;

        @Expose( )
        login: string;

    }
</code>```

Now in your controller use @MongooseClassSerializerInterceptor( UserDto )

Using exclude in schema is not very flexible when want to return response based on some role, e.g in required case admin may have access to more fields than normal user or vice-versa. In that case this is better approach.

Body:
I've started to play with NestJS, migrating from my old express/mongoose project and immediately crashed into a fence, just following MongoDB/serializations chapters from NestJS docs. I've prepared following schema

/////// schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Exclude, Expose } from 'class-transformer';

export type UserDocument = User & mongoose.Document;

@Schema()
export class User {
    @Prop()
    @Exclude()
    _id: String

    @Expose()
    get id(): String { return this._id ? `${this._id}` : undefined }

    @Prop()
    name: string

    @Prop({ unique: true })
    login: string

    @Exclude()
    @Prop()
    password: string
}

export const UserSchema = SchemaFactory.createForClass(User);

registered it in app.module

MongooseModule.forRoot('mongodb://localhost/old_project'),
MongooseModule.forFeature([ { name: User.name, schema: UserSchema } ]),

and tried following calls, expecting no password property revealed in results

/////// controller
  @UseInterceptors(ClassSerializerInterceptor)
  @Get('default')
  async default(): Promise<User> {
    let u = new User();
    u.name = 'Kos';
    u.password = "secret";
    u.login = 'k@o.s'

    return u;
  }

  // returns
  // {"name":"Kos","login":"k@o.s"}

  @Get('first_raw')
  async firstRaw(): Promise<User> {
    return this.userModel.findOne()
  }

  @Get('first_lean')
  async firstLean(): Promise<User> {
    return this.userModel.findOne().lean()
  }

  //both return
  // {"_id":"5f8731a36fc003421db08921","name":"Kos","login":"kos","password":"secret","__v":0}

  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first_raw_stripped')
  async firstRawStripped(): Promise<User> {
    return this.userModel.findOne()
  }

  //returns
  // {"$__":{"strictMode":true,"selected":{},"getters":{},"_id":"5f8731a36fc003421db08921","wasPopulated":false,"activePaths":{"paths":{"_id":"init","name":"init","login":"init","password":"init","__v":"init"},"states":{"ignore":{},"default":{},"init":{"_id":true,"name":true,"login":true,"password":true,"__v":true},"modify":{},"require":{}},"stateNames":["require","modify","init","default","ignore"]},"pathsToScopes":{},"cachedRequired":{},"$setCalled":[],"emitter":{"_events":{},"_eventsCount":0,"_maxListeners":0},"$options":{"skipId":true,"isNew":false,"willInit":true,"defaults":true}},"isNew":false,"$locals":{},"$op":null,"_doc":{"_id":"5f8731a36fc003421db08921","name":"Kos","login":"kos","password":"secret","__v":0},"$init":true}

  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first_lean_stripped')
  async firstLeanStripped(): Promise<User> {
    return this.userModel.findOne().lean()
  }

  //returns
  // {"_id":"5f8731a36fc003421db08921","name":"Kos","login":"kos","password":"secret","__v":0}

Finally I've found that only manual instantiation of User class does somehow what it should do, so I've added constructor to User class

constructor(partial?: Partial<User>) {
    if (partial)
        Object.assign(this, partial);
}

and then it finally returned what was expected - no password prop in result

  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first')
  async first(): Promise<User> {
    return new User(await this.userModel.findOne().lean());
  }

  //finally returns what's expected
  // {"name":"Kos","login":"kos","__v":0,"id":"5f8731a36fc003421db08921"}

Am I missing something? Somehow it seems a bit overwhelming...

UPDATE: it is either question about NestJS mongoose and serialization coupling - why this

  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first')
  async first(): Promise<User> {
    return await this.userModel.findOne().lean();
  }

doesn't work and this

  @UseInterceptors(ClassSerializerInterceptor)
  @Get('first')
  async first(): Promise<User> {
    return new User(await this.userModel.findOne().lean());
  }

works (which also means for each result enumerable map with entity creations required)

Body:
As explained by @Ali Sherafat, unfortunately solution didn't worked for me.

The Mongoose library that we use for connecting to MongoDB and
fetching entities does not return instances of our User class.
Therefore, the ClassSerializerInterceptor won’t work out of the box.

Definitely we would be requiring interceptor for mongoose serialization. So, I came up with one more similar solution with modifications.

Create interceptor for mongoose serialization as:

import {
    CallHandler,
    ExecutionContext,
    NestInterceptor,
    UseInterceptors,
} from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { map, Observable } from 'rxjs';

interface ClassConstructor {
    new ( ...args: any[ ] ): { };
}

export function MongooseClassSerializerInterceptor( dto: any ) {
    return UseInterceptors( new SerializeInterceptor( dto ) );
}

export class SerializeInterceptor implements NestInterceptor {
    constructor( private dto: any ) { }
    intercept( context: ExecutionContext, handler: CallHandler ): Observable< any > {

        return handler.handle( ).pipe(
            map( ( data: any ) => {
                return plainToClass( this.dto, data, {
                    excludeExtraneousValues: true
                } )
            } )
        )
    }
}

Create user dto as, this way you can use it for different role. So, for normal user we can expose required things:

import { Expose } from "class-transformer";

    export class UserDto {

        @Expose( )
        id: number;

        @Expose( )
        name: string;

        @Expose( )
        login: string;

    }

Now in your controller use @MongooseClassSerializerInterceptor( UserDto )

Using exclude in schema is not very flexible when want to return response based on some role, e.g in required case admin may have access to more fields than normal user or vice-versa. In that case this is better approach.


问:
Why am I having trouble filling an external screen on iPad (but not in simulator)?
I am able to detect when a screen is detected, associate it with an appropriate windowScene and add a view to it. Slightly hacky but approximately working (code for disconnection not included here), thanks to this SO question:

class ExternalViewController: UIViewController {
  override func viewDidLoad() {
    view.backgroundColor = .cyan
    print("external frame \(view.frame.width)x\(view.frame.height)")
  }
}
class ViewController: UIViewController {
  var additionalWindows: [UIWindow] = []
  override func viewDidLoad() {
    //nb, Apple documentation seems out of date.
    //https://stackoverflow.com/questions/61191134/setter-for-screen-was-deprecated-in-ios-13-0
    NotificationCenter.default.addObserver(forName: UIScreen.didConnectNotification, object: nil, queue: nil) { [weak self] notification in
      guard let self = self else {return}

      guard let newScreen = notification.object as? UIScreen else {return}
      // Give the system time to update the connected scenes
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
        // Find matching UIWindowScene
        let matchingWindowScene = UIApplication.shared.connectedScenes.first {
        guard let windowScene = $0 as? UIWindowScene else { return false }
        return windowScene.screen == newScreen
      } as? UIWindowScene

        guard let connectedWindowScene = matchingWindowScene else {
          NSLog("--- Connected scene was not found ---")
          return
          //fatalError("Connected scene was not found") // You might want to retry here after some time
        }
        let screenDimensions = newScreen.bounds

        let newWindow = UIWindow(frame: screenDimensions)
        NSLog("newWindow \(screenDimensions.width)x\(screenDimensions.height)")
        newWindow.windowScene = connectedWindowScene

        let vc = ExternalViewController()
        vc.mainVC = self

        newWindow.rootViewController = vc
        newWindow.isHidden = false
        self.additionalWindows.append(newWindow)
      }
    }
  }
}
```

When I do this in the iOS simulator, I see my graphics fill the screen as intended, but when running on my actual device, it appears with a substantial black border around all sides.

Note that this is not the usual border seen with the default display mirroring behaviour - the 16:9 aspect ratio is preserved, and I do see different graphics as expected, (flat cyan color in my example code, normally I'm doing some Metal rendering that has some slight anomalies that are out of scope here, although perhaps might lead to some different clues on this if I dig into it deeper).

The print messages report the expected 1920x1080 dimensions. I don't know UIKit very well, and haven't been doing much active Apple development (I'm dusting off a couple of old side projects here in the hopes of being able to use them to project visuals at a gig in the near future), so I don't know if there's something else to do with sizing constraints etc that I might be missing, but even so it's hard to see why it would behave differently in the simulator.

Other apps I have installed from the app store do indeed show fullscreen graphics on the external display - Netflix shows fullscreen video as you would expect, Concepts shows a different representation of the document than the one you see on the device.

答:
So, in this instance the issue is to do with Overscan Compensation. Thanks to Jerrot on Discord for pointing me in the right direction.

In the context of my app, it is sufficient to add newScreen.overscanCompensation = .none in the connection notification delegate (actually, in the part that is delayed a few ms after that - it doesn't work if applied directly in the connection notification). In the question linked above, there is further discussion of other aspects that may be important in a different context.

This is my ViewController modified to achieve the desired result:

class ViewController: UIViewController {
  var additionalWindows: [UIWindow] = []
  override func viewDidLoad() {
    //nb, Apple documentation seems out of date.
    //https://stackoverflow.com/questions/61191134/setter-for-screen-was-deprecated-in-ios-13-0
    NotificationCenter.default.addObserver(forName: UIScreen.didConnectNotification, object: nil, queue: nil) { [weak self] notification in
      guard let self = self else {return}

      guard let newScreen = notification.object as? UIScreen else {return}
      // Give the system time to update the connected scenes
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
        // Find matching UIWindowScene
        let matchingWindowScene = UIApplication.shared.connectedScenes.first {
        guard let windowScene = $0 as? UIWindowScene else { return false }
        return windowScene.screen == newScreen
      } as? UIWindowScene

        guard let connectedWindowScene = matchingWindowScene else {
          NSLog("--- Connected scene was not found ---")
          return
          //fatalError("Connected scene was not found") // You might want to retry here after some time
        }
        let screenDimensions = newScreen.bounds
      ////// new code here --->
        newScreen.overscanCompensation = .none
      //////
        let newWindow = UIWindow(frame: screenDimensions)
        NSLog("newWindow \(screenDimensions.width)x\(screenDimensions.height)")
        newWindow.windowScene = connectedWindowScene

        let vc = ExternalViewController()
        vc.mainVC = self

        newWindow.rootViewController = vc
        newWindow.isHidden = false
        self.additionalWindows.append(newWindow)
      }
    }
  }
}
```

In this day and age, I find it pretty peculiar that overscan compensation is enabled by default.

Body:
I am able to detect when a screen is detected, associate it with an appropriate windowScene and add a view to it. Slightly hacky but approximately working (code for disconnection not included here), thanks to this SO question:

class ExternalViewController: UIViewController {
  override func viewDidLoad() {
    view.backgroundColor = .cyan
    print("external frame \(view.frame.width)x\(view.frame.height)")
  }
}
class ViewController: UIViewController {
  var additionalWindows: [UIWindow] = []
  override func viewDidLoad() {
    //nb, Apple documentation seems out of date.
    //https://stackoverflow.com/questions/61191134/setter-for-screen-was-deprecated-in-ios-13-0
    NotificationCenter.default.addObserver(forName: UIScreen.didConnectNotification, object: nil, queue: nil) { [weak self] notification in
      guard let self = self else {return}

      guard let newScreen = notification.object as? UIScreen else {return}
      // Give the system time to update the connected scenes
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
        // Find matching UIWindowScene
        let matchingWindowScene = UIApplication.shared.connectedScenes.first {
        guard let windowScene = $0 as? UIWindowScene else { return false }
        return windowScene.screen == newScreen
      } as? UIWindowScene

        guard let connectedWindowScene = matchingWindowScene else {
          NSLog("--- Connected scene was not found ---")
          return
          //fatalError("Connected scene was not found") // You might want to retry here after some time
        }
        let screenDimensions = newScreen.bounds

        let newWindow = UIWindow(frame: screenDimensions)
        NSLog("newWindow \(screenDimensions.width)x\(screenDimensions.height)")
        newWindow.windowScene = connectedWindowScene

        let vc = ExternalViewController()
        vc.mainVC = self

        newWindow.rootViewController = vc
        newWindow.isHidden = false
        self.additionalWindows.append(newWindow)
      }
    }
  }
}

When I do this in the iOS simulator, I see my graphics fill the screen as intended, but when running on my actual device, it appears with a substantial black border around all sides.

Note that this is not the usual border seen with the default display mirroring behaviour - the 16:9 aspect ratio is preserved, and I do see different graphics as expected, (flat cyan color in my example code, normally I'm doing some Metal rendering that has some slight anomalies that are out of scope here, although perhaps might lead to some different clues on this if I dig into it deeper).

The print messages report the expected 1920x1080 dimensions. I don't know UIKit very well, and haven't been doing much active Apple development (I'm dusting off a couple of old side projects here in the hopes of being able to use them to project visuals at a gig in the near future), so I don't know if there's something else to do with sizing constraints etc that I might be missing, but even so it's hard to see why it would behave differently in the simulator.

Other apps I have installed from the app store do indeed show fullscreen graphics on the external display - Netflix shows fullscreen video as you would expect, Concepts shows a different representation of the document than the one you see on the device.

Body:
So, in this instance the issue is to do with Overscan Compensation. Thanks to Jerrot on Discord for pointing me in the right direction.

In the context of my app, it is sufficient to add newScreen.overscanCompensation = .none in the connection notification delegate (actually, in the part that is delayed a few ms after that - it doesn't work if applied directly in the connection notification). In the question linked above, there is further discussion of other aspects that may be important in a different context.

This is my ViewController modified to achieve the desired result:

class ViewController: UIViewController {
  var additionalWindows: [UIWindow] = []
  override func viewDidLoad() {
    //nb, Apple documentation seems out of date.
    //https://stackoverflow.com/questions/61191134/setter-for-screen-was-deprecated-in-ios-13-0
    NotificationCenter.default.addObserver(forName: UIScreen.didConnectNotification, object: nil, queue: nil) { [weak self] notification in
      guard let self = self else {return}

      guard let newScreen = notification.object as? UIScreen else {return}
      // Give the system time to update the connected scenes
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
        // Find matching UIWindowScene
        let matchingWindowScene = UIApplication.shared.connectedScenes.first {
        guard let windowScene = $0 as? UIWindowScene else { return false }
        return windowScene.screen == newScreen
      } as? UIWindowScene

        guard let connectedWindowScene = matchingWindowScene else {
          NSLog("--- Connected scene was not found ---")
          return
          //fatalError("Connected scene was not found") // You might want to retry here after some time
        }
        let screenDimensions = newScreen.bounds
      ////// new code here --->
        newScreen.overscanCompensation = .none
      //////
        let newWindow = UIWindow(frame: screenDimensions)
        NSLog("newWindow \(screenDimensions.width)x\(screenDimensions.height)")
        newWindow.windowScene = connectedWindowScene

        let vc = ExternalViewController()
        vc.mainVC = self

        newWindow.rootViewController = vc
        newWindow.isHidden = false
        self.additionalWindows.append(newWindow)
      }
    }
  }
}

In this day and age, I find it pretty peculiar that overscan compensation is enabled by default.


问:
How can I solve sql record grouping problem?
I'm trying to figure out a way to return results by using the group by function.

Is it possible to have a group by ignoring the NULL field. So that it does not group NULLs together because I still need all the rows where the specified field is NULL.

my records example
TABLEX

id
status
mode
update_date

1
null
0
13:46

1
null
1
12:22

1
1
null
15:00

1
0
null
15:55

i want to group last records with not null columns.

i tried this query but it is not success:

```<code>SELECT id, status, mode, update_date FROM TABLEX ORDER BY update_date GROUP BY id
</code>```

i want to get this result:

id
status
mode
update_date

1
0
0
15:55

how can i solve this situation.

答:
NOTES:

This is running on oracle 18c.

There's GOT to be a better way.... and this isn't tested w/ all edge cases I could think of...  But it appears to be working....

DEMO: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=be87b5778616a4732db3a3c4787804e0

```<code>WITH CTE AS (SELECT 1 ID, null STATUS,0 "MODE", '13:46' UPDATE_DATE from dual UNION ALL
         SELECT 1,null,1,'12:22' from dual UNION ALL
         SELECT 1,1,null,'15:00' from dual UNION ALL
         SELECT 1,0,null,'15:55' from dual)

SELECT A.ID, Z.Status, Y."MODE", max(A.Update_Date) UD
FROM CTE A
CROSS APPLY (SELECT B.Status FROM CTE B WHERE B.ID = A.ID and B.Status is not null ORDER BY UPDATE_DATE DESC FETCH FIRST 1 ROW ONLY) Z
CROSS APPLY (SELECT B."MODE" FROM CTE B WHERE B.ID = A.ID and B."MODE" is not null ORDER BY UPDATE_DATE DESC FETCH FIRST 1 ROW ONLY) Y
GROUP BY ID, Z.Status, Y."MODE"

+----+--------+------+-------+
| ID | STATUS | MODE |  UD   |
+----+--------+------+-------+
|  1 |      0 |    0 | 15:55 |
+----+--------+------+-------+
</code>```

I didn't bother with data type casting for the update date  so long as the time is in a 24 hour format the results would be the same so I didn't take the time.

So cross apply is running the inline queries once for each row in the main table and obtaining the status or mode following the rule of not null value and must have the highest Update_Date.  I thought First_Value analytic would work; but I couldn't get it working... (though I was using 11 at the time)

Since it will return the same values for all rows within an ID, grouping by it allows us to consolidate back into 1 record.

first_value may work on 18+ I didn't try it there...

More testing: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=705747c5b5f0e8414a2561fa82842fb7

Body:
I'm trying to figure out a way to return results by using the group by function.

Is it possible to have a group by ignoring the NULL field. So that it does not group NULLs together because I still need all the rows where the specified field is NULL.

my records example
TABLEX

id
status
mode
update_date

1
null
0
13:46

1
null
1
12:22

1
1
null
15:00

1
0
null
15:55

i want to group last records with not null columns.

i tried this query but it is not success:

SELECT id, status, mode, update_date FROM TABLEX ORDER BY update_date GROUP BY id

i want to get this result:

id
status
mode
update_date

1
0
0
15:55

how can i solve this situation.

Body:
NOTES:

This is running on oracle 18c.

There's GOT to be a better way.... and this isn't tested w/ all edge cases I could think of...  But it appears to be working....

DEMO: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=be87b5778616a4732db3a3c4787804e0

WITH CTE AS (SELECT 1 ID, null STATUS,0 "MODE", '13:46' UPDATE_DATE from dual UNION ALL
         SELECT 1,null,1,'12:22' from dual UNION ALL
         SELECT 1,1,null,'15:00' from dual UNION ALL
         SELECT 1,0,null,'15:55' from dual)

SELECT A.ID, Z.Status, Y."MODE", max(A.Update_Date) UD
FROM CTE A
CROSS APPLY (SELECT B.Status FROM CTE B WHERE B.ID = A.ID and B.Status is not null ORDER BY UPDATE_DATE DESC FETCH FIRST 1 ROW ONLY) Z
CROSS APPLY (SELECT B."MODE" FROM CTE B WHERE B.ID = A.ID and B."MODE" is not null ORDER BY UPDATE_DATE DESC FETCH FIRST 1 ROW ONLY) Y
GROUP BY ID, Z.Status, Y."MODE"

+----+--------+------+-------+
| ID | STATUS | MODE |  UD   |
+----+--------+------+-------+
|  1 |      0 |    0 | 15:55 |
+----+--------+------+-------+

I didn't bother with data type casting for the update date  so long as the time is in a 24 hour format the results would be the same so I didn't take the time.

So cross apply is running the inline queries once for each row in the main table and obtaining the status or mode following the rule of not null value and must have the highest Update_Date.  I thought First_Value analytic would work; but I couldn't get it working... (though I was using 11 at the time)

Since it will return the same values for all rows within an ID, grouping by it allows us to consolidate back into 1 record.

first_value may work on 18+ I didn't try it there...

More testing: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=705747c5b5f0e8414a2561fa82842fb7


问:
How can we change the IP of Android emulator
I was trying to communicate with 2 PC emulators. But after that I found that ,both emulator has same IP. How can I distinguish between which IP is for which emulator? Is there a way to set different IPs?</p>

答:
See interconnecting emulator instances on the android developer pages

In short:

```<code>To allow one emulator instance to communicate with another, you must set up the necessary network redirections as illustrated below.

Assume that your environment is

    A is you development machine
    B is your first emulator instance, running on A
    C is your second emulator instance, running on A too

and you want to run a server on B, to which C will connect, here is how you could set it up:

    Set up the server on B, listening to 10.0.2.15:<serverPort>
    On B's console, set up a redirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort>
    On C, have the client connect to 10.0.2.2:<localPort>

For example, if you wanted to run an HTTP server, you can select <serverPort> as 80 and <localPort> as 8080:

    B listens on 10.0.2.15:80
    On B's console, issue redir add tcp:8080:80
    C connects to 10.0.2.2:8080
</code>```

Body:
See interconnecting emulator instances on the android developer pages

In short:

To allow one emulator instance to communicate with another, you must set up the necessary network redirections as illustrated below.

Assume that your environment is

    A is you development machine
    B is your first emulator instance, running on A
    C is your second emulator instance, running on A too

and you want to run a server on B, to which C will connect, here is how you could set it up:

    Set up the server on B, listening to 10.0.2.15:<serverPort>
    On B's console, set up a redirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort>
    On C, have the client connect to 10.0.2.2:<localPort>

For example, if you wanted to run an HTTP server, you can select <serverPort> as 80 and <localPort> as 8080:

    B listens on 10.0.2.15:80
    On B's console, issue redir add tcp:8080:80
    C connects to 10.0.2.2:8080


问:
How do I filter an object with an object using Array.filter similar to lodash?
I am trying to avoid importing lodash for a simple filter. I am trying to do something similar to this...

```<code>// Items
[
  { "title": "a", "name": "a", "location": "here"},
  { "title": "b", "name": "a", "location": "here"},
  { "title": "d", "location": "there"},
]
// Filter
{ "name" : "a", "location": "here" }
</code>```

Should return the first two items. In lodash this is done by something similar to _.filter(Items, Filter). I would like to implement this without lodash or a bunch of code and getting Object.keys. Is there a simple way in modern Javascript to handle this?

答:
Here's what I came up with, seems to work well

let foo = [
  { "title": "a", "name": "a", "location": "here"},
  { "title": "b", "name": "a", "location": "here"},
  { "title": "d", "location": "there"},
];

let bar = { "name" : "a", "location": "here" };

let result = foo.filter(obj =>
  Object.entries(bar).every(([k,v]) => obj[k]===v)
);

console.log(result);```

Body:
I am trying to avoid importing lodash for a simple filter. I am trying to do something similar to this...

// Items
[
  { "title": "a", "name": "a", "location": "here"},
  { "title": "b", "name": "a", "location": "here"},
  { "title": "d", "location": "there"},
]
// Filter
{ "name" : "a", "location": "here" }

Should return the first two items. In lodash this is done by something similar to _.filter(Items, Filter). I would like to implement this without lodash or a bunch of code and getting Object.keys. Is there a simple way in modern Javascript to handle this?


问:
Android Kotlin - clear glide cache in background thread doesn't work
```<code>GlobalScope.launch(Dispatchers.Default) {
    Glide.with(this@UploadProfileImage).clearDiskCache()
}
</code>```

I get unresolved reference on clearDiskCache

When I do

```<code>Glide.with(this).clearDiskCache()
</code>```

instead then I don't get unresolved reference on clearDiskCache but

```<code>None of the following functions can be called with the arguments supplied:
public open fun with(activity: Activity): RequestManager defined in com.bumptech.glide.Glide
public open fun with(fragment: android.app.Fragment): RequestManager defined in com.bumptech.glide.Glide
public open fun with(context: Context): RequestManager defined in com.bumptech.glide.Glide
public open fun with(view: View): RequestManager defined in com.bumptech.glide.Glide
public open fun with(fragment: androidx.fragment.app.Fragment): RequestManager defined in com.bumptech.glide.Glide
public open fun with(activity: FragmentActivity): RequestManager defined in com.bumptech.glide.Glide
</code>```

on with

答: you should use 'Glide.get(context)' instead of 'Glide.with(context)' to use 'clearDiskCache' method.</p>

Body:
GlobalScope.launch(Dispatchers.Default) {
    Glide.with(this@UploadProfileImage).clearDiskCache()
}

I get unresolved reference on clearDiskCache

When I do

Glide.with(this).clearDiskCache()

instead then I don't get unresolved reference on clearDiskCache but

None of the following functions can be called with the arguments supplied:
public open fun with(activity: Activity): RequestManager defined in com.bumptech.glide.Glide
public open fun with(fragment: android.app.Fragment): RequestManager defined in com.bumptech.glide.Glide
public open fun with(context: Context): RequestManager defined in com.bumptech.glide.Glide
public open fun with(view: View): RequestManager defined in com.bumptech.glide.Glide
public open fun with(fragment: androidx.fragment.app.Fragment): RequestManager defined in com.bumptech.glide.Glide
public open fun with(activity: FragmentActivity): RequestManager defined in com.bumptech.glide.Glide

on with


问:
Managing multiple threads at the console
When I run multiple threads I get lost in System.out.println output because I suppose each thread has to be in a different consoles.

Is there an easy way to manage it using Eclipse?

EDIT: The problem is not to know which message belongs to each thread. The exact problem is that the console stops printing when a new thread is called, and the same happens with log4j too.

答:
If you use log4j you can keep the threads' logging straight using Nested Diagnostic Contexts.

Here's the description of NDCs from the log4j manual:

Most real-world systems have to deal with multiple clients
  simultaneously. In a typical multithreaded implementation of such a
  system, different threads will handle different clients. Logging is
  especially well suited to trace and debug complex distributed
  applications. A common approach to differentiate the logging output of
  one client from another is to instantiate a new separate logger for
  each client. This promotes the proliferation of loggers and increases
  the management overhead of logging.

A lighter technique is to uniquely stamp each log request initiated
  from the same client interaction. Neil Harrison described this method
  in the book "Patterns for Logging Diagnostic Messages," in Pattern
  Languages of Program Design 3, edited by R. Martin, D. Riehle, and F.
  Buschmann (Addison-Wesley, 1997).

To uniquely stamp each request, the user pushes contextual information
  into the NDC, the abbreviation of Nested Diagnostic Context. The NDC
  class is shown below.

```<code>public class NDC {
    // Used when printing the diagnostic
    public static String get();

    // Remove the top of the context from the NDC.
    public static String pop();

    // Add diagnostic context for the current thread.
    public static void push(String message);

    // Remove the diagnostic context for this thread.
    public static void remove();   }
</code>```

The NDC is managed per thread as a stack of contextual information.
  Note that all methods of the org.apache.log4j.NDC class are static.
  Assuming that NDC printing is turned on, every time a log request is
  made, the appropriate log4j component will include the entire NDC
  stack for the current thread in the log output. This is done without
  the intervention of the user, who is responsible only for placing the
  correct information in the NDC by using the push and pop methods at a
  few well-defined points in the code. In contrast, the per-client
  logger approach commands extensive changes in the code.

To illustrate this point, let us take the example of a servlet
  delivering content to numerous clients. The servlet can build the NDC
  at the very beginning of the request before executing other code. The
  contextual information can be the client's host name and other
  information inherent to the request, typically information contained
  in cookies. Hence, even if the servlet is serving multiple clients
  simultaneously, the logs initiated by the same code, i.e. belonging to
  the same logger, can still be distinguished because each client
  request will have a different NDC stack. Contrast this with the
  complexity of passing a freshly instantiated logger to all code
  exercised during the client's request.

Body:
If you use log4j you can keep the threads' logging straight using Nested Diagnostic Contexts.

Here's the description of NDCs from the log4j manual:

Most real-world systems have to deal with multiple clients
  simultaneously. In a typical multithreaded implementation of such a
  system, different threads will handle different clients. Logging is
  especially well suited to trace and debug complex distributed
  applications. A common approach to differentiate the logging output of
  one client from another is to instantiate a new separate logger for
  each client. This promotes the proliferation of loggers and increases
  the management overhead of logging.

A lighter technique is to uniquely stamp each log request initiated
  from the same client interaction. Neil Harrison described this method
  in the book "Patterns for Logging Diagnostic Messages," in Pattern
  Languages of Program Design 3, edited by R. Martin, D. Riehle, and F.
  Buschmann (Addison-Wesley, 1997).

To uniquely stamp each request, the user pushes contextual information
  into the NDC, the abbreviation of Nested Diagnostic Context. The NDC
  class is shown below.

public class NDC {
    // Used when printing the diagnostic
    public static String get();

    // Remove the top of the context from the NDC.
    public static String pop();

    // Add diagnostic context for the current thread.
    public static void push(String message);

    // Remove the diagnostic context for this thread.
    public static void remove();   }

The NDC is managed per thread as a stack of contextual information.
  Note that all methods of the org.apache.log4j.NDC class are static.
  Assuming that NDC printing is turned on, every time a log request is
  made, the appropriate log4j component will include the entire NDC
  stack for the current thread in the log output. This is done without
  the intervention of the user, who is responsible only for placing the
  correct information in the NDC by using the push and pop methods at a
  few well-defined points in the code. In contrast, the per-client
  logger approach commands extensive changes in the code.

To illustrate this point, let us take the example of a servlet
  delivering content to numerous clients. The servlet can build the NDC
  at the very beginning of the request before executing other code. The
  contextual information can be the client's host name and other
  information inherent to the request, typically information contained
  in cookies. Hence, even if the servlet is serving multiple clients
  simultaneously, the logs initiated by the same code, i.e. belonging to
  the same logger, can still be distinguished because each client
  request will have a different NDC stack. Contrast this with the
  complexity of passing a freshly instantiated logger to all code
  exercised during the client's request.


问:
Change JavaScript Date in Chrome
Without having to change the date/time of the computer I am debugging, is there a way, either via the dev tools or by running some custom JavaScript in the console, to set / change what time or date Google Chrome thinks it is?

IE so that new Date() returns what you've set the browser to think it is, rather than the system's date.

There are ways around it, but it would be handy to debug different dates / times.

答:
If you use this answer, you might get an error Uncaught TypeError: Date.now is not a function. In that case, you can add .now as a method returning the timestamp integer for the fake date.

const testDate = new Date('Fri Feb 11 2022 10:06:37 GMT-0500 (Eastern Standard Time)')
const returnTestDate = () => testDate
returnTestDate.now = () => testDate.getTime()
Date = returnTestDate

console.log(Date.now()) // returns 1644591997000 every time
```

Title: Change JavaScript Date in Chrome


问:
Efficiently check if an array is jagged
I'm looking for an efficient way to check if an array is jagged, where "jagged" means that an element of the array has a different shape from one of it's neighbors in the same dimension.

e.g. [[1, 2], [3, 4, 5]] or [[1, 2], [3, 4], [5, 6], [[7], [8]]]

Where I'm using list syntax for convenience, but the arguments may be nested lists or nested numpy arrays.  I'm also showing integers for convenience, by the lowest-level components could be anything (e.g. generic objects).  Let's say the lowest-level objects are not iterable themselves (e.g. str or dict, but definitely bonus points for a solution that can handle those too!).

Attemp:

Recursively flattening an array is pretty easy, though I'm guessing quite inefficient, and then the length of the flattened array can be compared to the numpy.size of the input array.  If they match, then it is not jagged.

```<code>def really1d(arr):
    # Returns false if the given array is not 1D or is a jagged 1D array.
    if np.ndim(arr) != 1:
        return False
    if len(arr) == 0:
        return True
    if np.any(np.vectorize(np.ndim)(arr)):
        return False
    return True

def flatten(arr):
    # Convert the given array to 1D (even if jagged)
    if (not np.iterable(arr)) or really1d(arr):
        return arr
    return np.concatenate([flatten(aa) for aa in arr])

def isjagged(arr):
    if (np.size(arr) == len(flatten(arr))):
        return False
    return True
</code>```

I'm pretty sure the concatenations are copying all of the data, which is a complete waste.  Maybe there is an itertools or numpy.flatiter method of achieving the same goal?  Ultimately the flattened array is only being used to find it's length.

答:
Perhaps not the most efficient but it works nicely in numpy. and will short circuit as soon as one of the conditions is False. If the first three conditions are True, we have no choice but to iterate through the rows.

Thankfull, all will shortcircuit as soon as one of the iterations is False so it won't check all the rows if it doesn't have to.

def jagged(x):
    x = np.asarray(x)
    return (
        x.dtype == "object"
        and x.ndim == 1
        and isinstance(x[0], list)
        and not all(len(row) == len(x[0]) for row in x)
    )
```

If you wan't to squeeze more efficieny out, it's actually performing the len(x[0]) every iteration of the all part but this is probably inconsequential and this is a lot more legible than the alaternative which would have you write out the whole if statement.

Title: Efficiently check if an array is jagged

Body:
I'm looking for an efficient way to check if an array is jagged, where "jagged" means that an element of the array has a different shape from one of it's neighbors in the same dimension.

e.g. [[1, 2], [3, 4, 5]] or [[1, 2], [3, 4], [5, 6], [[7], [8]]]

Where I'm using list syntax for convenience, but the arguments may be nested lists or nested numpy arrays.  I'm also showing integers for convenience, by the lowest-level components could be anything (e.g. generic objects).  Let's say the lowest-level objects are not iterable themselves (e.g. str or dict, but definitely bonus points for a solution that can handle those too!).

Attemp:

Recursively flattening an array is pretty easy, though I'm guessing quite inefficient, and then the length of the flattened array can be compared to the numpy.size of the input array.  If they match, then it is not jagged.

def really1d(arr):
    # Returns false if the given array is not 1D or is a jagged 1D array.
    if np.ndim(arr) != 1:
        return False
    if len(arr) == 0:
        return True
    if np.any(np.vectorize(np.ndim)(arr)):
        return False
    return True

def flatten(arr):
    # Convert the given array to 1D (even if jagged)
    if (not np.iterable(arr)) or really1d(arr):
        return arr
    return np.concatenate([flatten(aa) for aa in arr])

def isjagged(arr):
    if (np.size(arr) == len(flatten(arr))):
        return False
    return True

I'm pretty sure the concatenations are copying all of the data, which is a complete waste.  Maybe there is an itertools or numpy.flatiter method of achieving the same goal?  Ultimately the flattened array is only being used to find it's length.

Body:
Perhaps not the most efficient but it works nicely in numpy. and will short circuit as soon as one of the conditions is False. If the first three conditions are True, we have no choice but to iterate through the rows.

Thankfull, all will shortcircuit as soon as one of the iterations is False so it won't check all the rows if it doesn't have to.

def jagged(x):
    x = np.asarray(x)
    return (
        x.dtype == "object"
        and x.ndim == 1
        and isinstance(x[0], list)
        and not all(len(row) == len(x[0]) for row in x)
    )

If you wan't to squeeze more efficieny out, it's actually performing the len(x[0]) every iteration of the all part but this is probably inconsequential and this is a lot more legible than the alaternative which would have you write out the whole if statement.


问:
How to use akka in Scala 3?
How to use akka in Scala 3 ? I can't find akka dependencies while using scala 3

sbt errors :

```<code>[error]   not found: /Users/admin/.ivy2/localcom.typesafe.akka/akka-actor-typed_3/2.6.15/ivys/ivy.xml
[error]   not found: https://repo1.maven.org/maven2/com/typesafe/akka/akka-actor-typed_3/2.6.15/akka-actor-typed_3-2.6.15.pom
[error] (ssExtractDependencies) sbt.librarymanagement.ResolveException: Error downloading com.typesafe.akka:akka-actor-typed_3:2.6.15
[error]   Not found
[error]   Not found
[error]   not found: /Users/admin/.ivy2/localcom.typesafe.akka/akka-actor-typed_3/2.6.15/ivys/ivy.xml
[error]   not found: https://repo1.maven.org/maven2/com/typesafe/akka/akka-actor-typed_3/2.6.15/akka-actor-typed_3-2.6.15.pom
</code>```

答:
In order to use akka with Scala 3 e.g. the akka-actor-typed  you can include akka-actor-typed 2.6.18 as a dependency.

The example provided uses akka-actor-typed 2.6.15 whose target is scala 2.13 and 2.12.

Scala 3 is included as a target only since akka-actor-typed 2.6.17.

The latest version of akka-actor-typed where scala 3 is included as a target is akka-actor-typed 2.6.18.

Title: How to use akka in Scala 3?

Body:
How to use akka in Scala 3 ? I can't find akka dependencies while using scala 3

sbt errors :

[error]   not found: /Users/admin/.ivy2/localcom.typesafe.akka/akka-actor-typed_3/2.6.15/ivys/ivy.xml
[error]   not found: https://repo1.maven.org/maven2/com/typesafe/akka/akka-actor-typed_3/2.6.15/akka-actor-typed_3-2.6.15.pom
[error] (ssExtractDependencies) sbt.librarymanagement.ResolveException: Error downloading com.typesafe.akka:akka-actor-typed_3:2.6.15
[error]   Not found
[error]   Not found
[error]   not found: /Users/admin/.ivy2/localcom.typesafe.akka/akka-actor-typed_3/2.6.15/ivys/ivy.xml
[error]   not found: https://repo1.maven.org/maven2/com/typesafe/akka/akka-actor-typed_3/2.6.15/akka-actor-typed_3-2.6.15.pom


问:
stale element reference: element is not attached to the page document in java
Hey I have problem with my script in java and selenium
My script adds products to cart and later remove it from cart, but when i tried to remove products i get "stale element reference: element is not attached to the page document". If I understand well, the element  vanish from DOM. I tried await, reoload the page, but still it doesn not work</p>

答:
I cant remove all products and once. I need to click trash for every single product

public void deleteProduct()
{

```<code>        WebElement removedProduct = shopDriver.findElement(By.className("remove-from-cart"));
        for (int i = 0; i <= count; i++)
        {
            removedProduct.click();
            mainTest.stopThreed();
            clickArt();
            mainTest.stopThreed();
            pressCartButton();
            mainTest.stopThreed();

        }
        //WebDriverWait wait = new WebDriverWait(shopDriver,10);
        //WebElement removedProduct = wait.until(ExpectedConditions.elementToBeClickable(By.className("remove-from-cart")));
        //removedProduct.click();
}
</code>```

Body:
I cant remove all products and once. I need to click trash for every single product

public void deleteProduct()
{

        WebElement removedProduct = shopDriver.findElement(By.className("remove-from-cart"));
        for (int i = 0; i <= count; i++)
        {
            removedProduct.click();
            mainTest.stopThreed();
            clickArt();
            mainTest.stopThreed();
            pressCartButton();
            mainTest.stopThreed();

        }
        //WebDriverWait wait = new WebDriverWait(shopDriver,10);
        //WebElement removedProduct = wait.until(ExpectedConditions.elementToBeClickable(By.className("remove-from-cart")));
        //removedProduct.click();
}


问:
Cannot build .NET Framework web app targeting 4.7.2 with VS 2022 installed on a docker container
I can't successfully build basic ASP.NET web app targeting framework 4.7.2.
I built a docker image with a base image for Windows Server Core 2019. On this image I installed VS 2022 Enterprise and took Azure development, .NET desktop development, ASP.NET and web development modules, including recommended ones.
For dotnet core solutions everything works fine, but for dotnet framework I am getting such errors:

```<code>packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props(31,5): Error MSB3758: An error has occurred during compilation. error CS0014: Required file 'alink.dll' could not be found

packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props(31,5): Error MSB4175: The task factory "CodeTaskFactory" could not be loaded from the assembly "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Microsoft.Build.Tasks.Core.dll". The task factory must return a value for the "TaskType" property.
</code>```

I additionally installed .NET Frameworks: 4.5, 4.6, 4.6.1, 4.7.1, 4.8, but it didn't help.
Locally, I am able to build it without any problems. I checked the image if VS 2022 was installed without any issues and it looks fine as well. All environment variables are also in place. I thought the issue was related with some missing .NET Frameworks with SDKs, but it still persists.

Installing Redistributable C++ 2012-2022 didn't help as well. I am using MSBuild 17.
What I still might be missing?

I want to create an agent for Azure DevOps and as a reference I use the Dockerfile from Microsoft documentation. One difference is that before the start script, I run my custom script to silently install the VS 2022 with the modules I specified earlier.
I use Azure DevOps pipelines to build the solution, and the VSBuild@1 task.

答: I was finally able to solve the problem I had. It turned out that the base windows server core image didn't contain all of the needed prerequisites nor Visual Studio. Solution was to use extended windows server core image with sdk 4.8. This is strange, because Visual Studio already delivers everything for sdk 4.8. I think the extended image must have had something else that didn't come with the VS installation.

Body:
I can't successfully build basic ASP.NET web app targeting framework 4.7.2.
I built a docker image with a base image for Windows Server Core 2019. On this image I installed VS 2022 Enterprise and took Azure development, .NET desktop development, ASP.NET and web development modules, including recommended ones.
For dotnet core solutions everything works fine, but for dotnet framework I am getting such errors:

packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props(31,5): Error MSB3758: An error has occurred during compilation. error CS0014: Required file 'alink.dll' could not be found

packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props(31,5): Error MSB4175: The task factory "CodeTaskFactory" could not be loaded from the assembly "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Microsoft.Build.Tasks.Core.dll". The task factory must return a value for the "TaskType" property.

I additionally installed .NET Frameworks: 4.5, 4.6, 4.6.1, 4.7.1, 4.8, but it didn't help.
Locally, I am able to build it without any problems. I checked the image if VS 2022 was installed without any issues and it looks fine as well. All environment variables are also in place. I thought the issue was related with some missing .NET Frameworks with SDKs, but it still persists.

Installing Redistributable C++ 2012-2022 didn't help as well. I am using MSBuild 17.
What I still might be missing?

I want to create an agent for Azure DevOps and as a reference I use the Dockerfile from Microsoft documentation. One difference is that before the start script, I run my custom script to silently install the VS 2022 with the modules I specified earlier.
I use Azure DevOps pipelines to build the solution, and the VSBuild@1 task.


问:
Comparing a specific string in two csv files and making third csv based on those strings
I have this csv file:

```<code>OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
"CORP:John Smith:,John Smith:"       mail/123456.nsf
STORE:Mary Poppins:                  mail/789012.nsf
STORE:Tony Stark:                    mail/345678.nsf
STORE:Carmen Sandiego:               mail/901234.nsf
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
STORES:store123                      mail/369121.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf
</code>```

Then file2.csv:

```<code>OU
CORP
STORE
NEWS
</code>```

For every line in file2.csv that has 'CORP', 'STORE', or 'NEWS', I want to search through file1.csv and create a file, such as STOREall.csv, CORPall.csv, and NEWSall.csv.

Such as NEWSall.csv

```<code>OU                                   Mailfile

NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf
</code>```

But I'm getting this output instead:

In CORPall.csv

```<code>OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
CORP:John Smith:,John Smith:         mail/123456.nsf
NEWS:CORPmanager                     mail/137112.nsf
</code>```

Then NEWSall.csv

```<code>OU                                   Mailfile
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
</code>```

Since CORP is also in news, it appears in the CORPall.csv. I don't want that. If it says NEWS before the : then that should be in NEWSall.csv, etc.

I used this snippet that someone showed me on here:

```<code>for dept in OUList['OU']:
    df[df['OU'].str.contains(dept)]
    df_dept['OU'].to_csv(f'{dept}all.csv', index=False)
</code>```

It works great. But it only looks for what's in the whole file. So I need a way to search before the : (mind there's two in some cases)

答: It sounds like the "OU" column should be split into two columns on the : character.  You can do this with df['OU'].str.split(':').  Save the output to new columns and then you can use the same filter technique on the column created from the left of :

Body:
I have this csv file:

OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
"CORP:John Smith:,John Smith:"       mail/123456.nsf
STORE:Mary Poppins:                  mail/789012.nsf
STORE:Tony Stark:                    mail/345678.nsf
STORE:Carmen Sandiego:               mail/901234.nsf
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
STORES:store123                      mail/369121.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf

Then file2.csv:

OU
CORP
STORE
NEWS

For every line in file2.csv that has 'CORP', 'STORE', or 'NEWS', I want to search through file1.csv and create a file, such as STOREall.csv, CORPall.csv, and NEWSall.csv.

Such as NEWSall.csv

OU                                   Mailfile

NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf

But I'm getting this output instead:

In CORPall.csv

OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
CORP:John Smith:,John Smith:         mail/123456.nsf
NEWS:CORPmanager                     mail/137112.nsf

Then NEWSall.csv

OU                                   Mailfile
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf

Since CORP is also in news, it appears in the CORPall.csv. I don't want that. If it says NEWS before the : then that should be in NEWSall.csv, etc.

I used this snippet that someone showed me on here:

for dept in OUList['OU']:
    df[df['OU'].str.contains(dept)]
    df_dept['OU'].to_csv(f'{dept}all.csv', index=False)

It works great. But it only looks for what's in the whole file. So I need a way to search before the : (mind there's two in some cases)


问:
How do I add an integer to a string using Console.WriteLine?
I'm currently writing a program in C# and I'm practicing using integers. I'm trying to make it so the written line comes out with the int at the end. It doesn't give me the outcome I want though, and when I searched on Google it didn't give me the solution I was looking for.

Code:

```<code>Random rnd = new Random();
int Pi = rnd.Next(1,5);

Console.WriteLine("Checking 'Pi' value...");
Console.Beep(37,1000);
Console.WriteLine("Pi value found. Pi = ",Pi);
Console.ReadKey();
</code>```

Outcome:

```<code>Checking 'Pi' value...
Pi value found. Pi =
</code>```

If you know anything I can try, please let me know.

答:
There are multiple ways of doing this.

Console.WriteLine("Pi Value found. Pi = " + Pi);, which is a shortened version of Console.WriteLine("Pi Value found. Pi = " + Pi.ToString());.

This works because operators like + do different things depending on what you use them on. C# automatically adds ToString() to your integer, converting it to, well, a string. This means what you're actually passing into Console.WriteLine now looks like this (assuming your random number generation generated the number 4 in this case: "Pi Value found. Pi = " + "4". Notice the quotation marks around the 4 - you now simply have two strings. For two strings, the "+"-Operator concatenates them, creating the single string "Pi Value found. Pi = 4" in this case.

Console.WriteLine($"Pi Value found. Pi = {Pi}") or Console.WriteLine("Pi Value found. Pi = {0}", Pi) (although not quite the same technically, they're different ways of writing essentially the same thing for your purposes)

This is string interpolation. Essentially what you're doing with this is defining a template to format the string by - done either directly by the compiler, which is the $-method of doing it (see here for more details), or by providing a template that Console.WriteLine passes into String.Format for you.

It doesn't really matter which of these you choose, they are all valid ways of achieving the same goal.

Body:
I'm currently writing a program in C# and I'm practicing using integers. I'm trying to make it so the written line comes out with the int at the end. It doesn't give me the outcome I want though, and when I searched on Google it didn't give me the solution I was looking for.

Code:

Random rnd = new Random();
int Pi = rnd.Next(1,5);

Console.WriteLine("Checking 'Pi' value...");
Console.Beep(37,1000);
Console.WriteLine("Pi value found. Pi = ",Pi);
Console.ReadKey();

Outcome:

Checking 'Pi' value...
Pi value found. Pi =

If you know anything I can try, please let me know.


问:
Reverse matrix diagonal
```<code>d = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]

d1 = []

for i in range(n):
  d1.append(arr[i][i])
</code>```

d1 equals to [11, 5, -12] which is correct.

How to do a reverse matrix, I want an array with [4, 5, 10]

How can I do this with Python?

答:
You could do it in a list comprehension using enumerate on the rows to get items from last to first column:</p>
```<code>d = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]

d1 = [row[-i] for i,row in enumerate(d,1)]

print(d1)
[4, 5, 10]
</code>```

Title: Reverse matrix diagonal

Body:
d = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]

d1 = []

for i in range(n):
  d1.append(arr[i][i])

d1 equals to [11, 5, -12] which is correct.

How to do a reverse matrix, I want an array with [4, 5, 10]

How can I do this with Python?

Body:
You could do it in a list comprehension using enumerate on the rows to get items from last to first column:

d = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]

d1 = [row[-i] for i,row in enumerate(d,1)]

print(d1)
[4, 5, 10]


问:
Void withCheckedThrowingContinuation Generic parameter 'T' could not be inferred
I'm unable to get withCheckedThrowingContinuation to compile when there’s no return type. For example:

    public
    func
    write(toDevice inDeviceID: Int, atAddress inAddr: Int, value inVal: Float)
        async
        throws
    {
        try await withCheckedThrowingContinuation
               // ^ Generic parameter 'T' could not be inferred
        { inCont in
            self.workQ.async
            {
                do
                {
                    self.deviceID = inDeviceID
                    try self.write(address: inAddr, value: inVal)
                    inCont.resume()
                }

                catch (let e)
                {
                    inCont.resume(throwing: e)
                }
            }
        }
    }
```
<p>A version that returns works just fine:</p>
<pre class="lang-swift prettyprint-override"><code>    public
    func
    readRegister(address inAddr: Int, fromDevice inDeviceID: Int)
        async
        throws
        -> UInt16
    {
        try await withCheckedThrowingContinuation
        { inCont in
            self.workQ.async
            {
                do
                {
                    self.deviceID = inDeviceID
                    let r = try self.readRegister(address: inAddr)
                    inCont.resume(returning: r)
                }

                catch (let e)
                {
                    inCont.resume(throwing: e)
                }
            }
        }
    }
</code>```

答:
I thought I would add another example

```<code>extension Something {
    public func sync() async throws {
        // The swift compiler demands that we be explicit where there is no return type.
        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) -> Void in
            self.sync { result in
                switch result {
                case .success(let entry):
                    continuation.resume(with: .success(entry))
                case .failure(let error):
                    continuation.resume(with: .failure(error))
                }
            }
        }
    }
}
</code>```

UPDATE: Xcode can now wrap your closure based function with async/await continuations.

Body:
I'm unable to get withCheckedThrowingContinuation to compile when there’s no return type. For example:

    public
    func
    write(toDevice inDeviceID: Int, atAddress inAddr: Int, value inVal: Float)
        async
        throws
    {
        try await withCheckedThrowingContinuation
               // ^ Generic parameter 'T' could not be inferred
        { inCont in
            self.workQ.async
            {
                do
                {
                    self.deviceID = inDeviceID
                    try self.write(address: inAddr, value: inVal)
                    inCont.resume()
                }

                catch (let e)
                {
                    inCont.resume(throwing: e)
                }
            }
        }
    }

A version that returns works just fine:

    public
    func
    readRegister(address inAddr: Int, fromDevice inDeviceID: Int)
        async
        throws
        -> UInt16
    {
        try await withCheckedThrowingContinuation
        { inCont in
            self.workQ.async
            {
                do
                {
                    self.deviceID = inDeviceID
                    let r = try self.readRegister(address: inAddr)
                    inCont.resume(returning: r)
                }

                catch (let e)
                {
                    inCont.resume(throwing: e)
                }
            }
        }
    }

Body:
I thought I would add another example

extension Something {
    public func sync() async throws {
        // The swift compiler demands that we be explicit where there is no return type.
        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) -> Void in
            self.sync { result in
                switch result {
                case .success(let entry):
                    continuation.resume(with: .success(entry))
                case .failure(let error):
                    continuation.resume(with: .failure(error))
                }
            }
        }
    }
}

UPDATE: Xcode can now wrap your closure based function with async/await continuations.


答:
You could get the entries of the filter in advance to prevent getting th entries for every filtering iteration.

const
    filter = (array, filter) => {
        const
            filterBy = entries => o => entries.every(([k, v]) => o[k] === v);

        return items.filter(filterBy(Object.entries(filters)));
    },
    items = [{ title: "a", name: "a", location: "here" }, { title: "b", name: "a", location: "here" }, { title: "d", location: "there"}],
    filters = { name: "a", location: "here" },
    result = filter(items, filters);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How do I filter an object with an object using Array.filter similar to lodash?

Body:
You could get the entries of the filter in advance to prevent getting th entries for every filtering iteration.

const
    filter = (array, filter) => {
        const
            filterBy = entries => o => entries.every(([k, v]) => o[k] === v);

        return items.filter(filterBy(Object.entries(filters)));
    },
    items = [{ title: "a", name: "a", location: "here" }, { title: "b", name: "a", location: "here" }, { title: "d", location: "there"}],
    filters = { name: "a", location: "here" },
    result = filter(items, filters);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Array Prop Undefined - Mapping Array In Props
I am expecting to map over an array, and pass the data to a child component. The undesired outcome is it reads as undefined.

Parent Component:

```<code>import Tier from "./tier";
const data = [
  {
    title: "SAVER SALLY",
    subtitle: "22,000rmb/month",
    list: [
      "Income Tax: 3,295",
      "Income Tax: 3,295",
    ],
    bottom: {
      title: "Total Yearly Savings:",
      centralNumber: "144,480RMB",
      subtitle: "This is approximately £16,000 or 21,000USD",
    },
  }
];

const Tiers = ({ classes }) => {
    return (
        <>
        {data.map(set => <Tier objectInformation={set} />)}
        </>
    )
}

export default withStyles((theme) => ({}))(Tiers);
</code>```

The Child Component:

```<code>const Tier = ({ classes, objectInformation }) => {
  const {title, subtitle, list, bottom} = objectInformation
  console.log("OBJECT INFORMATION", objectInformation)
  return (
    <div>{title}</div>
  )
}
</code>```

The end goal is to have multiple objects in the data variable, that'll pass down as props to Tiers, the parents component.

答:
Solution

I missed an s on the imports.

Incorrect: import Tiers from "components/tiers/tier"

Correct: import Tiers from "components/tiers/tiers"

Changing this fixed the issue.

Body:
I am expecting to map over an array, and pass the data to a child component. The undesired outcome is it reads as undefined.

Parent Component:

import Tier from "./tier";
const data = [
  {
    title: "SAVER SALLY",
    subtitle: "22,000rmb/month",
    list: [
      "Income Tax: 3,295",
      "Income Tax: 3,295",
    ],
    bottom: {
      title: "Total Yearly Savings:",
      centralNumber: "144,480RMB",
      subtitle: "This is approximately £16,000 or 21,000USD",
    },
  }
];

const Tiers = ({ classes }) => {
    return (
        <>
        {data.map(set => <Tier objectInformation={set} />)}
        </>
    )
}

export default withStyles((theme) => ({}))(Tiers);

The Child Component:

const Tier = ({ classes, objectInformation }) => {
  const {title, subtitle, list, bottom} = objectInformation
  console.log("OBJECT INFORMATION", objectInformation)
  return (

{title}

  )
}

The end goal is to have multiple objects in the data variable, that'll pass down as props to Tiers, the parents component.


问:
Add column with row number count of grouped column values while excluding NA's
I am trying to add a column to a data frame with a row number by groups. I do not want to count NA's. I have grouped by Day and want to add a column counting the row numbers by group without NA's. I am getting a data frame that counts the NA's first and then the number values.

Code so far:

```<code>df <- data.frame (Day  = c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2", "3", "3", "3", "3", "3"),
                  test1 = c("1.2", NA, "3.2", NA, "7.2", "1.2", "2.5", "0.98", NA, "1.6","1.2", NA, "4.1", "9.2", "0.78")
)

df <- df %>%
  group_by(Day) %>%
  mutate(row_num = row_number(!is.na(test1)))
print(df)

# A tibble: 15 x 3
# Groups:   Day [3]
   Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             3
 2 1     NA              1
 3 1     3.2             4
 4 1     NA              2
 5 1     7.2             5
 6 2     1.2             2
 7 2     2.5             3
 8 2     0.98            4
 9 2     NA              1
10 2     1.6             5
11 3     1.2             2
12 3     NA              1
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5
</code>```

It should be:

```<code>Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             1
 2 1     NA
 3 1     3.2             2
 4 1     NA
 5 1     7.2             3
 6 2     1.2             4
 7 2     2.5             5
 8 2     0.98            6
 9 2     NA
10 2     1.6             1
11 3     1.2             2
12 3     NA
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5
</code>```

Body:
I am trying to add a column to a data frame with a row number by groups. I do not want to count NA's. I have grouped by Day and want to add a column counting the row numbers by group without NA's. I am getting a data frame that counts the NA's first and then the number values.

Code so far:

df <- data.frame (Day  = c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2", "3", "3", "3", "3", "3"),
                  test1 = c("1.2", NA, "3.2", NA, "7.2", "1.2", "2.5", "0.98", NA, "1.6","1.2", NA, "4.1", "9.2", "0.78")
)

df <- df %>%
  group_by(Day) %>%
  mutate(row_num = row_number(!is.na(test1)))
print(df)

# A tibble: 15 x 3
# Groups:   Day [3]
   Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             3
 2 1     NA              1
 3 1     3.2             4
 4 1     NA              2
 5 1     7.2             5
 6 2     1.2             2
 7 2     2.5             3
 8 2     0.98            4
 9 2     NA              1
10 2     1.6             5
11 3     1.2             2
12 3     NA              1
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5

It should be:

Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             1
 2 1     NA
 3 1     3.2             2
 4 1     NA
 5 1     7.2             3
 6 2     1.2             4
 7 2     2.5             5
 8 2     0.98            6
 9 2     NA
10 2     1.6             1
11 3     1.2             2
12 3     NA
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5

Body:
df %>%
  group_by(Day) %>%
  mutate(row_num = row_number(NA^is.na(test1)))
  Day   test1 row_num
   <chr> <chr>   <int>
 1 1     1.2         1
 2 1     NA         NA
 3 1     3.2         2
 4 1     NA         NA
 5 1     7.2         3
 6 2     1.2         1
 7 2     2.5         2
 8 2     0.98        3
 9 2     NA         NA
10 2     1.6         4
11 3     1.2         1
12 3     NA         NA
13 3     4.1         2
14 3     9.2         3
15 3     0.78        4


问:
Trying to do MySQL Concat
I have this below data

```<code>ID     name         page1     page2      page3     page4     page5
1      demo           1         1          1         1         1
10     compliance     1         1          0         0         0
12     compliance     1         1          1         0         0
20     compliance     0         1          0         1         0
25     compliance     1         1          0         0         1
</code>```

I am trying to combine the columns which has 1 into it.

I tried it by Concat like below

```<code>Select id, name,
Concat (
case when page1 = 1 then 'page1, ' End
case when page2 = 1 then 'page2, ' End
case when page3 = 1 then 'page3, ' End
case when page4 = 1 then 'page4, ' End
case when page5 = 1 then 'page5, ' End
)
</code>```

But this gives me below

```<code>ID     name          yes page
1      demo         page1, page2, page3, page4, page5
10     compliance    NULL
12     compliance    NULL
20     compliance    NULL
25     compliance    NULL
</code>```

and I am looking to have something like below

```<code>ID     name          yes page
1      demo         page1, page2, page3, page4, page5,
10     compliance   page1, page2,
12     compliance   page1, page2, page3,
20     compliance   page2, page3, page4,
25     compliance   page1, page2, page5,
</code>```

Please let me know if there is I can do to my concat statement to work, so I can have table like above. Thank you so much for your help!

答:
When you have a CASE expression where nothing matches, the result of the expression is NULL. When you concatenate NULL with any other string, the result is NULL. This explains the result you're seeing.

The solution is including a default value with each expression:

```<code>case when page1 = 1 then 'page1, ' Else '' End
</code>```

Remember, NULL does not mean "empty". It means "I don't know". When you combine anything with "I don't know", the result is always going to be "I don't know".

Title: Trying to do MySQL Concat

Body:
I have this below data

ID     name         page1     page2      page3     page4     page5
1      demo           1         1          1         1         1
10     compliance     1         1          0         0         0
12     compliance     1         1          1         0         0
20     compliance     0         1          0         1         0
25     compliance     1         1          0         0         1

I am trying to combine the columns which has 1 into it.

I tried it by Concat like below

Select id, name,
Concat (
case when page1 = 1 then 'page1, ' End
case when page2 = 1 then 'page2, ' End
case when page3 = 1 then 'page3, ' End
case when page4 = 1 then 'page4, ' End
case when page5 = 1 then 'page5, ' End
)

But this gives me below

ID     name          yes page
1      demo         page1, page2, page3, page4, page5
10     compliance    NULL
12     compliance    NULL
20     compliance    NULL
25     compliance    NULL

and I am looking to have something like below

ID     name          yes page
1      demo         page1, page2, page3, page4, page5,
10     compliance   page1, page2,
12     compliance   page1, page2, page3,
20     compliance   page2, page3, page4,
25     compliance   page1, page2, page5,

Please let me know if there is I can do to my concat statement to work, so I can have table like above. Thank you so much for your help!

Body:
When you have a CASE expression where nothing matches, the result of the expression is NULL. When you concatenate NULL with any other string, the result is NULL. This explains the result you're seeing.

The solution is including a default value with each expression:

case when page1 = 1 then 'page1, ' Else '' End

Remember, NULL does not mean "empty". It means "I don't know". When you combine anything with "I don't know", the result is always going to be "I don't know".