问:
How to fix yarn causing trouble while creating react-app
I want to create a react app with create-react-app react-app and I get the following error

```<code>Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

yarn add v1.13.0
info No lockfile found.
[1/4] Resolving packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
warning react-scripts > jest-environment-jsdom-fourteen > jsdom > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/314
2
info There appears to be trouble with your network connection. Retrying...
warning react-scripts > jest > jest-cli > jest-config > jest-environment-jsdom > jsdom > request@2.88.2: request has been deprecated, see https://github.com/req
uest/request/issues/3142
warning react-scripts > resolve-url-loader > rework > css > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
warning react-scripts > resolve-url-loader > rework > css > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
warning react-scripts > jest > jest-cli > jest-config > jest-environment-jsdom > jsdom > left-pad@1.3.0: use String.prototype.padStart()
warning react-scripts > resolve-url-loader > rework > css > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
warning react-scripts > workbox-webpack-plugin > workbox-build > strip-comments > babel-plugin-transform-object-rest-spread > babel-runtime > core-js@2.6.11: co
re-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3
.
[2/4] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@svgr/webpack/-/webpack-4.3.3.tgz: tunneling socket could not be established, cause=connect EC
ONNREFUSED 127.0.0.1:3128".

Aborting installation.
</code>```

I am working behind a company proxy but this is setup, I can install packages via npm for example npm i -g create-react-app, npm i winston, etc. without a problem.
I googled the problem and tried something like:

```<code>yarn install --network-timeout 1000000
</code>```

I configured the npm proxy and the yarn proxy but this doestn work either.
If I try something like this: 'Yarn install' cause 'trouble with network connection'
I cant even use npm install anymore.

答:
This only seems to be the problem with your internet connection.

If you are on windows try deleting the temporary files and restarting your router.

If that doesn't solve your problem then consider restarting your machine. Maybe it may help.

Body:
I want to create a react app with create-react-app react-app and I get the following error

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

yarn add v1.13.0
info No lockfile found.
[1/4] Resolving packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
warning react-scripts > jest-environment-jsdom-fourteen > jsdom > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/314
2
info There appears to be trouble with your network connection. Retrying...
warning react-scripts > jest > jest-cli > jest-config > jest-environment-jsdom > jsdom > request@2.88.2: request has been deprecated, see https://github.com/req
uest/request/issues/3142
warning react-scripts > resolve-url-loader > rework > css > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
warning react-scripts > resolve-url-loader > rework > css > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
warning react-scripts > jest > jest-cli > jest-config > jest-environment-jsdom > jsdom > left-pad@1.3.0: use String.prototype.padStart()
warning react-scripts > resolve-url-loader > rework > css > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
warning react-scripts > workbox-webpack-plugin > workbox-build > strip-comments > babel-plugin-transform-object-rest-spread > babel-runtime > core-js@2.6.11: co
re-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3
.
[2/4] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@svgr/webpack/-/webpack-4.3.3.tgz: tunneling socket could not be established, cause=connect EC
ONNREFUSED 127.0.0.1:3128".

Aborting installation.

I am working behind a company proxy but this is setup, I can install packages via npm for example npm i -g create-react-app, npm i winston, etc. without a problem.
I googled the problem and tried something like:

yarn install --network-timeout 1000000

I configured the npm proxy and the yarn proxy but this doestn work either.
If I try something like this: 'Yarn install' cause 'trouble with network connection'
I cant even use npm install anymore.


来源: stackexchange

问:
Programatic data binding
I am trying to get my head around the power and complexities of data binding. I'm working on a reasonably complex app that requires a view model to aggregate all of the disparate data, and then bind that model to the user controls.

My view model is structured to create numerous classes to manage the individual data elements, and I want to bind these classes together programatically, i.e outside the UI.

I need to bind data elements of two seemingly unrelated classes together. I can then bring the aggregate class data to the UI, using xaml.

In other words, classes "A and "B" each have a string declared as "Name". I want to achieve two way binding of these so that when either "Name" is changed, the binding takes care of the data update.

This task seems easy enough, but I have not been able to find any examples.

答:
Binding non UI view model classes will be complicated as you will have to manually hook property changed notifications and then set your aggregate property. But MultiBinding was specially designed for this scenario.

Instead of creating aggregate class property/class you should try MultiBinding,
http://msdn.microsoft.com/en-us/library/system.windows.data.multibinding.aspx

Another way is to create MultiBinding easily with following LambdaBinding Extensions.

Disclaimer: I will be talking about my company's product here.

We have something called Lambda Binding which allows you to bind complex expressions involving other controls and any other data items.

http://uiatoms.neurospeech.com/2011/03/ui-atoms-1-7-5-released/

ContentLicense: CC BY-SA 3.0

Title: Programatic data binding


问:
What caused SQL Server's Sequence number to skip?
I am using SQL Server's Sequence to generate running number for my document number on my "doc_no" column. A quick check revealed my table's Identity column number to skip is due to server restart and one way to prevent that is to disable the cache (on my local machine). What about sequence? Is it the same way for Sequence? Is there any way to see the current sequence number in the Sequence itself?

```<code>CREATE SEQUENCE [dbo].[PB_SEQ_DOCNO]
 AS [int]
 START WITH 1
 INCREMENT BY 1
 MINVALUE -2147483648
 MAXVALUE 2147483647
 CACHE
GO
</code>```

答:
The CACHE keyword (without an explicit cache size) uses the default server cache size - which is probably 1000 (just like for the IDENTITY columns). So SQL Server in the background caches the next 1000 sequence numbers. If your server crashes or unexpectedly restarts, those cached sequence numbers are "lost" (as in your case here, obviously).

You can use a smaller cache size (by specifying e.g. CACHE 50) or you can even turn this off altogether (NO CACHE) - benefit is not/less gaps, drawbacks is slower performance when dishing out the sequence numbers.

ContentLicense: CC BY-SA 4.0

Body:
I am using SQL Server's Sequence to generate running number for my document number on my "doc_no" column. A quick check revealed my table's Identity column number to skip is due to server restart and one way to prevent that is to disable the cache (on my local machine). What about sequence? Is it the same way for Sequence? Is there any way to see the current sequence number in the Sequence itself?

CREATE SEQUENCE [dbo].[PB_SEQ_DOCNO]
 AS [int]
 START WITH 1
 INCREMENT BY 1
 MINVALUE -2147483648
 MAXVALUE 2147483647
 CACHE
GO


问:
Is it possible to detect that your javascript code is executing because of an event?
If you don't control the invocation of your code, but would like to know if it's being executed by an event handler, is this possible?</p>

答:
Um...

There's really only 3 places to put javascript (that I know of): 1) inside of script tags directly, 2) inside of a function inside of a script tag, and 3) in a link or event directly (like... onClick="", etc.).

In the case of (1) it executes as soon as loaded by the browser and in this case it wouldn't really be invocated by an event.  But, in all other cases, the only way to get the code to execute is because of an event.

So, it seems to me that it is pretty easy to know if your code was executed because of an event...

Now, if you want to know the specific event handler that is executing your code, that is another matter. :D

OwnerDisplayName: daveb

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: BoltBait


问:
How to hide a container on scroll flutter
How can I hide the container HorizontalList()(Number 1 marked on the imgae bellow) on scroll(top to bottom).

Code for Body -:

```<code> body: Column(
    children: <Widget>[
      HorizontalList(),//Categories horizontal Scroll Bar **Hide this on scroll**(Number 1 on Img)
      Padding(
        padding: EdgeInsets.only(top: 2.0),
      ),
      CategoriesBar(),//Fillters and categories Title bar (Number 2 on Img)
      Padding(
        padding: EdgeInsets.only(top: 4.0),
      ),
      ProductView(),//All product view **GrideView** (Number 3 on Img)
    ],
  ),
</code>```

Code for HorizontalList() :-

