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
by OctoPrint python
6542 AGPL-3.0
OctoPrint is the snappy web interface for your 3D printer!
by openscad c++
4741 NOASSERTION
OpenSCAD - The Programmers Solid 3D CAD Modeller
by YadiraF python
4333 MIT
Joint 3D Face Reconstruction and Dense Alignment with Position Map Regression Network (ECCV 2018)
by prusa3d c++
4288 AGPL-3.0
G-code generator for 3D printers (RepRap, Makerbot, Ultimaker etc.)
by openMVG c++
4142 NOASSERTION
open Multiple View Geometry library. Basis for 3D computer vision and Structure from Motion.
by colmap c
3790 NOASSERTION
COLMAP - Structure-from-Motion and Multi-View Stereo
by Ultimaker python
3633 LGPL-3.0
3D printer / slicing GUI built on top of the Uranium framework
by Lyken17 python
2848 MIT
Count the MACs / FLOPs of your PyTorch model.
by slic3r c++
2720 AGPL-3.0
Open Source toolpath generator for 3D printers
Trending New libraries in 3D Printing
by facebookresearch python
915 NOASSERTION
code for Mesh R-CNN, ICCV 2019
by fogleman python
740 MIT
Simple SDF mesh generation in Python
by dbanay c
615 MIT
By the Bluebook implementation of Smalltalk-80
by YadiraF python
601 NOASSERTION
DECA: Detailed Expression Capture and Animation
by DantSu java
466 MIT
Useful library to help Android developpers to print with (Bluetooth, TCP, USB) ESC/POS thermal printer.
by dekuNukem c++
440 MIT
Installing a RGB mechanical keypad on my microwave.
by OpenPrinting c
437 Apache-2.0
OpenPrinting CUPS Sources
by jordanruthe python
347 AGPL-3.0
GUI for Klipper
by MirageC79 html
341 GPL-3.0
Advanced DIY 3D Printer
Top Authors in 3D Printing
1
24 Libraries
504
2
20 Libraries
7145
3
9 Libraries
236
4
7 Libraries
60
5
7 Libraries
383
6
6 Libraries
1332
7
6 Libraries
92
8
6 Libraries
507
9
6 Libraries
116
10
5 Libraries
82
1
24 Libraries
504
2
20 Libraries
7145
3
9 Libraries
236
4
7 Libraries
60
5
7 Libraries
383
6
6 Libraries
1332
7
6 Libraries
92
8
6 Libraries
507
9
6 Libraries
116
10
5 Libraries
82
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:
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:50The 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:01You 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
QUESTION
if state.obj.val1 === true, return state.obj.val2
Asked 2021-Sep-20 at 22:52I 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
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: "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 <Embed
161 autoplay={false}
162 width='100px'
163 height='100px'
164 color="white"
165 hd={false}
166 id={this.ifActiveField}
167 iframe={{
168 allowFullScreen: true,
169 style: {
170 padding: 10,
171 },
172 }}
173 />
174
ANSWER
Answered 2021-Sep-20 at 22:52It 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: "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 <Embed
161 autoplay={false}
162 width='100px'
163 height='100px'
164 color="white"
165 hd={false}
166 id={this.ifActiveField}
167 iframe={{
168 allowFullScreen: true,
169 style: {
170 padding: 10,
171 },
172 }}
173 />
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 < 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: "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 <Embed
161 autoplay={false}
162 width='100px'
163 height='100px'
164 color="white"
165 hd={false}
166 id={this.ifActiveField}
167 iframe={{
168 allowFullScreen: true,
169 style: {
170 padding: 10,
171 },
172 }}
173 />
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 < 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: "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 <Embed
161 autoplay={false}
162 width='100px'
163 height='100px'
164 color="white"
165 hd={false}
166 id={this.ifActiveField}
167 iframe={{
168 allowFullScreen: true,
169 style: {
170 padding: 10,
171 },
172 }}
173 />
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 < 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 => x.active).id;
200
QUESTION
How can i work with Example for nlp.update problem with spacy3.0
Asked 2021-May-06 at 04:05i 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("en")
5ner = nlp.create_pipe("ner")
6nlp.add_pipe('ner')
7ner.add_label("label")
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("en")
5ner = nlp.create_pipe("ner")
6nlp.add_pipe('ner')
7ner.add_label("label")
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<ipython-input-79-27d69961629b> in <module>
24 18 annotations = [entities for text, entities in batch]
25 19 # Update the model
26---> 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 """
31 1087 if _ is not None:
32-> 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("en")
5ner = nlp.create_pipe("ner")
6nlp.add_pipe('ner')
7ner.add_label("label")
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<ipython-input-79-27d69961629b> in <module>
24 18 annotations = [entities for text, entities in batch]
25 19 # Update the model
26---> 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 """
31 1087 if _ is not None:
32-> 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'], {"entities": entities})
43 TRAINING_DATA.append(spacy_entry)
44
My train data looks like this:
1import spacy
2import random
3import json
4nlp = spacy.blank("en")
5ner = nlp.create_pipe("ner")
6nlp.add_pipe('ner')
7ner.add_label("label")
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<ipython-input-79-27d69961629b> in <module>
24 18 annotations = [entities for text, entities in batch]
25 19 # Update the model
26---> 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 """
31 1087 if _ is not None:
32-> 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'], {"entities": 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:05You 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("en")
5ner = nlp.create_pipe("ner")
6nlp.add_pipe('ner')
7ner.add_label("label")
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<ipython-input-79-27d69961629b> in <module>
24 18 annotations = [entities for text, entities in batch]
25 19 # Update the model
26---> 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 """
31 1087 if _ is not None:
32-> 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'], {"entities": 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
QUESTION
Laravel whereIn doesn't return all data
Asked 2021-Apr-20 at 09:46I have following array (created by explode method)
1["3D Printing"," 3D Architecture"," .NET Micro Framework"]
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["3D Printing"," 3D Architecture"," .NET Micro Framework"]
2["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]
3
it supposed to return something like this
1["3D Printing"," 3D Architecture"," .NET Micro Framework"]
2["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]
3["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]
4
code
1["3D Printing"," 3D Architecture"," .NET Micro Framework"]
2["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]
3["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]
4$a = $request->input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
9return response()->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.
I've tried $b = str_replace([',', ' '], ['',''], $a);
but all I get now is []
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 31["3D Printing"," 3D Architecture"," .NET Micro Framework"]
2["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]
3["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]
4$a = $request->input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
9return response()->json($iddss);
10$a = $request->input('tags');
11// return
12"[3D Printing, 3D Architecture, .NET Micro Framework]"
13
.
1["3D Printing"," 3D Architecture"," .NET Micro Framework"]
2["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]
3["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]
4$a = $request->input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
9return response()->json($iddss);
10$a = $request->input('tags');
11// return
12"[3D Printing, 3D Architecture, .NET Micro Framework]"
13$b = str_replace(['[',']'], null, $a);
14// return
15"3D Printing, 3D Architecture, .NET Micro Framework"
16
.
1["3D Printing"," 3D Architecture"," .NET Micro Framework"]
2["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]
3["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]
4$a = $request->input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
9return response()->json($iddss);
10$a = $request->input('tags');
11// return
12"[3D Printing, 3D Architecture, .NET Micro Framework]"
13$b = str_replace(['[',']'], null, $a);
14// return
15"3D Printing, 3D Architecture, .NET Micro Framework"
16$comingTags = explode(',',$b);
17// return
18["3D Printing"," 3D Architecture"," .NET Micro Framework"]
19
ANSWER
Answered 2021-Apr-20 at 09:46To get rid of whitespace you can do
array_map('trim', $a);
(credits)
whereIn expects an array, so this should work
1["3D Printing"," 3D Architecture"," .NET Micro Framework"]
2["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]
3["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]
4$a = $request->input('tags');
5$b = str_replace(['[',']'], null, $a);
6$comingTags = explode(',',$b);
7
8$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
9return response()->json($iddss);
10$a = $request->input('tags');
11// return
12"[3D Printing, 3D Architecture, .NET Micro Framework]"
13$b = str_replace(['[',']'], null, $a);
14// return
15"3D Printing, 3D Architecture, .NET Micro Framework"
16$comingTags = explode(',',$b);
17// return
18["3D Printing"," 3D Architecture"," .NET Micro Framework"]
19$a = $request->input('tags');
20$b = str_replace(['[',']'], null, $a);
21$comingTags = array_map('trim', explode(',', $b));
22
23$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
24
25return response()->json($iddss);
26
QUESTION
Kotlin get ids of selected options
Asked 2021-Apr-20 at 07:51I 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<String>? = 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<String>()
11 val tagOptions = ArrayList<String>()
12 for (i in tags) {
13 tagOptions.add(i.title)
14 tagIds.add(i.id)
15 }
16 var checkedItems = ArrayList<Int>()
17 checkedItems.forEach{ index -> tagIds[index + 1] }
18
19 MaterialAlertDialogBuilder(this)
20 .setTitle(resources.getString(R.string.project_tags))
21 .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked ->
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("${checkedItems.size} tags selected")
29 }
30 .setPositiveButton(resources.getString(R.string.ok)) { dialog, which ->
31 for (i in checkedItems) {
32 Log.d("eeee1", tagOptions[i])
33 selectedTags = listOf(tagOptions[i])
34 }
35 }
36 .setNeutralButton(resources.getString(R.string.clear)) { dialog, which ->
37 pTags.text = null
38 pTags.hint = "0 tag selected"
39 if (checkedItems.size > 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<String>? = 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<String>()
11 val tagOptions = ArrayList<String>()
12 for (i in tags) {
13 tagOptions.add(i.title)
14 tagIds.add(i.id)
15 }
16 var checkedItems = ArrayList<Int>()
17 checkedItems.forEach{ index -> tagIds[index + 1] }
18
19 MaterialAlertDialogBuilder(this)
20 .setTitle(resources.getString(R.string.project_tags))
21 .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked ->
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("${checkedItems.size} tags selected")
29 }
30 .setPositiveButton(resources.getString(R.string.ok)) { dialog, which ->
31 for (i in checkedItems) {
32 Log.d("eeee1", tagOptions[i])
33 selectedTags = listOf(tagOptions[i])
34 }
35 }
36 .setNeutralButton(resources.getString(R.string.clear)) { dialog, which ->
37 pTags.text = null
38 pTags.hint = "0 tag selected"
39 if (checkedItems.size > 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 thoseselected items
instead of their names that's why I havevar 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:51The 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<String>? = 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<String>()
11 val tagOptions = ArrayList<String>()
12 for (i in tags) {
13 tagOptions.add(i.title)
14 tagIds.add(i.id)
15 }
16 var checkedItems = ArrayList<Int>()
17 checkedItems.forEach{ index -> tagIds[index + 1] }
18
19 MaterialAlertDialogBuilder(this)
20 .setTitle(resources.getString(R.string.project_tags))
21 .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked ->
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("${checkedItems.size} tags selected")
29 }
30 .setPositiveButton(resources.getString(R.string.ok)) { dialog, which ->
31 for (i in checkedItems) {
32 Log.d("eeee1", tagOptions[i])
33 selectedTags = listOf(tagOptions[i])
34 }
35 }
36 .setNeutralButton(resources.getString(R.string.clear)) { dialog, which ->
37 pTags.text = null
38 pTags.hint = "0 tag selected"
39 if (checkedItems.size > 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<String>? = 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<String>()
11 val tagOptions = ArrayList<String>()
12 for (i in tags) {
13 tagOptions.add(i.title)
14 tagIds.add(i.id)
15 }
16 var checkedItems = ArrayList<Int>()
17 checkedItems.forEach{ index -> tagIds[index + 1] }
18
19 MaterialAlertDialogBuilder(this)
20 .setTitle(resources.getString(R.string.project_tags))
21 .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked ->
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("${checkedItems.size} tags selected")
29 }
30 .setPositiveButton(resources.getString(R.string.ok)) { dialog, which ->
31 for (i in checkedItems) {
32 Log.d("eeee1", tagOptions[i])
33 selectedTags = listOf(tagOptions[i])
34 }
35 }
36 .setNeutralButton(resources.getString(R.string.clear)) { dialog, which ->
37 pTags.text = null
38 pTags.hint = "0 tag selected"
39 if (checkedItems.size > 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<String> = 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<String>? = 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<String>()
11 val tagOptions = ArrayList<String>()
12 for (i in tags) {
13 tagOptions.add(i.title)
14 tagIds.add(i.id)
15 }
16 var checkedItems = ArrayList<Int>()
17 checkedItems.forEach{ index -> tagIds[index + 1] }
18
19 MaterialAlertDialogBuilder(this)
20 .setTitle(resources.getString(R.string.project_tags))
21 .setMultiChoiceItems(tagOptions.toTypedArray(), null) { dialog, which, checked ->
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("${checkedItems.size} tags selected")
29 }
30 .setPositiveButton(resources.getString(R.string.ok)) { dialog, which ->
31 for (i in checkedItems) {
32 Log.d("eeee1", tagOptions[i])
33 selectedTags = listOf(tagOptions[i])
34 }
35 }
36 .setNeutralButton(resources.getString(R.string.clear)) { dialog, which ->
37 pTags.text = null
38 pTags.hint = "0 tag selected"
39 if (checkedItems.size > 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<String> = mutableListOf()
54
55...
56// In loop
57selectedTags.add(tagOptions[i])
58//Declaration
59var selectedTags: List<String>? = listOf()
60
61...
62// Skip the loop and use the map function
63.setPositiveButton(resources.getString(R.string.ok)) { dialog, which ->
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.
QUESTION
Getting all the HTML code from a website that is using React
Asked 2021-Apr-05 at 15:45I'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<!doctype html>
2<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">
3
4<head>
5 <title>PCB Feet/Standoffs for M3 by scruss - Thingiverse</title>
6 <meta http-equiv="Content-type" content="text/html; charset=utf-8">
7 <meta charset="utf-8">
8 <meta http-equiv="Content-Language" content="EN">
9 <meta http-equiv="imagetoolbar" content="no">
10 <meta name="keywords"
11 content="things, digital design, physical objects, rapid prototyping, 3D objects, 3D printing, reprap, fabrication, laser cutter, laser, thingaverse, thingyverse">
12 <meta name="abstract" content="Share your digital designs for physical objects.">
13 <meta name="author" content="Thingiverse.com">
14 <meta name="distribution" content="Global">
15 <meta name="revisit-after" content="1 days">
16 <meta name="robots" content="follow,index">
17 <meta name="description"
18 content="Download files and build them with your 3D printer, laser cutter, or CNC. Thingiverse is a universe of things.">
19 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
20 <meta name="theme-color" content="#248bfb">
21
22 <meta property="og:type" content="website">
23 <meta property="og:title" content="PCB Feet/Standoffs for M3 by scruss">
24 <meta property="og:description"
25 content="Basic &quot;I don&#039;t want my protoboard shorting or gouging holes in my desk&quot; feet/standoffs for M3-drilled 1.6 mm thick PCBs.">
26 <meta property="og:image" content="https://cdn.thingiverse.com/assets/d5/9e/0e/1c/f3/featured_preview_pcb_feet.png">
27 <meta property="twitter:card" content="summary">
28 <meta property="twitter:site" content="@thingiverse">
29 <meta property="og:url" content="https://www.thingiverse.com/thing:4796603">
30 <meta property="twitter:creator" content="@scruss">
31 <link rel="apple-touch-icon" sizes="57x57"
32 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-57x57.png">
33 <link rel="apple-touch-icon" sizes="114x114"
34 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-114x114.png">
35 <link rel="apple-touch-icon" sizes="72x72"
36 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-72x72.png">
37 <link rel="apple-touch-icon" sizes="144x144"
38 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-144x144.png">
39 <link rel="apple-touch-icon" sizes="60x60"
40 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-60x60.png">
41 <link rel="apple-touch-icon" sizes="120x120"
42 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-120x120.png">
43 <link rel="apple-touch-icon" sizes="76x76"
44 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-76x76.png">
45 <link rel="apple-touch-icon" sizes="152x152"
46 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-152x152.png">
47 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-192x192.png"
48 sizes="192x192">
49 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-160x160.png"
50 sizes="160x160">
51 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-96x96.png"
52 sizes="96x96">
53 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-16x16.png"
54 sizes="16x16">
55 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-32x32.png"
56 sizes="32x32">
57 <meta name="msapplication-TileColor" content="#ffffff">
58 <meta name="msapplication-TileImage" content="https://cdn.thingiverse.com/site/img/favicons/mstile-144x144.png">
59
60 <link rel="alternate" type="application/rss+xml" title="Thingiverse - PCB Feet/Standoffs for M3 Comments"
61 href="https://rss.thingiverse.com/thing:4796603">
62
63
64 <script type="text/javascript" src="https://www.datadoghq-browser-agent.com/datadog-logs-us.js"></script>
65 <script>
66 const ddClientToken = "pub24a00142f6aa558abe1827e911e11e58";
67 const ddEnv = "production";
68 const ddVersion = "2.11.0";
69
70 DD_LOGS.init({
71 clientToken: ddClientToken,
72 forwardErrorsToLogs: true,
73 service: "thingiverse-client",
74 env: ddEnv,
75 version: ddVersion,
76 sampleRate: 20
77 });
78
79
80 const ddIsTvNext = true;
81 const ddBuildTime = "1617625667";
82
83 DD_LOGS.addLoggerGlobalContext("is_thingiverse_next", ddIsTvNext);
84 DD_LOGS.addLoggerGlobalContext("build_time", ddBuildTime);
85 </script>
86
87 <script>
88 var scripts = ["https://cdn.thingiverse.com/site/js/thingiverse/build/lib-afbc32d766.js","https://cdn.thingiverse.com/site/js/thingiverse/build/header-aa33d7b171.js","https://cdn.thingiverse.com/site/js/thingiverse/build/footer-df22f3acb4.js","https://cdn.thingiverse.com/site/js/thingiverse/build/things-d4ffa805ef.js","https://cdn.thingiverse.com/site/js/thingiverse/build/orders-e1ac5a6395.js","https://cdn.thingiverse.com/site/js/thingiverse/build/gallery-7fc215e644.js"];
89 var stylesheets = [];
90 var build_time = 1617625667;
91 </script>
92</head>
93
94
95<script src="https://cdn.thingiverse.com/site/js/three.min.bundle.js?1617625667"></script>
96<div class="react-app" id="react-app"></div>
97<script src="https://cdn.thingiverse.com/site/js/app.bundle.js?1617625667"></script>
98<script>
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</script>
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:45You'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<!doctype html>
2<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">
3
4<head>
5 <title>PCB Feet/Standoffs for M3 by scruss - Thingiverse</title>
6 <meta http-equiv="Content-type" content="text/html; charset=utf-8">
7 <meta charset="utf-8">
8 <meta http-equiv="Content-Language" content="EN">
9 <meta http-equiv="imagetoolbar" content="no">
10 <meta name="keywords"
11 content="things, digital design, physical objects, rapid prototyping, 3D objects, 3D printing, reprap, fabrication, laser cutter, laser, thingaverse, thingyverse">
12 <meta name="abstract" content="Share your digital designs for physical objects.">
13 <meta name="author" content="Thingiverse.com">
14 <meta name="distribution" content="Global">
15 <meta name="revisit-after" content="1 days">
16 <meta name="robots" content="follow,index">
17 <meta name="description"
18 content="Download files and build them with your 3D printer, laser cutter, or CNC. Thingiverse is a universe of things.">
19 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
20 <meta name="theme-color" content="#248bfb">
21
22 <meta property="og:type" content="website">
23 <meta property="og:title" content="PCB Feet/Standoffs for M3 by scruss">
24 <meta property="og:description"
25 content="Basic &quot;I don&#039;t want my protoboard shorting or gouging holes in my desk&quot; feet/standoffs for M3-drilled 1.6 mm thick PCBs.">
26 <meta property="og:image" content="https://cdn.thingiverse.com/assets/d5/9e/0e/1c/f3/featured_preview_pcb_feet.png">
27 <meta property="twitter:card" content="summary">
28 <meta property="twitter:site" content="@thingiverse">
29 <meta property="og:url" content="https://www.thingiverse.com/thing:4796603">
30 <meta property="twitter:creator" content="@scruss">
31 <link rel="apple-touch-icon" sizes="57x57"
32 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-57x57.png">
33 <link rel="apple-touch-icon" sizes="114x114"
34 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-114x114.png">
35 <link rel="apple-touch-icon" sizes="72x72"
36 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-72x72.png">
37 <link rel="apple-touch-icon" sizes="144x144"
38 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-144x144.png">
39 <link rel="apple-touch-icon" sizes="60x60"
40 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-60x60.png">
41 <link rel="apple-touch-icon" sizes="120x120"
42 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-120x120.png">
43 <link rel="apple-touch-icon" sizes="76x76"
44 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-76x76.png">
45 <link rel="apple-touch-icon" sizes="152x152"
46 href="https://cdn.thingiverse.com/site/img/favicons/apple-touch-icon-152x152.png">
47 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-192x192.png"
48 sizes="192x192">
49 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-160x160.png"
50 sizes="160x160">
51 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-96x96.png"
52 sizes="96x96">
53 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-16x16.png"
54 sizes="16x16">
55 <link rel="icon" type="image/png" href="https://cdn.thingiverse.com/site/img/favicons/favicon-32x32.png"
56 sizes="32x32">
57 <meta name="msapplication-TileColor" content="#ffffff">
58 <meta name="msapplication-TileImage" content="https://cdn.thingiverse.com/site/img/favicons/mstile-144x144.png">
59
60 <link rel="alternate" type="application/rss+xml" title="Thingiverse - PCB Feet/Standoffs for M3 Comments"
61 href="https://rss.thingiverse.com/thing:4796603">
62
63
64 <script type="text/javascript" src="https://www.datadoghq-browser-agent.com/datadog-logs-us.js"></script>
65 <script>
66 const ddClientToken = "pub24a00142f6aa558abe1827e911e11e58";
67 const ddEnv = "production";
68 const ddVersion = "2.11.0";
69
70 DD_LOGS.init({
71 clientToken: ddClientToken,
72 forwardErrorsToLogs: true,
73 service: "thingiverse-client",
74 env: ddEnv,
75 version: ddVersion,
76 sampleRate: 20
77 });
78
79
80 const ddIsTvNext = true;
81 const ddBuildTime = "1617625667";
82
83 DD_LOGS.addLoggerGlobalContext("is_thingiverse_next", ddIsTvNext);
84 DD_LOGS.addLoggerGlobalContext("build_time", ddBuildTime);
85 </script>
86
87 <script>
88 var scripts = ["https://cdn.thingiverse.com/site/js/thingiverse/build/lib-afbc32d766.js","https://cdn.thingiverse.com/site/js/thingiverse/build/header-aa33d7b171.js","https://cdn.thingiverse.com/site/js/thingiverse/build/footer-df22f3acb4.js","https://cdn.thingiverse.com/site/js/thingiverse/build/things-d4ffa805ef.js","https://cdn.thingiverse.com/site/js/thingiverse/build/orders-e1ac5a6395.js","https://cdn.thingiverse.com/site/js/thingiverse/build/gallery-7fc215e644.js"];
89 var stylesheets = [];
90 var build_time = 1617625667;
91 </script>
92</head>
93
94
95<script src="https://cdn.thingiverse.com/site/js/three.min.bundle.js?1617625667"></script>
96<div class="react-app" id="react-app"></div>
97<script src="https://cdn.thingiverse.com/site/js/app.bundle.js?1617625667"></script>
98<script>
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</script>
101from selenium import webdriver
102driver = webdriver.Chrome('./chromedriver') # Downloaad the chrome driver and replace this path
103driver.get("your_url")
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
QUESTION
Python matching various keyword from dictionary issues
Asked 2021-Mar-14 at 14:50I have a complex text where I am categorizing different keywords stored in a dictionary:
1 text = 'data-ls-static="1">Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE</h3>'
2
3 sector = {"med tech": ['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="1">Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE</h3>'
2
3 sector = {"med tech": ['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:
For example, keywords like "Drug Delivery" that are separated by a space are not recognized and therefore categorized.
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.
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="1">Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE</h3>'
2
3 sector = {"med tech": ['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="1">Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE</h3>'
2
3 sector = {"med tech": ['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:16findall
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="1">Making Bio Implants, Drug Delivery and 3D Printing in Medicine,MEDICINE</h3>'
2
3 sector = {"med tech": ['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
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:14I'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<void> uploadFile(File file) async {
3///Using HTTP Package
4 Map<String, String> headers = {
5 "Content-type": "application/octet-stream",
6};
7var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
8var length = await file.length();
9var uri = Uri.parse("http://192.168.1.125/upload?X-Filename=nupo.gcode");
10
11var request = new http.MultipartRequest("POST", 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:14Postman 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]
QUESTION
Is there a name for this 3D printing effect?
Asked 2020-Sep-25 at 15:21I'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.
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.
- Is there a name for this effect?
- Are there mitigations?
I'm starting to rethink this whole approach...
ANSWER
Answered 2020-Sep-25 at 15:21I 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.
QUESTION
Python Nested Dictionaries Retrieve Key from nested value
Asked 2020-Jun-14 at 05:55I 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 & 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 & 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 & Shirts',
20 'subcategories': {}
21 },
22 100003141: {
23 'winning': False,
24 'name': 'Hoodies & 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 & Much More',
54 'winning': False,
55 'subcategories': {
56 100003084: {
57 'winning': True,
58 'name': 'Hoodies & Sweatshirts',
59 'subcategories': {}
60 },
61 200000707: {
62 'name': 'Tops & 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 & 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 & 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 & 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 & Office Gadgets, 3D Printing Pens, Computer Peripherals & 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 & Mouse Sets'
213 },
214 708023: {
215 'name': 'Mouse Pads'
216 },
217 708032: {
218 'name': 'USB Docks & 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 & Cases'
248 },
249 708031: {
250 'name': 'Laptop Skins & 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 & Lighting, Selfie Sticks, Earphones & Headphones, Smart Watches, E-Cigs & Vapes, Gaming Accessories, Speakers & Solar Gadgets',
266 'winning': False,
267 'subcategories': {
268 200002395: {
269 'winning': True,
270 'name': 'Camera & Photo',
271 'subcategories': {
272 200002411: {
273 'name': 'Photographic Lighting'
274 },
275 200002408: {
276 'name': 'Tripod & 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 & Photo Accessories'
289 },
290 200216669: {
291 'name': 'Selfie Sticks'
292 },
293 200216611: {
294 'name': 'Flashes & Accessories'
295 }
296 }
297 },
298 200002398: {
299 'winning': True,
300 'name': 'Portable Audio & Video',
301 'subcategories': {
302 200003109: {
303 'name': 'Earphone Accessories'
304 },
305 200217778: {
306 'name': 'Translator'
307 },
308 63705: {
309 'name': 'Earphones & 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 & Parts',
331 'subcategories': {
332 200084029: {
333 'name': 'Smart Power Sockets & Plugs'
334 },
335 200003200: {
336 'name': 'Tech Cables & Accessories'
337 },
338 200003127: {
339 'name': 'Cable Winders & Protectors'
340 },
341 380210: {
342 'name': 'Camera/Video Bags'
343 }
344 }
345 },
346 200005280: {
347 'winning': False,
348 'name': 'Electronic Cigarettes & 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 & Headphones',
409 'subcategories': {
410 200216686: {
411 'name': 'Earphones'
412 },
413 200216605: {
414 'name': 'Headphone/Headset'
415 },
416 200216593: {
417 'name': 'Bluetooth Earphones & 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 & 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:54There 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 & 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 & 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 & Shirts',
20 'subcategories': {}
21 },
22 100003141: {
23 'winning': False,
24 'name': 'Hoodies & 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 & Much More',
54 'winning': False,
55 'subcategories': {
56 100003084: {
57 'winning': True,
58 'name': 'Hoodies & Sweatshirts',
59 'subcategories': {}
60 },
61 200000707: {
62 'name': 'Tops & 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 & 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 & 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 & 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 & Office Gadgets, 3D Printing Pens, Computer Peripherals & 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 & Mouse Sets'
213 },
214 708023: {
215 'name': 'Mouse Pads'
216 },
217 708032: {
218 'name': 'USB Docks & 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 & Cases'
248 },
249 708031: {
250 'name': 'Laptop Skins & 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 & Lighting, Selfie Sticks, Earphones & Headphones, Smart Watches, E-Cigs & Vapes, Gaming Accessories, Speakers & Solar Gadgets',
266 'winning': False,
267 'subcategories': {
268 200002395: {
269 'winning': True,
270 'name': 'Camera & Photo',
271 'subcategories': {
272 200002411: {
273 'name': 'Photographic Lighting'
274 },
275 200002408: {
276 'name': 'Tripod & 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 & Photo Accessories'
289 },
290 200216669: {
291 'name': 'Selfie Sticks'
292 },
293 200216611: {
294 'name': 'Flashes & Accessories'
295 }
296 }
297 },
298 200002398: {
299 'winning': True,
300 'name': 'Portable Audio & Video',
301 'subcategories': {
302 200003109: {
303 'name': 'Earphone Accessories'
304 },
305 200217778: {
306 'name': 'Translator'
307 },
308 63705: {
309 'name': 'Earphones & 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 & Parts',
331 'subcategories': {
332 200084029: {
333 'name': 'Smart Power Sockets & Plugs'
334 },
335 200003200: {
336 'name': 'Tech Cables & Accessories'
337 },
338 200003127: {
339 'name': 'Cable Winders & Protectors'
340 },
341 380210: {
342 'name': 'Camera/Video Bags'
343 }
344 }
345 },
346 200005280: {
347 'winning': False,
348 'name': 'Electronic Cigarettes & 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 & Headphones',
409 'subcategories': {
410 200216686: {
411 'name': 'Earphones'
412 },
413 200216605: {
414 'name': 'Headphone/Headset'
415 },
416 200216593: {
417 'name': 'Bluetooth Earphones & 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 & 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.
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