问:
error LNK2001: unresolved external symbol v8::platform::NewDefaultPlatform
I'm getting linking error while trying to create
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform(0, v8::platform::IdleTaskSupport::kEnabled); in v8 ver 8.2.77

This my v8 build command

```<code>call gn gen out.gn/library --args="is_debug=false is_component_build=true v8_use_external_startup_data=true v8_static_library=false use_custom_libcxx=false use_custom_libcxx_for_host=true v8_enable_i18n_support=false target_cpu=\"x64\""
call ninja -C out.gn/library v8.dll
</code>```

Link lib(s)

```<code>v8.dll.lib
v8_libbase.dll.lib
v8_libplatform.dll.lib
</code>```

Error Message by Visual Studio 2019

```<code>class std::unique_ptr<class v8::Platform,struct std::default_delete<class v8::Platform> > __cdecl v8::platform::NewDefaultPlatform(int,enum v8::platform::IdleTaskSupport,enum v8::platform::InProcessStackDumping,class std::unique_ptr<class v8::TracingController,struct std::default_delete<class v8::TracingController> >)" (?NewDefaultPlatform@platform@v8@@YA?AV?$unique_ptr@VPlatform@v8@@U?$default_delete@VPlatform@v8@@@std@@@std@@HW4IdleTaskSupport@12@W4InProcessStackDumping@12@V?$unique_ptr@VTracingController@v8@@U?$default_delete@VTracingController@v8@@@std@@@4@@Z)
</code>```

答:
This bellow command is works and can be linked VS2019 C++ projects.

This given solution bring from groups.google.com

```<code>call gn gen out.gn/x64.release --args="is_debug=false use_glib=false is_component_build=true v8_use_external_startup_data=true v8_static_library=false is_clang = false v8_enable_i18n_support=false target_cpu=\"x64\""
</code>```

Body:
I'm getting linking error while trying to create
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform(0, v8::platform::IdleTaskSupport::kEnabled); in v8 ver 8.2.77

This my v8 build command

call gn gen out.gn/library --args="is_debug=false is_component_build=true v8_use_external_startup_data=true v8_static_library=false use_custom_libcxx=false use_custom_libcxx_for_host=true v8_enable_i18n_support=false target_cpu=\"x64\""
call ninja -C out.gn/library v8.dll

Link lib(s)

v8.dll.lib
v8_libbase.dll.lib
v8_libplatform.dll.lib

Error Message by Visual Studio 2019

class std::unique_ptr<class v8::Platform,struct std::default_delete<class v8::Platform> > __cdecl v8::platform::NewDefaultPlatform(int,enum v8::platform::IdleTaskSupport,enum v8::platform::InProcessStackDumping,class std::unique_ptr<class v8::TracingController,struct std::default_delete<class v8::TracingController> >)" (?NewDefaultPlatform@platform@v8@@YA?AV?$unique_ptr@VPlatform@v8@@U?$default_delete@VPlatform@v8@@@std@@@std@@HW4IdleTaskSupport@12@W4InProcessStackDumping@12@V?$unique_ptr@VTracingController@v8@@U?$default_delete@VTracingController@v8@@@std@@@4@@Z)

Body:
This bellow command is works and can be linked VS2019 C++ projects.

This given solution bring from groups.google.com

call gn gen out.gn/x64.release --args="is_debug=false use_glib=false is_component_build=true v8_use_external_startup_data=true v8_static_library=false is_clang = false v8_enable_i18n_support=false target_cpu=\"x64\""


来源: stackexchange

问:
How to print key and values from the following collection?
I have the following collection that holds a dictionary:

```<code> {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}
</code>```

I'd like to print the collection in the following output data format:

```<code> NAME    #TOTAL     #TK     #LA
 EHAM    78         55      23
 EGLL    67         46      21
 LOWW    67         44      23
 LFPG    75         43      32
</code>```

Right now I'm getting the following ouput:

```<code>#NAME #TOTAL #TK #LA
 EHAM [78, [55, 23]]
 EGLL [67, [46, 21]]
 LOWW [67, [44, 23]]
 LFPG [75, [43, 32]]
</code>```

This is the piece of code I'm using:

```<code>#print(topAirpots_dict)
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k,top_dict[k])
</code>```

答:
This may be helpful:

```<code>my_dict = {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}

print("NAME", "#TOTAL", "#TK", "#LA", sep="\t\t")
for k, item in my_dict.items():
    total, other = item
    tk, tl = other
    print(f"{k} {total:>10} {tk:>10} {tl:>7}")
</code>```

Output:

```<code>NAME        #TOTAL      #TK     #LA
EHAM         78         55      23
EGLL         67         46      21
LOWW         67         44      23
LFPG         75         43      32
</code>```

used