```<code>import 'package:flutter/material.dart';
class HorizontalList extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
return Container(
  height: 85.0,
  child: ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      Catagory(
        image_location: 'Images/Icons/smartphone.png',
        image_caption: 'Electronics',
        image_catagory: 'electronics',
      ),
      Catagory(
        image_location: 'Images/Icons/car.png',
        image_caption: 'Vehicles',
        image_catagory: 'vehicles',
      ),
      Catagory(
        image_location: 'Images/Icons/property.png',
        image_caption: 'Housing',
        image_catagory: 'realestate',
      ),
      Catagory(
        image_location: 'Images/Icons/shoes.png',
        image_caption: "${'Fashion & Accessories'.substring(0,9)}...", //'',
        image_catagory: 'fashion',
      ),
      Catagory(
        image_location: 'Images/Icons/baby.png',
        image_caption: "${'Baby & Child'.substring(0,8)}...", //'',
        image_catagory: 'baby',
      ),
      Catagory(
        image_location: 'Images/Icons/mega-ball.png',
        image_caption: "${'Leisure & Games'.substring(0,9)}...", //'',
        image_catagory: 'sports',
      ),
      Catagory(
        image_location: 'Images/Icons/sofa.png',
        image_caption: "${'Home & Garden'.substring(0,6)}...",
        image_catagory: 'furnitures',
      ),
      Catagory(
        image_location: 'Images/Icons/agreement.png',
        image_caption: "${'Jobs & Services'.substring(0,8)}...",
        image_catagory: 'jobs',
      ),
      Catagory(
        image_location: 'Images/Icons/boxes.png',
        image_caption: 'Other',
        image_catagory: 'other',
      ),
      Catagory(
        image_location: 'Images/Icons/gift.png',
        image_caption: 'Free Stuff',
        image_catagory: 'free',
      ),
    ],
  ),
);
}
}

class Catagory extends StatelessWidget {
final String image_location;
final String image_caption;
final String image_catagory;
Catagory({this.image_location, this.image_caption, this.image_catagory});
@override
 Widget build(BuildContext context) {
return Padding(
  padding: const EdgeInsets.all(0.0),
  child: GestureDetector(
    onTap: () {
      print("$image_catagory"); //Print tapped image_caption
    },
    child: Container(
      width: 105.0,
      color: Color(0xFF051622),
      child: ListTile(
        title: CircleAvatar(
          //Circle with gold border
          radius: 30.0,
          backgroundColor: Color(0xFFDEB992),
          child: CircleAvatar(
            //Circle which containes the icon
            radius: 27.0,
            backgroundColor: Colors.white,
            child: Image.asset(image_location),
          ),
        ),
        subtitle: Container(
          alignment: Alignment.topCenter,
          height: 18.0,
          child: Text(
            image_caption,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        ),
      ),
    ),
  ),
);
}
}
</code>```

Code for ProductView()

```<code>class ProductView extends StatefulWidget {
 @override
 _ProductViewState createState() => _ProductViewState();
 }

class _ProductViewState extends State<ProductView> {
 @override
 Widget build(BuildContext context) {

return new Flexible(
  child: new GridView.builder(
    gridDelegate:
        new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
    itemCount: storeItems.length,
    itemBuilder: (BuildContext context, int index) {
      return new Card(
        elevation: 12.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: new Stack(
          alignment: FractionalOffset.bottomCenter,
          children: <Widget>[
            new Column(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10.0),
                      topRight: Radius.circular(10.0)),
                  child: new Image.network(
                    storeItems[index].itemImage,
                    fit: BoxFit.cover,
                    width: 200.0,
                    height: 145.0,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(5.0),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: new Text(
                      storeItems[index].itemName,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.w700,
                      ),
                      textAlign: TextAlign.start,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 5.0),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: new Text(
                      "Rs${storeItems[index].itemPrice}",
                      style: TextStyle(
                          fontWeight: FontWeight.w500,
                          fontSize: 15.0,
                          color: Colors.deepOrangeAccent),
                      textAlign: TextAlign.left,
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
      );
    },
  ),
);
}
}
</code>```

is the Container() which should be hidden when scrolling

is the second container "All Categories" which should do nothing when scrolling

is the listView itself, this is where scrolling happens.

答:
You could achieve this using a ScrollController:

For this I believe you will have to change your need to create your controller in the parent widget of this screen then pass it down to your ProductView(3) so that it uses it. Then you add a listener to the controller so that if the scroll height is 0 or at the end
then you make the HorizontalList visible or not.

```<code>//...parent widget up here

class _ParentWidgetState extends State<ParentWidget> {
  final ScrollController scrollcontroller = new ScrollController();

  bool scroll_visibility = true;

  @Override
  void initState() {
    scrollcontroller.addListener(() {
      if(scrollcontroller.position.pixels > 0 || scrollcontroller.position.pixels < scrollcontroller.position.maxScrollExtent)
        scroll_visibility = false;
      else
        scroll_visibility = true;

      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Visibility(
            visible: scroll_visibility,
            child: HorizontalList()
          ),
          Padding(
            padding: EdgeInsets.only(top: 2.0),
          ),
          CategoriesBar(),
          Padding(
            padding: EdgeInsets.only(top: 4.0),
          ),
          /*
            You will need to pass the controller down to the scroll view in your product
            view widget, so it can work...
          */
          ProductView(controller: scrollcontroller),
        ],
      )
    );
  }
}
</code>```

Update

Okay awesome, so lets now see how we can pass the controller we have defined in the parent widget above. Since we say we have the ProductView as ProductView(controller: scrollcontroller) we need to declare it in the ProductView Widget:

```<code>class ProductView extends StatefulWidget {
  final ScrollController controller;

  /*
  *  this is where we add the controller so we contstruct with the controller
  *  from the parent.
  */
  ProductView({@required this.controller});

  @override
  _ProductViewState createState() => _ProductViewState();
}
/*
*  With that we now have a predefined controller from parent that we can use
*  in the ProductView widget.
*/
class _ProductViewState extends State<ProductView> {
  @override
  Widget build(BuildContext context) {
    return new Flexible(
      child: new GridView.builder(
        //then we add the controller here
        controller: widget.controller,
        gridDelegate:
          new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: storeItems.length,
        itemBuilder: (BuildContext context, int index) {
        //...your code here as described above
        }
      )
    )
  }
}
</code>```

Since we had already described the event listener in the parent we need only add it to your scrolling widget and you should be cool...

Body:
How can I hide the container HorizontalList()(Number 1 marked on the imgae bellow) on scroll(top to bottom).

Code for Body -:

 body: Column(
    children: <Widget>[
      HorizontalList(),//Categories horizontal Scroll Bar **Hide this on scroll**(Number 1 on Img)
      Padding(
        padding: EdgeInsets.only(top: 2.0),
      ),
      CategoriesBar(),//Fillters and categories Title bar (Number 2 on Img)
      Padding(
        padding: EdgeInsets.only(top: 4.0),
      ),
      ProductView(),//All product view **GrideView** (Number 3 on Img)
    ],
  ),

Code for HorizontalList() :-

