问:
Resend Code using Firebase Authentication in Swift
As there is no direct method to resend code once the code has already been sent , I am trying to resend it once again with following method :

```<code> func sendOTPGetVerfID(phoneNum: String, completion: @escaping((_ verificationID: String?, _ error: Error?) -> Void)) {

      PhoneAuthProvider.provider().verifyPhoneNumber( phoneNum , uiDelegate: nil) { (verificationID, error) in

        if let error = error {
            QL1(error.localizedDescription)
            completion(nil, error)
            return
        }
        // Sign in using the verificationID and the code sent to the user
        // ...
        QL1("VerificationID : \(verificationID ?? "")")
        completion(verificationID,nil)
    }
}
</code>```

Issue here is, I am not able to receive the verificationID second time, calling the above method
Any help appreciated

答:
Call requestOtp() method on resend OTP button click.

```<code>import FirebaseAuth

func requestOtp() {
let phNo = "Your phone number"
PhoneAuthProvider.provider().verifyPhoneNumber(phNo, uiDelegate: nil) { (verificationID, error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }
        // Sign in using the verificationid and the code sent to the user
        // ...
      UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
    }
}
</code>```

Verify Code with Auth:

```<code>func verifyNumberWith(verificationCode: String) {
  let verificationID=UserDefaults.standard.string(forKey:"authVerificationID")
    let credential = PhoneAuthProvider.provider().credential(
        withVerificationID: verificationID ?? "",
        verificationCode: verificationCode)

    Auth.auth().signIn(with: credential) { (authResult, error) in
        //Do your actions.
    }
}
</code>```

Body:
As there is no direct method to resend code once the code has already been sent , I am trying to resend it once again with following method :

 func sendOTPGetVerfID(phoneNum: String, completion: @escaping((_ verificationID: String?, _ error: Error?) -> Void)) {

      PhoneAuthProvider.provider().verifyPhoneNumber( phoneNum , uiDelegate: nil) { (verificationID, error) in

        if let error = error {
            QL1(error.localizedDescription)
            completion(nil, error)
            return
        }
        // Sign in using the verificationID and the code sent to the user
        // ...
        QL1("VerificationID : \(verificationID ?? "")")
        completion(verificationID,nil)
    }
}

Issue here is, I am not able to receive the verificationID second time, calling the above method
Any help appreciated

Body:
Call requestOtp() method on resend OTP button click.

import FirebaseAuth

func requestOtp() {
let phNo = "Your phone number"
PhoneAuthProvider.provider().verifyPhoneNumber(phNo, uiDelegate: nil) { (verificationID, error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }
        // Sign in using the verificationid and the code sent to the user
        // ...
      UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
    }
}

Verify Code with Auth:

func verifyNumberWith(verificationCode: String) {
  let verificationID=UserDefaults.standard.string(forKey:"authVerificationID")
    let credential = PhoneAuthProvider.provider().credential(
        withVerificationID: verificationID ?? "",
        verificationCode: verificationCode)

    Auth.auth().signIn(with: credential) { (authResult, error) in
        //Do your actions.
    }
}


来源: stackexchange

问:
How to use a hash table to find a cycle in a singly linked list?
I am aware this is a common question asked, but no answers I've found differ from my algorithm, yet leetcode states my algorithm doesn't work. How can I use a hash table to find if there is a cycle in a singly linked list in JS? I implemented the following algorithm:

```<code>var hasCycle = function(head) {
    let node = head;
    let table = {};

    while(node) {
        if(table[node.value]) {
            return true;
        }
        else {
            table[node.value] = true;
        }
        node = node.next;
    }

    return false;
};
</code>```

However on leetcode, my algorithm works until it hits the following test case:

```<code>Input: [1, 2], pos: -1
</code>```

Where [1, 2] is the linked list, and pos is the position of the node that the tail points to. Since it is -1, the tail points to null so there is no cycle.

Why does leetcode say my code returns true? In my while loop, the first iteration sets table[1] to true. In the second iteration, table[2] is set to true. Then we exit the while loop since node points to null now, so my code should return false. However, leetcode says my algorithm returns true. Where did I make a mistake?

I am aware of the tortoise and hare algorithm, but I am trying to understand the hash table method to find a cycle.

答:
Essentially what you need to do is traverse through the list and see which comes first? The end of the list, or a previously visited node. You can use your Hashtable to record what nodes you have visited, although you really need is a Set, but you can use a hashtable for this purpose if that is what the specifications are:

Here's how you go about it:

Check if the node you are at is null. If so, there are no cycles

Check if the node you are at is already in the hashtable. If so, there is a cycle

If not 1 or 2:

Add the node to the hashtable

Go on to the next node in the list

ContentLicense: CC BY-SA 4.0

Body:
I am aware this is a common question asked, but no answers I've found differ from my algorithm, yet leetcode states my algorithm doesn't work. How can I use a hash table to find if there is a cycle in a singly linked list in JS? I implemented the following algorithm:

var hasCycle = function(head) {
    let node = head;
    let table = {};

    while(node) {
        if(table[node.value]) {
            return true;
        }
        else {
            table[node.value] = true;
        }
        node = node.next;
    }

    return false;
};

However on leetcode, my algorithm works until it hits the following test case:

Input: [1, 2], pos: -1

Where [1, 2] is the linked list, and pos is the position of the node that the tail points to. Since it is -1, the tail points to null so there is no cycle.

Why does leetcode say my code returns true? In my while loop, the first iteration sets table[1] to true. In the second iteration, table[2] is set to true. Then we exit the while loop since node points to null now, so my code should return false. However, leetcode says my algorithm returns true. Where did I make a mistake?

I am aware of the tortoise and hare algorithm, but I am trying to understand the hash table method to find a cycle.


问:
Replace array by specific element value
I need to replace my main array elements by 'employee_id'.
I already tried array_replace_recursive() function But It replaces arrays by the default index value.

$merged = array_replace_recursive($empList, $getworkedHrs,
  $getErrAttnds);

The arrays look like this:
$empList

```<code>    array (
      0 =>
      array (
        'employee_id' => '254',
        'emp_name' => 'Mary McDonald',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 0,
      ),
      1 =>
      array (
        'employee_id' => '255',
        'emp_name' => 'Anthony Coffman',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 0,
      ),
      2 =>
      array (
        'employee_id' => '316',
        'emp_name' => 'cheth aruno',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 0,
      ),
   )
</code>```

2nd Array: $getworkedHrs

```<code>array (
  0 =>
  array (
    'employee_id' => '254',
    'worked_days' => '22',
    'worked_hours' => '7.0',
  ),
  1 =>
  array (
    'employee_id' => '255',
    'worked_days' => '8',
    'worked_hours' => '7.0',
  ),
)
</code>```

3rd array : $getErrAttnds

```<code>array (
  0 =>
  array (
    'employee_id' => '316',
    'error_attendance' => '1',
  ),
)
</code>```

Expected Result Array:

```<code>    array (
      0 =>
      array (
        'employee_id' => '254',
        'emp_name' => 'Mary McDonald',
        'worked_days' => 22,
        'worked_hours' => 7.0,
        'error_attendance' => 0,
      ),
      1 =>
      array (
        'employee_id' => '255',
        'emp_name' => 'Anthony Coffman',
        'worked_days' => 8,
        'worked_hours' => 7.0,
        'error_attendance' => 0,
      ),
      2 =>
      array (
        'employee_id' => '316',
        'emp_name' => 'cheth aruno',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 1,
      ),
   )
</code>```

答:
I believe the simplest solution is to merge them in two foreach.

First make the main array associative so that it's easier to get the correct employee.

Then loop the arrays and copy the values.

```<code>$empList = array_column($empList, null, 'employee_id');

foreach($getworkedHrs as $entry){
    $empList[$entry['employee_id']]['worked_days'] = $entry['worked_days'];
    $empList[$entry['employee_id']]['worked_hours'] = $entry['worked_hours'];
}

foreach($getErrAttnds as $entry){
    $empList[$entry['employee_id']]['error_attendance'] = $entry['error_attendance'];
}

var_export($empList);
</code>```

https://3v4l.org/gIXP6

Title: Replace array by specific element value

Body:
I need to replace my main array elements by 'employee_id'.
I already tried array_replace_recursive() function But It replaces arrays by the default index value.

$merged = array_replace_recursive($empList, $getworkedHrs,
  $getErrAttnds);

The arrays look like this:
$empList

    array (
      0 =>
      array (
        'employee_id' => '254',
        'emp_name' => 'Mary McDonald',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 0,
      ),
      1 =>
      array (
        'employee_id' => '255',
        'emp_name' => 'Anthony Coffman',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 0,
      ),
      2 =>
      array (
        'employee_id' => '316',
        'emp_name' => 'cheth aruno',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 0,
      ),
   )

2nd Array: $getworkedHrs

array (
  0 =>
  array (
    'employee_id' => '254',
    'worked_days' => '22',
    'worked_hours' => '7.0',
  ),
  1 =>
  array (
    'employee_id' => '255',
    'worked_days' => '8',
    'worked_hours' => '7.0',
  ),
)

3rd array : $getErrAttnds

array (
  0 =>
  array (
    'employee_id' => '316',
    'error_attendance' => '1',
  ),
)

Expected Result Array:

    array (
      0 =>
      array (
        'employee_id' => '254',
        'emp_name' => 'Mary McDonald',
        'worked_days' => 22,
        'worked_hours' => 7.0,
        'error_attendance' => 0,
      ),
      1 =>
      array (
        'employee_id' => '255',
        'emp_name' => 'Anthony Coffman',
        'worked_days' => 8,
        'worked_hours' => 7.0,
        'error_attendance' => 0,
      ),
      2 =>
      array (
        'employee_id' => '316',
        'emp_name' => 'cheth aruno',
        'worked_days' => 0,
        'worked_hours' => 0,
        'error_attendance' => 1,
      ),
   )

Body:
I believe the simplest solution is to merge them in two foreach.

First make the main array associative so that it's easier to get the correct employee.

Then loop the arrays and copy the values.

$empList = array_column($empList, null, 'employee_id');

