问:
Flutter - File() constructor "The argument type 'String' can't be assigned to the parameter type 'List<Object>'"
I'm new to flutter and trying to send image via chat section. I'm  getting 2 errors in my code. how can I solve this. appreciate your help on this.

error: The argument type 'String' can't be assigned to the parameter
type 'List'.

error: 2 positional argument(s) expected, but 1 found. )

Complete Reproducible Code on DartPad

```<code>final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  File? imageFile;
  Future getImage() async {
    ImagePicker _picker = ImagePicker();

    await _picker.pickImage(source: ImageSource.gallery).then((xFile) {
      if (xFile != null) {
        imageFile = File(xFile.path);
        uploadImage();
      }
    });
  }

  Future uploadImage() async {
    String fileName = Uuid().v1();
    int status = 1;

    await _firestore
        .collection('chatdetail')
        .doc(friendUid)
        .collection('chats')
        .doc(fileName)
        .set({
      "sendby": _auth.currentUser!.displayName,
      "message": "",
      "type": "img",
      "time": FieldValue.serverTimestamp(),
    });

    var ref =
    FirebaseStorage.instance.ref().child('images').child("$fileName.jpg");

    //error in ImageFile

    var uploadTask = await ref.putFile(imageFile!).catchError((error) async {
      await _firestore
          .collection('chatdetail')
          .doc(friendUid)
          .collection('chats')
          .doc(fileName)
          .delete();

      status = 0;
    });

    if (status == 1) {
      String imageUrl = await uploadTask.ref.getDownloadURL();

      await _firestore
          .collection('chatdetail')
          .doc(friendUid)
          .collection('chats')
          .doc(fileName)
          .update({"message": imageUrl});

      print(imageUrl);
    }
  }
</code>```

答: Replace import 'dart:html'; with 'import 'dart:io';'. You just imported the wrong package. File you want is from dart:io not dart:html.

Body:
I'm new to flutter and trying to send image via chat section. I'm  getting 2 errors in my code. how can I solve this. appreciate your help on this.

error: The argument type 'String' can't be assigned to the parameter
type 'List'.

error: 2 positional argument(s) expected, but 1 found. )

Complete Reproducible Code on DartPad

final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  File? imageFile;
  Future getImage() async {
    ImagePicker _picker = ImagePicker();

    await _picker.pickImage(source: ImageSource.gallery).then((xFile) {
      if (xFile != null) {
        imageFile = File(xFile.path);
        uploadImage();
      }
    });
  }

  Future uploadImage() async {
    String fileName = Uuid().v1();
    int status = 1;

    await _firestore
        .collection('chatdetail')
        .doc(friendUid)
        .collection('chats')
        .doc(fileName)
        .set({
      "sendby": _auth.currentUser!.displayName,
      "message": "",
      "type": "img",
      "time": FieldValue.serverTimestamp(),
    });

    var ref =
    FirebaseStorage.instance.ref().child('images').child("$fileName.jpg");

    //error in ImageFile

    var uploadTask = await ref.putFile(imageFile!).catchError((error) async {
      await _firestore
          .collection('chatdetail')
          .doc(friendUid)
          .collection('chats')
          .doc(fileName)
          .delete();

      status = 0;
    });

    if (status == 1) {
      String imageUrl = await uploadTask.ref.getDownloadURL();

      await _firestore
          .collection('chatdetail')
          .doc(friendUid)
          .collection('chats')
          .doc(fileName)
          .update({"message": imageUrl});

      print(imageUrl);
    }
  }


来源: stackexchange

问:
Methods with different signatures in Typescript class inheritence
could someone explain why the following code snippet will introduce error please? Thank you!

```<code>class Base {
  greet() {
    console.log("Hello, world!");
  }
}

class Derived extends Base {
  // Make this parameter required
  greet(name: string) { // why we have error here?
    console.log(`Hello, ${name.toUpperCase()}`);
  }
}
</code>```
```<code>const b: Base = new Derived();
b.greet(); // why it crashes here?
</code>```

I use Java a lot. So maybe I am thinking in a JAVA way. From my understanding, Derived class inherits great() method in Base class. When it defines greet(name: string) method, this method should be treated as method overloading. So Derived class should have both greet() and greet(name: string). Why we have error here? Thank you in advance!

答:
Consider this simple example:

type EmptyGreet = () => void

type FullGreed = (arg: string) => void

let emptyGreed: EmptyGreet = () => { }
let fullGreed: FullGreed = (arg: string) => arg.toLowerCase()

emptyGreed = fullGreed // error
emptyGreed() // ok, but there is runtime error

fullGreed = emptyGreed // ok
fullGreed('hello') // ok, hello argument does not have any impact on business logic
```
<p>Playground</p>
<p>As you might have noticed, it is unsafe to assign function with argument to the function without argument.</p>
<p>Same is here:</p>
<pre class="lang-js prettyprint-override"><code>class Base {
  greet() {
    console.log("Hello, world!");
  }
}

class Derived extends Base {
  // Make this parameter required
  greet(name: string) { // why we have error here?
    console.log(`Hello, ${name.toUpperCase()}`);
  }
}

const b: Base = new Derived();
b.greet(); // why it crashes here?
</code>```

class Derived expects an argument for greet method and you are trying to call greet without such argument. This is why TS does not allow you to use explicit type Base for b const

this method should be treated as method overloading ...

This is not true. This is not how method overloading works in typescript.

class Foo {
    foo(arg: string): string
    foo(arg: number): number
    foo(arg: any) {
        return null as any
    }
}
```

P.S. Please consider using keyword override (docs) if you want to override a method

ContentLicense: CC BY-SA 4.0

Body:
could someone explain why the following code snippet will introduce error please? Thank you!

class Base {
  greet() {
    console.log("Hello, world!");
  }
}

class Derived extends Base {
  // Make this parameter required
  greet(name: string) { // why we have error here?
    console.log(`Hello, ${name.toUpperCase()}`);
  }
}

const b: Base = new Derived();
b.greet(); // why it crashes here?

I use Java a lot. So maybe I am thinking in a JAVA way. From my understanding, Derived class inherits great() method in Base class. When it defines greet(name: string) method, this method should be treated as method overloading. So Derived class should have both greet() and greet(name: string). Why we have error here? Thank you in advance!

Body:
Consider this simple example:

type EmptyGreet = () => void

type FullGreed = (arg: string) => void

let emptyGreed: EmptyGreet = () => { }
let fullGreed: FullGreed = (arg: string) => arg.toLowerCase()

emptyGreed = fullGreed // error
emptyGreed() // ok, but there is runtime error

fullGreed = emptyGreed // ok
fullGreed('hello') // ok, hello argument does not have any impact on business logic

Playground

As you might have noticed, it is unsafe to assign function with argument to the function without argument.

Same is here:

class Base {
  greet() {
    console.log("Hello, world!");
  }
}

class Derived extends Base {
  // Make this parameter required
  greet(name: string) { // why we have error here?
    console.log(`Hello, ${name.toUpperCase()}`);
  }
}

const b: Base = new Derived();
b.greet(); // why it crashes here?

class Derived expects an argument for greet method and you are trying to call greet without such argument. This is why TS does not allow you to use explicit type Base for b const

this method should be treated as method overloading ...

This is not true. This is not how method overloading works in typescript.

class Foo {
    foo(arg: string): string
    foo(arg: number): number
    foo(arg: any) {
        return null as any
    }
}

P.S. Please consider using keyword override (docs) if you want to override a method


问:
MS ACCESS: INNER JOIN Always TRUE (e.g. ON TRUE | ON 1 = 1)

Hi Everyone,

I am trying to do a calculation between two tables and want the INNER JOIN to be always TRUE.

However, when I enter in MS ACCESS the error says the "JOIN-expression is not supported".

Any idea how I can deal with it to make it work? Or does MS ACCESS not allow ON TRUE expression in general?

SELECT
A.Part,
(Sqr(([T.R_SCHWERPKT_GK3]-[A.LX])^2+([T.H_SCHWERPKT_GK3]-[A.LY])^2)) AS ABSTAND
INTO ABSTAND_CALC
FROM AVANI_FPF_SSR0 AS A
INNER JOIN G_IVL_KOORDINATEN AS T
ON 1 = 1;

Many thanks, regards
Sina

答:
An INNER JOIN on everything is a cross join.

In Access SQL, we write cross joins by omitting the JOIN clause entirely, and separating the tables by a comma:

```<code>SELECT A.Part, (Sqr(([T.R_SCHWERPKT_GK3]-[A.LX])^2+([T.H_SCHWERPKT_GK3]-[A.LY])^2)) AS ABSTAND INTO ABSTAND_CALC
FROM AVANI_FPF_SSR0 AS A, G_IVL_KOORDINATEN AS T;
</code>```

Body:
An INNER JOIN on everything is a cross join.

In Access SQL, we write cross joins by omitting the JOIN clause entirely, and separating the tables by a comma:

SELECT A.Part, (Sqr(([T.R_SCHWERPKT_GK3]-[A.LX])^2+([T.H_SCHWERPKT_GK3]-[A.LY])^2)) AS ABSTAND INTO ABSTAND_CALC
FROM AVANI_FPF_SSR0 AS A, G_IVL_KOORDINATEN AS T;


问:
Where to put styled components styles
components for styling my react app, so far i had a separate folder in each page's folder called Styles and stored my styled component wrappers inside it( e.g. ThemeToggler.Style.js or Section.Style.js and ... ).

But i realized that my code is getting messy and project files count increases so fast because creating a component means creating 2 files, also some styles was so simple and small that i decided to write them inside the component's main file, because its more readable.

But i still feel that this approach is not good too because some styles are too long to put them inside the component's file , also some styles are not about the component it self, maybe i have a style for showing the adjacent nav of this div if user clicks on it. I thought that i'll put them inside a separate file called DivOnHover.js but it seems not correct :)

I'll like to hear your approach for managing styled-components styles, how do you store them in your folder structure ?

答:
Personally I tend to use this structure pretty often:

```<code>components/
| Button/
| | Button.js
| | Button.styles.js
| Navbar/
| | Navbar.js
| | Navbar.styles.js
</code>```

At the cost of making more files, it allows you to separate your component logic and styles.

Title: Where to put styled components styles

Body:
Personally I tend to use this structure pretty often:

components/
| Button/
| | Button.js
| | Button.styles.js
| Navbar/
| | Navbar.js
| | Navbar.styles.js

At the cost of making more files, it allows you to separate your component logic and styles.


问:
Linq FirstOrDefault ordering when OrderBy or OrderByDescending are not supplied?
If we have an EF entity with basic structure of

```<code>public class Entity
{
   public int Id {get; set;}
   public string name {get; set;}
   public DateTime lastUpdated {get; set;}
}
</code>```

And a collection of them with 4 entities:

```<code>entities = new List<Entity>{
   new { Id = 0, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 1, 0, 0, 0,)},
   new { Id = 1, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 4, 0, 0, 0,)},
   new { Id = 2, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 3, 0, 0, 0,)},
   new { Id = 3, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 2, 0, 0, 0,)}
};
</code>```

If we use Linq to select the FirstOrDefault by the Name property.

```<code>   var selectedEntity = entities.FirstOrDefault(e => e.Name == "Thing One");
</code>```

What is this going to return?

This is causing issues in a piece of code that I'm reviewing; which will be fixed by only allowing unique entities and using SingleOrDefault, but I'm curious at to what the FirstOrDefault is going to return by default when there is no OrderBy clause.

答:
The first item matching this condition is returned, if there are multiple items matching the result is unpredictable/undefined. If you want to ensure a specifc item you need to apply an OrderBy:

```<code>var selectedEntity = entities
   .Where(e => e.Name == "Thing One")
   .OrderByDescending(e => e.LastUpdated)
   .FirstOrDefault();
