问:
Error with Blockchain Test Difficulty Adjustment
I am currently learning how to develop blockchain using Javascript and Node.js. One of my tests continuously fails and I am unable to pinpoint why. Here is the code and to which this error pertains to.

```<code>const Block = require('./block');

    describe('Block', () => {

let data, lastBlock, block;

beforeEach(() =\> {
data = 'bar';
lastBlock = Block.genesis();
block = Block.mineBlock(lastBlock, data);
});

it('sets the `data` to match the input', () =\> {
expect(block.data).toEqual(data);
});

it('sets the `lastHash` to match the hash of the last block', () =\> {
expect(block.lastHash).toEqual(lastBlock.hash);
});

it('generates a hash that matches the difficulty', () =\> {
expect(block.hash.substring(0, block.difficulty))
.toEqual('0'.repeat(block.difficulty));
});

it('lowers the difficulty for slowly mined blocks', () =\> {
expect(Block.adjustDifficulty(block, block.timestamp+360000))
.toEqual(block.difficulty-1);
});

it('raises the difficulty for quickly mined blocks', () =\> {
expect(Block.adjustDifficulty(block, block.timestamp+1))
.toEqual(block.difficulty+1);
});
});
</code>```

and the error say this:

FAIL  blockchain/block.test.js
Block
✓ sets the data to match the input (21 ms)
✓ sets the lastHash to match the hash of the last block (28 ms)
✕ generates a hash that matches the difficulty (13 ms)
✕ lowers the difficulty for slowly mined blocks (18 ms)
✕ raises the difficulty for quickly mined blocks (32 ms)

● Block › generates a hash that matches the difficulty

```<code>expect(received).toEqual(expected) // deep equality

Expected: ""
Received: "0008c4cb5a7dfbb6e2a57a1cf57967935cd5d842d2c1e37fba95d9e716a5e39e"

  20 |   it('generates a hash that matches the difficulty', () => {
  21 |     expect(block.hash.substring(0, block.difficulty))
> 22 |       .toEqual('0'.repeat(block.difficulty));
     |        ^
  23 |   });
  24 |
  25 |   it('lowers the difficulty for slowly mined blocks', () => {

  at Object.toEqual (blockchain/block.test.js:22:8)
</code>```

● Block › lowers the difficulty for slowly mined blocks

```<code>expect(received).toEqual(expected) // deep equality

Expected: NaN
Received: 2

  25 |   it('lowers the difficulty for slowly mined blocks', () => {
  26 |     expect(Block.adjustDifficulty(block, block.timestamp+360000))
> 27 |       .toEqual(block.difficulty-1);
     |        ^
  28 |   });
  29 |
  30 |   it('raises the difficulty for quickly mined blocks', () => {

  at Object.toEqual (blockchain/block.test.js:27:8)
</code>```

● Block › raises the difficulty for quickly mined blocks

```<code>expect(received).toEqual(expected) // deep equality

Expected: NaN
Received: 4

  30 |   it('raises the difficulty for quickly mined blocks', () => {
  31 |     expect(Block.adjustDifficulty(block, block.timestamp+1))
> 32 |       .toEqual(block.difficulty+1);
     |        ^
  33 |   });
  34 | });
  35 |

  at Object.toEqual (blockchain/block.test.js:32:8)
</code>```

Test Suites: 1 failed, 1 total
Tests:       3 failed, 2 passed, 5 total
Snapshots:   0 total
Time:        0.328 s, estimated 1 s
Ran all test suites.

If anyone could help me out that would be much appreciated - thanks!

Body:
I am currently learning how to develop blockchain using Javascript and Node.js. One of my tests continuously fails and I am unable to pinpoint why. Here is the code and to which this error pertains to.

const Block = require('./block');

    describe('Block', () => {

let data, lastBlock, block;

beforeEach(() =\> {
data = 'bar';
lastBlock = Block.genesis();
block = Block.mineBlock(lastBlock, data);
});

it('sets the `data` to match the input', () =\> {
expect(block.data).toEqual(data);
});

it('sets the `lastHash` to match the hash of the last block', () =\> {
expect(block.lastHash).toEqual(lastBlock.hash);
});

it('generates a hash that matches the difficulty', () =\> {
expect(block.hash.substring(0, block.difficulty))
.toEqual('0'.repeat(block.difficulty));
});

it('lowers the difficulty for slowly mined blocks', () =\> {
expect(Block.adjustDifficulty(block, block.timestamp+360000))
.toEqual(block.difficulty-1);
});

it('raises the difficulty for quickly mined blocks', () =\> {
expect(Block.adjustDifficulty(block, block.timestamp+1))
.toEqual(block.difficulty+1);
});
});

and the error say this:

FAIL  blockchain/block.test.js
Block
✓ sets the data to match the input (21 ms)
✓ sets the lastHash to match the hash of the last block (28 ms)
✕ generates a hash that matches the difficulty (13 ms)
✕ lowers the difficulty for slowly mined blocks (18 ms)
✕ raises the difficulty for quickly mined blocks (32 ms)

● Block › generates a hash that matches the difficulty

expect(received).toEqual(expected) // deep equality

