问:
Third parameter (kwargs) sklearn fit() function
I'm quite new to scikit-learn and I have a question about the fit() function. I tried to look for information on the internet but couldn't find much.
In an assignement I have to create a dict of parameters passed to the fit function of a classifier, which means the function will take 3 arguments (X, y, kwargs). What parameters is this dictionary supposed to have? Apparently those are hyper parameters for the fit function. Online I only found information for xgbooster but I'm not supposed to use that, only classifiers from sklearn.

I also found online that fit can take a dictionary called **fit_params but there is nothing about the parameters the function might take.

I hope my question is clear, thanks a lot in advance!

答:
I haven't used scikit-learn before, but you can get the docs of a function that you are unsure about by using the __doc__ method. The fit() method of an estimator returns this for its __doc__ method:

```<code>Fit the SVM model according to the given training data.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)                 or (n_samples, n_samples)
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.
            For kernel="precomputed", the expected shape of X is
            (n_samples, n_samples).

        y : array-like of shape (n_samples,)
            Target values (class labels in classification, real numbers in
            regression)

        sample_weight : array-like of shape (n_samples,), default=None
            Per-sample weights. Rescale C per sample. Higher weights
            force the classifier to put more emphasis on these points.

        Returns
        -------
        self : object

        Notes
        -----
        If X and y are not C-ordered and contiguous arrays of np.float64 and
        X is not a scipy.sparse.csr_matrix, X and/or y may be copied.

        If X is a dense array, then the other methods will not support sparse
        matrices as input.
</code>```

I ran this to get that output:

from sklearn import svm
clf = svm.SVC(gamma=0.001, C=100.)
print(clf.fit.__doc__)
```

Body:
I haven't used scikit-learn before, but you can get the docs of a function that you are unsure about by using the __doc__ method. The fit() method of an estimator returns this for its __doc__ method:

Fit the SVM model according to the given training data.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)                 or (n_samples, n_samples)
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.
            For kernel="precomputed", the expected shape of X is
            (n_samples, n_samples).

        y : array-like of shape (n_samples,)
            Target values (class labels in classification, real numbers in
            regression)

        sample_weight : array-like of shape (n_samples,), default=None
            Per-sample weights. Rescale C per sample. Higher weights
            force the classifier to put more emphasis on these points.

        Returns
        -------
        self : object

        Notes
        -----
        If X and y are not C-ordered and contiguous arrays of np.float64 and
        X is not a scipy.sparse.csr_matrix, X and/or y may be copied.

        If X is a dense array, then the other methods will not support sparse
        matrices as input.

I ran this to get that output:

from sklearn import svm
clf = svm.SVC(gamma=0.001, C=100.)
print(clf.fit.__doc__)


来源: stackexchange

问:
equivalent of "minikube ssh" with docker-for-desktop Kubernetes node
I am using Docker for Mac but currently only using it for its Kubernetes cluster. The Kubernetes cluster's single node is named docker-for-desktop.

I'm currently going through a Kubernetes tutorial on Persistent Volumes (https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/) and as part of that, I'm setting up a hostPath persistent volume. It seems like the way this works is, you create a path on the Kubernetes Node itself and you can use that as your persistent volume for development and testing purposes.

To do that, the tutorial instructs you to SSH into your Kubernetes node itself and create a path which can then be turned into a persistent volume. The only problem is, I have no idea how to SSH directly into the Kubernetes node itself (not a container). The equivalent for minikube would just be minikube ssh. I can kubectl describe the node, but I only get an internal IP address, not an external one. So I have no idea how to address it in an ssh command.

Any ideas?

答:
Comment in the OP should get credit for this but i'll add again so i find it easier in a few months:

```<code>docker run -it --rm --privileged --pid=host justincormack/nsenter1
</code>```

From https://github.com/justincormack/nsenter1/blob/master/README.md

... this is useful when you are running a lightweight, container-optimized Linux distribution such as LinuxKit... you are demonstrating with Docker for Mac, for example, your containers are not running on your host directly, but are running instead inside of a minimal Linux OS virtual machine specially built for running containers, i.e., LinuxKit. But being a lightweight environment, LinuxKit isn't running sshd, so how do you get access to a shell so you can run nsenter to inspect the namespaces for the process running as pid 1?

ContentLicense: CC BY-SA 4.0

Body:
Comment in the OP should get credit for this but i'll add again so i find it easier in a few months:

docker run -it --rm --privileged --pid=host justincormack/nsenter1

From https://github.com/justincormack/nsenter1/blob/master/README.md

... this is useful when you are running a lightweight, container-optimized Linux distribution such as LinuxKit... you are demonstrating with Docker for Mac, for example, your containers are not running on your host directly, but are running instead inside of a minimal Linux OS virtual machine specially built for running containers, i.e., LinuxKit. But being a lightweight environment, LinuxKit isn't running sshd, so how do you get access to a shell so you can run nsenter to inspect the namespaces for the process running as pid 1?


问:
No hint path defined for [mail] Laravel 5.4
I am trying to show my markdown email on view, but there's something wrong on my mail view, it shows like

```<code>ErrorException in FileViewFinder.php line 112:
No hint path defined for [mail]. (View: /opt/lampp/htdocs/ppsb_new/core/resources/views/emails/tagihan.blade.php)
</code>```

and my markdown mail view

```<code>@component('mail::message')
# TAGIHAN PEMBAYARAN

Berikut tagihan anda untuk pembayaran

@component('mail::button', ['url' => ''])
wut ?
@endcomponent

Gunakan kode tagihan tersebut untuk membayar tagihan.

Thanks,<br>
{{ config('app.name') }}
@endcomponent
</code>```

and there's also vendor on my views who have their components.

答:
Try using a custom email view template, like this:</p>

```<code>You received a message from : {{ $name }}

<p>
Name: {{ $name }}
</p>

<p>
Email: {{ $email }}
</p>

<p>
Message: {{ $user_message }}
</p>
</code>```

Body:
I am trying to show my markdown email on view, but there's something wrong on my mail view, it shows like

ErrorException in FileViewFinder.php line 112:
No hint path defined for [mail]. (View: /opt/lampp/htdocs/ppsb_new/core/resources/views/emails/tagihan.blade.php)

and my markdown mail view

@component('mail::message')
# TAGIHAN PEMBAYARAN

Berikut tagihan anda untuk pembayaran

@component('mail::button', ['url' => ''])
wut ?
@endcomponent

Gunakan kode tagihan tersebut untuk membayar tagihan.

Thanks,

{{ config('app.name') }}
@endcomponent

and there's also vendor on my views who have their components.

Body:
Try using a custom email view template, like this:

You received a message from : {{ $name }}

<p>
Name: {{ $name }}
</p>

<p>
Email: {{ $email }}
</p>

<p>
Message: {{ $user_message }}
</p>


问:
Read contents from PDF File in Python
I'm trying to read the following PDF and I can't do it. Either I get unreadable characters or the UnicodeDecodeError. Some solution for that.</p>

```<code>import PyPDF2
import codecs

rutas = 'file.pdf'

pdf_file = open(rutas,'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print(page_content.encode('utf-8'))
b'\n\n\xcb\x98\xcb\x87\xcb\x86\xcb\x99\xcb\x9d\xcb\x98\xcb\x9b\xcb\x98\xcb\x87\n\xcb\x9a\xcb\x9c \xcb\x9c!"#\xcb\x98$%&&\xcb\x98\'\xcb\x98()\xcb\x9c*"*\xcb\x98*+\xcb\x98\x

temp = textract.process(rutas).decode('utf-8')
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 2075: character maps to <undefined>
</code>```

答:
Try using tika to extract the text:

```<code>from tika import parser

PdfPath = 'file.pdf'
raw = parser.from_file(PdfPath)
textPDF = raw['content']
print(textPDF)
</code>```

To get specific page contents you can split the file into separate pages/sections using PyPDF2 and use this method on splitted pages.

Title: Read contents from PDF File in Python

Body:
I'm trying to read the following PDF and I can't do it. Either I get unreadable characters or the UnicodeDecodeError. Some solution for that.

import PyPDF2
import codecs

rutas = 'file.pdf'

pdf_file = open(rutas,'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print(page_content.encode('utf-8'))
b'\n\n\xcb\x98\xcb\x87\xcb\x86\xcb\x99\xcb\x9d\xcb\x98\xcb\x9b\xcb\x98\xcb\x87\n\xcb\x9a\xcb\x9c \xcb\x9c!"#\xcb\x98$%&&\xcb\x98\'\xcb\x98()\xcb\x9c*"*\xcb\x98*+\xcb\x98\x

temp = textract.process(rutas).decode('utf-8')
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 2075: character maps to <undefined>

Body:
Try using tika to extract the text:

from tika import parser

PdfPath = 'file.pdf'
raw = parser.from_file(PdfPath)
textPDF = raw['content']
print(textPDF)

To get specific page contents you can split the file into separate pages/sections using PyPDF2 and use this method on splitted pages.


问:
Error: Could not find the correct Provider above this widget Flutter [PropertiesGrid]
I am trying to call a simple GridWiget inside my home page

and this is MyHomePage StatefulWidget:

```<code>import './app_theme.dart';
import 'package:flutter/material.dart';
import './widgets/properties_grid.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  var _showOnlyFavorites = false;
  AnimationController animationController;
  bool multiple = true;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    super.initState();
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 0));
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.white,
      body: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  appBar(),
                  Expanded(
                    child: FutureBuilder<bool>(
                      future: getData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<bool> snapshot) {
                        if (!snapshot.hasData) {
                          return const SizedBox();
                        } else {
                          return PropertiesGrid(_showOnlyFavorites);
                        }
                      },
                    ),
                  ),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    multiple ? Icons.dashboard : Icons.view_agenda,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