</code>```

What is returned by the database depends on the vendor. This related qustion might help: When no 'Order by' is specified, what order does a query choose for your record set?

Body:
If we have an EF entity with basic structure of

public class Entity
{
   public int Id {get; set;}
   public string name {get; set;}
   public DateTime lastUpdated {get; set;}
}

And a collection of them with 4 entities:

entities = new List<Entity>{
   new { Id = 0, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 1, 0, 0, 0,)},
   new { Id = 1, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 4, 0, 0, 0,)},
   new { Id = 2, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 3, 0, 0, 0,)},
   new { Id = 3, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 2, 0, 0, 0,)}
};

If we use Linq to select the FirstOrDefault by the Name property.

   var selectedEntity = entities.FirstOrDefault(e => e.Name == "Thing One");

What is this going to return?

This is causing issues in a piece of code that I'm reviewing; which will be fixed by only allowing unique entities and using SingleOrDefault, but I'm curious at to what the FirstOrDefault is going to return by default when there is no OrderBy clause.

Body:
The first item matching this condition is returned, if there are multiple items matching the result is unpredictable/undefined. If you want to ensure a specifc item you need to apply an OrderBy:

var selectedEntity = entities
   .Where(e => e.Name == "Thing One")
   .OrderByDescending(e => e.LastUpdated)
   .FirstOrDefault();

What is returned by the database depends on the vendor. This related qustion might help: When no 'Order by' is specified, what order does a query choose for your record set?


问:
Function address not in the range of memory-mapped files for the lisp image process
After defining and disassembling the function fn, I can see that the function (or code component) resides at memory address 0x53675216. But I don't see said memory address to be in the range of memory-mapped files attributed to the lisp image process (I'm using SBCL).

Am I missing something about how the internals of a process work?

FWIW My goal was to dump the entire memory of the process and inspect some of the memory. But if I can't even get at a function that I defined, what's the point?

答:
Please post the actual text rather than a picture of the text.

/proc/<pid>/map_files is not the right thing to look at: instead look at /proc/<pid>/maps which shows you all the memory maps.

In my case if I define & compile foo on SBCL on x64 / Linux as:

```<code>(defun foo ())
</code>```

Then (disassemble 'foo) looks like:

```<code>; disassembly for foo
; Size: 21 bytes. Origin: #x53624A7C                          ; foo
[...]
</code>```

And I can use my hexdump-thing function from this answer to check this:

```<code>> (hexdump-thing #'foo)
> (hexdump-thing #'foo)
lowtags:    1011
function:   0000000053624A6B : 0000000053624A60
</code>```

So the actual address of the object is #x0000000053624A60, which is compatible with what disassemble is saying.

So then if I look at /proc/<pid>/maps I see, among all the other lines, two lines like:

```<code>52a00000-533f8000 rwxp 016a8000 fd:00 2758077                            /local/environments/sbcl/lib/sbcl/sbcl.core
533f8000-5ac00000 rwxp 00000000 00:00 0
</code>```

The fields in this file are address, permissions, offset, device, inode, file.  You can see that the range that includes the function's address is not mapped to any file (note that p means 'copy on write' so the range mapped to the core file will never be written back to the core file).

The function's definition lives somewhere in this anonymous range of memory.

As a note: if you want to investigate the memory of the implementation, do it from within the implementation, which will be hugely easier than trying to investigate it from outside.  SBCL has lots of support for this sort of thing, although you have to find some of them by grovelling around in the source.  After all this sort of thing is exactly what a garbage collector has to do.

Body:
Please post the actual text rather than a picture of the text.

/proc/<pid>/map_files is not the right thing to look at: instead look at /proc/<pid>/maps which shows you all the memory maps.

In my case if I define & compile foo on SBCL on x64 / Linux as:

(defun foo ())

Then (disassemble 'foo) looks like:

; disassembly for foo
; Size: 21 bytes. Origin: #x53624A7C                          ; foo
[...]

And I can use my hexdump-thing function from this answer to check this:

> (hexdump-thing #'foo)
> (hexdump-thing #'foo)
lowtags:    1011
function:   0000000053624A6B : 0000000053624A60

So the actual address of the object is #x0000000053624A60, which is compatible with what disassemble is saying.

So then if I look at /proc/<pid>/maps I see, among all the other lines, two lines like:

52a00000-533f8000 rwxp 016a8000 fd:00 2758077                            /local/environments/sbcl/lib/sbcl/sbcl.core
533f8000-5ac00000 rwxp 00000000 00:00 0

The fields in this file are address, permissions, offset, device, inode, file.  You can see that the range that includes the function's address is not mapped to any file (note that p means 'copy on write' so the range mapped to the core file will never be written back to the core file).

The function's definition lives somewhere in this anonymous range of memory.

As a note: if you want to investigate the memory of the implementation, do it from within the implementation, which will be hugely easier than trying to investigate it from outside.  SBCL has lots of support for this sort of thing, although you have to find some of them by grovelling around in the source.  After all this sort of thing is exactly what a garbage collector has to do.


答:
The transactions are encoded with scale encoding. The answer depends on which language your coding in.

I would use a client library related to your language. https://docs.substrate.io/v3/integration/client-libraries/

(There's also tools like https://github.com/paritytech/subxt which could help.)

Title: How to get polkadot's transaction and transfer at json rpc

Body:
I testing at westend(polkadot testnet) use json-rpc

How can I extract transaction and etc from extrinsis and check it?

https://polkadot.js.org/docs/substrate/rpc/#getblockhash-blockhash-signedblock

curl -H "Content-Type: application/json" --data '{ "jsonrpc":"2.0", "method":"chain_getBlock", "params":["BlockHash"],"id":1 }'

response

{"block": {
"extrinsics": [ "0x280402000be1da78d37e01",     "0xd91f042d00401401000000001a6bb010c80ee356a801602fe9e28ff820f548a982312ee737dd15c85aead002687d4d83396efca5c145bca092834af45b6652512b06dc78b46bc52a3659fa83140101000000f0f8063ff5a2e8592347a2c11cd87d9e4ddfd7a5b93915e5492d36b79bd47648ac35ba1b7be83f7feedafbd0934c500521787a2b3a370d5f3aec1d9bf4baa38c1401020000005420cd14e1341f1eacf6d4bd19902c94e3af4441f3365db0420b635bae95235925f9046c84c7db838115573a7e745f380effa6f2aca3252611f8a52f7d7a29871401030000002e7b5ba51e269894a2d3a0f54f0a090a40d0de1ef9be6c2efa18d651f3465c547c184222851d0b72491a02d753a022ec2818ce8ed34cedd591fc0e4b86ca218c140104000000427d3becde96c713a4ef59c960e13ec5a8d0657d1214fdb24c56fc8f58f3293c8e9cd226583fee171561ad9c6a9812e311226cdf0fa44cc20db19aa2ee723e831401050000009c2b5da735b2e7d2f055e398780a8ede9309cb4bcccfa6665d30fba608a0cb6d00bf689db57242eedd438b2731497dec2484b0875e4bbc087ad2f55a4eed548a1401060000008e2d5a62d5cdda14bceb7c5a350dc2cc4125d0045f92f266bacd1c254785dd1525cbcd7605d1662991c30a706eb93351f795a5788cb136b9ede7200a2b6c288c140107000000746dd12921ddebfec87b4728aaf876870efe71c87e84907312ae992d7760fc686588068b92d448aaa314247323d760524fc59b2b5f4d714b11e613e57459ca8914010800000080878a3bec69850c7169a481f695b0d6ec3493e135a43ee5326b2707dbab4d59277c48da2e4fcbe545fefbc53de079f9ed907f24564c779c2deac2bcd89d4f8e14010900000014b71d48a4693da625dd709b5feed2d3f04f78f5eb40c932810dfd62d3af83638dbace4183ab8bc3067e8c5d8e82c1d8e870f52846392310d00189adec07b28d14010a0000005a83aa5e22bc75ff6cc66abd4a794d32459002702edbb2082266226852bd6a7bb257fa5b25286e8637f700b0d54e8c7cafcfe1dbbc98497ee1b852774605908d14010b000000deffb1ce2b547366b7fbb641db3ff98876611f3e920fbb9033eeed7acb859a04b3c24ea78841b4aaceb1d6a5e6deb5e0bb6ae0714b5eaa473b05765ed5157c8f14010c0000008299d03ca286f18e88e6d12ef23103700946b9a8a4e6806371a9473db04718298da1dd7f3db4d6c4fb4b8b4c6a5293f418108425ba30b50e761ec75c38caa28814010d00000072fcd84d7c7101e61f3031916b8911c88fe6933a3130528dd2a600c334f1955407f712c7683145018532cd9a5c646ecf0c5ba5104a1556b79a16d320a528d18d14010e000000181dbef7d3770317cadd65b825805cafe5dffe0f321dfc9b529842ebeafc2d35686b219b8d6ce86b0c3addfeb9fe245fa768f5544cd6b008a7375704586c5a8b14010f000000aea5c7442a39db454c9bcd7b1b83b0e6d0828eb8f0dc0693d0f8fd875b43c32d7608b5187782fd76e8fefe43c0cf024e73077a270e5ce3fb5409912d1d15388e04e9030000fdf27e9f1fd499ce9d312e5a7f60e88d06c506287c239bbdcfc9b3738a62c9f99c4a52f73dada2812d6843883b11e2c9210fcf9e093d3c70f44915b189d29159b239c4eec41a44c56054e5ee84472f4bd0a2a4fbbf8d8b3698ac647da7f9cf55402cc300a335ce4bf75dfbc8dbdfd5c6a751cd2b8235f6a128e4b7bb045b3170bcca143638a92149094c99362dbfae7a48fe6cdba889a6afa8474100fcdd77526c4a2fc779a56e6407ce148fb62b93766fa3e6e04c029556d6efc0074c9e83079f8dd8b5c1cfee99f50882e0616a1b41c64c64fa45ae81a70a78976fb83de08c390da23d6b6a0fc494f0d0c1f39f4df50f445815bea20792a9c09156fb075146f55507166fde3facca62f3aa6afca407575f4fe4bb551f7ca34d744c51f3a449000000e9023e0a1d9cefa6802f310b15b7d051630bb14b32598693c16856b2274abcaee602fe411e0016ae13ca9ccdbbf179f19fe39406882c694fa462512153b7e6410263ecec91db0a9858281824b47073941f2f995df3fd5f926003525eb0be77ad040acb72e36408066175726120a0bd2a080000000005617572610101c6c6e414428a0f7008535b8f3c210db91f83b4bfbba625880126a553433bc86d29e506280911770eb2dcec41ce7d9325c2f6c475c2a166f135abddb20c79c48700000000044e90000801c0018a180e681913ae9188ae7fc3675b1d5aff3b00281148d295ba7cceaa742449971fa0518e7f459bfaf54d7f4d9a0f54c14c3eb6b78f39929d27950b85f78202d0cd5b9df0527c9eb7951707d1bdf4fb09a80421a51b46c1dd18004600b1f44150f83bd1136d4c2f10701da7edd70ad22fa549f6aaef3be27936afe32967ba8c0c03007558ba642f453ddfe49fb888c27e2d181bfe29946f6bb7f64b755331e49461b012384102382051028e7ddaa12a120405bf9c7b7a956140ea07ab7d5f02c2c2d83077326b852a6b579ca7bbc1eb2f1dde3d3afb17650f21357517424cb87a450debfacff3080642414245b5010308000000417b551000000000ea5c8ce57aed643bdd6863a59ba4997842d4998c5d3a70452b5ac57f11d2b53484a5a4d4db26d5b1891c8b48dfbdfd614586989fdca4f00be2d7cad1b60b430040e23301a772481b46def0649a5813fb43199aefc856751f07d281905da2f90e05424142450101f62d0cb832fd292a38e50bd07570d36e922b4991922b4b5ebc5831fc41574f7d37ca591f9a4cd4ee80fbb91d06055274e80932f2d826ba24b2c2b7e5b4dca580"
],
"header": {
  "digest": {
    "logs": [
      "0x0642414245b5010305000000427b551000000000888493239316bb8a345f4712486de708aaaab935a754d49146da3f67466bc03132afee2bdb6c792a6fc343efba706e255a203a69ef3fc7896999196360889607880ffc042a635f463e2520146e0afde3591be104e5adc9146da6de0e8c049505",
      "0x054241424501017e8b20b09ea880e3b54a600a2cf451c87a2cd117a03c74fdb41383f043bfeb4a2816e0be57999060946764e0e031588badcc349b436879536c3756c9b161de87"
    ]
  },
  "extrinsicsRoot": "0x264d4ee5030a330b79b43b71d0d2ac503123a984b32082642355cf96ecfc09ed",
  "number": "0x904e05",
  "parentHash": "0xfdf27e9f1fd499ce9d312e5a7f60e88d06c506287c239bbdcfc9b3738a62c9f9",
  "stateRoot": "0xef4a702a0043e5cb5d7daa3569092fbd07f041fb5ced4cff5724981a5c721751"
}


问:
How to add a total value at the end of a datatable column that has an expression?
I want to add a total value at the end of a datatable column. But I can't do it because the column has an expression. The code is as below. Please help!</p>
```<code>public MainWindow()
        {
            InitializeComponent();

            DataTable table = new DataTable();
            table.Columns.Add("ColA", typeof(double));
            table.Columns.Add("ColB", typeof(double));
            table.Columns.Add("ColSum", typeof(double));

            table.Rows.Add(1.23, 2.34, null);
            table.Rows.Add(2.34, 3.45, null);
            table.Rows.Add(3.45, 4.56, null);

            table.Columns["ColSum"].Expression = "ColA + ColB";
            double total = (double)table.Compute("Sum(ColSum)", "");

            DataRow dr = table.NewRow();
            dr["ColSum"] = total;
            table.Rows.Add(dr);
            //Can't add total value at the end of ColSum because this column has an expression. How to solve the problem ?

            dataGrid1.ItemsSource = table.DefaultView;
        }
</code>```

答:
But I can't do it because the column has an expression

True. That's a fact so get rid of the expression and calculate the sum yourself:

```<code>DataTable table = new DataTable();
table.Columns.Add("ColA", typeof(double));
table.Columns.Add("ColB", typeof(double));
table.Columns.Add("ColSum", typeof(double));

table.Rows.Add(1.23, 2.34, 1.23 + 3.45);
table.Rows.Add(2.34, 3.45, 2.34 + 3.45);
table.Rows.Add(3.45, 4.56, 3.45 + 4.56);

double total = (double)table.Compute("Sum(ColSum)", "");

DataRow dr = table.NewRow();
dr["ColSum"] = total;
table.Rows.Add(dr);
</code>```

That's the only viable option if you choose to represent your data using a DataTable.

The other option is of course to create your own view model.

Body:
I want to add a total value at the end of a datatable column. But I can't do it because the column has an expression. The code is as below. Please help!

public MainWindow()
        {
            InitializeComponent();

            DataTable table = new DataTable();
            table.Columns.Add("ColA", typeof(double));
            table.Columns.Add("ColB", typeof(double));
            table.Columns.Add("ColSum", typeof(double));

            table.Rows.Add(1.23, 2.34, null);
            table.Rows.Add(2.34, 3.45, null);
            table.Rows.Add(3.45, 4.56, null);

            table.Columns["ColSum"].Expression = "ColA + ColB";
            double total = (double)table.Compute("Sum(ColSum)", "");

            DataRow dr = table.NewRow();
            dr["ColSum"] = total;
            table.Rows.Add(dr);
            //Can't add total value at the end of ColSum because this column has an expression. How to solve the problem ?

            dataGrid1.ItemsSource = table.DefaultView;
        }

Body:
But I can't do it because the column has an expression

True. That's a fact so get rid of the expression and calculate the sum yourself:

DataTable table = new DataTable();
table.Columns.Add("ColA", typeof(double));
table.Columns.Add("ColB", typeof(double));
table.Columns.Add("ColSum", typeof(double));

table.Rows.Add(1.23, 2.34, 1.23 + 3.45);
table.Rows.Add(2.34, 3.45, 2.34 + 3.45);
table.Rows.Add(3.45, 4.56, 3.45 + 4.56);

double total = (double)table.Compute("Sum(ColSum)", "");

DataRow dr = table.NewRow();
dr["ColSum"] = total;
table.Rows.Add(dr);

That's the only viable option if you choose to represent your data using a DataTable.

The other option is of course to create your own view model.


问:
eslint command fails on CI Server with error "ESLint couldn't find the config "standard" to extend from"
I have eslint configuration which works perfectly fine on my local setup (with vscode editor).

but on CI Server, it fails with following error:

```<code>  eslint:config-array-factory Config file found: /home/worker/workspace/-CI-CD-Pipeline-Node-Ts_DC-705/.eslintrc.json +0ms
  eslint:config-array-factory Loading {extends:"standard"} relative to /home/worker/workspace/-CI-CD-Pipeline-Node-Ts_DC-705/.eslintrc.json +1ms

Oops! Something went wrong! :(

ESLint: 6.6.0.

ESLint couldn't find the config "standard" to extend from. Please check that the name of the config is correct.

The config "standard" was referenced from the config file in "/home/worker/workspace/-CI-CD-Pipeline-Node-Ts_DC-705/.eslintrc.json".

If you still have problems, please stop by https://gitter.im/eslint/eslint to chat with the team.
</code>```

I am running following command to lint:

./node_modules/.bin/eslint ./ --ext .ts

I see there are multiple issues on git related to this (https://github.com/microsoft/vscode-eslint/issues/696) but none has solution or that did not worked for me.

Can anyone please help me here.

答:
To disable eslint during build you can add this code to *.config file as described here

```<code>module.exports = {
    eslint: {
            ignoreDuringBuilds: true,
  },
}
</code>```

it helped me remove the error

Body:
I have eslint configuration which works perfectly fine on my local setup (with vscode editor).

but on CI Server, it fails with following error:

  eslint:config-array-factory Config file found: /home/worker/workspace/-CI-CD-Pipeline-Node-Ts_DC-705/.eslintrc.json +0ms
  eslint:config-array-factory Loading {extends:"standard"} relative to /home/worker/workspace/-CI-CD-Pipeline-Node-Ts_DC-705/.eslintrc.json +1ms

Oops! Something went wrong! :(

ESLint: 6.6.0.

ESLint couldn't find the config "standard" to extend from. Please check that the name of the config is correct.

The config "standard" was referenced from the config file in "/home/worker/workspace/-CI-CD-Pipeline-Node-Ts_DC-705/.eslintrc.json".

If you still have problems, please stop by https://gitter.im/eslint/eslint to chat with the team.

I am running following command to lint:

./node_modules/.bin/eslint ./ --ext .ts

I see there are multiple issues on git related to this (https://github.com/microsoft/vscode-eslint/issues/696) but none has solution or that did not worked for me.

Can anyone please help me here.

Body:
To disable eslint during build you can add this code to *.config file as described here

module.exports = {
    eslint: {
            ignoreDuringBuilds: true,
  },
}

it helped me remove the error


问:
Mat-table Sorting Demo not Working
I am trying to get the mat-table sorting to work locally, and while I can get the data to show up as expected, clicking on the header row does not do the sorting as it does on online examples (nothing happens at all).
I am trying to get this demo working locally:
https://material.angular.io/components/sort/overview
https://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview

I have generated a new project with Angular CLI, then followed these steps:
https://material.angular.io/guide/getting-started

Here are my local files:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSort, MatTableModule } from '@angular/material';

import { AppComponent } from './app.component';
import { TableSortingExample } from './table-sorting-example';

@NgModule({
  declarations: [
    AppComponent,
    TableSortingExample,
    MatSort
  ],
  imports: [
    BrowserModule,
    MatTableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

<p><strong>app.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}
</code>```

app.component.html

    Welcome to {{title}}!

```

<p><strong>table-sorting-example.html</strong></p>

<pre class="lang-html prettyprint-override"><code><div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource" matSort>

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- ID Column -->
    <ng-container matColumnDef="userId">
      <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
    </ng-container>

    <!-- Progress Column -->
    <ng-container matColumnDef="progress">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Progress </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.progress}}% </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="userName">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <!-- Color Column -->
    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Color </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.color}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>

<!-- Copyright 2017 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->
</code>```

table-sorting-example.ts

import {Component, ViewChild} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

/**
 * @title Table with sorting
 */
@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample {
  displayedColumns = ['userId', 'userName', 'progress', 'color'];
  exampleDatabase = new ExampleDatabase();
  dataSource: ExampleDataSource | null;

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);
  }
}

/** Constants used to fill up our data base. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}

/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
  get data(): UserData[] { return this.dataChange.value; }

  constructor() {
    // Fill up the database with 100 users.
    for (let i = 0; i < 100; i++) { this.addUser(); }
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      id: (this.data.length + 1).toString(),
      name: name,
      progress: Math.round(Math.random() * 100).toString(),
      color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
    };
  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase, private _sort: MatSort) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<UserData[]> {
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.sortChange,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      return this.getSortedData();
    });
  }

  disconnect() {}

  /** Returns a sorted copy of the database data. */
  getSortedData(): UserData[] {
    const data = this._exampleDatabase.data.slice();
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';

      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}

/**  Copyright 2017 Google Inc. All Rights Reserved.
 Use of this source code is governed by an MIT-style license that
 can be found in the LICENSE file at http://angular.io/license */
```

Does anyone have an idea of why it would show up like the online table but lack the sorting functionality?

答:
After spending time on this for weeks. I found out you the following

You need to import MatSortModule in your app.module.ts.

```<code> imports: [
    ...
    MatSortModule
],
</code>```

```<code><ng-container matColumnDef="ledgerTransactionCreditSum">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Ledger Transaction Credit </th>
        <td mat-cell *matCellDef="let element"> {{element.ledgerTransactionCreditSum}} </td>
    </ng-container>
 matColumnDef and element.ledgerTransactionCreditSum variable and matcolumn def shoulde be same
</code>```

Define the sort and paginator in ngViewInit

```<code>ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.dataSource.paginator?._changePageSize(400)
  }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Mat-table Sorting Demo not Working