Expected: ""
Received: "0008c4cb5a7dfbb6e2a57a1cf57967935cd5d842d2c1e37fba95d9e716a5e39e"

  20 |   it('generates a hash that matches the difficulty', () => {
  21 |     expect(block.hash.substring(0, block.difficulty))
> 22 |       .toEqual('0'.repeat(block.difficulty));
     |        ^
  23 |   });
  24 |
  25 |   it('lowers the difficulty for slowly mined blocks', () => {

  at Object.toEqual (blockchain/block.test.js:22:8)

● Block › lowers the difficulty for slowly mined blocks

expect(received).toEqual(expected) // deep equality

Expected: NaN
Received: 2

  25 |   it('lowers the difficulty for slowly mined blocks', () => {
  26 |     expect(Block.adjustDifficulty(block, block.timestamp+360000))
> 27 |       .toEqual(block.difficulty-1);
     |        ^
  28 |   });
  29 |
  30 |   it('raises the difficulty for quickly mined blocks', () => {

  at Object.toEqual (blockchain/block.test.js:27:8)

● Block › raises the difficulty for quickly mined blocks

expect(received).toEqual(expected) // deep equality

Expected: NaN
Received: 4

  30 |   it('raises the difficulty for quickly mined blocks', () => {
  31 |     expect(Block.adjustDifficulty(block, block.timestamp+1))
> 32 |       .toEqual(block.difficulty+1);
     |        ^
  33 |   });
  34 | });
  35 |

  at Object.toEqual (blockchain/block.test.js:32:8)

Test Suites: 1 failed, 1 total
Tests:       3 failed, 2 passed, 5 total
Snapshots:   0 total
Time:        0.328 s, estimated 1 s
Ran all test suites.

If anyone could help me out that would be much appreciated - thanks!


来源: stackexchange

问:
Angular module based microfrontend
Is there any approach to build micro-frontend per module? Sharing one core, but with own build and env for each website?

I heard it's possible, but found only @angular-architects/module-federation, but this seems to work with project per entire app

ContentLicense: CC BY-SA 4.0

Title: Angular module based microfrontend


问:
Applying Lookahead with z3 Solver
I want to solve a CSP with the help of Lookahead method in z3 Solver. The issue I'm facing is not being convinced that it's invoked by setting an according parameter like s.set("sat.lookahead_simplify", True) or s.set("sat.lookahead.delta_fraction", 0.7).

Below is the code for solving my combinatorial problem. I ren a similar solver on a complex instance A and the runtime without these settings on Lookahead was 3674 seconds versus 3670 secunds with these settings. So, seems like they have no effect.
Does anyone know how to correctly invoke Lookahead here?

import numpy as np
import timeit
from z3 import *

def as_long(self):
    if z3_debug():
        _z3_assert(self.is_int(), "Integer value expected")
    return int(self.as_string())

def model_int(mo, R, C, m, n):
    R_int = [mo[R[i]].as_long() for i in range(m)]
    C_int = [mo[C[j]].as_long() for j in range(n)]
    return [R_int, C_int]  # integer model values

def CSP(A, D, bit_length=8):

  A_shape = A.shape
  m = A_shape[0]
  n = A_shape[1]

  #initialize solver
  s = Solver()

  s.set("lookahead_simplify", True)
  s.set("sat.lookahead.delta_fraction", 0.7)

  #initialize column and row variables c_j and r_i as bit vectors
  C = [BitVec(f"c_{j + 1}", bit_length) for j in range(n)]
  R = [BitVec(f"r_{i + 1}", bit_length) for i in range(m)]

  #initialize search space restriction constraints for r_i's as lists
  Constr_D = [Or([r == d for d in D]) for r in R]

  #initialize permit-constraints as lists
  Constr_permit  = [R[i] & C[j] == C[j] for i in range(m) for j in range(n) if     A[i,j]]
  Constr_npermit = [R[i] & C[j] != C[j] for i in range(m) for j in range(n) if not A[i,j]]

  #add constraints
  s.add(Constr_D + Constr_permit + Constr_npermit)

  #search solution
  check = s.check()

  if check == sat:
        return model_int(s.model(), R, C, m, n)

  return check

# model instance ........

D = [7,11,19,35,67,13,21,37,69,25,41,73,49,81,82,84,88] #domain

m = 15 #number of rows
n = 9 #number of columns

p=.11

A = np.random.choice(a=[1,0],size=(m,n),p=[p,1-p])

print(A)

# executing solver on model instance ........

starttime = timeit.default_timer()

print(CSP(A,D))

print("The time difference is :", timeit.default_timer() - starttime)
```

Title: Applying Lookahead with z3 Solver


问:
watchposition and getcurrentposition return inaccurate location in galaxy s22 a53
I have a website that is used as an application that uses location, on some devices the location is not accurate especially on Samsung devices like S22 A53, on the other devices it works well.
I emphasize that in other applications such as Google Maps the location is accurate for those devices.
Usually, this is accompanied by an error:
"{code:3,message:Timeout expired}"
But this error also happens to devices that return a good location, I think it's related to the fact that the user clicked refresh location several times.</p>
```<code>let timeout: number = 10000

export function watchPosition(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  if (navigator.geolocation) {
    return getCoordinates(gotPos, gotErr)
  }
}

function getCoordinates(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  return navigator.geolocation.watchPosition(
    (x: any) => {
      timeout = 10000
      gotPos(x);
    },
    (err: any) => {
      if (Number(err.code) === 3) {
        if(timeout < 100000)
          timeout += 10000
        else
          timeout = 300000
      }
      gotErr(err);
    },
    {
      enableHighAccuracy: true,
      maximumAge: 0,
      timeout: timeout,
    }
  );
}

let timeout: number = 10000

export function setGPS(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  if (navigator.geolocation) {
    getCoordinates(gotPos, gotErr)
  }
}

function getCoordinates(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  //Dummy request, which will result in a working next geolocation request.
  navigator.geolocation.getCurrentPosition(function () { }, function () { }, {});

  navigator.geolocation.getCurrentPosition(
    (x: any) => {
      timeout = 10000
      gotPos(x);
    },
    (err: any) => {
      if (Number(err.code) === 3) {
        if(timeout < 100000)
          timeout += 10000
        else
          timeout = 30000
      }
      gotErr(err);
    },
    {
      enableHighAccuracy: true,
      maximumAge: 0,
      timeout: timeout
    }
  );
}

</code>```

Body:
I have a website that is used as an application that uses location, on some devices the location is not accurate especially on Samsung devices like S22 A53, on the other devices it works well.
I emphasize that in other applications such as Google Maps the location is accurate for those devices.
Usually, this is accompanied by an error:
"{code:3,message:Timeout expired}"
But this error also happens to devices that return a good location, I think it's related to the fact that the user clicked refresh location several times.

let timeout: number = 10000

export function watchPosition(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  if (navigator.geolocation) {
    return getCoordinates(gotPos, gotErr)
  }
}

function getCoordinates(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  return navigator.geolocation.watchPosition(
    (x: any) => {
      timeout = 10000
      gotPos(x);
    },
    (err: any) => {
      if (Number(err.code) === 3) {
        if(timeout < 100000)
          timeout += 10000
        else
          timeout = 300000
      }
      gotErr(err);
    },
    {
      enableHighAccuracy: true,
      maximumAge: 0,
      timeout: timeout,
    }
  );
}

let timeout: number = 10000

export function setGPS(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  if (navigator.geolocation) {
    getCoordinates(gotPos, gotErr)
  }
}

function getCoordinates(gotPos: (x: any) => void, gotErr: (x: any) => void) {
  //Dummy request, which will result in a working next geolocation request.
  navigator.geolocation.getCurrentPosition(function () { }, function () { }, {});

  navigator.geolocation.getCurrentPosition(
    (x: any) => {
      timeout = 10000
      gotPos(x);
    },
    (err: any) => {
      if (Number(err.code) === 3) {
        if(timeout < 100000)
          timeout += 10000
        else
          timeout = 30000
      }
      gotErr(err);
    },
    {
      enableHighAccuracy: true,
      maximumAge: 0,
      timeout: timeout
    }
  );
}


问:
Tom cat 7.0.96 use HTTPS only, without redirect port to http how to?
I've a tomcat 7.0.96 installed on my PC.
I've added to server . xml this section :

```<code> <Connector executor="tomcatThreadPool"
           port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="9443" />

<Connector executor="tomcatThreadPool"
       protocol="HTTP/1.1"
       port="9443" maxThreads="200"
       scheme="https" secure="true" SSLEnabled="true"
       keystoreFile="C:cert.p12"
       keystorePass="1123"
       clientAuth="false" sslProtocol="TLS" sslEnabledProtocols="TLSv1.2" />
</code>```

in web.xml I've added this section :

```<code>    <security-constraint>
<web-resource-collection>
<web-resource-name>Protected Context</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>

<!-- auth-constraint goes here if you require authentication -->
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
</code>```

I need to enable HTTPS only without the HTTP being redirected to the HTTPS port.
I'v read this tomcat HTTP
but nothing from this Q&A is working for me.
The HTTP port is still available.

Any advice on how to disable HTTP port? and make the tomcat uses only HTTPS port?

Body:
I've a tomcat 7.0.96 installed on my PC.
I've added to server . xml this section :

 <Connector executor="tomcatThreadPool"
           port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="9443" />

<Connector executor="tomcatThreadPool"
       protocol="HTTP/1.1"
       port="9443" maxThreads="200"
       scheme="https" secure="true" SSLEnabled="true"
       keystoreFile="C:cert.p12"
       keystorePass="1123"
       clientAuth="false" sslProtocol="TLS" sslEnabledProtocols="TLSv1.2" />

in web.xml I've added this section :

    <security-constraint>
<web-resource-collection>
<web-resource-name>Protected Context</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>

<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

I need to enable HTTPS only without the HTTP being redirected to the HTTPS port.
I'v read this tomcat HTTP
but nothing from this Q&A is working for me.
The HTTP port is still available.

Any advice on how to disable HTTP port? and make the tomcat uses only HTTPS port?


问:
Style not compatible with Jupyter-Book when using python-sphinx autodoc to generate API documentation
I'd love to use the so elegant Jupyter-Book to construct documentation for my packages. I've tried quite a lot, and here is an example I'm finalizing those days :

the package is available on a gitlab repository https://framagit.org/nlp/iamtokenizing

the associated documentation is constructed (almost) automatically by calling jupyter-book build documentation/ on CI/CL-deployment of the master branch of the repository, and visible there : https://nlp.frama.io/iamtokenizing

One can see I use

jupyter-notebook to generate user guides or tutorials,

markdown to generate simple static pages without codes, and

sphinx autodoc to generate api documentation. Note I'm fairly newbie using sphinx and autodoc.

I'd like to enhance the publication style of the auto-generated api documentation. As one can see, e.g. on this page, there is no right sidebar in the API documentation, whereas one may want to write the names of the class methods, or module functions there.

Also, the parameters list might be better presented in indented lists instead of being queued in parenthesis, and the name of the class might be shorter, for instance only the name of the class, not the path to it might appear. In short, I'd prefer having

class BaseTokenizer(string: str = '',
                    subtoksep: chr = ' ',
                    intervals: Union[None, EvenSizedSortedSet] = None,
                    tokens: list = [])
```
<p>instead of the monolithic presentation</p>
<pre class="lang-py prettyprint-override"><code>class iamtokenizing.base_tokenizer.BaseTokenizer(string: str = '', subtoksep:
chr = ' ', intervals: Union[None,
extractionstring.even_sized_sorted_set.EvenSizedSortedSet] = None, tokens: list = [])
</code>```

Is there a way to do all of that, or should I consider raising an issue instead ?

Body:
I'd love to use the so elegant Jupyter-Book to construct documentation for my packages. I've tried quite a lot, and here is an example I'm finalizing those days :

the package is available on a gitlab repository https://framagit.org/nlp/iamtokenizing

the associated documentation is constructed (almost) automatically by calling jupyter-book build documentation/ on CI/CL-deployment of the master branch of the repository, and visible there : https://nlp.frama.io/iamtokenizing

One can see I use

jupyter-notebook to generate user guides or tutorials,

markdown to generate simple static pages without codes, and

sphinx autodoc to generate api documentation. Note I'm fairly newbie using sphinx and autodoc.

I'd like to enhance the publication style of the auto-generated api documentation. As one can see, e.g. on this page, there is no right sidebar in the API documentation, whereas one may want to write the names of the class methods, or module functions there.

Also, the parameters list might be better presented in indented lists instead of being queued in parenthesis, and the name of the class might be shorter, for instance only the name of the class, not the path to it might appear. In short, I'd prefer having

class BaseTokenizer(string: str = '',
                    subtoksep: chr = ' ',
                    intervals: Union[None, EvenSizedSortedSet] = None,
                    tokens: list = [])

instead of the monolithic presentation

class iamtokenizing.base_tokenizer.BaseTokenizer(string: str = '', subtoksep:
chr = ' ', intervals: Union[None,
extractionstring.even_sized_sorted_set.EvenSizedSortedSet] = None, tokens: list = [])

Is there a way to do all of that, or should I consider raising an issue instead ?


问:
Negating `function_constant()` call for conditionally omitting struct fields in Metal shading language
so it appears that Apple Metal got away with preprocessor directives, opting to use function constants for optionally enabling / disabling parts of shader code.

I can conditionally enable certain struct fields, like so:

```<code>constant bool is_cubemap_render [[function_constant(0)]];
struct FragmentOut {
  float depth [[depth(any), function_constant(is_cubemap_render)]];
};
</code>```

However I am having hard time understanding what is the best way to omit a field if is_cubemap_render is false.

```<code>struct FragmentOut {
  float depth [[depth(any), !function_constant(is_cubemap_render)]]; // does not compile
};

struct FragmentOut {
  float depth [[depth(any), function_constant(!is_cubemap_render)]]; // does not compile too
};
</code>```

What I resorted to doing is

```<code>constant bool is_cubemap_render [[function_constant(0)]];
constant bool is_not_cubemap_render = !is_cubemap_render;

struct FragmentOut {
  float depth [[depth(any), function_constant(is_cubemap_render)]];
  float4 color [[color(0), function_constant(is_not_cubemap_render)]];
};
</code>```

I don't really like it as it pollutes the start of my files and I have to manually declare new variables. Is there a better way to go about it?

Body:
so it appears that Apple Metal got away with preprocessor directives, opting to use function constants for optionally enabling / disabling parts of shader code.

I can conditionally enable certain struct fields, like so:

constant bool is_cubemap_render [[function_constant(0)]];
struct FragmentOut {
  float depth [[depth(any), function_constant(is_cubemap_render)]];
};

However I am having hard time understanding what is the best way to omit a field if is_cubemap_render is false.

struct FragmentOut {
  float depth [[depth(any), !function_constant(is_cubemap_render)]]; // does not compile
};

struct FragmentOut {
  float depth [[depth(any), function_constant(!is_cubemap_render)]]; // does not compile too
};

What I resorted to doing is

constant bool is_cubemap_render [[function_constant(0)]];
constant bool is_not_cubemap_render = !is_cubemap_render;

struct FragmentOut {
  float depth [[depth(any), function_constant(is_cubemap_render)]];
  float4 color [[color(0), function_constant(is_not_cubemap_render)]];
};

I don't really like it as it pollutes the start of my files and I have to manually declare new variables. Is there a better way to go about it?


问:
TDI Sockets bad request
I am trying to write requests to the server from the kernel using this lab
TDI based socket interface

Why is it that
when I TDISend the request for the address HTTPS://server.com:443/api/

I get this error:

```<code>Status 400
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>cloudflare</center>
</body>
</html>
</code>```

when I TDISend the request for the address HTTP://server.com:80/api/

I get this error:

```<code>Status 301
<a href="https://server.com/api/">Moved Permanently</a>.
</code>```

Title: TDI Sockets bad request

Body:
I am trying to write requests to the server from the kernel using this lab
TDI based socket interface

Why is it that
when I TDISend the request for the address HTTPS://server.com:443/api/

I get this error:

Status 400
<title>400 The plain HTTP request was sent to HTTPS port</title>

400 Bad Request

The plain HTTP request was sent to HTTPS port

cloudflare

when I TDISend the request for the address HTTP://server.com:80/api/

I get this error:

Status 301
Moved Permanently.


问:
LeaveCriticalSection causing the app crash
Our legacy C++ app crashing at LeaveCriticalSection.
The application is a single threaded and am not sure for what reasons critical section is used since it is a legacy code.
Still trying to find out the reasons of crash.
The crash window just says unhandled exception.
The app only crashes in release mode</p>


问:
How to create a list of objects from multiple input fields using javascript
I have created a form using HTML and CSS, and I want to store all the input values in the form in an object, then add the object to a list of objects, serving as a database for all the "users" of this form, with all their information of course. here's what I tried already:

```<code>signupbtn.addEventListener('click', function(){
addObject();
HideSignUpPage();
});

let objects = [];

function addObject(){
var firstname = document.getElementById("firstnamebox").value;
var lastname = document.getElementById("lastnamebox").value;
var emailornumber = document.getElementById("emailornumberbox").value;
var password = document.getElementById("passwordbox").value;
var month = document.getElementById("monthbox").value;
var year = document.getElementById("yearbox").value;
var day = document.getElementById("daybox").value;
var gender;
var radiobuttons = document.getElementsByName("gender");
for (let i = 0; i < radiobuttons.length; i++){
    if (radiobuttons[i].checked){
        gender = radiobuttons[i].value;
        break;
    }
}
var obj = {
    firstname: firstname,
    lastname: lastname,
    emailornumber: emailornumber,
    password: password,
    month: month,
    year: year,
    day: day,
    gender: gender
};

objects.push(obj)
}

document.getElementById("objects").innerHTML = objects
</code>```

for some reason, when I try to print out the objects list with a document.write, it prints out "undefined". even tho I have submitted the form multiple times so theoretically it should've filled the array with a bunch of objects.

Body:
I have created a form using HTML and CSS, and I want to store all the input values in the form in an object, then add the object to a list of objects, serving as a database for all the "users" of this form, with all their information of course. here's what I tried already:

signupbtn.addEventListener('click', function(){
addObject();
HideSignUpPage();
});

let objects = [];

function addObject(){
var firstname = document.getElementById("firstnamebox").value;
var lastname = document.getElementById("lastnamebox").value;
var emailornumber = document.getElementById("emailornumberbox").value;
var password = document.getElementById("passwordbox").value;
var month = document.getElementById("monthbox").value;
var year = document.getElementById("yearbox").value;
var day = document.getElementById("daybox").value;
var gender;
var radiobuttons = document.getElementsByName("gender");
for (let i = 0; i < radiobuttons.length; i++){
    if (radiobuttons[i].checked){
        gender = radiobuttons[i].value;
        break;
    }
}
var obj = {
    firstname: firstname,
    lastname: lastname,
    emailornumber: emailornumber,
    password: password,
    month: month,
    year: year,
    day: day,
    gender: gender
};

objects.push(obj)
}

document.getElementById("objects").innerHTML = objects

for some reason, when I try to print out the objects list with a document.write, it prints out "undefined". even tho I have submitted the form multiple times so theoretically it should've filled the array with a bunch of objects.


问:
nest app is unable to connect to postgresql
This is the env file code that I am using to run the docker container:

```<code>POSTGRES_HOST="localhost"
POSTGRES_PORT=5432
POSTGRES_USERNAME="postgres"
POSTGRES_PASSWORD="123"
POSTGRES_DATABASE="netabe"
</code>```

This is the docker.compose.yml file:

```<code>postgres:
    container_name: postgres_container
    image: 'postgres:latest'
    environment:
      POSTGRES_USER: ${POSTGRES_USERNAME}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DATABASE}
    ports:
      - 5432:5432
    networks:
      app_network:
        ipv4_address: 172.26.0.10
    restart: unless-stopped
    healthcheck:
      test: ['CMD', 'pg_isready -U postgres']
      interval: 5s
      timeout: 5s
      retries: 5
    volumes:
      - postgres:/data/postgres
</code>```

It runs the postgres in docker container successfully but when I run the nest app then it says [Nest] 13620  - 05/01/2023, 6:56:41 pm   ERROR [SequelizeModule] Unable to connect to the database. Retrying (1).... I don't understand why this is happening. My postgres is also up and running and the database is also created in postgres but in the console it is throwing an error. The start:dev command: NODE_ENV=development nest start --watch

The postgresqlProvider is a different module and then I imported this in my app.module.ts file.
the postgresqlprovider module code:

```<code>@Module({
  imports: [
    SequelizeModule.forRootAsync({
      imports: [PostgresConfigModule],
      useFactory: async (postgresConfigService: PostgresConfigService) => ({
        dialect: 'postgres' as string,
        host: postgresConfigService.host as string,
        port: postgresConfigService.port,
        username: postgresConfigService.username,
        password: postgresConfigService.password,
        database: postgresConfigService.database,
        keepConnectionAlive: true,
        synchronize: true,
        autoLoadModels: true,
      }),
      inject: [PostgresConfigService],
    } as SequelizeModuleAsyncOptions),
  ],
})
export class PostgresDatabaseProviderModule {}
</code>```

It has nothing to do with the docker however the problem I found is with the synchronize option. Whenever it is false it works just fine and does not throw any error but when it is set to true then it gives the error that I mentioned above. I don't understand why this is happening.

Body:
This is the env file code that I am using to run the docker container:

POSTGRES_HOST="localhost"
POSTGRES_PORT=5432
POSTGRES_USERNAME="postgres"
POSTGRES_PASSWORD="123"
POSTGRES_DATABASE="netabe"

This is the docker.compose.yml file:

postgres:
    container_name: postgres_container
    image: 'postgres:latest'
    environment:
      POSTGRES_USER: ${POSTGRES_USERNAME}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DATABASE}
    ports:
      - 5432:5432
    networks:
      app_network:
        ipv4_address: 172.26.0.10
    restart: unless-stopped
    healthcheck:
      test: ['CMD', 'pg_isready -U postgres']
      interval: 5s
      timeout: 5s
      retries: 5
    volumes:
      - postgres:/data/postgres

It runs the postgres in docker container successfully but when I run the nest app then it says [Nest] 13620  - 05/01/2023, 6:56:41 pm   ERROR [SequelizeModule] Unable to connect to the database. Retrying (1).... I don't understand why this is happening. My postgres is also up and running and the database is also created in postgres but in the console it is throwing an error. The start:dev command: NODE_ENV=development nest start --watch

The postgresqlProvider is a different module and then I imported this in my app.module.ts file.
the postgresqlprovider module code:

@Module({
  imports: [
    SequelizeModule.forRootAsync({
      imports: [PostgresConfigModule],
      useFactory: async (postgresConfigService: PostgresConfigService) => ({
        dialect: 'postgres' as string,
        host: postgresConfigService.host as string,
        port: postgresConfigService.port,
        username: postgresConfigService.username,
        password: postgresConfigService.password,
        database: postgresConfigService.database,
        keepConnectionAlive: true,
        synchronize: true,
        autoLoadModels: true,
      }),
      inject: [PostgresConfigService],
    } as SequelizeModuleAsyncOptions),
  ],
})
export class PostgresDatabaseProviderModule {}

It has nothing to do with the docker however the problem I found is with the synchronize option. Whenever it is false it works just fine and does not throw any error but when it is set to true then it gives the error that I mentioned above. I don't understand why this is happening.


问:
How to get VSCode git api repository information
I'm trying to use VsCode API for Git and get repository git information.

I'm getting VsCode Git API like this

const extensions = vscode.extensions.getExtension('vscode.git');

if (!extensions) {
    return;
}

const gitExtension: GitExtension = extensions.exports;
const api: API = gitExtension.getAPI(1);

const repos = api.repositories;
```

The API instance is not null and working. But api.repositories always returns an empty array.

Can someone help me with this?

Body:
I'm trying to use VsCode API for Git and get repository git information.

I'm getting VsCode Git API like this

const extensions = vscode.extensions.getExtension('vscode.git');

if (!extensions) {
    return;
}

const gitExtension: GitExtension = extensions.exports;
const api: API = gitExtension.getAPI(1);

const repos = api.repositories;

The API instance is not null and working. But api.repositories always returns an empty array.

Can someone help me with this?


问:
Passing API post request using curl and curl apparently ignores decimal points?
I wrote an application in python to basically post some expenses to a service using its API.
Since their API doesn't support multipart/form-data posts in python using the requests library (a pain in the ass), I had to write the post using cURL.
My post data has a key with values that are numbers with decimal points. After the post is made, I see that the value of this key gets posted without the decimal point, which leads to a wrong expense post! How can I solve this? Here's the relevant code snippet:

#the data:

```<code>PARAMS = {
             "total_cost": netto(), #this is the function that returns the cost as float
             "created_at": date,
             "spent_date": date,
             "user": user,
             "units": int(1)}
</code>```

#the curl post with file:

```<code>file_path = "./path/myfile.pdf"

command = ["curl", "--location", "--request", "POST", url]
for key, value in headers.items():
   command += ["--header", f"{key}: {value}"]
for key, value in PARAMS.items():
   command += ["--form", f"{key}={value}"]
command += ["--form", f"receipt=@{file_path}"]
</code>```

#calling the curl command:

```<code>response = subprocess.run(command, stdout=subprocess.PIPE)
</code>```

So basically after the post is done, the "total_cost" value is posted without the decimal points. Why??

I don't know how to solve this and have never seen this issue.

Body:
I wrote an application in python to basically post some expenses to a service using its API.
Since their API doesn't support multipart/form-data posts in python using the requests library (a pain in the ass), I had to write the post using cURL.
My post data has a key with values that are numbers with decimal points. After the post is made, I see that the value of this key gets posted without the decimal point, which leads to a wrong expense post! How can I solve this? Here's the relevant code snippet:

#the data:

PARAMS = {
             "total_cost": netto(), #this is the function that returns the cost as float
             "created_at": date,
             "spent_date": date,
             "user": user,
             "units": int(1)}

#the curl post with file:

file_path = "./path/myfile.pdf"

command = ["curl", "--location", "--request", "POST", url]
for key, value in headers.items():
   command += ["--header", f"{key}: {value}"]
for key, value in PARAMS.items():
   command += ["--form", f"{key}={value}"]
command += ["--form", f"receipt=@{file_path}"]

#calling the curl command:

response = subprocess.run(command, stdout=subprocess.PIPE)

So basically after the post is done, the "total_cost" value is posted without the decimal points. Why??

I don't know how to solve this and have never seen this issue.


问:
cucumber tests are not running with allure-cucumber7-jvm dependency
cucumber dependencies

```<code>    implementation group: 'io.cucumber', name: 'cucumber-spring', version: '7.5.0'
    implementation group: 'io.cucumber', name: 'cucumber-java', version: '7.5.0'
    //implementation group: 'io.qameta.allure', name: 'allure-cucumber7-jvm', version: '2.20.1'
</code>```

Gradle task

```<code>task cucumber(type: Test) {
    logger.lifecycle("Run cucumber gradle task. ")
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            var cucumberTags = "@DefaultTag"
            if (project.hasProperty('cucumberTags')) {
                logger.lifecycle("THIS IS MAAAAAAAAAAAAAAAAAAAAAARK")
                cucumberTags = project.property('cucumberTags');
            }
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            logger.lifecycle("Run cucumber tests by tag: " + cucumberTags)
            args = [
                   // '--plugin', 'io.qameta.allure.cucumber7jvm.AllureCucumber7Jvm',
                    '--tags', cucumberTags
            ]
            logger.lifecycle("Cucumber args: " + args.join(" "))
        }
    }
}
</code>```

Cucumber context configuration class

```<code>@Slf4j
@SpringBootTest
@Scope("cucumber.glue")
@CucumberContextConfiguration
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
                      classes = GeneralConfiguration.class)
public class CucumberContext {

}
</code>```

gradle command ./gradlew cucumber -PcucumberTags=@MyTag\

so, the thing is:
when allure-cucumber7-jvm dependency is commented, tests are running both from Intellij UI and via gradle cli.
when dependency is uncommented and gradle project reloaded, i still can run the test via Intellij UI, but not via gradle task

```<code>> Configure project :
Run cucumber gradle task.

> Task :cucumber
THIS IS MAAAAAAAAAAAAAAAAAAAAAARK
Run cucumber tests by tag: @MyTag
Cucumber args: --tags @MyTag

0 Scenarios
0 Steps
0m1.683s
</code>```

But why?

I didn't find much examples with allure-cucumber7-jvm,
no any specific instructions on allure github as well.
I also tried to add dependency 'io.qameta.allure', name: 'allure-cucumber-jvm', version: '2.7.0'
tests are running, but, obviously, while i'm adding the plugin, it fails because of incopatibility of those cucumber and allure versions

Body:
cucumber dependencies

    implementation group: 'io.cucumber', name: 'cucumber-spring', version: '7.5.0'
    implementation group: 'io.cucumber', name: 'cucumber-java', version: '7.5.0'
    //implementation group: 'io.qameta.allure', name: 'allure-cucumber7-jvm', version: '2.20.1'

Gradle task

task cucumber(type: Test) {
    logger.lifecycle("Run cucumber gradle task. ")
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            var cucumberTags = "@DefaultTag"
            if (project.hasProperty('cucumberTags')) {
                logger.lifecycle("THIS IS MAAAAAAAAAAAAAAAAAAAAAARK")
                cucumberTags = project.property('cucumberTags');
            }
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            logger.lifecycle("Run cucumber tests by tag: " + cucumberTags)
            args = [
                   // '--plugin', 'io.qameta.allure.cucumber7jvm.AllureCucumber7Jvm',
                    '--tags', cucumberTags
            ]
            logger.lifecycle("Cucumber args: " + args.join(" "))
        }
    }
}