</code>```

and this is PropertiesGrid StatelessWidget:

```<code>import 'package:aradi_online_vtwo/providers/properties.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/properties.dart';
import './property_item.dart';

class PropertiesGrid extends StatelessWidget {
  final bool showFavs;

  PropertiesGrid(this.showFavs);

  @override
  Widget build(BuildContext context) {
    final productsData = Provider.of<Properties>(context);
    final products = showFavs ? productsData.favoriteItems : productsData.items;
    return GridView.builder(
      padding: const EdgeInsets.all(10.0),
      itemCount: products.length,
      itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
            value: products[i],
            child: PropertyItem(
                ),
          ),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
      ),
    );
  }
}

</code>```

and the dummy provider data is something looks like this below one:

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

class Properties with ChangeNotifier {
  List<Property> _items = [
    Property(
      id: 'p1',
      purpose: '',
      title: 'House Title sdfsdffdgdfgdfs',
    ),
    Property(
      id: 'p3',
      purpose: '',
      title: 'land title',
    ),
  ];

  List<Property> get items {
    return [..._items];
  }

  List<Property> get favoriteItems {
    return _items.where((propItem) => propItem.isFavorite).toList();
  }

  Property findById(String id) {
    return _items.firstWhere((prop) => prop.id == id);
  }

  void addProperty(Property property) {
    final newProperty = Property(
      id: DateTime.now().toString(),
      purpose: property.purpose,
      title: property.title,
    );
    _items.add(newProperty);
    notifyListeners();
  }

  void updateProperty(String id, Property newProperty) {
    final propIndex = _items.lastIndexWhere((prop) => prop.id == id);
    if (propIndex >= 0) {
      _items[propIndex] = newProperty;
      notifyListeners();
    } else {
      print('...');
    }
  }

  void deleteProperty(String id) {
    _items.removeWhere((prop) => prop.id == id);
    notifyListeners();
  }
}

</code>```

and the GridItem is the below code:

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

import '../providers/property.dart';

class PropertyItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final property = Provider.of<Property>(context, listen: false);
    // final cart = Provider.of<Cart>(context, listen: false);
    return InkWell(
      onTap: () => {},
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
        ),
        elevation: 7,
        margin: EdgeInsets.all(2),
        child: Stack(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15),
                topRight: Radius.circular(15),
              ),
              // color: Colors.transparent,
              child: Image.asset(
                property.image,
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: Consumer<Property>(
                builder: (ctx, property, _) => IconButton(
                  icon: Icon(
                    property.isFavorite ? Icons.favorite : Icons.favorite_border,
                  ),
                  color: Colors.red,
                  onPressed: () {
                    property.toggleFavoriteStatus();
                  },
                ),
              ),
            ),
            Positioned(
                  right: 20,
                  top: 100,
                  child: Container(
                    width: 300,
                    color: Colors.black54,
                    padding: EdgeInsets.symmetric(
                      vertical: 5,
                      horizontal: 20,
                    ),
                    child: Text(
                      property.title,
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                      ),
                      softWrap: true,
                      overflow: TextOverflow.fade,
                    ),
                  ),
                )
          ],
        ),
      ),
    );
  }
}

</code>```

and this is the ModelProvider:

```<code>import 'package:flutter/foundation.dart';

class Property with ChangeNotifier {
  final String id;
  final String purpose;
  final String title;
  bool isFavorite;

  Property({
    @required this.id,
    @required this.purpose,
    @required this.title,
  });

  void toggleFavoriteStatus() {
    isFavorite = !isFavorite;
    notifyListeners();
  }
}

</code>```

As the error in this part:

```<code>return PropertiesGrid(_showOnlyFavorites);
</code>```

I hope some one could help I post all Information could be...

答:
You have to add a change notifier provider as a parent in order to access the property model from descendent widgets.

```<code>ChangeNotifierProvider(
  create: (context) => Property(),
  child: PropertiesGrid(_showOnlyFavorites),
),
</code>```

Now you can access the property change notifier model using Provider.of<Property>(context, listen: false); or using Consumer.

Body:
I am trying to call a simple GridWiget inside my home page

and this is MyHomePage StatefulWidget:

import './app_theme.dart';
import 'package:flutter/material.dart';
import './widgets/properties_grid.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  var _showOnlyFavorites = false;
  AnimationController animationController;
  bool multiple = true;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    super.initState();
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 0));
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.white,
      body: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  appBar(),
                  Expanded(
                    child: FutureBuilder<bool>(
                      future: getData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<bool> snapshot) {
                        if (!snapshot.hasData) {
                          return const SizedBox();
                        } else {
                          return PropertiesGrid(_showOnlyFavorites);
                        }
                      },
                    ),
                  ),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    multiple ? Icons.dashboard : Icons.view_agenda,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

and this is PropertiesGrid StatelessWidget:

import 'package:aradi_online_vtwo/providers/properties.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/properties.dart';
import './property_item.dart';

class PropertiesGrid extends StatelessWidget {
  final bool showFavs;

  PropertiesGrid(this.showFavs);

  @override
  Widget build(BuildContext context) {
    final productsData = Provider.of<Properties>(context);
    final products = showFavs ? productsData.favoriteItems : productsData.items;
    return GridView.builder(
      padding: const EdgeInsets.all(10.0),
      itemCount: products.length,
      itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
            value: products[i],
            child: PropertyItem(
                ),
          ),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
      ),
    );
  }
}

and the dummy provider data is something looks like this below one:

import 'package:flutter/material.dart';
import './property.dart';

class Properties with ChangeNotifier {
  List<Property> _items = [
    Property(
      id: 'p1',
      purpose: '',
      title: 'House Title sdfsdffdgdfgdfs',
    ),
    Property(
      id: 'p3',
      purpose: '',
      title: 'land title',
    ),
  ];

  List<Property> get items {
    return [..._items];
  }

  List<Property> get favoriteItems {
    return _items.where((propItem) => propItem.isFavorite).toList();
  }

  Property findById(String id) {
    return _items.firstWhere((prop) => prop.id == id);
  }

  void addProperty(Property property) {
    final newProperty = Property(
      id: DateTime.now().toString(),
      purpose: property.purpose,
      title: property.title,
    );
    _items.add(newProperty);
    notifyListeners();
  }

  void updateProperty(String id, Property newProperty) {
    final propIndex = _items.lastIndexWhere((prop) => prop.id == id);
    if (propIndex >= 0) {
      _items[propIndex] = newProperty;
      notifyListeners();
    } else {
      print('...');
    }
  }

  void deleteProperty(String id) {
    _items.removeWhere((prop) => prop.id == id);
    notifyListeners();
  }
}

and the GridItem is the below code:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/property.dart';

class PropertyItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final property = Provider.of<Property>(context, listen: false);
    // final cart = Provider.of<Cart>(context, listen: false);
    return InkWell(
      onTap: () => {},
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
        ),
        elevation: 7,
        margin: EdgeInsets.all(2),
        child: Stack(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15),
                topRight: Radius.circular(15),
              ),
              // color: Colors.transparent,
              child: Image.asset(
                property.image,
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: Consumer<Property>(
                builder: (ctx, property, _) => IconButton(
                  icon: Icon(
                    property.isFavorite ? Icons.favorite : Icons.favorite_border,
                  ),
                  color: Colors.red,
                  onPressed: () {
                    property.toggleFavoriteStatus();
                  },
                ),
              ),
            ),
            Positioned(
                  right: 20,
                  top: 100,
                  child: Container(
                    width: 300,
                    color: Colors.black54,
                    padding: EdgeInsets.symmetric(
                      vertical: 5,
                      horizontal: 20,
                    ),
                    child: Text(
                      property.title,
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                      ),
                      softWrap: true,
                      overflow: TextOverflow.fade,
                    ),
                  ),
                )
          ],
        ),
      ),
    );
  }
}

and this is the ModelProvider:

import 'package:flutter/foundation.dart';

class Property with ChangeNotifier {
  final String id;
  final String purpose;
  final String title;
  bool isFavorite;

  Property({
    @required this.id,
    @required this.purpose,
    @required this.title,
  });

  void toggleFavoriteStatus() {
    isFavorite = !isFavorite;
    notifyListeners();
  }
}

As the error in this part:

return PropertiesGrid(_showOnlyFavorites);

I hope some one could help I post all Information could be...

Body:
You have to add a change notifier provider as a parent in order to access the property model from descendent widgets.

ChangeNotifierProvider(
  create: (context) => Property(),
  child: PropertiesGrid(_showOnlyFavorites),
),

Now you can access the property change notifier model using Provider.of<Property>(context, listen: false); or using Consumer.


问:
atoi function on command line arguments
I have a problem with atoi function, when i use it, it returns 0 instead of the wanted number i already know the string shouldn't contain letters but still it wont work.

so here is my code

```<code>#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdbool.h>

    int main(int argc, char **argv)
    {
         int i;

         if (argc != 6){
        printf("the arguments must be 6 to execute.\n");
        exit(0);
         }

         char* useLru = argv[1];
         char* inputFile = argv[2];
         char* outputFile = argv[3];
         char* n = argv[4];
         char* m = argv[5];

         int a = atoi(n);
         int b = atoi(m);

         printf("%s\n%s\n%s\n%d\n%d\n",useLru,inputFile,outputFile,a,b);

        return 0;
    }