string formatting-> [https://www.geeksforgeeks.org/python-format-function/] &

string interpolation-> [https://realpython.com/python-string-formatting/]

ContentLicense: CC BY-SA 4.0

Body:
I have the following collection that holds a dictionary:

 {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}

I'd like to print the collection in the following output data format:

 NAME    #TOTAL     #TK     #LA
 EHAM    78         55      23
 EGLL    67         46      21
 LOWW    67         44      23
 LFPG    75         43      32

Right now I'm getting the following ouput:

#NAME #TOTAL #TK #LA
 EHAM [78, [55, 23]]
 EGLL [67, [46, 21]]
 LOWW [67, [44, 23]]
 LFPG [75, [43, 32]]

This is the piece of code I'm using:

#print(topAirpots_dict)
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k,top_dict[k])

Body:
This may be helpful:

my_dict = {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}

print("NAME", "#TOTAL", "#TK", "#LA", sep="\t\t")
for k, item in my_dict.items():
    total, other = item
    tk, tl = other
    print(f"{k} {total:>10} {tk:>10} {tl:>7}")

Output:

NAME        #TOTAL      #TK     #LA
EHAM         78         55      23
EGLL         67         46      21
LOWW         67         44      23
LFPG         75         43      32

used

string formatting-> [https://www.geeksforgeeks.org/python-format-function/] &

string interpolation-> [https://realpython.com/python-string-formatting/]


问:
How do I pass a 44 Bytes x25519 public key created by openssl to CryptoKit which requires a key length of 32 Bytes
Suppose I create a x25519 key pair using openssl, it will output a 64 Bytes private key and the corresponding 44 Bytes Base64 encoded public key which would look like

```<code>-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VuBCIEIMBF8S7zUco4bRrMiIuyTcSYU/rAVlNtE8SMYWphUatw
-----END PRIVATE KEY-----

-----BEGIN PUBLIC KEY-----
MCowBQYDK2VuAyEAE0eiiP0PKjy9AVM/0z2ZIZn453WSJNemrQ58HAXDaX0=
-----END PUBLIC KEY-----
</code>```

Swift CryptoKit is only accepting 32 Bytes for each, private and public key initialisation.

If I understood correctly, the 64 Bytes private key is the seed, where the first 32 Bytes are the actual private key.

Still, using the same principle for the the public key is not working (not very surprising tbh)

The question is now: How do I translate the public key to the 32 Bytes required by Swift CryptoKit?

Here is the non functioning example of using the first 32 Bytes of the base64 decoded public key

```<code>let base64PublicKey = Data(base64Encoded: "MCowBQYDK2VuAyEAE0eiiP0PKjy9AVM/0z2ZIZn453WSJNemrQ58HAXDaX0=")!.dropLast(12)

let publicKey = try! Curve25519.KeyAgreement.PublicKey(rawRepresentation: rawPublicKey)
</code>```

答:
```<code>-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VuBCIEIMBF8S7zUco4bRrMiIuyTcSYU/rAVlNtE8SMYWphUatw
-----END PRIVATE KEY-----
</code>```

per rfc7468 is a PKCS8-unencrypted PrivateKeyInfo which is encoded in ASN.1 DER and contains data about the algorithm (and in general but not here parameters) as well as the actual key. Running this into openssl asn1parse -i (which automatically de-base64's) gives

```<code>    0:d=0  hl=2 l=  46 cons: SEQUENCE
    2:d=1  hl=2 l=   1 prim:  INTEGER           :00
    5:d=1  hl=2 l=   5 cons:  SEQUENCE
    7:d=2  hl=2 l=   3 prim:   OBJECT            :X25519
   12:d=1  hl=2 l=  34 prim:  OCTET STRING      [HEX DUMP]:0420C045F12EF351CA386D1ACC888BB24DC49853FAC056536D13C48C616A6151AB70
</code>```

The algorithm-specific privatekey is the OCTETSTRING with value at offset 12+2 and length 34, but that actually contains a nested OCTETSTRING encoding whose first two octets are 04=tag and 20=length, so the true privatekey is at offset 16 with length 32 -- or more simply the last 32 bytes.

```<code>-----BEGIN PUBLIC KEY-----
MCowBQYDK2VuAyEAE0eiiP0PKjy9AVM/0z2ZIZn453WSJNemrQ58HAXDaX0=
-----END PUBLIC KEY-----
</code>```

similarly is the SubjectPublicKeyInfo structure defined by X.509 and PKIX which similarly is DER and contains data in addition to the key. Parsing it (with -dump) gives:

```<code>    0:d=0  hl=2 l=  42 cons: SEQUENCE
    2:d=1  hl=2 l=   5 cons:  SEQUENCE
    4:d=2  hl=2 l=   3 prim:   OBJECT            :X25519
    9:d=1  hl=2 l=  33 prim:  BIT STRING
      0000 - 00 13 47 a2 88 fd 0f 2a-3c bd 01 53 3f d3 3d 99   ..G....*<..S?.=.
      0010 - 21 99 f8 e7 75 92 24 d7-a6 ad 0e 7c 1c 05 c3 69   !...u.$....|...i
      0020 - 7d
</code>```

The first octet of a BITSTRING value is used for the number of unused/pad bits, here 00, so the real publickey value is the 33-1=32 octets at offset 9+2+1=12, or again the last 32 bytes.

Ed25519 hashes the privatekey to produce both a 32-byte scalar sometimes called the seed plus a 32-byte value which determines the publickey. This seed can be stored with the privatekey to make signing more efficient, but OpenSSL does not do this for Ed25519, and it doesn't apply at all to X25519.

Body:
Suppose I create a x25519 key pair using openssl, it will output a 64 Bytes private key and the corresponding 44 Bytes Base64 encoded public key which would look like

-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VuBCIEIMBF8S7zUco4bRrMiIuyTcSYU/rAVlNtE8SMYWphUatw
-----END PRIVATE KEY-----

-----BEGIN PUBLIC KEY-----
MCowBQYDK2VuAyEAE0eiiP0PKjy9AVM/0z2ZIZn453WSJNemrQ58HAXDaX0=
-----END PUBLIC KEY-----

Swift CryptoKit is only accepting 32 Bytes for each, private and public key initialisation.

If I understood correctly, the 64 Bytes private key is the seed, where the first 32 Bytes are the actual private key.

Still, using the same principle for the the public key is not working (not very surprising tbh)

The question is now: How do I translate the public key to the 32 Bytes required by Swift CryptoKit?

Here is the non functioning example of using the first 32 Bytes of the base64 decoded public key

let base64PublicKey = Data(base64Encoded: "MCowBQYDK2VuAyEAE0eiiP0PKjy9AVM/0z2ZIZn453WSJNemrQ58HAXDaX0=")!.dropLast(12)

let publicKey = try! Curve25519.KeyAgreement.PublicKey(rawRepresentation: rawPublicKey)

Body:
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VuBCIEIMBF8S7zUco4bRrMiIuyTcSYU/rAVlNtE8SMYWphUatw
-----END PRIVATE KEY-----

per rfc7468 is a PKCS8-unencrypted PrivateKeyInfo which is encoded in ASN.1 DER and contains data about the algorithm (and in general but not here parameters) as well as the actual key. Running this into openssl asn1parse -i (which automatically de-base64's) gives

    0:d=0  hl=2 l=  46 cons: SEQUENCE
    2:d=1  hl=2 l=   1 prim:  INTEGER           :00
    5:d=1  hl=2 l=   5 cons:  SEQUENCE
    7:d=2  hl=2 l=   3 prim:   OBJECT            :X25519
   12:d=1  hl=2 l=  34 prim:  OCTET STRING      [HEX DUMP]:0420C045F12EF351CA386D1ACC888BB24DC49853FAC056536D13C48C616A6151AB70

The algorithm-specific privatekey is the OCTETSTRING with value at offset 12+2 and length 34, but that actually contains a nested OCTETSTRING encoding whose first two octets are 04=tag and 20=length, so the true privatekey is at offset 16 with length 32 -- or more simply the last 32 bytes.

-----BEGIN PUBLIC KEY-----
MCowBQYDK2VuAyEAE0eiiP0PKjy9AVM/0z2ZIZn453WSJNemrQ58HAXDaX0=
-----END PUBLIC KEY-----

similarly is the SubjectPublicKeyInfo structure defined by X.509 and PKIX which similarly is DER and contains data in addition to the key. Parsing it (with -dump) gives:

    0:d=0  hl=2 l=  42 cons: SEQUENCE
    2:d=1  hl=2 l=   5 cons:  SEQUENCE
    4:d=2  hl=2 l=   3 prim:   OBJECT            :X25519
    9:d=1  hl=2 l=  33 prim:  BIT STRING
      0000 - 00 13 47 a2 88 fd 0f 2a-3c bd 01 53 3f d3 3d 99   ..G....*<..S?.=.
      0010 - 21 99 f8 e7 75 92 24 d7-a6 ad 0e 7c 1c 05 c3 69   !...u.$....|...i
      0020 - 7d

The first octet of a BITSTRING value is used for the number of unused/pad bits, here 00, so the real publickey value is the 33-1=32 octets at offset 9+2+1=12, or again the last 32 bytes.

Ed25519 hashes the privatekey to produce both a 32-byte scalar sometimes called the seed plus a 32-byte value which determines the publickey. This seed can be stored with the privatekey to make signing more efficient, but OpenSSL does not do this for Ed25519, and it doesn't apply at all to X25519.


问:
How to add and delete item from array in Angular
I am doing a project that need to display an array and user can add in new data or delete existing data from the array.

I am stuck with how to add and delete item from array.

I tried to use push function to add and pop function to delete but failed.

HTML

Student Details

 Name: <input type="text" [(ngModel)]="name" placeholder="Please enter Name" value={{selectedStudent.name}}>

 Age:<input type="text" [(ngModel)]="age" placeholder="Please enter Age" class="age"
                value={{selectedStudent.age}}>

College:<input type="text" [(ngModel)]="college" placeholder="Please enter College"
                value={{selectedStudent.college}}>

        <button class="btnA" onclick="addStudent()">Add</button>
        <button class="btnE" onclick="editStudent()">Edit</button>
        <button class="btnD" onclick="deleteStudent()">Delete</button>

        {{student.name}} {{student.age}} {{student.college}}

```
</div>
</div>
</p>

<p><strong>.ts</strong></p>

```export class WriteComponent implements OnInit {

    name: string;
    age: number;
    college: string;
    student = STUDENTS;
    selectedStudent: Student;

    constructor() {}
    ngOnInit(): void {}

    onSelect(student: Student): void {
        this.selectedStudent = student;
    }

}
```

<p><strong>mock-student.ts</strong> (where I store my array)</p>

```import { Student } from './student';

export const STUDENTS : Student[]=[
  {name:'Johnny',age:24,college:'Harvard'},
  {name:'Samantha',age:20,college:'INTI'},
  {name:'Aditya',age:21,college:'Sunway'},
  {name:'Troy',age:25,college:'TARUC'},
]
```

答:
Deleting an item from the array

You are setting your selectedStudent to one of the instances in your array, so it is simple enough to find its index when you want to remove it from the array.

You can use the splice array function to remove the item at the index.

```<code>// declare students here for the purpose of the answer
students: Student[] = [
  {name:'Johnny', age:24, college:'Harvard'}
  // ... more students here
];
selectedStudent : Student;

onSelect(student:Student): void {
  this.selectedStudent = student;
}

deleteStudent(): void {
  if (!this.selectedStudent) {
    return;
  }

  // find the index of the selected student
  // this works because your selected student is one of the array items
  // it wouldn't work if selected student was a copy
  const index = this.students.indexOf(this.selectedStudent);

  // use splice to remove 1 item starting at the given index
  this.students.splice(index, 1);

  // todo: logic to reset this.selectedStudent
}
</code>```

Adding an item to the array

Adding is simple. Use the push array function to append an item to an array.

```<code>students: Student[] = [];

name: string;
age: number;
college: string;

addStudent() {
  const student = {
    name: this.name,
    age: this.age,
    college: this.college
  };

  this.students.push(student);
}
</code>```

Body:
I am doing a project that need to display an array and user can add in new data or delete existing data from the array.

I am stuck with how to add and delete item from array.

I tried to use push function to add and pop function to delete but failed.

HTML

Student Details

 Name: <input type="text" [(ngModel)]="name" placeholder="Please enter Name" value={{selectedStudent.name}}>

 Age:<input type="text" [(ngModel)]="age" placeholder="Please enter Age" class="age"
                value={{selectedStudent.age}}>

College:<input type="text" [(ngModel)]="college" placeholder="Please enter College"
                value={{selectedStudent.college}}>

        <button class="btnA" onclick="addStudent()">Add</button>
        <button class="btnE" onclick="editStudent()">Edit</button>
        <button class="btnD" onclick="deleteStudent()">Delete</button>

        {{student.name}} {{student.age}} {{student.college}}

.ts

export class WriteComponent implements OnInit {

    name: string;
    age: number;
    college: string;
    student = STUDENTS;
    selectedStudent: Student;

    constructor() {}
    ngOnInit(): void {}

    onSelect(student: Student): void {
        this.selectedStudent = student;
    }

}

mock-student.ts (where I store my array)

import { Student } from './student';

export const STUDENTS : Student[]=[
  {name:'Johnny',age:24,college:'Harvard'},
  {name:'Samantha',age:20,college:'INTI'},
  {name:'Aditya',age:21,college:'Sunway'},
  {name:'Troy',age:25,college:'TARUC'},
]

Body:
Deleting an item from the array

You are setting your selectedStudent to one of the instances in your array, so it is simple enough to find its index when you want to remove it from the array.

You can use the splice array function to remove the item at the index.

// declare students here for the purpose of the answer
students: Student[] = [
  {name:'Johnny', age:24, college:'Harvard'}
  // ... more students here
];
selectedStudent : Student;

onSelect(student:Student): void {
  this.selectedStudent = student;
}

deleteStudent(): void {
  if (!this.selectedStudent) {
    return;
  }

  // find the index of the selected student
  // this works because your selected student is one of the array items
  // it wouldn't work if selected student was a copy
  const index = this.students.indexOf(this.selectedStudent);

  // use splice to remove 1 item starting at the given index
  this.students.splice(index, 1);

  // todo: logic to reset this.selectedStudent
}

Adding an item to the array

Adding is simple. Use the push array function to append an item to an array.

students: Student[] = [];

name: string;
age: number;
college: string;

addStudent() {
  const student = {
    name: this.name,
    age: this.age,
    college: this.college
  };

  this.students.push(student);
}


问:
Typescript for Facebook React
I've been looking into React lately and was hoping to use JSX and typescript. I haven't been able to find any resources on this or type definitions for React.

Can you use Typescript with JSX and are type definitions available?

答:
Now things seems have changed, from official Typescript docs

TypeScript supports embedding, type checking, and compiling JSX directly to JavaScript.

And this on how start a project directly with Typescript

ContentLicense: CC BY-SA 3.0

Title: Typescript for Facebook React


问:
How to replace list element in arangodb
I have a list in arango collection like below

```<code>{
"id":"123"
"studentlist": [
    "a",
    "b",
    "c"
  ]
}
</code>```

Now based on some filter condition i have to replace particular element of list with the replacement set. In this example i want to replace b with [b1,b2], so that my collection should look like below

```<code> {
        "id":"123"
        "studentlist": [
            "a",
            "b1",
            "b2",
            "c"
          ]
        }
</code>```

how to do it using arango query.

答:
You have a lot of functions at your disposal to manipulate the data, e.g. using the array-modifying REMOVE_VALUE, APPEND and SORTED I massage the studentlist of the original data, and use the object-modifying MERGE to return the desired result.

```<code>LET data = {
"id":"123",
"studentlist": [
    "a",
    "b",
    "c"
  ]
}
LET list = SORTED(APPEND(REMOVE_VALUE(data.studentlist, "b"), ["b1", "b2"]))
RETURN MERGE(data, {studentlist: list})
</code>```

Returns your desired

```<code>[
  {
    "id": "123",
    "studentlist": [
      "a",
      "b1",
      "b2",
      "c"
    ]
  }
]
</code>```

as single element of the result list.  This should get you started.  You can use LET expressions in FOR queries, you can use sub-queries to assemble data, and so on... And then use @Ömer_Taban's answer to update the documents, e.g.

```<code>FOR d IN data
   FILTER <YOUR_CONDITIONS>
   LET list...
   ...
   UPDATE d WITH list IN data
</code>```

Title: How to replace list element in arangodb

Body:
I have a list in arango collection like below

{
"id":"123"
"studentlist": [
    "a",
    "b",
    "c"
  ]
}

Now based on some filter condition i have to replace particular element of list with the replacement set. In this example i want to replace b with [b1,b2], so that my collection should look like below

 {
        "id":"123"
        "studentlist": [
            "a",
            "b1",
            "b2",
            "c"
          ]
        }

how to do it using arango query.

Body:
You have a lot of functions at your disposal to manipulate the data, e.g. using the array-modifying REMOVE_VALUE, APPEND and SORTED I massage the studentlist of the original data, and use the object-modifying MERGE to return the desired result.

LET data = {
"id":"123",
"studentlist": [
    "a",
    "b",
    "c"
  ]
}
LET list = SORTED(APPEND(REMOVE_VALUE(data.studentlist, "b"), ["b1", "b2"]))
RETURN MERGE(data, {studentlist: list})

Returns your desired

[
  {
    "id": "123",
    "studentlist": [
      "a",
      "b1",
      "b2",
      "c"
    ]
  }
]

as single element of the result list.  This should get you started.  You can use LET expressions in FOR queries, you can use sub-queries to assemble data, and so on... And then use @Ömer_Taban's answer to update the documents, e.g.

FOR d IN data
   FILTER <YOUR_CONDITIONS>
   LET list...
   ...
   UPDATE d WITH list IN data


问:
Scala spark aggregate a set of columns in a data frame to a JSON string
Given a data frame,

```<code>+-----------------------------+
| id|  name| payable| strategy|
+-----------------------------+
|  0|   Joe|     100|     st-1|
|  1|   Tom|     200|     st-2|
|  2|  John|     300|     st-1|
+-----------------------------+
</code>```

What would be the most efficient way to convert each row to a JSON string such as follows,

```<code>{
  "payload": {
     "name": "Joe",
     "payments": [
         {
            "strategy": "st-1",
            "payable": 100
         }
     ]
  }
}
</code>```

Currently I have UDF to manually stringify the provided columns, but I'm wondering whether there is a better way to achieve this. The to_json method is the best alternative I found so far but that takes only one column as an input.

Body:
Given a data frame,

+-----------------------------+
| id|  name| payable| strategy|
+-----------------------------+
|  0|   Joe|     100|     st-1|
|  1|   Tom|     200|     st-2|
|  2|  John|     300|     st-1|
+-----------------------------+

What would be the most efficient way to convert each row to a JSON string such as follows,

{
  "payload": {
     "name": "Joe",
     "payments": [
         {
            "strategy": "st-1",
            "payable": 100
         }
     ]
  }
}

Currently I have UDF to manually stringify the provided columns, but I'm wondering whether there is a better way to achieve this. The to_json method is the best alternative I found so far but that takes only one column as an input.

Body:
Using to_json() is the correct approach, but the contents need to be passed as struct as appropriate:

val df = Seq((0,"Joe",100,"st-1"), (1,"Tom",200,"st-2")).toDF("id","name","payable","strategy")

val result = df.select(
  to_json(struct(
    struct($"name",
      array(struct($"strategy",$"payable")) as "payments"
    ) as "payload")
  ) as "jsonValue"
 )

result.show(false)
+-------------------------------------------------------------------------+
|jsonValue                                                                |
+-------------------------------------------------------------------------+
|{"payload":{"name":"Joe","payments":[{"strategy":"st-1","payable":100}]}}|
|{"payload":{"name":"Tom","payments":[{"strategy":"st-2","payable":200}]}}|
+-------------------------------------------------------------------------+


问:
React material ui table won't stretch to fill
I'm experimenting with my own virtualization by using an example (rather than react-virtualized) and I'm having issues with styling

Can anyone tell me why the material table in the code sandbox below won't stretch to fit it's paper component? I'm sure there's a CSS property I need to set somewhere but I'm not sure what it is

https://codesandbox.io/s/material-ui-table-virtualization-c8tys

Any help would be appreciated

Thanks!

Adam

答:
This is not really related to React, but more to how you structure and style the table using html and css.

Why not just use the width: 100%; css rule on your table element? This would give your the result you want:

table {
  float: left;
  width: 100%;
  border-collapse: collapse;
  border: 1px solid lightgray;
}

table tr {
  height: 37px;
}

table thead {
  background-color: lightgray;
  font-weight: bold;
}

table tbody tr:nth-child(even) {
  background-color: #ededed;
}

table ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>01</td>
      <td>John</td>
      <td>Doe</td>
      <td>31</td>
    </tr>
    <tr>
      <td>02</td>
      <td>Marie</td>
      <td>Curie</td>
      <td>66</td>
    </tr>
    <tr>
      <td>01</td>
      <td>Larry</td>
      <td>Tesler</td>
      <td>75</td>
    </tr>
    <tr>
      <td>01</td>
      <td>Sheldon</td>
      <td>Cooper</td>
      <td>35</td>
    </tr>
  </tbody>
</table></code>```

Body:
This is not really related to React, but more to how you structure and style the table using html and css.

Why not just use the width: 100%; css rule on your table element? This would give your the result you want:

table {
  float: left;
  width: 100%;
  border-collapse: collapse;
  border: 1px solid lightgray;
}

table tr {
  height: 37px;
}

table thead {
  background-color: lightgray;
  font-weight: bold;
}

table tbody tr:nth-child(even) {
  background-color: #ededed;
}

table

<table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>01</td>
      <td>John</td>
      <td>Doe</td>
      <td>31</td>
    </tr>
    <tr>
      <td>02</td>
      <td>Marie</td>
      <td>Curie</td>
      <td>66</td>
    </tr>
    <tr>
      <td>01</td>
      <td>Larry</td>
      <td>Tesler</td>
      <td>75</td>
    </tr>
    <tr>
      <td>01</td>
      <td>Sheldon</td>
      <td>Cooper</td>
      <td>35</td>
    </tr>
  </tbody>
</table>


问:
Chart.js hours scale show day switch
I have an array of date for 2 days and I would like to show only hours. No problem for that.

But since we have 2 days, there is no way to see the day switch in the graph. Is there a way to have hours and then a tick with the day when we are switching ?

Something like that :

Thanks !

var labels = ['2018-12-20 14:00', '2018-12-20 15:00', '2018-12-20 16:00', '2018-12-20 17:00', '2018-12-20 18:00', '2018-12-20 19:00', '2018-12-20 23:00', '2018-12-21 02:00', '2018-12-21 03:00', '2018-12-21 04:00', '2018-12-21 05:00', '2018-12-21 10:00'];
var data = [256,24,14,12,154,123,23,254,145,123,11,255];

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Tickets selling',
         data: data,
         borderWidth: 1
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
                autoSkip: true,
                maxTicksLimit: 20,
                maxRotation: 0,
            },
            type: 'time',
            time: {
               unit: 'hour',
               displayFormats: {
                  hour: 'HH:mm'
               }
            }
         }]
      },
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="myChart"></canvas></code>```

答:
This can be done using the major ticks option in chartjs.

scales: {
  xAxes: [{
    type: 'time',
    time: {
        unit: 'hour',
        stepSize: 3, // I'm using 3 hour intervals here
        tooltipFormat: 'HH:mm',
    },
    ticks: {
        major: {
           enabled: true, // <-- This is the key line
           fontStyle: 'bold', //You can also style these values differently
           fontSize: 14 //You can also style these values differently
        },
    },
  }]
}
```

This produces an x axis like the follwong

Title: Chart.js hours scale show day switch

Body:
I have an array of date for 2 days and I would like to show only hours. No problem for that.

But since we have 2 days, there is no way to see the day switch in the graph. Is there a way to have hours and then a tick with the day when we are switching ?

Something like that :

Thanks !

var labels = ['2018-12-20 14:00', '2018-12-20 15:00', '2018-12-20 16:00', '2018-12-20 17:00', '2018-12-20 18:00', '2018-12-20 19:00', '2018-12-20 23:00', '2018-12-21 02:00', '2018-12-21 03:00', '2018-12-21 04:00', '2018-12-21 05:00', '2018-12-21 10:00'];
var data = [256,24,14,12,154,123,23,254,145,123,11,255];

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Tickets selling',
         data: data,
         borderWidth: 1
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
                autoSkip: true,
                maxTicksLimit: 20,
                maxRotation: 0,
            },
            type: 'time',
            time: {
               unit: 'hour',
               displayFormats: {
                  hour: 'HH:mm'
               }
            }
         }]
      },
   }
});