import 'package:flutter/material.dart';
class HorizontalList extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
return Container(
  height: 85.0,
  child: ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      Catagory(
        image_location: 'Images/Icons/smartphone.png',
        image_caption: 'Electronics',
        image_catagory: 'electronics',
      ),
      Catagory(
        image_location: 'Images/Icons/car.png',
        image_caption: 'Vehicles',
        image_catagory: 'vehicles',
      ),
      Catagory(
        image_location: 'Images/Icons/property.png',
        image_caption: 'Housing',
        image_catagory: 'realestate',
      ),
      Catagory(
        image_location: 'Images/Icons/shoes.png',
        image_caption: "${'Fashion & Accessories'.substring(0,9)}...", //'',
        image_catagory: 'fashion',
      ),
      Catagory(
        image_location: 'Images/Icons/baby.png',
        image_caption: "${'Baby & Child'.substring(0,8)}...", //'',
        image_catagory: 'baby',
      ),
      Catagory(
        image_location: 'Images/Icons/mega-ball.png',
        image_caption: "${'Leisure & Games'.substring(0,9)}...", //'',
        image_catagory: 'sports',
      ),
      Catagory(
        image_location: 'Images/Icons/sofa.png',
        image_caption: "${'Home & Garden'.substring(0,6)}...",
        image_catagory: 'furnitures',
      ),
      Catagory(
        image_location: 'Images/Icons/agreement.png',
        image_caption: "${'Jobs & Services'.substring(0,8)}...",
        image_catagory: 'jobs',
      ),
      Catagory(
        image_location: 'Images/Icons/boxes.png',
        image_caption: 'Other',
        image_catagory: 'other',
      ),
      Catagory(
        image_location: 'Images/Icons/gift.png',
        image_caption: 'Free Stuff',
        image_catagory: 'free',
      ),
    ],
  ),
);
}
}

class Catagory extends StatelessWidget {
final String image_location;
final String image_caption;
final String image_catagory;
Catagory({this.image_location, this.image_caption, this.image_catagory});
@override
 Widget build(BuildContext context) {
return Padding(
  padding: const EdgeInsets.all(0.0),
  child: GestureDetector(
    onTap: () {
      print("$image_catagory"); //Print tapped image_caption
    },
    child: Container(
      width: 105.0,
      color: Color(0xFF051622),
      child: ListTile(
        title: CircleAvatar(
          //Circle with gold border
          radius: 30.0,
          backgroundColor: Color(0xFFDEB992),
          child: CircleAvatar(
            //Circle which containes the icon
            radius: 27.0,
            backgroundColor: Colors.white,
            child: Image.asset(image_location),
          ),
        ),
        subtitle: Container(
          alignment: Alignment.topCenter,
          height: 18.0,
          child: Text(
            image_caption,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        ),
      ),
    ),
  ),
);
}
}

Code for ProductView()

class ProductView extends StatefulWidget {
 @override
 _ProductViewState createState() => _ProductViewState();
 }

class _ProductViewState extends State<ProductView> {
 @override
 Widget build(BuildContext context) {

return new Flexible(
  child: new GridView.builder(
    gridDelegate:
        new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
    itemCount: storeItems.length,
    itemBuilder: (BuildContext context, int index) {
      return new Card(
        elevation: 12.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: new Stack(
          alignment: FractionalOffset.bottomCenter,
          children: <Widget>[
            new Column(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10.0),
                      topRight: Radius.circular(10.0)),
                  child: new Image.network(
                    storeItems[index].itemImage,
                    fit: BoxFit.cover,
                    width: 200.0,
                    height: 145.0,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(5.0),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: new Text(
                      storeItems[index].itemName,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.w700,
                      ),
                      textAlign: TextAlign.start,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 5.0),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: new Text(
                      "Rs${storeItems[index].itemPrice}",
                      style: TextStyle(
                          fontWeight: FontWeight.w500,
                          fontSize: 15.0,
                          color: Colors.deepOrangeAccent),
                      textAlign: TextAlign.left,
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
      );
    },
  ),
);
}
}

is the Container() which should be hidden when scrolling

is the second container "All Categories" which should do nothing when scrolling

is the listView itself, this is where scrolling happens.

Body:
You could achieve this using a ScrollController:

For this I believe you will have to change your need to create your controller in the parent widget of this screen then pass it down to your ProductView(3) so that it uses it. Then you add a listener to the controller so that if the scroll height is 0 or at the end
then you make the HorizontalList visible or not.

//...parent widget up here

class _ParentWidgetState extends State<ParentWidget> {
  final ScrollController scrollcontroller = new ScrollController();

  bool scroll_visibility = true;

  @Override
  void initState() {
    scrollcontroller.addListener(() {
      if(scrollcontroller.position.pixels > 0 || scrollcontroller.position.pixels < scrollcontroller.position.maxScrollExtent)
        scroll_visibility = false;
      else
        scroll_visibility = true;

      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Visibility(
            visible: scroll_visibility,
            child: HorizontalList()
          ),
          Padding(
            padding: EdgeInsets.only(top: 2.0),
          ),
          CategoriesBar(),
          Padding(
            padding: EdgeInsets.only(top: 4.0),
          ),
          /*
            You will need to pass the controller down to the scroll view in your product
            view widget, so it can work...
          */
          ProductView(controller: scrollcontroller),
        ],
      )
    );
  }
}

Update

Okay awesome, so lets now see how we can pass the controller we have defined in the parent widget above. Since we say we have the ProductView as ProductView(controller: scrollcontroller) we need to declare it in the ProductView Widget:

class ProductView extends StatefulWidget {
  final ScrollController controller;

  /*
  *  this is where we add the controller so we contstruct with the controller
  *  from the parent.
  */
  ProductView({@required this.controller});