</code>```

this is my input from command line:

```<code> ./Memo 1 intput.txt output.txt 1000 50
</code>```

and this is the output i get:

```<code>1
intput.txt
output.txt
0
0
</code>```

problem is with a and b why they print zeros?

答:
When I copy/paste the input you give to my test program, this is what it shows on the terminal

My program is called test.

The function atoi is going to fail at the first character (not a digit).

The extra characters are invisible in your question, and on it's editing page.

Title: atoi function on command line arguments

Body:
I have a problem with atoi function, when i use it, it returns 0 instead of the wanted number i already know the string shouldn't contain letters but still it wont work.

so here is my code

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdbool.h>

    int main(int argc, char **argv)
    {
         int i;

         if (argc != 6){
        printf("the arguments must be 6 to execute.\n");
        exit(0);
         }

         char* useLru = argv[1];
         char* inputFile = argv[2];
         char* outputFile = argv[3];
         char* n = argv[4];
         char* m = argv[5];

         int a = atoi(n);
         int b = atoi(m);

         printf("%s\n%s\n%s\n%d\n%d\n",useLru,inputFile,outputFile,a,b);

        return 0;
    }

this is my input from command line:

 ./Memo 1 intput.txt output.txt 1000 50

and this is the output i get:

1
intput.txt
output.txt
0
0

problem is with a and b why they print zeros?


问:
trailing stop loss implementation in pine script study
I am using a simple trailing stop loss setup in one of my strategies (code as shown below). How can i use the same setup in a study script? any help would be highly appreciated.</p>

```<code>strategy.exit("long_tsl", "ChBrkLE", trail_points = 4000, trail_offset = 1500)
strategy.exit("short_tsl", "ChBrkSE", trail_points = 4000, trail_offset = 1500)
</code>```

答:
You're going to have to keep track of if you're long or short, as well as the stop price based on your trailing numbers. Update the stopPrice every candle depending on if you're long or short when price moves in your direction, and also check if your stop was hit every candle, then update your variables accordingly.

I updated this blog post with more details: https://marketscripters.com/pine-script-strategy-vs-study/

Body:
I am using a simple trailing stop loss setup in one of my strategies (code as shown below). How can i use the same setup in a study script? any help would be highly appreciated.

strategy.exit("long_tsl", "ChBrkLE", trail_points = 4000, trail_offset = 1500)
strategy.exit("short_tsl", "ChBrkSE", trail_points = 4000, trail_offset = 1500)


问:
NextJS - ReferenceError: window is not defined
```<code>import dynamic from 'next/dynamic'
import { convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToMarkdown from 'draftjs-to-markdown';
import ReactMarkdown from 'react-markdown'
</code>```

When I refresh page, it happens error: ReferenceError: window is not defined

I follow the solution and changed code as follow:

```<code>const { convertToRaw } = dynamic(import('draft-js'),{ssr:false})
const { Editor } = dynamic(import('react-draft-wysiwyg'),{ssr:false})

const draftToMarkdown = dynamic(() => import("draftjs-to-markdown"), {
  ssr: false
});
const ReactMarkdown = dynamic(() => import("react-markdown"), {ssr:false})
</code>```

But this time, it doesn't display, nothing, it is blank page
Please find the solution

答:
Since Next.js runs on the server & client, you need to make sure that your code access window object only when it runs in the client.

There are 2 things that runs on the client for sure, event handles & useEffect hook / componentDidMount.

Put your window related code there.

Body:
import dynamic from 'next/dynamic'
import { convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToMarkdown from 'draftjs-to-markdown';
import ReactMarkdown from 'react-markdown'

When I refresh page, it happens error: ReferenceError: window is not defined

I follow the solution and changed code as follow:

const { convertToRaw } = dynamic(import('draft-js'),{ssr:false})
const { Editor } = dynamic(import('react-draft-wysiwyg'),{ssr:false})

const draftToMarkdown = dynamic(() => import("draftjs-to-markdown"), {
  ssr: false
});
const ReactMarkdown = dynamic(() => import("react-markdown"), {ssr:false})

But this time, it doesn't display, nothing, it is blank page
Please find the solution


问:
Difference between \b and \B in regex
I am reading a book on regular expression and I came across this example for \b:

The cat scattered his food all over the room.

Using regex - \bcat\b will match the word cat but not the cat in scattered.

For \B the author uses the following example:

Please enter the nine-digit id as it

appears on your color - coded pass-key.

Using regex \B-\B matches - between the word color - coded. Using \b-\b on the other hand matches the - in nine-digit and pass-key.

How come in the first example we use \b to separate cat and in the second use \B to separate -? Using \b in the second example does the opposite of what it did earlier.

Please explain the difference to me.

EDIT: Also, can anyone please explain with a new example?

答:
\b is used as word boundary

```<code>word = "categorical cat"
</code>```

Find all "cat" in the above word

without \b

```<code>re.findall(r'cat',word)
['cat', 'cat']
</code>```

with \b

```<code>re.findall(r'\bcat\b',word)
['cat']
</code>```

ContentLicense: CC BY-SA 3.0

Title: Difference between \b and \B in regex

Body:
\b is used as word boundary

word = "categorical cat"

Find all "cat" in the above word

without \b

re.findall(r'cat',word)
['cat', 'cat']

with \b

re.findall(r'\bcat\b',word)
['cat']


问:
SailsJs/Postgresql - How to create a one way association or one-to-many relation via an unique field
I have two models:

PdfAnnotation.js:

```<code>module.exports = {
  tableName: "pdf_annotations",
  primaryKey: "pk_id",

  attributes: {
    pk_id: {
      type: "number",
      autoIncrement: true
    },
    annotation_id: {
      type: "string",
      unique: true,
      required: true,
    },
    comments: {
      collection: "pdfcomments",
      via: "fk_annotation_id"
    }
  }
};
</code>```

PdfComments.js:

```<code>
module.exports = {
  tableName: "pdf_comments",
  primaryKey: "pk_id",

  attributes: {
    pk_id: {
      type: "number",
      autoIncrement: true,
    },
    fk_annotation_id: {
      model: "pdfannotations",
    },
    comment_content: {
      type: "string",
    },
  }
};
</code>```

When I run these codes:

```<code>PdfAnnotations.create({
  annotation_id: "test3",
});
PdfComments.create({
  fk_annotation_id: 'test3',
  comment_content: 'test',
});
</code>```

I got this error:

I have followed the documentation: https://sailsjs.com/documentation/concepts/models-and-orm/associations/one-to-many.
The difference between my implementation and the docs is: the constraint I used for PdfComments to PdfAnnotations via an unique field annotation_id(string) not the primary key pk_id(number), so that I got the error.

For some reasons I don't want to use annotation_id as a primary key (such as its type is string)

I'm not familiar with Sails and its ORM, hope to see your help.

答:
Try something like this:</p>

```<code>const pdfannotation = await PdfAnnotations.create({
  annotation_id: 'test3',
}).fetch();

const pdfcomment = await PdfComments.create({
  fk_annotation_id: pdfannotation.id,
  comment_content: 'test',
});
</code>```

Body:
I have two models:

PdfAnnotation.js:

module.exports = {
  tableName: "pdf_annotations",
  primaryKey: "pk_id",

  attributes: {
    pk_id: {
      type: "number",
      autoIncrement: true
    },
    annotation_id: {
      type: "string",
      unique: true,
      required: true,
    },
    comments: {
      collection: "pdfcomments",
      via: "fk_annotation_id"
    }
  }
};

PdfComments.js:

module.exports = {
  tableName: "pdf_comments",
  primaryKey: "pk_id",

  attributes: {
    pk_id: {
      type: "number",
      autoIncrement: true,
    },
    fk_annotation_id: {
      model: "pdfannotations",
    },
    comment_content: {
      type: "string",
    },
  }
};

When I run these codes:

PdfAnnotations.create({
  annotation_id: "test3",
});
PdfComments.create({
  fk_annotation_id: 'test3',
  comment_content: 'test',
});

I got this error:

I have followed the documentation: https://sailsjs.com/documentation/concepts/models-and-orm/associations/one-to-many.
The difference between my implementation and the docs is: the constraint I used for PdfComments to PdfAnnotations via an unique field annotation_id(string) not the primary key pk_id(number), so that I got the error.

For some reasons I don't want to use annotation_id as a primary key (such as its type is string)

I'm not familiar with Sails and its ORM, hope to see your help.

Body:
Try something like this:

const pdfannotation = await PdfAnnotations.create({
  annotation_id: 'test3',
}).fetch();

const pdfcomment = await PdfComments.create({
  fk_annotation_id: pdfannotation.id,
  comment_content: 'test',
});


问:
find the corresponding control in repeater control
I have a Repeater control which contains a CheckBox and a lable control in each row. When a CheckBox is selected. I want to retrieve the text of the Label for the corresponding CheckBox. How to get it?

答:
You need to use the ItemCommand event of the Repeater as follows:

```<code>protected void rep1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Command")
        {
            Label lbl = e.Item.FindControl("labelID") as Label;
            lbl.Text //
            CheckBox chk= e.Item.FindControl("chkId") as CheckBox;
            chk.Checked //
        }

    }