foreach($getworkedHrs as $entry){
    $empList[$entry['employee_id']]['worked_days'] = $entry['worked_days'];
    $empList[$entry['employee_id']]['worked_hours'] = $entry['worked_hours'];
}

foreach($getErrAttnds as $entry){
    $empList[$entry['employee_id']]['error_attendance'] = $entry['error_attendance'];
}

var_export($empList);

https://3v4l.org/gIXP6


问:
How to get rows count of internal table in abap?
How do I get the row count of an internal table? I guess that I can loop on it. But there must be a saner way.

I don't know if it makes a difference but the code should run on 4.6c version.

答:
if I understand your question correctly, you want to know the row number during a conditional loop over an internal table.
You can use the system variable sy-tabix if you work with internal tables. Please refer to the ABAP documentation if you need more information (especially the chapter on internal table processing).

Example:

```<code>LOOP AT itab INTO workarea
        WHERE tablefield = value.

     WRITE: 'This is row number ', sy-tabix.

ENDLOOP.
</code>```

OwnerDisplayName: Igal Serban

ContentLicense: CC BY-SA 2.5

Body:
if I understand your question correctly, you want to know the row number during a conditional loop over an internal table.
You can use the system variable sy-tabix if you work with internal tables. Please refer to the ABAP documentation if you need more information (especially the chapter on internal table processing).

Example:

LOOP AT itab INTO workarea
        WHERE tablefield = value.

     WRITE: 'This is row number ', sy-tabix.

ENDLOOP.


问:
`for/in` loop contains weird indices
I am running Electron 4.0.6 and react-scripts 3.0.1, which, I believe, includes babel. I wrote this code:

```<code>const data = [1, 2, 3]
for( const idx in data ) console.log(idx)
</code>```

Expected output is:

0

  1

  2

Actual output is:

0

  1

  2

  peek

  last

with the last two indices mapping to functions. I have a large program written using for/in loops, and I am daunted by the possibility of putting in error checking in every one of my loops to make sure I'm not accidentally consuming a function index.

My questions:

Why am I seeing this?

How do I fix it?

Edit:

Thanks for everyone's input. To be clear, the program used to work until I reinstalled it on a new computer. I used to be able to use for/in to iterate over only the non-default indices in an array. I'm not sure why I can't do that anymore, and I'm wondering what changed that made it work the way it does now. Do I need to install an older version of react-scripts? Simply rewriting the whole program to use of loops doesn't work, either, because I already do that when I can. I use for/in loops when I need the index.

Edit 2:

I appreciate everybody's help. Thanks to the accepted answer, I was able to track down that the npm package dirty-json is overriding all arrays with .peek and .last without setting them as non-enumerable. I am now able to address this issue.

Final edit: dirty-json is fixed, so this exact problem should no longer occur. If you have arrived here because of a similar issue, check your packages; it is not dirty-json as of version 0.9.0.

答:
A for-in loop iterates over an object’s enumerable properties. I think you want a for-of which iterates or entries in an iterable, or forEach, which iterates over the elements in an array.

If there’s code in your app that’s modifying Array.prototype and adding peek and last and not marking them as non-enumerable, a for-in loop is going to see them.

Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method),

Object.defineProperty will let you add those methods with enumerable: false (the default).

For starters I’d probably just search the codebase (including node_modules) for ‘peek =‘ to see if that turns it up somewhere. Or look at your dependency list for some utility that seems like a likely culprit.

Title: `for/in` loop contains weird indices

Body:
I am running Electron 4.0.6 and react-scripts 3.0.1, which, I believe, includes babel. I wrote this code:

const data = [1, 2, 3]
for( const idx in data ) console.log(idx)

Expected output is:

0

  1

  2

Actual output is:

0

  1

  2

  peek

  last

with the last two indices mapping to functions. I have a large program written using for/in loops, and I am daunted by the possibility of putting in error checking in every one of my loops to make sure I'm not accidentally consuming a function index.

My questions:

Why am I seeing this?

How do I fix it?

Edit:

Thanks for everyone's input. To be clear, the program used to work until I reinstalled it on a new computer. I used to be able to use for/in to iterate over only the non-default indices in an array. I'm not sure why I can't do that anymore, and I'm wondering what changed that made it work the way it does now. Do I need to install an older version of react-scripts? Simply rewriting the whole program to use of loops doesn't work, either, because I already do that when I can. I use for/in loops when I need the index.

Edit 2:

I appreciate everybody's help. Thanks to the accepted answer, I was able to track down that the npm package dirty-json is overriding all arrays with .peek and .last without setting them as non-enumerable. I am now able to address this issue.

Final edit: dirty-json is fixed, so this exact problem should no longer occur. If you have arrived here because of a similar issue, check your packages; it is not dirty-json as of version 0.9.0.


问:
How to save data changes in MYSQL column
I have received a database, where I had to change the date format on one of the tables into msql date format. I was wondering how to save these changes on MySQL, once I conduct the command:

```<code>SELECT from_unixtime(last_post_date)
FROM it_forum;
</code>```

The column that I want to change to is below:

答:
You would typically create a new column, fill it from the old column and then drop the old column:

```<code>-- rename the "old" column
alter table mytable rename column last_post_date to last_post_date_old;

-- create the "new" column
alter table mytable add last_post_date datetime;

-- feed the "new" column
update mytable set last_post_date = from_unixtime(last_post_date_old);

-- drop the "old" column
alter table mytable drop column last_post_date_old;
</code>```

You need downtime on the table to run this safely.

Note: the rename syntax is available in MySQL 8.0 only. In earlier versions, you need to use the more cumbersome change syntax, which requires redeclaring the datatype (the following assumes int):

```<code>alter table mytable change last_post_date last_post_date_old int;
</code>```

Demo on DB Fiddle

Before:

```
| last_post_date |
| -------------: |
|     1591132456 |
```

After:

```
| last_post_date      |
| :------------------ |
| 2020-06-02 22:14:16 |
```

Body:
I have received a database, where I had to change the date format on one of the tables into msql date format. I was wondering how to save these changes on MySQL, once I conduct the command:

SELECT from_unixtime(last_post_date)
FROM it_forum;

The column that I want to change to is below:

Body:
You would typically create a new column, fill it from the old column and then drop the old column:

-- rename the "old" column
alter table mytable rename column last_post_date to last_post_date_old;

-- create the "new" column
alter table mytable add last_post_date datetime;

-- feed the "new" column
update mytable set last_post_date = from_unixtime(last_post_date_old);

-- drop the "old" column
alter table mytable drop column last_post_date_old;

You need downtime on the table to run this safely.

Note: the rename syntax is available in MySQL 8.0 only. In earlier versions, you need to use the more cumbersome change syntax, which requires redeclaring the datatype (the following assumes int):

alter table mytable change last_post_date last_post_date_old int;

Demo on DB Fiddle

Before:

| last_post_date |
| -------------: |
|     1591132456 |

After:

| last_post_date      |
| :------------------ |
| 2020-06-02 22:14:16 |


问:
Formik button not disabled initially
I am using Formik validation and I am trying to disable the button if the validation schema is not fulfilled. It's supposed to be a phone number so if I type alphabets, the button is disabled. It works.

However, initially when I open the screen and the text field is empty, the button should still be disabled. But it's not. Even though the validation schema says 'required'. How can I fix this?

```<code><Formik
              initialValues={initialValues}
              onSubmit={handleSubmitForm}
              validationSchema={validationSchema}>
              {({ handleChange, handleBlur, handleSubmit, values, isValid }) => (
                <View style={styles.searchFieldContainer}>
                  <View style={styles.form}>
                    <FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />
                    <ErrorMessage
                      name="phoneNumber"
                      render={(msg) => (
                        <Text style={styles.errorText}>{msg}</Text>
                      )}
                    />
                  </View>
                  <View style={styles.buttonContainer}>
                <Button
                  block
                  success
                  disabled={!isValid}
                  onPress={handleSubmit}
                  style={styles.button}>
                  <Text>Speichern</Text>
                </Button>
                  </View>
                </View>
              )}
            </Formik>
</code>```

```<code>const phoneNumberValidationSchema = yup.object().shape({
  phoneNumber: yup
    .string()
    .label('phoneNumber')
    .required('Bitte gebe deine Handynummer ein.')
    .matches(/^[0-9]*$/, 'Bitte nur Ziffern eingeben.'),
});
</code>```

答:
Try setting the isInitialValid prop on the Formik component to false.

<Formik
  initialValues={initialValues}
  onSubmit={handleSubmitForm}
  validationSchema={validationSchema}
  isInitialValid={false}
>
  ...
</Formik>
```

Title: Formik button not disabled initially

Body:
I am using Formik validation and I am trying to disable the button if the validation schema is not fulfilled. It's supposed to be a phone number so if I type alphabets, the button is disabled. It works.

However, initially when I open the screen and the text field is empty, the button should still be disabled. But it's not. Even though the validation schema says 'required'. How can I fix this?

<Formik
              initialValues={initialValues}
              onSubmit={handleSubmitForm}
              validationSchema={validationSchema}>
              {({ handleChange, handleBlur, handleSubmit, values, isValid }) => (
                <View style={styles.searchFieldContainer}>
                  <View style={styles.form}>
                    <FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />
                    <ErrorMessage
                      name="phoneNumber"
                      render={(msg) => (
                        <Text style={styles.errorText}>{msg}</Text>
                      )}
                    />
                  </View>
                  <View style={styles.buttonContainer}>
                <Button
                  block
                  success
                  disabled={!isValid}
                  onPress={handleSubmit}
                  style={styles.button}>
                  <Text>Speichern</Text>
                </Button>
                  </View>
                </View>
              )}
            </Formik>

const phoneNumberValidationSchema = yup.object().shape({
  phoneNumber: yup
    .string()
    .label('phoneNumber')
    .required('Bitte gebe deine Handynummer ein.')
    .matches(/^[0-9]*$/, 'Bitte nur Ziffern eingeben.'),
});


问:
What is the most efficient way to call a function on a 2D ndarray of coordinates?
I have a ndarray of size (M, N, 3). It holds M x N points, each of which is identified by its x, y, and z coordinates. I also have a function 'foo'. 'foo' takes in a point as a ndarray of size (, 3). Is there a faster way to call 'foo' on each of the M x N points in my array than to use two nested for loops?

So far, this is what I have tried. My array is the variable 'sample_array'.

```<code>num_rows = sample_array.shape[0]
num_columns = sample_array.shape[1]
solution = np.zeros((num_rows, num_columns))

