Explore all 3D printing open source software, libraries, packages, source code, cloud functions and APIs.

3D printing, or additive manufacturing, is the construction of a three-dimensional object from a CAD model or a digital 3D model. The term "3D printing" can refer to a variety of processes in which material is deposited, joined or solidified under computer control to create a three-dimensional object, with material being added together (such as liquids or powder grains being fused together), typically layer by layer.

Popular New Releases in 3D Printing

OctoPrint

1.8.0rc5 (release candidate)

openscad

OpenSCAD 2021.01

PrusaSlicer

PrusaSlicer 2.4.2-rc2

openMVG

v2.0 Rainbow Trout

colmap

3.7

Popular Libraries in 3D Printing

OctoPrint

by OctoPrint doticonpythondoticon

star image 6542 doticonAGPL-3.0

OctoPrint is the snappy web interface for your 3D printer!

openscad

by openscad doticonc++doticon

star image 4741 doticonNOASSERTION

OpenSCAD - The Programmers Solid 3D CAD Modeller

PRNet

by YadiraF doticonpythondoticon

star image 4333 doticonMIT

Joint 3D Face Reconstruction and Dense Alignment with Position Map Regression Network (ECCV 2018)

PrusaSlicer

by prusa3d doticonc++doticon

star image 4288 doticonAGPL-3.0

G-code generator for 3D printers (RepRap, Makerbot, Ultimaker etc.)

openMVG

by openMVG doticonc++doticon

star image 4142 doticonNOASSERTION

open Multiple View Geometry library. Basis for 3D computer vision and Structure from Motion.

colmap

by colmap doticoncdoticon

star image 3790 doticonNOASSERTION

COLMAP - Structure-from-Motion and Multi-View Stereo

Cura

by Ultimaker doticonpythondoticon

star image 3633 doticonLGPL-3.0

3D printer / slicing GUI built on top of the Uranium framework

pytorch-OpCounter

by Lyken17 doticonpythondoticon

star image 2848 doticonMIT

Count the MACs / FLOPs of your PyTorch model.

Slic3r

by slic3r doticonc++doticon

star image 2720 doticonAGPL-3.0

Open Source toolpath generator for 3D printers

Trending New libraries in 3D Printing

meshrcnn

by facebookresearch doticonpythondoticon

star image 915 doticonNOASSERTION

code for Mesh R-CNN, ICCV 2019

sdf

by fogleman doticonpythondoticon

star image 740 doticonMIT

Simple SDF mesh generation in Python

Smalltalk

by dbanay doticoncdoticon

star image 615 doticonMIT

By the Bluebook implementation of Smalltalk-80

DECA

by YadiraF doticonpythondoticon

star image 601 doticonNOASSERTION

DECA: Detailed Expression Capture and Animation

ESCPOS-ThermalPrinter-Android

by DantSu doticonjavadoticon

star image 466 doticonMIT

Useful library to help Android developpers to print with (Bluetooth, TCP, USB) ESC/POS thermal printer.

pimp_my_microwave

by dekuNukem doticonc++doticon

star image 440 doticonMIT

Installing a RGB mechanical keypad on my microwave.

cups

by OpenPrinting doticoncdoticon

star image 437 doticonApache-2.0

OpenPrinting CUPS Sources

KlipperScreen

by jordanruthe doticonpythondoticon

star image 347 doticonAGPL-3.0

GUI for Klipper

HevORT

by MirageC79 doticonhtmldoticon

star image 341 doticonGPL-3.0

Advanced DIY 3D Printer

Top Authors in 3D Printing

1

jneilliii

24 Libraries

star icon504

2

OctoPrint

20 Libraries

star icon7145

3

markwal

9 Libraries

star icon236

4

OutsourcedGuru

7 Libraries

star icon60

5

makerbase-mks

7 Libraries

star icon383

6

google

6 Libraries

star icon1332

7

Spiritdude

6 Libraries

star icon92

8

fieldOfView

6 Libraries

star icon507

9

adeebshihadeh

6 Libraries

star icon116

10

tapnair

5 Libraries

star icon82

1

24 Libraries

star icon504

2

20 Libraries

star icon7145

3

9 Libraries

star icon236

4

7 Libraries

star icon60

5

7 Libraries

star icon383

6

6 Libraries

star icon1332

7

6 Libraries

star icon92

8

6 Libraries

star icon507

9

6 Libraries

star icon116

10

5 Libraries

star icon82

Trending Kits in 3D Printing

A Virginia family gets keys to Habitat for Humanity's first 3D-printed home. The 1,200-square-foot home has three bedrooms, two full baths, and the technology allowed the house to be built in just 12 hours. The home also includes a 3D printer that will enable the owner to reprint maintenance needs like electrical outlets or cabinet knobs. 3D printing has matured over the years and is widely used across use cases ranging from DIY projects to affordable homes and 3D-printed terracotta tiles designed to help corals grow and restore ocean life! The printing materials have become versatile, from proprietary filaments, plastics to terracotta and concrete, expanding the use cases. kandi kit on 3D Printing Solutions covers 3D printing libraries across slicers, printer control, STL edit, and 3D modeling. Slicers break down 3D models into lines for a 3D printer. They can slice models for different printer types. Model manipulation tools are used to prepare 3D printing, laser engraving, or CNC routing items. Host and Control software helps manage 3D printers and control your machine remotely via web interfaces. They also control the printing process remotely and keep track of print jobs in progress. STL File utilities help view, edit, design, and repair STL files. Before printing, file-viewers preview G-code files.

At MGE Custom Prints, we have been consistently perfecting our printing process by taking great pride in the simplicity and efficiency of our operation since 2016. This is a reason why we always look forward to being your last stop and your first shop.


For more info visit this website:

Printing Company Maryland

Trending Discussions on 3D Printing

How to check and return value of state object array and use that to identify which object to take data from

if state.obj.val1 === true, return state.obj.val2

How can i work with Example for nlp.update problem with spacy3.0

Laravel whereIn doesn't return all data

Kotlin get ids of selected options

Getting all the HTML code from a website that is using React

Python matching various keyword from dictionary issues

How to create a Postman server mock for uploading file and doing some uploading test of Flutter code?

Is there a name for this 3D printing effect?

Python Nested Dictionaries Retrieve Key from nested value

QUESTION

How to check and return value of state object array and use that to identify which object to take data from

Asked 2021-Sep-22 at 15:50

The Aim: Use the value of i.id from the mapped components when clicked on to search state ids and locate the object which contains the same id value... When this object is found to return/update id and active values.

Clicking on the dynamic rendered component triggering onClick to change value of the current active: true to active: false and find object with id of the clicked component and this.setState({active:value}) in that object. Then if (active === true) render iframe containing the object's id value.

The state

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17

The components rendered for each state

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17{this.state.ids.map((i) => (
18                    <Image
19                      className="carouselitem"
20                      rounded
21                      fluid
22                      src={
23                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
24                      }
25                      size="small"
26                    />
27                  ))}
28

I am Really Stumped for what to do

I tried an if loop inside a for ...in... loop... but gave me nothing but errors when trying to render the page.

Full Code

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17{this.state.ids.map((i) => (
18                    <Image
19                      className="carouselitem"
20                      rounded
21                      fluid
22                      src={
23                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
24                      }
25                      size="small"
26                    />
27                  ))}
28import React from "react";
29import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
30import { Button, Embed, Icon, Image, List } from "semantic-ui-react";
31import "./Services.css";
32import logo from "./images/EIB 3D Logo v25.png";
33import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader
34import ReactPlayer from "react-player";
35import MediaQuery from "react-responsive";
36
37export default class Services extends React.Component {
38  constructor(props) {
39    super(props);
40    this.state = {
41      ids: [
42        {
43          id: "iCBvfW08jlo",
44          active: true,
45        },
46        {
47          id: "qvOcCQXZVg0",
48          active: false,
49        },
50        {
51          id: "YXNC3GKmjgk",
52          active: false,
53        },
54      ],
55    };
56  }
57  handleClick = (props) => {};
58  render() {
59    return (
60      <div className="serviceswrap">
61        <div className="servicesbdrop">
62          <div className="primarywrap">
63            <div className="primaryvideo">
64              <div className="carousel">
65                <div className="slider">
66                  {this.state.ids.map((i) => (
67                    <Image
68                      className="carouselitem"
69                      rounded
70                      fluid
71                      src={
72                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
73                      }
74                      size="small"
75                    />
76                  ))}
77                </div>
78              </div>
79            </div>
80            <List size="big" className="servicesList">
81              <List.Item>
82                <List.Icon size="big" name="cog" />
83                <List.Content>
84                  <List.Header as="a">3D Printing</List.Header>
85                  <List.Description>
86                    Print your design using our 3d-printer.
87                  </List.Description>
88                </List.Content>
89              </List.Item>
90              <List.Item>
91                <List.Icon size="big" name="cog" />
92                <List.Content>
93                  <List.Header as="a">CNC Machining</List.Header>
94                  <List.Description>
95                    Print your design using our CNC machienery.
96                  </List.Description>
97                </List.Content>
98              </List.Item>
99              <List.Item>
100                <List.Icon size="big" name="cog" />
101                <List.Content>
102                  <List.Header as="a">Personalised Designs</List.Header>
103                  <List.Description>
104                    Design your idea to suite your needs.
105                  </List.Description>
106                </List.Content>
107              </List.Item>
108              <List.Item>
109                <List.Icon size="big" name="cog" />
110                <List.Content>
111                  <List.Header as="a">Laser Etching</List.Header>
112                  <List.Description>
113                    Elegant designs etched onto wood.
114                  </List.Description>
115                </List.Content>
116              </List.Item>
117              <List.Item>
118                <List.Icon size="big" name="cog" />
119                <List.Content>
120                  <List.Header as="a">Wood Working</List.Header>
121                  <List.Description>
122                    Build custom designed indoor and outdoor wooden signage.
123                  </List.Description>
124                </List.Content>
125              </List.Item>
126            </List>
127          </div>
128        </div>
129      </div>
130    );
131  }
132}
133
134

ANSWER

Answered 2021-Sep-18 at 14:01

You can have a button inside each mapped component as follows.

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17{this.state.ids.map((i) => (
18                    <Image
19                      className="carouselitem"
20                      rounded
21                      fluid
22                      src={
23                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
24                      }
25                      size="small"
26                    />
27                  ))}
28import React from "react";
29import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
30import { Button, Embed, Icon, Image, List } from "semantic-ui-react";
31import "./Services.css";
32import logo from "./images/EIB 3D Logo v25.png";
33import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader
34import ReactPlayer from "react-player";
35import MediaQuery from "react-responsive";
36
37export default class Services extends React.Component {
38  constructor(props) {
39    super(props);
40    this.state = {
41      ids: [
42        {
43          id: "iCBvfW08jlo",
44          active: true,
45        },
46        {
47          id: "qvOcCQXZVg0",
48          active: false,
49        },
50        {
51          id: "YXNC3GKmjgk",
52          active: false,
53        },
54      ],
55    };
56  }
57  handleClick = (props) => {};
58  render() {
59    return (
60      <div className="serviceswrap">
61        <div className="servicesbdrop">
62          <div className="primarywrap">
63            <div className="primaryvideo">
64              <div className="carousel">
65                <div className="slider">
66                  {this.state.ids.map((i) => (
67                    <Image
68                      className="carouselitem"
69                      rounded
70                      fluid
71                      src={
72                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
73                      }
74                      size="small"
75                    />
76                  ))}
77                </div>
78              </div>
79            </div>
80            <List size="big" className="servicesList">
81              <List.Item>
82                <List.Icon size="big" name="cog" />
83                <List.Content>
84                  <List.Header as="a">3D Printing</List.Header>
85                  <List.Description>
86                    Print your design using our 3d-printer.
87                  </List.Description>
88                </List.Content>
89              </List.Item>
90              <List.Item>
91                <List.Icon size="big" name="cog" />
92                <List.Content>
93                  <List.Header as="a">CNC Machining</List.Header>
94                  <List.Description>
95                    Print your design using our CNC machienery.
96                  </List.Description>
97                </List.Content>
98              </List.Item>
99              <List.Item>
100                <List.Icon size="big" name="cog" />
101                <List.Content>
102                  <List.Header as="a">Personalised Designs</List.Header>
103                  <List.Description>
104                    Design your idea to suite your needs.
105                  </List.Description>
106                </List.Content>
107              </List.Item>
108              <List.Item>
109                <List.Icon size="big" name="cog" />
110                <List.Content>
111                  <List.Header as="a">Laser Etching</List.Header>
112                  <List.Description>
113                    Elegant designs etched onto wood.
114                  </List.Description>
115                </List.Content>
116              </List.Item>
117              <List.Item>
118                <List.Icon size="big" name="cog" />
119                <List.Content>
120                  <List.Header as="a">Wood Working</List.Header>
121                  <List.Description>
122                    Build custom designed indoor and outdoor wooden signage.
123                  </List.Description>
124                </List.Content>
125              </List.Item>
126            </List>
127          </div>
128        </div>
129      </div>
130    );
131  }
132}
133
134{
135  this.state.ids.map((i) => (
136    <>
137      <Image
138        className="carouselitem"
139        rounded
140        fluid
141        src={"http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"}
142        size="small"
143      />
144      <button onClick={() => this.changeActiveField(id)}>Change Activation</button>
145    </>
146  ));
147}
148

Then create changeActiveField method inside the class component for active field change in relevant object.

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17{this.state.ids.map((i) => (
18                    <Image
19                      className="carouselitem"
20                      rounded
21                      fluid
22                      src={
23                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
24                      }
25                      size="small"
26                    />
27                  ))}
28import React from "react";
29import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
30import { Button, Embed, Icon, Image, List } from "semantic-ui-react";
31import "./Services.css";
32import logo from "./images/EIB 3D Logo v25.png";
33import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader
34import ReactPlayer from "react-player";
35import MediaQuery from "react-responsive";
36
37export default class Services extends React.Component {
38  constructor(props) {
39    super(props);
40    this.state = {
41      ids: [
42        {
43          id: "iCBvfW08jlo",
44          active: true,
45        },
46        {
47          id: "qvOcCQXZVg0",
48          active: false,
49        },
50        {
51          id: "YXNC3GKmjgk",
52          active: false,
53        },
54      ],
55    };
56  }
57  handleClick = (props) => {};
58  render() {
59    return (
60      <div className="serviceswrap">
61        <div className="servicesbdrop">
62          <div className="primarywrap">
63            <div className="primaryvideo">
64              <div className="carousel">
65                <div className="slider">
66                  {this.state.ids.map((i) => (
67                    <Image
68                      className="carouselitem"
69                      rounded
70                      fluid
71                      src={
72                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
73                      }
74                      size="small"
75                    />
76                  ))}
77                </div>
78              </div>
79            </div>
80            <List size="big" className="servicesList">
81              <List.Item>
82                <List.Icon size="big" name="cog" />
83                <List.Content>
84                  <List.Header as="a">3D Printing</List.Header>
85                  <List.Description>
86                    Print your design using our 3d-printer.
87                  </List.Description>
88                </List.Content>
89              </List.Item>
90              <List.Item>
91                <List.Icon size="big" name="cog" />
92                <List.Content>
93                  <List.Header as="a">CNC Machining</List.Header>
94                  <List.Description>
95                    Print your design using our CNC machienery.
96                  </List.Description>
97                </List.Content>
98              </List.Item>
99              <List.Item>
100                <List.Icon size="big" name="cog" />
101                <List.Content>
102                  <List.Header as="a">Personalised Designs</List.Header>
103                  <List.Description>
104                    Design your idea to suite your needs.
105                  </List.Description>
106                </List.Content>
107              </List.Item>
108              <List.Item>
109                <List.Icon size="big" name="cog" />
110                <List.Content>
111                  <List.Header as="a">Laser Etching</List.Header>
112                  <List.Description>
113                    Elegant designs etched onto wood.
114                  </List.Description>
115                </List.Content>
116              </List.Item>
117              <List.Item>
118                <List.Icon size="big" name="cog" />
119                <List.Content>
120                  <List.Header as="a">Wood Working</List.Header>
121                  <List.Description>
122                    Build custom designed indoor and outdoor wooden signage.
123                  </List.Description>
124                </List.Content>
125              </List.Item>
126            </List>
127          </div>
128        </div>
129      </div>
130    );
131  }
132}
133
134{
135  this.state.ids.map((i) => (
136    <>
137      <Image
138        className="carouselitem"
139        rounded
140        fluid
141        src={"http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"}
142        size="small"
143      />
144      <button onClick={() => this.changeActiveField(id)}>Change Activation</button>
145    </>
146  ));
147}
148changeActiveField = (id) => {
149  this.setState({
150    ids: this.state.ids.map((obj) =>
151      obj.id === id ? { ...obj, active: false } : obj
152    ),
153  });
154};
155