Body:
I am trying to get the mat-table sorting to work locally, and while I can get the data to show up as expected, clicking on the header row does not do the sorting as it does on online examples (nothing happens at all).
I am trying to get this demo working locally:
https://material.angular.io/components/sort/overview
https://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview

I have generated a new project with Angular CLI, then followed these steps:
https://material.angular.io/guide/getting-started

Here are my local files:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSort, MatTableModule } from '@angular/material';

import { AppComponent } from './app.component';
import { TableSortingExample } from './table-sorting-example';

@NgModule({
  declarations: [
    AppComponent,
    TableSortingExample,
    MatSort
  ],
  imports: [
    BrowserModule,
    MatTableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

app.component.html

    Welcome to {{title}}!

table-sorting-example.html

  <mat-table #table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="userId">
      <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="progress">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Progress </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.progress}}% </mat-cell>
    </ng-container>

    <ng-container matColumnDef="userName">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Color </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.color}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>

table-sorting-example.ts

import {Component, ViewChild} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

/**
 * @title Table with sorting
 */
@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample {
  displayedColumns = ['userId', 'userName', 'progress', 'color'];
  exampleDatabase = new ExampleDatabase();
  dataSource: ExampleDataSource | null;

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);
  }
}

/** Constants used to fill up our data base. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}

/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
  get data(): UserData[] { return this.dataChange.value; }

  constructor() {
    // Fill up the database with 100 users.
    for (let i = 0; i < 100; i++) { this.addUser(); }
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      id: (this.data.length + 1).toString(),
      name: name,
      progress: Math.round(Math.random() * 100).toString(),
      color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
    };
  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase, private _sort: MatSort) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<UserData[]> {
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.sortChange,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      return this.getSortedData();
    });
  }

  disconnect() {}

  /** Returns a sorted copy of the database data. */
  getSortedData(): UserData[] {
    const data = this._exampleDatabase.data.slice();
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';

      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}

