问:
Flutter StreamBuilder's snapshot does not have date despite sending it -- snapshot.data always set to initialData
In this (small part of a app I'm building) I have a row of buttons which uses streams to select a behaviour (namely a time range to display data), that's working without problem. Then I want to change the selected action by setting the button color to say Colors.red. For this I use a Stream that take a value for a pressed button to rebuild the row of buttons with the appropriate colour.

For an unknown reason the snapshot.data is equal to initialData: whatever button I pressed. I checked that the stream value is the added value, and in order to make the StreamController behaves correctly I then replace the snapshot.data test by a test on var data = stream.listen((x) => data = x) and that works.

I just do not understand what's happening

flutter doctor  -v
[✓] Flutter (Channel stable, v1.17.2, on Mac OS X 10.15.4 19E287, locale en-FR)
    • Flutter version 1.17.2 at /usr/local/flutter
    • Framework revision 5f21edf8b6 (4 days ago), 2020-05-28 12:44:12 -0700
    • Engine revision b851c71829
    • Dart version 2.8.3

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/jfb/Library/Android/sdk
    • Platform android-29, build-tools 28.0.3
    • Java binary at: /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_242-b08)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.4.1, Build version 11E503a
    • CocoaPods version 1.9.1

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).

[✓] Connected device (1 available)

    • iPhone 11 • 17CF5871-B9F8-4739-B8BB-607807AD0530 • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-4 (simulator)

! Doctor found issues in 1 category.

Code of this part :

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:weight_trend/blocs/bloc_provider.dart';
import 'package:weight_trend/blocs/chart_bloc.dart';

var myStream = StreamController<int>.broadcast();
Stream stream = myStream.stream;
var data;  // normally should use snapshot.data

class ChartRangeSelectionButtons extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: myStream.stream,
      initialData: 2,
      builder: (context, snapshot) {
        myStream.stream.listen((x) => data = x);
        print(snapshot.data);
        if (data == 1) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W', buttonColor: Colors.red),
              ChartButton(title: '2W'),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 2) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W', buttonColor: Colors.red),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 3) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W'),
              ChartButton(title: '3W', buttonColor: Colors.red),
              ChartButton(title: '4W'),
            ],
          );
        } else {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(
                title: '1W',
              ),
              ChartButton(
                title: '2W',
              ),
              ChartButton(title: '3W'),
              ChartButton(title: '4W', buttonColor: Colors.red),
            ],
          );
        }
      },
    );
  }
}

class ChartButton extends StatelessWidget {
  const ChartButton({this.title, this.buttonColor = Colors.white});
  final String title;
  final buttonColor;
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 60,
      child: RaisedButton(
        onPressed: () {
          if (title == '1W') {
            BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.one);
            myStream.sink.add(1);
          } else if (title == '2W') {
            BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.two);
            myStream.sink.add(2);
          } else if (title == '3W') {
            BlocProvider.of<ChartBloc>(context)
                .inputEvent
                .add(ChartRange.three);
            myStream.sink.add(3);
          } else if (title == '4W') {
            BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.four);
            myStream.sink.add(4);
          }
        },
        color: buttonColor,
        textColor: Colors.black,
        splashColor: Colors.grey.shade400,
        child: Text(title),
      ),
    );
  }
}
</code>```

答:
I have made a simple example using your code and it seems to work ok:

```<code>2
2
3
1
</code>```

Why are You using Bloc? It seems to me overkill for this type of things.
Just start simple.

```<code>import 'package:flutter/material.dart';
import "dart:async";

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ChartRangeSelectionButtons(),
        ),
      ),
    );
  }
}

var myStream = StreamController<int>.broadcast();
Stream stream = myStream.stream;
var data;  // normally should use snapshot.data

class ChartRangeSelectionButtons extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: myStream.stream,
      initialData: 2,
      builder: (context, snapshot) {
        //myStream.stream.listen((x) => data = x);
        print(snapshot.data);
        if (data == 1) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W', buttonColor: Colors.red),
              ChartButton(title: '2W'),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 2) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W', buttonColor: Colors.red),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 3) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W'),
              ChartButton(title: '3W', buttonColor: Colors.red),
              ChartButton(title: '4W'),
            ],
          );
        } else {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(
                title: '1W',
              ),
              ChartButton(
                title: '2W',
              ),
              ChartButton(title: '3W'),
              ChartButton(title: '4W', buttonColor: Colors.red),
            ],
          );
        }
      },
    );
  }
}

class ChartButton extends StatelessWidget {
  const ChartButton({this.title, this.buttonColor = Colors.white});
  final String title;
  final buttonColor;
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 60,
      child: RaisedButton(
        onPressed: () {
          if (title == '1W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.one);
            myStream.sink.add(1);
          } else if (title == '2W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.two);
            myStream.sink.add(2);
          } else if (title == '3W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.three);
            myStream.sink.add(3);
          } else if (title == '4W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.four);
            myStream.sink.add(4);
          }
        },
        color: buttonColor,
        textColor: Colors.black,
        splashColor: Colors.grey.shade400,
        child: Text(title),
      ),
    );
  }
}
</code>```

Body:
In this (small part of a app I'm building) I have a row of buttons which uses streams to select a behaviour (namely a time range to display data), that's working without problem. Then I want to change the selected action by setting the button color to say Colors.red. For this I use a Stream that take a value for a pressed button to rebuild the row of buttons with the appropriate colour.

For an unknown reason the snapshot.data is equal to initialData: whatever button I pressed. I checked that the stream value is the added value, and in order to make the StreamController behaves correctly I then replace the snapshot.data test by a test on var data = stream.listen((x) => data = x) and that works.

I just do not understand what's happening

flutter doctor  -v
[✓] Flutter (Channel stable, v1.17.2, on Mac OS X 10.15.4 19E287, locale en-FR)
    • Flutter version 1.17.2 at /usr/local/flutter
    • Framework revision 5f21edf8b6 (4 days ago), 2020-05-28 12:44:12 -0700
    • Engine revision b851c71829
    • Dart version 2.8.3

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/jfb/Library/Android/sdk
    • Platform android-29, build-tools 28.0.3
    • Java binary at: /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_242-b08)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.4.1, Build version 11E503a
    • CocoaPods version 1.9.1

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).

[✓] Connected device (1 available)

    • iPhone 11 • 17CF5871-B9F8-4739-B8BB-607807AD0530 • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-4 (simulator)

! Doctor found issues in 1 category.

Code of this part :

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:weight_trend/blocs/bloc_provider.dart';
import 'package:weight_trend/blocs/chart_bloc.dart';

var myStream = StreamController<int>.broadcast();
Stream stream = myStream.stream;
var data;  // normally should use snapshot.data

class ChartRangeSelectionButtons extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: myStream.stream,
      initialData: 2,
      builder: (context, snapshot) {
        myStream.stream.listen((x) => data = x);
        print(snapshot.data);
        if (data == 1) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W', buttonColor: Colors.red),
              ChartButton(title: '2W'),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 2) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W', buttonColor: Colors.red),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 3) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W'),
              ChartButton(title: '3W', buttonColor: Colors.red),
              ChartButton(title: '4W'),
            ],
          );
        } else {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(
                title: '1W',
              ),
              ChartButton(
                title: '2W',
              ),
              ChartButton(title: '3W'),
              ChartButton(title: '4W', buttonColor: Colors.red),
            ],
          );
        }
      },
    );
  }
}

class ChartButton extends StatelessWidget {
  const ChartButton({this.title, this.buttonColor = Colors.white});
  final String title;
  final buttonColor;
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 60,
      child: RaisedButton(
        onPressed: () {
          if (title == '1W') {
            BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.one);
            myStream.sink.add(1);
          } else if (title == '2W') {
            BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.two);
            myStream.sink.add(2);
          } else if (title == '3W') {
            BlocProvider.of<ChartBloc>(context)
                .inputEvent
                .add(ChartRange.three);
            myStream.sink.add(3);
          } else if (title == '4W') {
            BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.four);
            myStream.sink.add(4);
          }
        },
        color: buttonColor,
        textColor: Colors.black,
        splashColor: Colors.grey.shade400,
        child: Text(title),
      ),
    );
  }
}

Body:
I have made a simple example using your code and it seems to work ok:

2
2
3
1

Why are You using Bloc? It seems to me overkill for this type of things.
Just start simple.

import 'package:flutter/material.dart';
import "dart:async";

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ChartRangeSelectionButtons(),
        ),
      ),
    );
  }
}

var myStream = StreamController<int>.broadcast();
Stream stream = myStream.stream;
var data;  // normally should use snapshot.data

class ChartRangeSelectionButtons extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: myStream.stream,
      initialData: 2,
      builder: (context, snapshot) {
        //myStream.stream.listen((x) => data = x);
        print(snapshot.data);
        if (data == 1) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W', buttonColor: Colors.red),
              ChartButton(title: '2W'),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 2) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W', buttonColor: Colors.red),
              ChartButton(title: '3W'),
              ChartButton(title: '4W'),
            ],
          );
        } else if (data == 3) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(title: '1W'),
              ChartButton(title: '2W'),
              ChartButton(title: '3W', buttonColor: Colors.red),
              ChartButton(title: '4W'),
            ],
          );
        } else {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              ChartButton(
                title: '1W',
              ),
              ChartButton(
                title: '2W',
              ),
              ChartButton(title: '3W'),
              ChartButton(title: '4W', buttonColor: Colors.red),
            ],
          );
        }
      },
    );
  }
}

class ChartButton extends StatelessWidget {
  const ChartButton({this.title, this.buttonColor = Colors.white});
  final String title;
  final buttonColor;
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 60,
      child: RaisedButton(
        onPressed: () {
          if (title == '1W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.one);
            myStream.sink.add(1);
          } else if (title == '2W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.two);
            myStream.sink.add(2);
          } else if (title == '3W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.three);
            myStream.sink.add(3);
          } else if (title == '4W') {
            //BlocProvider.of<ChartBloc>(context).inputEvent.add(ChartRange.four);
            myStream.sink.add(4);
          }
        },
        color: buttonColor,
        textColor: Colors.black,
        splashColor: Colors.grey.shade400,
        child: Text(title),
      ),
    );
  }
}


来源: stackexchange

问:
how to make deb file install other deb files without errors?
I created a local repository. Than i make a 2 debian files, a batman.deb file that have for dependency base.deb

Control file:

```<code>Package: batman
Version: 1.0
Architecture: all
Essential: no
Priority: optional
Depends: base
Maintainer: monkeyproduction
Description: test description
</code>```

postinst file:

```<code>apt-get -f install
</code>```

So i use postinst file to check for dependencies that need to be installed.

The problem is that i get those errors:

```<code>E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
dpkg: error processing package base (--configure):
 installed base package post-installation script subprocess returned error exit status 100
