问:
The data is not inserted correctly in the table tbody tag
I'm having a problem setting the body in the dynamic content table.

In fact, thead has been set correctly, but most likely the problem is the tbody; the header of the columns is perfectly displayed, but the content is not.

See image below (Nessun dato presente nella tabella --> No data in the table)

Can anyone kindly help me?

var allart = JSON.parse(this.responseText);
                console.log(allart);
                var tbdy = document.createElement('tbody');
                allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    ${item.id}
                    ${item.titolo}
                    ${item.marca}
                    ${item.immagine}
                    ${item.sezione}
                    ${item.data}
                    `;
                    table.appendChild(child);
                })
                tbdy.appendChild(tr);
                table.appendChild(tbdy);

$(document).ready(function () {
            $('#my-table').DataTable({
                "pagingType": "full_numbers",
                "lengthMenu": [5, 10, 20, 50, 100, 200, 500],
            });
            $('.dataTables_length').addClass('bs-select');
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="my-table" class="row-border hover" width="90%">
        <thead>
            <tr>
                <th class="th-sm">Id</th>
                <th class="th-sm">Titolo</th>
                <th class="th-sm">Marca</th>
                <th class="th-sm">Immagine</th>
                <th class="th-sm">Sezione</th>
                <th class="th-sm">Data</th>

            </tr>
        </thead>

    </table></code>```

答:
you need to append tr with tbody inside the loop.</p>
```<code>allart.Items.forEach(function (item) {
    let child = document.createElement("tr");
    child.innerHTML = `
                <td>${item.id}</td>
                <td>${item.titolo}</td>
                <td>${item.marca}</td>
                <td>${item.immagine}</td>
                <td>${item.sezione}</td>
                <td>${item.data}</td>
                `;
    tbdy.appendChild(child);
})
table.appendChild(tbdy);
</code>```

Body:
I'm having a problem setting the body in the dynamic content table.

In fact, thead has been set correctly, but most likely the problem is the tbody; the header of the columns is perfectly displayed, but the content is not.

See image below (Nessun dato presente nella tabella --> No data in the table)

Can anyone kindly help me?

var allart = JSON.parse(this.responseText);
                console.log(allart);
                var tbdy = document.createElement('tbody');
                allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    ${item.id}
                    ${item.titolo}
                    ${item.marca}
                    ${item.immagine}
                    ${item.sezione}
                    ${item.data}
                    `;
                    table.appendChild(child);
                })
                tbdy.appendChild(tr);
                table.appendChild(tbdy);

$(document).ready(function () {
            $('#my-table').DataTable({
                "pagingType": "full_numbers",
                "lengthMenu": [5, 10, 20, 50, 100, 200, 500],
            });
            $('.dataTables_length').addClass('bs-select');
        });

                Id
                Titolo
                Marca
                Immagine
                Sezione
                Data

Body:
you need to append tr with tbody inside the loop.

allart.Items.forEach(function (item) {
    let child = document.createElement("tr");
    child.innerHTML = `
                <td>${item.id}</td>
                <td>${item.titolo}</td>
                <td>${item.marca}</td>
                <td>${item.immagine}</td>
                <td>${item.sezione}</td>
                <td>${item.data}</td>
                `;
    tbdy.appendChild(child);
})
table.appendChild(tbdy);


来源: stackexchange

问:
Check if columns have a nan value if certain column has a specific value in Dataframe
I'm trying to add column in Dataframe which has a result of checking if other columns have value in it.

This is a test df I made:

```<code>df = pd.DataFrame({"condition":[1,np.nan,np.nan,np.nan,1],"a":[np.nan,4,5,6,np.nan],"b":[np.nan,2,"e",2,np.nan],"c":[3,2,1,2,np.nan]})
</code>```

So what I want to check is, for each row, if condition column's value is 1, "b","c","d" columns should not have values except np.nan. If "condition" has np.nan, result should be "-".

The ideal result should be something like this:

```<code>    condition    a      b      c     check_result
0    1        np.nan  np.nan    3        "X"
1    np.nan      4      2       2        "-"
2    np.nan      5      "e"     1        "-"
3    np.nan      6      2       2        "-"
4    1        np.nan  np.nan    np.nan   "O"
</code>```

I've tried two ways.

First, this one:

```<code>def na_and_check(domain,var_list):
    y = ""
    for var in var_list:
        y += '(np.isnan('+domain+'["'+var+'"]))&'
    y = y[:-1]
    print(y)
    return eval(y)

df["check_result"] = np.where(df["condition"]!=1,"-",np.where(na_and_check("df",["a","b","c"]),"O","X"))
</code>```

But since "b" columns has string value in it, it gives me this Error:

```<code>TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code>```

And for the second one, I tried this:

```<code>df["check_result"] = np.where(df["condition"]!=1,"-",np.where(df[["a","b","c"]].any(),"X","O"))
</code>```

I wasn't confident with .any() and yes, it gives me an error:

```<code>ValueError: operands could not be broadcast together with shapes (5,) () (3,)
</code>```

So um... I don't know what to do next.
Any advice or enlightenment, tips will be appreciated. I'll wait for your teach !
Thanks for stopping by. Have a wonderful day.

答:
so you have an if-elif-else situation. Then we can use np.select for it. It needs the conditions and what to do when they are satisfied:

your if is:      "condition is 1 and a,b,c has all nan"

your elif is: "condition is nan"

what remains is else, as usual

```<code>conditions = [df.condition.eq(1) & df[["a", "b", "c"]].isna().all(axis=1),
              df.condition.isna()]

what_to_do = ["O", "-"]
else_case = "X"

df["check_result"] = np.select(conditions, what_to_do, default=else_case)

df
</code>```
```<code>   condition    a    b    c check_result
0        1.0  NaN  NaN  3.0            X
1        NaN  4.0    2  2.0            -
2        NaN  5.0    e  1.0            -
3        NaN  6.0    2  2.0            -
4        1.0  NaN  NaN  NaN            O
</code>```

So we don't write else's condition. It goes to default.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add column in Dataframe which has a result of checking if other columns have value in it.

This is a test df I made:

df = pd.DataFrame({"condition":[1,np.nan,np.nan,np.nan,1],"a":[np.nan,4,5,6,np.nan],"b":[np.nan,2,"e",2,np.nan],"c":[3,2,1,2,np.nan]})

So what I want to check is, for each row, if condition column's value is 1, "b","c","d" columns should not have values except np.nan. If "condition" has np.nan, result should be "-".

The ideal result should be something like this:

    condition    a      b      c     check_result
0    1        np.nan  np.nan    3        "X"
1    np.nan      4      2       2        "-"
2    np.nan      5      "e"     1        "-"
3    np.nan      6      2       2        "-"
4    1        np.nan  np.nan    np.nan   "O"

I've tried two ways.

First, this one:

def na_and_check(domain,var_list):
    y = ""
    for var in var_list:
        y += '(np.isnan('+domain+'["'+var+'"]))&'
    y = y[:-1]
    print(y)
    return eval(y)

df["check_result"] = np.where(df["condition"]!=1,"-",np.where(na_and_check("df",["a","b","c"]),"O","X"))

But since "b" columns has string value in it, it gives me this Error:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

And for the second one, I tried this:

df["check_result"] = np.where(df["condition"]!=1,"-",np.where(df[["a","b","c"]].any(),"X","O"))

I wasn't confident with .any() and yes, it gives me an error:

ValueError: operands could not be broadcast together with shapes (5,) () (3,)

So um... I don't know what to do next.
Any advice or enlightenment, tips will be appreciated. I'll wait for your teach !
Thanks for stopping by. Have a wonderful day.

Body:
so you have an if-elif-else situation. Then we can use np.select for it. It needs the conditions and what to do when they are satisfied:

your if is:      "condition is 1 and a,b,c has all nan"

your elif is: "condition is nan"

what remains is else, as usual

conditions = [df.condition.eq(1) & df[["a", "b", "c"]].isna().all(axis=1),
              df.condition.isna()]

what_to_do = ["O", "-"]
else_case = "X"

df["check_result"] = np.select(conditions, what_to_do, default=else_case)

df

   condition    a    b    c check_result
0        1.0  NaN  NaN  3.0            X
1        NaN  4.0    2  2.0            -
2        NaN  5.0    e  1.0            -
3        NaN  6.0    2  2.0            -
4        1.0  NaN  NaN  NaN            O

So we don't write else's condition. It goes to default.


问:
Run/install/debug Android applications over Wi-Fi?
I thought there was a way to test your applications in development over Wi-Fi. Is this possible?

I'd love to be able to untether my phone and develop wirelessly.

答:
For Android 11 phones and Android Studio Bumblebee version, there's new update. You can just scan the QR code from your Android phone and
Boom! It is connected.

Saving time to copy paste the process.
Helpful official documentation is here


问:
Flutter app crashs and restart from splash screen when using camera function
I want to click an image and send it to the server. the code works well if we are using gallery function but fails to work when it is swap by camera function.

I am able to open the camera, click the image and after this select if correct or wrong.

after this step the app crash. Next to this step, image needs to be sent to the cropping screen.

here is the code:

```<code>Future getImage() async {
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
      var _image = await ImagePicker.pickImage(source: ImageSource.camera);
      croppedFile = await ImageCropper.cropImage(
      sourcePath: _image.path,
      aspectRatioPresets: [
        CropAspectRatioPreset.square,
        CropAspectRatioPreset.ratio3x2,
        CropAspectRatioPreset.original,
        CropAspectRatioPreset.ratio4x3,
        CropAspectRatioPreset.ratio16x9
      ],
      androidUiSettings: AndroidUiSettings(
          toolbarTitle: 'Cropper',
          toolbarColor: Colors.deepOrange,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.square,
          lockAspectRatio: false),
      iosUiSettings: IOSUiSettings(
        minimumAspectRatio: 1.0,
      )
    );
    if (_pickInProgress) {
        return;
    }
      _pickInProgress = true;
      if (_image != null) {
        setState(() {
          _newAvatar = croppedFile;
        });
      }
      _pickInProgress = false;
  }