Cucumber context configuration class

@Slf4j
@SpringBootTest
@Scope("cucumber.glue")
@CucumberContextConfiguration
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
                      classes = GeneralConfiguration.class)
public class CucumberContext {

}

gradle command ./gradlew cucumber -PcucumberTags=@MyTag\

so, the thing is:
when allure-cucumber7-jvm dependency is commented, tests are running both from Intellij UI and via gradle cli.
when dependency is uncommented and gradle project reloaded, i still can run the test via Intellij UI, but not via gradle task

> Configure project :
Run cucumber gradle task.

> Task :cucumber
THIS IS MAAAAAAAAAAAAAAAAAAAAAARK
Run cucumber tests by tag: @MyTag
Cucumber args: --tags @MyTag

0 Scenarios
0 Steps
0m1.683s

But why?

I didn't find much examples with allure-cucumber7-jvm,
no any specific instructions on allure github as well.
I also tried to add dependency 'io.qameta.allure', name: 'allure-cucumber-jvm', version: '2.7.0'
tests are running, but, obviously, while i'm adding the plugin, it fails because of incopatibility of those cucumber and allure versions


问:
How can I configure the date format in strapi (version 4) for the admin panel?
In the admin panel of the cms Strapi (version 4!) the date is shown in a very long format:

Is it possible to change this to e.g. YYYY-MM-DD HH:MM format?