<canvas id="myChart"></canvas>

Body:
This can be done using the major ticks option in chartjs.

scales: {
  xAxes: [{
    type: 'time',
    time: {
        unit: 'hour',
        stepSize: 3, // I'm using 3 hour intervals here
        tooltipFormat: 'HH:mm',
    },
    ticks: {
        major: {
           enabled: true, // <-- This is the key line
           fontStyle: 'bold', //You can also style these values differently
           fontSize: 14 //You can also style these values differently
        },
    },
  }]
}

This produces an x axis like the follwong


问:
No setter/getter Firebase
Hi everyone I have one question. I want to retrieve the data from the Firebase live database and it keeps telling me that it doesn't find the getter and the setter but as you can see below I did it, I create a class where I have the setter and the getter with the same name of the database fields.

Can anyone tell me what I'm doing wrong because I don't have a clue?

Thank you in advance.

Photo of the database:

Code of the Activity and the Class where you can see that I have the getter and the setter.

```<code>package com.example.ipill;

public class CartActivity extends AppCompatActivity {

    private TextView total;
    private ImageButton removeFromCart;
    private Button pay;

    private RecyclerView mResultList;
    private DatabaseReference mUserDatabase;
    public static int cart_count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");

        total        = findViewById(R.id.TotalPrice);
        removeFromCart   = findViewById(R.id.removeFromCart);
        mResultList  = findViewById(R.id.cartList);
        pay    = findViewById(R.id.pay);

        mResultList.setHasFixedSize(true);
        mResultList.setLayoutManager(new LinearLayoutManager(this));

         // Attach a listener to read the data at our posts reference
          mUserDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Users_get post = dataSnapshot.getValue(Users_get.class);
                System.out.println("DATAAAA: "+post);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        invalidateOptionsMenu();
    }

    // View Holder Class
    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;
        String nome;
        String surname;
        Long prezzo;
        public UsersViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void getDetails(String name,String cognome,Long price){
            nome=name;
            surname=cognome;
            prezzo=price;
        }

        public void setDetails(String name, String surname, Long price) {

            TextView user_name = (TextView) mView.findViewById(R.id.name_text);
            TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
            TextView user_price = (TextView)mView.findViewById(R.id.price);

            user_name.setText(name);
            user_surname.setText(surname);
            user_price.setText(Long.toString(price));

        }
     }
}
</code>```