</code>```

in Android Studio I have the bellow log when filter is used with keyword flutter:

```<code>2020-02-19 17:51:48.404 10631-10631/in.x.demo D/FlutterActivity: Using the launch theme as normal theme.
2020-02-19 17:51:48.413 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: Setting up FlutterEngine.
2020-02-19 17:51:48.413 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: No preferred FlutterEngine was provided. Creating a new FlutterEngine for this FlutterFragment.
2020-02-19 17:51:48.795 10631-10701/in.x.demo I/flutter: Observatory listening on http://127.0.0.1:38436/ayKKbiBs2ts=/
2020-02-19 17:51:49.031 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: Attaching FlutterEngine to the Activity that owns this Fragment.
2020-02-19 17:51:49.112 10631-10631/in.x.demo D/FlutterView: Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@178fa3d
2020-02-19 17:51:49.142 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: Executing Dart entrypoint: main, and sending initial route: /
2020-02-19 17:51:51.013 10631-10673/in.x.demo E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'contains' was called on null.
    Receiver: null
    Tried calling: contains("access_token")
    #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
    #1      _SplashScreenState.didChangeDependencies (package:demo/screens/common/splash_screen.dart:58:28)
    #2      _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:73:64)
    #3      _rootRunUnary (dart:async/zone.dart:1134:38)
    #4      _CustomZone.runUnary (dart:async/zone.dart:1031:19)
    #5      _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
    #6      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
    #7      Future._propagateToListeners (dart:async/future_impl.dart:709:32)
    #8      Future._propagateToListeners (dart:async/future_impl.dart:607:9)
    #9      Future._completeWithValue (dart:async/future_impl.dart:524:5)
    #10     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:554:7)
    #11     _rootRun (dart:async/zone.dart:1126:13)
    #12     _CustomZone.run (dart:async/zone.dart:1023:19)
    #13     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
    #14     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
    #15     _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
    #16     _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
2020-02-19 17:51:51.015 10631-10673/in.x.demo I/flutter: genesis started
2020-02-19 17:51:51.106 10631-10673/in.x.demo I/flutter: device ID: ee44d5897844a106
2020-02-19 17:51:52.078 10631-10673/in.x.demo I/flutter: genesis final completed
2020-02-19 17:51:52.102 10631-10673/in.x.demo I/flutter: genesis api called !
2020-02-19 17:51:52.102 10631-10673/in.x.demo I/flutter: hasToken true
2020-02-19 17:51:53.085 10631-10673/in.x.demo E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null.
    Receiver: null
    Tried calling: findAncestorStateOfType<NavigatorState>()
    #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
    #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1492:19)
    #2      _SplashScreenState.didChangeDependencies.<anonymous closure> (package:demo/screens/common/splash_screen.dart:54:23)
    #3      new Future.delayed.<anonymous closure> (dart:async/future.dart:316:39)
    #4      _rootRun (dart:async/zone.dart:1122:38)
    #5      _CustomZone.run (dart:async/zone.dart:1023:19)
    #6      _CustomZone.runGuarded (dart:async/zone.dart:925:7)
    #7      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
    #8      _rootRun (dart:async/zone.dart:1126:13)
    #9      _CustomZone.run (dart:async/zone.dart:1023:19)
    #10     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
    #11     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
    #12     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
    #13     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
    #14     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)

`
</code>```

答:
Your object is null when call '.contains('access_token')'

Maybe your context is null when called 'navigator.of'

Body:
I want to click an image and send it to the server. the code works well if we are using gallery function but fails to work when it is swap by camera function.

I am able to open the camera, click the image and after this select if correct or wrong.

after this step the app crash. Next to this step, image needs to be sent to the cropping screen.

here is the code:

Future getImage() async {
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
      var _image = await ImagePicker.pickImage(source: ImageSource.camera);
      croppedFile = await ImageCropper.cropImage(
      sourcePath: _image.path,
      aspectRatioPresets: [
        CropAspectRatioPreset.square,
        CropAspectRatioPreset.ratio3x2,
        CropAspectRatioPreset.original,
        CropAspectRatioPreset.ratio4x3,
        CropAspectRatioPreset.ratio16x9
      ],
      androidUiSettings: AndroidUiSettings(
          toolbarTitle: 'Cropper',
          toolbarColor: Colors.deepOrange,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.square,
          lockAspectRatio: false),
      iosUiSettings: IOSUiSettings(
        minimumAspectRatio: 1.0,
      )
    );
    if (_pickInProgress) {
        return;
    }
      _pickInProgress = true;
      if (_image != null) {
        setState(() {
          _newAvatar = croppedFile;
        });
      }
      _pickInProgress = false;
  }

in Android Studio I have the bellow log when filter is used with keyword flutter:

2020-02-19 17:51:48.404 10631-10631/in.x.demo D/FlutterActivity: Using the launch theme as normal theme.
2020-02-19 17:51:48.413 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: Setting up FlutterEngine.
2020-02-19 17:51:48.413 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: No preferred FlutterEngine was provided. Creating a new FlutterEngine for this FlutterFragment.
2020-02-19 17:51:48.795 10631-10701/in.x.demo I/flutter: Observatory listening on http://127.0.0.1:38436/ayKKbiBs2ts=/
2020-02-19 17:51:49.031 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: Attaching FlutterEngine to the Activity that owns this Fragment.
2020-02-19 17:51:49.112 10631-10631/in.x.demo D/FlutterView: Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@178fa3d
2020-02-19 17:51:49.142 10631-10631/in.x.demo D/FlutterActivityAndFragmentDelegate: Executing Dart entrypoint: main, and sending initial route: /
2020-02-19 17:51:51.013 10631-10673/in.x.demo E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'contains' was called on null.
    Receiver: null
    Tried calling: contains("access_token")
    #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
    #1      _SplashScreenState.didChangeDependencies (package:demo/screens/common/splash_screen.dart:58:28)
    #2      _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:73:64)
    #3      _rootRunUnary (dart:async/zone.dart:1134:38)
    #4      _CustomZone.runUnary (dart:async/zone.dart:1031:19)
    #5      _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
    #6      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
    #7      Future._propagateToListeners (dart:async/future_impl.dart:709:32)
    #8      Future._propagateToListeners (dart:async/future_impl.dart:607:9)
    #9      Future._completeWithValue (dart:async/future_impl.dart:524:5)
    #10     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:554:7)
    #11     _rootRun (dart:async/zone.dart:1126:13)
    #12     _CustomZone.run (dart:async/zone.dart:1023:19)
    #13     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
    #14     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
    #15     _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
    #16     _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
2020-02-19 17:51:51.015 10631-10673/in.x.demo I/flutter: genesis started
2020-02-19 17:51:51.106 10631-10673/in.x.demo I/flutter: device ID: ee44d5897844a106
2020-02-19 17:51:52.078 10631-10673/in.x.demo I/flutter: genesis final completed
2020-02-19 17:51:52.102 10631-10673/in.x.demo I/flutter: genesis api called !
2020-02-19 17:51:52.102 10631-10673/in.x.demo I/flutter: hasToken true
2020-02-19 17:51:53.085 10631-10673/in.x.demo E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null.
    Receiver: null
    Tried calling: findAncestorStateOfType<NavigatorState>()
    #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
    #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1492:19)
    #2      _SplashScreenState.didChangeDependencies.<anonymous closure> (package:demo/screens/common/splash_screen.dart:54:23)
    #3      new Future.delayed.<anonymous closure> (dart:async/future.dart:316:39)
    #4      _rootRun (dart:async/zone.dart:1122:38)
    #5      _CustomZone.run (dart:async/zone.dart:1023:19)
    #6      _CustomZone.runGuarded (dart:async/zone.dart:925:7)
    #7      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
    #8      _rootRun (dart:async/zone.dart:1126:13)
    #9      _CustomZone.run (dart:async/zone.dart:1023:19)
    #10     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
    #11     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
    #12     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
    #13     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
    #14     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)

`


问:
How after completing any task in the loop, pass a value to another method, return to the loop, and wait for the next task to complete?
There are 2 methods, one method depends on the other. I need to send several files to the server in parallel, which answer from the server comes first, and send it to DownloadFileAsync method, and do the same with the rest (without waiting for all answers at once, send them (answers from the server) to DownloadFileAsync() method, as they are received).

```<code>public async Task CompressAllFilesAsync(List<UserFile> files, string outputpath)
{
    await UploadAllFilesAsync(files);
    await DownloadAllFilesAsync(files, outputpath);
}

public async Task UploadAllFilesAsync(List<UserFile> files)
{
    IEnumerable<Task> allTasks = files.Select(async (file, i) =>
        files[i].FileLink = await UploadFileAsync(files[i])
    );

    await Task.WhenAll(allTasks);
}