  @override
  _ProductViewState createState() => _ProductViewState();
}
/*
*  With that we now have a predefined controller from parent that we can use
*  in the ProductView widget.
*/
class _ProductViewState extends State<ProductView> {
  @override
  Widget build(BuildContext context) {
    return new Flexible(
      child: new GridView.builder(
        //then we add the controller here
        controller: widget.controller,
        gridDelegate:
          new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: storeItems.length,
        itemBuilder: (BuildContext context, int index) {
        //...your code here as described above
        }
      )
    )
  }
}

Since we had already described the event listener in the parent we need only add it to your scrolling widget and you should be cool...


问:
Why does this DFS-based topological sort algorithm work?
Here is the algorithm that I pulled from this competitive programming resource.

```<code>int n; // number of vertices
vector<vector<int>> adj; // adjacency list of graph
vector<bool> visited;
vector<int> ans;

void dfs(int v) {
    visited[v] = true;
    for (int u : adj[v]) {
        if (!visited[u])
            dfs(u);
    }
    ans.push_back(v);
}

void topological_sort() {
    visited.assign(n, false);
    ans.clear();
    for (int i = 0; i < n; ++i) {
        if (!visited[i])
            dfs(i);
    }
    reverse(ans.begin(), ans.end());
}
</code>```

How does this algorithm avoid adding vertices to the topologically sorted collection that have incoming directed edges? Say, for example, that the first vertex (0 in this example) checked by the for loop has an incoming directed edge from vertex (1). What is stopping this algorithm from outputting (0) before first ensuring that (1) has been output?

答: As far as I can tell, the DFS approach requires the graph to not have any cycles. If the graph does have cycles, the DFS will not detect it and will give a wrong result. If the graph does not have cycles, the DFS will work. Certain other algorithms than DFS for finding the topological sort can detect cycles and rightly give an error if any cycle exists, since a topological sort is not possible for a graph with cycles. So, it is a very good question you ask.

Body:
Here is the algorithm that I pulled from this competitive programming resource.

int n; // number of vertices
vector<vector<int>> adj; // adjacency list of graph
vector<bool> visited;
vector<int> ans;

void dfs(int v) {
    visited[v] = true;
    for (int u : adj[v]) {
        if (!visited[u])
            dfs(u);
    }
    ans.push_back(v);
}

void topological_sort() {
    visited.assign(n, false);
    ans.clear();
    for (int i = 0; i < n; ++i) {
        if (!visited[i])
            dfs(i);
    }
    reverse(ans.begin(), ans.end());
}

How does this algorithm avoid adding vertices to the topologically sorted collection that have incoming directed edges? Say, for example, that the first vertex (0 in this example) checked by the for loop has an incoming directed edge from vertex (1). What is stopping this algorithm from outputting (0) before first ensuring that (1) has been output?


问:
Unable log in to the django admin page with a valid username and password
I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages

This question is in the django FAQ, but I've gone over the answers there and still can't get past the initial login screen.

I'm using django 1.4 on ubuntu 12.04 with apache2 and modwsgi.

I've confirmed that I'm registering the admin in the admin.py file, made sure to syncdb after adding INSTALLED_APPS.
When I enter the wrong password I DO get an error, so my admin user is being authenticated, just not proceeding to the admin page.

I've tried both setting SESSION_COOKIE_DOMAIN to the machine's IP and None.  (Confirmed that the cookie domain shows as the machine's IP in chrome)

Also, checked that the user authenticates via the shell:

```<code>>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff
True
>>> u.is_superuser
True
>>> u.is_active
True
</code>```

Attempted login using IE8 and chrome canary, both results in the same return to the login screen.

Is there something else I'm missing????

settings.py

```<code>...
MIDDLEWARE_CLASSES = (
    'django.middleware.gzip.GZipMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.transaction.TransactionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'myapp.main',
)

SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
</code>```

urls.py

```<code>from django.conf.urls.defaults import * #@UnusedWildImport
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    (r'^bin/', include('myproject.main.urls')),
    (r'^layer/r(?P<layer_id>\d+)/$', "myproject.layer.views.get_result_layer"),
    (r'^layer/b(?P<layer_id>\d+)/$', "myproject.layer.views.get_baseline_layer"),
    (r'^layer/c(?P<layer_id>\d+)/$', "myproject.layer.views.get_candidate_layer"),
    (r'^layers/$', "myproject.layer.views.get_layer_definitions"),
    (r'^js/mapui.js$', "myproject.layer.views.view_mapjs"),
    (r'^tilestache/config/$', "myproject.layer.views.get_tilestache_cfg"),
    (r'^admin/', include(admin.site.urls)),
    (r'^sites/', include("myproject.sites.urls")),
    (r'^$', "myproject.layer.views.view_map"),
)

urlpatterns += staticfiles_urlpatterns()
</code>```

Apache Version:

```<code>Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured
</code>```

Apache apache2/sites-available/default:

```<code><VirtualHost *:80>
        ServerAdmin ironman@localhost
        DocumentRoot /var/www/bin
        LogLevel warn
        WSGIDaemonProcess lbs processes=2 maximum-requests=500 threads=1
        WSGIProcessGroup lbs
        WSGIScriptAlias / /var/www/bin/apache/django.wsgi
        Alias /static /var/www/lbs/static/
</VirtualHost>
<VirtualHost *:8080>
        ServerAdmin ironman@localhost
        DocumentRoot /var/www/bin
        LogLevel warn
        WSGIDaemonProcess tilestache processes=2 maximum-requests=500 threads=1
        WSGIProcessGroup tilestache
        WSGIScriptAlias / /var/www/bin/tileserver/tilestache.wsgi
</VirtualHost>
</code>```

UPDATE

The admin page does proceed when using the development server via runserver so it seems like a wsgi/apache issue.  Still haven't figured it out yet.

SOLUTION

The problem was that I had the settings file SESSION_ENGINE value set to 'django.contrib.sessions.backends.cache' without having the CACHE_BACKEND properly configured.

I've changed the SESSION_ENGINE to 'django.contrib.sessions.backends.db' which resolved the issue.

答:
My issue was that My Admin Page was not loading and not working. Here is what I did:

```<code>pip uninstall django
pip install django==2.2
</code>```

For more Detail Check Django Documentation.

Body:
I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages

This question is in the django FAQ, but I've gone over the answers there and still can't get past the initial login screen.

I'm using django 1.4 on ubuntu 12.04 with apache2 and modwsgi.

I've confirmed that I'm registering the admin in the admin.py file, made sure to syncdb after adding INSTALLED_APPS.
When I enter the wrong password I DO get an error, so my admin user is being authenticated, just not proceeding to the admin page.

I've tried both setting SESSION_COOKIE_DOMAIN to the machine's IP and None.  (Confirmed that the cookie domain shows as the machine's IP in chrome)

Also, checked that the user authenticates via the shell:

>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff
True
>>> u.is_superuser
True
>>> u.is_active
True

Attempted login using IE8 and chrome canary, both results in the same return to the login screen.

Is there something else I'm missing????

settings.py

...
MIDDLEWARE_CLASSES = (
    'django.middleware.gzip.GZipMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.transaction.TransactionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'myapp.main',
)

SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False

urls.py

from django.conf.urls.defaults import * #@UnusedWildImport
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    (r'^bin/', include('myproject.main.urls')),
    (r'^layer/r(?P<layer_id>\d+)/$', "myproject.layer.views.get_result_layer"),
    (r'^layer/b(?P<layer_id>\d+)/$', "myproject.layer.views.get_baseline_layer"),
    (r'^layer/c(?P<layer_id>\d+)/$', "myproject.layer.views.get_candidate_layer"),
    (r'^layers/$', "myproject.layer.views.get_layer_definitions"),
    (r'^js/mapui.js$', "myproject.layer.views.view_mapjs"),
    (r'^tilestache/config/$', "myproject.layer.views.get_tilestache_cfg"),
    (r'^admin/', include(admin.site.urls)),
    (r'^sites/', include("myproject.sites.urls")),
    (r'^$', "myproject.layer.views.view_map"),
)

urlpatterns += staticfiles_urlpatterns()

Apache Version:

Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured

Apache apache2/sites-available/default:

<VirtualHost *:80>
        ServerAdmin ironman@localhost
        DocumentRoot /var/www/bin
        LogLevel warn
        WSGIDaemonProcess lbs processes=2 maximum-requests=500 threads=1
        WSGIProcessGroup lbs
        WSGIScriptAlias / /var/www/bin/apache/django.wsgi
        Alias /static /var/www/lbs/static/
</VirtualHost>
<VirtualHost *:8080>
        ServerAdmin ironman@localhost
        DocumentRoot /var/www/bin
        LogLevel warn
        WSGIDaemonProcess tilestache processes=2 maximum-requests=500 threads=1
        WSGIProcessGroup tilestache
        WSGIScriptAlias / /var/www/bin/tileserver/tilestache.wsgi
</VirtualHost>

UPDATE

The admin page does proceed when using the development server via runserver so it seems like a wsgi/apache issue.  Still haven't figured it out yet.

SOLUTION

The problem was that I had the settings file SESSION_ENGINE value set to 'django.contrib.sessions.backends.cache' without having the CACHE_BACKEND properly configured.

I've changed the SESSION_ENGINE to 'django.contrib.sessions.backends.db' which resolved the issue.

Body:
My issue was that My Admin Page was not loading and not working. Here is what I did:

pip uninstall django
pip install django==2.2

For more Detail Check Django Documentation.


问:
php echo an element of an array
I have a variable $var. On var_dump($var); it shows:

```<code>array(1) { [0]=> object(stdClass)#23 (2) { ["stop_id"]=> string(1) "1" ["flag"]=> string(1) "1" } }
</code>```

I want the element 'flag' to access from $var. How to do it?

I tried:

```<code>echo $var[0]["flag"];
</code>```

It shows:

Message: Cannot use object of type stdClass as array

Please help

答:
The reason for this error is the fact, that the first item in the $var array is an object, not an array. So flag is not an index, it's a property and you need to access it as a class member and depending on the visibility  of the property:

```<code><?php
class Test {
    protected $stop_id = "1";
    public $flag = "1";
}

$var = array(
   new Test
);

var_dump($var[0]->flag);
var_dump($var[0]->stop_id);
?>
</code>```

Result:

```<code>string(1) "1"
Exception: Cannot access protected property Test::$stop_id
</code>```

Title: php echo an element of an array

Body:
I have a variable $var. On var_dump($var); it shows:

array(1) { [0]=> object(stdClass)#23 (2) { ["stop_id"]=> string(1) "1" ["flag"]=> string(1) "1" } }

I want the element 'flag' to access from $var. How to do it?

I tried:

echo $var[0]["flag"];

It shows:

Message: Cannot use object of type stdClass as array

Please help

Body:
The reason for this error is the fact, that the first item in the $var array is an object, not an array. So flag is not an index, it's a property and you need to access it as a class member and depending on the visibility  of the property:

<?php
class Test {
    protected $stop_id = "1";
    public $flag = "1";
}

$var = array(
   new Test
);

var_dump($var[0]->flag);
var_dump($var[0]->stop_id);
?>

Result:

string(1) "1"
Exception: Cannot access protected property Test::$stop_id


问:
c++ std::future is not getting called
I am working with std::async and std::future in c++, but am having a bit of trouble.
When I run this code, i expect to see (in the stdout) "hello world" but, instead I get nothing:

```<code>#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string>* test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ &a };
}

int main() {
  A a = callA();
  cout << a.test->get() << endl;
}

</code>```

I am using a pointer to a future because in my real program, i have another struct in place of the std::string:

```<code>struct A;
struct B;

typedef struct A {
  future<B>* b;
} A;

typedef struct B {
  A a;
} B;
</code>```

and even if i don't use a pointer it will give me this error:

```<code>error: use of deleted function 'std::future<_Res>::future(const std::future<_Res>&) [with _Res = std::__cxx11::basic_string<char>]'
</code>```

(For the above error, i know that i can use std::move to fix it as seen here, but i need to use the pointer)

So how can i actually get the output of "hello world" from this program?

答:
The future is destroyed as soon as callA() returns, so you have a pointer to an object that no longer exists.  a.test->get() is therefore undefined behavior, and anything might happen -- including indefinitely blocking, or crashing, or actually printing the right result.

If you wish to return it from the function as a pointer, then use std::unique_ptr:

```<code>#include <iostream>
#include <future>
using namespace std;

struct A {
  unique_ptr<future<string>> test;
};

string getStr() {
  return "hello world";
}

A callA() {
  future<string> a = async(&getStr);

  return A{ make_unique<future<string>>(std::move(a)) };
}

int main() {
  A a = callA();
  cout << a.test->get() << endl;
}
</code>```

(Demo)

Side note: using namespace std; is a bad practice. Don't do it.

Title: c++ std::future is not getting called

Body:
I am working with std::async and std::future in c++, but am having a bit of trouble.
When I run this code, i expect to see (in the stdout) "hello world" but, instead I get nothing:

#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string>* test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ &a };
}

int main() {
  A a = callA();
  cout <get() << endl;
}

I am using a pointer to a future because in my real program, i have another struct in place of the std::string:

struct A;
struct B;

typedef struct A {
  future* b;
} A;

typedef struct B {
  A a;
} B;

and even if i don't use a pointer it will give me this error:

error: use of deleted function 'std::future<_Res>::future(const std::future<_Res>&) [with _Res = std::__cxx11::basic_string<char>]'

(For the above error, i know that i can use std::move to fix it as seen here, but i need to use the pointer)

So how can i actually get the output of "hello world" from this program?

Body:
The future is destroyed as soon as callA() returns, so you have a pointer to an object that no longer exists.  a.test->get() is therefore undefined behavior, and anything might happen -- including indefinitely blocking, or crashing, or actually printing the right result.

If you wish to return it from the function as a pointer, then use std::unique_ptr:

#include <iostream>
#include <future>
using namespace std;

struct A {
  unique_ptr<future<string>> test;
};

string getStr() {
  return "hello world";
}

A callA() {
  future<string> a = async(&getStr);

  return A{ make_unique<future<string>>(std::move(a)) };
}

int main() {
  A a = callA();
  cout << a.test->get() << endl;
}

(Demo)

Side note: using namespace std; is a bad practice. Don't do it.


问:
Deleting sub-element from JSON file
I thought it was simple to delete a key from JSON nested dict, but I end up with errors .
I have JSON file as shown below, and want to delete a key "8888" from its element "Codes".

dummy.json:

```<code>{
    "Codes": {
        "8888": "code1|18888",
        "9999": "code2|19999",
        "7777": "code3|17777"
    },
    "Names": {
        "Site1": "Site1|18888",
        "Site2": "Site2|19999",
        "Site3": "Site3|17777"
    }
}
</code>```

Python code:

```<code>import json

with open('dummy.json') as json_data:
    data = json.load(json_data)
    for element in data["Codes"]:
        #del element['8888']
        element.pop('8888', None)

with open('dummy.json'), 'w') as outfile:
    json.dump(data, outfile)
</code>```

Result:

For the first attempt, I tried del element['8888'] and it throws TypeError: 'str' object does not support item deletion

As per example found here I have tried with element.pop('8888', None) and it throws AttributeError: 'str' object has no attribute 'pop' error.

I am not sure what mistake I did, please help.

答:
In for element in data["Codes"] loop, element will be key of data["Codes"] dictionary. So if print all element of data["Codes"], result is like this.

```<code>for element in data["Codes"]:
    print(element)
>>> 8888
>>> 9999
>>> 7777
</code>```

You don't need for loop. If you want to delete(or pop) some key of data["Codes"], just do like this.

```<code>data["Codes"].pop("8888", None)
</code>```

Title: Deleting sub-element from JSON file

Body:
I thought it was simple to delete a key from JSON nested dict, but I end up with errors .
I have JSON file as shown below, and want to delete a key "8888" from its element "Codes".

dummy.json:

{
    "Codes": {
        "8888": "code1|18888",
        "9999": "code2|19999",
        "7777": "code3|17777"
    },
    "Names": {
        "Site1": "Site1|18888",
        "Site2": "Site2|19999",
        "Site3": "Site3|17777"
    }
}

Python code:

import json

with open('dummy.json') as json_data:
    data = json.load(json_data)
    for element in data["Codes"]:
        #del element['8888']
        element.pop('8888', None)

with open('dummy.json'), 'w') as outfile:
    json.dump(data, outfile)

Result:

For the first attempt, I tried del element['8888'] and it throws TypeError: 'str' object does not support item deletion

As per example found here I have tried with element.pop('8888', None) and it throws AttributeError: 'str' object has no attribute 'pop' error.

I am not sure what mistake I did, please help.

Body:
In for element in data["Codes"] loop, element will be key of data["Codes"] dictionary. So if print all element of data["Codes"], result is like this.

for element in data["Codes"]:
    print(element)
>>> 8888
>>> 9999
>>> 7777

You don't need for loop. If you want to delete(or pop) some key of data["Codes"], just do like this.

data["Codes"].pop("8888", None)


问:
Does not conform to protocol BindableObject - Xcode 11 Beta 4
Playing around with examples out there.  Found a project that had a class that was a bindableobject and it didn't give any errors.  Now that Xcode 11 beta 4 is out, I'm getting the error:

Type 'UserSettings' does not conform to protocol 'BindableObject'

It has a fix button on the error which when you click on that, it adds

```<code>typealias PublisherType = <#type#>
</code>```

It expects you to fill in the type.

What would the type be?

```<code>class UserSettings: BindableObject {

    let didChange = PassthroughSubject<Void, Never>()

    var score: Int = 0 {
        didSet {
            didChange.send()
        }
    }
}
</code>```

答:
SwiftUI and Combine are two new frameworks that were announced at WWDC 2019. These two frameworks received a lot of attention at WWDC 2019, as evidenced by the number of sessions in which these technologies were featured.

SwiftUI was introduced as

a revolutionary, new way to build better apps, faster.

Combine is described as

a unified declarative framework for processing values over time

Between the initial release and now (May, 2020, Swift 5.2), there have been some changes. Anyone new to SwiftUI and Combine, who may have watched the WWDC videos, may be left with a few questions as to how the two frameworks work together.

Combine defines two interfaces: Publisher and Subscriber. A publisher sends events to subscribers. See sequence diagram below.

If you start an application in SwiftUI, and then add combine, there will be no mention of a Publisher or a Subscriber, the two main players required to use Combine. Consider this very simple sample application below.

import SwiftUI
import Combine
import SwiftUI

final class ActorViewModel: ObservableObject {
    var name : String
    private var imageUrl : URL?
    //@Published
    private (set) var image : Image = Image(systemName: "photo") {
        willSet {
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }
    }