I have tried the way described here but that does not work in V4.
The issue does not seem to be solved yet. Is anybody out there with a good workaround?


问:
Yolov4 Darknet | Continue training with a ready-made weight
I have a weight file already trained. I want to add more images to the dataset and improve recognition. Is it possible to continue training with a ready-made weight, if so, how or will I have to train again?</p>


问:
How to run two pyspark udfs in parallel
I have 2 pyspark UDFs performing some actions, how to run those UDFs in parallel and doing this will result in enhancing performance of the code?</p>

Title: How to run two pyspark udfs in parallel


问:
Why my Vue3 Webcomponent has no css in its shadow dom
I have built a Vue3 web component and try to embed it in an other project.

This is my main.js for building the web component.

import {createApp, getCurrentInstance, h} from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
import i18n from './services/i18n'
import {router} from '@/helpers'
import VueApexCharts from "vue3-apexcharts";

import "bootstrap/dist/css/bootstrap.min.css"
import "bootstrap"
import './assets/main.css'
import './assets/sweetalert2.min.css'
import contextmenu from "v-contextmenu";
import "v-contextmenu/dist/themes/default.css";
import {defineCustomElement} from "vue";

const clickOutside = {
    beforeMount: (el, binding) => {
        el.clickOutsideEvent = event => {
            // here I check that click was outside the el and his children
            if (!(el == event.target || el.contains(event.target))) {
                // and if it did, call method provided in attribute value
                binding.value();
            }
        };
        document.addEventListener("click", el.clickOutsideEvent);
    },
    unmounted: el => {
        document.removeEventListener("click", el.clickOutsideEvent);
    },
};

const pinia = createPinia()

export const createElementInstance = ({
                                          component = null,
                                          props = [],
                                          sharedStoreInstance = false,
                                          plugins = [],
                                          renderOptions = {}
                                      } = {}) => {
    return defineCustomElement({
        props: props,
        setup() {
            const app = createApp();

            if (!sharedStoreInstance) {
                const pinia = createPinia();
                app.use(pinia);
            }

            app
                .use(router)
                .use(VueApexCharts)
                .use(pinia)
                .use(contextmenu)
                .use(i18n)
                .directive("click-outside", clickOutside)

            const inst = getCurrentInstance();
            Object.assign(inst.appContext, app._context);
            Object.assign(inst.provides, app._context.provides);
        },
        render: () => h(component, renderOptions)
    })
}

const config = {
    component: App,
    props: {title: String},
    sharedStoreInstance: true,
    renderOptions: {ref: 'component'}
}

customElements.define('ma-ansicht', createElementInstance(config, {
    shadow: true
}));

```
<p>I have 2 files to import in the other project</p>
<pre class="lang-html prettyprint-override"><code><script type="module" crossorigin src="/assets/index.3f46efca.js"></script>
<link rel="stylesheet" href="/assets/index.ac2fca12.css">
</code>```

The shadow dom of the component doesnt have any css and the generated css file appears in the header of the skeleton application.

How can I build a Web Component which includes my css in the shadow dom?

I have tried different build options like npm run build and

```<code>vue-cli-service build --target lib --name ma-ansicht src/main.js
</code>```

I have tried to embed the wc in different skeleton apps

I expect that my app as web component is fully functional and styled

Body:
I have built a Vue3 web component and try to embed it in an other project.

This is my main.js for building the web component.

import {createApp, getCurrentInstance, h} from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
import i18n from './services/i18n'
import {router} from '@/helpers'
import VueApexCharts from "vue3-apexcharts";

import "bootstrap/dist/css/bootstrap.min.css"
import "bootstrap"
import './assets/main.css'
import './assets/sweetalert2.min.css'
import contextmenu from "v-contextmenu";
import "v-contextmenu/dist/themes/default.css";
import {defineCustomElement} from "vue";

const clickOutside = {
    beforeMount: (el, binding) => {
        el.clickOutsideEvent = event => {
            // here I check that click was outside the el and his children
            if (!(el == event.target || el.contains(event.target))) {
                // and if it did, call method provided in attribute value
                binding.value();
            }
        };
        document.addEventListener("click", el.clickOutsideEvent);
    },
    unmounted: el => {
        document.removeEventListener("click", el.clickOutsideEvent);
    },
};

const pinia = createPinia()

export const createElementInstance = ({
                                          component = null,
                                          props = [],
                                          sharedStoreInstance = false,
                                          plugins = [],
                                          renderOptions = {}
                                      } = {}) => {
    return defineCustomElement({
        props: props,
        setup() {
            const app = createApp();

            if (!sharedStoreInstance) {
                const pinia = createPinia();
                app.use(pinia);
            }

            app
                .use(router)
                .use(VueApexCharts)
                .use(pinia)
                .use(contextmenu)
                .use(i18n)
                .directive("click-outside", clickOutside)

            const inst = getCurrentInstance();
            Object.assign(inst.appContext, app._context);
            Object.assign(inst.provides, app._context.provides);
        },
        render: () => h(component, renderOptions)
    })
}