dpkg: dependency problems prevent configuration of batman:
 batman depends on base; however:
  Package base is not configured yet.

dpkg: error processing package batman (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 base
 batman
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

How other installs do it without error? I mean when i try to install some package it says that it needs 10 other dependencies and the installation of them is going without those messages that i get.
How can i fix mine ones and make it clean install without errors?

答:
removed my apt-get -f install

apparently Depends: base is the only think that i need to have in my batman.deb control file to download and install base.deb file too

ContentLicense: CC BY-SA 4.0

Body:
I created a local repository. Than i make a 2 debian files, a batman.deb file that have for dependency base.deb

Control file:

Package: batman
Version: 1.0
Architecture: all
Essential: no
Priority: optional
Depends: base
Maintainer: monkeyproduction
Description: test description

postinst file:

apt-get -f install

So i use postinst file to check for dependencies that need to be installed.

The problem is that i get those errors:

E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
dpkg: error processing package base (--configure):
 installed base package post-installation script subprocess returned error exit status 100
dpkg: dependency problems prevent configuration of batman:
 batman depends on base; however:
  Package base is not configured yet.

dpkg: error processing package batman (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 base
 batman
E: Sub-process /usr/bin/dpkg returned an error code (1)

How other installs do it without error? I mean when i try to install some package it says that it needs 10 other dependencies and the installation of them is going without those messages that i get.
How can i fix mine ones and make it clean install without errors?


问:
App Insights Performing a Heartbeat Check to Api Root
I have a .Net Core 3.1 web api.  I added App Insights instrumentation, and now every 15 minutes it is performing a GET to /, which throws a 404.

Is there a way to set this url in the instrumentation configuration in my startup, or is there an option in Azure?

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();
    ...
}
</code>```

I'd rather make it hit an endpoint I specifically stood up for heartbeat checks.

I do know from this document that I could just disable the heartbeat, but I'd rather configure it.

答:
You can filter synthetic requests in Application Insights via a Custom Telemetry Processor.

Or you could just put an empty index.html at root level if you want to get rid of the 404.

Hope that helps,
Andreas

Body:
I have a .Net Core 3.1 web api.  I added App Insights instrumentation, and now every 15 minutes it is performing a GET to /, which throws a 404.

Is there a way to set this url in the instrumentation configuration in my startup, or is there an option in Azure?

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();
    ...
}

I'd rather make it hit an endpoint I specifically stood up for heartbeat checks.

I do know from this document that I could just disable the heartbeat, but I'd rather configure it.


问:
What is the least total batch size for SyncBatchNorm
For the normal BatchNorm, the least batch size per GPU is 2.

I wonder if I use the SyncBatchNorm, can I use batch_size=1 for every GPU with more than a single GPU?

I.e, the total_batch_size is more than 1 but batch_size_per_gpu is 1.

I would appreciate answers for any deep learning framework, pytorch, tensorflow, mxnet, etc

答: For PyTorch, using batch_size_per_gpu=1 and more than one GPU is fine.


问:
When the modal is closed go to previous url in React
Having a modal which is rendered when a conditions is fulfilled:

```<code>return this.state.value ? (
  <Modal> ... </Modal>
  ) : ( <div> ... </div>);
</code>```

before the modal is opened the URL is like this: http://myurl.com/items/5ed0c10ce1e24922e4906931, after it is opened it adds a word 'edit' :

http:///myurl.com/products/edit/5ed0c10ce1e24922e4906931

The problem is when I close the modal it remain the longer URL, it doesn't revert to the initial one as it should.

I guess it must be added something in closeModal but don't know what. At the moment there is set open to false (which is set on true while the modal is visible)

```<code>  closeModal = () => {
    this.setState({ open: false });
  };
</code>```

is there a way to get to the previous URL when the modal is closed?

答: You can simply use history.goBack() method from react-router-dom.

Body:
Having a modal which is rendered when a conditions is fulfilled:

return this.state.value ? (
  <Modal> ... </Modal>
  ) : (
 ...
);

before the modal is opened the URL is like this: http://myurl.com/items/5ed0c10ce1e24922e4906931, after it is opened it adds a word 'edit' :

http:///myurl.com/products/edit/5ed0c10ce1e24922e4906931

The problem is when I close the modal it remain the longer URL, it doesn't revert to the initial one as it should.

I guess it must be added something in closeModal but don't know what. At the moment there is set open to false (which is set on true while the modal is visible)

  closeModal = () => {
    this.setState({ open: false });
  };

is there a way to get to the previous URL when the modal is closed?


问:
Laravel Auth simple API always returning Unauthorized 401 error
This is driving me crazy... All is suppossed to be correct and im ALWAYS getting unauthorized error in my API routes!!

Api.php routes:

```<code>Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
</code>```

});

RegisterController:

```<code>    protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'api_token' => Str::random(80),
    ]);
}
</code>```

Database:

Request:

Accept application/json is set:

I tried too using jquery to make the request with a query parameter api_key but it doesnt work either!!

I searched a lot and can't solve this. I have another fresh application with Laravel and auth and it works perfect but this project is old and i recently updated it to Laravel 7 and I don't know why this dont works.

More info:

Im using php artisan serve to serve the application.

My kernel.php:

```<code><?php
</code>```

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

```<code>/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth:api',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'language' => \App\Http\Middleware\GetRequestLanguage::class,
    'setLocale' => \App\Http\Middleware\SetLocale::class,
];

/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\Authenticate::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];
</code>```

}

Thank's you... I hope you can help me...

答:
I found the solution.

When I upgraded from Laravel 6 to 7 I didn't change this in auth.php:

from 'hash' => 'false' to 'hash' => false, without quotes... This nonsense gave me a headache and finally I found that it causes the problem.

```<code>        'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
</code>```

Body:
This is driving me crazy... All is suppossed to be correct and im ALWAYS getting unauthorized error in my API routes!!

Api.php routes:

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();

});

RegisterController:

    protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'api_token' => Str::random(80),
    ]);
}

Database:

Request:

Accept application/json is set:

I tried too using jquery to make the request with a query parameter api_key but it doesnt work either!!

I searched a lot and can't solve this. I have another fresh application with Laravel and auth and it works perfect but this project is old and i recently updated it to Laravel 7 and I don't know why this dont works.

More info:

Im using php artisan serve to serve the application.

My kernel.php:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth:api',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'language' => \App\Http\Middleware\GetRequestLanguage::class,
    'setLocale' => \App\Http\Middleware\SetLocale::class,
];

/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\Authenticate::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];

}

Thank's you... I hope you can help me...

Body:
I found the solution.

When I upgraded from Laravel 6 to 7 I didn't change this in auth.php:

from 'hash' => 'false' to 'hash' => false, without quotes... This nonsense gave me a headache and finally I found that it causes the problem.

        'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],


问:
What data-type is used for images?
I was deriving NDVI (Normalized Difference Vegetation Index), which is a ratio of (NIR-R)/(NIR+R) where NIR is Near-Infrared band and R is Red band. This index ranges from -1 to 1. So I wrote a pyopencl code and here is what I have done and observed.

Python code:

```<code>import pyopencl as cl
import cv2
from PIL import Image
import numpy as np
from time import time
import matplotlib.pyplot as plt

#get kernel file
def getKernel():
    kernel = open('kernel.c').read()
    return kernel

#return images as numpy int32 arrays
def convToArray(im_r,im_nir):
    a = np.asarray(im_r).astype(np.int32)
    b = np.asarray(im_nir).astype(np.int32)

    return a,b

#processing part
def getDerivation(platform,device,im_r,im_nir):

    #setting device
    pltfrm = cl.get_platforms()[platform]
    dev = pltfrm.get_devices()[device]
    cntx = cl.Context([dev])
    queue = cl.CommandQueue(cntx)

    #get 2Darrays
    r,nir = convToArray(im_r,im_nir)

    #shape of array
    x = r.shape[1]

    mf = cl.mem_flags

    bs = time()

    #input images buffer
    inR = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=r)
    inIR = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=nir)

    #output image buffers
    ndvi = cl.Buffer(cntx,mf.WRITE_ONLY,r.nbytes)

    be = time()
    print("Buffering time: " + str(be-bs) + " sec")
    ts = time()

    #load kernel
    task = cl.Program(cntx,getKernel()%(x)).build()

    #execute the process
    task.derive(queue,r.shape,None,inR,inIR,ndvi)

    #create empty buffer to store result
    Vout = np.empty_like(r)

    #dump output buffers to empty arrays
    cl.enqueue_copy(queue,Vout,ndvi)

    te = time()

    #convert arrays to gray - image compatible formate
    NDVI = Vout.astype(np.uint8)

    print("Processing time: " + str(te - ts) + " On: " + pltfrm.name + " --> " + dev.name)

    return NDVI