/**  Copyright 2017 Google Inc. All Rights Reserved.
 Use of this source code is governed by an MIT-style license that
 can be found in the LICENSE file at http://angular.io/license */

Does anyone have an idea of why it would show up like the online table but lack the sorting functionality?

Body:
After spending time on this for weeks. I found out you the following

You need to import MatSortModule in your app.module.ts.

 imports: [
    ...
    MatSortModule
],

<ng-container matColumnDef="ledgerTransactionCreditSum">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Ledger Transaction Credit </th>
        <td mat-cell *matCellDef="let element"> {{element.ledgerTransactionCreditSum}} </td>
    </ng-container>
 matColumnDef and element.ledgerTransactionCreditSum variable and matcolumn def shoulde be same

Define the sort and paginator in ngViewInit

ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.dataSource.paginator?._changePageSize(400)
  }


问:
Linking sfDoctrineGuardPlugin with my own model schema
Im developing kind of a plugin for an already working system, and i intend to use symfony. My plugin requires authentication, and i want to use the symfony sfDoctrineGuardPlugin. I generated the schema.yaml from the existing database, using the command: $ php symfony doctrine:build-schema, where i had already modeled my user table, with some fields i needed, and foreign keys to other tables.

When i installed the mentioned plugin, i realized it creates its own schema, separated from mine. Is there any way to add fields to sfDoctrineGuardPlugin's user table? can i make foreign keys in this table? can i reference this table from other tables? I need a way to fully customize the user table and class created by the plugin...

Thank you very much for your attention and help!!!

答:
The materials you got from LuisClemente are enough.

To add references you use usual way to do it.

schema.yml:

```<code>  sfGuardUser:
    columns:
      personal_info_id: { type: integer(5), notnull: false }
    relations:
      PersonalInfo:
        class: PPersonalInfo
        local: personal_info_id
        foreign: id
        onDelete: CASCADE

  PPersonalInfo:
    columns:
      last_name:          { type: string(127), notnull: false }
      first_name:       { type: string(127), notnull: false }
</code>```

For more info see symfony blog

Body:
The materials you got from LuisClemente are enough.

To add references you use usual way to do it.

schema.yml:

  sfGuardUser:
    columns:
      personal_info_id: { type: integer(5), notnull: false }
    relations:
      PersonalInfo:
        class: PPersonalInfo
        local: personal_info_id
        foreign: id
        onDelete: CASCADE

  PPersonalInfo:
    columns:
      last_name:          { type: string(127), notnull: false }
      first_name:       { type: string(127), notnull: false }

For more info see symfony blog


问:
Problem dropping same file twice in a row
I'm using the Dash Upload component, which in turn uses react-dropzone.

I can drag a file into the component and the corresponding callback will fire.

I can then drag a different file into the component and the callback will fire again.

But, if I drag a file into the component (which fires the callback) and then drag the same file into the component again, the callback does not fire.

There's a demo app in this Gist that demonstrates the behavior.

Searching for similar problems (stack-overflow, github) suggests that this behavior is to be expected because from the browser's point of view nothing has changed.  Both of those discussions seem to end up with solutions that involve setting the .value part of some element to '', so that the browser sees the second drop event as a change.

Chriddyp contributed links to the relevant bit of code in Dash and pointed me to the react-dropzone component.

Is there a way to make dropping the file twice in a row work in Dash using react-dropzone?

Thanks!

g.

答:
Another workaround, similar to @aura's, is to replace the upload component entirely with a callback. This strategy can be useful when replacing "contents" would lead to circular callbacks.

See https://github.com/plotly/dash-core-components/issues/816#issuecomment-1032635061


问:
Unable to copy file - access to the path is denied
I am using Visual Studio 2005. After taking code from version control first,
 the c#.net application runs correctly. But, after doing some modifications, when I build I am getting the following error:

Error  383 Unable to copy file "..\root\leaf\Bin\Debug\test.Resources.xml" to
      "Bin\Debug\test.Resources.xml". Access to the path 'Bin\Debug\test.Resources.xml' is
      denied. li.rollmodel

Does anybody know why this issue is occurring?

Edit I can see that my entire project source code folder is Read-only, and I am not able to remove the read-only property.

First, can anybody tell me how to remove the Read-only property for this folder? I have tried removing it but the read-only property persists. I tried from the version-control side also and that did not work, either.