const config = {
    component: App,
    props: {title: String},
    sharedStoreInstance: true,
    renderOptions: {ref: 'component'}
}

customElements.define('ma-ansicht', createElementInstance(config, {
    shadow: true
}));

I have 2 files to import in the other project

<link rel="stylesheet" href="/assets/index.ac2fca12.css">

The shadow dom of the component doesnt have any css and the generated css file appears in the header of the skeleton application.

How can I build a Web Component which includes my css in the shadow dom?

I have tried different build options like npm run build and

vue-cli-service build --target lib --name ma-ansicht src/main.js

I have tried to embed the wc in different skeleton apps

I expect that my app as web component is fully functional and styled


问:
NameError: name 'X_train' is not defined....tried in spyder too
have been trying to run this statement in colab but it's always showing the NameError

```<code>from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.33,random_state = 42)
</code>```

pl help to solve this problem

Body:
have been trying to run this statement in colab but it's always showing the NameError

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.33,random_state = 42)

pl help to solve this problem


问:
In React, when I'm adding a new item in an array of objects, it gets rendered, but the onClick event won't trigger, why is that?
I'm building a link list, and I have a list of objects that represent sub-categories.

They're rendered that way:

```<code>subCategories.map(subCat => (
<CustomLinkWrapper>
 <CheckboxWrapper
  onClick={() => findAndToggleLinkInModal(link.name)}
 >
 <ModalCheckbox
  aria-label={`Select ${link.name}`}
  value={link.name}
  isChecked={link.checked}
  theme={theme}
 />
 <StackedText>
   <div>
    <p>Link name</p>
    {link.name}
   </div>
   <div>
    <p>URL</p>
    <Tooltip label={link.link}>{link.link}</Tooltip>
  </div>
 </StackedText>
</CheckboxWrapper>
<TripleDot
  ref={anchorRef}
  onClick={() => {
   setAddNewLink(false);
   handleTogglePopover(link.name, link.url, link.name);
  }}
>
 ...
</TripleDot>
<PopoverDialog
 aria-labelledby="linkActions"
 anchorRef={anchorRef}
 isOpen={isPopoverOpen}
 onClose={handleTogglePopover}
 placement={'auto'}
>
<List>
 <ListItem
  size={'big'}
  before={<Icon icon={mdiFileEdit} />}
  onItemSelected={handleClickEditOwnLink}
 >
  Edit the link
 </ListItem>
 <ListItem
  size={'big'}
  before={<Icon icon={mdiFileRemove} />}
  onItemSelected={() => {
   console.log('test');
   removeLinkFromOwnLink(link.name);
  }}
 >
   Remove the link
 </ListItem>
</List>
</PopoverDialog>
</CustomLinkWrapper>
))
</code>```

They have an onItemSelected() prop that should trigger on click. It works initially when the page renders, and the list is its first own version. But when I add a new item to the list, both <ListItem />'s onItemSelected don't work. I have no idea why, I've been on it for a day or so and it's getting frustrating.

I've tried adding an onClickEdit property to the links, because maybe on render, the onClick just wasn't present. But it didn't work. The onClick on the <TripleDot /> is working fine, but not the onClick on the <ListItem />, so it didn't change much.

Initially that code was in the main file with all the functions, but I thought maybe it wasn't rendering properly, so I copied/pasted the code to a child component, but it didn't work either.

Body:
I'm building a link list, and I have a list of objects that represent sub-categories.

They're rendered that way:

subCategories.map(subCat => (
<CustomLinkWrapper>
 <CheckboxWrapper
  onClick={() => findAndToggleLinkInModal(link.name)}
 >
 <ModalCheckbox
  aria-label={`Select ${link.name}`}
  value={link.name}
  isChecked={link.checked}
  theme={theme}
 />
 <StackedText>

Link name

    {link.name}

URL

    <Tooltip label={link.link}>{link.link}</Tooltip>

 </StackedText>
</CheckboxWrapper>
<TripleDot
  ref={anchorRef}
  onClick={() => {
   setAddNewLink(false);
   handleTogglePopover(link.name, link.url, link.name);
  }}
>
 ...
</TripleDot>
<PopoverDialog
 aria-labelledby="linkActions"
 anchorRef={anchorRef}
 isOpen={isPopoverOpen}
 onClose={handleTogglePopover}
 placement={'auto'}
>
<List>
 <ListItem
  size={'big'}
  before={<Icon icon={mdiFileEdit} />}
  onItemSelected={handleClickEditOwnLink}
 >
  Edit the link
 </ListItem>
 <ListItem
  size={'big'}
  before={<Icon icon={mdiFileRemove} />}
  onItemSelected={() => {
   console.log('test');
   removeLinkFromOwnLink(link.name);
  }}
 >
   Remove the link
 </ListItem>
</List>
</PopoverDialog>
</CustomLinkWrapper>
))

They have an onItemSelected() prop that should trigger on click. It works initially when the page renders, and the list is its first own version. But when I add a new item to the list, both <ListItem />'s onItemSelected don't work. I have no idea why, I've been on it for a day or so and it's getting frustrating.

I've tried adding an onClickEdit property to the links, because maybe on render, the onClick just wasn't present. But it didn't work. The onClick on the <TripleDot /> is working fine, but not the onClick on the <ListItem />, so it didn't change much.

Initially that code was in the main file with all the functions, but I thought maybe it wasn't rendering properly, so I copied/pasted the code to a child component, but it didn't work either.


问:
NextJs Cache on Kubernetes
We have a large NextJs project that works with server-side-rendering as it generates routes dynamically. It is dockerized and running on Kubernetes with autoscaling, so depending on the amount of traffic the amount of replicas varies from 3 to 10.
Every time a new replica is created (by autoscale or by a new deployment), it does not contain inside the cache of the pages or images, so we experience two problems, the rendering times can be more than 10 seconds, and the other problem is the excessive consumption of pod resources (0.8 cpu, 800 mb memory) during the generation of the cache.

We use usually two fetch methods. getStaticProps and getServerSideProps.
The issue only appears on getServerSideProps and the first render of getStaticProps as we don't use pre-cache with getStaticPaths

Is there any way to store that cache in a PV + PVC? Or has anyone found an effective way to mitigate these two problems?

Stack:

Next 13.0.4

Docker imageBase node:16.14-alpine3.15

Google Cloud Platform - GKE

Instance Type: e2-standard-4 (4 CPU, 16 GB Ram)

We increased the resources allocated to the container in the Pod and tested with n2-standard-4 instances, which resulted in a minimal decrease in cache generation time, but not a difference that we are satisfied with.

Title: NextJs Cache on Kubernetes


问:
How to link many external .lib to visual studio 2022 (windows)?
I usually work with ubuntu, but for a project with my student, we are learning how to use visual studio on windows. I have already learned how to link an external .lib to the visual studio project with the three steps:

Give the path to the .h

Give the path to the .lib folder

Give the name of the .lib to be added to the project

My issue is with the last point. I want to work with ROOT, whose lib folder contains about 100 .lib, so I don't want to copy/paste 100 names. Is there a way to give at once all the .lib contained in the lib folder?

With ubuntu I simply use a Makefile with the typical lines such as "EXT_LIBS := $(shell root-config --libs)"

Thanks for your help,
Benjamin

I did not try anything. I have simply no idea on how to o that.


问:
R+natural earth: download bounding box fails
I am experiencing some trouble with a command that used to work in the past to download and use a bounding box from the natural earth website.
See this snippet

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(rnaturalearth)
library(sf)
#> Linking to GEOS 3.9.0, GDAL 3.2.2, PROJ 7.2.1; sf_use_s2() is TRUE

bb <- ne_download(type = "wgs84_bounding_box", category = "physical",
                  returnclass = "sf")
#> Warning in utils::download.file(file.path(address),
#> zip_file <- tempfile()): cannot open URL
#> 'https://www.naturalearthdata.com/http/www.naturalearthdata.com/download/110m/physical/ne_110m_wgs84_bounding_box.zip':
#> HTTP status was '404 Not Found'
#> Error in utils::download.file(file.path(address), zip_file <- tempfile()): cannot open URL 'http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_wgs84_bounding_box.zip'