public async Task DownloadAllFilesAsync(List<UserFile> files, string outputpath)
{
    IEnumerable<Task> allTasks = files.Select((file, i) =>
        DownloadFileAsync(files[i].FileLink,
        Path.Combine(outputpath, $"{files[i].FileName}")
    ));

    await Task.WhenAll(allTasks);
}
</code>```

Now the program is waiting for all answers from the server (links to downloadable files) before running the DownloadAllFilesAsync() method.

答:
You could consider using the new (.NET 6) API Parallel.ForEachAsync, and execute the UploadFileAsync and then the DownloadFileAsync sequentially for each UserFile, but concurrently with other files:

```<code>public async Task CompressAllFilesAsync(List<UserFile> files, string outputPath)
{
    var options = new ParallelOptions() { MaxDegreeOfParallelism = 10 };
    await Parallel.ForEachAsync(files, options, async (file, ct) =>
    {
        await UploadFileAsync(file);
        await DownloadFileAsync(file.FileLink,
            Path.Combine(outputPath, $"{file.FileName}"));
    });
}
</code>```

The UploadFileAsync and DownloadFileAsync will be invoked on ThreadPool threads. This shouldn't be a problem, unless those methods interact with thread-affine components (like UI controls).

Body:
There are 2 methods, one method depends on the other. I need to send several files to the server in parallel, which answer from the server comes first, and send it to DownloadFileAsync method, and do the same with the rest (without waiting for all answers at once, send them (answers from the server) to DownloadFileAsync() method, as they are received).

public async Task CompressAllFilesAsync(List<UserFile> files, string outputpath)
{
    await UploadAllFilesAsync(files);
    await DownloadAllFilesAsync(files, outputpath);
}

public async Task UploadAllFilesAsync(List<UserFile> files)
{
    IEnumerable<Task> allTasks = files.Select(async (file, i) =>
        files[i].FileLink = await UploadFileAsync(files[i])
    );

    await Task.WhenAll(allTasks);
}

public async Task DownloadAllFilesAsync(List<UserFile> files, string outputpath)
{
    IEnumerable<Task> allTasks = files.Select((file, i) =>
        DownloadFileAsync(files[i].FileLink,
        Path.Combine(outputpath, $"{files[i].FileName}")
    ));

    await Task.WhenAll(allTasks);
}

Now the program is waiting for all answers from the server (links to downloadable files) before running the DownloadAllFilesAsync() method.

Body:
You could consider using the new (.NET 6) API Parallel.ForEachAsync, and execute the UploadFileAsync and then the DownloadFileAsync sequentially for each UserFile, but concurrently with other files:

public async Task CompressAllFilesAsync(List<UserFile> files, string outputPath)
{
    var options = new ParallelOptions() { MaxDegreeOfParallelism = 10 };
    await Parallel.ForEachAsync(files, options, async (file, ct) =>
    {
        await UploadFileAsync(file);
        await DownloadFileAsync(file.FileLink,
            Path.Combine(outputPath, $"{file.FileName}"));
    });
}

The UploadFileAsync and DownloadFileAsync will be invoked on ThreadPool threads. This shouldn't be a problem, unless those methods interact with thread-affine components (like UI controls).


问:
Cells don't appear to be updating within a loop?
I'm trying to update a wxgrid with values read from a database.

When I use SetCellValue directl above my loop, it correctly assigns the value, but within the loop it only appears to update a 'local'copy of the grid, and when out of the loop again, only contains the values it had previously - I'm sure this is a real silly mistake on my behalf, but its driving me mad so really appreciate any assistance.

```<code>    #now clear grid and re-populate with cafe data
    print('1,6 is ',self.myGrid.GetCellValue(1,6))
    self.myGrid.SetCellValue(1,7,'TEST')
    #self.myGrid.ClearGrid()
    for index, value in enumerate(curItems):
        x = 0
        print(index)
        print(len(value))
        while x < len(value):
            if debug : print(x,index,value[x])
            self.myGrid.SetCellValue(x,index,str(value[x]))
            print('grid values :',index,x,self.myGrid.GetCellValue(x,index))
            x += 1
    print('1,7 is ',self.myGrid.GetCellValue(1,7))
    self.myGrid.ForceRefresh
</code>```

cell (1,6) is defined with a test value in the definition function before this gets called on an event (which updates other setLabels etc fine), and gives the correct value here:

```<code>1,6 is  I'm in red!
</code>```

within the loop the values are set correctly:

```<code>grid values : 1 0 20220114002
grid values : 1 1 2022-01-14
grid values : 1 2 Electrical
grid values : 1 3 Toaster
grid values : 1 4 burns
grid values : 1 5 0
grid values : 1 6 Not Fixed
grid values : 1 7 Steve
grid values : 1 8 too damaged
grid values : 1 9 1
</code>```

but as soon as you come back out of the loop:

```<code>1,7 is  TEST
</code>```

答:
Maybe 'index' and 'x' are in the wrong place</p>
```<code>self.myGrid.SetCellValue(index,x,str(value[x]))
print('grid values :',index,x,self.myGrid.GetCellValue(index,x))
</code>```

Body:
I'm trying to update a wxgrid with values read from a database.

When I use SetCellValue directl above my loop, it correctly assigns the value, but within the loop it only appears to update a 'local'copy of the grid, and when out of the loop again, only contains the values it had previously - I'm sure this is a real silly mistake on my behalf, but its driving me mad so really appreciate any assistance.

    #now clear grid and re-populate with cafe data
    print('1,6 is ',self.myGrid.GetCellValue(1,6))
    self.myGrid.SetCellValue(1,7,'TEST')
    #self.myGrid.ClearGrid()
    for index, value in enumerate(curItems):
        x = 0
        print(index)
        print(len(value))
        while x < len(value):
            if debug : print(x,index,value[x])
            self.myGrid.SetCellValue(x,index,str(value[x]))
            print('grid values :',index,x,self.myGrid.GetCellValue(x,index))
            x += 1
    print('1,7 is ',self.myGrid.GetCellValue(1,7))
    self.myGrid.ForceRefresh

cell (1,6) is defined with a test value in the definition function before this gets called on an event (which updates other setLabels etc fine), and gives the correct value here:

1,6 is  I'm in red!

within the loop the values are set correctly:

grid values : 1 0 20220114002
grid values : 1 1 2022-01-14
grid values : 1 2 Electrical
grid values : 1 3 Toaster
grid values : 1 4 burns
grid values : 1 5 0
grid values : 1 6 Not Fixed
grid values : 1 7 Steve
grid values : 1 8 too damaged
grid values : 1 9 1

but as soon as you come back out of the loop:

1,7 is  TEST

Body:
Maybe 'index' and 'x' are in the wrong place

self.myGrid.SetCellValue(index,x,str(value[x]))
print('grid values :',index,x,self.myGrid.GetCellValue(index,x))


问:
Suppress warning CS1998: This async method lacks 'await'
I've got an interface with some functions that return Task. Some of the classes that implement the interface do not have anything to await, while others might just throw - so the warnings are spurious and annoying.

Is it possible to suppress these warnings? E.g.:

public async Task<object> test()
{
    throw new NotImplementedException();
}
```

yields:

warning CS1998: This async method lacks 'await' operators and will run
synchronously. Consider using the 'await' operator to await
non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work
on a background thread.

答:
Use throw of yielded exception</p>
```<code>public async Task<object> DoSomethingAsync()
{
    throw await Task.FromException<NotImplementedException>(new NotImplementedException());
}
</code>```

Body:
I've got an interface with some functions that return Task. Some of the classes that implement the interface do not have anything to await, while others might just throw - so the warnings are spurious and annoying.

Is it possible to suppress these warnings? E.g.:

public async Task<object> test()
{
    throw new NotImplementedException();
}

yields:

warning CS1998: This async method lacks 'await' operators and will run
synchronously. Consider using the 'await' operator to await
non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work
on a background thread.

Body:
Use throw of yielded exception

public async Task<object> DoSomethingAsync()
{
    throw await Task.FromException<NotImplementedException>(new NotImplementedException());
}


问:
Trying to access array offset on value of type int - problem with for loop
I have created a mastermind game with php sessions. I store a counter under the name of contador.

When I try to iterate and print each time the user has tried to enter an input like this:
1. Your numbers were...
2. your numbers were...
3. your numbers were...etc

I get this error:

! ) Notice: Trying to access array offset on value of type int in C:\xampp\htdocs\PhpProject4\juego.php on line 64

This is the session code

```<code>// abrimos sesion siempre arriba del todo php para que no de errores
session_start();

// initialize session variables
$_SESSION['logged_in_user_id'] = '1';
$_SESSION['logged_in_user_name'] = 'Paco';

//recogo los datos enviados por el metodo post
if (isset($_POST["enviar"])) {

    //compruebo que no esten vacios los datos
    if (($_POST['numero1'] === '') && ($_POST['numero2'] === '') && ($_POST['numero3'] === '') && ($_POST['numero4'] === '')) {
        //si estan vacios me sale el error siguiente y me muestra un boton para volver atras
        echo "Tienes que escribir numeros";
        ?>
        <html lang="es">
        <head>
            <title>Juego Mastermind</title>
        </head>
        <body>
        <br>
        <a href="juego.php">Volver</a>
        </body>
        </html>
        <?php
    } else {
        //if(is_numeric){
        //guardo cada numero en una variable
        $_SESSION['numero1'] = $_POST['numero1'];
        $_SESSION['numero2'] = $_POST['numero2'];
        $_SESSION['numero3'] = $_POST['numero3'];
        $_SESSION['numero4'] = $_POST['numero4'];

        //le doy +1 a contador y lo guardo en sesion
        if (!isset($_SESSION['contador'])){
            $_SESSION['contador'] = 1;
        }else{
            $_SESSION['contador']+=1;
        }

        //declaro el array
        $numerosPedidos = [];

        //meto los datos en el array
        array_push($numerosPedidos, $_SESSION['numero1'], $_SESSION['numero2'], $_SESSION['numero3'], $_SESSION['numero4']);

        //guardo el array de numeros pedidos
        $_SESSION['numerosPedidos'] = $numerosPedidos;

        //recibo el array de numeros aleatorios
        $arrayAleatorios = $_SESSION['numerosAleatorios'];

        //paso heridos y muertos al otro archivo php
        $_SESSION['muertos'] = buscarMuertos($numerosPedidos, $arrayAleatorios);
        $_SESSION['heridos'] = buscarHeridos($numerosPedidos, $arrayAleatorios);

        //session_destroy();

        //vuelvo al php juegos donde vuevlo a comprobar y muestro datos por pantalla
        header("Location:juego.php");
    }
}

//funcion buscar muerto que devuelvo la cantidad
function buscarMuertos($numerosPed, $numerosAle)
{
    //declaro el numero de muertos
    $muertos = 0;
    //hago un bucle para comprobar que esten en la misma posicion
    for ($i = 0; $i < 4; $i++) {
        if ($numerosPed[$i] == $numerosAle[$i]) {
            $muertos++;
        }
    }
    return $muertos;
}

//funcion buscar heridos que devuelve la cantidad
function buscarHeridos($numerosPed, $numerosAle)
{
    //declaro el numero de heridos
    $heridos = 0;

    //hago un bucle para comprobar numero de heridos
    for ($i = 0; $i < 4; $i++) {
        //primero comprouebo que el numero que quiero esta en ambos arrays
        if (in_array($numerosPed[$i], $numerosAle)) {
            //despues comrpuebo que esos numeros esten en posiciones diferentes
            if ($numerosPed[$i] != $numerosAle[$i]) {
                $heridos++;
            }

        }

    }
    return $heridos;
}
</code>```