for row in range(num_rows):
   for column in range(num_columns):
      point = sample_array[row, column]
      solution[row, column] = foo(point)
</code>```

I found this answer, which describes using these two solutions:

```<code>np.vectorize(foo)
np.array(map(foo, sample_array))
</code>```

However, I am not sure how to specify that I don't want the function mapped to every one of the M x N x 3 floats. Instead, I would like it to map the function to be called on each of the M x N (, 3) ndarrays.

Thank you!

答:
In fewer lines of code:</p>

```<code>solution = np.vectorize(foo)(*sample_array.reshape(-1, 3).T)
</code>```

Body:
I have a ndarray of size (M, N, 3). It holds M x N points, each of which is identified by its x, y, and z coordinates. I also have a function 'foo'. 'foo' takes in a point as a ndarray of size (, 3). Is there a faster way to call 'foo' on each of the M x N points in my array than to use two nested for loops?

So far, this is what I have tried. My array is the variable 'sample_array'.

num_rows = sample_array.shape[0]
num_columns = sample_array.shape[1]
solution = np.zeros((num_rows, num_columns))

for row in range(num_rows):
   for column in range(num_columns):
      point = sample_array[row, column]
      solution[row, column] = foo(point)

I found this answer, which describes using these two solutions:

np.vectorize(foo)
np.array(map(foo, sample_array))

However, I am not sure how to specify that I don't want the function mapped to every one of the M x N x 3 floats. Instead, I would like it to map the function to be called on each of the M x N (, 3) ndarrays.

Thank you!

Body:
In fewer lines of code:

solution = np.vectorize(foo)(*sample_array.reshape(-1, 3).T)


问:
Conditionally apply CSS classes in React
I know this has been answered but I couldn't figure out what is wrong with my code here. I'm trying to add a class based of the conditional field.

React Code:

```<code><div className="boards {task.IsClosed !== 0 ? 'complete' : ''}">
  <p>{task.TaskName}</p>
  <div>{task.IsClosed !== 0 ? <div>Completed</div> : null}</div>
</div>
</code>```

Output:

```<code><div class="boards {task.IsClosed !== 0 ? 'complete' : ''}">
  <p>Task 2</p>
  <div><div>Completed</div></div>
</div>
</code>```

I want the output to be

答:
<div className=`boards ${task.IsClosed !== 0 ? 'complete' : ''}`>

{task.TaskName}

{task.IsClosed !== 0 ?
Completed
 : null}

```

<p>I think you want this^^^</p>

<p>for string interpolation in javascript the ` character must be used for quotes and the expression being interpolated must be within ${}</p>

<p>...
or you can make a variable to store the class i.e.</p>

<pre class="lang-html prettyprint-override"><code>let className = task.IsClosed !== 0 ? 'complete' : '';
...
...
<div className={className}>
  <p>{task.TaskName}</p>
  <div>{task.IsClosed !== 0 ? <div>Completed</div> : null}</div>
</div>

</code>```

Body:
I know this has been answered but I couldn't figure out what is wrong with my code here. I'm trying to add a class based of the conditional field.

React Code:

{task.TaskName}

{task.IsClosed !== 0 ?
Completed
 : null}

Output:

Task 2

Completed

I want the output to be

Body:
<div className=`boards ${task.IsClosed !== 0 ? 'complete' : ''}`>
  <p>{task.TaskName}</p>
  <div>{task.IsClosed !== 0 ? <div>Completed</div> : null}</div>
</div>

I think you want this^^^

for string interpolation in javascript the ` character must be used for quotes and the expression being interpolated must be within ${}

...
or you can make a variable to store the class i.e.

let className = task.IsClosed !== 0 ? 'complete' : '';
...
...
<div className={className}>
  <p>{task.TaskName}</p>
  <div>{task.IsClosed !== 0 ? <div>Completed</div> : null}</div>
</div>


问:
convert Uint8Array into Uint16Array in NodeJs
I have an Uint8Array that i would like to convert into an Uint16Array so that each consecutive pair of element in the Uint8Array is converted in a Uint16 value. At the end, the uint16Array is thus half the size of the Uint8Array. I thus want to cast the whole array, not each values.

the only solution i found keeps the same lenght and change the underlying type of each element of the array. So it does not 'cast' the array but each element of the array, which is not what i want.

答:
If I understood correctly the question, the most native way coming to my mind (which still not is cast but requires a few lines) is converting to a Buffer, than converting it to a Uint16Array.

Following snippet seems to achieve the desired result.

```<code>const ar8 = new Uint8Array([0, 1, 1, 0, 0, 2, 2, 0]);
const buf = new Buffer(ar8);
const ar16 = new Uint16Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint16Array.BYTES_PER_ELEMENT);

console.log(ar8, buf, ar16);
</code>```

On my platform conversion is little endian; sorry but I don't know if conversion is little endian on all platforms or little/big endian conversion is platform dependent.

Body:
If I understood correctly the question, the most native way coming to my mind (which still not is cast but requires a few lines) is converting to a Buffer, than converting it to a Uint16Array.

Following snippet seems to achieve the desired result.

const ar8 = new Uint8Array([0, 1, 1, 0, 0, 2, 2, 0]);
const buf = new Buffer(ar8);
const ar16 = new Uint16Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint16Array.BYTES_PER_ELEMENT);

console.log(ar8, buf, ar16);

On my platform conversion is little endian; sorry but I don't know if conversion is little endian on all platforms or little/big endian conversion is platform dependent.


问:
Redraw Graph on Print Preview - Is Not a Function (Nested Vue Component)
I know I'm not accessing this function correct by the error, but I'm not sure how to debug this and determine the correct approach. Guidance is appreciated.

PerformanceDonut.vue is a component in Page.vue

PerformanceDonut.vue:

```<code>// ...
methods: {
    drawGraph() {
        this.chart = new CanvasJS.Chart(this.chartName, this.chartOptions);
        this.chart.render();
         console.log('Donut drawn')
    }
},
mounted() {
    this.drawGraph();
    // The function executes here

    // Redraw graph on print preview
    window.matchMedia('print').addListener(function(mql) {
        if (mql.matches) {
            this.drawGraph();
            // Error here
        }
    });
}
</code>```

Console Error:

```<code>Uncaught TypeError: this.drawGraph is not a function
</code>```

答:
Assign this to a global variable called vm and then access it in the callback since the execution context  is changed in the callback:

```<code>   mounted() {
            this.drawGraph();
            // The function executes here

            let vm=this;
            window.matchMedia('print').addListener(function(mql) {
                if (mql.matches) {
                    vm.drawGraph();

                }
            });

</code>```

Body:
I know I'm not accessing this function correct by the error, but I'm not sure how to debug this and determine the correct approach. Guidance is appreciated.

PerformanceDonut.vue is a component in Page.vue

PerformanceDonut.vue:

// ...
methods: {
    drawGraph() {
        this.chart = new CanvasJS.Chart(this.chartName, this.chartOptions);
        this.chart.render();
         console.log('Donut drawn')
    }
},
mounted() {
    this.drawGraph();
    // The function executes here

    // Redraw graph on print preview
    window.matchMedia('print').addListener(function(mql) {
        if (mql.matches) {
            this.drawGraph();
            // Error here
        }
    });
}

Console Error:

Uncaught TypeError: this.drawGraph is not a function

Body:
Assign this to a global variable called vm and then access it in the callback since the execution context  is changed in the callback:

   mounted() {
            this.drawGraph();
            // The function executes here

            let vm=this;
            window.matchMedia('print').addListener(function(mql) {
                if (mql.matches) {
                    vm.drawGraph();

                }
            });


问:
Leetcode 'NoneType' Object Has No Attribute 'Next'
I was working on this problem, and I was getting an error:

```<code>AttributeError: 'NoneType' object has no attribute 'next'
</code>```

Could someone help point me in the right direction?

```<code># Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:

        while (True):
            headA = headA.next      # advance '1' step in list_A {this is the error line}

            if (headA == headB):    # check for equality
                return headA

            headB = headB.next      # advance '1' step in list_B

</code>```

答: The error is obtained when you have reached the end of the linked list i.e. when headA is None.

Body:
I was working on this problem, and I was getting an error:

AttributeError: 'NoneType' object has no attribute 'next'

Could someone help point me in the right direction?

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:

        while (True):
            headA = headA.next      # advance '1' step in list_A {this is the error line}

            if (headA == headB):    # check for equality
                return headA

            headB = headB.next      # advance '1' step in list_B


问:
GO store value froom LOOP
```<code>package main

import "fmt"

func main() {
    var kata, kosong, kebalikan string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata)
    for i := panjang - 1; i >= 0; i-- {
        kebalikan := kosong + fmt.Print(string(kata[i]))
    }
    if kata == kebalikan {
        fmt.Println("\n", true)
    } else {
        fmt.Println("\n", false)
    }
}
</code>```

does anybody know how to store kosong + fmt.Print(string(kata[i])) to kebalikan ? just new in golang
the error is multiple-value fmt.Print() in single-value context

答:
There are two problems with your code.

You need to use fmt.Sprint instead of fmt.Print in your case. The former returns a string, the latter prints it to stdout.

Do not use : in kebalikan := kosong + fmt.Print(string(kata[i])). You do not want to create a new local variable, instead modify the existing variable.

Here is the fixed code:

```<code>package main

import "fmt"