sessionInfo()
#> R version 4.2.2 (2022-10-31)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Debian GNU/Linux 11 (bullseye)
#>
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
#>
#> locale:
#>  [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
#>  [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
#>  [5] LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8
#>  [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> other attached packages:
#> [1] sf_1.0-9            rnaturalearth_0.1.0 dplyr_1.0.10
#>
#> loaded via a namespace (and not attached):
#>  [1] Rcpp_1.0.9         compiler_4.2.2     pillar_1.8.1       highr_0.9
#>  [5] class_7.3-20       R.methodsS3_1.8.2  R.utils_2.12.1     tools_4.2.2
#>  [9] digest_0.6.30      lattice_0.20-45    evaluate_0.18      lifecycle_1.0.3
#> [13] tibble_3.1.8       R.cache_0.16.0     pkgconfig_2.0.3    rlang_1.0.6
#> [17] reprex_2.0.2       cli_3.4.1          DBI_1.1.3          yaml_2.3.6
#> [21] xfun_0.35          fastmap_1.1.0      e1071_1.7-12       withr_2.5.0
#> [25] styler_1.8.0       stringr_1.5.0      knitr_1.41         generics_0.1.3
#> [29] fs_1.5.2           vctrs_0.5.1        grid_4.2.2         classInt_0.4-8
#> [33] tidyselect_1.2.0   glue_1.6.2         R6_2.5.1           fansi_1.0.3
#> [37] rmarkdown_2.17     sp_1.5-1           purrr_1.0.0        magrittr_2.0.3
#> [41] units_0.8-0        htmltools_0.5.3    assertthat_0.2.1   KernSmooth_2.23-20
#> [45] utf8_1.2.2         proxy_0.4-27       stringi_1.7.8      R.oo_1.25.0
```

Created on 2023-01-05 with reprex v2.0.2

The bounding box is available at the link

https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_wgs84_bounding_box.zip

but it seems that the ne_download command generates the wrong link.
Two questions to conclude:

is this a bug of the rnaturalearth package?

is there any workaround if I manually download the zip file in the working directory?

Many thanks!

Body:
I am experiencing some trouble with a command that used to work in the past to download and use a bounding box from the natural earth website.
See this snippet

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(rnaturalearth)
library(sf)
#> Linking to GEOS 3.9.0, GDAL 3.2.2, PROJ 7.2.1; sf_use_s2() is TRUE

bb <- ne_download(type = "wgs84_bounding_box", category = "physical",
                  returnclass = "sf")
#> Warning in utils::download.file(file.path(address),
#> zip_file <- tempfile()): cannot open URL
#> 'https://www.naturalearthdata.com/http/www.naturalearthdata.com/download/110m/physical/ne_110m_wgs84_bounding_box.zip':
#> HTTP status was '404 Not Found'
#> Error in utils::download.file(file.path(address), zip_file <- tempfile()): cannot open URL 'http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_wgs84_bounding_box.zip'

sessionInfo()
#> R version 4.2.2 (2022-10-31)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Debian GNU/Linux 11 (bullseye)
#>
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
#>
#> locale:
#>  [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
#>  [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
#>  [5] LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8
#>  [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> other attached packages:
#> [1] sf_1.0-9            rnaturalearth_0.1.0 dplyr_1.0.10
#>
#> loaded via a namespace (and not attached):
#>  [1] Rcpp_1.0.9         compiler_4.2.2     pillar_1.8.1       highr_0.9
#>  [5] class_7.3-20       R.methodsS3_1.8.2  R.utils_2.12.1     tools_4.2.2
#>  [9] digest_0.6.30      lattice_0.20-45    evaluate_0.18      lifecycle_1.0.3
#> [13] tibble_3.1.8       R.cache_0.16.0     pkgconfig_2.0.3    rlang_1.0.6
#> [17] reprex_2.0.2       cli_3.4.1          DBI_1.1.3          yaml_2.3.6
#> [21] xfun_0.35          fastmap_1.1.0      e1071_1.7-12       withr_2.5.0
#> [25] styler_1.8.0       stringr_1.5.0      knitr_1.41         generics_0.1.3
#> [29] fs_1.5.2           vctrs_0.5.1        grid_4.2.2         classInt_0.4-8
#> [33] tidyselect_1.2.0   glue_1.6.2         R6_2.5.1           fansi_1.0.3
#> [37] rmarkdown_2.17     sp_1.5-1           purrr_1.0.0        magrittr_2.0.3
#> [41] units_0.8-0        htmltools_0.5.3    assertthat_0.2.1   KernSmooth_2.23-20
#> [45] utf8_1.2.2         proxy_0.4-27       stringi_1.7.8      R.oo_1.25.0

Created on 2023-01-05 with reprex v2.0.2

The bounding box is available at the link

https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_wgs84_bounding_box.zip

but it seems that the ne_download command generates the wrong link.
Two questions to conclude:

is this a bug of the rnaturalearth package?

is there any workaround if I manually download the zip file in the working directory?

Many thanks!


问:
validate object of array of objects using yup Javascript
I am using yup to validate an array of objects, every object of the array have a specific shape

shape of the array of objects : articles:[{offerId:'',url:'',site:'',imgPath:''}]}
an error message must be displayed under every missing field

I tried this code :

```<code>articles: yup
            .array()
            .min(1, '${path}  is required (min one)')
            .of(
                yup.object({
                    offerId: yup.number().required('Please enter offerid'),
                    url: yup.string().required('Please enter url').matches(URL, 'Enter correct url!'),
                    site: yup.string().required('Please enter site').matches(URL, 'Enter correct url!'),
                    imgPath: yup.string().required('Please enter imgPath').matches(URL, 'Enter correct url!')
                })
            ).compact((v) => !v.offerId && !v.url && !v.site && !v.imgPath)
</code>```

the error message of min 1 is displayed but the other error messages are not
as well there is an error occured when i am trying to add an article :

Objects are not valid as a React child (found : object with keys {url,site,imgPath}) if you meant to render a collection of children , use an array instead.
```

Body:
I am using yup to validate an array of objects, every object of the array have a specific shape

shape of the array of objects : articles:[{offerId:'',url:'',site:'',imgPath:''}]}
an error message must be displayed under every missing field

I tried this code :

articles: yup
            .array()
            .min(1, '${path}  is required (min one)')
            .of(
                yup.object({
                    offerId: yup.number().required('Please enter offerid'),
                    url: yup.string().required('Please enter url').matches(URL, 'Enter correct url!'),
                    site: yup.string().required('Please enter site').matches(URL, 'Enter correct url!'),
                    imgPath: yup.string().required('Please enter imgPath').matches(URL, 'Enter correct url!')
                })
            ).compact((v) => !v.offerId && !v.url && !v.site && !v.imgPath)

the error message of min 1 is displayed but the other error messages are not
as well there is an error occured when i am trying to add an article :

Objects are not valid as a React child (found : object with keys {url,site,imgPath}) if you meant to render a collection of children , use an array instead.


问:
Problem getting controller host launching AppDynamics
I'm configuring my AppDynamics agent for Python and I'm getting the following error

Error XML Controller Info Resolver found invalid controller host information [null] in controller-info.xml; Please specify a valid value if it is not already set in system properties

What is more strange to me is that the controller host information seems to be null, although I'm passing it. The rest of the information, like the tier or the app name or the access key are read and processed properly.

I've tried two setups to launch this.

Using a configuration file and launching my application with  pyagent run -c <path to appdynamics.cfg> -- python3 -B <path to main file>

My appdynamics.cfg is as follows

```<code>[agent]
app = <app name>
tier = <tier>
node = <node>
nodereuse = true
nodereuseprefix = <prefix>

[controller]
host = <host>
port = 443
ssl = on
account = <account>
accesskey = <access_key>
</code>```

Using env variables:

```<code>APPDYNAMICS_AGENT_ACCOUNT_NAME=<account_name>
APPDYNAMICS_AGENT_NODE_NAME=<node>
APPDYNAMICS_CONTROLLER_HOST_NAME=<controller_host_name>
APPDYNAMICS_AGENT_ACCOUNT_ACCESS_KEY=<access key>
APPDYNAMICS_AGENT_TIER_NAME=<tier>
APPDYNAMICS_APP_NAME=<app_name>
APPDYNAMICS_AGENT_APPLICATION_NAME=<agent_application_name>
</code>```

pyagent run -- python3 -B <path to main file>

In both cases the error is the one above.

The controller-info.xml that I can see doesn't look correct at a first sight, but I'm not sure how it should be filled.

```<code><?xml version="1.0" ?>
<controller-info>
    <enable-orchestration>false</enable-orchestration>
    <use-simple-hostname>false</use-simple-hostname>

    <!-- Before you enable Use Encrypted Credentials, see the instructions on how to initialize the
    Secure Credential Store:
    https://docs.appdynamics.com/display/LATEST/Encrypt+Credentials+for+Agent+Configuration
    Set Use Encrypted Credentials to "True" to configure the agent to use credentials encrypted
    with the Secure Credential Store. When you enable Use Encrypted Credentials, you must supply the
    Credential Store Filename and the obfuscated Credential Store Password. -->
    <use-encrypted-credentials />
    <!-- Full qualified path name for the SCS-KeyStore file name. -->
    <credential-store-filename />
    <!-- Password for the 'Secure Credential Store' (SCS). This password must be obfuscated. -->
    <credential-store-password />

    <!-- If this value is set to true, it indicates that the controller is expecting to perform
    Client-Authentication. If this value is false or undefined, all subsequent asymmetric are considered
    meaningless, hence ignored. -->
    <use-ssl-client-auth>false</use-ssl-client-auth>
    <!-- Asymmetric keystore filename -->
    <asymmetric-keystore-filename />
    <!-- Asymmetric keystore password - Note, this password must be encrypted, if scs is enabled. -->
    <asymmetric-keystore-password />
    <!-- Asymmetric key password - Note, this password must be encrypted, if scs is enabled. -->
    <asymmetric-key-password />
    <!-- Asymmetric key alias - this alias must be set only if keystore has multiple keys for deterministic key selection.-->
    <asymmetric-key-alias />

    <!-- If the Controller is running in multi-tenant mode, specify the account name. For both
    single-tenant and multi-tenant Controllers, specify the account access key. -->
    <!-- This can be overridden with an environment variable 'APPDYNAMICS_AGENT_ACCOUNT_ACCESS_KEY' or
    the system property '-Dappdynamics.agent.accountAccessKey'
    This account-access-key must be encrypted if 'use-encrypted-credentials' is set to true -->
    <!--  For Auto Agent Registration specify the application name, tier name,
          and node name. If the application, tier, or node does not
          exist already it will be created. -->
    <force-agent-registration>false</force-agent-registration>

    <!-- Sets the runtime directory for all runtime files (logs, transaction configuration) for nodes
    that use this agent installation. If this property is specified, all agent logs are written to
    <Agent-Runtime-Directory>/logs/node-name and transaction configuration is written to the
    <Agent-Runtime-Directory>/conf/node-name directory.
    This can be overridden with an environment variable 'APPDYNAMICS_AGENT_BASE_DIR' or or the system
    property '-Dappdynamics.agent.runtime.dir-->
    </controller-info>
</code>```

Body:
I'm configuring my AppDynamics agent for Python and I'm getting the following error

Error XML Controller Info Resolver found invalid controller host information [null] in controller-info.xml; Please specify a valid value if it is not already set in system properties

What is more strange to me is that the controller host information seems to be null, although I'm passing it. The rest of the information, like the tier or the app name or the access key are read and processed properly.

I've tried two setups to launch this.

Using a configuration file and launching my application with  pyagent run -c <path to appdynamics.cfg> -- python3 -B <path to main file>

My appdynamics.cfg is as follows

[agent]
app = <app name>
tier = <tier>
node = <node>
nodereuse = true
nodereuseprefix = <prefix>

[controller]
host = <host>
port = 443
ssl = on
account = <account>
accesskey = <access_key>

Using env variables:

APPDYNAMICS_AGENT_ACCOUNT_NAME=<account_name>
APPDYNAMICS_AGENT_NODE_NAME=<node>
APPDYNAMICS_CONTROLLER_HOST_NAME=<controller_host_name>
APPDYNAMICS_AGENT_ACCOUNT_ACCESS_KEY=<access key>
APPDYNAMICS_AGENT_TIER_NAME=<tier>
APPDYNAMICS_APP_NAME=<app_name>
APPDYNAMICS_AGENT_APPLICATION_NAME=<agent_application_name>

pyagent run -- python3 -B <path to main file>

In both cases the error is the one above.

The controller-info.xml that I can see doesn't look correct at a first sight, but I'm not sure how it should be filled.

<?xml version="1.0" ?>
<controller-info>
    <enable-orchestration>false</enable-orchestration>
    <use-simple-hostname>false</use-simple-hostname>

    <use-encrypted-credentials />

    <credential-store-filename />

    <credential-store-password />

    <use-ssl-client-auth>false</use-ssl-client-auth>

    <asymmetric-keystore-filename />

    <asymmetric-keystore-password />

    <asymmetric-key-password />

    <asymmetric-key-alias />

    <force-agent-registration>false</force-agent-registration>

    </controller-info>


问:
The order of script execution and layout?
Script execution will block html parsing, so Layout should be placed after script execution.Why is the Layout in front of the performance panel?

index.html

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./index.css" />

hello

world

```

index.js

console.log("hello world!");

index.css

* {padding: 0;margin: 0;}

And then click

Body:
Script execution will block html parsing, so Layout should be placed after script execution.Why is the Layout in front of the performance panel?

index.html

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./index.css" />

hello

world

index.js

console.log("hello world!");

index.css

* {padding: 0;margin: 0;}

And then click


问:
UE5.1 UMG Blueprint is not visible on Android
After moving from UE5.0 to UE5.1, none of my UMG blueprints appear on screen after packaging for Android. I have set up everything according to the UE5.1 documentation.

Here's the UMG spawning code in my Player Controller class, I can confirm the rest of the code to the right works as intended.
enter image description here

Any ideas what might cause this? Thanks


问:
ValueError: Input 0 of layer "model_1" is incompatible with the layer
I want to deploy my saved model to streamlit app. But I get the following error, though I resized the image using opencv. would you please kindly help me!

The code:

```<code>model.load_weights("BrainTumorPredictor.h5")
img = cv.imread ("mri-magnetic-resonance-imaging-scan-device-mri-2021-09-02-07-55-40-utc-scaled.jpg")
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
height = 224
width = 224
resized_img = cv.resize (img, (height, width))
result = model.predict (resized_img)
print (result)`
</code>```

error:
ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(32, 224, 3)

Body:
I want to deploy my saved model to streamlit app. But I get the following error, though I resized the image using opencv. would you please kindly help me!

The code:

model.load_weights("BrainTumorPredictor.h5")
img = cv.imread ("mri-magnetic-resonance-imaging-scan-device-mri-2021-09-02-07-55-40-utc-scaled.jpg")
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
height = 224
width = 224
resized_img = cv.resize (img, (height, width))
result = model.predict (resized_img)
print (result)`

error:
ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(32, 224, 3)


问:
Facebook Ads Event deduplication "You may still be sending test events" issue
Our  goal is to send a search event from our server and from Facebook's pixel(GTM) and de-duplicate them.

Our issue is that the external_id from pixel isn't populating as the other parameters    and affect on the overlap percentage.

There is an issue with test_evet_code, but I checked and I cannot find any test event codes in our GTM

I found this issue in GitHub and i think its relate to my issue


问:
Is there a way to download videos WITH sound with instaloader?
I'm trying to use instaloader to download instagram videos (reels) via "shortcode" of those videos (essentially the link to the video) this is my current approach:

import instaloader

L = instaloader.Instaloader()

post = instaloader.Post.from_shortcode(L.context, "SHORTCODE")
L.download_post(post, target=post.owner_username)
```

it's pretty simple but it simply does not download videos with audio. Is there a way to fix this/prevent this in instaloader or are there any different, better libraries that could be used for this task?

Body:
I'm trying to use instaloader to download instagram videos (reels) via "shortcode" of those videos (essentially the link to the video) this is my current approach:

import instaloader

L = instaloader.Instaloader()

post = instaloader.Post.from_shortcode(L.context, "SHORTCODE")
L.download_post(post, target=post.owner_username)

it's pretty simple but it simply does not download videos with audio. Is there a way to fix this/prevent this in instaloader or are there any different, better libraries that could be used for this task?


问:
How to properly configure Entity Framework Core and SQL Server Charset / Encoding?
My application is using EF Core 6.0.5 and connecting to SQL Server Database. I'm facing an issue with a specific character in the database that can't be read correctly.

When the application reads the character Ó it is transformed in the encoding A\u0093. Other special characters like ã and ç are correct, what seems odd.

The Database Collation is: SQL_Latin1_General_CP1_CI_AS

The column data type is: nvarchar()

The system System.Text.Encoding Default property is: System.Text.UTF8Encoding+UTF8EncodingSealed


问:
how to instrument java code hosted in aws ecs instance and aws lambda with context propogation using opentelemetry
I want to instrument my java code hosted in aws ecs instance (producer) and aws lambda (consumer) with context propagation using opentelemetry.

Tried auto instrumentation which works fine for the producer and consumer as a seperate entity, there is no continuity of trace from producer till consumer


问:
Units of measurements in PyQt5 Combbox
I have a GUI where the user can input a value into a spinbox. I want the following things to happen:

If the user didn't specify a unit while entering the value I want the spinbox to add the units behind the value.

If the user specified a unit other than the default I want it to automatically be converted to the default unit. E.g.: 1 m -> 1000 mm

(Optional) When I access the value of the spibox I want to get the raw float value back, not a string where I have to cut the unit and convert it to a float.

I want the spinboxes to behave like the spinboxes in Photoshop, Illustrator etc.

I guess I could write a conversion function with a lot of checks which gets signaled and then use a different function which cuts the units every time I access the values, but this seems very inconvenient.

It has been suggested that I create a new class named UnitSpinBox which inherits from QDoubleSpinBox. This is roughly the code snippet they suggested:

class UnitSpinBox(QDoubleSpinBox):
    def __init__(self, unit, *args, **kwargs):
        self.unit = unit
        super().__init__(*args, **kwargs)

    def textFromValue(self, value):
        return f"{value} {self.unit}"

    def valueFromText(self, text):
        text = text.replace(",", ".")
        try:
            value, unit = text.split()
            # Convert the unit to the default unit if necessary
            if unit != self.unit:
                value = self.convertToDefaultUnit(value, unit)
                print("CONVERTED!")
            return float(value)

        except:
            return float(text)

    def convertToDefaultUnit(self, value, unit):
        if unit == "m":
            value = value * 1000

        return value
```

The unit gets displayed correctly but when I try to write into the spinbox it won't accept space or letter characters which makes it impossible for me to insert a value with a different unit.

Also the conversion function doesn't change the text displayed in the spinbox.

Title: Units of measurements in PyQt5 Combbox

Body:
I have a GUI where the user can input a value into a spinbox. I want the following things to happen:

If the user didn't specify a unit while entering the value I want the spinbox to add the units behind the value.

If the user specified a unit other than the default I want it to automatically be converted to the default unit. E.g.: 1 m -> 1000 mm

(Optional) When I access the value of the spibox I want to get the raw float value back, not a string where I have to cut the unit and convert it to a float.

I want the spinboxes to behave like the spinboxes in Photoshop, Illustrator etc.

I guess I could write a conversion function with a lot of checks which gets signaled and then use a different function which cuts the units every time I access the values, but this seems very inconvenient.

It has been suggested that I create a new class named UnitSpinBox which inherits from QDoubleSpinBox. This is roughly the code snippet they suggested:

class UnitSpinBox(QDoubleSpinBox):
    def __init__(self, unit, *args, **kwargs):
        self.unit = unit
        super().__init__(*args, **kwargs)

    def textFromValue(self, value):
        return f"{value} {self.unit}"

    def valueFromText(self, text):
        text = text.replace(",", ".")
        try:
            value, unit = text.split()
            # Convert the unit to the default unit if necessary
            if unit != self.unit:
                value = self.convertToDefaultUnit(value, unit)
                print("CONVERTED!")
            return float(value)

        except:
            return float(text)

    def convertToDefaultUnit(self, value, unit):
        if unit == "m":
            value = value * 1000

        return value

The unit gets displayed correctly but when I try to write into the spinbox it won't accept space or letter characters which makes it impossible for me to insert a value with a different unit.

Also the conversion function doesn't change the text displayed in the spinbox.


问:
Select merging string only, not all the line in KDiff3
I work on files with long strings and I would like to compare and merge them the way I want after checking all modifications.

For exemple, let's say I have fileA.txt:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'

Then, a co-worker modifies it in the following way in fileB.txt:
'Lorem ipsum dolor sit amet, consectetur WITH MORE TEXT adipiscing elit, sed do eiusmod tempor incididunt ut labore.'

There is two modifications:

adding text 'WITH MORE TEXT'

deleting the end of fileA.txt

In KDiff3 when I click on merge, because this is only 1 line, the merging tool only propose fileA or fileB.
I would like a file accepting the modification 1 and refusing the 2:
'Lorem ipsum dolor sit amet, consectetur WITH MORE TEXT adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'

How to do it in KDiff3 ?
Or which other free tool ?

This is only a short exemple, I have this on file with thousands of lines. So I need to check all modifications.

Thank you !


问:
Cant Debug a Application compiled with makefile in CLion
I have a C and assembly Application compiled with makefile, i wanted to debug it with CLion debugging tools, but i cant do it.
I have several .asm .c and .h files that my main.c uses, when i call the make run command it works just fine but i cant debug it on CLion. I have followed a lot of documentations and nothing seems to work although my case also seem preety simple at the same time.

This is my makefile

```<code>INCLUDES = daily_matrix.h random.h gen_val_sens.h sensores.h set_limit_values.h create_new_dinamic_array.h create_new_sensor.h add_remove_sensors.h frequency_for_sensors.h
SOURCES =  main.c daily_matrix.c random.s sensores.s gen_val_sens.c set_limit_values.c create_new_dinamic_array.c create_new_sensor.c add_remove_sensors.c frequency_for_sensors.c
OBJFILES = main.o daily_matrix.o random.o sensores.o gen_val_sens.o set_limit_values.o create_new_dinamic_array.o create_new_sensor.o add_remove_sensors.o frequency_for_sensors.o
EXEC = prog