CLASS

```<code>public class Users_get  {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    private String name, surname;
    private Long price;
}
</code>```

JSON structure

```<code>{
  "Cart": {
    "-M0U3UXq2ZA00Jq5o9as": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WlUbQHj1hdH40uWVF": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WxZhI98Xb1s9Xy5HV": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0X00Zr64RocyQHhoFB": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    }
  },
  "Users": {
    "01": {
      "Name": "Alex",
      "Price": 120,
      "Surname": "Kyto"
    },
    "02": {
      "Name": "Alex",
      "Price": 200,
      "Surname": "Pablo"
    }
  }
}
</code>```

答:
In addition to other answer, To get Users_get data, according your database structure you have to go one level more.

Currently your database reference pointed to Cart. So iterate through children of cart to get cart data. Check below:

```<code>mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");
mUserDatabase.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            Users_get post = childSnapshot.getValue(Users_get.class);
            System.out.println("DATAAAA: " + post);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
});
</code>```

Title: No setter/getter Firebase

Body:
Hi everyone I have one question. I want to retrieve the data from the Firebase live database and it keeps telling me that it doesn't find the getter and the setter but as you can see below I did it, I create a class where I have the setter and the getter with the same name of the database fields.

Can anyone tell me what I'm doing wrong because I don't have a clue?

Thank you in advance.

Photo of the database:

Code of the Activity and the Class where you can see that I have the getter and the setter.

package com.example.ipill;

public class CartActivity extends AppCompatActivity {

    private TextView total;
    private ImageButton removeFromCart;
    private Button pay;

    private RecyclerView mResultList;
    private DatabaseReference mUserDatabase;
    public static int cart_count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");

        total        = findViewById(R.id.TotalPrice);
        removeFromCart   = findViewById(R.id.removeFromCart);
        mResultList  = findViewById(R.id.cartList);
        pay    = findViewById(R.id.pay);

        mResultList.setHasFixedSize(true);
        mResultList.setLayoutManager(new LinearLayoutManager(this));

         // Attach a listener to read the data at our posts reference
          mUserDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Users_get post = dataSnapshot.getValue(Users_get.class);
                System.out.println("DATAAAA: "+post);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        invalidateOptionsMenu();
    }

    // View Holder Class
    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;
        String nome;
        String surname;
        Long prezzo;
        public UsersViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void getDetails(String name,String cognome,Long price){
            nome=name;
            surname=cognome;
            prezzo=price;
        }

        public void setDetails(String name, String surname, Long price) {

            TextView user_name = (TextView) mView.findViewById(R.id.name_text);
            TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
            TextView user_price = (TextView)mView.findViewById(R.id.price);

            user_name.setText(name);
            user_surname.setText(surname);
            user_price.setText(Long.toString(price));

        }
     }
}

CLASS

public class Users_get  {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    private String name, surname;
    private Long price;
}

JSON structure

{
  "Cart": {
    "-M0U3UXq2ZA00Jq5o9as": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WlUbQHj1hdH40uWVF": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WxZhI98Xb1s9Xy5HV": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0X00Zr64RocyQHhoFB": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    }
  },
  "Users": {
    "01": {
      "Name": "Alex",
      "Price": 120,
      "Surname": "Kyto"
    },
    "02": {
      "Name": "Alex",
      "Price": 200,
      "Surname": "Pablo"
    }
  }
}

Body:
In addition to other answer, To get Users_get data, according your database structure you have to go one level more.

Currently your database reference pointed to Cart. So iterate through children of cart to get cart data. Check below:

mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");
mUserDatabase.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            Users_get post = childSnapshot.getValue(Users_get.class);
            System.out.println("DATAAAA: " + post);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
});


问:
Android AudioHardware pcm playback is going to standby
Occasionally when I have a lot going on in my app, and I am playing a number of sounds using SoundPool, my app just completely freezes.  Looking at the logs, I see this:
I/AudioHardwareMSM72XX(   56): AudioHardware pcm playback is going to standby.

My app must then be force closed and restarted.  Does anyone know what may be causing this, or a possible workaround?  I cannot reproduce this in the emulator - only on my HTC Hero, so I am wondering if this may be a device specific bug.

答:
There are two possible causes of this.

Cause 1: If you don't keep hold of a reference to your MediaPlayer object it can get garbage collected even though it is playing something. I have some code in a repeating timer that plays a sound, I had to assign the MediaPlayer to a static variable to stop it being garbage collected, and the problem of the sound stopping part way through went away.

Cause 2: I've read that if you are streaming it is possible to give the MediaPlayer too much data and it dies - see this discussion thread: /593575">http://www.last.fm/group/Last.fm+Android/forum/114391//593575

ContentLicense: CC BY-SA 2.5


问:
write regex in JsonFormat pattern
```<code>@JsonFormat(shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd'T'HH:mm:ss.SSS")
</code>```

is it possible to write regex in pattern? I could not

pattern ="yyyy-MM-dd'T'HH:mm:ss.SSS(Z?)"

I want to make Z as optional

any links suggestions?

答:
I ended up creating custom deserializer based on LocalDateDeserializer.INSTANCE and moved the regex there.

After registering the deserializer the object mapper as a custom module the @JsonFormat annotation is no longer required:

```<code>    @Bean
    public ObjectMapper createObjectMapper() {
        return new ObjectMapper()
              .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
              .registerModule(new JavaTimeModule())
              .registerModule(new CustomTimeModule());
    }
</code>```

and defined the deserializer in the CustomTimeModule

```<code>    class CustomTimeModule extends SimpleModule {
        public CustomTimeModule() {
            super();
            addDeserializer(LocalDate.class, CustomLocalDateDeserializer.INSTANCE);
        }
    }
</code>```

and finally the regex part, in my case was cutting of the optional non-standard time zone that i was sometimes getting after the date, but could be easily extended to match your case:

```<code>        public class CustomLocalDateDeserializer extends JSR310DateTimeDeserializerBase<LocalDate> {
            private static final long serialVersionUID = 1L;

            private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;

            public static final CustomLocalDateDeserializer INSTANCE = new CustomLocalDateDeserializer();

            private CustomLocalDateDeserializer() {
                this(DEFAULT_FORMATTER);
            }

            public CustomLocalDateDeserializer(DateTimeFormatter dtf) {
                super(LocalDate.class, dtf);
            }

            @Override
            protected JsonDeserializer<LocalDate> withDateFormat(DateTimeFormatter dtf) {
                return new CustomLocalDateDeserializer(dtf);
            }

            @Override
            public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException
            {
                if (parser.hasToken(JsonToken.VALUE_STRING)) {
                    String string = parser.getText().trim();
                    if (string.length() == 0) {
                        return null;
                    }

                    // >>>>>>> regex part comes here <<<<<<<
                    string = parser.getText().trim().substring(0, 10);
                    // >>>>>>> regex part comes here <<<<<<<

                    // as per [datatype-jsr310#37], only check for optional (and, incorrect...) time marker 'T'
                    // if we are using default formatter
                    try {
                        return LocalDate.parse(string, _formatter);
                    } catch (DateTimeException e) {
                        return _handleDateTimeException(context, e, string);
                    }
                }
                if (parser.isExpectedStartArrayToken()) {
                    JsonToken t = parser.nextToken();
                    if (t == JsonToken.END_ARRAY) {
                        return null;
                    }
                    if (context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
                            && (t == JsonToken.VALUE_STRING || t==JsonToken.VALUE_EMBEDDED_OBJECT)) {
                        final LocalDate parsed = deserialize(parser, context);
                        if (parser.nextToken() != JsonToken.END_ARRAY) {
                            handleMissingEndArrayForSingle(parser, context);
                        }
                        return parsed;
                    }
                    if (t == JsonToken.VALUE_NUMBER_INT) {
                        int year = parser.getIntValue();
                        int month = parser.nextIntValue(-1);
                        int day = parser.nextIntValue(-1);

                        if (parser.nextToken() != JsonToken.END_ARRAY) {
                            throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                                    "Expected array to end");
                        }
                        return LocalDate.of(year, month, day);
                    }
                    context.reportInputMismatch(handledType(),
                            "Unexpected token (%s) within Array, expected VALUE_NUMBER_INT",
                            t);
                }
                if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
                    return (LocalDate) parser.getEmbeddedObject();
                }
                // 06-Jan-2018, tatu: Is this actually safe? Do users expect such coercion?
                if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
                    return LocalDate.ofEpochDay(parser.getLongValue());
                }
                return _handleUnexpectedToken(context, parser, "Expected array or string.");
            }

</code>```

Title: write regex in JsonFormat pattern

Body:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd'T'HH:mm:ss.SSS")

is it possible to write regex in pattern? I could not

pattern ="yyyy-MM-dd'T'HH:mm:ss.SSS(Z?)"

I want to make Z as optional

any links suggestions?

Body:
I ended up creating custom deserializer based on LocalDateDeserializer.INSTANCE and moved the regex there.

After registering the deserializer the object mapper as a custom module the @JsonFormat annotation is no longer required:

    @Bean
    public ObjectMapper createObjectMapper() {
        return new ObjectMapper()
              .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
              .registerModule(new JavaTimeModule())
              .registerModule(new CustomTimeModule());
    }

and defined the deserializer in the CustomTimeModule

    class CustomTimeModule extends SimpleModule {
        public CustomTimeModule() {
            super();
            addDeserializer(LocalDate.class, CustomLocalDateDeserializer.INSTANCE);
        }
    }