This is the game code

```<code><?php
//abrimos sesion al principio para que no falle
session_start();

$usuario = $_SESSION['usuario'];
//compruebo que entre datos de usuario para acceder, si no da error y termina el programa
if ($usuario == null || $usuario = "") {
    echo "Debes escribir un nombre de usuario para acceder";
    die();
}

/*   Si no existe la varaible numeroaleatorios dentro de la sesion la creo, en caso contrario la mantengo para que no cambie el numero
     cada vez que cambio de sesion*/
if (!isset($_SESSION['numerosAleatorios'])) {
    //generamos los numeros con un rango del 0 al 9 y los guardo en un array de forma aleatoria
    $numeros = range(0, 9);
    shuffle($numeros);

    //los hacemos aleatorios en un array pero tienen 9 posiciones por lo que solo voy a usar las 4 primeras y son las unicas que extraigo
    for ($i = 0; $i < 4; $i++) {
        $aleatorios[$i] = $numeros[$i];
    }

    //creo el array para enviarlo a sesion.php y alli hacer comprobaciones
    $_SESSION['numerosAleatorios'] = $aleatorios;
} else {
    //establezco aleatorios de nuevo para que funcione y no de errores el codigo
    $aleatorios = $_SESSION['numerosAleatorios'];
    ?>
    <!--            genero el HTML              -->
    <html lang="es">
    <head>
        <title>Juego Mastermind</title>
    </head>
    <body>
    <h3>Bienvenido de nuevo <?php echo $_SESSION['usuario'] ?></h3>
    <!--Imprimo las 4 primeras cifras del array numeros que son las que voy a usar-->
    <h2>Numero: <?php print_r($aleatorios[0] . $aleatorios[1] . $aleatorios[2] . $aleatorios[3]) ?></h2>
    <h1>Mastermind Juego de los muertos y heridos</h1>
    <h2>Registro de jugadas</h2>
    <?php
    //si esta creada la sesion contador entonces me hace el proceso de mostrarme la informacion
    if (isset($_SESSION['contador'])) {

//        paso el contador a una variable
        $contador = $_SESSION['contador'];

        //si el numero de muertos es menor que cuatro muestro por pantalla, si es 4 reenvio a otra sesion donde muestro que ha ganado
        if ($_SESSION['muertos'] < 4) {
//          hago un bucle para escribir por pantalla los numeros que lleva
            /*
            foreach ($_SESSION as $sesion){
                //aqui transformo el array en un string para que me lo muestre sin problemas mas adelante
                $numerosTransformados = implode("", $_SESSION['numerosPedidos']);

                echo "<p>".$contador.". Con el numero introducido: " . $numerosTransformados . " tienes " . $_SESSION['muertos'] .
                    " muertos y " . $_SESSION['heridos'] . " heridos" . "</p>";
            }*/

            for ($i=0; $i<$contador; $i++){
                //aqui transformo el array en un string para que me lo muestre sin problemas mas adelante
                $numerosTransformados = implode("", $_SESSION['numerosPedidos']);

                echo "<p>".$contador[$i].". Con el numero introducido: " . $numerosTransformados[$i] . " tienes " . $_SESSION['muertos'] .
                    " muertos y " . $_SESSION['heridos'] . " heridos" . "</p>";
            }
        } else if ($_SESSION['muertos'] == 4) {
            header("Location:ganado.php");
        }
    }
    ?>
    <form method="POST" action="sesion.php">
        <p>Introduce Numeros</p>
        <label for="numero1">
            <input type="number" min="0" max="9" name="numero1">
        </label>
        <label for="numero2">
            <input type="number" min="0" max="9" name="numero2">
        </label>
        <label for="numero3">
            <input type="number" min="0" max="9" name="numero3">
        </label>
        <label for="numero4">
            <input type="number" min="0" max="9" name="numero4">
        </label>

        <button type="submit" name="enviar" value="enviar" id="enviar">Enviar</button>
    </form>
    <a href="cerrarSesion.php">Cerrar sesion</a>
    </body>
    </html>
    <?php
}
?>
</code>```

Thank you very much in advance

答:
The error message is quite clear. Line 64 is this line:

        echo "
".$contador[$i]." // followed by more strings
```
<p>But <code>$contador</code> is an integer, not an array. We can see you treat is (correctly) as an integer right before that line:</p>
<pre class="lang-php prettyprint-override"><code>    for ($i=0; $i<$contador; $i++){
</code>```

So accessing $contador[$i] makes no sense. I don't know what you wanted to do, but replacing that with just $contador will resolve the error.

Then, for the same reason you'll get probably unexpected output with $numerosTransformados[$i]. That is not an array, ... it is a string. So this will produce the character at index $i.

Body:
I have created a mastermind game with php sessions. I store a counter under the name of contador.

When I try to iterate and print each time the user has tried to enter an input like this:
1. Your numbers were...
2. your numbers were...
3. your numbers were...etc

I get this error:

! ) Notice: Trying to access array offset on value of type int in C:\xampp\htdocs\PhpProject4\juego.php on line 64

This is the session code

// abrimos sesion siempre arriba del todo php para que no de errores
session_start();

// initialize session variables
$_SESSION['logged_in_user_id'] = '1';
$_SESSION['logged_in_user_name'] = 'Paco';

//recogo los datos enviados por el metodo post
if (isset($_POST["enviar"])) {

    //compruebo que no esten vacios los datos
    if (($_POST['numero1'] === '') && ($_POST['numero2'] === '') && ($_POST['numero3'] === '') && ($_POST['numero4'] === '')) {
        //si estan vacios me sale el error siguiente y me muestra un boton para volver atras
        echo "Tienes que escribir numeros";
        ?>

            <title>Juego Mastermind</title>

        Volver

        <?php
    } else {
        //if(is_numeric){
        //guardo cada numero en una variable
        $_SESSION['numero1'] = $_POST['numero1'];
        $_SESSION['numero2'] = $_POST['numero2'];
        $_SESSION['numero3'] = $_POST['numero3'];
        $_SESSION['numero4'] = $_POST['numero4'];

        //le doy +1 a contador y lo guardo en sesion
        if (!isset($_SESSION['contador'])){
            $_SESSION['contador'] = 1;
        }else{
            $_SESSION['contador']+=1;
        }

        //declaro el array
        $numerosPedidos = [];

        //meto los datos en el array
        array_push($numerosPedidos, $_SESSION['numero1'], $_SESSION['numero2'], $_SESSION['numero3'], $_SESSION['numero4']);

        //guardo el array de numeros pedidos
        $_SESSION['numerosPedidos'] = $numerosPedidos;

        //recibo el array de numeros aleatorios
        $arrayAleatorios = $_SESSION['numerosAleatorios'];

        //paso heridos y muertos al otro archivo php
        $_SESSION['muertos'] = buscarMuertos($numerosPedidos, $arrayAleatorios);
        $_SESSION['heridos'] = buscarHeridos($numerosPedidos, $arrayAleatorios);

        //session_destroy();

        //vuelvo al php juegos donde vuevlo a comprobar y muestro datos por pantalla
        header("Location:juego.php");
    }
}

//funcion buscar muerto que devuelvo la cantidad
function buscarMuertos($numerosPed, $numerosAle)
{
    //declaro el numero de muertos
    $muertos = 0;
    //hago un bucle para comprobar que esten en la misma posicion
    for ($i = 0; $i < 4; $i++) {
        if ($numerosPed[$i] == $numerosAle[$i]) {
            $muertos++;
        }
    }
    return $muertos;
}

//funcion buscar heridos que devuelve la cantidad
function buscarHeridos($numerosPed, $numerosAle)
{
    //declaro el numero de heridos
    $heridos = 0;

    //hago un bucle para comprobar numero de heridos
    for ($i = 0; $i < 4; $i++) {
        //primero comprouebo que el numero que quiero esta en ambos arrays
        if (in_array($numerosPed[$i], $numerosAle)) {
            //despues comrpuebo que esos numeros esten en posiciones diferentes
            if ($numerosPed[$i] != $numerosAle[$i]) {
                $heridos++;
            }

        }

    }
    return $heridos;
}

This is the game code

<?php
//abrimos sesion al principio para que no falle
session_start();

$usuario = $_SESSION['usuario'];
//compruebo que entre datos de usuario para acceder, si no da error y termina el programa
if ($usuario == null || $usuario = "") {
    echo "Debes escribir un nombre de usuario para acceder";
    die();
}

/*   Si no existe la varaible numeroaleatorios dentro de la sesion la creo, en caso contrario la mantengo para que no cambie el numero
     cada vez que cambio de sesion*/