</code>```

You can get a better idea from this article: ASP.Net Repeater OnItemCommand Event using C#

Body:
You need to use the ItemCommand event of the Repeater as follows:

protected void rep1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Command")
        {
            Label lbl = e.Item.FindControl("labelID") as Label;
            lbl.Text //
            CheckBox chk= e.Item.FindControl("chkId") as CheckBox;
            chk.Checked //
        }

    }

You can get a better idea from this article: ASP.Net Repeater OnItemCommand Event using C#


问:
Converting Laravel validation message dot syntax into array
I'am using Laravel on server side. Let's imagine our controller receive two fields url [string] and data [array with index head]. We can validate data and customize errors messages with

```<code>$this->validate($request, [

    'url' => 'required',
    'data.head' => 'required',

], [

    'url.required' => 'The :attribute field is required',
    'data.head.required' => 'The :attribute field is required',
]);
</code>```

If validation fails, Laravel send back response with json data

```<code>{
    "url": ["The url field is required"],
    "data.head": ["The data.head field is required"]
}
</code>```

How we can convert response data to send json, as below?

```<code>{
    "url": ["The url field is required"],
    "data": {
        "head": ["The data.head field is required"]
    }
}
</code>```

答:
```<code>key = key.replace(/\./g, '[') + Array(key.split('.').length).join(']');
</code>```

Body:
I'am using Laravel on server side. Let's imagine our controller receive two fields url [string] and data [array with index head]. We can validate data and customize errors messages with

$this->validate($request, [

    'url' => 'required',
    'data.head' => 'required',

], [

    'url.required' => 'The :attribute field is required',
    'data.head.required' => 'The :attribute field is required',
]);

If validation fails, Laravel send back response with json data

{
    "url": ["The url field is required"],
    "data.head": ["The data.head field is required"]
}

How we can convert response data to send json, as below?

{
    "url": ["The url field is required"],
    "data": {
        "head": ["The data.head field is required"]
    }
}


问:
progress bar loading not showing response from server?
I am developing news app but TopHeadlinesFragment loading progress bar not showing response from server
what I want to know where I am making mistake what I have to do in order to show response from server. Maybe something wrong with my observer in topHeadlinesFragment.kt or koin network module

below my screenshot of the app

loading progress

below my TopHeadlinesFragment.kt

```<code>class TopHeadlinesFragment : Fragment() {

    private lateinit var binding: FragmentTopHeadlinesBinding
    private val viewModel by viewModel<MainViewModel>()

    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
    // private val newsRepository: NewsRepository by inject()

    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
        binding.lifecycleOwner = this
        topHeadlinesAdapter = TopHeadlinesAdapter()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
      //  loadingAds()

    }

    private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()

                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.VISIBLE else View.GONE
                    })
                }
                is Results.Failure -> {
                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.INVISIBLE else View.GONE
                })
            }

        }

        viewModel.loadNews()
    })

    }

    }
</code>```

below NewsRepository.kt

```<code>class NewsRepository(
    private val sportNewsApi: SportNewsInterface,
    private val sportNewsDao: SportNewsDao
) {

    companion object{
        const val  TAG=  "Error"
    }

    val data = sportNewsDao.getAllData()

    suspend fun refresh() = withContext(Dispatchers.IO) {
        val articles = sportNewsApi.getNewsAsync().body()?.articles
        if (articles != null) {
            sportNewsDao.addAll(articles)
          Log.e(TAG,"Error")
            Results.Success(articles)
        } else {
            Results.Failure("MyError")
        }
    }
}
</code>```

below My MainViewModel.kt

```<code>class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    val job = Job()

    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    private val _showLoading = MutableLiveData<Boolean>()
    private val _sportList = MutableLiveData<Results>()

    val showLoading: LiveData<Boolean>
        get() = _showLoading

    val sportList: LiveData<Results>
        get() = _sportList

    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        _showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result =  newsRepository.refresh()
            _sportList.value = result
            _showLoading.value = false
        }
    }

    override fun onCleared() {
        job.cancel()
    }

}
</code>```

below my KoinNetworkModule.kt

```<code>const val BASE_URL = "https://newsapi.org/"
val netModule = module {

    single {
        createWebService<SportNewsInterface>(
            okHttpClient = createHttpClient(),
            factory = RxJava2CallAdapterFactory.create(),
            baseUrl = BASE_URL
        )
    }
}

/* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
fun createHttpClient(): OkHttpClient {
    val client = OkHttpClient.Builder()
    client.readTimeout(5 * 60, TimeUnit.SECONDS)
    return client.addInterceptor {
        val original = it.request()
        val requestBuilder = original.newBuilder()
        requestBuilder.header("Content-Type", "application/json")
        val request = requestBuilder.method(original.method, original.body).build()
        return@addInterceptor it.proceed(request)
    }.build()
}

/* function to build our Retrofit service */
inline fun <reified T> createWebService(
    okHttpClient: OkHttpClient,
    factory: CallAdapter.Factory, baseUrl: String
): T {
    val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .addCallAdapterFactory(factory)
        .client(okHttpClient)
        .build()
    return retrofit.create(T::class.java)
}
</code>```

答:
Got your Problem. If you seriously want to show the response, whatever you are getting use this code in the Retrofit Instance. The role of Intercepter is used to show the request and response at the Log level. You can findout the URL of API, Request and resonse in the Log window.

Now modify  KoinNetworkModule.kt like this

```<code>            const val BASE_URL = "https://newsapi.org/"
            val netModule = module {

                single {
                    createWebService<SportNewsInterface>(
                        okHttpClient = createHttpClient(),
                        factory = RxJava2CallAdapterFactory.create(),
                        baseUrl = BASE_URL
                    )
                }
            }

            /* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
            fun createHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        val client1 = OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .writeTimeout(2, TimeUnit.MINUTES) // write timeout
            .readTimeout(2, TimeUnit.MINUTES) // read timeout

            .addInterceptor(interceptor)
            .build()

            /* function to build our Retrofit service */
            inline fun <reified T> createWebService(
                okHttpClient: OkHttpClient,
                factory: CallAdapter.Factory, baseUrl: String
            ): T {

                val retrofit = Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
                    .addCallAdapterFactory(CoroutineCallAdapterFactory())
                    .addCallAdapterFactory(factory)
                    .client(client1)
                    .build()
                return retrofit.create(T::class.java)
            }