Source https://stackoverflow.com/questions/69235238

QUESTION

if state.obj.val1 === true, return state.obj.val2

Asked 2021-Sep-20 at 22:52

I am trying to find an object key value in a state array, and when that value is found (true) return the value of another key value in that object. I am really bad with loops :/ I've attempted may variations of loops and this is only my latest attempt.

the state

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17

my latest attempt at retrieving the value returning Array.prototype.map() expects a value to be returned at the end of arrow function

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17ifActiveField = this.ids.map((val) => {
18    if (val["active"] === true) {
19      return { ...val["id"] };
20    }
21  });
22

The id returned from the active object would then be passed to render a new component.

This is what the page is returning when app is run This is what the page is returning when app is run

My full Code

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17ifActiveField = this.ids.map((val) => {
18    if (val["active"] === true) {
19      return { ...val["id"] };
20    }
21  });
22import React from "react";
23import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
24import { Button, Embed, Icon, Image, List } from "semantic-ui-react";
25import "./Services.css";
26import logo from "./images/EIB 3D Logo v25.png";
27import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader
28import ReactPlayer from "react-player";
29import MediaQuery from "react-responsive";
30
31export default class Services extends React.Component {
32  constructor(props) {
33    super(props);
34    this.state = {
35      ids: [
36        {
37          id: "iCBvfW08jlo",
38          active: true,
39        },
40        {
41          id: "qvOcCQXZVg0",
42          active: false,
43        },
44        {
45          id: "YXNC3GKmjgk",
46          active: false,
47        },
48      ],
49    };
50  }
51
52  ifActiveField = this.ids.map((val) => {
53    if (val["active"] === true) {
54      return { ...val["id"] };
55    }
56  });
57  changeActiveField = (id, active) => {
58    this.setState({
59      ids: this.state.ids.map((obj) =>
60        obj.id === id ? { ...obj, active: false } : obj
61      ),
62    });
63  };
64
65  render() {
66    return (
67      <div className="serviceswrap">
68        <div className="servicesbdrop">
69          <div className="primarywrap">
70            <div className="primaryvideo">
71            <Embed
72                autoplay={false}
73                width='100px'
74                height='100px'
75                color="white"
76                hd={false}
77                id={this.ifActiveField}
78                iframe={{
79                  allowFullScreen: true,
80                  style: {
81                    padding: 10,
82                  },
83                }}
84              />
85              <div className="carousel">
86                <div className="slider">
87                  {this.state.ids.map((i) => (
88                    <Image
89                      className="carouselitem"
90                      rounded
91                      fluid
92                      onClick={() => this.changeActiveField(i.id)}
93                      src={
94                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
95                      }
96                      size="small"
97                    />
98                  ))}
99                </div>
100              </div>
101            </div>
102            <List size="big" className="servicesList">
103              <List.Item>
104                <List.Icon size="big" name="cog" />
105                <List.Content>
106                  <List.Header as="a">3D Printing</List.Header>
107                  <List.Description>
108                    Print your design using our 3d-printer.
109                  </List.Description>
110                </List.Content>
111              </List.Item>
112              <List.Item>
113                <List.Icon size="big" name="cog" />
114                <List.Content>
115                  <List.Header as="a">CNC Machining</List.Header>
116                  <List.Description>
117                    Print your design using our CNC machienery.
118                  </List.Description>
119                </List.Content>
120              </List.Item>
121              <List.Item>
122                <List.Icon size="big" name="cog" />
123                <List.Content>
124                  <List.Header as="a">Personalised Designs</List.Header>
125                  <List.Description>
126                    Design your idea to suite your needs.
127                  </List.Description>
128                </List.Content>
129              </List.Item>
130              <List.Item>
131                <List.Icon size="big" name="cog" />
132                <List.Content>
133                  <List.Header as="a">Laser Etching</List.Header>
134                  <List.Description>
135                    Elegant designs etched onto wood.
136                  </List.Description>
137                </List.Content>
138              </List.Item>
139              <List.Item>
140                <List.Icon size="big" name="cog" />
141                <List.Content>
142                  <List.Header as="a">Wood Working</List.Header>
143                  <List.Description>
144                    Build custom designed indoor and outdoor wooden signage.
145                  </List.Description>
146                </List.Content>
147              </List.Item>
148            </List>
149          </div>
150        </div>
151      </div>
152    );
153  }
154}
155
156

EDIT ______________________________________________

For reference, the three images surrounded in salmon BG on the following link https://test.ghostrez.net/ then click on the Services page

These will be made clickable so that when clicked. the corresponding object in this.state.ids is found and this.state.ids.active is set to active:true.

Here is my current question I'm trying to scan the state.ids.objects.active for which object has the active value true. When this object is found that objects id value should be returned.

Example the function should find this state array object, and return iCBvfW08jlo.

1this.state = {
2      ids: [
3        {
4          id: "iCBvfW08jlo",
5          active: true,
6        },
7        {
8          id: "qvOcCQXZVg0",
9          active: false,
10        },
11        {
12          id: "YXNC3GKmjgk",
13          active: false,
14        },
15      ],
16    };
17ifActiveField = this.ids.map((val) => {
18    if (val["active"] === true) {
19      return { ...val["id"] };
20    }
21  });
22import React from "react";
23import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
24import { Button, Embed, Icon, Image, List } from "semantic-ui-react";
25import "./Services.css";
26import logo from "./images/EIB 3D Logo v25.png";
27import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader
28import ReactPlayer from "react-player";
29import MediaQuery from "react-responsive";
30
31export default class Services extends React.Component {
32  constructor(props) {
33    super(props);
34    this.state = {
35      ids: [
36        {
37          id: "iCBvfW08jlo",
38          active: true,
39        },
40        {
41          id: "qvOcCQXZVg0",
42          active: false,
43        },
44        {
45          id: "YXNC3GKmjgk",
46          active: false,
47        },
48      ],
49    };
50  }
51
52  ifActiveField = this.ids.map((val) => {
53    if (val["active"] === true) {
54      return { ...val["id"] };
55    }
56  });
57  changeActiveField = (id, active) => {
58    this.setState({
59      ids: this.state.ids.map((obj) =>
60        obj.id === id ? { ...obj, active: false } : obj
61      ),
62    });
63  };
64
65  render() {
66    return (
67      <div className="serviceswrap">
68        <div className="servicesbdrop">
69          <div className="primarywrap">
70            <div className="primaryvideo">
71            <Embed
72                autoplay={false}
73                width='100px'
74                height='100px'
75                color="white"
76                hd={false}
77                id={this.ifActiveField}
78                iframe={{
79                  allowFullScreen: true,
80                  style: {
81                    padding: 10,
82                  },
83                }}
84              />
85              <div className="carousel">
86                <div className="slider">
87                  {this.state.ids.map((i) => (
88                    <Image
89                      className="carouselitem"
90                      rounded
91                      fluid
92                      onClick={() => this.changeActiveField(i.id)}
93                      src={
94                        "http://img.youtube.com/vi/" + i.id + "/hqdefault.jpg"
95                      }
96                      size="small"
97                    />
98                  ))}
99                </div>
100              </div>
101            </div>
102            <List size="big" className="servicesList">
103              <List.Item>
104                <List.Icon size="big" name="cog" />
105                <List.Content>
106                  <List.Header as="a">3D Printing</List.Header>
107                  <List.Description>
108                    Print your design using our 3d-printer.
109                  </List.Description>
110                </List.Content>
111              </List.Item>
112              <List.Item>
113                <List.Icon size="big" name="cog" />
114                <List.Content>
115                  <List.Header as="a">CNC Machining</List.Header>
116                  <List.Description>
117                    Print your design using our CNC machienery.
118                  </List.Description>
119                </List.Content>
120              </List.Item>
121              <List.Item>
122                <List.Icon size="big" name="cog" />
123                <List.Content>
124                  <List.Header as="a">Personalised Designs</List.Header>
125                  <List.Description>
126                    Design your idea to suite your needs.
127                  </List.Description>
128                </List.Content>
129              </List.Item>
130              <List.Item>
131                <List.Icon size="big" name="cog" />
132                <List.Content>
133                  <List.Header as="a">Laser Etching</List.Header>
134                  <List.Description>
135                    Elegant designs etched onto wood.
136                  </List.Description>
137                </List.Content>
138              </List.Item>
139              <List.Item>
140                <List.Icon size="big" name="cog" />
141                <List.Content>
142                  <List.Header as="a">Wood Working</List.Header>
143                  <List.Description>
144                    Build custom designed indoor and outdoor wooden signage.
145                  </List.Description>
146                </List.Content>
147              </List.Item>
148            </List>
149          </div>
150        </div>
151      </div>
152    );
153  }
154}
155
156{
157          id: "iCBvfW08jlo",
158          active: true,
159        },
160

so then I can pass that value into rendering the appropriate <div className='primaryvideo'></div>

1this.state = {
2      ids: [
3        {
4          id: &quot;iCBvfW08jlo&quot;,
5          active: true,
6        },
7        {
8          id: &quot;qvOcCQXZVg0&quot;,
9          active: false,
10        },
11        {
12          id: &quot;YXNC3GKmjgk&quot;,
13          active: false,
14        },
15      ],
16    };
17ifActiveField = this.ids.map((val) =&gt; {
18    if (val[&quot;active&quot;] === true) {
19      return { ...val[&quot;id&quot;] };
20    }
21  });
22import React from &quot;react&quot;;
23import { BrowserRouter as Router, Switch, Route, Link } from &quot;react-router-dom&quot;;
24import { Button, Embed, Icon, Image, List } from &quot;semantic-ui-react&quot;;
25import &quot;./Services.css&quot;;
26import logo from &quot;./images/EIB 3D Logo v25.png&quot;;
27import &quot;react-responsive-carousel/lib/styles/carousel.min.css&quot;; // requires a loader
28import ReactPlayer from &quot;react-player&quot;;
29import MediaQuery from &quot;react-responsive&quot;;
30
31export default class Services extends React.Component {
32  constructor(props) {
33    super(props);
34    this.state = {
35      ids: [
36        {
37          id: &quot;iCBvfW08jlo&quot;,
38          active: true,
39        },
40        {
41          id: &quot;qvOcCQXZVg0&quot;,
42          active: false,
43        },
44        {
45          id: &quot;YXNC3GKmjgk&quot;,
46          active: false,
47        },
48      ],
49    };
50  }
51
52  ifActiveField = this.ids.map((val) =&gt; {
53    if (val[&quot;active&quot;] === true) {
54      return { ...val[&quot;id&quot;] };
55    }
56  });
57  changeActiveField = (id, active) =&gt; {
58    this.setState({
59      ids: this.state.ids.map((obj) =&gt;
60        obj.id === id ? { ...obj, active: false } : obj
61      ),
62    });
63  };
64
65  render() {
66    return (
67      &lt;div className=&quot;serviceswrap&quot;&gt;
68        &lt;div className=&quot;servicesbdrop&quot;&gt;
69          &lt;div className=&quot;primarywrap&quot;&gt;
70            &lt;div className=&quot;primaryvideo&quot;&gt;
71            &lt;Embed
72                autoplay={false}
73                width='100px'
74                height='100px'
75                color=&quot;white&quot;
76                hd={false}
77                id={this.ifActiveField}
78                iframe={{
79                  allowFullScreen: true,
80                  style: {
81                    padding: 10,
82                  },
83                }}
84              /&gt;
85              &lt;div className=&quot;carousel&quot;&gt;
86                &lt;div className=&quot;slider&quot;&gt;
87                  {this.state.ids.map((i) =&gt; (
88                    &lt;Image
89                      className=&quot;carouselitem&quot;
90                      rounded
91                      fluid
92                      onClick={() =&gt; this.changeActiveField(i.id)}
93                      src={
94                        &quot;http://img.youtube.com/vi/&quot; + i.id + &quot;/hqdefault.jpg&quot;
95                      }
96                      size=&quot;small&quot;
97                    /&gt;
98                  ))}
99                &lt;/div&gt;
100              &lt;/div&gt;
101            &lt;/div&gt;
102            &lt;List size=&quot;big&quot; className=&quot;servicesList&quot;&gt;
103              &lt;List.Item&gt;
104                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
105                &lt;List.Content&gt;
106                  &lt;List.Header as=&quot;a&quot;&gt;3D Printing&lt;/List.Header&gt;
107                  &lt;List.Description&gt;
108                    Print your design using our 3d-printer.
109                  &lt;/List.Description&gt;
110                &lt;/List.Content&gt;
111              &lt;/List.Item&gt;
112              &lt;List.Item&gt;
113                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
114                &lt;List.Content&gt;
115                  &lt;List.Header as=&quot;a&quot;&gt;CNC Machining&lt;/List.Header&gt;
116                  &lt;List.Description&gt;
117                    Print your design using our CNC machienery.
118                  &lt;/List.Description&gt;
119                &lt;/List.Content&gt;
120              &lt;/List.Item&gt;
121              &lt;List.Item&gt;
122                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
123                &lt;List.Content&gt;
124                  &lt;List.Header as=&quot;a&quot;&gt;Personalised Designs&lt;/List.Header&gt;
125                  &lt;List.Description&gt;
126                    Design your idea to suite your needs.
127                  &lt;/List.Description&gt;
128                &lt;/List.Content&gt;
129              &lt;/List.Item&gt;
130              &lt;List.Item&gt;
131                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
132                &lt;List.Content&gt;
133                  &lt;List.Header as=&quot;a&quot;&gt;Laser Etching&lt;/List.Header&gt;
134                  &lt;List.Description&gt;
135                    Elegant designs etched onto wood.
136                  &lt;/List.Description&gt;
137                &lt;/List.Content&gt;
138              &lt;/List.Item&gt;
139              &lt;List.Item&gt;
140                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
141                &lt;List.Content&gt;
142                  &lt;List.Header as=&quot;a&quot;&gt;Wood Working&lt;/List.Header&gt;
143                  &lt;List.Description&gt;
144                    Build custom designed indoor and outdoor wooden signage.
145                  &lt;/List.Description&gt;
146                &lt;/List.Content&gt;
147              &lt;/List.Item&gt;
148            &lt;/List&gt;
149          &lt;/div&gt;
150        &lt;/div&gt;
151      &lt;/div&gt;
152    );
153  }
154}
155
156{
157          id: &quot;iCBvfW08jlo&quot;,
158          active: true,
159        },
160          &lt;Embed
161                autoplay={false}
162                width='100px'
163                height='100px'
164                color=&quot;white&quot;
165                hd={false}
166                id={this.ifActiveField}
167                iframe={{
168                  allowFullScreen: true,
169                  style: {
170                    padding: 10,
171                  },
172                }}
173              /&gt;
174

ANSWER

Answered 2021-Sep-20 at 22:52

It is not entirely clear what you are asking, do you just want the first id that is "active"? Or an array of "active" ids?

If it is just the first then simply loop over them, and return the correct id if active is true.