def process(platform,device,im_r,im_nir):
    NDVI,NDBI,NDWI = getDerivation(platform,device,im_g,im_r,im_nir,im_swir)
    print(NDVI)
    cv2.imshow("NDVI",NDVI)
    cv2.waitKey(0)

if __name__ == '__main__':

    R = cv2.imread("BAND3.jpg",0)
    NIR = cv2.imread("BAND4.jpg",0)

    print(R.dtype) #returns uint8

    process(0,0,R,NIR) #(0,0) is my intel gpu

</code>```

kernel code(C):

```<code>__kernel void derive(__global int* inR,__global int* inIR,__global int* ndvi){

    int x = get_global_id(0);
    int y = get_global_id(1);

    int width = %d;
    int index = x + y*width;

    //ndvi ratio (-1 to 1)

    int a = ((inIR[index] - inR[index])/(inIR[index] + inR[index])) * (256);

    a = (a <   (0) ?   (-1*a)  :   (a));
    a = (a >   (255) ?   (255) :   (a));

    ndvi[index] = (a);

}
</code>```

input image R:

input image NIR:

both the images have bit depth of 8

BUT I GET JUST A BLANK IMAGE. I wrote the result on the command line for debugging reasons initially,
command line output:

```<code>(1151, 1151)
Buffering time: 0.015959739685058594 sec
Processing time: 0.22115755081176758 On: Intel(R) OpenCL --> Intel(R) HD Graphics 520
[[0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 ...
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]]
</code>```

Now what i think is i may not be using proper datatype for the images? also, in the kernel the line ((inIR[index] - inR[index])/(inIR[index] + inR[index])) will gives a float value, which i multiply with 256 to get a pixel value for that respective float value. So is it there the problem? Does any one know where i am going wrong?

Help is much appreciated!

答: Okay ... i got it. I just changed the datatype in the line a = np.asarray(im_r).astype(np.int32) in the function convToArray() to float32 and in the kernel file, i changed the parameter type to float and added  int a = (int)((((float)(inIR[index] - inR[index])/(float)(inIR[index] + inR[index]))+1)*127.5); for the calculation. However, i need an explaination, why this worked and not the other way... I probably can think like, the result what we get after this calculation, int type loses data while conversion from float...is it?

Title: What data-type is used for images?

Body:
I was deriving NDVI (Normalized Difference Vegetation Index), which is a ratio of (NIR-R)/(NIR+R) where NIR is Near-Infrared band and R is Red band. This index ranges from -1 to 1. So I wrote a pyopencl code and here is what I have done and observed.

Python code:

import pyopencl as cl
import cv2
from PIL import Image
import numpy as np
from time import time
import matplotlib.pyplot as plt

#get kernel file
def getKernel():
    kernel = open('kernel.c').read()
    return kernel

#return images as numpy int32 arrays
def convToArray(im_r,im_nir):
    a = np.asarray(im_r).astype(np.int32)
    b = np.asarray(im_nir).astype(np.int32)

    return a,b

#processing part
def getDerivation(platform,device,im_r,im_nir):

    #setting device
    pltfrm = cl.get_platforms()[platform]
    dev = pltfrm.get_devices()[device]
    cntx = cl.Context([dev])
    queue = cl.CommandQueue(cntx)

    #get 2Darrays
    r,nir = convToArray(im_r,im_nir)

    #shape of array
    x = r.shape[1]

    mf = cl.mem_flags

    bs = time()

    #input images buffer
    inR = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=r)
    inIR = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=nir)

    #output image buffers
    ndvi = cl.Buffer(cntx,mf.WRITE_ONLY,r.nbytes)

    be = time()
    print("Buffering time: " + str(be-bs) + " sec")
    ts = time()

    #load kernel
    task = cl.Program(cntx,getKernel()%(x)).build()

    #execute the process
    task.derive(queue,r.shape,None,inR,inIR,ndvi)

    #create empty buffer to store result
    Vout = np.empty_like(r)

    #dump output buffers to empty arrays
    cl.enqueue_copy(queue,Vout,ndvi)

    te = time()

    #convert arrays to gray - image compatible formate
    NDVI = Vout.astype(np.uint8)

    print("Processing time: " + str(te - ts) + " On: " + pltfrm.name + " --> " + dev.name)

    return NDVI

def process(platform,device,im_r,im_nir):
    NDVI,NDBI,NDWI = getDerivation(platform,device,im_g,im_r,im_nir,im_swir)
    print(NDVI)
    cv2.imshow("NDVI",NDVI)
    cv2.waitKey(0)

if __name__ == '__main__':

    R = cv2.imread("BAND3.jpg",0)
    NIR = cv2.imread("BAND4.jpg",0)

    print(R.dtype) #returns uint8

    process(0,0,R,NIR) #(0,0) is my intel gpu

kernel code(C):

__kernel void derive(__global int* inR,__global int* inIR,__global int* ndvi){

    int x = get_global_id(0);
    int y = get_global_id(1);

    int width = %d;
    int index = x + y*width;

    //ndvi ratio (-1 to 1)

    int a = ((inIR[index] - inR[index])/(inIR[index] + inR[index])) * (256);

    a = (a <   (0) ?   (-1*a)  :   (a));
    a = (a >   (255) ?   (255) :   (a));

    ndvi[index] = (a);

}

input image R:

input image NIR:

both the images have bit depth of 8

BUT I GET JUST A BLANK IMAGE. I wrote the result on the command line for debugging reasons initially,
command line output:

(1151, 1151)
Buffering time: 0.015959739685058594 sec
Processing time: 0.22115755081176758 On: Intel(R) OpenCL --> Intel(R) HD Graphics 520
[[0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 ...
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]]

Now what i think is i may not be using proper datatype for the images? also, in the kernel the line ((inIR[index] - inR[index])/(inIR[index] + inR[index])) will gives a float value, which i multiply with 256 to get a pixel value for that respective float value. So is it there the problem? Does any one know where i am going wrong?

Help is much appreciated!


问:
FileNotFoundException: class path resource [FileChangeListener.class] cannot be opened because it does not exist
spring devtools are not included in the fat executable jar which gives this error if we try to run the spring boot jar using "java -jar " command.</p>

答:
Devtools are excluded by default in spring boot project. So we need to prevent that.
The following page contains the detailed answer: Spring DevTools not included in the fat jar packaged with spring-boot-maven-plugin</p>


问:
How are garbage collector (GC) roots stored?
I know how roots are found, but the thing is, (AFAIK) they have to be found at runtime. For that, you'll need a fixed size container that may overflow or a resizable container. I don't want to go with the fixed size container because it would not be easy to tell how much space to reserve (and it may be wasteful). The resizable container seems best, but the problem is, the GC runs when there is not enough space, so the resizable container won't be able to store what it needs to. So with these conditions, how are GC roots stored?</p>

答:
A GC root is a location outside the heap that can contain a reference
to an object inside the heap. A location can be anything that can
store a reference. Usually it is four or eight bytes of memory storing
32 or 64 bit addresses but it can also be a machine register or space
on disk. Sometimes a location is called a "slot" because you can "slot
in" exactly one reference. A classical mark & sweep collector works by
first marking all objects referenced by the roots and then continues
the tracing from there.

Where and how roots are stored depends on the VM and gets very
complicated when you consider things like partial GC, threading and
JITting. But conceptually it's simple. Suppose you have a Python-like
language with only functions and globals and the following code:

```<code> 0: FOO = "hel"
 1: BAR = "hi"
 2: def foo(x):
 3:    y = x + "there"
 4:    <GC HERE>
 5:    return
 6: def bar(x):
 7:    y = x + "lo"
 8:    foo(y)
 9:    return
10: bar(FOO)
11: ...
</code>```

Assume GC happens on the indicated line. The callstack would look
something like this:

```<code>Return address to line 11
Reference to object "hello"
Return address to line 9
Reference to object "hellothere"
</code>```

The GC would scan through this callstack distinguishing between return
addresses and references and marking the objects it finds. Then it
would do the same for global references. They could be stored in a
dictionary (hashmap) on the heap and referenced by a single root:

```<code>{name("FOO") : "hel", name("BAR") : "hi"}
</code>```

Note that the space required for storing all roots is tiny. You only
need eight bytes (one reference) for the globals and eight bytes for
each element on the callstack. You can run out of stack space and get
a stack overflow but with say 256kb preallocated for the stack and
proper tail call optimization it is a non-issue.

Body:
A GC root is a location outside the heap that can contain a reference
to an object inside the heap. A location can be anything that can
store a reference. Usually it is four or eight bytes of memory storing
32 or 64 bit addresses but it can also be a machine register or space
on disk. Sometimes a location is called a "slot" because you can "slot
in" exactly one reference. A classical mark & sweep collector works by
first marking all objects referenced by the roots and then continues
the tracing from there.

Where and how roots are stored depends on the VM and gets very
complicated when you consider things like partial GC, threading and
JITting. But conceptually it's simple. Suppose you have a Python-like
language with only functions and globals and the following code:

 0: FOO = "hel"
 1: BAR = "hi"
 2: def foo(x):
 3:    y = x + "there"
 4:    <GC HERE>
 5:    return
 6: def bar(x):
 7:    y = x + "lo"
 8:    foo(y)
 9:    return
10: bar(FOO)
11: ...

Assume GC happens on the indicated line. The callstack would look
something like this:

Return address to line 11
Reference to object "hello"
Return address to line 9
Reference to object "hellothere"

The GC would scan through this callstack distinguishing between return
addresses and references and marking the objects it finds. Then it
would do the same for global references. They could be stored in a
dictionary (hashmap) on the heap and referenced by a single root:

{name("FOO") : "hel", name("BAR") : "hi"}

Note that the space required for storing all roots is tiny. You only
need eight bytes (one reference) for the globals and eight bytes for
each element on the callstack. You can run out of stack space and get
a stack overflow but with say 256kb preallocated for the stack and
proper tail call optimization it is a non-issue.


问:
How to make dynamic @yield in laravel?
I want to make @yield('dynamic') to load different pages like single page application in laravel.

Route:

```<code>Route::get(
    '/front-office-setup/{setup_type}',
    'AdmissionFrontOfficeSetupController@index'
)->name('frontofficesetupview');
</code>```

Controller:

```<code>public function index($setup_type)
{
    $data['setup_type'] = $setup_type;

    return view('frontoffice::frontofficesetup.frontofficesetup', $data);
}
</code>```

View:

```<code><div class="row">
    <div class="col-md-3">asdf</div>
    <div class="col-md-4">asdf</div>
    <div class="col-md-5"> @yield('{{$setup_type}}')</div>