func main() {
    var kata, kosong, kebalikan string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata)
    for i := panjang - 1; i >= 0; i-- {
        kebalikan = kosong + fmt.Sprint(string(kata[i]))
    }
    if kata == kebalikan {
        fmt.Println("\n", true)
    } else {
        fmt.Println("\n", false)
    }
}
</code>```

Title: GO store value froom LOOP

Body:
package main

import "fmt"

func main() {
    var kata, kosong, kebalikan string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata)
    for i := panjang - 1; i >= 0; i-- {
        kebalikan := kosong + fmt.Print(string(kata[i]))
    }
    if kata == kebalikan {
        fmt.Println("\n", true)
    } else {
        fmt.Println("\n", false)
    }
}

does anybody know how to store kosong + fmt.Print(string(kata[i])) to kebalikan ? just new in golang
the error is multiple-value fmt.Print() in single-value context

Body:
There are two problems with your code.

You need to use fmt.Sprint instead of fmt.Print in your case. The former returns a string, the latter prints it to stdout.

Do not use : in kebalikan := kosong + fmt.Print(string(kata[i])). You do not want to create a new local variable, instead modify the existing variable.

Here is the fixed code:

package main

import "fmt"

func main() {
    var kata, kosong, kebalikan string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata)
    for i := panjang - 1; i >= 0; i-- {
        kebalikan = kosong + fmt.Sprint(string(kata[i]))
    }
    if kata == kebalikan {
        fmt.Println("\n", true)
    } else {
        fmt.Println("\n", false)
    }
}


问:
Svelte wrapping each slot
I am looking to create a Spacer element in svelte. I have accomplished what I have set out to which is allow a user to wrap elements in a <Space></Space> tag and pass props to space them evenly vertically/horizontally or even align the interior elements center/start/end/baseline. The issue I have is that I have to wrap each child element to <Space></Space> with a <SpaceItem></SpaceItem> to get the desired effect. Here is the example code:

App.svelte

```<code><script>
    import {Space, SpaceItem} from './components/Space';
</script>

<Space>
    <SpaceItem>
        <Button primary>Primary</Button>
    </SpaceItem>
    <SpaceItem>
        <Button primary icon="add">Primary</Button>
    </SpaceItem>
    <SpaceItem>
        <Button danger>Danger</Button>
    </SpaceItem>
</Space>
</code>```

Space.svelte

```<code><script>
    import { SPACE } from './SpaceContext.svelte';
    import { setContext } from 'svelte';
    import { readable } from 'svelte/store';
    export let vertical = false;
    export let horizontal = true;
    export let alignCenter = false;
    export let alignStart = false;
    export let alignEnd = false;
    export let alignBaseline = false;
    export let large = false;
    export let middle = false;
    export let size = null;

    horizontal = vertical ? false : true;
    size = size ? size : large ? 24 : middle ? 16 : 8;

    const gap = readable(size);
    const direction = readable(horizontal ? 'horizontal' : 'vertical');

    setContext(SPACE, {
        gap,
        direction,
    });
</script>

<style>
    .space {
        display: -webkit-inline-box;
        display: -ms-inline-flexbox;
        display: inline-flex;
    }
    .vertical {
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
        -ms-flex-direction: column;
        flex-direction: column;
    }
    .align-center {
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
    }
    .align-start {
        -webkit-box-align: start;
        -ms-flex-align: start;
        align-items: flex-start;
    }
    .align-end {
        -webkit-box-align: end;
        -ms-flex-align: end;
        align-items: flex-end;
    }
    .align-baseline {
        -webkit-box-align: baseline;
        -ms-flex-align: baseline;
        align-items: baseline;
    }
</style>

<div
    class="space"
    class:horizontal
    class:vertical
    class:size
    class:align-center={alignCenter}
    class:align-start={alignStart}
    class:align-end={alignEnd}
    class:align-baseline={alignBaseline}>
    <slot />
</div>
</code>```

SpaceItem

```<code><script>
    import { SPACE } from './SpaceContext.svelte';
    import { getContext } from 'svelte';
    const { gap, direction } = getContext(SPACE);

    let style;
    if ($direction === 'horizontal') {
        style = `margin-right: ${$gap}px;`;
    } else {
        style = `margin-bottom: ${$gap}px;`;
    }
</script>

<style>

</style>

<div class="item" {style}>
    <slot />
</div>
</code>```

Is there a way to eliminate the <SpaceItem></SpaceItem> element and for <Space></Space> to wrap each element passed to its <slot /> with the <SpaceItem></SpaceItem>? I would like to only have to wrap all elements in one Space tag and not wrap each individual one in a SpaceItem tag.

Desired effect is for me to be able to write:

App.svelte

```<code><script>
    import {Space, SpaceItem} from './components/Space';
</script>

<Space>
    <Button primary>Primary</Button>
    <Button primary icon="add">Primary</Button>
    <Button danger>Danger</Button>
</Space>
</code>```

And still wrap each button with <SpaceItem></SpaceItem> within the Space.svelte file.

答:
Here is a solution that I have worked out on my own but I am not sure if this will have any performance issues in a real world application so comments are welcome.

App.svelte

```<code><script>
  import Space from './Space.svelte';
  import Button from './Button.svelte';
</script>

<Space>
  <Button primary>Primary</Button>
  <Button primary icon="add">Primary</Button>
  <Button danger>Danger</Button>
</Space>

<Space vertical large alignCenter>
  <Button primary icon="add">Primary</Button>
  <Button danger>Danger</Button>
</Space>
</code>```

Space.svelte

```<code><script>
  import { onMount } from 'svelte';
  import addWrapper from './utils/addWrapper';
  export let vertical = false;
  export let horizontal = true;
  export let alignCenter = false;
  export let alignStart = false;
  export let alignEnd = false;
  export let alignBaseline = false;
  export let large = false;
  export let middle = false;
  export let size = null;

  horizontal = vertical ? false : true;
  size = size ? size : large ? 24 : middle ? 16 : 8;

  const gap = size;
  const direction = horizontal ? 'horizontal' : 'vertical';
  let style;

  if (direction === 'horizontal') {
    style = `margin-right: ${gap}px;`;
  } else {
    style = `margin-bottom: ${gap}px;`;
  }
  let currentEl;

  onMount(async () => {
    addWrapper({
      node: currentEl,
      tag: 'div',
      style,
    });
  });
</script>