if (!isset($_SESSION['numerosAleatorios'])) {
    //generamos los numeros con un rango del 0 al 9 y los guardo en un array de forma aleatoria
    $numeros = range(0, 9);
    shuffle($numeros);

    //los hacemos aleatorios en un array pero tienen 9 posiciones por lo que solo voy a usar las 4 primeras y son las unicas que extraigo
    for ($i = 0; $i < 4; $i++) {
        $aleatorios[$i] = $numeros[$i];
    }

    //creo el array para enviarlo a sesion.php y alli hacer comprobaciones
    $_SESSION['numerosAleatorios'] = $aleatorios;
} else {
    //establezco aleatorios de nuevo para que funcione y no de errores el codigo
    $aleatorios = $_SESSION['numerosAleatorios'];
    ?>

        <title>Juego Mastermind</title>

Bienvenido de nuevo <?php echo $_SESSION['usuario'] ?>

Numero: <?php print_r($aleatorios[0] . $aleatorios[1] . $aleatorios[2] . $aleatorios[3]) ?>

Mastermind Juego de los muertos y heridos

Registro de jugadas

    <?php
    //si esta creada la sesion contador entonces me hace el proceso de mostrarme la informacion
    if (isset($_SESSION['contador'])) {

//        paso el contador a una variable
        $contador = $_SESSION['contador'];

        //si el numero de muertos es menor que cuatro muestro por pantalla, si es 4 reenvio a otra sesion donde muestro que ha ganado
        if ($_SESSION['muertos'] < 4) {
//          hago un bucle para escribir por pantalla los numeros que lleva
            /*
            foreach ($_SESSION as $sesion){
                //aqui transformo el array en un string para que me lo muestre sin problemas mas adelante
                $numerosTransformados = implode("", $_SESSION['numerosPedidos']);

                echo "
".$contador.". Con el numero introducido: " . $numerosTransformados . " tienes " . $_SESSION['muertos'] .
                    " muertos y " . $_SESSION['heridos'] . " heridos" . "
";
            }*/

            for ($i=0; $i<$contador; $i++){
                //aqui transformo el array en un string para que me lo muestre sin problemas mas adelante
                $numerosTransformados = implode("", $_SESSION['numerosPedidos']);

                echo "
".$contador[$i].". Con el numero introducido: " . $numerosTransformados[$i] . " tienes " . $_SESSION['muertos'] .
                    " muertos y " . $_SESSION['heridos'] . " heridos" . "
";
            }
        } else if ($_SESSION['muertos'] == 4) {
            header("Location:ganado.php");
        }
    }
    ?>
    <form method="POST" action="sesion.php">

Introduce Numeros

            <input type="number" min="0" max="9" name="numero1">

            <input type="number" min="0" max="9" name="numero2">

            <input type="number" min="0" max="9" name="numero3">

            <input type="number" min="0" max="9" name="numero4">

        <button type="submit" name="enviar" value="enviar" id="enviar">Enviar</button>
    </form>
    Cerrar sesion

    <?php
}
?>

Thank you very much in advance

Body:
The error message is quite clear. Line 64 is this line:

        echo "<p>".$contador[$i]." // followed by more strings

But $contador is an integer, not an array. We can see you treat is (correctly) as an integer right before that line:

    for ($i=0; $i<$contador; $i++){

So accessing $contador[$i] makes no sense. I don't know what you wanted to do, but replacing that with just $contador will resolve the error.

Then, for the same reason you'll get probably unexpected output with $numerosTransformados[$i]. That is not an array, ... it is a string. So this will produce the character at index $i.


问:
Youtube API "An error occurred while initializing the YouTube player."
I'm using Youtube API to have simple playerView on my application. I did what the API said to do but I keep getting "application is stopped" message. I don't really know the exact english phrase since I'm using a Korean Phone. Hope that's the right phrase in English.

I put Youtubeandroidplayerapi.jar in libs and built the path and have the unnecessary components in library.

Here is Menu.java.

```<code>package com.hobak.sci;

import com.hobak.sci.DeveloperKey;
import com.hobak.sci.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import android.os.Bundle;

public class Menu extends YouTubeBaseActivity implements
    YouTubePlayer.OnInitializedListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);

        YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,
        YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        player.cueVideo("2LHv1FPd1Ec");
    }
}

protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.youtube_view);
}

@Override
public void onInitializationFailure(Provider arg0,
        YouTubeInitializationResult arg1) {
    // TODO Auto-generated method stub

}

}
</code>```

and here is my xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFACD"
    android:orientation="vertical" >

  <com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/youtube_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

</LinearLayout>
</code>```

and here is my logcat

```<code>03-17 15:55:51.260: E/AndroidRuntime(5277): FATAL EXCEPTION: main
03-17 15:55:51.260: E/AndroidRuntime(5277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hobak.sci/com.hobak.sci.Menu}: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1961)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.access$600(ActivityThread.java:128)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1152)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Looper.loop(Looper.java:137)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.main(ActivityThread.java:4453)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invokeNative(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invoke(Method.java:511)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at dalvik.system.NativeStart.main(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277): Caused by: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ContextImpl.bindService(ContextImpl.java:1164)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.content.ContextWrapper.bindService(ContextWrapper.java:370)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.internal.r.e(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubeBaseActivity$a.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.initialize(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.hobak.sci.Menu.onCreate(Menu.java:21)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Activity.performCreate(Activity.java:4467)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1925)
03-17 15:55:51.260: E/AndroidRuntime(5277):     ... 11 more
</code>```

答:
The issue may also be caused by Android 11 restricting access to other apps. https://developer.android.com/training/basics/intents/package-visibility

Adding the following <queries> tag to <manifest> tag in AndroidManifest.xml to declare that my app needs to access the Youtube package and matching the appropriate intent filter signature solved the issue for me:

<manifest package="com.example.game">
    <queries>
        <intent>
            <action
                android:name="com.google.android.youtube.api.service.START" />
        </intent>
    </queries>
    ...
</manifest>
```

Read more: https://developer.android.com/training/package-visibility/declaring#intent-filter-signature

ContentLicense: CC BY-SA 3.0

Body:
I'm using Youtube API to have simple playerView on my application. I did what the API said to do but I keep getting "application is stopped" message. I don't really know the exact english phrase since I'm using a Korean Phone. Hope that's the right phrase in English.

I put Youtubeandroidplayerapi.jar in libs and built the path and have the unnecessary components in library.

Here is Menu.java.

package com.hobak.sci;

import com.hobak.sci.DeveloperKey;
import com.hobak.sci.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import android.os.Bundle;

public class Menu extends YouTubeBaseActivity implements
    YouTubePlayer.OnInitializedListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);

        YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,
        YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        player.cueVideo("2LHv1FPd1Ec");
    }
}

protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.youtube_view);
}

@Override
public void onInitializationFailure(Provider arg0,
        YouTubeInitializationResult arg1) {
    // TODO Auto-generated method stub

}

}

and here is my xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFACD"
    android:orientation="vertical" >

  <com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/youtube_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

</LinearLayout>

and here is my logcat