1this.state = {
2      ids: [
3        {
4          id: &quot;iCBvfW08jlo&quot;,
5          active: true,
6        },
7        {
8          id: &quot;qvOcCQXZVg0&quot;,
9          active: false,
10        },
11        {
12          id: &quot;YXNC3GKmjgk&quot;,
13          active: false,
14        },
15      ],
16    };
17ifActiveField = this.ids.map((val) =&gt; {
18    if (val[&quot;active&quot;] === true) {
19      return { ...val[&quot;id&quot;] };
20    }
21  });
22import React from &quot;react&quot;;
23import { BrowserRouter as Router, Switch, Route, Link } from &quot;react-router-dom&quot;;
24import { Button, Embed, Icon, Image, List } from &quot;semantic-ui-react&quot;;
25import &quot;./Services.css&quot;;
26import logo from &quot;./images/EIB 3D Logo v25.png&quot;;
27import &quot;react-responsive-carousel/lib/styles/carousel.min.css&quot;; // requires a loader
28import ReactPlayer from &quot;react-player&quot;;
29import MediaQuery from &quot;react-responsive&quot;;
30
31export default class Services extends React.Component {
32  constructor(props) {
33    super(props);
34    this.state = {
35      ids: [
36        {
37          id: &quot;iCBvfW08jlo&quot;,
38          active: true,
39        },
40        {
41          id: &quot;qvOcCQXZVg0&quot;,
42          active: false,
43        },
44        {
45          id: &quot;YXNC3GKmjgk&quot;,
46          active: false,
47        },
48      ],
49    };
50  }
51
52  ifActiveField = this.ids.map((val) =&gt; {
53    if (val[&quot;active&quot;] === true) {
54      return { ...val[&quot;id&quot;] };
55    }
56  });
57  changeActiveField = (id, active) =&gt; {
58    this.setState({
59      ids: this.state.ids.map((obj) =&gt;
60        obj.id === id ? { ...obj, active: false } : obj
61      ),
62    });
63  };
64
65  render() {
66    return (
67      &lt;div className=&quot;serviceswrap&quot;&gt;
68        &lt;div className=&quot;servicesbdrop&quot;&gt;
69          &lt;div className=&quot;primarywrap&quot;&gt;
70            &lt;div className=&quot;primaryvideo&quot;&gt;
71            &lt;Embed
72                autoplay={false}
73                width='100px'
74                height='100px'
75                color=&quot;white&quot;
76                hd={false}
77                id={this.ifActiveField}
78                iframe={{
79                  allowFullScreen: true,
80                  style: {
81                    padding: 10,
82                  },
83                }}
84              /&gt;
85              &lt;div className=&quot;carousel&quot;&gt;
86                &lt;div className=&quot;slider&quot;&gt;
87                  {this.state.ids.map((i) =&gt; (
88                    &lt;Image
89                      className=&quot;carouselitem&quot;
90                      rounded
91                      fluid
92                      onClick={() =&gt; this.changeActiveField(i.id)}
93                      src={
94                        &quot;http://img.youtube.com/vi/&quot; + i.id + &quot;/hqdefault.jpg&quot;
95                      }
96                      size=&quot;small&quot;
97                    /&gt;
98                  ))}
99                &lt;/div&gt;
100              &lt;/div&gt;
101            &lt;/div&gt;
102            &lt;List size=&quot;big&quot; className=&quot;servicesList&quot;&gt;
103              &lt;List.Item&gt;
104                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
105                &lt;List.Content&gt;
106                  &lt;List.Header as=&quot;a&quot;&gt;3D Printing&lt;/List.Header&gt;
107                  &lt;List.Description&gt;
108                    Print your design using our 3d-printer.
109                  &lt;/List.Description&gt;
110                &lt;/List.Content&gt;
111              &lt;/List.Item&gt;
112              &lt;List.Item&gt;
113                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
114                &lt;List.Content&gt;
115                  &lt;List.Header as=&quot;a&quot;&gt;CNC Machining&lt;/List.Header&gt;
116                  &lt;List.Description&gt;
117                    Print your design using our CNC machienery.
118                  &lt;/List.Description&gt;
119                &lt;/List.Content&gt;
120              &lt;/List.Item&gt;
121              &lt;List.Item&gt;
122                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
123                &lt;List.Content&gt;
124                  &lt;List.Header as=&quot;a&quot;&gt;Personalised Designs&lt;/List.Header&gt;
125                  &lt;List.Description&gt;
126                    Design your idea to suite your needs.
127                  &lt;/List.Description&gt;
128                &lt;/List.Content&gt;
129              &lt;/List.Item&gt;
130              &lt;List.Item&gt;
131                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
132                &lt;List.Content&gt;
133                  &lt;List.Header as=&quot;a&quot;&gt;Laser Etching&lt;/List.Header&gt;
134                  &lt;List.Description&gt;
135                    Elegant designs etched onto wood.
136                  &lt;/List.Description&gt;
137                &lt;/List.Content&gt;
138              &lt;/List.Item&gt;
139              &lt;List.Item&gt;
140                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
141                &lt;List.Content&gt;
142                  &lt;List.Header as=&quot;a&quot;&gt;Wood Working&lt;/List.Header&gt;
143                  &lt;List.Description&gt;
144                    Build custom designed indoor and outdoor wooden signage.
145                  &lt;/List.Description&gt;
146                &lt;/List.Content&gt;
147              &lt;/List.Item&gt;
148            &lt;/List&gt;
149          &lt;/div&gt;
150        &lt;/div&gt;
151      &lt;/div&gt;
152    );
153  }
154}
155
156{
157          id: &quot;iCBvfW08jlo&quot;,
158          active: true,
159        },
160          &lt;Embed
161                autoplay={false}
162                width='100px'
163                height='100px'
164                color=&quot;white&quot;
165                hd={false}
166                id={this.ifActiveField}
167                iframe={{
168                  allowFullScreen: true,
169                  style: {
170                    padding: 10,
171                  },
172                }}
173              /&gt;
174var state = {
175  ids: [{
176      id: "iCBvfW08jlo",
177      active: true,
178    },
179    {
180      id: "qvOcCQXZVg0",
181      active: false,
182    },
183    {
184      id: "YXNC3GKmjgk",
185      active: false,
186    },
187  ]
188};
189
190function firstActiveId(ids) {
191  for (var i = 0; i &lt; ids.length; i++) {
192    if (ids[i].active) {
193      return ids[i].id;
194    }
195  }
196}
197
198console.log(firstActiveId(state.ids));

To use the function in your example simply call it passing in the array of ids. e.g.

1this.state = {
2      ids: [
3        {
4          id: &quot;iCBvfW08jlo&quot;,
5          active: true,
6        },
7        {
8          id: &quot;qvOcCQXZVg0&quot;,
9          active: false,
10        },
11        {
12          id: &quot;YXNC3GKmjgk&quot;,
13          active: false,
14        },
15      ],
16    };
17ifActiveField = this.ids.map((val) =&gt; {
18    if (val[&quot;active&quot;] === true) {
19      return { ...val[&quot;id&quot;] };
20    }
21  });
22import React from &quot;react&quot;;
23import { BrowserRouter as Router, Switch, Route, Link } from &quot;react-router-dom&quot;;
24import { Button, Embed, Icon, Image, List } from &quot;semantic-ui-react&quot;;
25import &quot;./Services.css&quot;;
26import logo from &quot;./images/EIB 3D Logo v25.png&quot;;
27import &quot;react-responsive-carousel/lib/styles/carousel.min.css&quot;; // requires a loader
28import ReactPlayer from &quot;react-player&quot;;
29import MediaQuery from &quot;react-responsive&quot;;
30
31export default class Services extends React.Component {
32  constructor(props) {
33    super(props);
34    this.state = {
35      ids: [
36        {
37          id: &quot;iCBvfW08jlo&quot;,
38          active: true,
39        },
40        {
41          id: &quot;qvOcCQXZVg0&quot;,
42          active: false,
43        },
44        {
45          id: &quot;YXNC3GKmjgk&quot;,
46          active: false,
47        },
48      ],
49    };
50  }
51
52  ifActiveField = this.ids.map((val) =&gt; {
53    if (val[&quot;active&quot;] === true) {
54      return { ...val[&quot;id&quot;] };
55    }
56  });
57  changeActiveField = (id, active) =&gt; {
58    this.setState({
59      ids: this.state.ids.map((obj) =&gt;
60        obj.id === id ? { ...obj, active: false } : obj
61      ),
62    });
63  };
64
65  render() {
66    return (
67      &lt;div className=&quot;serviceswrap&quot;&gt;
68        &lt;div className=&quot;servicesbdrop&quot;&gt;
69          &lt;div className=&quot;primarywrap&quot;&gt;
70            &lt;div className=&quot;primaryvideo&quot;&gt;
71            &lt;Embed
72                autoplay={false}
73                width='100px'
74                height='100px'
75                color=&quot;white&quot;
76                hd={false}
77                id={this.ifActiveField}
78                iframe={{
79                  allowFullScreen: true,
80                  style: {
81                    padding: 10,
82                  },
83                }}
84              /&gt;
85              &lt;div className=&quot;carousel&quot;&gt;
86                &lt;div className=&quot;slider&quot;&gt;
87                  {this.state.ids.map((i) =&gt; (
88                    &lt;Image
89                      className=&quot;carouselitem&quot;
90                      rounded
91                      fluid
92                      onClick={() =&gt; this.changeActiveField(i.id)}
93                      src={
94                        &quot;http://img.youtube.com/vi/&quot; + i.id + &quot;/hqdefault.jpg&quot;
95                      }
96                      size=&quot;small&quot;
97                    /&gt;
98                  ))}
99                &lt;/div&gt;
100              &lt;/div&gt;
101            &lt;/div&gt;
102            &lt;List size=&quot;big&quot; className=&quot;servicesList&quot;&gt;
103              &lt;List.Item&gt;
104                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
105                &lt;List.Content&gt;
106                  &lt;List.Header as=&quot;a&quot;&gt;3D Printing&lt;/List.Header&gt;
107                  &lt;List.Description&gt;
108                    Print your design using our 3d-printer.
109                  &lt;/List.Description&gt;
110                &lt;/List.Content&gt;
111              &lt;/List.Item&gt;
112              &lt;List.Item&gt;
113                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
114                &lt;List.Content&gt;
115                  &lt;List.Header as=&quot;a&quot;&gt;CNC Machining&lt;/List.Header&gt;
116                  &lt;List.Description&gt;
117                    Print your design using our CNC machienery.
118                  &lt;/List.Description&gt;
119                &lt;/List.Content&gt;
120              &lt;/List.Item&gt;
121              &lt;List.Item&gt;
122                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
123                &lt;List.Content&gt;
124                  &lt;List.Header as=&quot;a&quot;&gt;Personalised Designs&lt;/List.Header&gt;
125                  &lt;List.Description&gt;
126                    Design your idea to suite your needs.
127                  &lt;/List.Description&gt;
128                &lt;/List.Content&gt;
129              &lt;/List.Item&gt;
130              &lt;List.Item&gt;
131                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
132                &lt;List.Content&gt;
133                  &lt;List.Header as=&quot;a&quot;&gt;Laser Etching&lt;/List.Header&gt;
134                  &lt;List.Description&gt;
135                    Elegant designs etched onto wood.
136                  &lt;/List.Description&gt;
137                &lt;/List.Content&gt;
138              &lt;/List.Item&gt;
139              &lt;List.Item&gt;
140                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
141                &lt;List.Content&gt;
142                  &lt;List.Header as=&quot;a&quot;&gt;Wood Working&lt;/List.Header&gt;
143                  &lt;List.Description&gt;
144                    Build custom designed indoor and outdoor wooden signage.
145                  &lt;/List.Description&gt;
146                &lt;/List.Content&gt;
147              &lt;/List.Item&gt;
148            &lt;/List&gt;
149          &lt;/div&gt;
150        &lt;/div&gt;
151      &lt;/div&gt;
152    );
153  }
154}
155
156{
157          id: &quot;iCBvfW08jlo&quot;,
158          active: true,
159        },
160          &lt;Embed
161                autoplay={false}
162                width='100px'
163                height='100px'
164                color=&quot;white&quot;
165                hd={false}
166                id={this.ifActiveField}
167                iframe={{
168                  allowFullScreen: true,
169                  style: {
170                    padding: 10,
171                  },
172                }}
173              /&gt;
174var state = {
175  ids: [{
176      id: "iCBvfW08jlo",
177      active: true,
178    },
179    {
180      id: "qvOcCQXZVg0",
181      active: false,
182    },
183    {
184      id: "YXNC3GKmjgk",
185      active: false,
186    },
187  ]
188};
189
190function firstActiveId(ids) {
191  for (var i = 0; i &lt; ids.length; i++) {
192    if (ids[i].active) {
193      return ids[i].id;
194    }
195  }
196}
197
198console.log(firstActiveId(state.ids));ifActiveField = firstActiveId(this.ids);
199

If you want to use find or some such that is also possible...simply

1this.state = {
2      ids: [
3        {
4          id: &quot;iCBvfW08jlo&quot;,
5          active: true,
6        },
7        {
8          id: &quot;qvOcCQXZVg0&quot;,
9          active: false,
10        },
11        {
12          id: &quot;YXNC3GKmjgk&quot;,
13          active: false,
14        },
15      ],
16    };
17ifActiveField = this.ids.map((val) =&gt; {
18    if (val[&quot;active&quot;] === true) {
19      return { ...val[&quot;id&quot;] };
20    }
21  });
22import React from &quot;react&quot;;
23import { BrowserRouter as Router, Switch, Route, Link } from &quot;react-router-dom&quot;;
24import { Button, Embed, Icon, Image, List } from &quot;semantic-ui-react&quot;;
25import &quot;./Services.css&quot;;
26import logo from &quot;./images/EIB 3D Logo v25.png&quot;;
27import &quot;react-responsive-carousel/lib/styles/carousel.min.css&quot;; // requires a loader
28import ReactPlayer from &quot;react-player&quot;;
29import MediaQuery from &quot;react-responsive&quot;;
30
31export default class Services extends React.Component {
32  constructor(props) {
33    super(props);
34    this.state = {
35      ids: [
36        {
37          id: &quot;iCBvfW08jlo&quot;,
38          active: true,
39        },
40        {
41          id: &quot;qvOcCQXZVg0&quot;,
42          active: false,
43        },
44        {
45          id: &quot;YXNC3GKmjgk&quot;,
46          active: false,
47        },
48      ],
49    };
50  }
51
52  ifActiveField = this.ids.map((val) =&gt; {
53    if (val[&quot;active&quot;] === true) {
54      return { ...val[&quot;id&quot;] };
55    }
56  });
57  changeActiveField = (id, active) =&gt; {
58    this.setState({
59      ids: this.state.ids.map((obj) =&gt;
60        obj.id === id ? { ...obj, active: false } : obj
61      ),
62    });
63  };
64
65  render() {
66    return (
67      &lt;div className=&quot;serviceswrap&quot;&gt;
68        &lt;div className=&quot;servicesbdrop&quot;&gt;
69          &lt;div className=&quot;primarywrap&quot;&gt;
70            &lt;div className=&quot;primaryvideo&quot;&gt;
71            &lt;Embed
72                autoplay={false}
73                width='100px'
74                height='100px'
75                color=&quot;white&quot;
76                hd={false}
77                id={this.ifActiveField}
78                iframe={{
79                  allowFullScreen: true,
80                  style: {
81                    padding: 10,
82                  },
83                }}
84              /&gt;
85              &lt;div className=&quot;carousel&quot;&gt;
86                &lt;div className=&quot;slider&quot;&gt;
87                  {this.state.ids.map((i) =&gt; (
88                    &lt;Image
89                      className=&quot;carouselitem&quot;
90                      rounded
91                      fluid
92                      onClick={() =&gt; this.changeActiveField(i.id)}
93                      src={
94                        &quot;http://img.youtube.com/vi/&quot; + i.id + &quot;/hqdefault.jpg&quot;
95                      }
96                      size=&quot;small&quot;
97                    /&gt;
98                  ))}
99                &lt;/div&gt;
100              &lt;/div&gt;
101            &lt;/div&gt;
102            &lt;List size=&quot;big&quot; className=&quot;servicesList&quot;&gt;
103              &lt;List.Item&gt;
104                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
105                &lt;List.Content&gt;
106                  &lt;List.Header as=&quot;a&quot;&gt;3D Printing&lt;/List.Header&gt;
107                  &lt;List.Description&gt;
108                    Print your design using our 3d-printer.
109                  &lt;/List.Description&gt;
110                &lt;/List.Content&gt;
111              &lt;/List.Item&gt;
112              &lt;List.Item&gt;
113                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
114                &lt;List.Content&gt;
115                  &lt;List.Header as=&quot;a&quot;&gt;CNC Machining&lt;/List.Header&gt;
116                  &lt;List.Description&gt;
117                    Print your design using our CNC machienery.
118                  &lt;/List.Description&gt;
119                &lt;/List.Content&gt;
120              &lt;/List.Item&gt;
121              &lt;List.Item&gt;
122                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
123                &lt;List.Content&gt;
124                  &lt;List.Header as=&quot;a&quot;&gt;Personalised Designs&lt;/List.Header&gt;
125                  &lt;List.Description&gt;
126                    Design your idea to suite your needs.
127                  &lt;/List.Description&gt;
128                &lt;/List.Content&gt;
129              &lt;/List.Item&gt;
130              &lt;List.Item&gt;
131                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
132                &lt;List.Content&gt;
133                  &lt;List.Header as=&quot;a&quot;&gt;Laser Etching&lt;/List.Header&gt;
134                  &lt;List.Description&gt;
135                    Elegant designs etched onto wood.
136                  &lt;/List.Description&gt;
137                &lt;/List.Content&gt;
138              &lt;/List.Item&gt;
139              &lt;List.Item&gt;
140                &lt;List.Icon size=&quot;big&quot; name=&quot;cog&quot; /&gt;
141                &lt;List.Content&gt;
142                  &lt;List.Header as=&quot;a&quot;&gt;Wood Working&lt;/List.Header&gt;
143                  &lt;List.Description&gt;
144                    Build custom designed indoor and outdoor wooden signage.
145                  &lt;/List.Description&gt;
146                &lt;/List.Content&gt;
147              &lt;/List.Item&gt;
148            &lt;/List&gt;
149          &lt;/div&gt;
150        &lt;/div&gt;
151      &lt;/div&gt;
152    );
153  }
154}
155
156{
157          id: &quot;iCBvfW08jlo&quot;,
158          active: true,
159        },
160          &lt;Embed
161                autoplay={false}
162                width='100px'
163                height='100px'
164                color=&quot;white&quot;
165                hd={false}
166                id={this.ifActiveField}
167                iframe={{
168                  allowFullScreen: true,
169                  style: {
170                    padding: 10,
171                  },
172                }}
173              /&gt;
174var state = {
175  ids: [{
176      id: "iCBvfW08jlo",
177      active: true,
178    },
179    {
180      id: "qvOcCQXZVg0",
181      active: false,
182    },
183    {
184      id: "YXNC3GKmjgk",
185      active: false,
186    },
187  ]
188};
189
190function firstActiveId(ids) {
191  for (var i = 0; i &lt; ids.length; i++) {
192    if (ids[i].active) {
193      return ids[i].id;
194    }
195  }
196}
197
198console.log(firstActiveId(state.ids));ifActiveField = firstActiveId(this.ids);
199ifActiveField = this.ids.find(x =&gt; x.active).id;
200