<style>
  .space {
    display: -webkit-inline-box;
    display: -ms-inline-flexbox;
    display: inline-flex;
  }
  .vertical {
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
  }
  .align-center {
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .align-start {
    -webkit-box-align: start;
    -ms-flex-align: start;
    align-items: flex-start;
  }
  .align-end {
    -webkit-box-align: end;
    -ms-flex-align: end;
    align-items: flex-end;
  }
  .align-baseline {
    -webkit-box-align: baseline;
    -ms-flex-align: baseline;
    align-items: baseline;
  }
</style>

<div
  bind:this={currentEl}
  class="space"
  class:horizontal
  class:vertical
  class:align-center={alignCenter}
  class:align-start={alignStart}
  class:align-end={alignEnd}
  class:align-baseline={alignBaseline}
>
  <slot />
</div>
</code>```

addWrapper.js

```<code>export default async function addWrapper({ node, tag, style }) {
  const children = node.childNodes;
  [].forEach.call(children, function (child) {
    if (child.nodeName !== "#text" && child.nodeName !== "#comment") {
      let wrapper = document.createElement(tag);
      wrapper.setAttribute("style", style);
      child.parentNode.insertBefore(wrapper, child);
      wrapper.appendChild(child);
    }
  });
}
</code>```

Like is said this works and eliminates the need for creating individual wrappers for simple situations but more complex wrappers would require re-working. If anyone has a better suggestion that is simpler and more performant I am all ears.

Title: Svelte wrapping each slot

Body:
I am looking to create a Spacer element in svelte. I have accomplished what I have set out to which is allow a user to wrap elements in a <Space></Space> tag and pass props to space them evenly vertically/horizontally or even align the interior elements center/start/end/baseline. The issue I have is that I have to wrap each child element to <Space></Space> with a <SpaceItem></SpaceItem> to get the desired effect. Here is the example code:

App.svelte

<Space>
    <SpaceItem>
        <Button primary>Primary</Button>
    </SpaceItem>
    <SpaceItem>
        <Button primary icon="add">Primary</Button>
    </SpaceItem>
    <SpaceItem>
        <Button danger>Danger</Button>
    </SpaceItem>
</Space>

Space.svelte

    <slot />

SpaceItem

    <slot />

Is there a way to eliminate the <SpaceItem></SpaceItem> element and for <Space></Space> to wrap each element passed to its <slot /> with the <SpaceItem></SpaceItem>? I would like to only have to wrap all elements in one Space tag and not wrap each individual one in a SpaceItem tag.

Desired effect is for me to be able to write:

App.svelte

<Space>
    <Button primary>Primary</Button>
    <Button primary icon="add">Primary</Button>
    <Button danger>Danger</Button>
</Space>

And still wrap each button with <SpaceItem></SpaceItem> within the Space.svelte file.

Body:
Here is a solution that I have worked out on my own but I am not sure if this will have any performance issues in a real world application so comments are welcome.

App.svelte

<script>
  import Space from './Space.svelte';
  import Button from './Button.svelte';
</script>

<Space>
  <Button primary>Primary</Button>
  <Button primary icon="add">Primary</Button>
  <Button danger>Danger</Button>
</Space>

<Space vertical large alignCenter>
  <Button primary icon="add">Primary</Button>
  <Button danger>Danger</Button>
</Space>

Space.svelte

<script>
  import { onMount } from 'svelte';
  import addWrapper from './utils/addWrapper';
  export let vertical = false;
  export let horizontal = true;
  export let alignCenter = false;
  export let alignStart = false;
  export let alignEnd = false;
  export let alignBaseline = false;
  export let large = false;
  export let middle = false;
  export let size = null;

  horizontal = vertical ? false : true;
  size = size ? size : large ? 24 : middle ? 16 : 8;

  const gap = size;
  const direction = horizontal ? 'horizontal' : 'vertical';
  let style;

  if (direction === 'horizontal') {
    style = `margin-right: ${gap}px;`;
  } else {
    style = `margin-bottom: ${gap}px;`;
  }
  let currentEl;

  onMount(async () => {
    addWrapper({
      node: currentEl,
      tag: 'div',
      style,
    });
  });
</script>

<style>
  .space {
    display: -webkit-inline-box;
    display: -ms-inline-flexbox;
    display: inline-flex;
  }
  .vertical {
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
  }
  .align-center {
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .align-start {
    -webkit-box-align: start;
    -ms-flex-align: start;
    align-items: flex-start;
  }
  .align-end {
    -webkit-box-align: end;
    -ms-flex-align: end;
    align-items: flex-end;
  }
  .align-baseline {
    -webkit-box-align: baseline;
    -ms-flex-align: baseline;
    align-items: baseline;
  }
</style>

<div
  bind:this={currentEl}
  class="space"
  class:horizontal
  class:vertical
  class:align-center={alignCenter}
  class:align-start={alignStart}
  class:align-end={alignEnd}
  class:align-baseline={alignBaseline}
>
  <slot />
</div>

addWrapper.js

export default async function addWrapper({ node, tag, style }) {
  const children = node.childNodes;
  [].forEach.call(children, function (child) {
    if (child.nodeName !== "#text" && child.nodeName !== "#comment") {
      let wrapper = document.createElement(tag);
      wrapper.setAttribute("style", style);
      child.parentNode.insertBefore(wrapper, child);
      wrapper.appendChild(child);
    }
  });
}

Like is said this works and eliminates the need for creating individual wrappers for simple situations but more complex wrappers would require re-working. If anyone has a better suggestion that is simpler and more performant I am all ears.


问:
JqGrid Primary Key other than Id
Can any Body tell me how to configure primary key in JqGrid. Since Jqgrid uses id as primary key But I am using fid as primary key.

Example of Jqgrid:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>PHP jqGrid</title>

        <link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.8.2.custom.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

        <script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>
        <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
        <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            // Here we set a globally the altRows option
            //jQuery.extend(jQuery.jgrid.defaults, { altRows:true });
        </script>
        <script type="text/javascript">

            jQuery(document).ready(function(){
                jQuery("#jsonmap").jqGrid({
                    url:'example.php?q=4',
                    datatype: "json",
                    colNames:['FId','Id', 'Colname', 'Index','width','Form Name','Fiel Name','Editable','Show','Extra Field'],
                    colModel:[
                        {name:'fid',index:'fid', width:55,size:10,editable:false},
                        {name:'id',index:'id', width:90,editable:true,size:5}, /*name : database field name*/
                        {name:'col_name',index:'col_name', width:100,editable:true},
                        {name:'ind_ex',index:'ind_ex', width:80, align:"right",editable:true},
                        {name:'width',index:'width', width:80, align:"right",editable:true},
                        {name:'form_name',index:'form_name', width:80, align:"right",editable:true},
                        {name:'field_name',index:'field_name', width:80,align:"right",editable:true},
                        {name:'editable',index:'editable', width:150, sortable:false,editable:true},
                        {name:'s_how',index:'s_how', width:150, sortable:false,editable:true},
                        {name:'extra_field',index:'extra_field', width:150, sortable:false,editable:true}
                 /*{name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10}},
        {name:'invdate',index:'invdate', width:80,editable:true,editoptions:{size:10}},
        {name:'name',index:'name', width:90,editable:true,editoptions:{size:25}},
        {name:'amount',index:'amount', width:60, align:"right",editable:true,editoptions:{size:10}},
        {name:'tax',index:'tax', width:60, align:"right",editable:true,editoptions:{size:10}},
        {name:'total',index:'total', width:60,align:"right",editable:true,editoptions:{size:10}},
        {name:'closed',index:'closed',width:55,align:'center',editable:true,edittype:"checkbox",editoptions:{value:"Yes:No"}},
        {name:'ship_via',index:'ship_via',width:70, editable: true,edittype:"select",editoptions:{value:"FE:FedEx;TN:TNT"}},
        {name:'note',index:'note', width:100, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"20"}}
                   */ ],
                    rowNum:10,
                    rowList:[10,20,30],
                    pager: '#pjmap',
                    sortname: 'id',
                    viewrecords: true,
                    sortorder: "desc",
                    gridview: true,
                    editurl:'edit.php',
                    closeAfterEdit: true,
                    closeAfterAdd: true,
                   jsonReader: {
                  //     root: "Rows",
                //page: "Page",
                //total: "Total",
                //records: "Records",
                repeatitems: false,
                 **fid: "PrimaryKey"**
                        //repeatitems : false,
                        //id: "5"

                    },
                    caption: "ADD DELETE UPDATE",
                    height: '100%'
                }).navGrid('#pager',{edit:false,add:true,del:true,search:false}).navButtonAdd('#pjmap',{
                    caption:"Add",
                    buttonicon:"ui-icon-add",
                    closeAfterAdd:true,
                    onClickButton: function(){
                       jQuery("#jsonmap").editGridRow("new",{height:400,scroll:true,reloadAfterSubmit:false});
                        //alert("Adding Row");
                    },
                    position:"last"
                })

               /* .navButtonAdd('#pjmap',{

                    caption:"Del",
                    buttonicon:"ui-icon-del",
                    onClickButton: function(rp_ge,postdata){
                        alert(getRowData(postdata.id));

                    },
                    position:"last"
                });
                */
            });

        </script>
    </head>
    <body>
        <table id="jsonmap"></table>
        <div id="pjmap"></div>
<!--<input type="BUTTON" id="bedata" value="Edit Selected" />-->
    </body>
</html>

server2.php
<?php
include_once('../../../../wp-load.php');
include('dbconfig.php');
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$result = @mysql_query("SELECT COUNT(*) AS count FROM $table");
$row = @mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if ( $count >0 )
   { $total_pages = ceil($count/1); }
else
   { $total_pages = 0; }
if ($page > $total_pages)
  $page=$total_pages;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
$SQL = "SELECT * from $table Order By id ";
$SQL = "SELECT * from $table";
$result = @mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());
$responce->page = $page; $responce->total = $total_pages; $responce->records = $count; $i=0;
while($row = @mysql_fetch_array($result,MYSQL_ASSOC))
{
$responce->rows[$i]['id']=$row[id];
$responce->rows[$i]['cell']=array($row[id],$row[business_name],$row[title],$row[firstname],$row[lastname],$row[address],$row[city],$row[state],$row[postcode],$row[email]);
$i++;
}
echo json_encode($responce);
?>
</code>```

答:
You can either use

```<code>jsonReader: {repeatitems: false, id: "fid" }
</code>```

or use

```<code>jsonReader: {repeatitems: false }
</code>```

and define additional key:true property for the 'fid' column definition:

```<code>{ name:'fid', index:'fid', key:true, width:55 }
</code>```

The key:true property overwrite id property of jsonReader.

One more remark: If you want use closeAfterEdit: true and closeAfterAdd: true setings of form editing you should define there on another place: as a part of navGrid parameters:

```<code>jQuery("#jsonmap").jqGrid({
    // ... jqGrid parameters
}).navGrid('#pager',
           {/*navGrid options*/},
           {closeAfterEdit: true}, // Edit form options
           {closeAfterAdd: true}   // Add form options
           )
  .navButtonAdd('#pjmap',{
                // navButtonAdd options
            })
</code>```

ContentLicense: CC BY-SA 3.0

Title: JqGrid Primary Key other than Id

Body:
Can any Body tell me how to configure primary key in JqGrid. Since Jqgrid uses id as primary key But I am using fid as primary key.

Example of Jqgrid:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>PHP jqGrid</title>

        <link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.8.2.custom.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

server2.php
<?php
include_once('../../../../wp-load.php');
include('dbconfig.php');
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$result = @mysql_query("SELECT COUNT(*) AS count FROM $table");
$row = @mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if ( $count >0 )
   { $total_pages = ceil($count/1); }
else
   { $total_pages = 0; }
if ($page > $total_pages)
  $page=$total_pages;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
$SQL = "SELECT * from $table Order By id ";
$SQL = "SELECT * from $table";
$result = @mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());
$responce->page = $page; $responce->total = $total_pages; $responce->records = $count; $i=0;
while($row = @mysql_fetch_array($result,MYSQL_ASSOC))
{
$responce->rows[$i]['id']=$row[id];
$responce->rows[$i]['cell']=array($row[id],$row[business_name],$row[title],$row[firstname],$row[lastname],$row[address],$row[city],$row[state],$row[postcode],$row[email]);
$i++;
}
echo json_encode($responce);
?>

Body:
You can either use

jsonReader: {repeatitems: false, id: "fid" }

or use

jsonReader: {repeatitems: false }

and define additional key:true property for the 'fid' column definition:

{ name:'fid', index:'fid', key:true, width:55 }

The key:true property overwrite id property of jsonReader.

One more remark: If you want use closeAfterEdit: true and closeAfterAdd: true setings of form editing you should define there on another place: as a part of navGrid parameters:

jQuery("#jsonmap").jqGrid({
    // ... jqGrid parameters
}).navGrid('#pager',
           {/*navGrid options*/},
           {closeAfterEdit: true}, // Edit form options
           {closeAfterAdd: true}   // Add form options
           )
  .navButtonAdd('#pjmap',{
                // navButtonAdd options
            })


问:
python appending dictionaries to lists causes keyError
I am trying to make a list that adds dictionaries to it.
I have done this many times but can't seem to find out why this happens. It should add the dictionary to the list and continue to the code but returns the error KeyError: '"id"'

Here is my code
raid_damage.append("""{"id":{}, "damage":{}, "taken":{}, "streak":{}}""".format(str(user), str(damage_dealt), str(damage_taken), "1"))

I have tried using ' in place of " (whilst removing the triple quotes) and using eval() but still the exact same error

Any Ideas?

答:
As you have curly brackets inside your string, when you're using format() you get an error because the {} are the special char to input the values given in parameter, the solution is to double them

```<code>raid_damage.append("""{{"id":{}, "damage":{}, "taken":{}, "streak":{}}}""".format(str(user), str(damage_dealt), str(damage_taken), "1"))
print(raid_damage[0]) # {"id":a, "damage":b, "taken":c, "streak":1}
</code>```

But careful, you did not add a dict but just a string representation of a dict, puttinh a dict would be like