</code>```

Body:
I am developing news app but TopHeadlinesFragment loading progress bar not showing response from server
what I want to know where I am making mistake what I have to do in order to show response from server. Maybe something wrong with my observer in topHeadlinesFragment.kt or koin network module

below my screenshot of the app

loading progress

below my TopHeadlinesFragment.kt

class TopHeadlinesFragment : Fragment() {

    private lateinit var binding: FragmentTopHeadlinesBinding
    private val viewModel by viewModel<MainViewModel>()

    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
    // private val newsRepository: NewsRepository by inject()

    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
        binding.lifecycleOwner = this
        topHeadlinesAdapter = TopHeadlinesAdapter()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
      //  loadingAds()

    }

    private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()

                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.VISIBLE else View.GONE
                    })
                }
                is Results.Failure -> {
                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.INVISIBLE else View.GONE
                })
            }

        }

        viewModel.loadNews()
    })

    }

    }

below NewsRepository.kt

class NewsRepository(
    private val sportNewsApi: SportNewsInterface,
    private val sportNewsDao: SportNewsDao
) {

    companion object{
        const val  TAG=  "Error"
    }

    val data = sportNewsDao.getAllData()

    suspend fun refresh() = withContext(Dispatchers.IO) {
        val articles = sportNewsApi.getNewsAsync().body()?.articles
        if (articles != null) {
            sportNewsDao.addAll(articles)
          Log.e(TAG,"Error")
            Results.Success(articles)
        } else {
            Results.Failure("MyError")
        }
    }
}

below My MainViewModel.kt

class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    val job = Job()

    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    private val _showLoading = MutableLiveData<Boolean>()
    private val _sportList = MutableLiveData<Results>()

    val showLoading: LiveData<Boolean>
        get() = _showLoading

    val sportList: LiveData<Results>
        get() = _sportList

    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        _showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result =  newsRepository.refresh()
            _sportList.value = result
            _showLoading.value = false
        }
    }

    override fun onCleared() {
        job.cancel()
    }

}

below my KoinNetworkModule.kt

const val BASE_URL = "https://newsapi.org/"
val netModule = module {

    single {
        createWebService<SportNewsInterface>(
            okHttpClient = createHttpClient(),
            factory = RxJava2CallAdapterFactory.create(),
            baseUrl = BASE_URL
        )
    }
}

/* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
fun createHttpClient(): OkHttpClient {
    val client = OkHttpClient.Builder()
    client.readTimeout(5 * 60, TimeUnit.SECONDS)
    return client.addInterceptor {
        val original = it.request()
        val requestBuilder = original.newBuilder()
        requestBuilder.header("Content-Type", "application/json")
        val request = requestBuilder.method(original.method, original.body).build()
        return@addInterceptor it.proceed(request)
    }.build()
}

/* function to build our Retrofit service */
inline fun <reified T> createWebService(
    okHttpClient: OkHttpClient,
    factory: CallAdapter.Factory, baseUrl: String
): T {
    val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .addCallAdapterFactory(factory)
        .client(okHttpClient)
        .build()
    return retrofit.create(T::class.java)
}

Body:
Got your Problem. If you seriously want to show the response, whatever you are getting use this code in the Retrofit Instance. The role of Intercepter is used to show the request and response at the Log level. You can findout the URL of API, Request and resonse in the Log window.

Now modify  KoinNetworkModule.kt like this

            const val BASE_URL = "https://newsapi.org/"
            val netModule = module {

                single {
                    createWebService<SportNewsInterface>(
                        okHttpClient = createHttpClient(),
                        factory = RxJava2CallAdapterFactory.create(),
                        baseUrl = BASE_URL
                    )
                }
            }

            /* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
            fun createHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        val client1 = OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .writeTimeout(2, TimeUnit.MINUTES) // write timeout
            .readTimeout(2, TimeUnit.MINUTES) // read timeout

            .addInterceptor(interceptor)
            .build()

            /* function to build our Retrofit service */
            inline fun <reified T> createWebService(
                okHttpClient: OkHttpClient,
                factory: CallAdapter.Factory, baseUrl: String
            ): T {

                val retrofit = Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
                    .addCallAdapterFactory(CoroutineCallAdapterFactory())
                    .addCallAdapterFactory(factory)
                    .client(client1)
                    .build()
                return retrofit.create(T::class.java)
            }


问:
DataGrid is not included inside of "this" context in subscribe scope in Angular
In my Angular project, a page includes 2 components named "head" and "product"..

In "head", I can change the currency of page.. I keep the currency information in localStorage.. When the currency is changed, I push a random number by "next" as below:

this.service.refreshNumberOfAllPriceByCurrency.next(Math.random()); //"refreshNumberOfAllPriceByCurrency" is defined as ReplaySubject<any>(1) in service component.

This line is triggering subscribe in "product" component as below:

```<code>constructor(.........)
{
   this.service.refreshNumberOfAllPriceByCurrency.subscribe(number => {
        this.gridProduct.instance.refresh();
        this.gridPrice.instance.refresh();
   });
}
</code>```

When debugging inside of subscribe scope, "this" context doesn't contain gridProduct, gridPrice and linensOfferId. So it can not get the instance of "undefined"…

How can I get the instance of these grids inside of subscribe scope?

Thanks in advance…

答:
I solved this problem. "this.service.refreshNumberOfAllPriceByCurrency.subscribe()" event is in constructor. I modified the code as below:

```<code>constructor()
{
   var this2=this;

   this.service.refreshNumberOfAllPriceByCurrency.subscribe(number => {
       if (this2.linensOfferId > 0) {
           this2.gridProduct.instance.refresh();
           this2.gridPrice.instance.refresh();
       }
   });
}
</code>```

Before subscribe(), I defined this2 and it is equal to "this". By this way, I can reach this context fully from inside of subscribe() scope…

Thank you…

Body:
In my Angular project, a page includes 2 components named "head" and "product"..

In "head", I can change the currency of page.. I keep the currency information in localStorage.. When the currency is changed, I push a random number by "next" as below:

this.service.refreshNumberOfAllPriceByCurrency.next(Math.random()); //"refreshNumberOfAllPriceByCurrency" is defined as ReplaySubject<any>(1) in service component.

This line is triggering subscribe in "product" component as below:

constructor(.........)
{
   this.service.refreshNumberOfAllPriceByCurrency.subscribe(number => {
        this.gridProduct.instance.refresh();
        this.gridPrice.instance.refresh();
   });
}

When debugging inside of subscribe scope, "this" context doesn't contain gridProduct, gridPrice and linensOfferId. So it can not get the instance of "undefined"…

How can I get the instance of these grids inside of subscribe scope?

Thanks in advance…

Body:
I solved this problem. "this.service.refreshNumberOfAllPriceByCurrency.subscribe()" event is in constructor. I modified the code as below:

constructor()
{
   var this2=this;

   this.service.refreshNumberOfAllPriceByCurrency.subscribe(number => {
       if (this2.linensOfferId > 0) {
           this2.gridProduct.instance.refresh();
           this2.gridPrice.instance.refresh();
       }
   });
}

Before subscribe(), I defined this2 and it is equal to "this". By this way, I can reach this context fully from inside of subscribe() scope…

Thank you…


问:
How do I edit multiple input controlled components in React?
I have a component that stores a contact object as state - {firstName: "John", lastName: "Doe", phone: "1234567890} I want to create a form to edit this object but if I want the inputs to hold the value of the original contact parameter, I need to make each input a controlled component. However, I don't know how to create a handleChange function that will adjust to each parameter because my state only holds {contact: {...}}. Below is what I currently have -

```<code>  getInitialState: function () {
    return ({contact: {}});
  },
  handleChange: function (event) {
    this.setState({contact: event.target.value });
  },
  render: function () {
    return (
        <div>
          <input type="text" onChange={this.handleChange} value={this.state.contact.firstName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
        </div>
      );
    }
</code>```

I wish in my handleChange I can do something like

```<code>  handleChange: function (event) {
    this.setState({contact.firstName: event.target.value });
  }
</code>```

答:
```<code>updatePrevData=(event)=>{
    let eventName=event.target.name;
   this.setState({
       ...this.state,
       prev_data:{
        ...this.state.prev_data,
        [eventName]:event.target.value
       }

   })

   console.log(this.state)

}
</code>```

Body:
I have a component that stores a contact object as state - {firstName: "John", lastName: "Doe", phone: "1234567890} I want to create a form to edit this object but if I want the inputs to hold the value of the original contact parameter, I need to make each input a controlled component. However, I don't know how to create a handleChange function that will adjust to each parameter because my state only holds {contact: {...}}. Below is what I currently have -

  getInitialState: function () {
    return ({contact: {}});
  },
  handleChange: function (event) {
    this.setState({contact: event.target.value });
  },
  render: function () {
    return (

          <input type="text" onChange={this.handleChange} value={this.state.contact.firstName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>

      );
    }

I wish in my handleChange I can do something like

  handleChange: function (event) {
    this.setState({contact.firstName: event.target.value });
  }


问:
How to parse below JSON Data
I have below JSON Array extracted from Console of browser through data saved in localstorage.

Below I have two json objects which I store in localstorage while adding it in via inputtext.
It has inch denoted in goods using doublequotes (")

But, on next page where I try to extract and using JSON.parse() function gives error due to usage of double quotes inside value of goods

```<code>0: "{"srno":"1","goods":"Item 1 - 1/2" x 3"","hsncode":"12345","qty":"12","rate":"122/-","taxablevalue":"123.60"}"
1: "{"srno":"2","goods":"Item 2- 1 " x 4" ","hsncode":"1245","qty":"10","rate":"10/-","taxablevalue":"12.15"}"
</code>```

答:
Please go to https://json.org/example.html and find the issues what is difference between your JSON string and the normal one.

```<code>{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
</code>```

Your JSON string should be start and end with curly braces {}.
Also, you need to escape the double quotes, as \" a simple String.replace

Hope this one helps you.

Title: How to parse below JSON Data

Body:
I have below JSON Array extracted from Console of browser through data saved in localstorage.

Below I have two json objects which I store in localstorage while adding it in via inputtext.
It has inch denoted in goods using doublequotes (")

But, on next page where I try to extract and using JSON.parse() function gives error due to usage of double quotes inside value of goods

0: "{"srno":"1","goods":"Item 1 - 1/2" x 3"","hsncode":"12345","qty":"12","rate":"122/-","taxablevalue":"123.60"}"
1: "{"srno":"2","goods":"Item 2- 1 " x 4" ","hsncode":"1245","qty":"10","rate":"10/-","taxablevalue":"12.15"}"

Body:
Please go to https://json.org/example.html and find the issues what is difference between your JSON string and the normal one.

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

Your JSON string should be start and end with curly braces {}.
Also, you need to escape the double quotes, as \" a simple String.replace

Hope this one helps you.


问:
Print SubArray of Maximum Contiguous product in Array
Maximum Product Subarray
Given an array that contains both positive and negative integers, find the subarray of the maximum product .
Examples:

Input: arr[] = {6, -3, -10, 0, 2}
Output:  The subarray is {6, -3, -10}

Input: arr[] = {-1, -3, -10, 0, 60}
Output:  The subarray is {60}

Input: arr[] = {-2, -3, 0, -2, -40}
Output:  The subarray is {-2, -40}

Note: Finding the Max Product is done as using the kadane algo where i tried to reuse it for finding sub array but not able to break the part of finding the start index, finding end index is easy. end index is where res  < max.

```<code>public int maxProductSubArray(int arr[], int len) {

        int res = arr[0];

        int max = arr[0];
        int min = arr[0];

        for (int i = 1; i < len; i++) {

            int temp = max;

            max = Math.max(Math.max(max * arr[i], min * arr[i]), arr[i]);
            min = Math.min(Math.min(temp * arr[i], min * arr[i]), arr[i]);

            res = Math.max(res, max);
        }

        return res;

    }
</code>```

but not able to break the problem to find the SubArray.

答:
This problem can be efficiently solved by divide and conquer.

Assume you want to solve the problem for a subarray [l, r]; Then, assuming c = (l + r) / 2 the solution is either subarray in [l, c], or in [c + 1, r], or in some subarray containing c and c + 1.

Then let's define a function f(l, r) returning the answer for subsegment; Then, to compute this function, first recursively call f(l, c) and f(c + 1, r) and pick the maximum as the temporary answer. Then compute multiplications of segments [c, c], then [c - 1, c] and so on (using multiplication of [c - k, c] = multiplication of [c - k + 1, c] * array[c - k]) and compute maximum and minimum multiplications across all such segments. Do the same for segments to the right of c ([c + 1, c + 1], [c + 1, c + 2] and so on) Then, the answer will be either a temporary answer, of multiplication of maximums or multiplication of minimums or multiplication of minimum and maximum and vice versa (minimum times maximum is required if such multiplication would be negative). Return the maximum across these four values or the temporary answer as the function result.

If it is necessary, instead of returning just the value of multiplication function can also return the segment where these value is reached.

This solution uses Θ(n log n) time and Θ(n) space.

Body:
Maximum Product Subarray
Given an array that contains both positive and negative integers, find the subarray of the maximum product .
Examples:

Input: arr[] = {6, -3, -10, 0, 2}
Output:  The subarray is {6, -3, -10}

Input: arr[] = {-1, -3, -10, 0, 60}
Output:  The subarray is {60}

Input: arr[] = {-2, -3, 0, -2, -40}
Output:  The subarray is {-2, -40}

Note: Finding the Max Product is done as using the kadane algo where i tried to reuse it for finding sub array but not able to break the part of finding the start index, finding end index is easy. end index is where res  < max.

public int maxProductSubArray(int arr[], int len) {

        int res = arr[0];

        int max = arr[0];
        int min = arr[0];

        for (int i = 1; i < len; i++) {

            int temp = max;

            max = Math.max(Math.max(max * arr[i], min * arr[i]), arr[i]);
            min = Math.min(Math.min(temp * arr[i], min * arr[i]), arr[i]);

            res = Math.max(res, max);
        }

        return res;

    }

but not able to break the problem to find the SubArray.


问:
How to use forEach in vueJs?
I have a response like below from an API call,

Now, I have to repeat the whole arrays inside the arrays. How do I do that in VueJS?

I have searched for using forEach.. nowhere I found forEach usage like key|value pair.

Can anyone help me on how to fetch the values from that arrays by using either forEach or any else(VueJS)?

Thanks & Regards,

答:
In VueJS you can loop through an array like this :
    const array1 = ['a', 'b', 'c'];

```<code>Array.from(array1).forEach(element =>
 console.log(element)
      );
</code>```

in my case I want to loop through files and add their types to another array:

```<code> Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }
</code>```

Title: How to use forEach in vueJs?

Body:
In VueJS you can loop through an array like this :
    const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element =>
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }


问:
Exception after code conversion from Java to Kotlin: java.lang.ClassCastException: java.lang.String cannot be cast to com.example.misc.Restaurant
I am in a process of converting my app from Java to Kotlin and I am getting a ClassCastException  while executing the code below. Thoughts?

```<code>private fun getImageFragments(imagesList: MutableList<Restaurant?>?) {

   if (imagesList != null) {

   val restaurant: Restaurant? = imagesList[0]
/*exception: java.lang.ClassCastException:
  java.lang.String cannot be cast to com.example.misc.Restaurant */

   }
}
</code>```

Not sure if the implementation of the Restaurant Class is of any importance in this case? https://pastebin.com/q5z76exh

While inspecting the contents of imagesList[0] with debugger I am seeing this:

ArrayList size = 1

```<code>    https://domainName.com/files/app/banners/1550449003515.png
    count=116
    hash:0
    shadow$_klass_=class java.lang.String
    shadow$_monitor_
</code>```

Moreover, when I try to rewrite the problematic line to

```<code>val restaurant: String? = imagesList[0]
</code>```

I am getting:

```<code>Type mismatch: inferred type is Restaurant? but String? was expected
</code>```

EDIT:

So as per requests I am posting some more code, be warned though, it's not going to be pretty. Trust me, I would gladly show you the whole thing if it wasn't closed but the main reason is I don't want you to suffer. Ask if you want more. Here is the code of the function that is calling getImageFragments:

```<code>getDrawerBanners(App.preference.getString("language", "ENG"),
object : OnAPIRequestListResultListener<Restaurant?> {

    override fun onListResult(list: MutableList<Restaurant?>?) {
        bannerViewPager.adapter = fragmentManager?.
        let{ DrawerBannersAdapter(it, getImageFragments(list)) }
    }
})
</code>```

And here is OnAPIRequestListResultListener interface, I have a strong feeling that error might be hidden smowewhere here, if you think otherwise read on further.

```<code>interface OnAPIRequestListResultListener<T> {
                fun onListResult(list: MutableList<T>?)
            }
</code>```

Original signature + body of getDrawerBanners function

```<code> // Downloading banners  from server
    @JvmStatic
fun getDrawerBanners(languageCode: String?, listener:
OnAPIRequestListResultListener<Restaurant?>) {
    val async = GetMenuBannersAsync(listener)
    async.execute(languageCode)
}
</code>```

GetMenuBannersAsync

```<code>private class GetMenuBannersAsync(var listener:
OnAPIRequestListResultListener<Restaurant?>) : AsyncTask<String?, Void?, Void?>() {
        var bannersUrls: MutableList<Restaurant?> = ArrayList()

        override fun doInBackground(vararg params: String?): Void? {
            val url = "https://api.smartapp.com/App/Language/" + params[0]
            val client: HttpClient = DefaultHttpClient()
            val httpGet = HttpGet(url)
                httpGet.addHeader(AUTHORIZATION, AUTHORIZATION_STRING)
            var httpResponse: HttpResponse? = null
            var httpEntity: HttpEntity? = null
                httpResponse = client.execute(httpGet)
                httpEntity = httpResponse.entity
            val response = EntityUtils.toString(httpEntity)
            val json = JSONObject(response)
                // Getting drawer banner
            val bannersArray = json.getJSONArray("mainMenuBanners")
                bannersUrls = ArrayList()

            for (i in 0 until bannersArray.length()) {
                val bannerObj = bannersArray.getJSONObject(i)
                val imageUrl = bannerObj.getString("image")
                    (bannersUrls as ArrayList<String>).add(imageUrl)
            }

            return null
        }

        override fun onPostExecute(result: Void?) {
            listener.onListResult(bannersUrls)
            super.onPostExecute(result)
        }

    }
</code>```

答:
The problem lies in your GetMenuBannersAsync function. There you create the bannersUrls list with type MutableList<Restaurant?> but the you put values into the list with (bannersUrls as ArrayList<String>).add(imageUrl). The cast expression tells the compiler that the conversion you do is save, which it is not in your case.

So always remember that you are on your own if your use a cast and the type system will no longer help you to detect problems. You need to make sure that the conversion is safe do do.

To solve the actual problem you need to create the Restaurant objects and put them into the list instead of urls.

Body:
I am in a process of converting my app from Java to Kotlin and I am getting a ClassCastException  while executing the code below. Thoughts?

private fun getImageFragments(imagesList: MutableList<Restaurant?>?) {

   if (imagesList != null) {

   val restaurant: Restaurant? = imagesList[0]
/*exception: java.lang.ClassCastException:
  java.lang.String cannot be cast to com.example.misc.Restaurant */

   }
}

Not sure if the implementation of the Restaurant Class is of any importance in this case? https://pastebin.com/q5z76exh

While inspecting the contents of imagesList[0] with debugger I am seeing this:

ArrayList size = 1

    https://domainName.com/files/app/banners/1550449003515.png
    count=116
    hash:0
    shadow$_klass_=class java.lang.String
    shadow$_monitor_

Moreover, when I try to rewrite the problematic line to

val restaurant: String? = imagesList[0]

I am getting:

Type mismatch: inferred type is Restaurant? but String? was expected

EDIT:

So as per requests I am posting some more code, be warned though, it's not going to be pretty. Trust me, I would gladly show you the whole thing if it wasn't closed but the main reason is I don't want you to suffer. Ask if you want more. Here is the code of the function that is calling getImageFragments:

getDrawerBanners(App.preference.getString("language", "ENG"),
object : OnAPIRequestListResultListener<Restaurant?> {

    override fun onListResult(list: MutableList<Restaurant?>?) {
        bannerViewPager.adapter = fragmentManager?.
        let{ DrawerBannersAdapter(it, getImageFragments(list)) }
    }
})

And here is OnAPIRequestListResultListener interface, I have a strong feeling that error might be hidden smowewhere here, if you think otherwise read on further.

interface OnAPIRequestListResultListener<T> {
                fun onListResult(list: MutableList<T>?)
            }

Original signature + body of getDrawerBanners function

 // Downloading banners  from server
    @JvmStatic
fun getDrawerBanners(languageCode: String?, listener:
OnAPIRequestListResultListener<Restaurant?>) {
    val async = GetMenuBannersAsync(listener)
    async.execute(languageCode)
}

GetMenuBannersAsync

private class GetMenuBannersAsync(var listener:
OnAPIRequestListResultListener<Restaurant?>) : AsyncTask<String?, Void?, Void?>() {
        var bannersUrls: MutableList<Restaurant?> = ArrayList()

        override fun doInBackground(vararg params: String?): Void? {
            val url = "https://api.smartapp.com/App/Language/" + params[0]
            val client: HttpClient = DefaultHttpClient()
            val httpGet = HttpGet(url)
                httpGet.addHeader(AUTHORIZATION, AUTHORIZATION_STRING)
            var httpResponse: HttpResponse? = null
            var httpEntity: HttpEntity? = null
                httpResponse = client.execute(httpGet)
                httpEntity = httpResponse.entity
            val response = EntityUtils.toString(httpEntity)
            val json = JSONObject(response)
                // Getting drawer banner
            val bannersArray = json.getJSONArray("mainMenuBanners")
                bannersUrls = ArrayList()

            for (i in 0 until bannersArray.length()) {
                val bannerObj = bannersArray.getJSONObject(i)
                val imageUrl = bannerObj.getString("image")
                    (bannersUrls as ArrayList<String>).add(imageUrl)
            }

            return null
        }

        override fun onPostExecute(result: Void?) {
            listener.onListResult(bannersUrls)
            super.onPostExecute(result)
        }

    }


问:
stat() function only works in the current directory C language
i'm using C on windows to read the contents of a directory and info about each entry, however the stat() function only works if i opened the current directory "."

directory = opendir(".")

whenever i try something like this "C:\Users\User\Desktop\programming" it does not work and outputs -1

directory = opendir("C:\\Users\\User\\Desktop\\programming")

can you pleas guide me here

```<code>#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void perror(const char *str);// for error detail

int main()
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("C:\\Users\\User\\Desktop\\programming");//also C:\\Users\\User\\Desktop\\programming\\ didn't work
    if ( directory == NULL )
        {
            puts("the directory couldn't be accessed or does not exist");
          return(2);
        }

    printf("No   type         name              size           TimeStamp \n\n");
    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly
        stat(file->d_name,&info);
        if ((stat(file->d_name,&info)) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }

    return(0);
}
</code>```

the output pic link : https://i.stack.imgur.com/tORZU.png

答:
```<code>if ( (stat(file->d_name, &info) ) == -1) { ...
</code>```

file->d_name contains only a string with the name of the file, but not its path. stat() needs to have the exact path to the file as first argument.

Try:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>

int main (void)
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;
    char* path = "C:\\Users\\User\\Desktop\\programming";

    // entering the directory
    directory = opendir(path);

    if ( directory == NULL )
    {
        puts("the directory couldn't be accessed or does not exist");
        return(2);
    }

    printf("No   type         name              size           TimeStamp \n\n");

    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly

        if (stat(path, &info) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }

    return(0);
}
</code>```

Body:
i'm using C on windows to read the contents of a directory and info about each entry, however the stat() function only works if i opened the current directory "."

directory = opendir(".")

whenever i try something like this "C:\Users\User\Desktop\programming" it does not work and outputs -1

directory = opendir("C:\\Users\\User\\Desktop\\programming")

can you pleas guide me here

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void perror(const char *str);// for error detail

int main()
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("C:\\Users\\User\\Desktop\\programming");//also C:\\Users\\User\\Desktop\\programming\\ didn't work
    if ( directory == NULL )
        {
            puts("the directory couldn't be accessed or does not exist");
          return(2);
        }

    printf("No   type         name              size           TimeStamp \n\n");
    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly
        stat(file->d_name,&info);
        if ((stat(file->d_name,&info)) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }

    return(0);
}