</div>
</code>```

Section:

```<code>@extends('frontoffice::frontofficesetup.frontofficesetup')
@section('visitor-purpose')
sdfasd
@endsection
</code>```

But it doesn't render or show in @yield('{{$setup_type}}')

Is there any way to do this?

Edit part*
Also i have already included a @yield type of things in view file

```<code>@extends('backend.master.master')
@section('content')
<div class="row">
    <div class="col-md-3">asdf</div>
    <div class="col-md-4">asdf</div>
    <div class="col-md-5"> @yield($setup_type)</div>
</div>
@endsection
</code>```

答: @yield is already started PHP tag <?php. SO no need to mention braces again{{}}. Simply try @yield($setup_type) It will work perfectly.

Title: How to make dynamic @yield in laravel?

Body:
I want to make @yield('dynamic') to load different pages like single page application in laravel.

Route:

Route::get(
    '/front-office-setup/{setup_type}',
    'AdmissionFrontOfficeSetupController@index'
)->name('frontofficesetupview');

Controller:

public function index($setup_type)
{
    $data['setup_type'] = $setup_type;

    return view('frontoffice::frontofficesetup.frontofficesetup', $data);
}

View:

asdf

asdf

 @yield('{{$setup_type}}')

Section:

@extends('frontoffice::frontofficesetup.frontofficesetup')
@section('visitor-purpose')
sdfasd
@endsection

But it doesn't render or show in @yield('{{$setup_type}}')

Is there any way to do this?

Edit part*
Also i have already included a @yield type of things in view file

@extends('backend.master.master')
@section('content')

asdf

asdf

 @yield($setup_type)

@endsection


问:
Multiple files creation in C with specific path
I am working on something where I need to create multiple files say 10 files in a specific path. I achieved it by below code

```<code>int index = 0;
    char filename[6];

    while(index < 10) {
        sprintf(filename, "%s_%d", "data",index);
        FILE *fp = fopen (filename, "w");
        index++;
    }
</code>```

Here variable filename is used as file name but this creates all 10 files in the root directory where my code is placed. I have to create files in different directory lets say Desktop

```<code>FILE *fp = fopen ("Desktop\filename", "w");
</code>```

this creates only one file in desktop and if i loop the same with above snippet it creates 10 files of same name which indeed finally one file only.

```<code>  while(index < 10) {
        sprintf(filename, "%s_%d", "data",index);
        FILE *fp = fopen ("Desktop\filename", "w");
        index++;
    }
</code>```

which creates 10 files with hardcoded filename i.e. it is not taking my filename variable value.

How to achieve this to create multiple files with specific directory ?

答:
How to achieve this to create multiple files with specific directory ?

Just prepend your directory path to the variable.

```<code> char filename[2000];
 for (int i = 0; i < 10; ++i) {
      snprintf(filename, sizeof(filename), "Desktop\\filename\\data_%d", i);
      FILE *f = fopen(filename, "w");
      if (f != NULL) {
         fclose(f);
      }
 }
</code>```

Body:
I am working on something where I need to create multiple files say 10 files in a specific path. I achieved it by below code

int index = 0;
    char filename[6];

    while(index < 10) {
        sprintf(filename, "%s_%d", "data",index);
        FILE *fp = fopen (filename, "w");
        index++;
    }

Here variable filename is used as file name but this creates all 10 files in the root directory where my code is placed. I have to create files in different directory lets say Desktop

FILE *fp = fopen ("Desktop\filename", "w");

this creates only one file in desktop and if i loop the same with above snippet it creates 10 files of same name which indeed finally one file only.

  while(index < 10) {
        sprintf(filename, "%s_%d", "data",index);
        FILE *fp = fopen ("Desktop\filename", "w");
        index++;
    }

which creates 10 files with hardcoded filename i.e. it is not taking my filename variable value.

How to achieve this to create multiple files with specific directory ?

Body:
How to achieve this to create multiple files with specific directory ?

Just prepend your directory path to the variable.

 char filename[2000];
 for (int i = 0; i < 10; ++i) {
      snprintf(filename, sizeof(filename), "Desktop\\filename\\data_%d", i);
      FILE *f = fopen(filename, "w");
      if (f != NULL) {
         fclose(f);
      }
 }


问:
apollo-client used to make multiple requests to make a real-time search
We're developing a search engine inside an app with Apollo and we do not know exactly how to develop a real-time search engine that makes a request to the server on every keyboard press.

On the documentation it says that we must use the new <Query /> component, but I see that this case mostly fits with firing a manual query: https://www.apollographql.com/docs/react/essentials/queries.html#manual-query

I don't know if I'm correct, or maybe we should use it in another way.

thanks!

答:
UPDATE

With Apollo Client V2.6, it is now possible to make a Query to the server manually using a hook. The hook that you want is useLazyQuery.

You'd have something like this;

const [onSearch, { called, loading, data }] = useLazyQuery(
    SEARCH_QUERY,
    { variables: { searchText: state.searchText } }
  );
```

<p>Then you can call the <code>onSearch</code> function whenever your text changes inside a <code>useEffect</code> like below. </p>

```useEffect(() => {
onSearch()
}, [state.searchText])
```

Note that you might want to dounce your onSearch function such that you don't hammer your server on every key stroke.

Body:
UPDATE

With Apollo Client V2.6, it is now possible to make a Query to the server manually using a hook. The hook that you want is useLazyQuery.

You'd have something like this;

const [onSearch, { called, loading, data }] = useLazyQuery(
    SEARCH_QUERY,
    { variables: { searchText: state.searchText } }
  );

Then you can call the onSearch function whenever your text changes inside a useEffect like below.

useEffect(() => {
onSearch()
}, [state.searchText])

Note that you might want to dounce your onSearch function such that you don't hammer your server on every key stroke.


问:
If Statement with Multiple Conditions vs Individual If Statements
I would like to check each condition and return if true.

Is it better to have:

1. Multiple conditions in a single if statement?

```<code>if (string.IsNullOrEmpty(myStr) ||
    myBool == true ||
    myList.Count == 0)
{
    return;
}
</code>```

2. Or multiple if statements, each checking a different condition.

```<code>if (string.IsNullOrEmpty(myStr))
{
    return;
}

if (myBool == true)
{
    return;
}

if (myList.Count == 0)
{
    return;
}
</code>```

If myStr is Empty.

My thought is that the first way checks all 3 conditions before it reaches the return (or does it)?

And the second way only has to check the 1st condition string.IsNullOrEmpty, reaches the return, and doesn't have to process the other 2 condition checks below it.

Or does the compiler optimize the code to work most efficient no matter how the source is written?

答:
It's a matter of preference really, as both will result in the same overall performance.  Both are equivalent to each other.  By default, C# uses short-circuit evaluation, meaning the if statement will stop as soon as it finds an expression that evaluates to true.  Most of the time, I've seen it written as a single if statement, but separate checks can be easier for debugging if you want to put a breakpoint on one of the specific conditions.

Also of note, although if (myBool == true) will work, you don't have to explicitly equate it to true.  The if statement just has to evaluate to true, so you can write it as if (myBool).  Again it's personal preference, but it's shorter and can make it easier to read.

Lastly, you might consider using string.IsNullOrWhiteSpace, which is just like string.IsNullOrEmpty but also checks if the string only contains spaces, tabs, etc., with no content.

Body:
I would like to check each condition and return if true.

Is it better to have:

1. Multiple conditions in a single if statement?

if (string.IsNullOrEmpty(myStr) ||
    myBool == true ||
    myList.Count == 0)
{
    return;
}

2. Or multiple if statements, each checking a different condition.

if (string.IsNullOrEmpty(myStr))
{
    return;
}

if (myBool == true)
{
    return;
}

if (myList.Count == 0)
{
    return;
}

If myStr is Empty.

My thought is that the first way checks all 3 conditions before it reaches the return (or does it)?

And the second way only has to check the 1st condition string.IsNullOrEmpty, reaches the return, and doesn't have to process the other 2 condition checks below it.

Or does the compiler optimize the code to work most efficient no matter how the source is written?


问:
React Developer Tools shows all components as "Anonymous"
I've installed the React Developer Tools extension on Google Chrome to debug a React application written in TypeScript, but once I start debugging the application and open the "Components" window, all components are shown as "Anonymous".

Granted, the application uses mostly function components.

Does anyone know if there is a way to get React Developer Tools to show component names in its component tree?

答:
If you're using an exported anonymous functional component or a memo'ed component; it would be shown as Anonymous

Refer this - https://github.com/facebook/react/issues/17876