```<code>raid_damage.append({"id":user, "damage":damage_dealt, "taken":damage_taken, "streak":"1"})
print(raid_damage[0]) # {'id': 'a', 'damage': 'b', 'taken': 'c', 'streak': '1'}
</code>```

Body:
As you have curly brackets inside your string, when you're using format() you get an error because the {} are the special char to input the values given in parameter, the solution is to double them

raid_damage.append("""{{"id":{}, "damage":{}, "taken":{}, "streak":{}}}""".format(str(user), str(damage_dealt), str(damage_taken), "1"))
print(raid_damage[0]) # {"id":a, "damage":b, "taken":c, "streak":1}

But careful, you did not add a dict but just a string representation of a dict, puttinh a dict would be like

raid_damage.append({"id":user, "damage":damage_dealt, "taken":damage_taken, "streak":"1"})
print(raid_damage[0]) # {'id': 'a', 'damage': 'b', 'taken': 'c', 'streak': '1'}


问:
Is there anyway to train doc2vec model in multiples batches
i don't know how to train model in multiples batches with doc2vec . Since i load all my data in ram and it't can not be loaded </p>

```<code>#Import all the dependencies
from gensim.models.doc2vec import Doc2Vec, TaggedDocument

import nltk
nltk.download('punkt')

from nltk.tokenize import word_tokenize
#import ReadExeFileCapstone
import update-doc2vec
mapData = ReadExeFileCapstone.readData()

# print ('mapData', mapData)

max_epochs = 10000
vec_size = 200
alpha = 0.025

model = Doc2Vec(size=vec_size,
                alpha=alpha,
                min_alpha=0.00025,
                min_count=1,
                dm =1)
data = []
for key in mapData:
    listData = mapData[key]
    # print ("listData: ", len(listData), listData)

    for i in range(len(listData)):
        listToStr = ' '.join([str(elem) for elem in listData[i]]) #convert array to list string
        data.append(listToStr)

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]

model.build_vocab(tagged_data)
#build vocab
for epoch in range(max_epochs):
    print('iteration {0}'.format(epoch))
    model.train(tagged_data,
                total_examples=model.corpus_count,
                epochs=model.iter)
    # decrease the learning rate
    model.alpha -= 0.0002
    # fix the learning rate, no decay
    model.min_alpha = model.alpha
# train model
model.save("d2v_ASM.model")
print("Model Saved")
</code>```

答:
Doc2Vec (& similar model classes in gensim) don't require the full training data to be a list-in-memory. They will accept a Python 'iterable' object, which simply provides items one-at-a-time, repeatedly.

Such an iterable object can stream items from some other source, like a large file on disk – even a file that's far larger than available RAM.

It's not clear what your ReadExeFileCapstone utility class is doing. (There are no web hits for code with this name.) But, it can likely be changed to itself return an iterable object that, every time it is iterated over, returns each text, one-at-a-time, from the original data source. You can then wrap that in your code for creating the necessary TaggedDocument objects, again as an iterable rather than a full-list-in-memory.

A reasonable intro to this technique is available at:

https://rare-technologies.com/data-streaming-in-python-generators-iterators-iterables/

Separately:

10000 epochs is an absurdly large count compared to published work, which usually uses 10-20 epochs, sometimes more for very small datasets.  (But, such small datasets are less likely to get good results from Doc2Vec-like algorithms, which need lots of varied data. However, if you're having memory problems, your dataset is probably not tiny.)

Don't call train() multiple times in a loop where you hand-tamper with the alpha value. This is unnecessarily and error prone – and in fact your current code is erroneous, because subtracting 0.0002 from your 0.025 starting-alpha thousands of times will drive alpha negative, a nonsensical & destructive value. Call train() once with your desired number of epochs - it will do the right thing. And it's rare to need to tune the default alpha values at all.

If you want more progress output – or just to better understand what's happening at each step – enable logging at the INFO level.

Body:
i don't know how to train model in multiples batches with doc2vec . Since i load all my data in ram and it't can not be loaded

#Import all the dependencies
from gensim.models.doc2vec import Doc2Vec, TaggedDocument

import nltk
nltk.download('punkt')

from nltk.tokenize import word_tokenize
#import ReadExeFileCapstone
import update-doc2vec
mapData = ReadExeFileCapstone.readData()

# print ('mapData', mapData)

max_epochs = 10000
vec_size = 200
alpha = 0.025

model = Doc2Vec(size=vec_size,
                alpha=alpha,
                min_alpha=0.00025,
                min_count=1,
                dm =1)
data = []
for key in mapData:
    listData = mapData[key]
    # print ("listData: ", len(listData), listData)

    for i in range(len(listData)):
        listToStr = ' '.join([str(elem) for elem in listData[i]]) #convert array to list string
        data.append(listToStr)

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]

model.build_vocab(tagged_data)
#build vocab
for epoch in range(max_epochs):
    print('iteration {0}'.format(epoch))
    model.train(tagged_data,
                total_examples=model.corpus_count,
                epochs=model.iter)
    # decrease the learning rate
    model.alpha -= 0.0002
    # fix the learning rate, no decay
    model.min_alpha = model.alpha
# train model
model.save("d2v_ASM.model")
print("Model Saved")


问:
How to exclude lines matching a regex pattern in a column by awk?
I want to exclude lines containing a specific string.

```<code>header
1:test
2:test
3:none
4:test
</code>```

Why don't these commands work?

```<code>awk -F: 'FNR>1 {$0 !~ /none/} {print $1}' 1.txt
awk -F: 'FNR>1 {$2 !~ /none/} {print $1}' 1.txt
</code>```

but this works:

```<code>awk '$0 !~ /none/ {print $0}' 1.txt
</code>```

I intend to get

```<code>1
2
4
</code>```

答:
You need to provide the regex test as condition, not as action, and may use

```<code>awk -F: 'FNR>1 && !/none/{print $1}' file
awk -F: 'FNR>1 && $2 !~ /none/{print $1}' file
</code>```

See an awk online demo

Details

-F: - sets the field separator to a colon

FNR>1 && !/none/ - if number of processed records for current file is more than 1 and there is no none on the line (if $2 !~ /none/ is used, returns true if Field 2 does not contain none pattern)

{print $1} - print Field 1 value.

Body:
I want to exclude lines containing a specific string.

header
1:test
2:test
3:none
4:test

Why don't these commands work?

awk -F: 'FNR>1 {$0 !~ /none/} {print $1}' 1.txt
awk -F: 'FNR>1 {$2 !~ /none/} {print $1}' 1.txt

but this works:

awk '$0 !~ /none/ {print $0}' 1.txt

I intend to get

1
2
4

Body:
You need to provide the regex test as condition, not as action, and may use

awk -F: 'FNR>1 && !/none/{print $1}' file
awk -F: 'FNR>1 && $2 !~ /none/{print $1}' file

See an awk online demo

Details

-F: - sets the field separator to a colon

FNR>1 && !/none/ - if number of processed records for current file is more than 1 and there is no none on the line (if $2 !~ /none/ is used, returns true if Field 2 does not contain none pattern)

{print $1} - print Field 1 value.


问:
How to group by key and retrieve keys from the grouped elements?
I'm trying to group and sum dicts from a DataFrame like this:

```<code>dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pandas.DataFrame(dt).groupby('is_cumulative')
result = df.sum()
</code>```

The result is:

```<code>               discount_value
is_cumulative
False                      10
True                       20
</code>```

But i need to get all "code" key used to sum the final resultt, e.g:

```<code>result['discount_value'][True]  # 20
# how to get the codes "x" and "x1"?
</code>```

答:
I would do a little differently:

```<code>dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pd.DataFrame(dt)                         # here
result = df.groupby('is_cumulative').sum()    # and here

# get the code
df.loc[df.is_cumulative, 'code']
</code>```

Output:

```<code>0     x
1    x1
Name: code, dtype: object
</code>```

Body:
I'm trying to group and sum dicts from a DataFrame like this:

dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pandas.DataFrame(dt).groupby('is_cumulative')
result = df.sum()

The result is:

               discount_value
is_cumulative
False                      10
True                       20

But i need to get all "code" key used to sum the final resultt, e.g:

result['discount_value'][True]  # 20
# how to get the codes "x" and "x1"?

Body:
I would do a little differently:

dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pd.DataFrame(dt)                         # here
result = df.groupby('is_cumulative').sum()    # and here

# get the code
df.loc[df.is_cumulative, 'code']

Output:

0     x
1    x1
Name: code, dtype: object


问:
Checking Duplicate Records in Table Where Id is Identity
In my table, ID is primary key field and identity column.
I want to check duplicate records.
(Certainly duplicate records do not have same ID)

And do not have date fields same.

How do I check this.

Extra Detail: I have 10 columns with 1 ID, 2 Date, and other 3 string, 3 Int, 1 bit.

Thansk in Advance.

答:
A generalized approach would be as follows. hope this helps you.</p>

```<code>SELECT COL1, COL2, ..., COLn, COUNT(*)
FROM TABLE1
GROUP BY COL1,COL2, .., COLn
HAVING COUNT(*) > 1
</code>```

Body:
A generalized approach would be as follows. hope this helps you.

SELECT COL1, COL2, ..., COLn, COUNT(*)
FROM TABLE1
GROUP BY COL1,COL2, .., COLn
HAVING COUNT(*) > 1


答:
You can use an arrow function in order to work this as reference of Vue component:

window.matchMedia('print').addListener( mql => {
    if (mql.matches) {
        this.drawGraph();
    }
});
```

Title: Redraw Graph on Print Preview - Is Not a Function (Nested Vue Component)


问:
How to make the complement and difference operation between two sets in CLIPS?
I need to make complement and difference operations between two sets. I've a example, to do union between two sets, I can reuse this code to make these two other operations.

Thanks

答:
The union example, that I've is:

```<code>(deffacts datos-iniciales
(conjunto B C A D E E B C E)
(conjunto E E B F D E))

(defrule inicio
=>
(assert (union)))
(defrule union
?h <- (union $?u)
(conjunto ? $? ?e $?)
(not (union $? ?e $?))
=>
(retract ?h)
(assert (union ?e $?u)))