答:
For those who still face this issue in VS 2019

1- Open terminal

2- write 'dotnet clean '


问:
Reusable javascript component issue
I have a woking accessible responsive navigation which for DEMO perpuses I have to make it reusable so I can show different sort of senarios. However tho, the click burger menu is not working.

This header with responsive navigation should work indipenently multiple times.

On click and matchMedia

typial responsive nav behavious with an extra touch of matchMedia in case user moves the window.

open navigation on click and remove navigation if > 900

navigation remove Attribute hidden on desktop and on click.

All of this should work multiple times.

```<code>if (navBlocks.length > 0){
        Array.prototype.forEach.call(navBlocks, function(el) {
</code>```

the forEach function shoud do the work right? how come is not really working?

DEMO HERE

const navBlocks = document.querySelectorAll('.nav-container');
const nav = document.querySelector('.sliding-nav');
const menu = document.querySelector(".sliding-nav ul");
const toggleMenu = document.querySelector(".nav-container .nav-cta");
const mediaQuery = window.matchMedia('(min-width: 900px)');

let isMenuOpen = false;

if (navBlocks.length > 0) {
  Array.prototype.forEach.call(navBlocks, function(el) {

    el.addEventListener('click', e => {

      e.preventDefault();

      isMenuOpen = !isMenuOpen;

      toggleMenu.setAttribute('aria-expanded', String(isMenuOpen));
      menu.hidden = !isMenuOpen;

      if (isMenuOpen) {
        nav.classList.add('is-open');
        document.body.classList.add("is-no-scroll", "is-fixed");
        //console.log(isMenuOpen);
      } else {
        nav.classList.remove('is-open');
        document.body.classList.remove("is-no-scroll", "is-fixed");
        //console.log(!isMenuOpen);
      }
    });

    function handleTabletChange(e) {
      // Check if the media query is true

      if (e.matches) {

        toggleMenu.setAttribute("aria-expanded", false);
        menu.removeAttribute("hidden");
        nav.classList.remove('is-open');
        document.body.classList.remove("is-no-scroll", "is-fixed");

      } else {
        toggleMenu.setAttribute("aria-expanded", false);
        //nav.removeAttribute("aria-expanded");

      }
    }

    // Register event listener
    mediaQuery.addListener(handleTabletChange);

    // Initial check
    handleTabletChange(mediaQuery);

  });
}```

答:
I think you should do something like this,
add event listener on burger menu icon to toggle an active class in nav bar and you should write css for that active class that if nav contains "active" class it should be set to display or else it should display none!</p>

Title: Reusable javascript component issue

Body:
I have a woking accessible responsive navigation which for DEMO perpuses I have to make it reusable so I can show different sort of senarios. However tho, the click burger menu is not working.

This header with responsive navigation should work indipenently multiple times.

On click and matchMedia

typial responsive nav behavious with an extra touch of matchMedia in case user moves the window.

open navigation on click and remove navigation if > 900

navigation remove Attribute hidden on desktop and on click.

All of this should work multiple times.

if (navBlocks.length > 0){
        Array.prototype.forEach.call(navBlocks, function(el) {

the forEach function shoud do the work right? how come is not really working?

DEMO HERE

const navBlocks = document.querySelectorAll('.nav-container');
const nav = document.querySelector('.sliding-nav');
const menu = document.querySelector(".sliding-nav ul");
const toggleMenu = document.querySelector(".nav-container .nav-cta");
const mediaQuery = window.matchMedia('(min-width: 900px)');

let isMenuOpen = false;

if (navBlocks.length > 0) {
  Array.prototype.forEach.call(navBlocks, function(el) {

    el.addEventListener('click', e => {

      e.preventDefault();

      isMenuOpen = !isMenuOpen;

      toggleMenu.setAttribute('aria-expanded', String(isMenuOpen));
      menu.hidden = !isMenuOpen;

      if (isMenuOpen) {
        nav.classList.add('is-open');
        document.body.classList.add("is-no-scroll", "is-fixed");
        //console.log(isMenuOpen);
      } else {
        nav.classList.remove('is-open');
        document.body.classList.remove("is-no-scroll", "is-fixed");
        //console.log(!isMenuOpen);
      }
    });

    function handleTabletChange(e) {
      // Check if the media query is true

      if (e.matches) {

        toggleMenu.setAttribute("aria-expanded", false);
        menu.removeAttribute("hidden");
        nav.classList.remove('is-open');
        document.body.classList.remove("is-no-scroll", "is-fixed");

      } else {
        toggleMenu.setAttribute("aria-expanded", false);
        //nav.removeAttribute("aria-expanded");

      }
    }

    // Register event listener
    mediaQuery.addListener(handleTabletChange);

    // Initial check
    handleTabletChange(mediaQuery);

  });
}


问:
how do i make a black background for a div with 50% transparency? alpha channel in rgba not working with black
alpha channel in rgba specifies the opacity for a color. It works when i use it with other colors, but with black, instead of changing the opacity, it is just making the black color lighter. How do i make it transparent?

background-color: rgba(0, 0, 0, 0.5);

答:
You haven't got a problem.

Try this simple snippet - the background has been set to a color other than white and you can see it mixing with the semi opaque black.

body {
  background-color: magenta;
  width: 100vw;
  height: 100vh;
}

div {
  background-color: rgba(0, 0, 0, 0.5);
  display: inline-block;
  width: 50%;
  height: 500%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div></div>
</body></code>```

It may be that you are expecting a different sort of black (gray)??

Body:
You haven't got a problem.

Try this simple snippet - the background has been set to a color other than white and you can see it mixing with the semi opaque black.

body {
  background-color: magenta;
  width: 100vw;
  height: 100vh;
}

div {
  background-color: rgba(0, 0, 0, 0.5);
  display: inline-block;
  width: 50%;
  height: 500%;
}

<body>
  <div></div>
</body>

It may be that you are expecting a different sort of black (gray)??


问:
Install Ruby 2.2 on Mac OSX Catalina with ruby-install
Here's what I get when I try to install Ruby 2.2:

```<code>$ ruby-install ruby 2.2.10
# ...
>>> Compiling ruby 2.2.10 ...
    CC = clang
    LD = ld
    LDSHARED = clang -dynamic -bundle
    CFLAGS = -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens   -pipe
    XCFLAGS = -D_FORTIFY_SOURCE=2 -fstack-protector -fno-strict-overflow -fvisibility=hidden -DRUBY_EXPORT -fPIE
    CPPFLAGS = -I/opt/X11/include -I/usr/local/opt/openssl@1.1/include -I/usr/local/opt/readline/include -I/usr/local/opt/libyaml/include -I/usr/local/opt/gdbm/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT   -I. -I.ext/include/x86_64-darwin19 -I./include -I.
    DLDFLAGS = -Wl,-undefined,dynamic_lookup -Wl,-multiply_defined,suppress -L/usr/local/opt/openssl@1.1/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/gdbm/lib  -fstack-protector -Wl,-u,_objc_msgSend -Wl,-pie -framework CoreFoundation
    SOLIBS = -lgmp
Apple clang version 12.0.0 (clang-1200.0.31.1)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
translating probes probes.d
. ./vm_opts.h
file2lastrev.rb: does not seem to be under a vcs: .
make: [.revision.time] Error 1 (ignored)
./revision.h unchanged
compiling main.c
compiling dmydln.c
compiling miniinit.c
compiling miniprelude.c
compiling array.c
compiling bignum.c
compiling class.c
compiling compar.c
compiling complex.c
compiling dir.c
compiling dln_find.c
compiling encoding.c
encoding.c:825:2: error: implicit declaration of function 'rb_str_change_terminator_length' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
        rb_str_change_terminator_length(obj, oldtermlen, termlen);
        ^
1 error generated.
make: *** [encoding.o] Error 1
!!! Compiling ruby 2.2.10 failed!
</code>```

OS Version: 10.15.6

ruby-install version: 0.7.1

Any ideas on how to debug or fix this? I was previously able to install other versions of 2.2 before I upgraded my OS. I'm also able to install later versions like Ruby 2.7 with no problem

答:
I recently had to install ruby-2.2.0 in Catalina 10.15.7 and was facing the same issues. But luckily managed to get my work done. Steps are as follows:

Installed openssl as a rvm package:

 ```$ rvm pkg install openssl```

Ignored compiler warnings:

 ```$ export optflags="-Wno-error=implicit-function-declaration"```

Installed required ruby version (2.2.0 in my case) while providing openssl directory parameter and ignoring rubygems:

 ```$ rvm install 2.2.0 --with-openssl-dir=$rvm_path/usr --rubygems ignore```

Body:
Here's what I get when I try to install Ruby 2.2:

$ ruby-install ruby 2.2.10
# ...
>>> Compiling ruby 2.2.10 ...
    CC = clang
    LD = ld
    LDSHARED = clang -dynamic -bundle
    CFLAGS = -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens   -pipe
    XCFLAGS = -D_FORTIFY_SOURCE=2 -fstack-protector -fno-strict-overflow -fvisibility=hidden -DRUBY_EXPORT -fPIE
    CPPFLAGS = -I/opt/X11/include -I/usr/local/opt/openssl@1.1/include -I/usr/local/opt/readline/include -I/usr/local/opt/libyaml/include -I/usr/local/opt/gdbm/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT   -I. -I.ext/include/x86_64-darwin19 -I./include -I.
    DLDFLAGS = -Wl,-undefined,dynamic_lookup -Wl,-multiply_defined,suppress -L/usr/local/opt/openssl@1.1/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/gdbm/lib  -fstack-protector -Wl,-u,_objc_msgSend -Wl,-pie -framework CoreFoundation
    SOLIBS = -lgmp
Apple clang version 12.0.0 (clang-1200.0.31.1)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
translating probes probes.d
. ./vm_opts.h
file2lastrev.rb: does not seem to be under a vcs: .
make: [.revision.time] Error 1 (ignored)
./revision.h unchanged
compiling main.c
compiling dmydln.c
compiling miniinit.c
compiling miniprelude.c
compiling array.c
compiling bignum.c
compiling class.c
compiling compar.c
compiling complex.c
compiling dir.c
compiling dln_find.c
compiling encoding.c
encoding.c:825:2: error: implicit declaration of function 'rb_str_change_terminator_length' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
        rb_str_change_terminator_length(obj, oldtermlen, termlen);
        ^