the output pic link : https://i.stack.imgur.com/tORZU.png

Body:
if ( (stat(file->d_name, &info) ) == -1) { ...

file->d_name contains only a string with the name of the file, but not its path. stat() needs to have the exact path to the file as first argument.

Try:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>

int main (void)
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;
    char* path = "C:\\Users\\User\\Desktop\\programming";

    // entering the directory
    directory = opendir(path);

    if ( directory == NULL )
    {
        puts("the directory couldn't be accessed or does not exist");
        return(2);
    }

    printf("No   type         name              size           TimeStamp \n\n");

    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly

        if (stat(path, &info) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }

    return(0);
}


问:
how to get absolute xpath from a relative xpath
I can find an object with a relative xpath. is there a way I can get it's absolute path?
something like absXpath = weblelement.getxpath();
working in c#.

thanks

答: I don't know if this helps but when you inspect the element you can copy the full xpath i.e. copy -> copy full xpath</p>


问:
How to display comments coming from Redux store on individual component
I have created a basic single page app, on initial page there is some dummy data and on click of each item I direct user to individual details page of that item. I wanted to implement comment and delete comment functionality which I successfully did but now when I comment or delete the comment it doesn't only happen at that individual page but in every other page too. Please see the sandbox example for better clarify.

https://codesandbox.io/s/objective-feistel-g62g0?file=/src/components/ProductDetails.js