.SUFFIXES : .c .o

.c.o:
    gcc -Wall -g -c $<

${EXEC}: ${OBJFILES}
    gcc -Wall -g -o ${EXEC} ${OBJFILES}

${OBJFILES}: ${SOURCES} ${INCLUDES}

run: ${EXEC}
    ./${EXEC}

clean:
    rm -f ${OBJFILES} ${EXEC}
</code>```

I also know that i can "translate" this make file and compile the applicattion with Cmake but that seemed a bigger route than just working with makefile

Body:
I have a C and assembly Application compiled with makefile, i wanted to debug it with CLion debugging tools, but i cant do it.
I have several .asm .c and .h files that my main.c uses, when i call the make run command it works just fine but i cant debug it on CLion. I have followed a lot of documentations and nothing seems to work although my case also seem preety simple at the same time.

This is my makefile

INCLUDES = daily_matrix.h random.h gen_val_sens.h sensores.h set_limit_values.h create_new_dinamic_array.h create_new_sensor.h add_remove_sensors.h frequency_for_sensors.h
SOURCES =  main.c daily_matrix.c random.s sensores.s gen_val_sens.c set_limit_values.c create_new_dinamic_array.c create_new_sensor.c add_remove_sensors.c frequency_for_sensors.c
OBJFILES = main.o daily_matrix.o random.o sensores.o gen_val_sens.o set_limit_values.o create_new_dinamic_array.o create_new_sensor.o add_remove_sensors.o frequency_for_sensors.o
EXEC = prog

.SUFFIXES : .c .o

.c.o:
    gcc -Wall -g -c $<

${EXEC}: ${OBJFILES}
    gcc -Wall -g -o ${EXEC} ${OBJFILES}

${OBJFILES}: ${SOURCES} ${INCLUDES}

run: ${EXEC}
    ./${EXEC}

clean:
    rm -f ${OBJFILES} ${EXEC}

I also know that i can "translate" this make file and compile the applicattion with Cmake but that seemed a bigger route than just working with makefile


问:
Problem with data showed in a recycler view when user log out and log in firebase realtime
I have a weird behavior with a recyclerview. The app is a kind of social network where users publish post and I look for all the post of all users that authentifated user has bookmarked. My app works fine the first time an user logins. But if the user log out, and later log in, the first post it's not showed. But If the user start over again the app it works properly. I'm really lost why it's happening.
This is a picture of part of my database, but I can read the correctly. I think the problem has to be with the recyclew view.But not sure

Here is the code where I search the data. I use two functions buscarUsuarioSeguidos which store an array with the list of user's id that later I use to look for user's posts with mostrarPublicacionesSeguidas.

```<code> private fun buscarUsuariosSeguidos(usuarioUid:String){
        //BUSCAMOS EN LA TABLA SEGUIR CADA ENTRADA DONDE APAREZCA COMO SEGUIDOR EL USUARIO AUTENTIFICADO
        val seguidoresRef= referenciaBD.child("Seguir").child(usuarioUid).child("Siguiendo")
        // LIMPIAMOS LAS PUBLICACIONES SEGUIDAS
        usuariosSeguidosUid?.clear()
        //CARGAMOS LAS PUBLICACIONES EN EL RECYCLERVIEW DATACHANGE SE ENCARGA DE CARGAR LOS DATOS
        seguidoresRef.addValueEventListener(object :ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()){
                    for (snap in snapshot.children)
                        //RECUPERAMOS LA CLAVE DE CADA CHILDREN QUE REALMENTE ES EL UID DEL USUARIO
                        snap.key?.let { (usuariosSeguidosUid as ArrayList<String>).add(it) }
                }
            }
            override fun onCancelled(error: DatabaseError) {
            }
        })
    }
    //ESTA FUNCION BUSCA LAS PUBLICACIONES DE TODOS LOS USUARIOS QUE SIGUE EL USUARIO AUTENTIFICADO
    private fun mostrarPublicacionesSeguidas() {
        //CREAMOS LA QUERY DE BUSQUEDA QUE APUNTA A LA TABLA PUBLICACIONES
        val publicacionRef = referenciaBD.child("Publicaciones")
        //listaPublicaciones?.clear()
        publicacionRef.addValueEventListener(object : ValueEventListener {
            //CARGAMOS TODOS LOS DATOS DE LA TABLA POSTS EN EL RECYCLERVIEW DATACHANGE SE ENCARGA DE CARGAR LOS DATOS
            override fun onDataChange(snapshot: DataSnapshot) {
                //LIMPIAMOS LA LISTA DE PUBLICACIONES
                listaPublicaciones?.clear()
                for (snapshot in snapshot.children) {
                    // SE VA RECUPÈRANDO CADA PUBLICACION
                    val publicacion = snapshot.getValue(Publicacion::class.java)
                    // Y SE RECORRE EL ARRAY CON LOS UID DE LOS USUARIOS SEGUIDOS PARA VER SI SE DEBE MOSTRAR
                    for (usuarioUid in usuariosSeguidosUid as ArrayList<String>)
                        // EN CASO DE QUE SE ENCUENTRE CONICIDENCIA SE AÑADE LA PUBLICACION A SU LISTA
                        if (usuarioUid == publicacion!!.nombreUsuario ){
                            listaPublicaciones?.add(publicacion!!)
                        }
                }
                //invertimos la lista para que los ultimos posts esten os primero
                listaPublicaciones!!.reverse()
                //SE ACTUALIZA EL LISTADO DE PUBLICACIONES MOSTRADOR EN EL ADAPTADOR
                publicacionAdaptador?.notifyDataSetChanged()
            }
            override fun onCancelled(error: DatabaseError) {
                //VER QUE HACE
            }
        })
    }
</code>```

And this is the function to log out.

```<code>   private fun desconectarUsuario(){
        FirebaseAuth.getInstance().signOut()
        val intent = Intent(context,IdentificarseActivity::class.java)
        startActivity(intent)
    }
</code>```

Thank

Body:
I have a weird behavior with a recyclerview. The app is a kind of social network where users publish post and I look for all the post of all users that authentifated user has bookmarked. My app works fine the first time an user logins. But if the user log out, and later log in, the first post it's not showed. But If the user start over again the app it works properly. I'm really lost why it's happening.
This is a picture of part of my database, but I can read the correctly. I think the problem has to be with the recyclew view.But not sure

Here is the code where I search the data. I use two functions buscarUsuarioSeguidos which store an array with the list of user's id that later I use to look for user's posts with mostrarPublicacionesSeguidas.

 private fun buscarUsuariosSeguidos(usuarioUid:String){
        //BUSCAMOS EN LA TABLA SEGUIR CADA ENTRADA DONDE APAREZCA COMO SEGUIDOR EL USUARIO AUTENTIFICADO
        val seguidoresRef= referenciaBD.child("Seguir").child(usuarioUid).child("Siguiendo")
        // LIMPIAMOS LAS PUBLICACIONES SEGUIDAS
        usuariosSeguidosUid?.clear()
        //CARGAMOS LAS PUBLICACIONES EN EL RECYCLERVIEW DATACHANGE SE ENCARGA DE CARGAR LOS DATOS
        seguidoresRef.addValueEventListener(object :ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()){
                    for (snap in snapshot.children)
                        //RECUPERAMOS LA CLAVE DE CADA CHILDREN QUE REALMENTE ES EL UID DEL USUARIO
                        snap.key?.let { (usuariosSeguidosUid as ArrayList<String>).add(it) }
                }
            }
            override fun onCancelled(error: DatabaseError) {
            }
        })
    }
    //ESTA FUNCION BUSCA LAS PUBLICACIONES DE TODOS LOS USUARIOS QUE SIGUE EL USUARIO AUTENTIFICADO
    private fun mostrarPublicacionesSeguidas() {
        //CREAMOS LA QUERY DE BUSQUEDA QUE APUNTA A LA TABLA PUBLICACIONES
        val publicacionRef = referenciaBD.child("Publicaciones")
        //listaPublicaciones?.clear()
        publicacionRef.addValueEventListener(object : ValueEventListener {
            //CARGAMOS TODOS LOS DATOS DE LA TABLA POSTS EN EL RECYCLERVIEW DATACHANGE SE ENCARGA DE CARGAR LOS DATOS
            override fun onDataChange(snapshot: DataSnapshot) {
                //LIMPIAMOS LA LISTA DE PUBLICACIONES
                listaPublicaciones?.clear()
                for (snapshot in snapshot.children) {
                    // SE VA RECUPÈRANDO CADA PUBLICACION
                    val publicacion = snapshot.getValue(Publicacion::class.java)
                    // Y SE RECORRE EL ARRAY CON LOS UID DE LOS USUARIOS SEGUIDOS PARA VER SI SE DEBE MOSTRAR
                    for (usuarioUid in usuariosSeguidosUid as ArrayList<String>)
                        // EN CASO DE QUE SE ENCUENTRE CONICIDENCIA SE AÑADE LA PUBLICACION A SU LISTA
                        if (usuarioUid == publicacion!!.nombreUsuario ){
                            listaPublicaciones?.add(publicacion!!)
                        }
                }
                //invertimos la lista para que los ultimos posts esten os primero
                listaPublicaciones!!.reverse()
                //SE ACTUALIZA EL LISTADO DE PUBLICACIONES MOSTRADOR EN EL ADAPTADOR
                publicacionAdaptador?.notifyDataSetChanged()
            }
            override fun onCancelled(error: DatabaseError) {
                //VER QUE HACE
            }
        })
    }

And this is the function to log out.

   private fun desconectarUsuario(){
        FirebaseAuth.getInstance().signOut()
        val intent = Intent(context,IdentificarseActivity::class.java)
        startActivity(intent)
    }

Thank


问:
Embed ReactJS into Flutter
Background:
We have a ReactJS Web app. We are planning to move to Flutter when expanding the app with more new features.

Question 1: What is the best way to embed the existing ReactJS web into Flutter Web without rewrite ReactJS code in Dart?

Question 2: If the ReactJS app uses Web APIs (such as Windows), is there any way to embed that in Flutter iOS and Android, in addition to WebView?

Title: Embed ReactJS into Flutter