    init(name: String, imageUrl: URL?) {
        self.name = name
        self.imageUrl = imageUrl
        self.fetchImage()
    }

    private func fetchImage() {
        guard nil != self.imageUrl,
            String() != self.imageUrl!.absoluteString else { return }
        let task = URLSession.shared.dataTask(with: self.imageUrl!) { (data, response, error) in

            guard nil == error , nil != response, nil != data,
                let uiImage = UIImage(data: data!) else { return }
                self.image = Image(uiImage: uiImage)

        }
        task.resume()
    }
}

struct ContentView: View {
    @ObservedObject var actor : ActorViewModel

    var body: some View {
        HStack {
            actor.image
                .resizable()
                .aspectRatio(contentMode: ContentMode.fit)
                .frame(width: 60, height: 60)
            Text(actor.name)
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let actor = ActorViewModel(name: "Mark Hammill",
                                   imageUrl: URL(string: "https://m.media-amazon.com/images/M/MV5BOGY2MjI5MDQtOThmMC00ZGIwLWFmYjgtYWU4MzcxOGEwMGVkXkEyXkFqcGdeQXVyMzM4MjM0Nzg@._V1_.jpg"))
        return ContentView(actor: actor)
    }
}
```

The app preview via the canvas will look like this:

The app uses a list view to display names and images of actors. There are just two classes to consider:

ContentView -- the SwiftUI View subclass

ActorViewModel -- the source of the data for the ContentView (called a ViewModel as it performs the role of VM in MVVM)

The view has a reference to the actor object, as per the class diagram below.

Although this example is using Combine, it is not immediately apparent. There is no mention of a Publisher or a Subscriber. What is going on?

Answer: Looking at the class hierarchy fills in the missing gaps. The below class diagram explains the full picture (click on the image to see it in greater detail).

Consulting Apple's documentation provides definitions for these types:

ObservedObject: A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.

ObservableObject: A type of object with a publisher that emits before the object has changed. By default an ObservableObject synthesizes an  objectWillChange publisher that emits the changed value before any of its @Published properties changes.

objectWillChange: A publisher that emits before the object has changed.

PassthroughSubject: A subject that broadcasts elements to downstream subscribers. As a concrete implementation of Subject, the PassthroughSubject provides a convenient way to adapt existing imperative code to the Combine model.

First, consider what the @ObservedObject means. This is a property wrapper. A property wrapper reduces code duplication, and allows for a succinct syntax when declaring properties that hides how the property is stored and defined. In this case, the "Observed Object" is a property which observes another object.

In other words, the property is a Subscriber (from the Combine Framework). The actor is (through the use of a property wrapper) is a Subscriber, which subscribes to a Publisher, but what is the Publisher in this scenario?

The "Observable Object" is not itself the publisher, but rather has a publisher. The ActorViewModel conforms to the ObservableObject protocol. By doing so, it is provided with a publisher property called objectWillChange by an extension (which the framework provides on the ObservableObject protocol). This objectWillChange property is of type PassthroughSubject, which is a concrete type of the Publisher protocol. The passthrough subject has a property called send, which is a publisher method used to send data to any subscribers. So the property called "objectWillChange" is the Publisher.

To recap, the Subscriber is the property called actor from the ContentView class, and the Publisher is the property objectWillChange from the ActorViewModel class. What about the need for the Subscriber to Subscribe to the Publisher? The "@ObservedObject" property wrapper is itself a Subscriber, so it must subscribe to the Publisher. But how does the View find out about changes sent to the Subscriber? That is handled by the SwiftUI framework, which we never see.

Take-away: we don't need to worry about subscribing the view to the Publisher. On the other hand, we do need to worry about making sure the publisher tell the subscriber when something is about to change. When the image has been fetched from a remote server, and the data has been transformed into an image object, we call objectWillChange.send() to inform the View. Once the subscriber receives notification from the publisher that something is about to / has changed, it invalidates the view (which results in the view redrawing itself).

Summary
The way in which SwiftUI uses a ObservedObject PropertyWrapper does not on the surface give away the fact that Combine even exists in the equation. But by inspecting ObservedObject and ObservableObject, the underlying Combine framework is revealed, along with the design pattern:

subscriber --> subscribing to a publisher --> which then publishes changes --> that are received by the subscriber

References:

Blog Article

WWDC 2019 Session 204

WWDC 2019 Session 226

Body:
Playing around with examples out there.  Found a project that had a class that was a bindableobject and it didn't give any errors.  Now that Xcode 11 beta 4 is out, I'm getting the error:

Type 'UserSettings' does not conform to protocol 'BindableObject'

It has a fix button on the error which when you click on that, it adds

typealias PublisherType = <#type#>

It expects you to fill in the type.

What would the type be?

class UserSettings: BindableObject {

    let didChange = PassthroughSubject<Void, Never>()

    var score: Int = 0 {
        didSet {
            didChange.send()
        }
    }
}

Body:
SwiftUI and Combine are two new frameworks that were announced at WWDC 2019. These two frameworks received a lot of attention at WWDC 2019, as evidenced by the number of sessions in which these technologies were featured.

SwiftUI was introduced as

a revolutionary, new way to build better apps, faster.

Combine is described as

a unified declarative framework for processing values over time

Between the initial release and now (May, 2020, Swift 5.2), there have been some changes. Anyone new to SwiftUI and Combine, who may have watched the WWDC videos, may be left with a few questions as to how the two frameworks work together.

Combine defines two interfaces: Publisher and Subscriber. A publisher sends events to subscribers. See sequence diagram below.

If you start an application in SwiftUI, and then add combine, there will be no mention of a Publisher or a Subscriber, the two main players required to use Combine. Consider this very simple sample application below.

import SwiftUI
import Combine
import SwiftUI

final class ActorViewModel: ObservableObject {
    var name : String
    private var imageUrl : URL?
    //@Published
    private (set) var image : Image = Image(systemName: "photo") {
        willSet {
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }
    }

    init(name: String, imageUrl: URL?) {
        self.name = name
        self.imageUrl = imageUrl
        self.fetchImage()
    }

    private func fetchImage() {
        guard nil != self.imageUrl,
            String() != self.imageUrl!.absoluteString else { return }
        let task = URLSession.shared.dataTask(with: self.imageUrl!) { (data, response, error) in

            guard nil == error , nil != response, nil != data,
                let uiImage = UIImage(data: data!) else { return }
                self.image = Image(uiImage: uiImage)

        }
        task.resume()
    }
}

struct ContentView: View {
    @ObservedObject var actor : ActorViewModel

    var body: some View {
        HStack {
            actor.image
                .resizable()
                .aspectRatio(contentMode: ContentMode.fit)
                .frame(width: 60, height: 60)
            Text(actor.name)
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let actor = ActorViewModel(name: "Mark Hammill",
                                   imageUrl: URL(string: "https://m.media-amazon.com/images/M/MV5BOGY2MjI5MDQtOThmMC00ZGIwLWFmYjgtYWU4MzcxOGEwMGVkXkEyXkFqcGdeQXVyMzM4MjM0Nzg@._V1_.jpg"))
        return ContentView(actor: actor)
    }
}

The app preview via the canvas will look like this:

The app uses a list view to display names and images of actors. There are just two classes to consider:

ContentView -- the SwiftUI View subclass

ActorViewModel -- the source of the data for the ContentView (called a ViewModel as it performs the role of VM in MVVM)

The view has a reference to the actor object, as per the class diagram below.

Although this example is using Combine, it is not immediately apparent. There is no mention of a Publisher or a Subscriber. What is going on?

Answer: Looking at the class hierarchy fills in the missing gaps. The below class diagram explains the full picture (click on the image to see it in greater detail).

Consulting Apple's documentation provides definitions for these types:

ObservedObject: A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.

ObservableObject: A type of object with a publisher that emits before the object has changed. By default an ObservableObject synthesizes an  objectWillChange publisher that emits the changed value before any of its @Published properties changes.

objectWillChange: A publisher that emits before the object has changed.

PassthroughSubject: A subject that broadcasts elements to downstream subscribers. As a concrete implementation of Subject, the PassthroughSubject provides a convenient way to adapt existing imperative code to the Combine model.

First, consider what the @ObservedObject means. This is a property wrapper. A property wrapper reduces code duplication, and allows for a succinct syntax when declaring properties that hides how the property is stored and defined. In this case, the "Observed Object" is a property which observes another object.

In other words, the property is a Subscriber (from the Combine Framework). The actor is (through the use of a property wrapper) is a Subscriber, which subscribes to a Publisher, but what is the Publisher in this scenario?

The "Observable Object" is not itself the publisher, but rather has a publisher. The ActorViewModel conforms to the ObservableObject protocol. By doing so, it is provided with a publisher property called objectWillChange by an extension (which the framework provides on the ObservableObject protocol). This objectWillChange property is of type PassthroughSubject, which is a concrete type of the Publisher protocol. The passthrough subject has a property called send, which is a publisher method used to send data to any subscribers. So the property called "objectWillChange" is the Publisher.

To recap, the Subscriber is the property called actor from the ContentView class, and the Publisher is the property objectWillChange from the ActorViewModel class. What about the need for the Subscriber to Subscribe to the Publisher? The "@ObservedObject" property wrapper is itself a Subscriber, so it must subscribe to the Publisher. But how does the View find out about changes sent to the Subscriber? That is handled by the SwiftUI framework, which we never see.

Take-away: we don't need to worry about subscribing the view to the Publisher. On the other hand, we do need to worry about making sure the publisher tell the subscriber when something is about to change. When the image has been fetched from a remote server, and the data has been transformed into an image object, we call objectWillChange.send() to inform the View. Once the subscriber receives notification from the publisher that something is about to / has changed, it invalidates the view (which results in the view redrawing itself).

Summary
The way in which SwiftUI uses a ObservedObject PropertyWrapper does not on the surface give away the fact that Combine even exists in the equation. But by inspecting ObservedObject and ObservableObject, the underlying Combine framework is revealed, along with the design pattern:

subscriber --> subscribing to a publisher --> which then publishes changes --> that are received by the subscriber

References:

Blog Article

WWDC 2019 Session 204

WWDC 2019 Session 226


问:
How to center an iframe horizontally?
Consider the following example: (live demo)

HTML:

```<code><div>div</div>
<iframe></iframe>
</code>```

CSS:

```<code>div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}
</code>```

Result:

Why the iframe is not centrally aligned like the div? How could I centrally align it?

答:
Here I have put snippet for all of you who are suffering to make iframe or image in center of the screen horizontally.
  Give me THUMBS UP VOTE if you like.⯅.

style > img & iframe > this is your tag name so change that if you're want any other tag in  center

            ```

Title: How to center an iframe horizontally?

Body:
Consider the following example: (live demo)

HTML:

div

CSS:

div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}

Result:

Why the iframe is not centrally aligned like the div? How could I centrally align it?

Body:
Here I have put snippet for all of you who are suffering to make iframe or image in center of the screen horizontally.
  Give me THUMBS UP VOTE if you like.⯅.

style > img & iframe > this is your tag name so change that if you're want any other tag in  center

<html >
 <head>
            <style type=text/css>
            div{}
            img{
                 margin: 0 auto;
          display:block;
          }
  iframe{
  margin: 0 auto;
  display:block;
  }