Source https://stackoverflow.com/questions/69240781

QUESTION

How can i work with Example for nlp.update problem with spacy3.0

Asked 2021-May-06 at 04:05

i am trying to train my data with spacy v3.0 and appareantly the nlp.update do not accept any tuples. Here is the piece of code:

1import spacy
2import random
3import json
4nlp = spacy.blank(&quot;en&quot;)
5ner = nlp.create_pipe(&quot;ner&quot;)
6nlp.add_pipe('ner')
7ner.add_label(&quot;label&quot;)
8# Start the training
9nlp.begin_training()
10# Loop for 40 iterations
11for itn in range(40):
12    # Shuffle the training data
13    random.shuffle(TRAINING_DATA)
14    losses = {}
15# Batch the examples and iterate over them
16    for batch in spacy.util.minibatch(TRAINING_DATA, size=2):
17        texts = [text for text, entities in batch]
18        annotations = [entities for text, entities in batch]
19# Update the model
20        nlp.update(texts, annotations, losses=losses, drop=0.3)
21    print(losses)
22

and i am receiving error

1import spacy
2import random
3import json
4nlp = spacy.blank(&quot;en&quot;)
5ner = nlp.create_pipe(&quot;ner&quot;)
6nlp.add_pipe('ner')
7ner.add_label(&quot;label&quot;)
8# Start the training
9nlp.begin_training()
10# Loop for 40 iterations
11for itn in range(40):
12    # Shuffle the training data
13    random.shuffle(TRAINING_DATA)
14    losses = {}
15# Batch the examples and iterate over them
16    for batch in spacy.util.minibatch(TRAINING_DATA, size=2):
17        texts = [text for text, entities in batch]
18        annotations = [entities for text, entities in batch]
19# Update the model
20        nlp.update(texts, annotations, losses=losses, drop=0.3)
21    print(losses)
22ValueError                                Traceback (most recent call last)
23&lt;ipython-input-79-27d69961629b&gt; in &lt;module&gt;
24     18         annotations = [entities for text, entities in batch]
25     19 # Update the model
26---&gt; 20         nlp.update(texts, annotations, losses=losses, drop=0.3)
27     21     print(losses)
28
29~\Anaconda3\lib\site-packages\spacy\language.py in update(self, examples, _, drop, sgd, losses, component_cfg, exclude)
30   1086         &quot;&quot;&quot;
31   1087         if _ is not None:
32-&gt; 1088             raise ValueError(Errors.E989)
33   1089         if losses is None:
34   1090             losses = {}
35
36ValueError: [E989] `nlp.update()` was called with two positional arguments. This may be due to a backwards-incompatible change to the format of the training data in spaCy 3.0 onwards. The 'update' function should now be called with a batch of Example objects, instead of `(text, annotation)` tuples. 
37

I set my train data format:

1import spacy
2import random
3import json
4nlp = spacy.blank(&quot;en&quot;)
5ner = nlp.create_pipe(&quot;ner&quot;)
6nlp.add_pipe('ner')
7ner.add_label(&quot;label&quot;)
8# Start the training
9nlp.begin_training()
10# Loop for 40 iterations
11for itn in range(40):
12    # Shuffle the training data
13    random.shuffle(TRAINING_DATA)
14    losses = {}
15# Batch the examples and iterate over them
16    for batch in spacy.util.minibatch(TRAINING_DATA, size=2):
17        texts = [text for text, entities in batch]
18        annotations = [entities for text, entities in batch]
19# Update the model
20        nlp.update(texts, annotations, losses=losses, drop=0.3)
21    print(losses)
22ValueError                                Traceback (most recent call last)
23&lt;ipython-input-79-27d69961629b&gt; in &lt;module&gt;
24     18         annotations = [entities for text, entities in batch]
25     19 # Update the model
26---&gt; 20         nlp.update(texts, annotations, losses=losses, drop=0.3)
27     21     print(losses)
28
29~\Anaconda3\lib\site-packages\spacy\language.py in update(self, examples, _, drop, sgd, losses, component_cfg, exclude)
30   1086         &quot;&quot;&quot;
31   1087         if _ is not None:
32-&gt; 1088             raise ValueError(Errors.E989)
33   1089         if losses is None:
34   1090             losses = {}
35
36ValueError: [E989] `nlp.update()` was called with two positional arguments. This may be due to a backwards-incompatible change to the format of the training data in spaCy 3.0 onwards. The 'update' function should now be called with a batch of Example objects, instead of `(text, annotation)` tuples. 
37TRAINING_DATA = []
38for entry in labeled_data:
39    entities = []
40    for e in entry['labels']:
41        entities.append((e[0], e[1],e[2]))
42    spacy_entry = (entry['text'], {&quot;entities&quot;: entities})
43    TRAINING_DATA.append(spacy_entry)
44

My train data looks like this:

1import spacy
2import random
3import json
4nlp = spacy.blank(&quot;en&quot;)
5ner = nlp.create_pipe(&quot;ner&quot;)
6nlp.add_pipe('ner')
7ner.add_label(&quot;label&quot;)
8# Start the training
9nlp.begin_training()
10# Loop for 40 iterations
11for itn in range(40):
12    # Shuffle the training data
13    random.shuffle(TRAINING_DATA)
14    losses = {}
15# Batch the examples and iterate over them
16    for batch in spacy.util.minibatch(TRAINING_DATA, size=2):
17        texts = [text for text, entities in batch]
18        annotations = [entities for text, entities in batch]
19# Update the model
20        nlp.update(texts, annotations, losses=losses, drop=0.3)
21    print(losses)
22ValueError                                Traceback (most recent call last)
23&lt;ipython-input-79-27d69961629b&gt; in &lt;module&gt;
24     18         annotations = [entities for text, entities in batch]
25     19 # Update the model
26---&gt; 20         nlp.update(texts, annotations, losses=losses, drop=0.3)
27     21     print(losses)
28
29~\Anaconda3\lib\site-packages\spacy\language.py in update(self, examples, _, drop, sgd, losses, component_cfg, exclude)
30   1086         &quot;&quot;&quot;
31   1087         if _ is not None:
32-&gt; 1088             raise ValueError(Errors.E989)
33   1089         if losses is None:
34   1090             losses = {}
35
36ValueError: [E989] `nlp.update()` was called with two positional arguments. This may be due to a backwards-incompatible change to the format of the training data in spaCy 3.0 onwards. The 'update' function should now be called with a batch of Example objects, instead of `(text, annotation)` tuples. 
37TRAINING_DATA = []
38for entry in labeled_data:
39    entities = []
40    for e in entry['labels']:
41        entities.append((e[0], e[1],e[2]))
42    spacy_entry = (entry['text'], {&quot;entities&quot;: entities})
43    TRAINING_DATA.append(spacy_entry)
44[('Part List', {'entities': []}), ('pending', {'entities': []}), ('3D Printing', {'entities': [(0, 11, 'Process')]}), ('Recommended to use a FDM 3D printer with PLA material.', {'entities': [(25, 36, 'Process'), (41, 44, 'Material')]}), ('', {'entities': []}), ('No need supports or rafts.', {'entities': []}), ('Resolution: 0.20mm', {'entities': []}), ('Fill density 20%', {'entities': []}), ('As follows from the analysis, part of the project is devoted to 3D', {'entities': [(64, 66, 'Process')]}), ('printing, as all static components were created using 3D modelling and', {'entities': [(54, 66, 'Process')]}), ('subsequent printing.', {'entities': []}), ('', {'entities': []}), ('In our project, we created several versions of the', {'entities': []}), ('model during modelling, which we will describe and document in the', {'entities': []}), ('following subchapters. As a tool for 3D modelling, we used the Sketchup', {'entities': [(37, 49, 'Process')]}), ('Make tool, version from 2017. The main reason was the high degree of', {'entities': []}), ('intuitiveness and simplicity of the tool, as we had not encountered 3D', {'entities': [(68, 70, 'Process')]}), ('modelling before and needed a relatively flexible and efficient tool to', {'entities': []}), ('guarantee the desired result. with zero previous experience.', {'entities': []}), ('In this version, which is shown in the figures Figure 13 - Version no. 2 side view and Figure 24 - Version no. 2 - front view, for the first time, the specific dimensions of the infuser were clarified and', {'entities': []}), ('modelled. The details of the lower servo attachment, the cable hole in', {'entities': []}), ('the main mast, the winding cylinder mounting, the protrusion on the', {'entities': [(36, 44, 'Process')]}), ('winding cylinder for holding the tea bag, the preparation for fitting', {'entities': []}), ('the wooden and aluminium plate and the shape of the cylinder end that', {'entities': [(15, 25, 'Material')]}), ('exactly fit the servo were also reworked.', {'entities': []}), ('After the creation of this', {'entities': []}), ('version of the model, this model was subsequently officially consulted', {'entities': []}), ('and commented on for the first time.', {'entities': []}), ('In this version, which is shown in the figures Figure 13 - Version no. 2 side view and Figure 24 - Version no. 2 - front view, for the first time, the specific dimensions of the infuser were clarified and', {'entities': []}), ('modelled. The details of the lower servo attachment, the cable hole in', {'entities': []}), ('the main mast, the winding cylinder mounting, the protrusion on the', {'entities': [(36, 44, 'Process')]})]
45

I would appreciate your help as a new contributor. Thanks a lot!

ANSWER

Answered 2021-May-06 at 04:05

You didn't provide your TRAIN_DATA, so I cannot reproduce it. However, you should try something like this:

1import spacy
2import random
3import json
4nlp = spacy.blank(&quot;en&quot;)
5ner = nlp.create_pipe(&quot;ner&quot;)
6nlp.add_pipe('ner')
7ner.add_label(&quot;label&quot;)
8# Start the training
9nlp.begin_training()
10# Loop for 40 iterations
11for itn in range(40):
12    # Shuffle the training data
13    random.shuffle(TRAINING_DATA)
14    losses = {}
15# Batch the examples and iterate over them
16    for batch in spacy.util.minibatch(TRAINING_DATA, size=2):
17        texts = [text for text, entities in batch]
18        annotations = [entities for text, entities in batch]
19# Update the model
20        nlp.update(texts, annotations, losses=losses, drop=0.3)
21    print(losses)
22ValueError                                Traceback (most recent call last)
23&lt;ipython-input-79-27d69961629b&gt; in &lt;module&gt;
24     18         annotations = [entities for text, entities in batch]
25     19 # Update the model
26---&gt; 20         nlp.update(texts, annotations, losses=losses, drop=0.3)
27     21     print(losses)
28
29~\Anaconda3\lib\site-packages\spacy\language.py in update(self, examples, _, drop, sgd, losses, component_cfg, exclude)
30   1086         &quot;&quot;&quot;
31   1087         if _ is not None:
32-&gt; 1088             raise ValueError(Errors.E989)
33   1089         if losses is None:
34   1090             losses = {}
35
36ValueError: [E989] `nlp.update()` was called with two positional arguments. This may be due to a backwards-incompatible change to the format of the training data in spaCy 3.0 onwards. The 'update' function should now be called with a batch of Example objects, instead of `(text, annotation)` tuples. 
37TRAINING_DATA = []
38for entry in labeled_data:
39    entities = []
40    for e in entry['labels']:
41        entities.append((e[0], e[1],e[2]))
42    spacy_entry = (entry['text'], {&quot;entities&quot;: entities})
43    TRAINING_DATA.append(spacy_entry)
44[('Part List', {'entities': []}), ('pending', {'entities': []}), ('3D Printing', {'entities': [(0, 11, 'Process')]}), ('Recommended to use a FDM 3D printer with PLA material.', {'entities': [(25, 36, 'Process'), (41, 44, 'Material')]}), ('', {'entities': []}), ('No need supports or rafts.', {'entities': []}), ('Resolution: 0.20mm', {'entities': []}), ('Fill density 20%', {'entities': []}), ('As follows from the analysis, part of the project is devoted to 3D', {'entities': [(64, 66, 'Process')]}), ('printing, as all static components were created using 3D modelling and', {'entities': [(54, 66, 'Process')]}), ('subsequent printing.', {'entities': []}), ('', {'entities': []}), ('In our project, we created several versions of the', {'entities': []}), ('model during modelling, which we will describe and document in the', {'entities': []}), ('following subchapters. As a tool for 3D modelling, we used the Sketchup', {'entities': [(37, 49, 'Process')]}), ('Make tool, version from 2017. The main reason was the high degree of', {'entities': []}), ('intuitiveness and simplicity of the tool, as we had not encountered 3D', {'entities': [(68, 70, 'Process')]}), ('modelling before and needed a relatively flexible and efficient tool to', {'entities': []}), ('guarantee the desired result. with zero previous experience.', {'entities': []}), ('In this version, which is shown in the figures Figure 13 - Version no. 2 side view and Figure 24 - Version no. 2 - front view, for the first time, the specific dimensions of the infuser were clarified and', {'entities': []}), ('modelled. The details of the lower servo attachment, the cable hole in', {'entities': []}), ('the main mast, the winding cylinder mounting, the protrusion on the', {'entities': [(36, 44, 'Process')]}), ('winding cylinder for holding the tea bag, the preparation for fitting', {'entities': []}), ('the wooden and aluminium plate and the shape of the cylinder end that', {'entities': [(15, 25, 'Material')]}), ('exactly fit the servo were also reworked.', {'entities': []}), ('After the creation of this', {'entities': []}), ('version of the model, this model was subsequently officially consulted', {'entities': []}), ('and commented on for the first time.', {'entities': []}), ('In this version, which is shown in the figures Figure 13 - Version no. 2 side view and Figure 24 - Version no. 2 - front view, for the first time, the specific dimensions of the infuser were clarified and', {'entities': []}), ('modelled. The details of the lower servo attachment, the cable hole in', {'entities': []}), ('the main mast, the winding cylinder mounting, the protrusion on the', {'entities': [(36, 44, 'Process')]})]
45from spacy.training.example import Example
46
47for batch in spacy.util.minibatch(TRAINING_DATA, size=2):
48    for text, annotations in batch:
49        # create Example
50        doc = nlp.make_doc(text)
51        example = Example.from_dict(doc, annotations)
52        # Update the model
53        nlp.update([example], losses=losses, drop=0.3)
54