1 error generated.
make: *** [encoding.o] Error 1
!!! Compiling ruby 2.2.10 failed!

OS Version: 10.15.6

ruby-install version: 0.7.1

Any ideas on how to debug or fix this? I was previously able to install other versions of 2.2 before I upgraded my OS. I'm also able to install later versions like Ruby 2.7 with no problem

Body:
I recently had to install ruby-2.2.0 in Catalina 10.15.7 and was facing the same issues. But luckily managed to get my work done. Steps are as follows:

Installed openssl as a rvm package:

$ rvm pkg install openssl

Ignored compiler warnings:

$ export optflags="-Wno-error=implicit-function-declaration"

Installed required ruby version (2.2.0 in my case) while providing openssl directory parameter and ignoring rubygems:

$ rvm install 2.2.0 --with-openssl-dir=$rvm_path/usr --rubygems ignore


问:
Sort a list of object w.r.t to a particular member/state
I have a list of java object that have 4 members.

```<code>int id;
String name;
String age;
int order;
</code>```

I want to sort the list of this object w.r.t name

答:
You can create a comparator that compares 2 objects from that type by their names, and sort using this comparator:

```<code>private static class MyComparator implements Comparator<MyType>
{

    @Override
    public int compare(MyType o1, MyType o2)
    {
        return o1.getName().compareTo(o2.getName());
    }

}
</code>```

And then sort:

```<code> Collections.sort(list, myComparator);
</code>```

Body:
I have a list of java object that have 4 members.

int id;
String name;
String age;
int order;

I want to sort the list of this object w.r.t name

Body:
You can create a comparator that compares 2 objects from that type by their names, and sort using this comparator:

private static class MyComparator implements Comparator<MyType>
{

    @Override
    public int compare(MyType o1, MyType o2)
    {
        return o1.getName().compareTo(o2.getName());
    }

}

And then sort:

 Collections.sort(list, myComparator);


问:
I have a hard time understanding the purpose of a "backing property"
I am learning Kotlin right now. For context, I am a Java developer for +10 years.

I stumbled upon the concept of backing properties. As I understand it, the problem to be solved is this: I have a property in a class. I want this property to be mutable and visible only in the containing class, so I declare it as private var. The property should only be modified in the containing class, but it should be readable outside the class. So, the Kotlin docs propose something like this:

private var _word = "test"
val word: String
   get() = _word
```
<p>This works and fulfills the above requirements, but this looks a bit odd, for a Java developer. In Java, we only need 1 field (there is no such thing as a property in Java):</p>
```private String word = "test";

public String getWord() {
   return word;
}
```
<p>AFAIK, same result.</p>
<p>Today I learned that in Kotlin, I simply can make a setter private. So what about this Kotlin code:</p>
```var word = "test"
     private set
```

All requirements fulfilled, much more concise code.

Im I missing something? Why do I need a backing property?

答:
You're right, there's no reason to do this:

```<code>private var _word = "test"
val word: String
   get() = _word
</code>```

Because you can just do this:

```<code>var word = "test"
    private set
</code>```

Just like in Java with a private field and a getter method, you can choose later to change getter logic without breaking external code. In Java you could choose to do something more complicated than use a single private backing field. Maybe calculate something involving multiple backing fields, etc. In Kotlin, you can come back later and change it to use other backing properties later if it gets more complicated, and change only the getter implementation.

The most common reason I've seen to use a backing property is so you can return a less specific type in your public property:

```<code>private val _myList: MutableList<String> = mutableListOf()
val myList: List<String> get() = _myList
</code>```

This code helps prevent outside classes from mutating the returned list.

The Kotlin designers have mentioned in presentations that they plan to add a new syntax in the future that will eliminate the need for a backing property in this use case. Something like this:

```<code>// Not valid syntax yet in Kotlin 1.6
private val myList: MutableList<String> = mutableListOf()
    public get: List<String>