            </style>
</head>
 <body >

   <iframe src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4" width="320" height="180" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

   <img src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg" width="320" height="180"  />
            </body>
            </html>


问:
nswag generated client with wrong response type
This is autogenerated Angular service file from C# controller with help of nswag swagger client generation. This below code has all the services. In component i am trying to call getCompanyInfoOption() api. But i am not getting response data that i am sending from controller.

```<code>/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v13.6.0.0 (NJsonSchema v10.1.18.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable({
providedIn:'root'
})
export class CompanyInfoService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44311";
    }

    getCompanyInfoOption(): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetCompanyInfoOption(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetCompanyInfoOption(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetCompanyInfoOption(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }
</code>```

how can i call this service in my component? i am trying to call with subscribe method in ngOnInit of component

```<code>  ngOnInit(): void {
      this.service.getCompanyInfoOption().subscribe(
        value => {
          console.log(value);
        },
        error => console.error(JSON.stringify(error)),
        () => console.log('done')
      );
  }
</code>```

I am getting this output after calling getCompanyInfoOption api

Console Log

My c# controller

ASP .net core C# controller

The type of response of compantInfoOption send in ok is given below

conpanyInfoOption type

答:
It seems you are. Because you response type is FileResponse and in console.log you may see this object. Other thing that in data you store blob and if you need a text interpretation if it just use smth like blobToText function which is in the end of your generated file.

If I'm wrong please add expectation result to the question.

Body:
This is autogenerated Angular service file from C# controller with help of nswag swagger client generation. This below code has all the services. In component i am trying to call getCompanyInfoOption() api. But i am not getting response data that i am sending from controller.

/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v13.6.0.0 (NJsonSchema v10.1.18.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable({
providedIn:'root'
})
export class CompanyInfoService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44311";
    }