Or try solutions mentioned here - React Dev tools show my Component as Unknown


问:
how can I save the state of the 'liked' post by the user?
I have two collections in firestore, 'users' and 'posts'. HomePage is where all the posts are displayed in a listview and every post has a 'like' button. I'm saving the liked posts in a set final _likedPosts = Set<Posts>(); on the page but it only temporarily saves the liked posts and it loses all that data once the app is closed. How can I save the user's _likedPosts permanently so that the data is retained. What query should I make for the users to retain the _likedPosts? or is there any other way for this?

This is how the Icon and onTap is currently,

```<code>final _likedPosts = _savedPosts.contains(post);

Icon(_likedPosts ? Icons.favorite : Icons.favorite_border,
            color: _likedPosts ? Colors.red : null),
        onTap: () {
          setState(() {
            if (_likedPosts) {
              _savedPosts.remove(post);
            } else {
              _savedPosts.add(post);
            }
          });
        }
</code>```

答: Are you saving a liked post of a certain user? then I suggest getting that post(ID) and save it to an array in the users doc Liked-Posts per user. Because state doesn't persist or can't be saved unless you use an external db.</p>

Body:
I have two collections in firestore, 'users' and 'posts'. HomePage is where all the posts are displayed in a listview and every post has a 'like' button. I'm saving the liked posts in a set final _likedPosts = Set<Posts>(); on the page but it only temporarily saves the liked posts and it loses all that data once the app is closed. How can I save the user's _likedPosts permanently so that the data is retained. What query should I make for the users to retain the _likedPosts? or is there any other way for this?

This is how the Icon and onTap is currently,

final _likedPosts = _savedPosts.contains(post);

Icon(_likedPosts ? Icons.favorite : Icons.favorite_border,
            color: _likedPosts ? Colors.red : null),
        onTap: () {
          setState(() {
            if (_likedPosts) {
              _savedPosts.remove(post);
            } else {
              _savedPosts.add(post);
            }
          });
        }


问:
Modification of QuickSort (partition Hoare), first even numbers descending, then odd numbers descending
I have a big problem to modify the Hoare partition so that it sorts in descending order: first by even numbers and then by odd numbers. Example: arr[] = {1, 6, 7, 8, 4, 5},                      out: arr[] = {8, 6, 4, 7, 5, 1}.

I was able to do this by dividing the array separately into even and odd numbers and sorting each of these parts separately. However, the task is to rework the quicksort so that you do not have to divide the array.

Below I have my partition, I'm going in the right direction?

```<code>static int partition(int []arr, int low,
                                int high)
{
    int pivot = arr[low];
    int i = low - 1, j = high + 1;

    while (true)
    {

        do
        {
            i++;
        } while ((arr[i] > pivot && ((arr[i]%2==0 && pivot%2==0) || (arr[i]%2!=0 && pivot%2!=0))) || (arr[i]<pivot && arr[i]%2==0 && pivot%2!=0));

        do
        {
            j--;
        } while (arr[j] < pivot);

        if (i >= j)
            return j;
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
</code>```

答:
You did an effort in the condition of the first loop, but:

It is not entirely correct

It should be applied similarly to the second loop condition as well

For the second reason it may be good to define a compare-function:

```<code>    private static int cmp(int a, int b) {
        if (a % 2 != b % 2) return a % 2 - b % 2;
        return b - a;
    }
</code>```

Now the loop conditions should be simple:

while (cmp(arr[i], pivot) < 0)

while (cmp(arr[j], pivot) > 0)

Body:
I have a big problem to modify the Hoare partition so that it sorts in descending order: first by even numbers and then by odd numbers. Example: arr[] = {1, 6, 7, 8, 4, 5},                      out: arr[] = {8, 6, 4, 7, 5, 1}.

I was able to do this by dividing the array separately into even and odd numbers and sorting each of these parts separately. However, the task is to rework the quicksort so that you do not have to divide the array.

Below I have my partition, I'm going in the right direction?