</code>```

Another reason to have a backing property is simply when there isn't a one-to-one correspondence between what you're returning and how it is stored or generated. For example:

```<code>private val myRandom = Random(1234)
val aNumber: Int get() = myRandom.nextInt(100)
</code>```

Body:
I am learning Kotlin right now. For context, I am a Java developer for +10 years.

I stumbled upon the concept of backing properties. As I understand it, the problem to be solved is this: I have a property in a class. I want this property to be mutable and visible only in the containing class, so I declare it as private var. The property should only be modified in the containing class, but it should be readable outside the class. So, the Kotlin docs propose something like this:

private var _word = "test"
val word: String
   get() = _word

This works and fulfills the above requirements, but this looks a bit odd, for a Java developer. In Java, we only need 1 field (there is no such thing as a property in Java):

private String word = "test";

public String getWord() {
   return word;
}

AFAIK, same result.

Today I learned that in Kotlin, I simply can make a setter private. So what about this Kotlin code:

var word = "test"
     private set

All requirements fulfilled, much more concise code.

Im I missing something? Why do I need a backing property?

Body:
You're right, there's no reason to do this:

private var _word = "test"
val word: String
   get() = _word

Because you can just do this:

var word = "test"
    private set

Just like in Java with a private field and a getter method, you can choose later to change getter logic without breaking external code. In Java you could choose to do something more complicated than use a single private backing field. Maybe calculate something involving multiple backing fields, etc. In Kotlin, you can come back later and change it to use other backing properties later if it gets more complicated, and change only the getter implementation.

The most common reason I've seen to use a backing property is so you can return a less specific type in your public property:

private val _myList: MutableList<String> = mutableListOf()
val myList: List<String> get() = _myList

This code helps prevent outside classes from mutating the returned list.

The Kotlin designers have mentioned in presentations that they plan to add a new syntax in the future that will eliminate the need for a backing property in this use case. Something like this:

// Not valid syntax yet in Kotlin 1.6
private val myList: MutableList<String> = mutableListOf()
    public get: List<String>

Another reason to have a backing property is simply when there isn't a one-to-one correspondence between what you're returning and how it is stored or generated. For example:

private val myRandom = Random(1234)
val aNumber: Int get() = myRandom.nextInt(100)


问:
How to mimic Audacity's "truncate silence" with ffmpeg "silenceremove" filter
I want to remove completely silence parts from wav files with ffmpeg.

Input wav can be like :

I am using the following ffmpeg command to remove silence part ffmpeg -i input.wav -af silenceremove=stop_periods=-1:stop_duration=0.2:stop_threshold=-45dB output.wav because I understand from the doc that it will remove all silence parts longer than 0.2 s (silence being below -45dB).

But I get that  where silence part has only been reduced to around 0.1 wheras I want it to be 0 (no remaining silence).

In Audacity I will use "truncate audio" filter and choose the above parameters to detect silence and in the action part I will choose to truncate to 0: .

This will yield to what I want (ie an audio with no silence part remaining):

Searching on the internet only lead me to what I already do.

So how can I reproduce the output I get from Audacity "Truncate Silence" filter with ffmpeg and remove all silence parts from audio ?

Edit: The output from silencedetect filter is correct: ffmpeg -i input.wav -af silencedetect=0.2:n=-45dB -f null - detects exactly what audacity detects.

Thanks in advance for your help

答:
It looks like the equivalent command to AUdacity's truncate silence behaviour is the following (in bold what is added):

ffmpeg -i input.wav -af silenceremove=start_periods=1:stop_periods=-1:stop_duration=0.2:start_threshold=-45dB:stop_threshold=-45dB output.wav

I am not sure why adding those 2 parameters leads to the expected behaviour but it works although for some files silenceremove can remove more parts than Audacity / silencedetect detect.


问:
awk calculate the difference with last row and create new column with value
I have a file like this :

```<code>time,VALUE
2022-02-02 00:00:39,57
2022-02-02 00:01:39,58
2022-02-02 00:02:39,59
2022-02-02 00:03:39,59
2022-02-02 00:04:40,62
2022-02-02 00:05:40,60
</code>```

And I would like (maybe the better choice is awk) to create a new column which calculate the difference with last row. Example :

```<code>time,VALUE,Diff
2022-02-02 00:00:39,57,0
2022-02-02 00:01:39,58,1
2022-02-02 00:02:39,59,1
2022-02-02 00:03:39,59,0
2022-02-02 00:04:40,62,3
2022-02-02 00:05:40,60,-2
</code>```

I have this little script  awk 'NR==1{s=$1;next}{print $1-s;s=$1}' but I don't know how to easily add a new colum with results and to add a '0' for the first line

Thanks

Body:
I have a file like this :

time,VALUE
2022-02-02 00:00:39,57
2022-02-02 00:01:39,58
2022-02-02 00:02:39,59
2022-02-02 00:03:39,59
2022-02-02 00:04:40,62
2022-02-02 00:05:40,60

And I would like (maybe the better choice is awk) to create a new column which calculate the difference with last row. Example :

time,VALUE,Diff
2022-02-02 00:00:39,57,0
2022-02-02 00:01:39,58,1
2022-02-02 00:02:39,59,1
2022-02-02 00:03:39,59,0
2022-02-02 00:04:40,62,3
2022-02-02 00:05:40,60,-2

I have this little script  awk 'NR==1{s=$1;next}{print $1-s;s=$1}' but I don't know how to easily add a new colum with results and to add a '0' for the first line

Thanks

Body:
You can define special rules for the first two lines

awk -F "," -v OFS="," 'NR==1{print $0,"Diff"}
                       NR==2{print $0,0}
                       NR>2{print $0,$2-last} {last=$2}' file
time,VALUE,Diff
2022-02-02 00:00:39,57,0
2022-02-02 00:01:39,58,1
2022-02-02 00:02:39,59,1
2022-02-02 00:03:39,59,0
2022-02-02 00:04:40,62,3
2022-02-02 00:05:40,60,-2


问:
PHP-Isset function is not working
I am new to PHP. My isset function is not working .It does not not show  error .It always insert the table. I have given my code. Kindly advice what i done wrong on this

```<code><?php
if(isset($_POST['submit'])) {
    $a= $_POST['companyname'];
    $b= $_POST['ballpark_url'];
    $c= $_POST['username'];
    $d= $_POST['email'];
    $e= $_POST['login1'];
    $f= $_POST['pass'];
    $error = false;
    if(validname($a) ==false) {
        echo $nameerror = "enter the valid name";
    }
    if(validemail($d) ==false) {
        echo $nameerror = "enter the valid email";
    }
    if(isset($_POST['companyname'])) {
        if($error==false) {
            $query= "INSERT INTO user VALUES ('$a','$b','$c','$d','$e','$f','');";
            if(!mysql_query($query)) {
                die ('error:'.mysql_error());
            }
            mysql_close($conn);
        }
        include("templats/header_1.html");
        include("templats/content.html");
        include("templats/footer.html");
    }
?>
</code>```

kindly rectify the issue in my code and send back to me...

答:
Check if you have a line in your form like

```<code> <input type="submit" name="submit" value="submitOrSomething">
</code>```

Your isset checks if a name value pair exist with the key "submit". So if you have a submit button but it has a different name other than submit then you have to use that with isset.

Title: PHP-Isset function is not working

Body:
I am new to PHP. My isset function is not working .It does not not show  error .It always insert the table. I have given my code. Kindly advice what i done wrong on this

<?php
if(isset($_POST['submit'])) {
    $a= $_POST['companyname'];
    $b= $_POST['ballpark_url'];
    $c= $_POST['username'];
    $d= $_POST['email'];
    $e= $_POST['login1'];
    $f= $_POST['pass'];
    $error = false;
    if(validname($a) ==false) {
        echo $nameerror = "enter the valid name";
    }
    if(validemail($d) ==false) {
        echo $nameerror = "enter the valid email";
    }
    if(isset($_POST['companyname'])) {
        if($error==false) {
            $query= "INSERT INTO user VALUES ('$a','$b','$c','$d','$e','$f','');";
            if(!mysql_query($query)) {
                die ('error:'.mysql_error());
            }
            mysql_close($conn);
        }
        include("templats/header_1.html");
        include("templats/content.html");
        include("templats/footer.html");
    }
?>

kindly rectify the issue in my code and send back to me...

Body:
Check if you have a line in your form like

 <input type="submit" name="submit" value="submitOrSomething">

Your isset checks if a name value pair exist with the key "submit". So if you have a submit button but it has a different name other than submit then you have to use that with isset.


问:
Restart .NET AnyCPU exe with different bitness
I have a .NET exe compiled for "AnyCPU", so it can theoretically run in both 32-bit and 64-bit mode (on a 64-bit operating system). Since my exe strongly interacts with MS Office, I need to run it with the same bitness as the installed Office version. (Please take this requirement as granted, I will gladly provide details in the comments, if you are interested.)

Now, I have thought up a solution for this, but it seems more complicated than necessary:

Compile two versions: MyExe32.exe and MyExe64.exe, targeting x86 and x64, respectively, instead of AnyCPU.

Create a launcher application Launcher.exe, which determines the bitness of the locally installed Office version (I know how to do that) and then starts MyExe32.exe or MyExe64.exe.

This would work, but I'd rather have a single, simple MyExe.exe with something like the following pseudo-code during start-up:

```<code>if (Environment.Is64BitProcess && IsOffice32BitInstalled)
{
    // restart myself in a 32-bit process instead of a 64-bit process
    ???  // <-- this is where I need help
}
</code>```

Is that possible? If yes, how?

Notes: I know about the CorFlags utility, but I'd rather have a solution that does not require modifying the exe itself at runtime.

答:
Is restarting via runtime parameter an option?

```<code>dotnet run -r win-x86
</code>```

https://stackoverflow.com/a/63252884/18152293

Body:
I have a .NET exe compiled for "AnyCPU", so it can theoretically run in both 32-bit and 64-bit mode (on a 64-bit operating system). Since my exe strongly interacts with MS Office, I need to run it with the same bitness as the installed Office version. (Please take this requirement as granted, I will gladly provide details in the comments, if you are interested.)

Now, I have thought up a solution for this, but it seems more complicated than necessary:

Compile two versions: MyExe32.exe and MyExe64.exe, targeting x86 and x64, respectively, instead of AnyCPU.

Create a launcher application Launcher.exe, which determines the bitness of the locally installed Office version (I know how to do that) and then starts MyExe32.exe or MyExe64.exe.

This would work, but I'd rather have a single, simple MyExe.exe with something like the following pseudo-code during start-up:

if (Environment.Is64BitProcess && IsOffice32BitInstalled)
{
    // restart myself in a 32-bit process instead of a 64-bit process
    ???  // <-- this is where I need help
}

Is that possible? If yes, how?

Notes: I know about the CorFlags utility, but I'd rather have a solution that does not require modifying the exe itself at runtime.

Body:
Is restarting via runtime parameter an option?

dotnet run -r win-x86

https://stackoverflow.com/a/63252884/18152293


问:
Pandas: Censoring subjects in longitudinal data based on criteria in another column
I have a dataframe of longitudinal data for subjects in a study. Each subject has repeated observations at a different time point Wave. One data point condition_A is expressed as a string with possible values (normal, MCI, dementia) where all subjects have condition_A = normal at Wave 1. Some subjects go on to develop condition_A = dementia or condition_A = MCI at varying time points. Other subjects condition_A = normal at all time points.

I am trying to find a way to exclude data from subjects with condition_A = dementia from the time point where condition_A first equals dementia and any future waves, while preserving any preceding data.

Data frame is set up as below:

```<code>>>> index = pd.MultiIndex.from_arrays([[1,1,1,2,2,2,3,3,3,4,4,4],[1,2,3]*4], names = ('SubjectID', 'Wave'))
>>> df = pd.DataFrame({"condition_A":['normal', 'normal', 'normal', 'normal', 'normal', 'dementia', 'normal', 'MCI', 'dementia', 'normal', 'dementia', 'dementia']}, index=index)

>>> df
               condition_A
SubjectID Wave
1         1         normal
          2         normal
          3         normal
2         1         normal
          2         normal
          3       dementia
3         1         normal
          2            MCI
          3       dementia
4         1         normal
          2       dementia
          3       dementia
</code>```

The desired output I want is:

```<code>               condition_A
SubjectID Wave
1         1         normal
          2         normal
          3         normal
2         1         normal
          2         normal
3         1         normal
          2            MCI
4         1         normal
</code>```

One approach I tried was to use an external Series object to store the inclusion/exclusion status of each subject, then use apply on each row:

```<code>>>> df['condition_A_exclude'] = False
>>> subject_list = pd.Series(False, index=index.levels[0])
Int64Index([1, 2, 3], dtype='int64', name='SubjectID')
>>> def determine_condition_A(row):
...     index = row['SubjectID']
...     if subject_list.loc[index]:
...         row['condition_A_exclude'] = True
...     elif row['condition_A']=='dementia':
...          subject_list.loc[index] = True
...          row['condition_A_exclude'] = True
...     return row

>>> df.apply(determine_condition_A, axis = 'columns')
</code>```

This approach works, but it relies on an external Series. I wondered if there was a way to accomplish this in place?

答:
To exclude all data (True or False), per SubjectID as soon as there is a True, you can use groupby+cummax to compute a mask:

```<code>mask = df.groupby(level='SubjectID')['condition_A'].cummax()
# updated example with "dementia"
mask = df['condition_A'].eq('dementia').groupby(level='SubjectID').cummax()

df.loc[~mask]
</code>```

output:

```<code>                condition_A
SubjectID Wave
1         1           False
2         1           False
          2           False
3         1           False
          2           False
          3           False
</code>```

Body:
I have a dataframe of longitudinal data for subjects in a study. Each subject has repeated observations at a different time point Wave. One data point condition_A is expressed as a string with possible values (normal, MCI, dementia) where all subjects have condition_A = normal at Wave 1. Some subjects go on to develop condition_A = dementia or condition_A = MCI at varying time points. Other subjects condition_A = normal at all time points.

I am trying to find a way to exclude data from subjects with condition_A = dementia from the time point where condition_A first equals dementia and any future waves, while preserving any preceding data.

Data frame is set up as below:

>>> index = pd.MultiIndex.from_arrays([[1,1,1,2,2,2,3,3,3,4,4,4],[1,2,3]*4], names = ('SubjectID', 'Wave'))
>>> df = pd.DataFrame({"condition_A":['normal', 'normal', 'normal', 'normal', 'normal', 'dementia', 'normal', 'MCI', 'dementia', 'normal', 'dementia', 'dementia']}, index=index)

>>> df
               condition_A
SubjectID Wave
1         1         normal
          2         normal
          3         normal
2         1         normal
          2         normal
          3       dementia
3         1         normal
          2            MCI
          3       dementia
4         1         normal
          2       dementia
          3       dementia

The desired output I want is:

               condition_A
SubjectID Wave
1         1         normal
          2         normal
          3         normal
2         1         normal
          2         normal
3         1         normal
          2            MCI
4         1         normal

One approach I tried was to use an external Series object to store the inclusion/exclusion status of each subject, then use apply on each row:

>>> df['condition_A_exclude'] = False
>>> subject_list = pd.Series(False, index=index.levels[0])
Int64Index([1, 2, 3], dtype='int64', name='SubjectID')
>>> def determine_condition_A(row):
...     index = row['SubjectID']
...     if subject_list.loc[index]:
...         row['condition_A_exclude'] = True
...     elif row['condition_A']=='dementia':
...          subject_list.loc[index] = True
...          row['condition_A_exclude'] = True
...     return row

>>> df.apply(determine_condition_A, axis = 'columns')

This approach works, but it relies on an external Series. I wondered if there was a way to accomplish this in place?

Body:
To exclude all data (True or False), per SubjectID as soon as there is a True, you can use groupby+cummax to compute a mask:

mask = df.groupby(level='SubjectID')['condition_A'].cummax()
# updated example with "dementia"
mask = df['condition_A'].eq('dementia').groupby(level='SubjectID').cummax()

df.loc[~mask]

output:

                condition_A
SubjectID Wave
1         1           False
2         1           False
          2           False
3         1           False
          2           False
          3           False


问:
Groovy JSON slurper check child element failed
I have this JSON input

```<code>{ "field": "AAA", "list": { "item": [ { "field01": "111", "field02": "222" }, { "field01": "333", "field02": "444" } ] }}
</code>```

I need to do something on this json based on this condition: item count > 0.
I'm trying this code.

```<code>def myJson = '..' //above json; def jsonParser = new JsonSlurper(); def jsonObject=jsonParser.parseText(myJson); jsonObject.list.item.size()
</code>```

But when item doesn't exist I get an exception. How can I get a value telling me item exists under list?

答:
To check, if there is a item:</p>
```<code>if (jsonObject.list.item)
{
  // do your things...
}
else
{
  // no item, so what?
}
</code>```

Body:
I have this JSON input

{ "field": "AAA", "list": { "item": [ { "field01": "111", "field02": "222" }, { "field01": "333", "field02": "444" } ] }}

I need to do something on this json based on this condition: item count > 0.
I'm trying this code.

def myJson = '..' //above json; def jsonParser = new JsonSlurper(); def jsonObject=jsonParser.parseText(myJson); jsonObject.list.item.size()

But when item doesn't exist I get an exception. How can I get a value telling me item exists under list?

Body:
To check, if there is a item:

if (jsonObject.list.item)
{
  // do your things...
}
else
{
  // no item, so what?
}


问:
Sending calculated data from one component to another without Services
I want to send the value from one component to another, they are not related so all solutions are saying that I must use shared service to do that. But these services are using templates (if I'm right). Is there a way to do this sharing without services?

I want to send the BMI value from homepage.component.ts to result.component.ts.

homepage.component.ts:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight

console.log(this.bmi); //this is the calculated value to send

  }
}
</code>```

result.component.ts:

```<code>    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
      constructor() { }

//I want to get the bmi here
      ngOnInit(): void {
      }

    }
</code>```

答:
If your components are not related then you can create a shared service between them. Then, you need to use dependency injection to communicate between these components. So, there is a great Angular tutorial which describes how to do it.

The service code would look like this:

```<code>@Injectable()
export class FooService {

  constructor(  ) { }

  private yourData;

  setData(data){
    this.yourData = data;
  }

  getData(){
    let temp = this.yourData;
    this.clearData();
    return temp;
  }
}
</code>```

and sender component:

```<code>import { Router } from '@angular/router';
import { FooService} from './services/foo.service';

export class SenderComponent implements OnInit {
  constructor(
    private fooService: FooService,
    private router:Router) {}

  somefunction(data){
   this.fooService.setData(data);
   this.router.navigateByUrl('/reciever');//as per router
 }
}
</code>```

and subscriber:

```<code>import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class RecieverComponent implements OnInit {
    data;

    constructor(
        private fooService: FooService){
    }

    ngOnInit() {
        data = this.transfereService.getData();
        console.log(`data: `, data)
    }
}

</code>```

Body:
I want to send the value from one component to another, they are not related so all solutions are saying that I must use shared service to do that. But these services are using templates (if I'm right). Is there a way to do this sharing without services?

I want to send the BMI value from homepage.component.ts to result.component.ts.

homepage.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight

console.log(this.bmi); //this is the calculated value to send

  }
}