So once you add some comments in individual page, go back and then click to another products, apparently you will see that the comments you've done in other pages are also available there. What do you think causing this problem ?

答:
The same state being reused by all the different pages.

Try to load dynamically load reducers for each page/router differently to use distinct state values.

You can start from here

Redux modules and code splitting


问:
Swift - checking type of a generic class
I am having a Swift generic class as follows:

```<code>class List<T> {
    var value: T
    var next: List<T>?
    ...
}
</code>```

I would like to check for some object if it is an instance of this class, no matter what the type T is. For example, if I'm having:

```<code>let a = List<Int>(2, 3)
let b = List<Any>(5, List<String>("a", "b"))
let c = "something which is not a list"
</code>```

I would like the procedure (or the code snippet) to return true for a and b, and false for c.

Thanks in advance.

答:
One of the solutions can be to use a protocol for your generic List:

```<code>protocol AnyList {}

class List<T>: AnyList {
    var value: T
    var next: List<T>?
    ...
}

func isList<T>(_ object: T) -> Bool {
    object is AnyList
}

let a = List<Int>(value: 2)
let b = "something which is not a list"

print(isList(a)) // true
print(isList(b)) // false
</code>```

Body:
I am having a Swift generic class as follows:

class List<T> {
    var value: T
    var next: List<T>?
    ...
}

I would like to check for some object if it is an instance of this class, no matter what the type T is. For example, if I'm having:

let a = List<Int>(2, 3)
let b = List<Any>(5, List<String>("a", "b"))
let c = "something which is not a list"

I would like the procedure (or the code snippet) to return true for a and b, and false for c.

Thanks in advance.

Body:
One of the solutions can be to use a protocol for your generic List:

protocol AnyList {}

class List<T>: AnyList {
    var value: T
    var next: List<T>?
    ...
}