static int partition(int []arr, int low,
                                int high)
{
    int pivot = arr[low];
    int i = low - 1, j = high + 1;

    while (true)
    {

        do
        {
            i++;
        } while ((arr[i] > pivot && ((arr[i]%2==0 && pivot%2==0) || (arr[i]%2!=0 && pivot%2!=0))) || (arr[i]<pivot && arr[i]%2==0 && pivot%2!=0));

        do
        {
            j--;
        } while (arr[j] < pivot);

        if (i >= j)
            return j;
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

Body:
You did an effort in the condition of the first loop, but:

It is not entirely correct

It should be applied similarly to the second loop condition as well

For the second reason it may be good to define a compare-function:

    private static int cmp(int a, int b) {
        if (a % 2 != b % 2) return a % 2 - b % 2;
        return b - a;
    }

Now the loop conditions should be simple:

while (cmp(arr[i], pivot) < 0)

while (cmp(arr[j], pivot) > 0)


问:
How to automate next() call in every route function? (express.js)
Hi I am facing the problem that I need to log each incomming request and the associated responses in my database. My current solution looks like the following:

./routes/customer.js

```<code>router.get('/', async (req, res, next) => {
    req.allCustomers = await fetchAllCustomers();
    res.status(200).send(req.allCustomers);
    next();  // <- this is my personal problem
});
</code>```

./middleware/logging.js

```<code>module.exports = function (req, res, next) {
    db.query(
        `INSERT INTO logging SET ?`,
         {
            request: JSON.stringify([req.body, req.params]),
            response: JSON.stringify(req.response)
         }
    );
}
</code>```

routes declaration

```<code>module.exports = function(app) {
    app.use(express.json());
    app.use('/api/customers', customers); // <- ROUTE ./routes/customer.js
    app.use(logging); // <- MIDDLEWARE ./middleware/logging.js
}

</code>```

I already mentioned my problem in my first piece of code. It is really repetitive to call next() in every route manually and I would like to avoid this. I already tried to load the middleware before all routes, call next() in the middleware function and execute my db query afterwards but I do not have the response at this point because of the async functionality.

Is there any way to handle this situation or will I need keep calling next() at the end of each route function?

答:
If you don't want to call next() from your routes, you cannot have middleware run after them. It needs to be placed before. But can you get the response inside a middleware that runs before the route? The answer is yes!

It may be a little hacky, but since your route uses res.send(), you can use that to your advantage. By running before your route, your middleware can hijack that res.send function, to make it do other stuff.

./routes/customer.js

```<code>router.get('/', async (req, res, next) => {
    req.allCustomers = await fetchAllCustomers();
    res.send(req.allCustomers); // We'll hijack this
});
</code>```

./middleware/logging.js

```<code>module.exports = function (shouldBeLoggedFunc) {
  return function (req, res, next) {
    if (shouldBeLoggedFunc(req)) {
      // Store the original send method
      const _send = res.send;
      // Override it
      res.send = function (body) {
        // Reset it
        res.send = _send;
        // Actually send the response
        res.send(body);
        // Log it (console.log for the demo)
        console.log(`INSERT INTO logging SET ?`, {
          request: JSON.stringify([req.body, req.params]),
          response: JSON.stringify(body)
        });
      };
    }
    next();
  };
};
</code>```

routes declaration

```<code>function shouldBeLogged(req) {
  // Here, check the route and method and decide whether you want to log it
  console.log(req.method, req.path); // e.g. GET /api/customers
  return true;
}

module.exports = function(app) {
    app.use(express.json());
    app.use(logging(shouldBeLogged)); // <- Place this before your routes
    app.use('/api/customers', customers);
};
</code>```

Body:
Hi I am facing the problem that I need to log each incomming request and the associated responses in my database. My current solution looks like the following:

./routes/customer.js

router.get('/', async (req, res, next) => {
    req.allCustomers = await fetchAllCustomers();
    res.status(200).send(req.allCustomers);
    next();  // <- this is my personal problem
});

./middleware/logging.js

module.exports = function (req, res, next) {
    db.query(
        `INSERT INTO logging SET ?`,
         {
            request: JSON.stringify([req.body, req.params]),
            response: JSON.stringify(req.response)
         }
    );
}

routes declaration

module.exports = function(app) {
    app.use(express.json());
    app.use('/api/customers', customers); // <- ROUTE ./routes/customer.js
    app.use(logging); // <- MIDDLEWARE ./middleware/logging.js
}

I already mentioned my problem in my first piece of code. It is really repetitive to call next() in every route manually and I would like to avoid this. I already tried to load the middleware before all routes, call next() in the middleware function and execute my db query afterwards but I do not have the response at this point because of the async functionality.

Is there any way to handle this situation or will I need keep calling next() at the end of each route function?

Body:
If you don't want to call next() from your routes, you cannot have middleware run after them. It needs to be placed before. But can you get the response inside a middleware that runs before the route? The answer is yes!

It may be a little hacky, but since your route uses res.send(), you can use that to your advantage. By running before your route, your middleware can hijack that res.send function, to make it do other stuff.

./routes/customer.js

router.get('/', async (req, res, next) => {
    req.allCustomers = await fetchAllCustomers();
    res.send(req.allCustomers); // We'll hijack this
});

./middleware/logging.js

module.exports = function (shouldBeLoggedFunc) {
  return function (req, res, next) {
    if (shouldBeLoggedFunc(req)) {
      // Store the original send method
      const _send = res.send;
      // Override it
      res.send = function (body) {
        // Reset it
        res.send = _send;
        // Actually send the response
        res.send(body);
        // Log it (console.log for the demo)
        console.log(`INSERT INTO logging SET ?`, {
          request: JSON.stringify([req.body, req.params]),
          response: JSON.stringify(body)
        });
      };
    }
    next();
  };
};

routes declaration

function shouldBeLogged(req) {
  // Here, check the route and method and decide whether you want to log it
  console.log(req.method, req.path); // e.g. GET /api/customers
  return true;
}

module.exports = function(app) {
    app.use(express.json());
    app.use(logging(shouldBeLogged)); // <- Place this before your routes
    app.use('/api/customers', customers);
};


问:
Is there any easy algorithm to do edge coloring on a complete graph
For a given complete graph $G$ having $n$ nodes, how can we build a edge coloring of
$G$ with $n$ colors.</p>

答:
You can look at the graph as a sports tournament where each node is a team, each edge is a match, and each color is a round. You are then looking for a round-robin tournament and can use the circle method (see wikipedia) to find the coloring:

The circle method is the standard algorithm to create a schedule for a round-robin tournament. All competitors are assigned to numbers, and then paired in the first round:

Round 1. (1 plays 14, 2 plays 13, ... )

Next, one of the competitors in the first or last column of the table is fixed (number one in this example) and the others rotated clockwise one position

Round 2. (1 plays 13, 14 plays 12, ... )

Round 3. (1 plays 12, 13 plays 11, ... )

This is repeated until you end up almost back at the initial position:

Round 13. (1 plays 2, 3 plays 14, ... )

For n even this leads to a coloring with n - 1 colors.

The standard round-robin approach to deal with an odd number of teams is to add a dummy team. So for n odd there is one additional round and you'll get a coloring with n colors.


问:
How to get associative array from url query string, javascript
I have url query string

```<code>?filter%5B%22customer_rating_heading%22%5D=customer_rating_6_up%2Ccustomer_rating_7_up%2Ccustomer_rating_9_up&map=1
</code>```

which is

```<code>?filter["customer_rating_heading"]=customer_rating_6_up,customer_rating_7_up,customer_rating_9_up&map=1
</code>```

I want to ask for filter like params.get('filter) and get

```<code>[customer_rating_heading => 'customer_rating_6_up,customer_rating_7_up,customer_rating_9_up' //(later I'll make array from this string)
</code>```

But I don't know how to do this, I tried let query = Object.fromEntries(new URLSearchParams(location.search) but it gives me:

```<code>{filter["customer_rating_heading"]: "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
map: "1"}
</code>```

but I can't get filter like query.filter it's always undefined

does anyone know a solution for such problem?

答:
if you want to access your filter you can use that snippet:</p>

```<code>let [filter] = Object.keys(query).map( key => query[key] )
</code>```

Body:
I have url query string

?filter%5B%22customer_rating_heading%22%5D=customer_rating_6_up%2Ccustomer_rating_7_up%2Ccustomer_rating_9_up&map=1

which is

?filter["customer_rating_heading"]=customer_rating_6_up,customer_rating_7_up,customer_rating_9_up&map=1

I want to ask for filter like params.get('filter) and get

[customer_rating_heading => 'customer_rating_6_up,customer_rating_7_up,customer_rating_9_up' //(later I'll make array from this string)

But I don't know how to do this, I tried let query = Object.fromEntries(new URLSearchParams(location.search) but it gives me:

{filter["customer_rating_heading"]: "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
map: "1"}

but I can't get filter like query.filter it's always undefined

does anyone know a solution for such problem?

Body:
if you want to access your filter you can use that snippet:

let [filter] = Object.keys(query).map( key => query[key] )


问:
What is the best way to store a nested Json data generated from API into SQL DB using Python
I have a Json response coming from the API, i need to store this into a SQL DB from python. Apparently the Json data is nested.
What is the best way to store this?

Is there a way i can create table automatically with the schema that is generating by Json response, like it needs to take columns names from Json response and needs to be quite dynamic that if in future if there is a new value coming in it needs to create a new column

Here is the Json data example -

```<code>{
  "data": [
    {
      "id": 111,
      "name": "Test",
      "client": {
        "id": 12,
        "name": "Test"
      },
      "office": {
        "id": 12,
        "name": "Test",
        "country": "Test"
      },
      "primaryContact": {
        "name": "<PrimaryContactName>",
        "email": "<PrimaryContactEmail>"
      },
      "data": [
        {
          "fieldid": 10,
          "fieldLabel": "Test1",
          "hasMutlipleValues": false,
          "multiValues": [],
          "fieldValue": "Test2",
          "sfid": 0
        },
        {
          "fieldid": 132,
          "fieldLabel": "Test3",
          "hasMutlipleValues": false,
          "multiValues": [],
          "fieldValue": "Test4"
        }
      ]
    }
  ],
  "total": 1
}
</code>```

答:
I think the best way would be to store the json itself in db. Since you mentioned the JSON is dynamic in nature.

This is with mariadb.

```<code>CREATE TABLE Sample (id int, json_file JSON, PRIMARY KEY(id));
</code>```

If the above method doesn't work you can convert the json to string and then store in db in a VARCHAR field .

```<code>import json
json_string = json.dump(json_file)
</code>```

Creating columns as they are generated is something I feel is unnecessary.

Body:
I have a Json response coming from the API, i need to store this into a SQL DB from python. Apparently the Json data is nested.
What is the best way to store this?

Is there a way i can create table automatically with the schema that is generating by Json response, like it needs to take columns names from Json response and needs to be quite dynamic that if in future if there is a new value coming in it needs to create a new column

Here is the Json data example -

{
  "data": [
    {
      "id": 111,
      "name": "Test",
      "client": {
        "id": 12,
        "name": "Test"
      },
      "office": {
        "id": 12,
        "name": "Test",
        "country": "Test"
      },
      "primaryContact": {
        "name": "<PrimaryContactName>",
        "email": "<PrimaryContactEmail>"
      },
      "data": [
        {
          "fieldid": 10,
          "fieldLabel": "Test1",
          "hasMutlipleValues": false,
          "multiValues": [],
          "fieldValue": "Test2",
          "sfid": 0
        },
        {
          "fieldid": 132,
          "fieldLabel": "Test3",
          "hasMutlipleValues": false,
          "multiValues": [],
          "fieldValue": "Test4"
        }
      ]
    }
  ],
  "total": 1
}

Body:
I think the best way would be to store the json itself in db. Since you mentioned the JSON is dynamic in nature.

This is with mariadb.

CREATE TABLE Sample (id int, json_file JSON, PRIMARY KEY(id));

If the above method doesn't work you can convert the json to string and then store in db in a VARCHAR field .

import json
json_string = json.dump(json_file)

Creating columns as they are generated is something I feel is unnecessary.


问:
python program to find hcf and lcm
i wrote the following progran in python to find out hcf and lcm of two numbers a and b. x is the greater of the two numbers and y is smaller, both of which i intend to find in upper part of program. they will be used later for finding hcf and lcm.but when i run it, it shades x in red. i cant understand the reason.

```<code>a,b=raw_input("enter two numbers (with space in between: ").split()
if (a>b):
    int x==a
else:
    int x==b
for i in range (1,x):
    if (a%i==0 & b%i==0):
        int hcf=i
print ("hcf of both is: ", hcf)
for j in range (x,a*b):
    if (j%a==0 & j%b==0):
        int lcm=j
print ("lcm of both is: ", lcm)
</code>```

this algo of finding lcm, hcf works perfectly in c, so i dont feel there should be problem with algo. it might be some syntax problem.

答:
Program to find the LCM and HCF</p>

```<code>a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
if(a>b):
    x=a
else:
    x=b
for i in range(1,x+1):
    if(a%i==0)and(b%i==0):
        hcf=i
print("The HCF of {0} and {1} is={2}".format(a,b,hcf));
for j in range(x,a*b):
    if(j%a==0)and(j%b==0):
        lcm=j
        break
print("The LCM of {0} and {1} is={2}".format(a,b,lcm));
</code>```

ContentLicense: CC BY-SA 3.0

Title: python program to find hcf and lcm

Body:
i wrote the following progran in python to find out hcf and lcm of two numbers a and b. x is the greater of the two numbers and y is smaller, both of which i intend to find in upper part of program. they will be used later for finding hcf and lcm.but when i run it, it shades x in red. i cant understand the reason.

a,b=raw_input("enter two numbers (with space in between: ").split()
if (a>b):
    int x==a
else:
    int x==b
for i in range (1,x):
    if (a%i==0 & b%i==0):
        int hcf=i
print ("hcf of both is: ", hcf)
for j in range (x,a*b):
    if (j%a==0 & j%b==0):
        int lcm=j
print ("lcm of both is: ", lcm)

this algo of finding lcm, hcf works perfectly in c, so i dont feel there should be problem with algo. it might be some syntax problem.

Body:
Program to find the LCM and HCF

a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
if(a>b):
    x=a
else:
    x=b
for i in range(1,x+1):
    if(a%i==0)and(b%i==0):
        hcf=i
print("The HCF of {0} and {1} is={2}".format(a,b,hcf));
for j in range(x,a*b):
    if(j%a==0)and(j%b==0):
        lcm=j
        break
print("The LCM of {0} and {1} is={2}".format(a,b,lcm));


问:
Hasura: How to establish relationship to existing record (many to many) at insert time?
Hasura: How to establish relationship to existing record (many to many) at insert time?

I have two tables: product and category that are linked to each other in a many to many relationship based on an id column in each table and an intermediary table product_category.

I can insert records directly into postgres for both tables and link them with product_category and this works great in Hasura for queries so I know I have set things up properly.

What I want to be able to do is insert a new product and knowing the id of a category (or categories) I want to establish the relationship at insert time. Preferably without a seperate call

https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships

The documentation only covers inserting both the object and related objects at the same time but what if the other one already exists?

I have tried what I would expect to work (linking this product to category with id 1):

```<code>mutation MyMutation {
  insert_product_one(
    object: {
      name: "Champion",
      category: {data: {id: 1}}
    }) {
    id
  }
}
</code>```

But that throws:

"Not-NULL violation. null value in column \"product_id\" violates not-null constraint"

How can I insert this new product and link it to one or more categories? Preferably all in one statement but even an example of retrieving the generated id and an update mutation would be not ideal, but non-the-less a solution.

Update: As a sanity check I've recreated the product and category tables as a minimal, basic example and tried both my query and the upsert conflict method xadm suggested.

The data and relations I've added some screenshots of here:

https://imgur.com/a/GUomMbe

```<code>mutation MyMutation {
  insert_testproduct_one(
    object: {
      name: "Champion",
      category: {
          data: {id: 1},
          on_conflict: { constraint: primarykeything , update_columns: [id] }
    }
    }) {
    id
  }
}
</code>```

The error is similar: "Not-NULL violation. null value in column \"testcategory_id\" violates not-null constraint"

Note: primarykeything is the primary key on the bridge table consisting of the two ids.

答:
Since it's a many to many relationship, you have a join table in between them.  From what I can see in the screenshot you posted the id for the category in your category relationship is called testcategory_id and not id.

mutation MyMutation {
  insert_testproduct_one(
    object: {
      name: "Champion",
      category: {
          data: {testcategory_id: 1}
    }
    }) {
    id
  }
}
```

For it to work the id in the table testproduct_testcategory has to be auto-incremented

Body:
Hasura: How to establish relationship to existing record (many to many) at insert time?

I have two tables: product and category that are linked to each other in a many to many relationship based on an id column in each table and an intermediary table product_category.

I can insert records directly into postgres for both tables and link them with product_category and this works great in Hasura for queries so I know I have set things up properly.

What I want to be able to do is insert a new product and knowing the id of a category (or categories) I want to establish the relationship at insert time. Preferably without a seperate call

https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships

The documentation only covers inserting both the object and related objects at the same time but what if the other one already exists?

I have tried what I would expect to work (linking this product to category with id 1):

mutation MyMutation {
  insert_product_one(
    object: {
      name: "Champion",
      category: {data: {id: 1}}
    }) {
    id
  }
}

But that throws:

"Not-NULL violation. null value in column \"product_id\" violates not-null constraint"

How can I insert this new product and link it to one or more categories? Preferably all in one statement but even an example of retrieving the generated id and an update mutation would be not ideal, but non-the-less a solution.

Update: As a sanity check I've recreated the product and category tables as a minimal, basic example and tried both my query and the upsert conflict method xadm suggested.

The data and relations I've added some screenshots of here:

https://imgur.com/a/GUomMbe

mutation MyMutation {
  insert_testproduct_one(
    object: {
      name: "Champion",
      category: {
          data: {id: 1},
          on_conflict: { constraint: primarykeything , update_columns: [id] }
    }
    }) {
    id
  }
}

The error is similar: "Not-NULL violation. null value in column \"testcategory_id\" violates not-null constraint"

Note: primarykeything is the primary key on the bridge table consisting of the two ids.

Body:
Since it's a many to many relationship, you have a join table in between them.  From what I can see in the screenshot you posted the id for the category in your category relationship is called testcategory_id and not id.

mutation MyMutation {
  insert_testproduct_one(
    object: {
      name: "Champion",
      category: {
          data: {testcategory_id: 1}
    }
    }) {
    id
  }
}

For it to work the id in the table testproduct_testcategory has to be auto-incremented


问:
Declaring variables and using getElementById to print Hello World
The assignment is such that I have to declare variables 1(Hello), 2(world) and result,  and create a string in p element using getElementById/innerHTML. The result should also printed in console log. I've tried several combinations such as this, but I have no idea how to go from here.</p>

```<code><!DOCTYPE html>
<html>

<body>
    <p id= "tulos">Haloo maailma!</p>

    <script>

   var tulos = document.getElementById("tulos").innerHTML "Haloo";
   var tulos = document.getElementById("tulos").innerHTML = document.getElementById("tulos").innerHTML+ "maailma!";
   console.log(tulos);

</script>
</body>
</html>
</code>```

答:
im not sure what do you need, but my guess is you want to print variable to a p tag and also able to console it</p>

```<code><p id="target"></p>
<script>
   let var1 = 'hello';
   let var2 = 'world';
   let result = var1 +' '+var2;
   let target = document.getElementById('target');
   target.innerHTML = result;
   console.log(result);
</script>
</code>```

Body:
The assignment is such that I have to declare variables 1(Hello), 2(world) and result,  and create a string in p element using getElementById/innerHTML. The result should also printed in console log. I've tried several combinations such as this, but I have no idea how to go from here.

<!DOCTYPE html>

Haloo maailma!

Body:
im not sure what do you need, but my guess is you want to print variable to a p tag and also able to console it

<p id="target"></p>
<script>
   let var1 = 'hello';
   let var2 = 'world';
   let result = var1 +' '+var2;
   let target = document.getElementById('target');
   target.innerHTML = result;
   console.log(result);
</script>


问:
How to stretch an image in Matlab
All,

I need to know how to stretch an image for further work.

for example, I have the next two images:

I want that the numbers will fill the entire square like this:

any help will be greatly appreciated.

答:
The background of the image is black? White?
Find the smallest rectangle which encloses the image. And cut the borders by the command img(uppixel:downpoxil, leftpixel:rightpixel)

You find the smallest rectangle by for loop and compare each pixel not in background against the border

Title: How to stretch an image in Matlab


问:
CS50 recover segmentation fault
This is Recover from pset4 CS50. There is no error when I compile it. When I run the code I get segmentation fault. I do not understand what exactly is the mistake. I have looked up solutions related to questions on segmentation fault posted by others but they don't seem to solve my problem. </p>

<p>Can somebody explain whats wrong and how do I solve it. </p>

```<code>#include <stdio.h>
#include <stdint.h>
typedef uint8_t BYTE;

int main(int argc, char *argv[])
{

if (argc != 2)
{
    printf("Usage: ./recover image\n");
    return 1;
}

FILE *inFile = fopen(argv[1], "r");
if(!inFile)
{
    printf("Could not open file!\n");
    return 1;
}

BYTE buffer[512];
FILE *outFile = NULL;
int imageNum = 0;
char fileName[8];

while (!feof(inFile))
{
     fread(buffer, 1, sizeof(buffer), inFile);
     if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[4] & 0xf0) == 0xef0)
     {
         if (imageNum > 0)
         {
            fclose(outFile);
         }
         imageNum++;
         sprintf(fileName, "%03i.jpg", imageNum);
         outFile = fopen(fileName, "w");
     }
    if (outFile != NULL)
    {
        fwrite(buffer, 1, sizeof(buffer), outFile);
    }
}
fclose(outFile);
fclose(inFile);
return 0;
}
</code>```

答: fileName is defined to have eight elements in char fileName[8];, but sprintf(fileName, "%03i.jpg", imageNum); writes more than eight characters once imageNum exceeds 999.

Title: CS50 recover segmentation fault

Body:
This is Recover from pset4 CS50. There is no error when I compile it. When I run the code I get segmentation fault. I do not understand what exactly is the mistake. I have looked up solutions related to questions on segmentation fault posted by others but they don't seem to solve my problem.

Can somebody explain whats wrong and how do I solve it.

#include <stdio.h>
#include <stdint.h>
typedef uint8_t BYTE;

int main(int argc, char *argv[])
{

if (argc != 2)
{
    printf("Usage: ./recover image\n");
    return 1;
}

FILE *inFile = fopen(argv[1], "r");
if(!inFile)
{
    printf("Could not open file!\n");
    return 1;
}

BYTE buffer[512];
FILE *outFile = NULL;
int imageNum = 0;
char fileName[8];

while (!feof(inFile))
{
     fread(buffer, 1, sizeof(buffer), inFile);
     if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[4] & 0xf0) == 0xef0)
     {
         if (imageNum > 0)
         {
            fclose(outFile);
         }
         imageNum++;
         sprintf(fileName, "%03i.jpg", imageNum);
         outFile = fopen(fileName, "w");
     }
    if (outFile != NULL)
    {
        fwrite(buffer, 1, sizeof(buffer), outFile);
    }
}
fclose(outFile);
fclose(inFile);
return 0;
}


问:
Score Not Updating Pong Pygame
I'm not sure why the score isn't updating. When either player scores the debugger prints 0's. Here are my score variables.

```<code>player_score = 0
opponent_score = 0
basic_font = pygame.font.Font('freesansbold.ttf', 32)

And the variables for rendering the score:

player_text = basic_font.render(f'{player_score}', False, light_grey)
screen.blit(player_text, (660, 470))

opponent_text = basic_font.render(f'{opponent_score}', False, light_grey)
screen.blit(opponent_text, (600, 470))
</code>```

And my update method.

```<code>    def update(self, left_paddle, right_paddle, player_score, opponent_score):
    self.rect.x += self.vx
    self.rect.y += self.vy

    if self.rect.top <= 0 or self.rect.bottom >= screen_height:
        self.vy *= -1

    if self.rect.left <= 0:
        self.ball_start()
        player_score += 1

    if self.rect.right >= screen_width:
        self.ball_start()
        opponent_score += 1

    if self.rect.colliderect(left_paddle) or self.rect.colliderect(right_paddle):
        self.vx *= -1

def ball_start(self):
    self.rect.center = (screen_width / 2, screen_height / 2)
    self.vy *= random.choice((1, -1))
    self.vx *= random.choice((1, -1))
</code>```

And then i call the update method:

ball.update(left_paddle, right_paddle, player_score, opponent_score)

Here's the code for the project. Your help would be greatly appreciated.

```<code>import logging
import pygame, sys
from inputs import handle_input
import random

class Paddle:
    def __init__(self):
        self.rect = pygame.Rect(10, screen_height / 2 - 70, 10, 140)

        self.speed = 10

    def draw(self, screen):
        pygame.draw.rect(screen, light_grey, self.rect)

    def move_up(self):
        self.rect.y -= self.speed
        self._keep_in_bounds()

    def move_down(self):
        self.rect.y += self.speed
        self._keep_in_bounds()

    def _keep_in_bounds(self):
        if self.rect.top <= 0:
            self.rect.top = 0

        if self.rect.bottom >= screen_height:
            self.rect.bottom = screen_height

class Ball:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height)
        self.speed = 7
        self.vx = self.speed * random.choice((1, -1))
        self.vy = self.speed * random.choice((1, -1))

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, self.rect)

    def update(self, left_paddle, right_paddle, player_score, opponent_score):

        self.rect.x += self.vx
        self.rect.y += self.vy

        if self.rect.top <= 0 or self.rect.bottom >= screen_height:
            self.vy *= -1

        if self.rect.left <= 0:
            self.ball_start()
            player_score += 1

        if self.rect.right >= screen_width:
            self.ball_start()
            opponent_score += 1

        if self.rect.colliderect(left_paddle) or self.rect.colliderect(right_paddle):
            self.vx *= -1

    def ball_start(self):
        self.rect.center = (screen_width / 2, screen_height / 2)
        # print(self.rect.center)
        self.vy *= random.choice((1, -1))
        self.vx *= random.choice((1, -1))

# General setup
pygame.init()
clock = pygame.time.Clock()

# Main Window
screen_width = 1280
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Pong')

# Colors
light_grey = (200, 200, 200)
bg_color = pygame.Color('grey12')

# Game Rectangles
ball = Ball(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
left_paddle = Paddle()
right_paddle = Paddle()
right_paddle.rect.x = screen_width - right_paddle.rect.width

player_score = 0
opponent_score = 0
basic_font = pygame.font.Font('freesansbold.ttf', 32)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Game logic
    handle_input(left_paddle, right_paddle)
    screen.fill(bg_color)
    pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))
    ball.draw(screen)
    left_paddle.draw(screen)
    right_paddle.draw(screen)
    ball.update(left_paddle, right_paddle, player_score, opponent_score)

    player_text = basic_font.render(f'{player_score}', False, light_grey)
    screen.blit(player_text, (660, 470))

    opponent_text = basic_font.render(f'{opponent_score}', False, light_grey)
    screen.blit(opponent_text, (600, 470))

    pygame.display.flip()
    clock.tick(60)