03-17 15:55:51.260: E/AndroidRuntime(5277): FATAL EXCEPTION: main
03-17 15:55:51.260: E/AndroidRuntime(5277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hobak.sci/com.hobak.sci.Menu}: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1961)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.access$600(ActivityThread.java:128)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1152)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Looper.loop(Looper.java:137)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.main(ActivityThread.java:4453)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invokeNative(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invoke(Method.java:511)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at dalvik.system.NativeStart.main(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277): Caused by: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ContextImpl.bindService(ContextImpl.java:1164)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.content.ContextWrapper.bindService(ContextWrapper.java:370)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.internal.r.e(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubeBaseActivity$a.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.initialize(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.hobak.sci.Menu.onCreate(Menu.java:21)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Activity.performCreate(Activity.java:4467)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1925)
03-17 15:55:51.260: E/AndroidRuntime(5277):     ... 11 more

Body:
The issue may also be caused by Android 11 restricting access to other apps. https://developer.android.com/training/basics/intents/package-visibility

Adding the following <queries> tag to <manifest> tag in AndroidManifest.xml to declare that my app needs to access the Youtube package and matching the appropriate intent filter signature solved the issue for me:

<manifest package="com.example.game">
    <queries>
        <intent>
            <action
                android:name="com.google.android.youtube.api.service.START" />
        </intent>
    </queries>
    ...
</manifest>

Read more: https://developer.android.com/training/package-visibility/declaring#intent-filter-signature


问:
Heavy CRON Tasks
I have to run a pretty heavy task on PHP once a week (script that curls to various locations (websites, API's), gathers, sorts data and inserts it into a db). The whole script takes about 10 to 15 mintues to run on my mac (localhost) - guessing it'll run a bit faster on a server. Nevertheless - I'm currently looping through with AJAX, so when each task is finished, next one is launched. Now I need to run it weekly, automatically. So I think I can't do it with AJAX Anymore.

Do I have to just set the php.ini to let a script run for 30 mintues or there is a better way to do it ?

答:
The maximum execution time of the PHP script is determined by the amount of time in which no output has been generated. So writing data into STDOUT (e.g. to a logfile) will keep the script running.

However, if you're running the script from command line, the max-execution-time will be defaulted to zero anyway and as already suggested, I'd start the script with a cronjob instead of an AJAX-Request or similar methods. I actually do that for most of my php-scripts performing administrative tasks like synchronizing data across several databases or similar purposes.

Title: Heavy CRON Tasks


问:
pandasql OperationalError: near "(": syntax error
I am using pandasql in python and I am new to SQlLITE

```<code>
query = '''
select row_number() over (order by cumSum) as SegmentOrder
, min(rowLoc) as SegmentStart
, max(rowLoc) - min(rowLoc) as Height
from df_lineLocations
where line = 0
--and CumSum !=0
group by cumSum
'''

df_SegmentLocations  = ps.sqldf(query, locals())
df_SegmentLocations
</code>```

I tried removing the parentheses in row_number() but nothing happened

答:
You just need to update your SQLite to the latest version and this query will work.

If you are working on Colab then the default SQLite version is old. And older versions throws up OperationalError whenever there are compound queries which require special characters like ( , * etc.

I have referred to this answer to update SQLite to the latest version on Colab:
https://stackoverflow.com/a/59429952/13248955

Here's the code snippet:

```<code># compiling is the same as before
!curl https://www.sqlite.org/src/tarball/sqlite.tar.gz?r=release | tar xz
%cd sqlite/
!./configure
!make sqlite3.c
%cd /content
!npx degit coleifer/pysqlite3 -f
!cp sqlite/sqlite3.[ch] .
!python setup.py build_static build
</code>```

will unzip the sqlite latest version

```<code># check where it is now
!ls build
</code>```

lib.linux-x86_64-3.7  temp.linux-x86_64-3.7

```<code># !ls build/lib.linux-*version which you got as output in previous step*/pysqlite3/

!ls build/lib.linux-x86_64-3.7/pysqlite3/
</code>```

dbapi2.py  init.py    _sqlite3.cpython-37m-x86_64-linux-gnu.so

```<code>!ls /usr/lib/ | grep python
</code>```

The output will be something like this:

python2.7 python3 python3.6 python3.7 python3.8

```<code> # From the list, select python3.7
 !cp build/lib.linux-x86_64-3.7/pysqlite3/_sqlite3.cpython-37m-x86_64-linux-gnu.so/usr/lib/python3.7/lib-dynload/
</code>```

then MENU: Runtime > Restart runtime

```<code> import sqlite3
 sqlite3.sqlite_version
</code>```

'3.37.2'  // will print out the latest SQLite version

Body:
I am using pandasql in python and I am new to SQlLITE

query = '''
select row_number() over (order by cumSum) as SegmentOrder
, min(rowLoc) as SegmentStart
, max(rowLoc) - min(rowLoc) as Height
from df_lineLocations
where line = 0
--and CumSum !=0
group by cumSum
'''

df_SegmentLocations  = ps.sqldf(query, locals())
df_SegmentLocations

I tried removing the parentheses in row_number() but nothing happened

Body:
You just need to update your SQLite to the latest version and this query will work.

If you are working on Colab then the default SQLite version is old. And older versions throws up OperationalError whenever there are compound queries which require special characters like ( , * etc.

I have referred to this answer to update SQLite to the latest version on Colab:
https://stackoverflow.com/a/59429952/13248955

Here's the code snippet:

# compiling is the same as before
!curl https://www.sqlite.org/src/tarball/sqlite.tar.gz?r=release | tar xz
%cd sqlite/
!./configure
!make sqlite3.c
%cd /content
!npx degit coleifer/pysqlite3 -f
!cp sqlite/sqlite3.[ch] .
!python setup.py build_static build

will unzip the sqlite latest version

# check where it is now
!ls build

lib.linux-x86_64-3.7  temp.linux-x86_64-3.7

# !ls build/lib.linux-*version which you got as output in previous step*/pysqlite3/

!ls build/lib.linux-x86_64-3.7/pysqlite3/

dbapi2.py  init.py    _sqlite3.cpython-37m-x86_64-linux-gnu.so

!ls /usr/lib/ | grep python

The output will be something like this:

python2.7 python3 python3.6 python3.7 python3.8

 # From the list, select python3.7
 !cp build/lib.linux-x86_64-3.7/pysqlite3/_sqlite3.cpython-37m-x86_64-linux-gnu.so/usr/lib/python3.7/lib-dynload/

then MENU: Runtime > Restart runtime

 import sqlite3
 sqlite3.sqlite_version

'3.37.2'  // will print out the latest SQLite version


问:
How do I slice data from a text file with a prefix in Python?
I was wondering if I could slice data from a txt file using a prefix for example:

f = open("file.txt", "r")
print(f.read())
```
<p>Let's say for example's sake there is only 1 line and that line is "21:days" the prefix here is ":" and I want to make Python understand that data on the left of the prefix which is ":" is x and data on the right is y.</p>
<p>I am aware of the split function but I want to process a text file and I don't know how to split it according to something like this</p>
<p>Edit:
An example of an input I would like to process is "39!@:Option2", this is going to be looped to every line in the text file which has a similar format.</p>
<p>An example of the expected output is:</p>
<pre class="lang-python prettyprint-override"><code>391!@ requested Option2
</code>```

答:
Most people use pandas library when processing data like this.

Reading data from a text file separated with special characters is a normal procedure using python. These files with plain text are known as Character Separated Values (CSV) which use a special character to identify the different information that the file contains. Using the pandas library is one of the most common ways to process the information contained in these files.

Here is how you would do it with your file separated with ":"

```<code>import pandas as pd
df = pd.read_csv("file.txt", sep = ":", names=['User', 'Option'])
</code>```

To access the information you will only need to point to the data contained in the dataframe created, like so: y = df['User'][0] This will get you the value in the first row of the column User. To get an output like the one you've presented in your example, you could just use something like: print(df['User'][0] + " requested " + df['Option'][0]) which will return:

```<code>391!@ requested Option2
</code>```

Consider that this way of accessing information is optimized to read multiple lines in a text file. That way, you'll have all the information contained in a dataframe separated in rows and columns.

Processing data like this will avoid you having to loop through the entire file using split

Body:
I was wondering if I could slice data from a txt file using a prefix for example:

f = open("file.txt", "r")
print(f.read())

Let's say for example's sake there is only 1 line and that line is "21:days" the prefix here is ":" and I want to make Python understand that data on the left of the prefix which is ":" is x and data on the right is y.

I am aware of the split function but I want to process a text file and I don't know how to split it according to something like this

Edit:
An example of an input I would like to process is "39!@:Option2", this is going to be looped to every line in the text file which has a similar format.

An example of the expected output is:

391!@ requested Option2

Body:
Most people use pandas library when processing data like this.

Reading data from a text file separated with special characters is a normal procedure using python. These files with plain text are known as Character Separated Values (CSV) which use a special character to identify the different information that the file contains. Using the pandas library is one of the most common ways to process the information contained in these files.

Here is how you would do it with your file separated with ":"

import pandas as pd
df = pd.read_csv("file.txt", sep = ":", names=['User', 'Option'])

To access the information you will only need to point to the data contained in the dataframe created, like so: y = df['User'][0] This will get you the value in the first row of the column User. To get an output like the one you've presented in your example, you could just use something like: print(df['User'][0] + " requested " + df['Option'][0]) which will return:

391!@ requested Option2

Consider that this way of accessing information is optimized to read multiple lines in a text file. That way, you'll have all the information contained in a dataframe separated in rows and columns.

Processing data like this will avoid you having to loop through the entire file using split


问:
Google Maps Issue Cannot call method 'apply' of undefined?
I have searched all over google for a solution however this seems a new one? I am trying to implement google maps API on a site however I keep getting the following error:

Uncaught TypeError: Cannot call method 'apply' of undefined

My JS is as follows:

```<code>        var map;
        function initialize(location) {
            var mapDiv = document.getElementById('map-canvas');
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066356, 1.102388);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            map = new google.maps.Map(mapDiv, {
                center: latLng,
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location));

        }

        function addMarker(location) {
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066703, 1.113573);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            var marker = new google.maps.Marker({
                position: latLng,
                map: map
            });
        }

        $(document).ready(function () {
            initialize(0);
        });
</code>```

答:
The problem is you're invoking the function addMarker which you should be supplying a callback.  Change your call to the following

```<code>google.maps.event.addDomListener(map, 'tilesloaded', function() { addMarker(location) });
</code>```

Right now you're instead directly invoking addMarker which returns no value.  This means you're effectively passing undefined to the API and the google library is hitting the error attempting to invoke your callback

Body:
I have searched all over google for a solution however this seems a new one? I am trying to implement google maps API on a site however I keep getting the following error:

Uncaught TypeError: Cannot call method 'apply' of undefined

My JS is as follows:

        var map;
        function initialize(location) {
            var mapDiv = document.getElementById('map-canvas');
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066356, 1.102388);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            map = new google.maps.Map(mapDiv, {
                center: latLng,
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location));

        }

        function addMarker(location) {
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066703, 1.113573);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            var marker = new google.maps.Marker({
                position: latLng,
                map: map
            });
        }

        $(document).ready(function () {
            initialize(0);
        });

Body:
The problem is you're invoking the function addMarker which you should be supplying a callback.  Change your call to the following

google.maps.event.addDomListener(map, 'tilesloaded', function() { addMarker(location) });

Right now you're instead directly invoking addMarker which returns no value.  This means you're effectively passing undefined to the API and the google library is hitting the error attempting to invoke your callback


答:
I guess you want to display ....

the slug, price, and time of

the oldest row in the table

that's newer than one day ago

for each slug.

First, get the times of the records you want with this subquery.

```<code>         SELECT MIN(time) time, slug
           FROM items
          WHERE time >= NOW() - INTERVAL 24 HOUR
          GROUP BY slug
</code>```

Then join that subquery to your table like this.

```<code>SELECT items.slug, items.price, items.time
  FROM items
  JOIN (
         SELECT MIN(time) time, slug
           FROM items
          WHERE time >= NOW() - INTERVAL 1 DAY
          GROUP BY slug
       ) h ON items.slug = h.slug AND items.time = h.time
 ORDER BY slug
</code>```

This index will help you make this fast. The server can jump immediately to the relevant rows by time.

```<code>ALTER TABLE CREATE INDEX timeslug (time, slug);
</code>```

Title: How to get a single record per group from one day ago in a very large MySQL table?

Body:
Suppose I have a table containing various types of fruit and vegetables. Once every 5-10 minutes, I am checking the current price of all items I have listed, and I insert a new record for that timestamp with the current price.

The following is an example of such a table (number of rows reduced for readability, but imagine there are entries every 5 minutes for each fruit):

| slug   | price | time                |
+--------+-------+---------------------+
| tomato | 1.5   | 2022-02-05 18:05:00 |
| tomato | 1.5   | 2022-02-05 21:05:00 |
| tomato | 1.55  | 2022-02-06 01:05:00 |
| tomato | 1.7   | 2022-02-06 08:05:00 |
| tomato | 1.65  | 2022-02-06 14:05:00 |
| tomato | 1.63  | 2022-02-07 02:05:00 |
| tomato | 1.69  | 2022-02-07 10:05:00 |
| tomato | 1.7   | 2022-02-07 18:05:00 |
| tomato | 1.49  | 2022-02-08 04:05:00 |
| tomato | 1.58  | 2022-02-08 18:05:00 |
| kiwi   | 0.9   | 2022-02-05 18:05:00 |
| kiwi   | 0.95  | 2022-02-05 21:05:00 |
| kiwi   | 0.81  | 2022-02-06 01:05:00 |
| kiwi   | 1.01  | 2022-02-06 08:05:00 |
| kiwi   | 1.05  | 2022-02-06 14:05:00 |
| kiwi   | 1.1   | 2022-02-07 02:05:00 |
| kiwi   | 1.08  | 2022-02-07 10:05:00 |
| kiwi   | 0.95  | 2022-02-07 18:05:00 |
| kiwi   | 1.04  | 2022-02-08 04:05:00 |
| kiwi   | 1.15  | 2022-02-08 18:05:00 |
| lemon  | 1.69  | 2022-02-05 18:05:00 |
| lemon  | 1.3   | 2022-02-05 21:05:00 |
| lemon  | 1.35  | 2022-02-06 01:05:00 |
| lemon  | 1.35  | 2022-02-06 08:05:00 |
| lemon  | 1.3   | 2022-02-06 14:05:00 |
| lemon  | 1.35  | 2022-02-07 02:05:00 |
| lemon  | 1.41  | 2022-02-07 10:05:00 |
| lemon  | 1.49  | 2022-02-07 18:05:00 |
| lemon  | 1.5   | 2022-02-08 04:05:00 |
| lemon  | 1.49  | 2022-02-08 18:05:00 |

Now, I want to select all items that I have, and show what their price was 24 hours ago. Using the following query, I can fetch a single entry per each such item that matches the "1 day ago" criteria:

SELECT slug, price, time
FROM items
WHERE time >= NOW() - INTERVAL 1 DAY
GROUP BY slug

The problem, however, is that over time the size of the table increases substantially, and this query, that used to take a fraction of a second, now takes 5-10 seconds (in my current table I have roughly 9 million records like these, with some additional columns of course).

Is there a more optimal way to execute this?

Body:
I guess you want to display ....

the slug, price, and time of

the oldest row in the table

that's newer than one day ago

for each slug.

First, get the times of the records you want with this subquery.

         SELECT MIN(time) time, slug
           FROM items
          WHERE time >= NOW() - INTERVAL 24 HOUR
          GROUP BY slug

Then join that subquery to your table like this.

SELECT items.slug, items.price, items.time
  FROM items
  JOIN (
         SELECT MIN(time) time, slug
           FROM items
          WHERE time >= NOW() - INTERVAL 1 DAY
          GROUP BY slug
       ) h ON items.slug = h.slug AND items.time = h.time
 ORDER BY slug

This index will help you make this fast. The server can jump immediately to the relevant rows by time.

ALTER TABLE CREATE INDEX timeslug (time, slug);


问:
Selenium Exception NoSuchElementException: Unable to locate element: {"method":"xpath","selector":
When running this code after making changes form find_element_by_xpath to find_element(By.XPATH I am now encountering an error of not be able to locate the element.</p>
```<code>        search_btn = self.driver.find_element(By.XPATH, "//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]")
        time.sleep(4)
        search_btn.click()
        time.sleep(5)
'''
DevTools listening on ws://127.0.0.1:63724/devtools/browser/c4f952a3-afd0-4074-8aaf-452394b3300d
[22840:23968:0212/182455.570:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[22840:23968:0212/182455.570:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[22840:23968:0212/182455.571:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[22840:19460:0212/182455.579:ERROR:device_event_log_impl.cc(214)] [18:24:55.579] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[22840:19460:0212/182455.587:ERROR:device_event_log_impl.cc(214)] [18:24:55.587] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[22840:23968:0212/182455.590:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
Traceback (most recent call last):
  File "C:\!!!Angela\Paid screen scraper\data scraping\data scraping\my_ui_scrapy12.py", line 277, in show_page
    search_btn = self.driver.find_element(
  File "C:\Users\vwalt_000\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\vwalt_000\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Users\vwalt_000\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]"}
  (Session info: chrome=98.0.4758.82)
</code>```

答:
The exception message is quite clear:

NoSuchElementException

Have you tried your XPATH - if it gives exactly the right element?

For now it looks like:

//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]

Much better will be depicted for which exactly element has such id, like:

//button[@id='id-name']

And try to omit

div[3]/button[2]

if more elements (like more buttons) will be added your XPATH fails.

Also, it could be that this element hasn't been loaded yet. You could add explicit wait.

UPDATE:

For processing Xpath locators from page you able to use extension for Firefox browser:

FirePath

Xpath Checker

You could use the browser's console for it as well.

Body:
When running this code after making changes form find_element_by_xpath to find_element(By.XPATH I am now encountering an error of not be able to locate the element.

        search_btn = self.driver.find_element(By.XPATH, "//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]")
        time.sleep(4)
        search_btn.click()
        time.sleep(5)
'''
DevTools listening on ws://127.0.0.1:63724/devtools/browser/c4f952a3-afd0-4074-8aaf-452394b3300d
[22840:23968:0212/182455.570:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[22840:23968:0212/182455.570:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[22840:23968:0212/182455.571:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[22840:19460:0212/182455.579:ERROR:device_event_log_impl.cc(214)] [18:24:55.579] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[22840:19460:0212/182455.587:ERROR:device_event_log_impl.cc(214)] [18:24:55.587] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[22840:23968:0212/182455.590:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
Traceback (most recent call last):
  File "C:\!!!Angela\Paid screen scraper\data scraping\data scraping\my_ui_scrapy12.py", line 277, in show_page
    search_btn = self.driver.find_element(
  File "C:\Users\vwalt_000\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\vwalt_000\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Users\vwalt_000\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]"}
  (Session info: chrome=98.0.4758.82)


问:
io_uring_queue_init permission denied
I've updated my fedora linux with dnf update to kernel version Linux 5.16.7-200.fc35.x86_64 x86_64 and am now getting a EPERM/permission denied error for a call to io_uring_queue_init, even when calling my program as root.

I am at a total loss, is this a bug in the kernel build or do I need to add some init code?

答:
It was selinux, I solved it by disabling selinux.

The upgrade came with kernel 5.16:

https://www.phoronix.com/scan.php?page=news_item&px=SELinux-IO_uring-Linux-5.16

Title: io_uring_queue_init permission denied


问:
updating Map values in array flutter Firebase
here is the map and the vlaue im trying to update

the problem is when i try to update the imageUrl , the whole Map replacing with only ImageUrl new value
like this

what i want is to update imageUrl only , not effecting other data

this is what i do but not work

```<code>FirebaseFirestore.instance.collection('oorders').doc('MyDocId')
                                 .update({ 'items.0.imageUrl'    :  'new image Url' });
</code>```

答:
From the provided Firestore Database structure it is clear that you are trying to update an element inside an array field in a Firestore document. But currently Firestore doesn't have the ability to update an existing element in an indexed array. It supports only two methods, arrayUnion() to add an element and arrayRemove() to remove an element from the array as mentioned in the documentation.

So if you try to do something like the following -

```<code>FirebaseFirestore.instance
    .collection('oorders')
    .doc('MyDocId')
    .update({'items.0.imageUrl': 'new image Url'});
</code>```

it will delete the array element items and create another map named items with the field mentioned in the update statement.

As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely. This is an error prone and tedious process. You can have a look at this article to know more about it.

I am not sure of your use case, but it seems you can make your database structure more suitable by using maps(nested objects) instead of arrays. Something like this -

By doing this you can update the nested objects by dot notation as mentioned here which will update only the mentioned field without deleting the other fields. The sample to update the document will look like this -

```<code>   var item = 'item1';
   var propertyToBeUpdated = 'imageUrl';
   var newImageUrl = 'New image Url';
   FirebaseFirestore.instance
       .collection('collectionId')
       .doc('documentId')
       .update({'items.$item.$propertyToBeUpdated': newImageUrl});
</code>```

Body:
here is the map and the vlaue im trying to update

the problem is when i try to update the imageUrl , the whole Map replacing with only ImageUrl new value
like this

what i want is to update imageUrl only , not effecting other data

this is what i do but not work

FirebaseFirestore.instance.collection('oorders').doc('MyDocId')
                                 .update({ 'items.0.imageUrl'    :  'new image Url' });

Body:
From the provided Firestore Database structure it is clear that you are trying to update an element inside an array field in a Firestore document. But currently Firestore doesn't have the ability to update an existing element in an indexed array. It supports only two methods, arrayUnion() to add an element and arrayRemove() to remove an element from the array as mentioned in the documentation.

So if you try to do something like the following -

FirebaseFirestore.instance
    .collection('oorders')
    .doc('MyDocId')
    .update({'items.0.imageUrl': 'new image Url'});

it will delete the array element items and create another map named items with the field mentioned in the update statement.

As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely. This is an error prone and tedious process. You can have a look at this article to know more about it.

I am not sure of your use case, but it seems you can make your database structure more suitable by using maps(nested objects) instead of arrays. Something like this -

By doing this you can update the nested objects by dot notation as mentioned here which will update only the mentioned field without deleting the other fields. The sample to update the document will look like this -

   var item = 'item1';
   var propertyToBeUpdated = 'imageUrl';
   var newImageUrl = 'New image Url';
   FirebaseFirestore.instance
       .collection('collectionId')
       .doc('documentId')
       .update({'items.$item.$propertyToBeUpdated': newImageUrl});


问:
Mysql Join AND SUM
Please look to this picture

http://i.stack.imgur.com/A2RB2.jpg

i want to get

sum of money in table come

sum of money in table leave

inner join  emp using id

Thats my query

```<code>SELECT uid,SUM(money) FROM come
INNER JOIN emp ON(come.uid = emp.id)
WHERE emp.statue=1
GROUP BY come.uid
UNION
SELECT uid,SUM(money) FROM `leave`
INNER JOIN emp ON ( leave.uid = emp.id )
GROUP BY leave.uid
</code>```

and the result was this image

http://i.stack.imgur.com/xZtO3.jpg

答:
Another way to do it (not tested, so let me know if it blows up):

```<code>SELECT emp.id, IF(emp.statue=1, c.sumCome, 0) AS sumCome, l.sumLeave
FROM emp
     LEFT JOIN (SELECT uid, SUM(money) AS sumCome
                FROM come
                GROUP BY uid
               ) c ON emp.id = c.uid
     LEFT JOIN (SELECT uid, SUM(money) AS sumLeave
                FROM leave
                GROUP BY uid
               ) l ON emp.id = l.uid
</code>```

I don't know which'll be faster compared to Kevin's. You might want to explain them both and see.

Title: Mysql Join AND SUM

Body:
Please look to this picture

http://i.stack.imgur.com/A2RB2.jpg

i want to get

sum of money in table come

sum of money in table leave

inner join  emp using id

Thats my query

SELECT uid,SUM(money) FROM come
INNER JOIN emp ON(come.uid = emp.id)
WHERE emp.statue=1
GROUP BY come.uid
UNION
SELECT uid,SUM(money) FROM `leave`
INNER JOIN emp ON ( leave.uid = emp.id )
GROUP BY leave.uid

and the result was this image

http://i.stack.imgur.com/xZtO3.jpg

Body:
Another way to do it (not tested, so let me know if it blows up):

SELECT emp.id, IF(emp.statue=1, c.sumCome, 0) AS sumCome, l.sumLeave
FROM emp
     LEFT JOIN (SELECT uid, SUM(money) AS sumCome
                FROM come
                GROUP BY uid
               ) c ON emp.id = c.uid
     LEFT JOIN (SELECT uid, SUM(money) AS sumLeave
                FROM leave
                GROUP BY uid
               ) l ON emp.id = l.uid

I don't know which'll be faster compared to Kevin's. You might want to explain them both and see.


问:
How to login into Twitter once and then open twitter links without getting login interrupt?
I am working on a Twitter bot. What twitter bot do is as follows:
First of all, bot will open twitter.com and will login to Twitter.
1- Bot uses an excel file having hundreds of links.(provided to bot)
2- Bot reads the first link and opens it in the tab but the problem is that I am opening the new link with this command: driver.get(link)
It opens a new browser and it needs to login again as previous browser gets closed and new opens every time bot reads a new link from the file. I want to add such a functionality in the code that it login once and then work for all the links and don't ask to login again and again.
This is the code part that I am currently using after just logging in once.

```<code>with open('link.csv') as csvfile:
csvReader = csv.reader(csvfile, delimiter=',')
for row in csvReader:
    link = row[0]
    comment_no = row[1]
    driver.get(link)
    driver.maximize_window()
    driver.implicitly_wait(2)

    # reply button
    driver.find_element_by_xpath("//div[@aria-label='Reply']").click()

    driver.implicitly_wait(2)

    #message box
    message_box = driver.find_element_by_xpath(
        '//div[@class="public-DraftStyleDefault-block public-DraftStyleDefault-ltr"]')
    message_box.send_keys(answers_list[int(comment_no)])

    tweet_button = driver.find_element_by_xpath("//div[@data-testid='toolBar']//div[2]//div[2]//div[1]")
    tweet_button.click()
    time.sleep(0.5)
</code>```

If anybody have any solution, Please come forward. Thank You!

答:
This is because of selenium uses empty profile. You need to load profile to your selenium.

Thats the example for Chrome:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Path") #Path mean your chrome profile
driver = webdriver.Chrome(executable_path="C:\\Users\\chromedriver.exe", chrome_options=options)
</code>```

Maybe you need to use "r" before "user-data-dir=C:\\Path"

Body:
I am working on a Twitter bot. What twitter bot do is as follows:
First of all, bot will open twitter.com and will login to Twitter.
1- Bot uses an excel file having hundreds of links.(provided to bot)
2- Bot reads the first link and opens it in the tab but the problem is that I am opening the new link with this command: driver.get(link)
It opens a new browser and it needs to login again as previous browser gets closed and new opens every time bot reads a new link from the file. I want to add such a functionality in the code that it login once and then work for all the links and don't ask to login again and again.
This is the code part that I am currently using after just logging in once.

with open('link.csv') as csvfile:
csvReader = csv.reader(csvfile, delimiter=',')
for row in csvReader:
    link = row[0]
    comment_no = row[1]
    driver.get(link)
    driver.maximize_window()
    driver.implicitly_wait(2)

    # reply button
    driver.find_element_by_xpath("//div[@aria-label='Reply']").click()

    driver.implicitly_wait(2)

    #message box
    message_box = driver.find_element_by_xpath(
        '//div[@class="public-DraftStyleDefault-block public-DraftStyleDefault-ltr"]')
    message_box.send_keys(answers_list[int(comment_no)])

    tweet_button = driver.find_element_by_xpath("//div[@data-testid='toolBar']//div[2]//div[2]//div[1]")
    tweet_button.click()
    time.sleep(0.5)

If anybody have any solution, Please come forward. Thank You!

Body:
This is because of selenium uses empty profile. You need to load profile to your selenium.

Thats the example for Chrome:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Path") #Path mean your chrome profile
driver = webdriver.Chrome(executable_path="C:\\Users\\chromedriver.exe", chrome_options=options)

Maybe you need to use "r" before "user-data-dir=C:\\Path"


问:
Extract the last word from the first line
I want to capture the last word from the first line only not including the subsequent lines. I have the pattern below but it captures all the last words from all lines…

Here’s my pattern: https://regex101.com/r/pgU14C/1

```<code>Data:
*A* abcd efgh ijkl         Word
djdjfjfjfjfjfkfkfkfk       agjfj
gjfjfjfjfkfkffk            sjfjfj

Desired Match: Word
</code>```

答:
Just delete the global flag and u will get ur desired output:

```<code>/\w+$/m
</code>```

Body:
I want to capture the last word from the first line only not including the subsequent lines. I have the pattern below but it captures all the last words from all lines…

Here’s my pattern: https://regex101.com/r/pgU14C/1

Data:
*A* abcd efgh ijkl         Word
djdjfjfjfjfjfkfkfkfk       agjfj
gjfjfjfjfkfkffk            sjfjfj

Desired Match: Word

Body:
Just delete the global flag and u will get ur desired output:

/\w+$/m


问:
check if scrollbar is visible with virtual dom
So I was reading the solution here: https://stackoverflow.com/Questions/4814398/how-can-i-check-if-a-scrollbar-is-visible

This is what I am going with...

```<code>function hasScrollbar() {
    console.log(
        "hasScrollbar:",
        document.body.scrollHeight > document.body.clientHeight
    );
    return document.body.scrollHeight > document.body.clientHeight;
}
</code>```
```<code><div
    className="landing-top"
    style={{ paddingRight: hasScrollbar() ? "0px" : `${scrollBarWidth}px` }}
></div>
</code>```

However, because of reacts virtual dom, it doesn't seem to be reading it correctly...

Does anyone have any ideas?

答:
For some unknown reason this didn't work when I tried it before, but it is working now...

```<code>const [isScrollBarVisible, setIsScrollBarVisible] = useState(false);
</code>```
```<code>function hasScrollbar() {
  return document.body.scrollHeight > document.body.clientHeight;
}
</code>```
```<code>useEffect(() => {
  setIsScrollBarVisible(hasScrollbar());
}, [isLoadingData, isSearchingData, searchText]);
</code>```
```<code><div
  className="landing-top"
  style={{ paddingRight: isScrollBarVisible ? '0px' : `${scrollBarWidth}px` }}
>...more html elements here...</div>
</code>```

I think all I ended up doing to fix it was restarting the server. Very weird, but this is working now.

Body:
So I was reading the solution here: https://stackoverflow.com/Questions/4814398/how-can-i-check-if-a-scrollbar-is-visible

This is what I am going with...

function hasScrollbar() {
    console.log(
        "hasScrollbar:",
        document.body.scrollHeight > document.body.clientHeight
    );
    return document.body.scrollHeight > document.body.clientHeight;
}

<div
    className="landing-top"
    style={{ paddingRight: hasScrollbar() ? "0px" : `${scrollBarWidth}px` }}
>

However, because of reacts virtual dom, it doesn't seem to be reading it correctly...

Does anyone have any ideas?

Body:
For some unknown reason this didn't work when I tried it before, but it is working now...

const [isScrollBarVisible, setIsScrollBarVisible] = useState(false);

function hasScrollbar() {
  return document.body.scrollHeight > document.body.clientHeight;
}

useEffect(() => {
  setIsScrollBarVisible(hasScrollbar());
}, [isLoadingData, isSearchingData, searchText]);

<div
  className="landing-top"
  style={{ paddingRight: isScrollBarVisible ? '0px' : `${scrollBarWidth}px` }}
>...more html elements here...</div>

I think all I ended up doing to fix it was restarting the server. Very weird, but this is working now.


问:
How to write to MongoDB asynchronously with Apache Camel
I'd like to know if it is possible to write to MongoDB with Apache Camel and choose to write asynchronously. I've seen no reference for the MongoDB Java Reactive Streams Driver, but I'd like to know if there's also an option of writing to MongoDB with Apache Camel with the Reactive driver (for Project Reactor users).</p>

答:
The MongoDB producer Apache Camel component uses the Sync - MongoDB Java Driver by default.

A component in Apache Camel runs as is and cannot be modified unless through a predefined set of configuration options.

To achieve multi-threading, you can decouple the continuation of message routing from consuming thread using the Threads EIP patten:

```<code>from("direct:operation")
    .threads(1)
    .to("mongodb:myDb?database=someDb&collection=someCollection&operation=save")
</code>```

You can read more on the supported options in the documentation.

Body:
The MongoDB producer Apache Camel component uses the Sync - MongoDB Java Driver by default.

A component in Apache Camel runs as is and cannot be modified unless through a predefined set of configuration options.

To achieve multi-threading, you can decouple the continuation of message routing from consuming thread using the Threads EIP patten:

from("direct:operation")
    .threads(1)
    .to("mongodb:myDb?database=someDb&collection=someCollection&operation=save")

You can read more on the supported options in the documentation.