Source https://stackoverflow.com/questions/66675261

QUESTION

Laravel whereIn doesn't return all data

Asked 2021-Apr-20 at 09:46

I have following array (created by explode method)

1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2

when I try to match this titles to my database and get id of each of them, I only get id of first item.

1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;]
3

it supposed to return something like this

1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;]
3[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;, &quot;1234...&quot;, &quot;567...]
4

code

1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;]
3[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;, &quot;1234...&quot;, &quot;567...]
4$a = $request-&gt;input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)-&gt;pluck('id');
9return response()-&gt;json($iddss);
10

Any suggestion?

PS: My best guess is that 2nd and 3rd item in my array have spaces and that might be causing the problem "{SPACE IS HERE}3D Architecture" not sure if that's the reason.

Update

I've tried $b = str_replace([',', ' '], ['',''], $a); but all I get now is []

Update 2

By using $b = str_replace(['[', ']', ' '], null, $a); it does remove spaces from my strings but also removes spaces between my titles words so 3D Architecture becomes 3DArchitecture and by that I'm also not able to match the title with my database in $iddss = Tag::whereIn('title', $comingTags)->pluck('id'); because my database title is 3D Architecture and what I'm trying to match with it is 3DArchitecture.

Any suggestion on that?

Update 3
1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;]
3[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;, &quot;1234...&quot;, &quot;567...]
4$a = $request-&gt;input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)-&gt;pluck('id');
9return response()-&gt;json($iddss);
10$a = $request-&gt;input('tags');
11// return 
12&quot;[3D Printing, 3D Architecture, .NET Micro Framework]&quot;
13

.

1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;]
3[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;, &quot;1234...&quot;, &quot;567...]
4$a = $request-&gt;input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)-&gt;pluck('id');
9return response()-&gt;json($iddss);
10$a = $request-&gt;input('tags');
11// return 
12&quot;[3D Printing, 3D Architecture, .NET Micro Framework]&quot;
13$b = str_replace(['[',']'], null, $a);
14// return
15&quot;3D Printing, 3D Architecture, .NET Micro Framework&quot;
16

.

1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;]
3[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;, &quot;1234...&quot;, &quot;567...]
4$a = $request-&gt;input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)-&gt;pluck('id');
9return response()-&gt;json($iddss);
10$a = $request-&gt;input('tags');
11// return 
12&quot;[3D Printing, 3D Architecture, .NET Micro Framework]&quot;
13$b = str_replace(['[',']'], null, $a);
14// return
15&quot;3D Printing, 3D Architecture, .NET Micro Framework&quot;
16$comingTags = explode(',',$b);
17// return
18[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
19

ANSWER

Answered 2021-Apr-20 at 09:46

To get rid of whitespace you can do array_map('trim', $a); (credits)

whereIn expects an array, so this should work

1[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
2[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;]
3[&quot;d21c6805-8780-4726-ba1d-12c9c3a28d0a&quot;, &quot;1234...&quot;, &quot;567...]
4$a = $request-&gt;input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)-&gt;pluck('id');
9return response()-&gt;json($iddss);
10$a = $request-&gt;input('tags');
11// return 
12&quot;[3D Printing, 3D Architecture, .NET Micro Framework]&quot;
13$b = str_replace(['[',']'], null, $a);
14// return
15&quot;3D Printing, 3D Architecture, .NET Micro Framework&quot;
16$comingTags = explode(',',$b);
17// return
18[&quot;3D Printing&quot;,&quot; 3D Architecture&quot;,&quot; .NET Micro Framework&quot;]
19$a = $request-&gt;input('tags');
20$b = str_replace(['[',']'], null, $a);
21$comingTags = array_map('trim', explode(',', $b));
22
23$iddss = Tag::whereIn('title', $comingTags)-&gt;pluck('id');
24
25return response()-&gt;json($iddss);
26

Source https://stackoverflow.com/questions/67175038

QUESTION

Kotlin get ids of selected options

Asked 2021-Apr-20 at 07:51

I have multiple option select and I need to get array of selected options but all I get is latest option selected.

Code

1class PublishActivity : AppCompatActivity() {
2    
3    var selectedTags: List&lt;String&gt;? = null
4
5    override fun onCreate(savedInstanceState: Bundle?) {
6        super.onCreate(savedInstanceState)
7        setContentView(R.layout.activity_publish)
8
9        pTags.setOnClickListener {
10            var tagIds = ArrayList&lt;String&gt;()
11            val tagOptions = ArrayList&lt;String&gt;()
12            for (i in tags) {
13                tagOptions.add(i.title)
14                tagIds.add(i.id)
15            }
16            var checkedItems = ArrayList&lt;Int&gt;()
17            checkedItems.forEach{ index -&gt; tagIds[index + 1] }
18
19            MaterialAlertDialogBuilder(this)
20                .setTitle(resources.getString(R.string.project_tags))
21                .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked -&gt;
22                    if (checked) {
23                        checkedItems.add(which)
24                    } else if (checkedItems.contains(which)) {
25                        checkedItems.remove(Integer.valueOf(which))
26                    }
27                    // Respond to item chosen
28                    pTags.setText(&quot;${checkedItems.size} tags selected&quot;)
29                }
30                .setPositiveButton(resources.getString(R.string.ok)) { dialog, which -&gt;
31                    for (i in checkedItems) {
32                        Log.d(&quot;eeee1&quot;, tagOptions[i])
33                        selectedTags = listOf(tagOptions[i])
34                    }
35                }
36                .setNeutralButton(resources.getString(R.string.clear)) { dialog, which -&gt;
37                    pTags.text = null
38                    pTags.hint = &quot;0 tag selected&quot;
39                    if (checkedItems.size &gt; 0) {
40                        checkedItems.clear()
41                    }
42                }
43                .show()
44        }
45    }
46}
47

Log.d("eeee1", tagOptions[i]) returns such data in logcat

1class PublishActivity : AppCompatActivity() {
2    
3    var selectedTags: List&lt;String&gt;? = null
4
5    override fun onCreate(savedInstanceState: Bundle?) {
6        super.onCreate(savedInstanceState)
7        setContentView(R.layout.activity_publish)
8
9        pTags.setOnClickListener {
10            var tagIds = ArrayList&lt;String&gt;()
11            val tagOptions = ArrayList&lt;String&gt;()
12            for (i in tags) {
13                tagOptions.add(i.title)
14                tagIds.add(i.id)
15            }
16            var checkedItems = ArrayList&lt;Int&gt;()
17            checkedItems.forEach{ index -&gt; tagIds[index + 1] }
18
19            MaterialAlertDialogBuilder(this)
20                .setTitle(resources.getString(R.string.project_tags))
21                .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked -&gt;
22                    if (checked) {
23                        checkedItems.add(which)
24                    } else if (checkedItems.contains(which)) {
25                        checkedItems.remove(Integer.valueOf(which))
26                    }
27                    // Respond to item chosen
28                    pTags.setText(&quot;${checkedItems.size} tags selected&quot;)
29                }
30                .setPositiveButton(resources.getString(R.string.ok)) { dialog, which -&gt;
31                    for (i in checkedItems) {
32                        Log.d(&quot;eeee1&quot;, tagOptions[i])
33                        selectedTags = listOf(tagOptions[i])
34                    }
35                }
36                .setNeutralButton(resources.getString(R.string.clear)) { dialog, which -&gt;
37                    pTags.text = null
38                    pTags.hint = &quot;0 tag selected&quot;
39                    if (checkedItems.size &gt; 0) {
40                        checkedItems.clear()
41                    }
42                }
43                .show()
44        }
45    }
46}
47D/eeee1: 3D Printing
48D/eeee1: 3D Architecture
49D/eeee1: .NET/Mono
50D/eeee1: ActionScript
51

but in my selectedTags I get only D/eeer1: [ActionScript]

It supposed to give me something like this D/eeer1: ["3D Printing", "3D Architecture", ".NET/Mono", "ActionScript"]

PS: what I'm actually look to achieve here is to get id of those selected items instead of their names that's why I have var tagIds = ArrayList<String>() but if that's not possible to achieve as long as it just return array of all names (like sample above) it's fine by me as well.

Any idea?

ANSWER

Answered 2021-Apr-20 at 07:51

The following code sets your variable to a list with a single item. So you just overwrite your variable over and over again

1class PublishActivity : AppCompatActivity() {
2    
3    var selectedTags: List&lt;String&gt;? = null
4
5    override fun onCreate(savedInstanceState: Bundle?) {
6        super.onCreate(savedInstanceState)
7        setContentView(R.layout.activity_publish)
8
9        pTags.setOnClickListener {
10            var tagIds = ArrayList&lt;String&gt;()
11            val tagOptions = ArrayList&lt;String&gt;()
12            for (i in tags) {
13                tagOptions.add(i.title)
14                tagIds.add(i.id)
15            }
16            var checkedItems = ArrayList&lt;Int&gt;()
17            checkedItems.forEach{ index -&gt; tagIds[index + 1] }
18
19            MaterialAlertDialogBuilder(this)
20                .setTitle(resources.getString(R.string.project_tags))
21                .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked -&gt;
22                    if (checked) {
23                        checkedItems.add(which)
24                    } else if (checkedItems.contains(which)) {
25                        checkedItems.remove(Integer.valueOf(which))
26                    }
27                    // Respond to item chosen
28                    pTags.setText(&quot;${checkedItems.size} tags selected&quot;)
29                }
30                .setPositiveButton(resources.getString(R.string.ok)) { dialog, which -&gt;
31                    for (i in checkedItems) {
32                        Log.d(&quot;eeee1&quot;, tagOptions[i])
33                        selectedTags = listOf(tagOptions[i])
34                    }
35                }
36                .setNeutralButton(resources.getString(R.string.clear)) { dialog, which -&gt;
37                    pTags.text = null
38                    pTags.hint = &quot;0 tag selected&quot;
39                    if (checkedItems.size &gt; 0) {
40                        checkedItems.clear()
41                    }
42                }
43                .show()
44        }
45    }
46}
47D/eeee1: 3D Printing
48D/eeee1: 3D Architecture
49D/eeee1: .NET/Mono
50D/eeee1: ActionScript
51selectedTags = listOf(tagOptions[i])
52

you need:

1class PublishActivity : AppCompatActivity() {
2    
3    var selectedTags: List&lt;String&gt;? = null
4
5    override fun onCreate(savedInstanceState: Bundle?) {
6        super.onCreate(savedInstanceState)
7        setContentView(R.layout.activity_publish)
8
9        pTags.setOnClickListener {
10            var tagIds = ArrayList&lt;String&gt;()
11            val tagOptions = ArrayList&lt;String&gt;()
12            for (i in tags) {
13                tagOptions.add(i.title)
14                tagIds.add(i.id)
15            }
16            var checkedItems = ArrayList&lt;Int&gt;()
17            checkedItems.forEach{ index -&gt; tagIds[index + 1] }
18
19            MaterialAlertDialogBuilder(this)
20                .setTitle(resources.getString(R.string.project_tags))
21                .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked -&gt;
22                    if (checked) {
23                        checkedItems.add(which)
24                    } else if (checkedItems.contains(which)) {
25                        checkedItems.remove(Integer.valueOf(which))
26                    }
27                    // Respond to item chosen
28                    pTags.setText(&quot;${checkedItems.size} tags selected&quot;)
29                }
30                .setPositiveButton(resources.getString(R.string.ok)) { dialog, which -&gt;
31                    for (i in checkedItems) {
32                        Log.d(&quot;eeee1&quot;, tagOptions[i])
33                        selectedTags = listOf(tagOptions[i])
34                    }
35                }
36                .setNeutralButton(resources.getString(R.string.clear)) { dialog, which -&gt;
37                    pTags.text = null
38                    pTags.hint = &quot;0 tag selected&quot;
39                    if (checkedItems.size &gt; 0) {
40                        checkedItems.clear()
41                    }
42                }
43                .show()
44        }
45    }
46}
47D/eeee1: 3D Printing
48D/eeee1: 3D Architecture
49D/eeee1: .NET/Mono
50D/eeee1: ActionScript
51selectedTags = listOf(tagOptions[i])
52//Declaration
53var selectedTags: MutableList&lt;String&gt; = mutableListOf()
54
55...
56// In loop
57selectedTags.add(tagOptions[i])
58

You could also do it with a more functional approach:

1class PublishActivity : AppCompatActivity() {
2    
3    var selectedTags: List&lt;String&gt;? = null
4
5    override fun onCreate(savedInstanceState: Bundle?) {
6        super.onCreate(savedInstanceState)
7        setContentView(R.layout.activity_publish)
8
9        pTags.setOnClickListener {
10            var tagIds = ArrayList&lt;String&gt;()
11            val tagOptions = ArrayList&lt;String&gt;()
12            for (i in tags) {
13                tagOptions.add(i.title)
14                tagIds.add(i.id)
15            }
16            var checkedItems = ArrayList&lt;Int&gt;()
17            checkedItems.forEach{ index -&gt; tagIds[index + 1] }
18
19            MaterialAlertDialogBuilder(this)
20                .setTitle(resources.getString(R.string.project_tags))
21                .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked -&gt;
22                    if (checked) {
23                        checkedItems.add(which)
24                    } else if (checkedItems.contains(which)) {
25                        checkedItems.remove(Integer.valueOf(which))
26                    }
27                    // Respond to item chosen
28                    pTags.setText(&quot;${checkedItems.size} tags selected&quot;)
29                }
30                .setPositiveButton(resources.getString(R.string.ok)) { dialog, which -&gt;
31                    for (i in checkedItems) {
32                        Log.d(&quot;eeee1&quot;, tagOptions[i])
33                        selectedTags = listOf(tagOptions[i])
34                    }
35                }
36                .setNeutralButton(resources.getString(R.string.clear)) { dialog, which -&gt;
37                    pTags.text = null
38                    pTags.hint = &quot;0 tag selected&quot;
39                    if (checkedItems.size &gt; 0) {
40                        checkedItems.clear()
41                    }
42                }
43                .show()
44        }
45    }
46}
47D/eeee1: 3D Printing
48D/eeee1: 3D Architecture
49D/eeee1: .NET/Mono
50D/eeee1: ActionScript
51selectedTags = listOf(tagOptions[i])
52//Declaration
53var selectedTags: MutableList&lt;String&gt; = mutableListOf()
54
55...
56// In loop
57selectedTags.add(tagOptions[i])
58//Declaration
59var selectedTags: List&lt;String&gt;? = listOf()
60
61...
62// Skip the loop and use the map function
63.setPositiveButton(resources.getString(R.string.ok)) { dialog, which -&gt;
64    selectedTags = checkedItems.map{ tagOptions[it] }
65}
66

To get the Id's instead of the titles you should just be able to use your tagIds instead of tagOptions. Just make sure that you get your typing right. The selectedTags list needs to be of the same type as tag.id.

Source https://stackoverflow.com/questions/67173758

QUESTION

Getting all the HTML code from a website that is using React