</code>```

Specifically, which part of the program should be changed? Thx

Body:
The union example, that I've is:

(deffacts datos-iniciales
(conjunto B C A D E E B C E)
(conjunto E E B F D E))

(defrule inicio
=>
(assert (union)))
(defrule union
?h <- (union $?u)
(conjunto ? $? ?e $?)
(not (union $? ?e $?))
=>
(retract ?h)
(assert (union ?e $?u)))

Specifically, which part of the program should be changed? Thx


问:
How to display Firebase Auth user profile image in SwiftUI?
I do this, but give me this error --> Cannot convert value of type 'URL' to expected argument type 'String'

  var profilePic = URL(string: Auth.auth().currentUser?.photoURL as Any as! String) as Any as! URL

  var body : some View {
    VStack {
      Image(self.profilePic)
    }
  }
```

How can I display the user's profile image?

答:
SwiftUI's Image view is unable to load remote images from the network.  The standard practice would be to install SDWebImageSwiftUI using a dependency manager like CocoaPods.  The following would then work effectively:

```<code>import SwiftUI
import SDWebImageSwiftUI
import FirebaseAuth

struct ProfilePicView: View {
     var body: some View {
         WebImage(url: Auth.auth().currentUser?.photoURL)
     }
}
</code>```

You can then apply the same modifiers to WebImage as you would image, and it handles all of your networking for you.

Body:
I do this, but give me this error --> Cannot convert value of type 'URL' to expected argument type 'String'

  var profilePic = URL(string: Auth.auth().currentUser?.photoURL as Any as! String) as Any as! URL

  var body : some View {
    VStack {
      Image(self.profilePic)
    }
  }

How can I display the user's profile image?

Body:
SwiftUI's Image view is unable to load remote images from the network.  The standard practice would be to install SDWebImageSwiftUI using a dependency manager like CocoaPods.  The following would then work effectively:

import SwiftUI
import SDWebImageSwiftUI
import FirebaseAuth

struct ProfilePicView: View {
     var body: some View {
         WebImage(url: Auth.auth().currentUser?.photoURL)
     }
}

You can then apply the same modifiers to WebImage as you would image, and it handles all of your networking for you.


答:
Here is what you want:

import pandas
dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pandas.DataFrame(dt).groupby('is_cumulative')
result = df.agg({'discount_value':sum, 'code':list})
print(result)
```

<p>The output:</p>

```               discount_value     code
is_cumulative
False                      10     [x2]
True                       20  [x, x1]
```

Title: How to group by key and retrieve keys from the grouped elements?

Body:
Here is what you want:

import pandas
dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pandas.DataFrame(dt).groupby('is_cumulative')
result = df.agg({'discount_value':sum, 'code':list})
print(result)

The output:

               discount_value     code
is_cumulative
False                      10     [x2]
True                       20  [x, x1]


问:
interstitial ad (plugin: admob-free)
My interest is relatively very basic. All I wanted an interstitial banner shows up in some pages of my hybrid application. I indeed appreciate your any comments and guidance since I am a novice developer, a hobbyist only.

I use Adobe PhoneGap build web interface and my "config.xml" is successful to build my apk which works charm.

```<code> <preference name="android-build-tool" value="gradle" />
 <preference name="phonegap-version" value="cli-7.1.0" />
 <plugin name="cordova-plugin-admob-free">
    <variable name="ADMOB_APP_ID" value="ca-app-pub-1122334455667788~12345" />
 </plugin>