    getCompanyInfoOption(): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetCompanyInfoOption(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetCompanyInfoOption(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetCompanyInfoOption(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

how can i call this service in my component? i am trying to call with subscribe method in ngOnInit of component

  ngOnInit(): void {
      this.service.getCompanyInfoOption().subscribe(
        value => {
          console.log(value);
        },
        error => console.error(JSON.stringify(error)),
        () => console.log('done')
      );
  }

I am getting this output after calling getCompanyInfoOption api

Console Log

My c# controller

ASP .net core C# controller

The type of response of compantInfoOption send in ok is given below

conpanyInfoOption type


问:
url shortening in python
I am trying to find the simplest way to shorten my URLs using python 3. The libraries that I have seen so far are outdated and no longer maintained. People will see these URLs so I want to use something trustworthy like tinyurl or bit.ly or goog.gl

Given a URL, how can I pass it into a function that will shorten it?

What is the best way to programmatically shorten URLs in 2020?

答:
For bit.ly, you can use their API, which is documented here. If it's a simple application, you should probably start with a generic access token (get one here)

Once you have an access token, you can post a request:

method: POST

URL: https://api-ssl.bitly.com/v4/shorten

Headers:

```<code>Authorization: Bearer TOKEN_GOES_HERE```
```</li>
<li><p>Body: </p>

```  "domain": "bit.ly",
  "long_url": "https://www.my-url.com"
}```
</code>```

the response is:

```<code>{
"created_at": "2020-05-31T06:20:30+0000",
"id": "...",
"link": "<bit-ly link comes here",
"custom_bitlinks": [],
"long_url": "https://www.my-url.com/",
... some other stuff.
</code>```

In python, it would look like:

```<code>headers = {
    "content-type": "application/json",
    "Authorization": "Bearer <TOKEN_GOES_HERE"
}

body = json.dumps({
  "domain": "bit.ly",
  "long_url": "https://www.my-url.com"
})

URL = "https://api-ssl.bitly.com/v4/shorten"
res = requests.post(url = URL, data = body, headers = headers)
</code>```

Title: url shortening in python

Body:
For bit.ly, you can use their API, which is documented here. If it's a simple application, you should probably start with a generic access token (get one here)

Once you have an access token, you can post a request:

method: POST

URL: https://api-ssl.bitly.com/v4/shorten

Headers:

Authorization: Bearer TOKEN_GOES_HERE```
</code></pre></li>
<li><p>Body: </p>

<pre><code>  "domain": "bit.ly",
  "long_url": "https://www.my-url.com"
}```

the response is:

{
"created_at": "2020-05-31T06:20:30+0000",
"id": "...",
"link": "<bit-ly link comes here",
"custom_bitlinks": [],
"long_url": "https://www.my-url.com/",
... some other stuff.

In python, it would look like:

headers = {
    "content-type": "application/json",
    "Authorization": "Bearer <TOKEN_GOES_HERE"
}

body = json.dumps({
  "domain": "bit.ly",
  "long_url": "https://www.my-url.com"
})

URL = "https://api-ssl.bitly.com/v4/shorten"
res = requests.post(url = URL, data = body, headers = headers)


问:
Extract already know shape from image
I´m trying to extract this piece

From this

Ive tried to detect shapes, no way, train an haarscascade...(Idont have negatives) no way, .... the position can vary (not all of them are inserted) and the angle is not the same.. I cannot crop one by one :-(

Any suggestion ??? Thanks in advance

PS Original image is here https://pasteboard.co/JaTSoJF.png (sorry > 2Mb)

After working on @ganeshtata we got

```<code>import cv2
import numpy as np
img = cv2.imread('cropsmall.png')
height, width = img.shape[:2]
green_channel = img[:,0:] # Blue channel extraction
res = cv2.fastNlMeansDenoising(green_channel, None, 3, 7, 21) # Non-local means denoising
cv2.imshow('denoised',res)
edges = cv2.Canny(res, 11, 11, 3) # Edge detection
kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel) # Morphological closing
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours in the image

for cnt in contours: # Iterate through all contours
    x, y, w, h = cv2.boundingRect(cnt) # Reject contours whose height is less than half the image height
    if h < height / 2:
        continue
    y = 0 # Assuming that all shapes start from the top of the image
    cv2.rectangle(img, (x, y), \
          (x + w, y + h), (0, 255, 0), 2)
    cv2.imshow('IMG',img)
    cv2.imwrite("test.jpg",img)
    cv2.waitKey(0)
</code>```

That gives us

Not bad...

答:
I used the following approach to extract the pattern specified in the question.

Read the image and extract the blue channel from the image.

```<code>import cv2
import numpy as np
img = cv2.imread('image.png')
height, width = img.shape[:2]
blue_channel = img[:,:,0]
</code>```

Blue Channel -

Apply OpenCV's Non-local Means Denoising algorithm on the blue channel image. This ensures that most of the random noise in the image is smoothed.

```<code>res = cv2.fastNlMeansDenoising(blue_channel, None, 3, 7, 21)
</code>```

Denoised image -

Apply Canny edge detection.

```<code>edges = cv2.Canny(res, 1, 10, 3)
</code>```

Edge output -

Apply Morpological Closing to try and close small gaps/holes in the image.

```<code>kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
</code>```

Image after applying morphological closing -

Find all contours in the image using cv2.findContours. After finding all contours, we can determine the bounding box of each contour using cv2.boundingRect.

```<code>im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours

for cnt in contours: # Iterate through all contours
    x, y, w, h = cv2.boundingRect(cnt) $ Get contour bounding box
    if h < height / 2: # Reject contours whose height is less than half the image height
        continue
    y = 0  # Assuming that all shapes start from the top of the image
    cv2.rectangle(img, (x, y), \
          (x + w, y + h), (0, 255, 0), 2)
</code>```

Final result -

The complete code -

```<code>import cv2
import numpy as np
img = cv2.imread('image.png')
height, width = img.shape[:2]
blue_channel = img[:,:,0] # Blue channel extraction
res = cv2.fastNlMeansDenoising(blue_channel, None, 3, 7, 21) # Non-local means denoising
edges = cv2.Canny(res, 1, 10, 3) # Edge detection
kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel) # Morphological closing
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours in the image

for cnt in contours: # Iterate through all contours
    x, y, w, h = cv2.boundingRect(cnt) # Reject contours whose height is less than half the image height
    if h < height / 2:
        continue
    y = 0 # Assuming that all shapes start from the top of the image
    cv2.rectangle(img, (x, y), \
          (x + w, y + h), (0, 255, 0), 2)
</code>```

Note - This approach works for the sample image posted by you. It might/might not generalize for all images.

Title: Extract already know shape from image

Body:
I´m trying to extract this piece

From this

Ive tried to detect shapes, no way, train an haarscascade...(Idont have negatives) no way, .... the position can vary (not all of them are inserted) and the angle is not the same.. I cannot crop one by one :-(

Any suggestion ??? Thanks in advance

PS Original image is here https://pasteboard.co/JaTSoJF.png (sorry > 2Mb)

After working on @ganeshtata we got

import cv2
import numpy as np
img = cv2.imread('cropsmall.png')
height, width = img.shape[:2]
green_channel = img[:,0:] # Blue channel extraction
res = cv2.fastNlMeansDenoising(green_channel, None, 3, 7, 21) # Non-local means denoising
cv2.imshow('denoised',res)
edges = cv2.Canny(res, 11, 11, 3) # Edge detection
kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel) # Morphological closing
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours in the image

for cnt in contours: # Iterate through all contours
    x, y, w, h = cv2.boundingRect(cnt) # Reject contours whose height is less than half the image height
    if h < height / 2:
        continue
    y = 0 # Assuming that all shapes start from the top of the image
    cv2.rectangle(img, (x, y), \
          (x + w, y + h), (0, 255, 0), 2)
    cv2.imshow('IMG',img)
    cv2.imwrite("test.jpg",img)
    cv2.waitKey(0)

That gives us

Not bad...

Body:
I used the following approach to extract the pattern specified in the question.

Read the image and extract the blue channel from the image.

import cv2
import numpy as np
img = cv2.imread('image.png')
height, width = img.shape[:2]
blue_channel = img[:,:,0]

Blue Channel -

Apply OpenCV's Non-local Means Denoising algorithm on the blue channel image. This ensures that most of the random noise in the image is smoothed.

res = cv2.fastNlMeansDenoising(blue_channel, None, 3, 7, 21)

Denoised image -

Apply Canny edge detection.

edges = cv2.Canny(res, 1, 10, 3)

Edge output -

Apply Morpological Closing to try and close small gaps/holes in the image.

kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)

Image after applying morphological closing -

Find all contours in the image using cv2.findContours. After finding all contours, we can determine the bounding box of each contour using cv2.boundingRect.

im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours

for cnt in contours: # Iterate through all contours
    x, y, w, h = cv2.boundingRect(cnt) $ Get contour bounding box
    if h < height / 2: # Reject contours whose height is less than half the image height
        continue
    y = 0  # Assuming that all shapes start from the top of the image
    cv2.rectangle(img, (x, y), \
          (x + w, y + h), (0, 255, 0), 2)

Final result -

The complete code -

import cv2
import numpy as np
img = cv2.imread('image.png')
height, width = img.shape[:2]
blue_channel = img[:,:,0] # Blue channel extraction
res = cv2.fastNlMeansDenoising(blue_channel, None, 3, 7, 21) # Non-local means denoising
edges = cv2.Canny(res, 1, 10, 3) # Edge detection
kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel) # Morphological closing
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours in the image

for cnt in contours: # Iterate through all contours
    x, y, w, h = cv2.boundingRect(cnt) # Reject contours whose height is less than half the image height
    if h < height / 2:
        continue
    y = 0 # Assuming that all shapes start from the top of the image
    cv2.rectangle(img, (x, y), \
          (x + w, y + h), (0, 255, 0), 2)

Note - This approach works for the sample image posted by you. It might/might not generalize for all images.


答:
Try this:</p>

```<code>with open('test.json') as fp:
    data = json.loads(fp.read())
    del data['Codes']['8888']
</code>```

Title: Deleting sub-element from JSON file

Body:
Try this:

with open('test.json') as fp:
    data = json.loads(fp.read())
    del data['Codes']['8888']