Asked 2021-Apr-05 at 15:45

I'm trying to scrape the Thingiverse website, more specifically the page displaying a "thing", like this one for example. The problem is that when making a get request (using the python urllib or requests package) the response is an empty HTML file containing a lot of header data, some scripts and an empty react-app div:

1&lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:fb=&quot;http://ogp.me/ns/fb#&quot;&gt;
3
4&lt;head&gt;
5    &lt;title&gt;PCB Feet/Standoffs for M3 by scruss - Thingiverse&lt;/title&gt;
6    &lt;meta http-equiv=&quot;Content-type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;
7    &lt;meta charset=&quot;utf-8&quot;&gt;
8    &lt;meta http-equiv=&quot;Content-Language&quot; content=&quot;EN&quot;&gt;
9    &lt;meta http-equiv=&quot;imagetoolbar&quot; content=&quot;no&quot;&gt;
10    &lt;meta name=&quot;keywords&quot;
11        content=&quot;things, digital design, physical objects, rapid prototyping, 3D objects, 3D printing, reprap, fabrication, laser cutter, laser, thingaverse, thingyverse&quot;&gt;
12    &lt;meta name=&quot;abstract&quot; content=&quot;Share your digital designs for physical objects.&quot;&gt;
13    &lt;meta name=&quot;author&quot; content=&quot;Thingiverse.com&quot;&gt;
14    &lt;meta name=&quot;distribution&quot; content=&quot;Global&quot;&gt;
15    &lt;meta name=&quot;revisit-after&quot; content=&quot;1 days&quot;&gt;
16    &lt;meta name=&quot;robots&quot; content=&quot;follow,index&quot;&gt;
17    &lt;meta name=&quot;description&quot;
18        content=&quot;Download files and build them with your 3D printer, laser cutter, or CNC. Thingiverse is a universe of things.&quot;&gt;
19    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, maximum-scale=1&quot;&gt;
20    &lt;meta name=&quot;theme-color&quot; content=&quot;#248bfb&quot;&gt;
21
22    &lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;
23    &lt;meta property=&quot;og:title&quot; content=&quot;PCB Feet/Standoffs for M3 by scruss&quot;&gt;
24    &lt;meta property=&quot;og:description&quot;
25        content=&quot;Basic &amp;quot;I don&amp;#039;t want my protoboard shorting or gouging holes in my desk&amp;quot; feet/standoffs for M3-drilled 1.6 mm thick PCBs.&quot;&gt;
26    &lt;meta property=&quot;og:image&quot; content=&quot;https://cdn.thingiverse.com/assets/d5/9e/0e/1c/f3/featured_preview_pcb_feet.png&quot;&gt;
27    &lt;meta property=&quot;twitter:card&quot; content=&quot;summary&quot;&gt;
28    &lt;meta property=&quot;twitter:site&quot; content=&quot;@thingiverse&quot;&gt;
29    &lt;meta property=&quot;og:url&quot; content=&quot;https://www.thingiverse.com/thing:4796603&quot;&gt;
30    &lt;meta property=&quot;twitter:creator&quot; content=&quot;@scruss&quot;&gt;
31    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;57x57&quot;
32        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-57x57.png&quot;&gt;
33    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;114x114&quot;
34        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-114x114.png&quot;&gt;
35    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;72x72&quot;
36        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-72x72.png&quot;&gt;
37    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;144x144&quot;
38        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-144x144.png&quot;&gt;
39    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;60x60&quot;
40        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-60x60.png&quot;&gt;
41    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;120x120&quot;
42        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-120x120.png&quot;&gt;
43    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;76x76&quot;
44        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-76x76.png&quot;&gt;
45    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;152x152&quot;
46        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-152x152.png&quot;&gt;
47    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-192x192.png&quot;
48        sizes=&quot;192x192&quot;&gt;
49    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-160x160.png&quot;
50        sizes=&quot;160x160&quot;&gt;
51    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-96x96.png&quot;
52        sizes=&quot;96x96&quot;&gt;
53    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-16x16.png&quot;
54        sizes=&quot;16x16&quot;&gt;
55    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-32x32.png&quot;
56        sizes=&quot;32x32&quot;&gt;
57    &lt;meta name=&quot;msapplication-TileColor&quot; content=&quot;#ffffff&quot;&gt;
58    &lt;meta name=&quot;msapplication-TileImage&quot; content=&quot;https://cdn.thingiverse.com/site/img/favicons/mstile-144x144.png&quot;&gt;
59
60    &lt;link rel=&quot;alternate&quot; type=&quot;application/rss+xml&quot; title=&quot;Thingiverse - PCB Feet/Standoffs for M3 Comments&quot;
61        href=&quot;https://rss.thingiverse.com/thing:4796603&quot;&gt;
62
63
64    &lt;script type=&quot;text/javascript&quot; src=&quot;https://www.datadoghq-browser-agent.com/datadog-logs-us.js&quot;&gt;&lt;/script&gt;
65    &lt;script&gt;
66        const ddClientToken = &quot;pub24a00142f6aa558abe1827e911e11e58&quot;;
67            const ddEnv = &quot;production&quot;;
68            const ddVersion = &quot;2.11.0&quot;;
69
70            DD_LOGS.init({
71                clientToken: ddClientToken,
72                forwardErrorsToLogs: true,
73                service: &quot;thingiverse-client&quot;,
74                env: ddEnv,
75                version: ddVersion,
76                sampleRate: 20
77            });
78
79            
80            const ddIsTvNext = true;
81            const ddBuildTime = &quot;1617625667&quot;;
82
83            DD_LOGS.addLoggerGlobalContext(&quot;is_thingiverse_next&quot;, ddIsTvNext);
84            DD_LOGS.addLoggerGlobalContext(&quot;build_time&quot;, ddBuildTime);
85    &lt;/script&gt;
86
87    &lt;script&gt;
88        var scripts     = [&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/lib-afbc32d766.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/header-aa33d7b171.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/footer-df22f3acb4.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/things-d4ffa805ef.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/orders-e1ac5a6395.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/gallery-7fc215e644.js&quot;];
89            var stylesheets = [];
90            var build_time  = 1617625667;
91    &lt;/script&gt;
92&lt;/head&gt;
93
94
95&lt;script src=&quot;https://cdn.thingiverse.com/site/js/three.min.bundle.js?1617625667&quot;&gt;&lt;/script&gt;
96&lt;div class=&quot;react-app&quot; id=&quot;react-app&quot;&gt;&lt;/div&gt;
97&lt;script src=&quot;https://cdn.thingiverse.com/site/js/app.bundle.js?1617625667&quot;&gt;&lt;/script&gt;
98&lt;script&gt;
99    (function(w,d,s){w._uptime_rum={};w._uptime_rum.uuid='AVO7-994EF0DD9662F23C';w._uptime_rum.url='https://rum.uptime.com/rum/record-data';s=document.createElement('script');s.async=1;s.src='https://uptime.com/static/rum/compiled/rum.js';d.getElementsByTagName('head')[0].appendChild(s);})(window,document);
100&lt;/script&gt;
101

This unfortunately isn't the HTML you see when inspecting the page in a browser. I'm guessing React inserts its HTML later on, which is why the div is empty. Is there any way of getting around that and receiving the actual HTML code that you can see in the browser?

ANSWER

Answered 2021-Apr-05 at 15:45

You'll need a browser to render the javascript and then extract the rendered HTML. Try selenium. It lets you manage a browser through your python code and interact with web page elements.

Install selenium:

pip install selenium

Then something like this to extract the HTML