result.component.ts:

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
      constructor() { }

//I want to get the bmi here
      ngOnInit(): void {
      }

    }

Body:
If your components are not related then you can create a shared service between them. Then, you need to use dependency injection to communicate between these components. So, there is a great Angular tutorial which describes how to do it.

The service code would look like this:

@Injectable()
export class FooService {

  constructor(  ) { }

  private yourData;

  setData(data){
    this.yourData = data;
  }

  getData(){
    let temp = this.yourData;
    this.clearData();
    return temp;
  }
}

and sender component:

import { Router } from '@angular/router';
import { FooService} from './services/foo.service';

export class SenderComponent implements OnInit {
  constructor(
    private fooService: FooService,
    private router:Router) {}

  somefunction(data){
   this.fooService.setData(data);
   this.router.navigateByUrl('/reciever');//as per router
 }
}

and subscriber:

import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class RecieverComponent implements OnInit {
    data;

    constructor(
        private fooService: FooService){
    }

    ngOnInit() {
        data = this.transfereService.getData();
        console.log(`data: `, data)
    }
}


问:
how to show message in apex when data already exist?
I want to show message using dynamic action say this data already exist
after check the database
i tried to do that using excute server side code then alert
i tried to use trigger and automation</p>

答:
You didn't describe what you're doing so I'm assuming this is a form region and you want the message to appear on change of the page item.
Here is an example with a form on the EMP/DEPT sample data. Functionality is that on change of the item P59_ENAME, a dynamic action fires and shows a javascript alert if the ename already exists. In my case this is page 59. I tested this on apex 21.2

Create a form on table EMP

Create an additional page item of type "Hidden" named P59_ENAME_EXISTS

Create a dynamic action on the item P59_ENAME

Add a first true action to execute the pl/sql code. This will set a value for the page item P59_ENAME_EXISTS (Y if ename exists, N if it does not exist). Note the "items to submit" and "items to return" values - those are very important.

Add a second true action to show the javascript alert if ename already exists. Note the client side condition.

Add a 3rd action to reset the value of page item P59_ENAME_EXISTS

Run the form, change the ENAME to an existing value and click in another field on the page. You'll get the popup.

Triggers or Automations cannot be used to achieve this functionality.


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

I have this piece of code:

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

This loop is long I get this error:

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

What can I do?

UPDATE:

If i use closeAllConnections() I get:

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

答: Close some connections? Could be as easy as inserting closeAllConnections() at the end of that loop body.

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

I have this piece of code:

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

This loop is long I get this error:

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

What can I do?

UPDATE:

If i use closeAllConnections() I get:

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


问:
Laravel Throttle overwrite in second
How to use laravel throttle in second instead of in minute?
I want to use this for chat app, and i think limiting it to second will be better.

and i tried to overwrite the laravel middleWareGroup throttle with this

```<code>Route::get("/v0/chat/get/{room}","chatController@chat_get")->middleware('throttle:120,1');
</code>```

but the ->middleware() overwrite failed. Thanks

答:
With this issue, you can use throttle in seconds.

Now it is possible to use float for seconds, like 0.5 = 30 seconds.

Title: Laravel Throttle overwrite in second

Body:
How to use laravel throttle in second instead of in minute?
I want to use this for chat app, and i think limiting it to second will be better.

and i tried to overwrite the laravel middleWareGroup throttle with this

Route::get("/v0/chat/get/{room}","chatController@chat_get")->middleware('throttle:120,1');

but the ->middleware() overwrite failed. Thanks


问:
Converting an object to a string
How can I convert a JavaScript object into a string?

Example:

```<code>var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
</code>```

Output:

Object { a=1, b=2} // very nice readable output :)

  Item: [object Object] // no idea what's inside :(

答:
A modified approach using reduce that let to change the separator sep between (key,value) tuple while checking last item:

```<code>/**
     * Object to string
     * @param {*} obj
     * @param {*} k_sep keys separator
     * @param {*} v_sep values separator
     * @returns
     */
    var objectToString: function (obj, k_sep = '=', v_sep = ',') {
      const entries = Object.entries(obj);
      return entries.reduce((str, [p, val], counter) => {
        if (counter < entries.length - 1) {
          return `${str}${p}${k_sep}${val}${v_sep}`;
        } else {
          return `${str}${p}${k_sep}${val}`;
        }
      }, '');
    }
</code>```

/**
 * Object to string
 * @param {*} obj
 * @param {*} k_sep keys separator
 * @param {*} v_sep values separator
 * @returns
 */
var objectToString = function(obj, k_sep = '=', v_sep = ',') {
  const entries = Object.entries(obj);
  return entries.reduce((str, [p, val], counter) => {
    if (counter < entries.length - 1) {
      return `${str}${p}${k_sep}${val}${v_sep}`;
    } else {
      return `${str}${p}${k_sep}${val}`;
    }
  }, '');
}

console.log(
  objectToString({
    status_code: 200,
    execute_time: 0.1,
    ip: '1270.0.0.1'
  }, ':', ","))
console.log(
  objectToString({
    status_code: 200,
    execute_time: 0.1,
    ip: '1270.0.0.1'
  }, '=', ","))```

Title: Converting an object to a string

Body:
How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

Output:

Object { a=1, b=2} // very nice readable output :)

  Item: [object Object] // no idea what's inside :(

Body:
A modified approach using reduce that let to change the separator sep between (key,value) tuple while checking last item:

/**
     * Object to string
     * @param {*} obj
     * @param {*} k_sep keys separator
     * @param {*} v_sep values separator
     * @returns
     */
    var objectToString: function (obj, k_sep = '=', v_sep = ',') {
      const entries = Object.entries(obj);
      return entries.reduce((str, [p, val], counter) => {
        if (counter < entries.length - 1) {
          return `${str}${p}${k_sep}${val}${v_sep}`;
        } else {
          return `${str}${p}${k_sep}${val}`;
        }
      }, '');
    }

/**
 * Object to string
 * @param {*} obj
 * @param {*} k_sep keys separator
 * @param {*} v_sep values separator
 * @returns
 */
var objectToString = function(obj, k_sep = '=', v_sep = ',') {
  const entries = Object.entries(obj);
  return entries.reduce((str, [p, val], counter) => {
    if (counter < entries.length - 1) {
      return `${str}${p}${k_sep}${val}${v_sep}`;
    } else {
      return `${str}${p}${k_sep}${val}`;
    }
  }, '');
}

console.log(
  objectToString({
    status_code: 200,
    execute_time: 0.1,
    ip: '1270.0.0.1'
  }, ':', ","))
console.log(
  objectToString({
    status_code: 200,
    execute_time: 0.1,
    ip: '1270.0.0.1'
  }, '=', ","))