func isList<T>(_ object: T) -> Bool {
    object is AnyList
}

let a = List<Int>(value: 2)
let b = "something which is not a list"

print(isList(a)) // true
print(isList(b)) // false


问:
Android Studio data binding error, cannot resolve symbol
I have a perfectly working project. It didn't give any error or anything. But today I upgraded my Android Studio to 4.0 version and Gradle plugin version to 4.0.0. Then I changed my gradle file.

So I change it from this

```<code>viewBinding {
        enabled = true
    }
</code>```

to this

```<code>buildFeatures{
        dataBinding = true
    }
</code>```

I sync my project. But it gives "cannot resolve symbol" error with my databindings.

I have a xml named "activity_admin_screen.xml" so I have variable like this

```<code>private  ActivityAdminScreenBinding binding;
</code>```

This was working perfectly but now it gives cannot resolve symbol error. I tried invalidate and restart a  few times. I deleted project from my computer and clone it from my github again as a new project. I tried to write another xml files. But none of them recognized. I tried to write a new xml named activity_admin_screen2.xml. When I tried to write is as ActivityAdminScreen2Binding Android Studio doesn't recognize it.

I tried to Rebuild my entire project this doesn't help either. Can anyone help me with it I can't run my project.

I didn't post any code because this code works with previous Android Studio version perfectly. After the update no code changed but it doesn't work. I made a research but everyone says there is no need to change bindings. They say Android studio should take care of it. Thanks in advance I am  open for any possible solution.

Solution:

I changed this

```<code>buildFeatures{
        dataBinding = true
    }
</code>```

to this

```<code>buildFeatures{
        viewBinding = true
    }
</code>```

Now it is working perfectly.

答:
For android studio 4.0, You should try with  viewBinding = true

```<code>android {
    buildFeatures {
        viewBinding = true
    }
}
</code>```

Then Clean-Rebuild.

Body:
I have a perfectly working project. It didn't give any error or anything. But today I upgraded my Android Studio to 4.0 version and Gradle plugin version to 4.0.0. Then I changed my gradle file.

So I change it from this

viewBinding {
        enabled = true
    }

to this

buildFeatures{
        dataBinding = true
    }

I sync my project. But it gives "cannot resolve symbol" error with my databindings.

I have a xml named "activity_admin_screen.xml" so I have variable like this

private  ActivityAdminScreenBinding binding;

This was working perfectly but now it gives cannot resolve symbol error. I tried invalidate and restart a  few times. I deleted project from my computer and clone it from my github again as a new project. I tried to write another xml files. But none of them recognized. I tried to write a new xml named activity_admin_screen2.xml. When I tried to write is as ActivityAdminScreen2Binding Android Studio doesn't recognize it.

I tried to Rebuild my entire project this doesn't help either. Can anyone help me with it I can't run my project.

I didn't post any code because this code works with previous Android Studio version perfectly. After the update no code changed but it doesn't work. I made a research but everyone says there is no need to change bindings. They say Android studio should take care of it. Thanks in advance I am  open for any possible solution.

Solution:

I changed this

buildFeatures{
        dataBinding = true
    }

to this

buildFeatures{
        viewBinding = true
    }

Now it is working perfectly.

Body:
For android studio 4.0, You should try with  viewBinding = true

android {
    buildFeatures {
        viewBinding = true
    }
}

Then Clean-Rebuild.


问:
How to synchronise multiple threads?
How would you synchronise multiple threads to be at a certain place in their code at a particular time?

I am not looking for WaitAll, await etc. As in the example code, the threads do not return, only one thread is created per worker.

I have made this monster...
It works for simple and slow cases, but there is a race condition: when a fast thread locks _sync before the synchroniser. As a result sometimes that thread will execute more than once per cycle and break any assumptions of what is ready for use by other threads.

```<code>static readonly Stopwatch timer = new Stopwatch();

static readonly object _locker1 = new object();
static readonly object _locker2 = new object();
...
static readonly object _sync = new object();

static void Main()
{
    Task.Run(Synchroniser);
    Task.Run(DoWork1);
    Task.Run(DoWork2);
    ...
}

static void Synchroniser()
{
    while (true)
    {
        lock (_sync)
        {
            timer.Restart();
            while (timer.ElapseMilliseconds < 16) ;
            lock (_locker1) ;
            lock (_locker2) ;
            ...
        }
    }
}

static void DoWork1()
{
    while (true)
    {
        lock (_locker1)
        {
            //all worker threads continue from here at the same time
            ...
        }
        lock (_sync) ;
    }
}
...
</code>```

答:
You should have a look at the wait() function and such for the Task class.
It provides a way to continue execution of the current thread when a Task or a given array of tasks finishes execution.

For reference: https://learn.microsoft.com/en-gb/dotnet/api/system.threading.tasks.task.wait?view=netcore-3.1

So for example:

```<code>static void Main()
{
    Task t1 = Task.Run(() => DoStuff_1("Task"));
    Task t2 = Task.Run(() => DoStuff_2("Task"));

    Task.WaitAll({t1, t2}); // Blocks the current thread till the given tasks finish execution
}
</code>```

Title: How to synchronise multiple threads?

Body:
How would you synchronise multiple threads to be at a certain place in their code at a particular time?

I am not looking for WaitAll, await etc. As in the example code, the threads do not return, only one thread is created per worker.

I have made this monster...
It works for simple and slow cases, but there is a race condition: when a fast thread locks _sync before the synchroniser. As a result sometimes that thread will execute more than once per cycle and break any assumptions of what is ready for use by other threads.

static readonly Stopwatch timer = new Stopwatch();

static readonly object _locker1 = new object();
static readonly object _locker2 = new object();
...
static readonly object _sync = new object();

static void Main()
{
    Task.Run(Synchroniser);
    Task.Run(DoWork1);
    Task.Run(DoWork2);
    ...
}

static void Synchroniser()
{
    while (true)
    {
        lock (_sync)
        {
            timer.Restart();
            while (timer.ElapseMilliseconds < 16) ;
            lock (_locker1) ;
            lock (_locker2) ;
            ...
        }
    }
}

static void DoWork1()
{
    while (true)
    {
        lock (_locker1)
        {
            //all worker threads continue from here at the same time
            ...
        }
        lock (_sync) ;
    }
}
...

Body:
You should have a look at the wait() function and such for the Task class.
It provides a way to continue execution of the current thread when a Task or a given array of tasks finishes execution.

For reference: https://learn.microsoft.com/en-gb/dotnet/api/system.threading.tasks.task.wait?view=netcore-3.1

So for example:

static void Main()
{
    Task t1 = Task.Run(() => DoStuff_1("Task"));
    Task t2 = Task.Run(() => DoStuff_2("Task"));

    Task.WaitAll({t1, t2}); // Blocks the current thread till the given tasks finish execution
}


问:
How can I set the date from one date input to another date input?
I have two date inputs. When I choose start date, I want jquery to automatically generate an end date that's 3 months later.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    Start Date
    <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">

    End date
    <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">

```

答:
```<code><script>
   $('#darbo_pradzia').on('focusout', function(){
    let startDate = new Date($('#darbo_pradzia').val());
    let endDate = new Date(startDate);
    endDate.setMonth(endDate.getMonth()+3);

   let day = ("0" + endDate.getDate()).slice(-2);
   let month = ("0" + (endDate.getMonth() + 1)).slice(-2);
   let date = endDate.getFullYear()+"-"+(month)+"-"+(day) ;

$('#bandomasis_laikotarpis').val(date);
   })
</script>
</code>```

You can read the value on the onchange event or focusout event. Read the date and you can copy the inserted date from the Date constructor. Increase the month, no problem if you overflow the 12 months because automatically the year is increased and the month value scaled between [0-11].  Now to write the date in the input date field there are two problem:

Date control in HTML 5 accepts in the format of Year - month - day

If the month is 5, it needs to be set as 05 not 5 simply. The same thing for day field also.

Add the script downwards in the page, or add a ready/onload event

Body:
<script>
   $('#darbo_pradzia').on('focusout', function(){
    let startDate = new Date($('#darbo_pradzia').val());
    let endDate = new Date(startDate);
    endDate.setMonth(endDate.getMonth()+3);

   let day = ("0" + endDate.getDate()).slice(-2);
   let month = ("0" + (endDate.getMonth() + 1)).slice(-2);
   let date = endDate.getFullYear()+"-"+(month)+"-"+(day) ;

$('#bandomasis_laikotarpis').val(date);
   })
</script>

You can read the value on the onchange event or focusout event. Read the date and you can copy the inserted date from the Date constructor. Increase the month, no problem if you overflow the 12 months because automatically the year is increased and the month value scaled between [0-11].  Now to write the date in the input date field there are two problem:

Date control in HTML 5 accepts in the format of Year - month - day

If the month is 5, it needs to be set as 05 not 5 simply. The same thing for day field also.

Add the script downwards in the page, or add a ready/onload event