</code>```

答:
Your updates are not getting reflected in the global variables because you are simply not updating them. You are updating a local copy of them, which you got from passing them to the Ball.update function.

Try this:

def update(self, left_paddle, right_paddle):
    global player_score, opponent_score

    ...

    if self.rect.left <= 0:
        self.ball_start()
        player_score += 1

    if self.rect.right >= screen_width:
        self.ball_start()
        opponent_score += 1

    ...
    # function ends here
```

I think the best would be to create a Player class and keep track of scores there only and, pass instances of this Player class to the update function. Then, later retrieve the scores form these instances.

Title: Score Not Updating Pong Pygame

Body:
I'm not sure why the score isn't updating. When either player scores the debugger prints 0's. Here are my score variables.

player_score = 0
opponent_score = 0
basic_font = pygame.font.Font('freesansbold.ttf', 32)

And the variables for rendering the score:

player_text = basic_font.render(f'{player_score}', False, light_grey)
screen.blit(player_text, (660, 470))

opponent_text = basic_font.render(f'{opponent_score}', False, light_grey)
screen.blit(opponent_text, (600, 470))

And my update method.

    def update(self, left_paddle, right_paddle, player_score, opponent_score):
    self.rect.x += self.vx
    self.rect.y += self.vy

    if self.rect.top <= 0 or self.rect.bottom >= screen_height:
        self.vy *= -1

    if self.rect.left <= 0:
        self.ball_start()
        player_score += 1

    if self.rect.right >= screen_width:
        self.ball_start()
        opponent_score += 1

    if self.rect.colliderect(left_paddle) or self.rect.colliderect(right_paddle):
        self.vx *= -1