and finally the regex part, in my case was cutting of the optional non-standard time zone that i was sometimes getting after the date, but could be easily extended to match your case:

        public class CustomLocalDateDeserializer extends JSR310DateTimeDeserializerBase<LocalDate> {
            private static final long serialVersionUID = 1L;

            private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;

            public static final CustomLocalDateDeserializer INSTANCE = new CustomLocalDateDeserializer();

            private CustomLocalDateDeserializer() {
                this(DEFAULT_FORMATTER);
            }

            public CustomLocalDateDeserializer(DateTimeFormatter dtf) {
                super(LocalDate.class, dtf);
            }

            @Override
            protected JsonDeserializer<LocalDate> withDateFormat(DateTimeFormatter dtf) {
                return new CustomLocalDateDeserializer(dtf);
            }

            @Override
            public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException
            {
                if (parser.hasToken(JsonToken.VALUE_STRING)) {
                    String string = parser.getText().trim();
                    if (string.length() == 0) {
                        return null;
                    }

                    // >>>>>>> regex part comes here <<<<<<<
                    string = parser.getText().trim().substring(0, 10);
                    // >>>>>>> regex part comes here <<<<<<<

                    // as per [datatype-jsr310#37], only check for optional (and, incorrect...) time marker 'T'
                    // if we are using default formatter
                    try {
                        return LocalDate.parse(string, _formatter);
                    } catch (DateTimeException e) {
                        return _handleDateTimeException(context, e, string);
                    }
                }
                if (parser.isExpectedStartArrayToken()) {
                    JsonToken t = parser.nextToken();
                    if (t == JsonToken.END_ARRAY) {
                        return null;
                    }
                    if (context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
                            && (t == JsonToken.VALUE_STRING || t==JsonToken.VALUE_EMBEDDED_OBJECT)) {
                        final LocalDate parsed = deserialize(parser, context);
                        if (parser.nextToken() != JsonToken.END_ARRAY) {
                            handleMissingEndArrayForSingle(parser, context);
                        }
                        return parsed;
                    }
                    if (t == JsonToken.VALUE_NUMBER_INT) {
                        int year = parser.getIntValue();
                        int month = parser.nextIntValue(-1);
                        int day = parser.nextIntValue(-1);

                        if (parser.nextToken() != JsonToken.END_ARRAY) {
                            throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                                    "Expected array to end");
                        }
                        return LocalDate.of(year, month, day);
                    }
                    context.reportInputMismatch(handledType(),
                            "Unexpected token (%s) within Array, expected VALUE_NUMBER_INT",
                            t);
                }
                if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
                    return (LocalDate) parser.getEmbeddedObject();
                }
                // 06-Jan-2018, tatu: Is this actually safe? Do users expect such coercion?
                if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
                    return LocalDate.ofEpochDay(parser.getLongValue());
                }
                return _handleUnexpectedToken(context, parser, "Expected array or string.");
            }


问:
Google Sheets import multiple HTML table images
Summary

I'm looking to import a data table from a website that does not appear to have an API. The table is broken down to various images and text. The goal is to have all of the content available in a table to then reference for other sheets.

Issue

When I pull in the data, I get some of the text, none of the other images, and a reference to another table. I looked up some options, but none of them yielded anything but blank cells.

I also tried to use the =IMAGE() formula with a direct link to the images URLs, but there is a portion of the URL that is specific to the unit's release date, and as such, too dynamic to account for.

Excel Formula

=IMPORTHTML("https://gamepress.gg/pokemonmasters/database/sync-pair-list","table",3)

答:
Unfortunately without an API it is going to be difficult to achieve what you aim here. These are the main reasons why:

PROBLEMS AND WORKAROUNDS

This table has nested tables that therefore need to be accessed separately. If you take a look at: =IMPORTHTML("https://gamepress.gg/pokemonmasters/database/sync-pair-list","table",4)
 you will see how the table 4 of this HTML page is the stats of a random character of the main table. If you go for 5 or 6 you will realise that the nested tables are not even numerically ordered and that you cannot access them by accessing to the main table (i.e mainTable[0].nestedTable). A hard working approach to do this is to go one by one finding their corresponding stat table and placing next to it. For this I recommend extracting only the name field of the main table to be able to align each stat to their character. You can simply do this using:=INDEX(IMPORTHTML("https://gamepress.gg/pokemonmasters/database/sync-pair-list","table",3),0,1). You can find out more about INDEX here

IMPORTHTML cannot access images nor links so it will be very difficult to get the images in the last columns. A way to solve this is by using as you mentioned the image with its url like this: =IMAGE("https://gamepress.gg/pokemonmasters/sites/pokemonmasters/files/styles/30x30/public/2019-07/Electric.png?itok=fkRfkrFX"). You can find more info about inserting images here

CONCLUSION

To sum up, there is no easy way to solve this problem. The closest you can get is by:

Importing the name column.

Figuring out which tables belong to which character and placing them with next to their name.

Getting the image url of each weakness and type and add it to each character.

I am sorry this site does not have an API to make things smooth, good luck with your project and let me know if you need anything else or if you did not understand anything.

Here you can find more information about IMPORTHTML


问:
How to use sbt-eclipse to create Eclipse project files of a project?
I followed the official documentation to set up the plugin in my sbt project:

Added addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" %
"2.5.0") to ~/.sbt/plugins/plugins.sbt file

cded to a project and ran sbt

In sbt shell, typed eclipse

That's where I faced the following error:

```<code>> eclipse
[error] Not a valid command: eclipse (similar: help, alias)
[error] Not a valid project ID: eclipse (similar: sbteclipse)
[error] Expected ':' (if selecting a configuration)
[error] Not a valid key: eclipse (similar: deliver, licenses, clean)
[error] eclipse
[error]        ^
</code>```

What am I missing?

Thanks in advance for any help you can give me.

```<code>$ /opt/sbt-0.13.5/bin/sbt
[warn] The global sbt directory is now versioned and is located at /Users/first.last/.sbt/0.13.
[warn]   You are seeing this warning because there is global configuration in /Users/first.last/.sbt but not in /Users/first.last/.sbt/0.13.
[warn]   The global sbt directory may be changed via the sbt.global.base system property.
[info] Loading project definition from /Users/first.last/git/myproject/project
[info] Set current project to myproject (in build file:/Users/first.last/git/myproject/)
> eclipse
[error] Not a valid command: eclipse (similar: help, alias)
[error] Not a valid project ID: eclipse
[error] Expected ':' (if selecting a configuration)
[error] Not a valid key: eclipse (similar: deliver, licenses, clean)
[error] eclipse
[error]        ^
</code>```

答:
to create your sbt project on scala eclipse you need to few things:

create a new project

add folders structure in the project

go to the terminal, through cd command go to your project,

type sbt, then it starts downloading, after that

go to project see, is there any project folder made or not

under that folder create plugin.sbt and add sbt (addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.13")
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.2.4")

then go to terminal again type compile den eclipse

it's done, it show a success message

Body:
I followed the official documentation to set up the plugin in my sbt project:

Added addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" %
"2.5.0") to ~/.sbt/plugins/plugins.sbt file

cded to a project and ran sbt

In sbt shell, typed eclipse

That's where I faced the following error:

> eclipse
[error] Not a valid command: eclipse (similar: help, alias)
[error] Not a valid project ID: eclipse (similar: sbteclipse)
[error] Expected ':' (if selecting a configuration)
[error] Not a valid key: eclipse (similar: deliver, licenses, clean)
[error] eclipse
[error]        ^

What am I missing?

Thanks in advance for any help you can give me.

$ /opt/sbt-0.13.5/bin/sbt
[warn] The global sbt directory is now versioned and is located at /Users/first.last/.sbt/0.13.
[warn]   You are seeing this warning because there is global configuration in /Users/first.last/.sbt but not in /Users/first.last/.sbt/0.13.
[warn]   The global sbt directory may be changed via the sbt.global.base system property.
[info] Loading project definition from /Users/first.last/git/myproject/project
[info] Set current project to myproject (in build file:/Users/first.last/git/myproject/)
> eclipse
[error] Not a valid command: eclipse (similar: help, alias)
[error] Not a valid project ID: eclipse
[error] Expected ':' (if selecting a configuration)
[error] Not a valid key: eclipse (similar: deliver, licenses, clean)
[error] eclipse
[error]        ^


问:
How can I migrate a custom submenu with ir.actions.server from Odoo9 to Odoo12?
I have a module with custom submenu for transfers in Odoo9.

In the xml, I have this code:

<record id='action_menu_location_transfer_server' model='ir.actions.server'>
  <field name="name">Custom Transfers</field>
  <field name="model_id" ref="model_wizard_location_transfers_internal_transfer"/>
  <field name="state">code</field>
  <field name="code">action = self.custom_get_transfer_views(cr, uid, context=context)</field>
  <field eval="True" name="condition"/>
</record>

<menuitem id="menu_refund_returns"
         name="Custom Transfers"
         action="action_menu_location_transfer_server"
         parent="stock.menu_stock_warehouse_mgmt"
         sequence="1"
         groups="base.group_user"/>
```

<p>But in Odoo12, if I try to use the code, it shows this error:</p>

```Odoo Server Error
Traceback (most recent call last):
  File "/etc/odoo/server12/odoo/tools/safe_eval.py", line 350, in safe_eval
    return unsafe_eval(c, globals_dict, locals_dict)
  File "", line 1, in <module>
NameError: name 'self' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/etc/odoo/server12/odoo/http.py", line 656, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/etc/odoo/server12/odoo/http.py", line 314, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/etc/odoo/server12/odoo/tools/pycompat.py", line 87, in reraise
    raise value
  File "/etc/odoo/server12/odoo/http.py", line 698, in dispatch
    result = self._call_function(**self.params)
  File "/etc/odoo/server12/odoo/http.py", line 346, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/etc/odoo/server12/odoo/service/model.py", line 97, in wrapper
    return f(dbname, *args, **kwargs)
  File "/etc/odoo/server12/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/etc/odoo/server12/odoo/http.py", line 941, in __call__
    return self.method(*args, **kw)
  File "/etc/odoo/server12/odoo/http.py", line 519, in response_wrap
    response = f(*args, **kw)
  File "/etc/odoo/server12/addons/web/controllers/main.py", line 1269, in run
    result = request.env['ir.actions.server'].browse([action_id]).run()
  File "/etc/odoo/server12/odoo/addons/base/models/ir_actions.py", line 553, in run
    res = func(action, eval_context=eval_context)
  File "/etc/odoo/server12/odoo/addons/base/models/ir_actions.py", line 444, in run_action_code_multi
    safe_eval(action.sudo().code.strip(), eval_context, mode="exec", nocopy=True)  # nocopy allows to return 'action'
  File "/etc/odoo/server12/odoo/tools/safe_eval.py", line 373, in safe_eval
    pycompat.reraise(ValueError, ValueError('%s: "%s" while evaluating\n%r' % (ustr(type(e)), ustr(e), expr)), exc_info[2])
  File "/etc/odoo/server12/odoo/tools/pycompat.py", line 86, in reraise
    raise value.with_traceback(tb)
  File "/etc/odoo/server12/odoo/tools/safe_eval.py", line 350, in safe_eval
    return unsafe_eval(c, globals_dict, locals_dict)
  File "", line 1, in <module>
ValueError: <class 'NameError'>: "name 'self' is not defined" while evaluating
'action = self.custom_get_transfer_views(cr, uid, context=context)'
```

What is the problem with the code for Odoo 12?

I have tried with self, record, object and nothing changes.

答:
you can try this

<record id='action_menu_location_transfer_server' model='ir.actions.server'>
  <field name="name">Custom Transfers</field>
  <field name="model_id" ref="model_wizard_location_transfers_internal_transfer"/>
  <field name="state">code</field>
  <field name="code">model.custom_get_transfer_views()</field>
  <field eval="True" name="condition"/>
</record>
```