</code>```

My app is an HTML5 uses Jquery as well.
The index.html page calls following JS files.

```<code><script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</code>```

There is no cordova.js as the phonegap injects during its build, My "js/index.js" file as follows,

```<code>var admobid = {}
if (/(android)/i.test(navigator.userAgent)) {  // for android & amazon-fireos
  admobid = {
    banner: 'ca-app-pub-1122334455667788/12345',
    interstitial: 'ca-app-pub-1122334455667788/12345',
  }
} else if (/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {  // for ios
  admobid = {
    banner: 'ca-app-pub-1122334455667788/12345',
    interstitial: 'ca-app-pub-1122334455667788/12345',
  }
}

document.addEventListener('deviceready', function() {
  admob.banner.config({
    id: admobid.banner,
    isTesting: true,
    autoShow: true,
  })
  admob.banner.prepare()

  admob.interstitial.config({
    id: admobid.interstitial,
    isTesting: true,
    autoShow: true,
  })
  admob.interstitial.prepare()

  document.getElementById('showAd').disabled = true
  document.getElementById('showAd').onclick = function() {
    admob.interstitial.show()
  }

}, false)

document.addEventListener('admob.banner.events.LOAD_FAIL', function(event) {
  console.log(event)
})

document.addEventListener('admob.interstitial.events.LOAD_FAIL', function(event) {
  console.log(event)
})

document.addEventListener('admob.interstitial.events.LOAD', function(event) {
  console.log(event)
  document.getElementById('showAd').disabled = false
})

document.addEventListener('admob.interstitial.events.CLOSE', function(event) {
  console.log(event)

  admob.interstitial.prepare()
})
</code>```

I build the app successfully but interstitial ads does not appear. (ps. banner does not appear either)

Could you please help me to figure this out? Huge thanks to all of you!

答:
since you are trying to display your ad in testing mode remove

```<code>id: admobid.interstitial
</code>```

and

```<code>id: admobid.banner
</code>```

Title: interstitial ad (plugin: admob-free)

Body:
My interest is relatively very basic. All I wanted an interstitial banner shows up in some pages of my hybrid application. I indeed appreciate your any comments and guidance since I am a novice developer, a hobbyist only.

I use Adobe PhoneGap build web interface and my "config.xml" is successful to build my apk which works charm.

 <preference name="android-build-tool" value="gradle" />
 <preference name="phonegap-version" value="cli-7.1.0" />
 <plugin name="cordova-plugin-admob-free">
    <variable name="ADMOB_APP_ID" value="ca-app-pub-1122334455667788~12345" />
 </plugin>

My app is an HTML5 uses Jquery as well.
The index.html page calls following JS files.

There is no cordova.js as the phonegap injects during its build, My "js/index.js" file as follows,

var admobid = {}
if (/(android)/i.test(navigator.userAgent)) {  // for android & amazon-fireos
  admobid = {
    banner: 'ca-app-pub-1122334455667788/12345',
    interstitial: 'ca-app-pub-1122334455667788/12345',
  }
} else if (/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {  // for ios
  admobid = {
    banner: 'ca-app-pub-1122334455667788/12345',
    interstitial: 'ca-app-pub-1122334455667788/12345',
  }
}

document.addEventListener('deviceready', function() {
  admob.banner.config({
    id: admobid.banner,
    isTesting: true,
    autoShow: true,
  })
  admob.banner.prepare()

  admob.interstitial.config({
    id: admobid.interstitial,
    isTesting: true,
    autoShow: true,
  })
  admob.interstitial.prepare()

  document.getElementById('showAd').disabled = true
  document.getElementById('showAd').onclick = function() {
    admob.interstitial.show()
  }

}, false)

document.addEventListener('admob.banner.events.LOAD_FAIL', function(event) {
  console.log(event)
})

document.addEventListener('admob.interstitial.events.LOAD_FAIL', function(event) {
  console.log(event)
})

document.addEventListener('admob.interstitial.events.LOAD', function(event) {
  console.log(event)
  document.getElementById('showAd').disabled = false
})

document.addEventListener('admob.interstitial.events.CLOSE', function(event) {
  console.log(event)

  admob.interstitial.prepare()
})

I build the app successfully but interstitial ads does not appear. (ps. banner does not appear either)

Could you please help me to figure this out? Huge thanks to all of you!

Body:
since you are trying to display your ad in testing mode remove

id: admobid.interstitial

and

id: admobid.banner


问:
How to write KTable in a Kafka topic? Like we use "to()" in KStreams how to do that for KTable?
As there is no "to()" method for KTable so do we need to always convert it to KStream before sending any message to a topic?
Or how can we store a KTable in our topic? </p>

答: Yes, in order to materialize a KTable to a topic, you're required to convert it to a regular stream (instead of a changelog stream) via table.toStream().to("myTopic").


问:
Delete newer duplicate value based on two columns .NET Core
I have huge transactions table in azure database, where we import files with +1 million objects.

public class Transaction
    {
        [Key]
        public int Id { get; set; }
        public int TransactionId { get; set; }
        public DateTime Date { get; set; }
        public decimal Price { get; set; }
        public int UserId { get; set; }
        public string Product { get; set; }
        public int ClientId { get; set; }
        public int Uploaed { get; set; }
        public string UniqueId { get; set; }
        public string Custom1 { get; set; }
        public string Custom2 { get; set; }
        public string Custom3{ get; set; }

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

<p>after importing all new data I take all new transaction ids, and take all transaction ids for that client from database.</p>

```        // ids from import
        string transactionsString = string.Join(",", transactionIdsCsv);
        var result = await   _transactionsDataRepository.GetByTransactionIdsAndClientId(transactionIdsCsv.ToArray(), clientId);
        // ids from repository
        string transactionsDBString = string.Join(",", result.ToList());

        // remove rows in db where duplicate transactions ids and clientId=ClientId
```

but I am struggling to find the most effective way. I wanted to do something like
delete from transactions where transactionId IN (transactionsDBString) and clientId = ClientID but that would delete both values and I only want new value to be deleted (and old value to stay)

but would that be a good way? even fetching var result = await _transactionsDataRepository... can take a lot of time since there are millions of rows.

答:
I only want new value to be deleted (and old value to stay)

Since you already know how to identify the transaction IDs you want to delete you could delete the necessary rows while keeping the latest like so (you didn't mention it but I'm assuming you're using Entity Framework - given your use of the [Key] attribute - correct me if I'm wrong):

var transToRemove = dbContext.Transactions
    .Where(t => t.ClientId == clientId && transIds.Contains(t.TransactionId))
    .GroupBy(t => t.TransactionId, t => t) // Group transactions with the same TransactionId
    .SelectMany(
        group => group.OrderBy(t => t.Date) // Order the oldest first
                     .Skip(1) // Skip the oldest (we want to keep it)
    );

dbContext.Transactions.RemoveRange(transToRemove);
dbContext.SaveChanges();
```

<hr>

<p><strong>Edit:</strong> Included an example that should work for Dapper...</p>

```var cn = // Create your DbConnection

// This query should select all transactions you want to delete excluding
// those with the oldest Date. This is just like 'transToRemove' above
var selectQuery = @"
SELECT t1.Id FROM Transactions t1
INNER JOIN (
    SELECT
        MIN(tInner.Date) AS FirstTransDate,
        tInner.TransactionId,
        tInner.ClientId
    FROM Transactions tInner
    WHERE tInner.ClientId = @clientId
        AND tInner.TransactionId IN @transIds
    GROUP BY tInner.TransactionId, tInner.ClientId
) t2 ON t2.ClientId = t1.ClientId AND t2.TransactionId = t1.TransactionId
WHERE t1.Date != t2.FirstTransDate
";
var idsToDelete = cn.Query<int>(
    selectQuery,
    new { clientId, transIds }).ToList();

// Delete the whole list in one go
cn.Execute("DELETE FROM Transactions WHERE Id in @idsToDelete", new {idsToDelete});
```

(inspiration from here and here)

I haven't tested this using Dapper but the list of idsToDelete should be correct according to this fiddle I made. A couple things to note:

Depending on how long your list of transIds is (I believe those ID's are in result in your own example) you might want to repeat this in smaller batches instead of trying to delete the whole list in one go.

The SQL query above doesn't take into account if two "duplicate" transactions have the same "oldest" Date. If that can happen in your table, then this query will only remove all "duplicate" rows apart from those two.

Improvements

There are a couple of things that seem a little out of place with your setup that I think you should consider:

even fetching var result = await _transactionsDataRepository... can take a lot of time since there are millions of rows

Millions of rows should not be an issue for any decent database server to handle. It sounds like you are missing some indexes on your table. With proper indexes your queries should be pretty swift as long as you can keep them simple.

but would that be a good way?

Not quite sure what you are referring to being good or bad here, but I'll interpret a little... Right now you are writing tons of rows to the table that seems to contain duplicate data. When I think of a transaction-based system, no two transactions should share the same ID. That means for two different ClientIds there should never be a case where t1.TransactionId == t2.TransactionId. Now you can avoid checking ClientId in my code-snippet above.

Since you want to only keep 1 transaction for each TransactionId will you ever need to have two transactions with the same TransactionId? If not, then you can go even further and make the TransactionId column unique and avoid inserting two rows with the same TransactionId. You can use the Entity Framework [Index(IsUnique=true)] attribute to also create an index to speed up queries on that column/property.

Body:
I have huge transactions table in azure database, where we import files with +1 million objects.

public class Transaction
    {
        [Key]
        public int Id { get; set; }
        public int TransactionId { get; set; }
        public DateTime Date { get; set; }
        public decimal Price { get; set; }
        public int UserId { get; set; }
        public string Product { get; set; }
        public int ClientId { get; set; }
        public int Uploaed { get; set; }
        public string UniqueId { get; set; }
        public string Custom1 { get; set; }
        public string Custom2 { get; set; }
        public string Custom3{ get; set; }

    }

after importing all new data I take all new transaction ids, and take all transaction ids for that client from database.

        // ids from import
        string transactionsString = string.Join(",", transactionIdsCsv);
        var result = await   _transactionsDataRepository.GetByTransactionIdsAndClientId(transactionIdsCsv.ToArray(), clientId);
        // ids from repository
        string transactionsDBString = string.Join(",", result.ToList());

        // remove rows in db where duplicate transactions ids and clientId=ClientId

but I am struggling to find the most effective way. I wanted to do something like
delete from transactions where transactionId IN (transactionsDBString) and clientId = ClientID but that would delete both values and I only want new value to be deleted (and old value to stay)

but would that be a good way? even fetching var result = await _transactionsDataRepository... can take a lot of time since there are millions of rows.

Body:
I only want new value to be deleted (and old value to stay)

Since you already know how to identify the transaction IDs you want to delete you could delete the necessary rows while keeping the latest like so (you didn't mention it but I'm assuming you're using Entity Framework - given your use of the [Key] attribute - correct me if I'm wrong):

var transToRemove = dbContext.Transactions
    .Where(t => t.ClientId == clientId && transIds.Contains(t.TransactionId))
    .GroupBy(t => t.TransactionId, t => t) // Group transactions with the same TransactionId
    .SelectMany(
        group => group.OrderBy(t => t.Date) // Order the oldest first
                     .Skip(1) // Skip the oldest (we want to keep it)
    );

dbContext.Transactions.RemoveRange(transToRemove);
dbContext.SaveChanges();

Edit: Included an example that should work for Dapper...

var cn = // Create your DbConnection

// This query should select all transactions you want to delete excluding
// those with the oldest Date. This is just like 'transToRemove' above
var selectQuery = @"
SELECT t1.Id FROM Transactions t1
INNER JOIN (
    SELECT
        MIN(tInner.Date) AS FirstTransDate,
        tInner.TransactionId,
        tInner.ClientId
    FROM Transactions tInner
    WHERE tInner.ClientId = @clientId
        AND tInner.TransactionId IN @transIds
    GROUP BY tInner.TransactionId, tInner.ClientId
) t2 ON t2.ClientId = t1.ClientId AND t2.TransactionId = t1.TransactionId
WHERE t1.Date != t2.FirstTransDate
";
var idsToDelete = cn.Query<int>(
    selectQuery,
    new { clientId, transIds }).ToList();

// Delete the whole list in one go
cn.Execute("DELETE FROM Transactions WHERE Id in @idsToDelete", new {idsToDelete});

(inspiration from here and here)

I haven't tested this using Dapper but the list of idsToDelete should be correct according to this fiddle I made. A couple things to note:

Depending on how long your list of transIds is (I believe those ID's are in result in your own example) you might want to repeat this in smaller batches instead of trying to delete the whole list in one go.

The SQL query above doesn't take into account if two "duplicate" transactions have the same "oldest" Date. If that can happen in your table, then this query will only remove all "duplicate" rows apart from those two.

Improvements

There are a couple of things that seem a little out of place with your setup that I think you should consider:

even fetching var result = await _transactionsDataRepository... can take a lot of time since there are millions of rows

Millions of rows should not be an issue for any decent database server to handle. It sounds like you are missing some indexes on your table. With proper indexes your queries should be pretty swift as long as you can keep them simple.

but would that be a good way?

Not quite sure what you are referring to being good or bad here, but I'll interpret a little... Right now you are writing tons of rows to the table that seems to contain duplicate data. When I think of a transaction-based system, no two transactions should share the same ID. That means for two different ClientIds there should never be a case where t1.TransactionId == t2.TransactionId. Now you can avoid checking ClientId in my code-snippet above.

Since you want to only keep 1 transaction for each TransactionId will you ever need to have two transactions with the same TransactionId? If not, then you can go even further and make the TransactionId column unique and avoid inserting two rows with the same TransactionId. You can use the Entity Framework [Index(IsUnique=true)] attribute to also create an index to speed up queries on that column/property.


问:
Blur the edges of an image or background image with CSS
I know there are a bunch of new CSS filters and I am wondering if there is a way to apply those to an image or background image.  Everything I have read talks about softening the image with a drop shadow, however, a drop shadow is a color, and I want to blur the edges of images so that I could blend them together more seamlessly if they were next to each other.  Right now it looks like you can only go with a drop shadow or apply a blur to the entire image (based on what I have read).

The closest I can come up with is a semi-transparent box shadow....like this

```<code>-webkit-box-shadow: 12px 29px 81px 0px rgba(0,0,0,0.75);
-moz-box-shadow: 12px 29px 81px 0px rgba(0,0,0,0.75);
box-shadow: 12px 29px 81px 0px rgba(0,0,0,0.75);
</code>```

答:
If you set the image in div, you also must set both height and width. This may cause the image to lose its proportion. In addition, you must set the image URL in CSS instead of HTML.

Instead, you can set the image using the IMG tag. In the container class you can only set the width in percent or pixel and the height will automatically maintain proportion.

This is also more effective for accessibility of search engines and reading engines to define an image using an IMG tag.

.container {
    margin: auto;
    width: 200px;
    position: relative;
}

img {
    width: 100%;
}

.block {
    width: 100%;
    position: absolute;
    bottom: 0px;
    top: 0px;
    box-shadow: inset -10px -10px 10px 20px white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <img src="https://picsum.photos/200/200">
    <!-- http://lorempixel.com/200/200/city -->
    <div class="block"></div>
</div></code>```

Body:
I know there are a bunch of new CSS filters and I am wondering if there is a way to apply those to an image or background image.  Everything I have read talks about softening the image with a drop shadow, however, a drop shadow is a color, and I want to blur the edges of images so that I could blend them together more seamlessly if they were next to each other.  Right now it looks like you can only go with a drop shadow or apply a blur to the entire image (based on what I have read).

The closest I can come up with is a semi-transparent box shadow....like this

-webkit-box-shadow: 12px 29px 81px 0px rgba(0,0,0,0.75);
-moz-box-shadow: 12px 29px 81px 0px rgba(0,0,0,0.75);
box-shadow: 12px 29px 81px 0px rgba(0,0,0,0.75);

Body:
If you set the image in div, you also must set both height and width. This may cause the image to lose its proportion. In addition, you must set the image URL in CSS instead of HTML.

Instead, you can set the image using the IMG tag. In the container class you can only set the width in percent or pixel and the height will automatically maintain proportion.

This is also more effective for accessibility of search engines and reading engines to define an image using an IMG tag.

.container {
    margin: auto;
    width: 200px;
    position: relative;
}

img {
    width: 100%;
}

.block {
    width: 100%;
    position: absolute;
    bottom: 0px;
    top: 0px;
    box-shadow: inset -10px -10px 10px 20px white;
}

<div class="container">
    <img src="https://picsum.photos/200/200">
    <!-- http://lorempixel.com/200/200/city -->
    <div class="block"></div>
</div>