1&lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:fb=&quot;http://ogp.me/ns/fb#&quot;&gt;
3
4&lt;head&gt;
5    &lt;title&gt;PCB Feet/Standoffs for M3 by scruss - Thingiverse&lt;/title&gt;
6    &lt;meta http-equiv=&quot;Content-type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;
7    &lt;meta charset=&quot;utf-8&quot;&gt;
8    &lt;meta http-equiv=&quot;Content-Language&quot; content=&quot;EN&quot;&gt;
9    &lt;meta http-equiv=&quot;imagetoolbar&quot; content=&quot;no&quot;&gt;
10    &lt;meta name=&quot;keywords&quot;
11        content=&quot;things, digital design, physical objects, rapid prototyping, 3D objects, 3D printing, reprap, fabrication, laser cutter, laser, thingaverse, thingyverse&quot;&gt;
12    &lt;meta name=&quot;abstract&quot; content=&quot;Share your digital designs for physical objects.&quot;&gt;
13    &lt;meta name=&quot;author&quot; content=&quot;Thingiverse.com&quot;&gt;
14    &lt;meta name=&quot;distribution&quot; content=&quot;Global&quot;&gt;
15    &lt;meta name=&quot;revisit-after&quot; content=&quot;1 days&quot;&gt;
16    &lt;meta name=&quot;robots&quot; content=&quot;follow,index&quot;&gt;
17    &lt;meta name=&quot;description&quot;
18        content=&quot;Download files and build them with your 3D printer, laser cutter, or CNC. Thingiverse is a universe of things.&quot;&gt;
19    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, maximum-scale=1&quot;&gt;
20    &lt;meta name=&quot;theme-color&quot; content=&quot;#248bfb&quot;&gt;
21
22    &lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;
23    &lt;meta property=&quot;og:title&quot; content=&quot;PCB Feet/Standoffs for M3 by scruss&quot;&gt;
24    &lt;meta property=&quot;og:description&quot;
25        content=&quot;Basic &amp;quot;I don&amp;#039;t want my protoboard shorting or gouging holes in my desk&amp;quot; feet/standoffs for M3-drilled 1.6 mm thick PCBs.&quot;&gt;
26    &lt;meta property=&quot;og:image&quot; content=&quot;https://cdn.thingiverse.com/assets/d5/9e/0e/1c/f3/featured_preview_pcb_feet.png&quot;&gt;
27    &lt;meta property=&quot;twitter:card&quot; content=&quot;summary&quot;&gt;
28    &lt;meta property=&quot;twitter:site&quot; content=&quot;@thingiverse&quot;&gt;
29    &lt;meta property=&quot;og:url&quot; content=&quot;https://www.thingiverse.com/thing:4796603&quot;&gt;
30    &lt;meta property=&quot;twitter:creator&quot; content=&quot;@scruss&quot;&gt;
31    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;57x57&quot;
32        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-57x57.png&quot;&gt;
33    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;114x114&quot;
34        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-114x114.png&quot;&gt;
35    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;72x72&quot;
36        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-72x72.png&quot;&gt;
37    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;144x144&quot;
38        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-144x144.png&quot;&gt;
39    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;60x60&quot;
40        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-60x60.png&quot;&gt;
41    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;120x120&quot;
42        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-120x120.png&quot;&gt;
43    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;76x76&quot;
44        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-76x76.png&quot;&gt;
45    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;152x152&quot;
46        href=&quot;https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-152x152.png&quot;&gt;
47    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-192x192.png&quot;
48        sizes=&quot;192x192&quot;&gt;
49    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-160x160.png&quot;
50        sizes=&quot;160x160&quot;&gt;
51    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-96x96.png&quot;
52        sizes=&quot;96x96&quot;&gt;
53    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-16x16.png&quot;
54        sizes=&quot;16x16&quot;&gt;
55    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;https://cdn.thingiverse.com/site/img/favicons/favicon-32x32.png&quot;
56        sizes=&quot;32x32&quot;&gt;
57    &lt;meta name=&quot;msapplication-TileColor&quot; content=&quot;#ffffff&quot;&gt;
58    &lt;meta name=&quot;msapplication-TileImage&quot; content=&quot;https://cdn.thingiverse.com/site/img/favicons/mstile-144x144.png&quot;&gt;
59
60    &lt;link rel=&quot;alternate&quot; type=&quot;application/rss+xml&quot; title=&quot;Thingiverse - PCB Feet/Standoffs for M3 Comments&quot;
61        href=&quot;https://rss.thingiverse.com/thing:4796603&quot;&gt;
62
63
64    &lt;script type=&quot;text/javascript&quot; src=&quot;https://www.datadoghq-browser-agent.com/datadog-logs-us.js&quot;&gt;&lt;/script&gt;
65    &lt;script&gt;
66        const ddClientToken = &quot;pub24a00142f6aa558abe1827e911e11e58&quot;;
67            const ddEnv = &quot;production&quot;;
68            const ddVersion = &quot;2.11.0&quot;;
69
70            DD_LOGS.init({
71                clientToken: ddClientToken,
72                forwardErrorsToLogs: true,
73                service: &quot;thingiverse-client&quot;,
74                env: ddEnv,
75                version: ddVersion,
76                sampleRate: 20
77            });
78
79            
80            const ddIsTvNext = true;
81            const ddBuildTime = &quot;1617625667&quot;;
82
83            DD_LOGS.addLoggerGlobalContext(&quot;is_thingiverse_next&quot;, ddIsTvNext);
84            DD_LOGS.addLoggerGlobalContext(&quot;build_time&quot;, ddBuildTime);
85    &lt;/script&gt;
86
87    &lt;script&gt;
88        var scripts     = [&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/lib-afbc32d766.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/header-aa33d7b171.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/footer-df22f3acb4.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/things-d4ffa805ef.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/orders-e1ac5a6395.js&quot;,&quot;https://cdn.thingiverse.com/site/js/thingiverse/build/gallery-7fc215e644.js&quot;];
89            var stylesheets = [];
90            var build_time  = 1617625667;
91    &lt;/script&gt;
92&lt;/head&gt;
93
94
95&lt;script src=&quot;https://cdn.thingiverse.com/site/js/three.min.bundle.js?1617625667&quot;&gt;&lt;/script&gt;
96&lt;div class=&quot;react-app&quot; id=&quot;react-app&quot;&gt;&lt;/div&gt;
97&lt;script src=&quot;https://cdn.thingiverse.com/site/js/app.bundle.js?1617625667&quot;&gt;&lt;/script&gt;
98&lt;script&gt;
99    (function(w,d,s){w._uptime_rum={};w._uptime_rum.uuid='AVO7-994EF0DD9662F23C';w._uptime_rum.url='https://rum.uptime.com/rum/record-data';s=document.createElement('script');s.async=1;s.src='https://uptime.com/static/rum/compiled/rum.js';d.getElementsByTagName('head')[0].appendChild(s);})(window,document);
100&lt;/script&gt;
101from selenium import webdriver
102driver = webdriver.Chrome('./chromedriver') # Downloaad the chrome driver and replace this path
103driver.get(&quot;your_url&quot;)
104# Wait for some element to be rendered or just a blind sleep
105print(driver.page_source) # This'll give you the full rendered HTML
106driver.close()
107

Source https://stackoverflow.com/questions/66955402

QUESTION

Python matching various keyword from dictionary issues

Asked 2021-Mar-14 at 14:50

I have a complex text where I am categorizing different keywords stored in a dictionary:

1    text = 'data-ls-static=&quot;1&quot;&gt;Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE&lt;/h3&gt;'
2
3    sector = {&quot;med tech&quot;: ['Drug Delivery' '3D printing', 'medicine', 'medical technology', 'bio cell']}
4

this can successfully find my keywords and categorize them with some limitations:

1    text = 'data-ls-static=&quot;1&quot;&gt;Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE&lt;/h3&gt;'
2
3    sector = {&quot;med tech&quot;: ['Drug Delivery' '3D printing', 'medicine', 'medical technology', 'bio cell']}
4    pattern = r'[a-zA-Z0-9]+'
5
6    [cat for cat in sector if any(x in re.findall(pattern,text) for x in sector[cat])]
7

The limitations that I cannot solve are:

  1. For example, keywords like "Drug Delivery" that are separated by a space are not recognized and therefore categorized.

  2. I was not able to make the pattern case insensitive, as words like MEDICINE are not recognized. I tried to add (?i) to the pattern but it doesn't work.

  3. The categorized keywords go into a pandas df, but they are printed into []. I tried to loop again the script to take them out but they are still there.

Data to pandas df:

1    text = 'data-ls-static=&quot;1&quot;&gt;Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE&lt;/h3&gt;'
2
3    sector = {&quot;med tech&quot;: ['Drug Delivery' '3D printing', 'medicine', 'medical technology', 'bio cell']}
4    pattern = r'[a-zA-Z0-9]+'
5
6    [cat for cat in sector if any(x in re.findall(pattern,text) for x in sector[cat])]
7    ind_list = []
8    for site in url_list:
9        ind = [cat for cat in indication if any(x in re.findall(pattern,soup_string) for x in indication[cat])]
10        ind_list.append(ind)
11
12    websites['Indication'] = ind_list
13

Current output:

1    text = 'data-ls-static=&quot;1&quot;&gt;Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE&lt;/h3&gt;'
2
3    sector = {&quot;med tech&quot;: ['Drug Delivery' '3D printing', 'medicine', 'medical technology', 'bio cell']}
4    pattern = r'[a-zA-Z0-9]+'
5
6    [cat for cat in sector if any(x in re.findall(pattern,text) for x in sector[cat])]
7    ind_list = []
8    for site in url_list:
9        ind = [cat for cat in indication if any(x in re.findall(pattern,soup_string) for x in indication[cat])]
10        ind_list.append(ind)
11
12    websites['Indication'] = ind_list
13Website                                  Sector                              Sub-sector                                 Therapeutical Area Focus URL status
140     url3.com                              [med tech]                                      []                                                 []          []         []
151     www.url1.com                    [med tech, services]                                      []                       [oncology, gastroenterology]          []         []
162     www.url2.com                    [med tech, services]                                      []                                        [orthopedy]          []         []
17

In the output I get [] that I'd like to avoid.

Can you help me with these points?

Thanks!

ANSWER

Answered 2021-Mar-13 at 14:16

findall is pretty wasteful here since you are repeatedly breaking up the string for each keyword.

If you want to test whether the keyword is in the string:

1    text = 'data-ls-static=&quot;1&quot;&gt;Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE&lt;/h3&gt;'
2
3    sector = {&quot;med tech&quot;: ['Drug Delivery' '3D printing', 'medicine', 'medical technology', 'bio cell']}
4    pattern = r'[a-zA-Z0-9]+'
5
6    [cat for cat in sector if any(x in re.findall(pattern,text) for x in sector[cat])]
7    ind_list = []
8    for site in url_list:
9        ind = [cat for cat in indication if any(x in re.findall(pattern,soup_string) for x in indication[cat])]
10        ind_list.append(ind)
11
12    websites['Indication'] = ind_list
13Website                                  Sector                              Sub-sector                                 Therapeutical Area Focus URL status
140     url3.com                              [med tech]                                      []                                                 []          []         []
151     www.url1.com                    [med tech, services]                                      []                       [oncology, gastroenterology]          []         []
162     www.url2.com                    [med tech, services]                                      []                                        [orthopedy]          []         []
17[cat for cat in sector if any(re.search(word, text, re.I) for word in sector[cat])]
18# Output: med tech
19

Source https://stackoverflow.com/questions/66613710

QUESTION

How to create a Postman server mock for uploading file and doing some uploading test of Flutter code?

Asked 2020-Nov-04 at 12:14

I'm trying to connect to a printer server to be able to save the printing files directly in the printer storage. I'm able to do it using the curl curl -v -H 'Content-Type:application/octet-stream' 'http://192.168.1.125/upload?X-Filename=model.gcode' --data-binary @model.gcode Now I'm trying to add this function to a Flutter app but don't works.... So now I am trying to debug the code using a postman server. Can you help me to create a postman server mock to upload the file as binary, like in this curl code?

1curl -v -H 'Content-Type:application/octet-stream' 'http://192.168.1.125/upload?X-Filename=model.gcode' --data-binary @model.gcode
2

I want to create it because I want to test this Flutter code witch isn't working in the server of the printer.

FLUTTER CODE:

1curl -v -H 'Content-Type:application/octet-stream' 'http://192.168.1.125/upload?X-Filename=model.gcode' --data-binary @model.gcode
2  Future&lt;void&gt; uploadFile(File file) async {
3///Using HTTP Package
4 Map&lt;String, String&gt; headers = {
5  &quot;Content-type&quot;: &quot;application/octet-stream&quot;,
6};
7var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
8var length = await file.length();
9var uri = Uri.parse(&quot;http://192.168.1.125/upload?X-Filename=nupo.gcode&quot;);
10
11var request = new http.MultipartRequest(&quot;POST&quot;, uri);
12var multipartFile = new http.MultipartFile('application', stream, length,
13    filename: file.path);
14request.headers.addAll(headers);
15request.files.add(multipartFile);
16var response = await request.send();
17print(response.statusCode);
18response.stream.transform(utf8.decoder).listen((value) {
19  print(value);
20});
21}
22

The server should be able to receive binary file and the command should be upload?X-Filename=filename.gcode, X-Filename is the command to give the name.

(this files are 3D printing files so .gcode is the enstention of motor command)

ANSWER

Answered 2020-Nov-04 at 12:14

Postman is not a server usable for this scope. You can use it only for testing an existing server. Best practice with postman or visiti [POstman support][1]

Source https://stackoverflow.com/questions/64248169

QUESTION

Is there a name for this 3D printing effect?

Asked 2020-Sep-25 at 15:21

I'm relatively new to 3D printing, but I've taken to it with much gusto. I wish I'd done this years ago.

Trying to solve a printing problem, and I've been stymied by not knowing the name for the effect I'm seeing - there is zero chance I'm the first one to discover this.

A minimum reproducible example is a triplet of vertical cylinders on a raft, it's clear that the tool path starts at one spot, runs a full circle around to end in that same spot, and it lingers long enough to extrude just a tiny bit more material that builds up in a vertical line.

What's that vertical line called?

This matches exactly the tool path shown in the slicer and this effect is repeatable no matter how many parameters I changed. I've done many dozens of test prints and am not getting anywhere.

These are 16mm across and are used as inserts into a tray holding vials to shim a narrower diameter tube, and the bump is enough to matter. I have to make thousands of these and am hoping not to have to file them all down by hand.

If it matters, I'm using a Sindoh 3DWOX 2D and a 3DWOX 1 with PLA filament.

  1. Is there a name for this effect?
  2. Are there mitigations?

I'm starting to rethink this whole approach...

ANSWER

Answered 2020-Sep-25 at 15:21

I was happy to find my own answer elsewhere.

First, that effect is known as a "seam", and one mitigation is known as "vase mode" (known in some slicers as "Spiralise Outer Contour"), which builds the cylinder in a continuous spiral from the bottom up with no seam. It can create really nice aesthetically-pleasing prints.

However, vase mode only works for a single model because stopping (and possibly retracting) to print a second model breaks the whole continuous-spiral thing.

So, if I had only a few of these to print, I'd do them one at a time, but given that I need thousands of them, I've found other approaches to solving the problem.

Source https://stackoverflow.com/questions/64033351

QUESTION

Python Nested Dictionaries Retrieve Key from nested value

Asked 2020-Jun-14 at 05:55

I have a Python dictionary with dictionaries nested heavily within. There are several tiers.

What I am trying to accomplish is a function where I can enter any one of the "subcategories" values, for example, 20003482 or 200000879 and it has to return the first nested subcategory key, so for the above examples, 100003109

I am unsure about the best way to go about this, but I've tried something like

1        group = [k for k, v in category_groups.items() if c1 in v][0]
2

and that only seems to work for the first tier of nesting

is there a general recursive solution here? whats the best way to go about this

1        group = [k for k, v in category_groups.items() if c1 in v][0]
2cat_list = {
3  1: {
4    'name': 'Clothing &amp; Accessories',
5    'subcategories': {
6      100003109: {
7        'name': "Women's Clothing",
8        'image': '/images/vectors/niche/womens.jpg',
9        'description': 'Womens Dresses, Blouses, Hoodies, Sweaters, Jackets, Leggings &amp; Much More',
10        'winning': True,
11        'subcategories': {
12          200003482: {
13            'winning': False,
14            'name': 'Dresses',
15            'subcategories': {}
16          },
17          200001648: {
18            'winning': False,
19            'name': 'Blouses &amp; Shirts',
20            'subcategories': {}
21          },
22          100003141: {
23            'winning': False,
24            'name': 'Hoodies &amp; Sweatshirts',
25            'subcategories': {}
26          },
27          200000783: {
28            'name': 'Sweaters',
29            'winning': True,
30            'subcategories': {
31              200000879: {
32                'name': 'Pullovers'
33              },
34              200000877: {
35                'name': 'Cardigans'
36              },
37              200000882: {
38                'name': 'Vests'
39              },
40              200000881: {
41                'name': 'Shrugs'
42              },
43              200217993: {
44                'name': 'Cloak'
45              }
46            }
47          },
48        }
49      },
50      100003070: {
51        'name': "Men's Clothing",
52        'image': '/images/vectors/niche/mens.jpg',
53        'description': 'Mens Hoodies, T-Shirts, Jackets, Jeans, Suits &amp; Much More',
54        'winning': False,
55        'subcategories': {
56          100003084: {
57            'winning': True,
58            'name': 'Hoodies &amp; Sweatshirts',
59            'subcategories': {}
60          },
61          200000707: {
62            'name': 'Tops &amp; T-Shirts',
63            'winning': False,
64            'subcategories': {
65              200000717: {
66                'name': 'Tank Tops'
67              },
68              200010062: {
69                'name': 'Polo Shirts'
70              },
71              100003071: {
72                'name': 'T-Shirts'
73              }
74            }
75          },
76        }
77      },
78  },
79  2: {
80    'name': 'Electronics',
81    'subcategories': {
82      509: {
83        'name': 'Phones',
84        'image': '/images/vectors/niche/mobile.jpg',
85        'description': 'iPhone &amp; Android Accessories, Cases, Chargers',
86        'winning': False,
87        'subcategories': {
88          200084017: {
89            'winning': False,
90            'name': 'Mobile Phone Accessories',
91            'subcategories': {
92              200003189: {
93                'name': 'Mobile Phone Lenses'
94              },
95              200003130: {
96                'name': 'Armbands'
97              },
98              200003132: {
99                'name': 'Power Bank'
100              },
101              200003089: {
102                'name': 'Phone Screen Protectors'
103              },
104              200217751: {
105                'name': 'Wireless Chargers'
106              },
107              200217746: {
108                'name': 'Car Chargers'
109              },
110              100003569: {
111                'name': 'Mobile Phone Cables'
112              },
113              100003571: {
114                'name': 'Mobile Phone Chargers'
115              },
116              5093005: {
117                'name': 'Mobile Phone Straps'
118              },
119              5093004: {
120                'name': 'Mobile Phone Holders &amp; Stands'
121              },
122              5093006: {
123                'name': 'Mobile Phone Adapters'
124              },
125              5093001: {
126                'name': 'Mobile Phone Stickers'
127              }
128            }
129          },
130          200216959: {
131            'winning': False,
132            'name': 'Phone Bags &amp; Cases',
133            'subcategories': {
134              200215191: {
135                'name': 'Battery Charger Cases'
136              },
137              200216972: {
138                'name': 'Wallet Cases'
139              },
140              200216991: {
141                'name': 'Phone Bumper Cases'
142              },
143              200216981: {
144                'name': 'Fitted Cases'
145              },
146              200216980: {
147                'name': 'Phone Pouches'
148              },
149              200216978: {
150                'name': 'Rhinestone Cases'
151              },
152              200216977: {
153                'name': 'Flip Cases'
154              },
155              200217991: {
156                'name': 'Slim Cases'
157              }
158            }
159          }
160        }
161      },
162      7: {
163        'name': 'Computers',
164        'image': '/images/vectors/niche/computer.jpg',
165        'description': 'Tablet &amp; Office Gadgets, 3D Printing Pens, Computer Peripherals &amp; Cleaners. Laptop Accessories.',
166        'winning': False,
167        'subcategories': {
168          200004720: {
169            'winning': True,
170            'name': 'Office Electronics',
171            'subcategories': {
172              2107: {
173                'name': 'Projectors'
174              },
175              200138005: {
176                'name': '3D Pens'
177              },
178              200042003: {
179                'name': '3D Printers'
180              },
181              200140003: {
182                'name': '3D Printing Materials'
183              }
184            }
185          },
186          200002361: {
187            'winning': False,
188            'name': 'Tablet Accessories',
189            'subcategories': {
190              200002368: {
191                'name': 'Tablet Touch Pens'
192              },
193              200002365: {
194                'name': 'Tablet Stickers'
195              },
196              200002364: {
197                'name': 'Tablet Cases'
198              },
199              200002624: {
200                'name': 'Tablet Stands'
201              },
202              200003724: {
203                'name': 'Tablet Screen Protectors'
204              }
205            }
206          },
207          200002342: {
208            'winning': False,
209            'name': 'Computer Peripherals',
210            'subcategories': {
211              708024: {
212                'name': 'Keyboard &amp; Mouse Sets'
213              },
214              708023: {
215                'name': 'Mouse Pads'
216              },
217              708032: {
218                'name': 'USB Docks &amp; Hubs'
219              },
220              70802: {
221                'name': 'Keyboards'
222              },
223              70805: {
224                'name': 'Mice'
225              },
226              7171: {
227                'name': 'USB Gadgets'
228              }
229            }
230          },
231          708022: {
232            'winning': False,
233            'name': 'Computer Cleaners',
234            'subcategories': {}
235          },
236          100005063: {
237            'winning': True,
238            'name': 'Laptop Accessories',
239            'subcategories': {
240              200002360: {
241                'name': 'Laptop Desks'
242              },
243              721: {
244                'name': 'Laptop Cooling Pads'
245              },
246              380110: {
247                'name': 'Laptop Bags &amp; Cases'
248              },
249              708031: {
250                'name': 'Laptop Skins &amp; Stickers'
251              },
252              708021: {
253                'name': 'Keyboard Covers'
254              },
255              200216761: {
256                'name': 'Laptop Stand'
257              }
258            }
259          }
260        }
261      },
262      44: {
263        'name': 'Gadgets',
264        'image': '/images/vectors/niche/electronics.jpg',
265        'description': 'Camera Accessories &amp; Lighting, Selfie Sticks, Earphones &amp; Headphones, Smart Watches, E-Cigs &amp; Vapes, Gaming Accessories, Speakers &amp; Solar Gadgets',
266        'winning': False,
267        'subcategories': {
268          200002395: {
269            'winning': True,
270            'name': 'Camera &amp; Photo',
271            'subcategories': {
272              200002411: {
273                'name': 'Photographic Lighting'
274              },
275              200002408: {
276                'name': 'Tripod &amp; Accessories'
277              },
278              200002413: {
279                'name': 'Mini Camcorders'
280              },
281              200216548: {
282                'name': 'Tabletop Shooting'
283              },
284              1901: {
285                'name': 'Film Camera'
286              },
287              1903: {
288                'name': 'Camera &amp; Photo Accessories'
289              },
290              200216669: {
291                'name': 'Selfie Sticks'
292              },
293              200216611: {
294                'name': 'Flashes &amp; Accessories'
295              }
296            }
297          },
298          200002398: {
299            'winning': True,
300            'name': 'Portable Audio &amp; Video',
301            'subcategories': {
302              200003109: {
303                'name': 'Earphone Accessories'
304              },
305              200217778: {
306                'name': 'Translator'
307              },
308              63705: {
309                'name': 'Earphones &amp; Headphones'
310              },
311              63708: {
312                'name': 'Microphones'
313              }
314            }
315          },
316          200010196: {
317            'winning': True,
318            'name': 'Smart Electronics',
319            'subcategories': {
320              200086023: {
321                'name': 'Smart Home Electronics'
322              },
323              200010206: {
324                'name': 'Smart Watches'
325              }
326            }
327          },
328          200002394: {
329            'winning': False,
330            'name': 'Accessories &amp; Parts',
331            'subcategories': {
332              200084029: {
333                'name': 'Smart Power Sockets &amp; Plugs'
334              },
335              200003200: {
336                'name': 'Tech Cables &amp; Accessories'
337              },
338              200003127: {
339                'name': 'Cable Winders &amp; Protectors'
340              },
341              380210: {
342                'name': 'Camera/Video Bags'
343              }
344            }
345          },
346          200005280: {
347            'winning': False,
348            'name': 'Electronic Cigarettes &amp; Vapes',
349            'subcategories': {
350              200005289: {
351                'name': 'Electronic Cigarette Mods'
352              },
353              200005288: {
354                'name': 'Elctronic Cigarette Chargers'
355              },
356              200005282: {
357                'name': 'Electronic Cigarette Accessories'
358              },
359              200005281: {
360                'name': 'Electronic Cigarette Kits'
361              },
362              200005287: {
363                'name': 'Electronic Cigarette Batteries'
364              },
365              200005285: {
366                'name': 'Electronic Cigarette Atomizers'
367              },
368              200005284: {
369                'name': 'Eletronic Cigarette Atomizer Cores'
370              }
371            }
372          },
373          200002396: {
374            'winning': False,
375            'name': 'Video Games',
376            'subcategories': {
377              200215241: {
378                'name': 'Stands'
379              },
380              200215236: {
381                'name': 'Screen Protectors'
382              },
383              200215208: {
384                'name': 'Joysticks'
385              },
386              200215202: {
387                'name': 'Cases'
388              },
389              200215201: {
390                'name': 'Bags'
391              },
392              200215228: {
393                'name': 'Handheld Game Players'
394              },
395              200215227: {
396                'name': 'Gamepads'
397              },
398              200215197: {
399                'name': 'Chargers'
400              },
401              200004542: {
402                'name': 'Video Games Wheels'
403              }
404            }
405          },
406          200216623: {
407            'winning': True,
408            'name': 'Earphones &amp; Headphones',
409            'subcategories': {
410              200216686: {
411                'name': 'Earphones'
412              },
413              200216605: {
414                'name': 'Headphone/Headset'
415              },
416              200216593: {
417                'name': 'Bluetooth Earphones &amp; Headphones'
418              }
419            }
420          },
421          200084019: {
422            'winning': True,
423            'name': 'Wearable Devices',
424            'subcategories': {
425              200010211: {
426                'name': 'Smart Accessories'
427              },
428              200010209: {
429                'name': 'Smart Activity Trackers'
430              },
431              200010207: {
432                'name': 'Smart Wristbands'
433              },
434              200010206: {
435                'name': 'Smart Watches'
436              }
437            }
438          },
439          200215272: {
440            'winning': False,
441            'name': 'VR/AR Devices',
442            'subcategories': {
443              100007533: {
444                'name': '3D Glasses/ Virtual Reality Glasses'
445              }
446            }
447          },
448          200216592: {
449            'winning': False,
450            'name': '360° Video Cameras &amp; Accessories',
451            'subcategories': {
452              200215271: {
453                'name': '360° Video Camera'
454              }
455            }
456          },
457          200217534: {
458            'winning': False,
459            'name': 'Speakers',
460            'subcategories': {
461              518: {
462                'name': 'Portable Speakers'
463              },
464              200217564: {
465                'name': 'Subwoofer'
466              },
467              200217561: {
468                'name': 'Soundbar'
469              }
470            }
471          },
472          200218547: {
473            'winning': False,
474            'name': 'Solar Gadgets',
475            'subcategories': {
476              200218548: {
477                'name': 'Solar'
478              }
479            }
480          }
481        }
482      }
483    }
484  },
485  }
486}
487

In terms of examples, here is what should happen:

Entering 10003109, 200003482 or 200000879 should result in the value of the key 10003109.

Entering 100003070, 100003084 or 200000717 should result in the value of the key 100003070

Entering 509, 200084017 or 200215241 should result in the value of the key 509

ANSWER

Answered 2020-Jun-11 at 23:54

There could be 2 different solutions. The simpler one would be here you know that the subcategories are at a fixed depth, in this case

1        group = [k for k, v in category_groups.items() if c1 in v][0]
2cat_list = {
3  1: {
4    'name': 'Clothing &amp; Accessories',
5    'subcategories': {
6      100003109: {
7        'name': "Women's Clothing",
8        'image': '/images/vectors/niche/womens.jpg',
9        'description': 'Womens Dresses, Blouses, Hoodies, Sweaters, Jackets, Leggings &amp; Much More',
10        'winning': True,
11        'subcategories': {
12          200003482: {
13            'winning': False,
14            'name': 'Dresses',
15            'subcategories': {}
16          },
17          200001648: {
18            'winning': False,
19            'name': 'Blouses &amp; Shirts',
20            'subcategories': {}
21          },
22          100003141: {
23            'winning': False,
24            'name': 'Hoodies &amp; Sweatshirts',
25            'subcategories': {}
26          },
27          200000783: {
28            'name': 'Sweaters',
29            'winning': True,
30            'subcategories': {
31              200000879: {
32                'name': 'Pullovers'
33              },
34              200000877: {
35                'name': 'Cardigans'
36              },
37              200000882: {
38                'name': 'Vests'
39              },
40              200000881: {
41                'name': 'Shrugs'
42              },
43              200217993: {
44                'name': 'Cloak'
45              }
46            }
47          },
48        }
49      },
50      100003070: {
51        'name': "Men's Clothing",
52        'image': '/images/vectors/niche/mens.jpg',
53        'description': 'Mens Hoodies, T-Shirts, Jackets, Jeans, Suits &amp; Much More',
54        'winning': False,
55        'subcategories': {
56          100003084: {
57            'winning': True,
58            'name': 'Hoodies &amp; Sweatshirts',
59            'subcategories': {}
60          },
61          200000707: {
62            'name': 'Tops &amp; T-Shirts',
63            'winning': False,
64            'subcategories': {
65              200000717: {
66                'name': 'Tank Tops'
67              },
68              200010062: {
69                'name': 'Polo Shirts'
70              },
71              100003071: {
72                'name': 'T-Shirts'
73              }
74            }
75          },
76        }
77      },
78  },
79  2: {
80    'name': 'Electronics',
81    'subcategories': {
82      509: {
83        'name': 'Phones',
84        'image': '/images/vectors/niche/mobile.jpg',
85        'description': 'iPhone &amp; Android Accessories, Cases, Chargers',
86        'winning': False,
87        'subcategories': {
88          200084017: {
89            'winning': False,
90            'name': 'Mobile Phone Accessories',
91            'subcategories': {
92              200003189: {
93                'name': 'Mobile Phone Lenses'
94              },
95              200003130: {
96                'name': 'Armbands'
97              },
98              200003132: {
99                'name': 'Power Bank'
100              },
101              200003089: {
102                'name': 'Phone Screen Protectors'
103              },
104              200217751: {
105                'name': 'Wireless Chargers'
106              },
107              200217746: {
108                'name': 'Car Chargers'
109              },
110              100003569: {
111                'name': 'Mobile Phone Cables'
112              },
113              100003571: {
114                'name': 'Mobile Phone Chargers'
115              },
116              5093005: {
117                'name': 'Mobile Phone Straps'
118              },
119              5093004: {
120                'name': 'Mobile Phone Holders &amp; Stands'
121              },
122              5093006: {
123                'name': 'Mobile Phone Adapters'
124              },
125              5093001: {
126                'name': 'Mobile Phone Stickers'
127              }
128            }
129          },
130          200216959: {
131            'winning': False,
132            'name': 'Phone Bags &amp; Cases',
133            'subcategories': {
134              200215191: {
135                'name': 'Battery Charger Cases'
136              },
137              200216972: {
138                'name': 'Wallet Cases'
139              },
140              200216991: {
141                'name': 'Phone Bumper Cases'
142              },
143              200216981: {
144                'name': 'Fitted Cases'
145              },
146              200216980: {
147                'name': 'Phone Pouches'
148              },
149              200216978: {
150                'name': 'Rhinestone Cases'
151              },
152              200216977: {
153                'name': 'Flip Cases'
154              },
155              200217991: {
156                'name': 'Slim Cases'
157              }
158            }
159          }
160        }
161      },
162      7: {
163        'name': 'Computers',
164        'image': '/images/vectors/niche/computer.jpg',
165        'description': 'Tablet &amp; Office Gadgets, 3D Printing Pens, Computer Peripherals &amp; Cleaners. Laptop Accessories.',
166        'winning': False,
167        'subcategories': {
168          200004720: {
169            'winning': True,
170            'name': 'Office Electronics',
171            'subcategories': {
172              2107: {
173                'name': 'Projectors'
174              },
175              200138005: {
176                'name': '3D Pens'
177              },
178              200042003: {
179                'name': '3D Printers'
180              },
181              200140003: {
182                'name': '3D Printing Materials'
183              }
184            }
185          },
186          200002361: {
187            'winning': False,
188            'name': 'Tablet Accessories',
189            'subcategories': {
190              200002368: {
191                'name': 'Tablet Touch Pens'
192              },
193              200002365: {
194                'name': 'Tablet Stickers'
195              },
196              200002364: {
197                'name': 'Tablet Cases'
198              },
199              200002624: {
200                'name': 'Tablet Stands'
201              },
202              200003724: {
203                'name': 'Tablet Screen Protectors'
204              }
205            }
206          },
207          200002342: {
208            'winning': False,
209            'name': 'Computer Peripherals',
210            'subcategories': {
211              708024: {
212                'name': 'Keyboard &amp; Mouse Sets'
213              },
214              708023: {
215                'name': 'Mouse Pads'
216              },
217              708032: {
218                'name': 'USB Docks &amp; Hubs'
219              },
220              70802: {
221                'name': 'Keyboards'
222              },
223              70805: {
224                'name': 'Mice'
225              },
226              7171: {
227                'name': 'USB Gadgets'
228              }
229            }
230          },
231          708022: {
232            'winning': False,
233            'name': 'Computer Cleaners',
234            'subcategories': {}
235          },
236          100005063: {
237            'winning': True,
238            'name': 'Laptop Accessories',
239            'subcategories': {
240              200002360: {
241                'name': 'Laptop Desks'
242              },
243              721: {
244                'name': 'Laptop Cooling Pads'
245              },
246              380110: {
247                'name': 'Laptop Bags &amp; Cases'
248              },
249              708031: {
250                'name': 'Laptop Skins &amp; Stickers'
251              },
252              708021: {
253                'name': 'Keyboard Covers'
254              },
255              200216761: {
256                'name': 'Laptop Stand'
257              }
258            }
259          }
260        }
261      },
262      44: {
263        'name': 'Gadgets',
264        'image': '/images/vectors/niche/electronics.jpg',
265        'description': 'Camera Accessories &amp; Lighting, Selfie Sticks, Earphones &amp; Headphones, Smart Watches, E-Cigs &amp; Vapes, Gaming Accessories, Speakers &amp; Solar Gadgets',
266        'winning': False,
267        'subcategories': {
268          200002395: {
269            'winning': True,
270            'name': 'Camera &amp; Photo',
271            'subcategories': {
272              200002411: {
273                'name': 'Photographic Lighting'
274              },
275              200002408: {
276                'name': 'Tripod &amp; Accessories'
277              },
278              200002413: {
279                'name': 'Mini Camcorders'
280              },
281              200216548: {
282                'name': 'Tabletop Shooting'
283              },
284              1901: {
285                'name': 'Film Camera'
286              },
287              1903: {
288                'name': 'Camera &amp; Photo Accessories'
289              },
290              200216669: {
291                'name': 'Selfie Sticks'
292              },
293              200216611: {
294                'name': 'Flashes &amp; Accessories'
295              }
296            }
297          },
298          200002398: {
299            'winning': True,
300            'name': 'Portable Audio &amp; Video',
301            'subcategories': {
302              200003109: {
303                'name': 'Earphone Accessories'
304              },
305              200217778: {
306                'name': 'Translator'
307              },
308              63705: {
309                'name': 'Earphones &amp; Headphones'
310              },
311              63708: {
312                'name': 'Microphones'
313              }
314            }
315          },
316          200010196: {
317            'winning': True,
318            'name': 'Smart Electronics',
319            'subcategories': {
320              200086023: {
321                'name': 'Smart Home Electronics'
322              },
323              200010206: {
324                'name': 'Smart Watches'
325              }
326            }
327          },
328          200002394: {
329            'winning': False,
330            'name': 'Accessories &amp; Parts',
331            'subcategories': {
332              200084029: {
333                'name': 'Smart Power Sockets &amp; Plugs'
334              },
335              200003200: {
336                'name': 'Tech Cables &amp; Accessories'
337              },
338              200003127: {
339                'name': 'Cable Winders &amp; Protectors'
340              },
341              380210: {
342                'name': 'Camera/Video Bags'
343              }
344            }
345          },
346          200005280: {
347            'winning': False,
348            'name': 'Electronic Cigarettes &amp; Vapes',
349            'subcategories': {
350              200005289: {
351                'name': 'Electronic Cigarette Mods'
352              },
353              200005288: {
354                'name': 'Elctronic Cigarette Chargers'
355              },
356              200005282: {
357                'name': 'Electronic Cigarette Accessories'
358              },
359              200005281: {
360                'name': 'Electronic Cigarette Kits'
361              },
362              200005287: {
363                'name': 'Electronic Cigarette Batteries'
364              },
365              200005285: {
366                'name': 'Electronic Cigarette Atomizers'
367              },
368              200005284: {
369                'name': 'Eletronic Cigarette Atomizer Cores'
370              }
371            }
372          },
373          200002396: {
374            'winning': False,
375            'name': 'Video Games',
376            'subcategories': {
377              200215241: {
378                'name': 'Stands'
379              },
380              200215236: {
381                'name': 'Screen Protectors'
382              },
383              200215208: {
384                'name': 'Joysticks'
385              },
386              200215202: {
387                'name': 'Cases'
388              },
389              200215201: {
390                'name': 'Bags'
391              },
392              200215228: {
393                'name': 'Handheld Game Players'
394              },
395              200215227: {
396                'name': 'Gamepads'
397              },
398              200215197: {
399                'name': 'Chargers'
400              },
401              200004542: {
402                'name': 'Video Games Wheels'
403              }
404            }
405          },
406          200216623: {
407            'winning': True,
408            'name': 'Earphones &amp; Headphones',
409            'subcategories': {
410              200216686: {
411                'name': 'Earphones'
412              },
413              200216605: {
414                'name': 'Headphone/Headset'
415              },
416              200216593: {
417                'name': 'Bluetooth Earphones &amp; Headphones'
418              }
419            }
420          },
421          200084019: {
422            'winning': True,
423            'name': 'Wearable Devices',
424            'subcategories': {
425              200010211: {
426                'name': 'Smart Accessories'
427              },
428              200010209: {
429                'name': 'Smart Activity Trackers'
430              },
431              200010207: {
432                'name': 'Smart Wristbands'
433              },
434              200010206: {
435                'name': 'Smart Watches'
436              }
437            }
438          },
439          200215272: {
440            'winning': False,
441            'name': 'VR/AR Devices',
442            'subcategories': {
443              100007533: {
444                'name': '3D Glasses/ Virtual Reality Glasses'
445              }
446            }
447          },
448          200216592: {
449            'winning': False,
450            'name': '360° Video Cameras &amp; Accessories',
451            'subcategories': {
452              200215271: {
453                'name': '360° Video Camera'
454              }
455            }
456          },
457          200217534: {
458            'winning': False,
459            'name': 'Speakers',
460            'subcategories': {
461              518: {
462                'name': 'Portable Speakers'
463              },
464              200217564: {
465                'name': 'Subwoofer'
466              },
467              200217561: {
468                'name': 'Soundbar'
469              }
470            }
471          },
472          200218547: {
473            'winning': False,
474            'name': 'Solar Gadgets',
475            'subcategories': {
476              200218548: {
477                'name': 'Solar'
478              }
479            }
480          }
481        }
482      }
483    }
484  },
485  }
486}
487cat_list[n]['subcategories'][upper_item]['subcategories'][lower_item]
488

This can be solved with nested loops. I would write it using for loops and once working, convert to list comprehension.

The second more complicated way is arbitrary levels, using recursion. should not be too hard.

Source https://stackoverflow.com/questions/62333686

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in 3D Printing

Tutorials and Learning Resources are not available at this moment for 3D Printing

Share this Page

share link

Get latest updates on 3D Printing