def ball_start(self):
    self.rect.center = (screen_width / 2, screen_height / 2)
    self.vy *= random.choice((1, -1))
    self.vx *= random.choice((1, -1))

And then i call the update method:

ball.update(left_paddle, right_paddle, player_score, opponent_score)

Here's the code for the project. Your help would be greatly appreciated.

import logging
import pygame, sys
from inputs import handle_input
import random

class Paddle:
    def __init__(self):
        self.rect = pygame.Rect(10, screen_height / 2 - 70, 10, 140)

        self.speed = 10

    def draw(self, screen):
        pygame.draw.rect(screen, light_grey, self.rect)

    def move_up(self):
        self.rect.y -= self.speed
        self._keep_in_bounds()

    def move_down(self):
        self.rect.y += self.speed
        self._keep_in_bounds()

    def _keep_in_bounds(self):
        if self.rect.top <= 0:
            self.rect.top = 0

        if self.rect.bottom >= screen_height:
            self.rect.bottom = screen_height

class Ball:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height)
        self.speed = 7
        self.vx = self.speed * random.choice((1, -1))
        self.vy = self.speed * random.choice((1, -1))

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, self.rect)

    def update(self, left_paddle, right_paddle, player_score, opponent_score):

        self.rect.x += self.vx
        self.rect.y += self.vy

        if self.rect.top <= 0 or self.rect.bottom >= screen_height:
            self.vy *= -1

        if self.rect.left <= 0:
            self.ball_start()
            player_score += 1

        if self.rect.right >= screen_width:
            self.ball_start()
            opponent_score += 1

        if self.rect.colliderect(left_paddle) or self.rect.colliderect(right_paddle):
            self.vx *= -1

    def ball_start(self):
        self.rect.center = (screen_width / 2, screen_height / 2)
        # print(self.rect.center)
        self.vy *= random.choice((1, -1))
        self.vx *= random.choice((1, -1))

# General setup
pygame.init()
clock = pygame.time.Clock()

# Main Window
screen_width = 1280
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Pong')

# Colors
light_grey = (200, 200, 200)
bg_color = pygame.Color('grey12')

# Game Rectangles
ball = Ball(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
left_paddle = Paddle()
right_paddle = Paddle()
right_paddle.rect.x = screen_width - right_paddle.rect.width

player_score = 0
opponent_score = 0
basic_font = pygame.font.Font('freesansbold.ttf', 32)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Game logic
    handle_input(left_paddle, right_paddle)
    screen.fill(bg_color)
    pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))
    ball.draw(screen)
    left_paddle.draw(screen)
    right_paddle.draw(screen)
    ball.update(left_paddle, right_paddle, player_score, opponent_score)

    player_text = basic_font.render(f'{player_score}', False, light_grey)
    screen.blit(player_text, (660, 470))

    opponent_text = basic_font.render(f'{opponent_score}', False, light_grey)
    screen.blit(opponent_text, (600, 470))

    pygame.display.flip()
    clock.tick(60)

Body:
Your updates are not getting reflected in the global variables because you are simply not updating them. You are updating a local copy of them, which you got from passing them to the Ball.update function.

Try this:

def update(self, left_paddle, right_paddle):
    global player_score, opponent_score

    ...

    if self.rect.left <= 0:
        self.ball_start()
        player_score += 1

    if self.rect.right >= screen_width:
        self.ball_start()
        opponent_score += 1

    ...
    # function ends here

I think the best would be to create a Player class and keep track of scores there only and, pass instances of this Player class to the update function. Then, later retrieve the scores form these instances.


问:
How to have multiple *ngIf combined with && operator and as in angular?
How can I achieve the 'as' with '&&' operator to get the following result?

```<code>*ngIf="(items$ | async as items) && (filters$ | async as filters)"
</code>```

Currently this is returning a template parse error.
I've tried out a bunch of variants.

答:
You can do it in these three ways:

1.

```<code><ng-container *ngIf="items$ | async as items">
  <ng-container *ngIf="filters$ | async as filters">

  </ng-container>
</ng-container>
</code>```

2.

```<code><ng-container *ngIf="{ items: items$ | async, filters: filter$ | async } as data">
  <ng-container *ngIf="data.items && data.filters">

  </ng-container>
</ng-container>
</code>```

3.

ts:

```<code>readonly filterItems$ = combineLatest([
  this.items$,
  this.filters$
]).pipe(
  map(([ items, filters ]) => ({ items, filters }))
);
</code>```

```<code><ng-container *ngIf="filterItems$ | async as filterItems"></ng-container>
</code>```

With the last option you can access the items and filters like filteritems.items and filterItems.filters

Body:
How can I achieve the 'as' with '&&' operator to get the following result?

*ngIf="(items$ | async as items) && (filters$ | async as filters)"

Currently this is returning a template parse error.
I've tried out a bunch of variants.

Body:
You can do it in these three ways:

1.

<ng-container *ngIf="items$ | async as items">
  <ng-container *ngIf="filters$ | async as filters">

  </ng-container>
</ng-container>

2.

<ng-container *ngIf="{ items: items$ | async, filters: filter$ | async } as data">
  <ng-container *ngIf="data.items && data.filters">

  </ng-container>
</ng-container>

3.

ts:

readonly filterItems$ = combineLatest([
  this.items$,
  this.filters$
]).pipe(
  map(([ items, filters ]) => ({ items, filters }))
);

<ng-container *ngIf="filterItems$ | async as filterItems"></ng-container>

With the last option you can access the items and filters like filteritems.items and filterItems.filters