the 'cr, uid,' no longer used in v12,

you can add the code of the 'custom_get_transfer_views' method to correct

Body:
I have a module with custom submenu for transfers in Odoo9.

In the xml, I have this code:

<record id='action_menu_location_transfer_server' model='ir.actions.server'>
  <field name="name">Custom Transfers</field>
  <field name="model_id" ref="model_wizard_location_transfers_internal_transfer"/>
  <field name="state">code</field>
  <field name="code">action = self.custom_get_transfer_views(cr, uid, context=context)</field>
  <field eval="True" name="condition"/>
</record>

<menuitem id="menu_refund_returns"
         name="Custom Transfers"
         action="action_menu_location_transfer_server"
         parent="stock.menu_stock_warehouse_mgmt"
         sequence="1"
         groups="base.group_user"/>

But in Odoo12, if I try to use the code, it shows this error:

Odoo Server Error
Traceback (most recent call last):
  File "/etc/odoo/server12/odoo/tools/safe_eval.py", line 350, in safe_eval
    return unsafe_eval(c, globals_dict, locals_dict)
  File "", line 1, in <module>
NameError: name 'self' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/etc/odoo/server12/odoo/http.py", line 656, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/etc/odoo/server12/odoo/http.py", line 314, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/etc/odoo/server12/odoo/tools/pycompat.py", line 87, in reraise
    raise value
  File "/etc/odoo/server12/odoo/http.py", line 698, in dispatch
    result = self._call_function(**self.params)
  File "/etc/odoo/server12/odoo/http.py", line 346, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/etc/odoo/server12/odoo/service/model.py", line 97, in wrapper
    return f(dbname, *args, **kwargs)
  File "/etc/odoo/server12/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/etc/odoo/server12/odoo/http.py", line 941, in __call__
    return self.method(*args, **kw)
  File "/etc/odoo/server12/odoo/http.py", line 519, in response_wrap
    response = f(*args, **kw)
  File "/etc/odoo/server12/addons/web/controllers/main.py", line 1269, in run
    result = request.env['ir.actions.server'].browse([action_id]).run()
  File "/etc/odoo/server12/odoo/addons/base/models/ir_actions.py", line 553, in run
    res = func(action, eval_context=eval_context)
  File "/etc/odoo/server12/odoo/addons/base/models/ir_actions.py", line 444, in run_action_code_multi
    safe_eval(action.sudo().code.strip(), eval_context, mode="exec", nocopy=True)  # nocopy allows to return 'action'
  File "/etc/odoo/server12/odoo/tools/safe_eval.py", line 373, in safe_eval
    pycompat.reraise(ValueError, ValueError('%s: "%s" while evaluating\n%r' % (ustr(type(e)), ustr(e), expr)), exc_info[2])
  File "/etc/odoo/server12/odoo/tools/pycompat.py", line 86, in reraise
    raise value.with_traceback(tb)
  File "/etc/odoo/server12/odoo/tools/safe_eval.py", line 350, in safe_eval
    return unsafe_eval(c, globals_dict, locals_dict)
  File "", line 1, in <module>
ValueError: <class 'NameError'>: "name 'self' is not defined" while evaluating
'action = self.custom_get_transfer_views(cr, uid, context=context)'

What is the problem with the code for Odoo 12?

I have tried with self, record, object and nothing changes.

Body:
you can try this

<record id='action_menu_location_transfer_server' model='ir.actions.server'>
  <field name="name">Custom Transfers</field>
  <field name="model_id" ref="model_wizard_location_transfers_internal_transfer"/>
  <field name="state">code</field>
  <field name="code">model.custom_get_transfer_views()</field>
  <field eval="True" name="condition"/>
</record>

the 'cr, uid,' no longer used in v12,

you can add the code of the 'custom_get_transfer_views' method to correct


问:
MS SQL Server 2008 How can I know whether table/Stored Procedure is in use or not?
Is there any way to determine if any table is in use or not by any project?
Of course question would be when table is only read-only; otherwise, I could see from
new inserted rows. Same question is for a stored procedure. SQL Server Profiler should probably help for SP, not sure about table.
But I don't want to sit and observe SQL Server Profiler. I wish to have a kind of notification.
So basically, I would like to set up a trigger or something, if table gets hit, read then
it notifies me.

Thanks for your help

答:
Try using the stored procedure sp_who2

Link : http://sqlserverplanet.com/dba/using-sp_who2/


问:
Can't paginate data in Laravel
I've successfully retrieved data and displayed it in the list of table but my list is not having paginate

I tried to display 15 data per page,but it displayed all data at once in the page.My data is coming from API .

My controller

```<code> public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
        $content = json_decode($response->getContents(),true);

        $collection = new \Illuminate\Support\Collection($content);

        $total = count($collection['data']);

        $paginationRecord = CollectionPaginate::paginate($collection, $total, 15);

         return view('configuration.comuserprofiles.ComUserProfilesList', compact('paginationRecord'));
}
</code>```

half of my table view

```<code>   @foreach($paginationRecord as $i=>$user)

                            @foreach($user as $i => $u)

                             @php

                                $currentRecordno = 1;
                           // dd($u['irel__com_access_level']['ID']);
                            @endphp

                            <tr>

                                <td>{{ $currentRecordno + $i }}</td>
                                 <td>{{ $u['ID'] }}</td>
                             <td>{{ $u['NICK_NAME'] }}</td>
                             <td>{{ $u['PWD_INVALID_HIT'] }}</td>

                         </tr>
                         @endforeach
</code>```

my pagination blade

```<code><div class="row row-pagination">
    <div class="col-sm-6 text-left">
        <small class="text-muted inline m-t-sm m-b-sm"><font color="#00000f">{{ $paginationRecord->total() }} record/s found </font></small>
    </div>
    <div class="col-md-6 text-right text-center-xs">
        <ul>
            {{ $paginationRecord->links() }}
        </ul>
    </div>
</div>
</code>```

I'm expecting to display 15 records per page

答:
Use take() Collection's method to get specific number of elements

$paginationRecord = CollectionPaginate::paginate($collection->take(15), $total, 15);
```

<p>You can also use <code>forPage()</code>.</p>

<pre class="lang-php prettyprint-override"><code>$page = Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1;
$paginationRecord = new Illuminate\Pagination\LengthAwarePaginator($collection->forPage($page, 15), $total, 15, $page);
</code>```

Title: Can't paginate data in Laravel

Body:
I've successfully retrieved data and displayed it in the list of table but my list is not having paginate

I tried to display 15 data per page,but it displayed all data at once in the page.My data is coming from API .

My controller

 public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
        $content = json_decode($response->getContents(),true);

        $collection = new \Illuminate\Support\Collection($content);

        $total = count($collection['data']);

        $paginationRecord = CollectionPaginate::paginate($collection, $total, 15);

         return view('configuration.comuserprofiles.ComUserProfilesList', compact('paginationRecord'));
}

half of my table view

   @foreach($paginationRecord as $i=>$user)

                            @foreach($user as $i => $u)

                             @php

                                $currentRecordno = 1;
                           // dd($u['irel__com_access_level']['ID']);
                            @endphp

                                {{ $currentRecordno + $i }}
                                 {{ $u['ID'] }}
                             {{ $u['NICK_NAME'] }}
                             {{ $u['PWD_INVALID_HIT'] }}

                         @endforeach

my pagination blade

        {{ $paginationRecord->total() }} record/s found

            {{ $paginationRecord->links() }}

I'm expecting to display 15 records per page

Body:
Use take() Collection's method to get specific number of elements

$paginationRecord = CollectionPaginate::paginate($collection->take(15), $total, 15);

You can also use forPage().

$page = Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1;
$paginationRecord = new Illuminate\Pagination\LengthAwarePaginator($collection->forPage($page, 15), $total, 15, $page);


问:
How to solve a recurrence relation by unrolling?
If I have T(n) = T(n-1) + T(n-2)+ cn; T(1) = T(2) = d

How can I apply unrolling to solve a closed-form for T(n)?

When I try to unroll this by substitution, my equation gets really long and hard to keep track.

答:
You could use sympy, Python's symbolic math library to write out the terms.

from sympy.abc import c, d

def T(n):
    if n <= 0:
        return None
    elif n <= 2:
        return d
    else:
        return T(n-1) + T(n-2) + c*n

for i in range(1, 11):
    print(i, T(i))
```

<p>This gives:</p>

<pre class="lang-py prettyprint-override"><code>1 d
2 d
3 3*c + 2*d
4 7*c + 3*d
5 15*c + 5*d
6 28*c + 8*d
7 50*c + 13*d
8 86*c + 21*d
9 145*c + 34*d
10 241*c + 55*d
</code>```

The coefficients for d are clearly the Fibonacci numbers. The coefficients for c can be looked up in oeis leading to A023552. This gives a long explicit formula, and also Fibonacci(n+2) + 2*Fibonacci(n) - (n+3).

Replacing Fibonacci with Binet's formula using sqrt(5), results in following expression for T(n):

```<code>-2**(-n)*(c*(20*2**n*n + 60*2**n + 8*sqrt(5)*((1 - sqrt(5))**n - (1 + sqrt(5))**n) + sqrt(5)*((1 - sqrt(5))**(n + 2) - (1 + sqrt(5))**(n + 2))) + 4*sqrt(5)*d*((1 - sqrt(5))**n - (1 + sqrt(5))**n))/20
</code>```

This formula coincides nicely with the values above for n = 1 .. 10. But it doesn't look like a formula to be calculated 'by hand'. (Note that Python uses ** for power and reserves ^ for exclusive or.)

Alternatively, one could try Sympy's rsolve to get an explicit formula:

from sympy import Function, rsolve
from sympy.abc import n, c, d

f = Function('f')
T = f(n) - f(n-1) - f(n-2) - c*n
s = rsolve(T, f(n), {f(1): d, f(2): d})
print (s.simplify())
```

<p>Which outputs:</p>

```2**(1 - n)*d*(-2**n*c*n - 2**(n + 1)*c + c*(1 + sqrt(5))**n - (1 - sqrt(5))**n + (1 + sqrt(5))**n)/(-5*c + sqrt(5)*c + 2*sqrt(5))
```

and which unfortunately seems to be wrong.

Body:
You could use sympy, Python's symbolic math library to write out the terms.

from sympy.abc import c, d

def T(n):
    if n <= 0:
        return None
    elif n <= 2:
        return d
    else:
        return T(n-1) + T(n-2) + c*n

for i in range(1, 11):
    print(i, T(i))

This gives:

1 d
2 d
3 3*c + 2*d
4 7*c + 3*d
5 15*c + 5*d
6 28*c + 8*d
7 50*c + 13*d
8 86*c + 21*d
9 145*c + 34*d
10 241*c + 55*d

The coefficients for d are clearly the Fibonacci numbers. The coefficients for c can be looked up in oeis leading to A023552. This gives a long explicit formula, and also Fibonacci(n+2) + 2*Fibonacci(n) - (n+3).

Replacing Fibonacci with Binet's formula using sqrt(5), results in following expression for T(n):

-2**(-n)*(c*(20*2**n*n + 60*2**n + 8*sqrt(5)*((1 - sqrt(5))**n - (1 + sqrt(5))**n) + sqrt(5)*((1 - sqrt(5))**(n + 2) - (1 + sqrt(5))**(n + 2))) + 4*sqrt(5)*d*((1 - sqrt(5))**n - (1 + sqrt(5))**n))/20

This formula coincides nicely with the values above for n = 1 .. 10. But it doesn't look like a formula to be calculated 'by hand'. (Note that Python uses ** for power and reserves ^ for exclusive or.)

Alternatively, one could try Sympy's rsolve to get an explicit formula:

from sympy import Function, rsolve
from sympy.abc import n, c, d

f = Function('f')
T = f(n) - f(n-1) - f(n-2) - c*n
s = rsolve(T, f(n), {f(1): d, f(2): d})
print (s.simplify())

Which outputs:

2**(1 - n)*d*(-2**n*c*n - 2**(n + 1)*c + c*(1 + sqrt(5))**n - (1 - sqrt(5))**n + (1 + sqrt(5))**n)/(-5*c + sqrt(5)*c + 2*sqrt(5))

and which unfortunately seems to be wrong.


问:
Displaying Currency in Indian Numbering Format
I have a question about formatting the Rupee currency (Indian Rupee - INR).

Typically a value like 450500 is formatted and shown as 450,500. In India, the same value is displayed as 4,50,500

For example, numbers here are represented as:

```<code>1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
</code>```

Refer Indian Numbering System

The separators are after two digits, except for the last set, which is in thousands.

I've searched on the internet and people have asked to use the locale en_GB or pattern #,##,##,##,##0.00

I tried this on JSTL by using the following tag:

```<code><fmt:formatNumber value="${product.price}" type="currency"
  pattern="#,##,##,##,###.00"/>
</code>```

But this does not seem to solve the issue.

答:
```<code>public static String paiseToString(long paise)
{
    DecimalFormat fmt = new DecimalFormat("#0.00");
    boolean minus = paise < 0;
    StringBuilder sb = new StringBuilder(fmt.format(Math.abs(paise)/100.0));
    for (int index = sb.length()-6; index > 0; index-=2)
    {
        sb.insert(index,',');
    }
    if (minus)
       sb.insert(0,'-');
    return sb.toString();
}

public static String rupeesToString(long rupees)
{
    boolean minus = rupees < 0;
    StringBuilder sb = new StringBuilder(Long.toString(Math.abs(rupees)));
    for (int index = sb.length()-3; index > 0; index-=2)
    {
        sb.insert(index,',');
    }
    if (minus)
       sb.insert(0,'-');
    return sb.toString();
}

// Test the functions
public static void main(String[] args)
{
    // Test for positive values
    long val = 1;
    while (val < Long.MAX_VALUE/10)
    {
        System.out.printf("%28s %28s\n",paiseToString(val),rupeesToString(val));
        val *= 10;
    }
    // Test for negative values
    val = -1;
    while (val > Long.MIN_VALUE/10)
    {
        System.out.printf("%28s %28s\n",paiseToString(val),rupeesToString(val));
        val *= 10;
    }
}
</code>```

Body:
I have a question about formatting the Rupee currency (Indian Rupee - INR).

Typically a value like 450500 is formatted and shown as 450,500. In India, the same value is displayed as 4,50,500

For example, numbers here are represented as:

1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000

Refer Indian Numbering System

The separators are after two digits, except for the last set, which is in thousands.

I've searched on the internet and people have asked to use the locale en_GB or pattern #,##,##,##,##0.00

I tried this on JSTL by using the following tag:

<fmt:formatNumber value="${product.price}" type="currency"
  pattern="#,##,##,##,###.00"/>

But this does not seem to solve the issue.


问:
Implement GeckoView Web Extension
I'm trying to implement a noddy web extension for GeckoView in Android to simply execute some javascript on a web page, the equivalent of webView.evaluateJavascript() on a normal Android WebView, however I'm having trouble finding any useful examples or tutorials online.

I have previously tried a WebView before, however the site I am attempting to access bugs during login meaning I cannot access it. However the login works with a GeckoView

I've followed these so far:

https://sammacbeth.eu/blog/2019/09/04/geckoview-extensions.html

https://mozilla.github.io/geckoview/consumer/docs/web-extensions

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension

However, they seem to be a bit dated, even mozilla's own documentation, as the API I am using no longer follows the examples.

I'm using the stable release of GeckoView: 73.0.20200217142647

As per [3] above, my file structure is:

```<code>java
 |
 +-- assets
 |   |
 |   +--checkExtension
 |      |
 |      manifest.json
 |      checkExtension.js
 |
 +-- res
 |
 +-- src
</code>```

The contents of manifest.json is

```<code> {

  "manifest_version": 2,
  "name": "checkExtension",
  "version": "1.0",

  "description": "Automatically clicks the authorise button to continue the photo upload.",

  "content_scripts": [
    {
      "matches": ["*"],
      "js": ["checkExtension.js"]
    }
  ],
  "permissions": [
    "nativeMessaging",
    "geckoViewAddons"
  ]

}
</code>```

'matches' is set to '*' so that it should match any and all pages navigated to

checkExtension.js just contains:

```<code>alert('hello')
</code>```

My GeckoView activity is:

```<code>GeckoView view = findViewById(R.id.geckoview);
GeckoSession session = new GeckoSession();
GeckoRuntime runtime = GeckoRuntime.create(this);

session.open(runtime);

WebExtension test = new WebExtension(
    "resource://assets/extension/checkExtension/",
    runtime.getWebExtensionController());

runtime.registerWebExtension(test);

view.setSession(session);
session.loadUri("https://www.google.com");
</code>```

However, no alert is showing when the page loads. I have tried a few site-specific targeted scripts besides just attempting to show an alert box, however none of them have worked either.

Is there anything obvious is am missing or any resources that might help me?

Many Thanks.

答:
However, no alert is showing when the page loads

Note that by default GeckoView will not show any alerts itself and instead invoke GeckoSession.PromptDelegate.onAlertPrompt() if you register a PromptDelegate.

Instead of using alert you could log, or implement onAlertPrompt() to log or show a dialog. This is how the sample app implements it:
https://searchfox.org/mozilla-central/rev/fca0be7e2cf2f922c9b927423ce28e8a04b3fd90/mobile/android/geckoview_example/src/main/java/org/mozilla/geckoview_example/BasicGeckoViewPrompt.java#68-81

In addition to that registerWebExtension() returns a GeckoResult that you can use to detect whether the extension was successfully loaded. This may help you debug problems, e.g.:

```<code>runtime.registerWebExtension(ext.nativeExtension).then({
    Log.d(TAG, "WebExtension registered successfully")
}, { throwable ->
    Log.d(TAG, "WebExtension registration failed", throwable)
})
</code>```

Title: Implement GeckoView Web Extension

Body:
I'm trying to implement a noddy web extension for GeckoView in Android to simply execute some javascript on a web page, the equivalent of webView.evaluateJavascript() on a normal Android WebView, however I'm having trouble finding any useful examples or tutorials online.

I have previously tried a WebView before, however the site I am attempting to access bugs during login meaning I cannot access it. However the login works with a GeckoView

I've followed these so far:

https://sammacbeth.eu/blog/2019/09/04/geckoview-extensions.html

https://mozilla.github.io/geckoview/consumer/docs/web-extensions

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension

However, they seem to be a bit dated, even mozilla's own documentation, as the API I am using no longer follows the examples.

I'm using the stable release of GeckoView: 73.0.20200217142647

As per [3] above, my file structure is:

java
 |
 +-- assets
 |   |
 |   +--checkExtension
 |      |
 |      manifest.json
 |      checkExtension.js
 |
 +-- res
 |
 +-- src

The contents of manifest.json is

 {

  "manifest_version": 2,
  "name": "checkExtension",
  "version": "1.0",

  "description": "Automatically clicks the authorise button to continue the photo upload.",

  "content_scripts": [
    {
      "matches": ["*"],
      "js": ["checkExtension.js"]
    }
  ],
  "permissions": [
    "nativeMessaging",
    "geckoViewAddons"
  ]

}

'matches' is set to '*' so that it should match any and all pages navigated to

checkExtension.js just contains:

alert('hello')

My GeckoView activity is:

GeckoView view = findViewById(R.id.geckoview);
GeckoSession session = new GeckoSession();
GeckoRuntime runtime = GeckoRuntime.create(this);

session.open(runtime);

WebExtension test = new WebExtension(
    "resource://assets/extension/checkExtension/",
    runtime.getWebExtensionController());

runtime.registerWebExtension(test);

view.setSession(session);
session.loadUri("https://www.google.com");

However, no alert is showing when the page loads. I have tried a few site-specific targeted scripts besides just attempting to show an alert box, however none of them have worked either.

Is there anything obvious is am missing or any resources that might help me?

Many Thanks.

Body:
However, no alert is showing when the page loads

Note that by default GeckoView will not show any alerts itself and instead invoke GeckoSession.PromptDelegate.onAlertPrompt() if you register a PromptDelegate.

Instead of using alert you could log, or implement onAlertPrompt() to log or show a dialog. This is how the sample app implements it:
https://searchfox.org/mozilla-central/rev/fca0be7e2cf2f922c9b927423ce28e8a04b3fd90/mobile/android/geckoview_example/src/main/java/org/mozilla/geckoview_example/BasicGeckoViewPrompt.java#68-81

In addition to that registerWebExtension() returns a GeckoResult that you can use to detect whether the extension was successfully loaded. This may help you debug problems, e.g.:

runtime.registerWebExtension(ext.nativeExtension).then({
    Log.d(TAG, "WebExtension registered successfully")
}, { throwable ->
    Log.d(TAG, "WebExtension registration failed", throwable)
})


问:
Case statement to bucket amounts into categories
If I want to create a case statement that buckets column values into one new column how can I do this without multiple case statements?

```<code>ID | Amount
B     200
W     300
B     300
W     20
</code>```

etc.

Ouput would be grouping by ID and sum of amount for that ID have a new column that buckets them into a category but in one case statement?

```<code>ID | Amount | Bucket
B     600     >= 500
W     320     >=0 and <=500
</code>```

Thanks

答:
You can do:</p>

```<code>select id, sum(amount) as amount,
       (case when sum(amount) >= 0 and sum(amount) < = 500
             then '>= 0 and <= 500'
             when sum(amount) > 500
             then '> 500'
        end) as Bucket
from table t
group by id;
</code>```

Body:
If I want to create a case statement that buckets column values into one new column how can I do this without multiple case statements?

ID | Amount
B     200
W     300
B     300
W     20

etc.

Ouput would be grouping by ID and sum of amount for that ID have a new column that buckets them into a category but in one case statement?

ID | Amount | Bucket
B     600     >= 500
W     320     >=0 and <=500

Thanks

Body:
You can do:

select id, sum(amount) as amount,
       (case when sum(amount) >= 0 and sum(amount) < = 500
             then '>= 0 and <= 500'
             when sum(amount) > 500
             then '> 500'
        end) as Bucket
from table t
group by id;


问:
Chain Code not deploying on Test Network after executing the deployment script in Hyperledger Fabric 2.0 documentation
I ran the script ./network.sh deployCC, then its not able to deploy it on the network(Fabric 2.0), this is the error:

```<code>deploying chaincode on channel 'mychannel'

Vendoring Go dependencies ...
~/Desktop/Fabric/fabric-samples/chaincode/fabcar/go
~/Desktop/Fabric/fabric-samples/test-network
go: unknown subcommand "mod"
Run 'go help' for usage.
~/Desktop/Fabric/fabric-samples/test-network
Finished vendoring Go dependencies
Using organization 1
++ peer lifecycle chaincode package fabcar.tar.gz --path
../chaincode/fabcar/go/ --lang golang --label fabcar_1
++ res=1
++ set +x
Error: error getting chaincode bytes: listing deps for pacakge
../chaincode/fabcar/go/ failed: exit status 2
!!!!!!!!!!!!!!! Chaincode packaging on peer0.org1 has failed
!!!!!!!!!!!!!!!!

ERROR !!! Deploying chaincode failed
</code>```

答:
The issue is with the Go package you installed.Which version you have installed?
The ideal way to install the latest Go is from here.Go

And if your using ubuntu don't go with the apt installation.

First remove apt installed go

$ sudo apt-get remove go

Download the tar file for linux from the site https://golang.org/dl/
450

Execute the command $ sudo tar -C /usr/local -xzf

Body:
I ran the script ./network.sh deployCC, then its not able to deploy it on the network(Fabric 2.0), this is the error:

deploying chaincode on channel 'mychannel'

Vendoring Go dependencies ...
~/Desktop/Fabric/fabric-samples/chaincode/fabcar/go
~/Desktop/Fabric/fabric-samples/test-network
go: unknown subcommand "mod"
Run 'go help' for usage.
~/Desktop/Fabric/fabric-samples/test-network
Finished vendoring Go dependencies
Using organization 1
++ peer lifecycle chaincode package fabcar.tar.gz --path
../chaincode/fabcar/go/ --lang golang --label fabcar_1
++ res=1
++ set +x
Error: error getting chaincode bytes: listing deps for pacakge
../chaincode/fabcar/go/ failed: exit status 2
!!!!!!!!!!!!!!! Chaincode packaging on peer0.org1 has failed
!!!!!!!!!!!!!!!!

ERROR !!! Deploying chaincode failed


问:
How to access the volume in host in docker for windows
I run the docker for Windows and ubuntu in WSL.
When I run the following command

docker volume create test

docker volume inspect test

I get the following output

```<code>[
    {
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/test/_data",
        "Name": "test",
        "Options": {},
        "Scope": "local"
    }
]
</code>```

when I access the location, I get
bash: cd: /var/lib/docker/volumes: No such file or directory

So how should I access the folder?

答:
based on @nick's answer

From linux: sudo ls /mnt/wsl/docker-desktop-data/data/docker/volumes

From windows: \\wsl$\docker-desktop-data\mnt\wsl\docker-desktop-data\data\docker\volumes

Body:
I run the docker for Windows and ubuntu in WSL.
When I run the following command

docker volume create test

docker volume inspect test

I get the following output

[
    {
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/test/_data",
        "Name": "test",
        "Options": {},
        "Scope": "local"
    }
]

when I access the location, I get
bash: cd: /var/lib/docker/volumes: No such file or directory

So how should I access the folder?


问:
NSNumber value changing when JSON object is converted to data and then that data is again converted back to JSON object
I am creating NSData object with a dictionary as follows,

dictionary:

```<code>{
    channelId = 201;
    lang = EN;
    reqRefNo = vZRIzNd;
    storeInfo =     {
        clientInfo =         {
            deviceId = XXXXXXXXA67F488B836D19D80EC4FD8D;
        };
        loginLogId = XXXXXXXX5CAD4A0DA06BE2F055929856;
        qrCodeInfo =         {
            itemDesc = "";
            itemName = hahsj;
            price = 106;
        };
        userInfo =         {
            storeId = 3252;
        };
    };
}
</code>```

price = 106

```<code>NSData *data = [NSJSONSerialization dataWithJSONObject:paramDict options:kNilOptions error:nil];
</code>```

Now I'm again converting it back to JSON object as follows,

```<code>NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                         options:kNilOptions
                                                       error:&error];
</code>```

But I'm getting wrong price this time.

converted dictionary

```<code>{
    channelId = 201;
    lang = EN;
    reqRefNo = vZRIzNd;
    storeInfo =     {
        clientInfo =         {
            deviceId = XXXXXXXXA67F488B836D19D80EC4FD8D;
        };
        loginLogId = XXXXXXXX5CAD4A0DA06BE2F055929856;
        qrCodeInfo =         {
            itemDesc = "";
            itemName = hahsj;
            price = "105.9999923706055";
        };
        userInfo =         {
            storeId = 3252;
        };
    };
}
</code>```

price = "105.9999923706055"

Code for generating NSNumber,

```<code>//_amountTF.text = "S$1.06";
NSString *amount = [_amountTF.text stringByReplacingOccurrencesOfString:@"S$" withString:@""];
float amt = [amount floatValue];
amt *=100;
NSNumber *num = [NSNumber numberWithFloat:amt];
</code>```

Can anyone please explain me the reason behind this? Thanks.

答:
while. creating dictionary add price Value:

price = [NSString stringWithFormat:@"106"];
or,
int  priceValue = 106;
price = [NSString stringWithFormat:@"%d",priceValue];

Now converted dictionary. will be whatever you need.

Body:
I am creating NSData object with a dictionary as follows,

dictionary:

{
    channelId = 201;
    lang = EN;
    reqRefNo = vZRIzNd;
    storeInfo =     {
        clientInfo =         {
            deviceId = XXXXXXXXA67F488B836D19D80EC4FD8D;
        };
        loginLogId = XXXXXXXX5CAD4A0DA06BE2F055929856;
        qrCodeInfo =         {
            itemDesc = "";
            itemName = hahsj;
            price = 106;
        };
        userInfo =         {
            storeId = 3252;
        };
    };
}

price = 106

NSData *data = [NSJSONSerialization dataWithJSONObject:paramDict options:kNilOptions error:nil];

Now I'm again converting it back to JSON object as follows,

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                         options:kNilOptions
                                                       error:&error];

But I'm getting wrong price this time.

converted dictionary

{
    channelId = 201;
    lang = EN;
    reqRefNo = vZRIzNd;
    storeInfo =     {
        clientInfo =         {
            deviceId = XXXXXXXXA67F488B836D19D80EC4FD8D;
        };
        loginLogId = XXXXXXXX5CAD4A0DA06BE2F055929856;
        qrCodeInfo =         {
            itemDesc = "";
            itemName = hahsj;
            price = "105.9999923706055";
        };
        userInfo =         {
            storeId = 3252;
        };
    };
}

price = "105.9999923706055"

Code for generating NSNumber,

//_amountTF.text = "S$1.06";
NSString *amount = [_amountTF.text stringByReplacingOccurrencesOfString:@"S$" withString:@""];
float amt = [amount floatValue];
amt *=100;
NSNumber *num = [NSNumber numberWithFloat:amt];

Can anyone please explain me the reason behind this? Thanks.


问:
Webpack eveything loads but the worker
I'm trying to use webpack to bundle my react project. All the modules and everything loads perfectly fine after I defined the webpack_public_path variable.
Everything but the worker.

```<code>const path = require('path');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
    mode: "production",

    resolve: {
        extensions: ["*", ".ts", ".tsx", ".js", ".mjs", ".css", ".ttf"]
    },

    module: {
        rules: [
            {
                test: /\.worker\.js$/,
                use: {
                    loader: 'worker-loader',
                    options: {inline: true}
                },
            },
            {
                test: /\.mjs$/,
                include: /node_modules/,
                type: 'javascript/auto'
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.ttf$/,
                use: ['file-loader']
            },
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            }
        ]
    },
    plugins: [
        new MonacoWebpackPlugin({
            languages: ['markdown'],
        })
    ],
    entry: './src/index.tsx',
    output: {
        path: path.resolve(__dirname, 'assets'),
        filename: 'graphqlschemaeditor.js'
    }
};
</code>```

This is my webpack.config.js

Does anyone have an idea what I'm doing wrong? Thanks a lot

答:
Have you tried to specify an explicit publicPath?

E.g.

```<code>{
  loader: 'worker-loader',
  options: { publicPath: '/workers/' }
}
</code>```

This may resolve loading problems.

Title: Webpack eveything loads but the worker

Body:
I'm trying to use webpack to bundle my react project. All the modules and everything loads perfectly fine after I defined the webpack_public_path variable.
Everything but the worker.

const path = require('path');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
    mode: "production",

    resolve: {
        extensions: ["*", ".ts", ".tsx", ".js", ".mjs", ".css", ".ttf"]
    },

    module: {
        rules: [
            {
                test: /\.worker\.js$/,
                use: {
                    loader: 'worker-loader',
                    options: {inline: true}
                },
            },
            {
                test: /\.mjs$/,
                include: /node_modules/,
                type: 'javascript/auto'
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.ttf$/,
                use: ['file-loader']
            },
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            }
        ]
    },
    plugins: [
        new MonacoWebpackPlugin({
            languages: ['markdown'],
        })
    ],
    entry: './src/index.tsx',
    output: {
        path: path.resolve(__dirname, 'assets'),
        filename: 'graphqlschemaeditor.js'
    }
};

This is my webpack.config.js

Does anyone have an idea what I'm doing wrong? Thanks a lot

Body:
Have you tried to specify an explicit publicPath?

E.g.

{
  loader: 'worker-loader',
  options: { publicPath: '/workers/' }
}

This may resolve loading problems.