I trained Yolo v3 using my own data, but prediction shows class I did not train - object-detection

I'm trying to make a Yolo v3 model for detecting traffic lights for each color.
So I started to train Yolo v3 using my own data of traffic lights.
The classes I set are six.
red light, green light, yellow light, left turn, go straight and left turn, right turn.
(I will make these 4 classes.)
After training, I run Yolo v3 detector by my own Weight and cfg file.
But prediction showed an unexpected result!
Its class had nothing to do with what I've set. Like car, aeroplane, motobike...
What's wrong with this?
I'm using Ubuntu 16.04 LTS and GForce RTX 2080. OpenCV, CUDA, CuDNN also.
So makefile of darknet has been set like this.
GPU=1
CUDNN=1
OPENCV=1
OPENMP=0
DEBUG=0
...
I used pre-trianed weight darknet19_448.conv.23.
I heard it is needed.
Add my cfg file for training I've set.
[net]
# Testing
#batch=1
#subdivisions=1
# Training
batch=24
subdivisions=8
width=416
height=416
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1
learning_rate=0.001
burn_in=1000
max_batches = 20000
policy=steps
steps=400000,450000
scales=.1,.1
[convolutional]
batch_normalize=1
filters=32
size=3
stride=1
pad=1
activation=leaky
# Downsample
[convolutional]
batch_normalize=1
filters=64
size=3
stride=2
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=32
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
# Downsample
[convolutional]
batch_normalize=1
filters=128
size=3
stride=2
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=64
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=64
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
# Downsample
[convolutional]
batch_normalize=1
filters=256
size=3
stride=2
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
# Downsample
[convolutional]
batch_normalize=1
filters=512
size=3
stride=2
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
# Downsample
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=2
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
[shortcut]
from=-3
activation=linear
######################
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky
[convolutional]
size=1
stride=1
pad=1
filters=33
activation=linear
[yolo]
mask = 6,7,8
anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326
classes=6
num=9
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1
[route]
layers = -4
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[upsample]
stride=2
[route]
layers = -1, 61
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=512
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=512
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=512
activation=leaky
[convolutional]
size=1
stride=1
pad=1
filters=33
activation=linear
[yolo]
mask = 3,4,5
anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326
classes=6
num=9
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1
[route]
layers = -4
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[upsample]
stride=2
[route]
layers = -1, 36
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=256
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=256
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=256
activation=leaky
[convolutional]
size=1
stride=1
pad=1
filters=33
activation=linear
[yolo]
mask = 0,1,2
anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326
classes=6
num=9
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1
I would really appreciate it if you answer me.

What repository are you using?
There should also be some .data or .names files somewhere that you should change. Take a look at this page for example. You need to change number of filters, number of classes, and class names before training your model. The model you are using is probably pre-trained on some other data-set for vehicle detection.

Related

How do I get a context from field table using regex in oracle SQL?

How can I catch the part of content "Description scenario::" and the rest of the information using REGEXP_LIKE in SQL Oracle?
select description
from tbl_error
where REGEXP_LIKE(description, '[Description scenario::].*$' )
Error Details
Report steps Erro: WEB
Contributor name:: Lorem Lorem
Description scenario:: Lorem ipsum dolor sit amet. Est ducimus magnam qui culpa internos in Quis neque et quibusdam ipsa. Aut dolorum omnis qui doloribus eveniet aut neque impedit est expedita consectetur et omnis nulla non sunt sequi. Hic dolor incidunt aut itaque ipsam autem fuga in rerum molestiae. A accusantium facere ad impedit quasi et dolorem quia cum veniam dolores et odit voluptate aut animi illum.
If regex isn't a must, use substr + instr combination:
SQL> select substr(description, instr(description, 'Description scenario::') +
2 length('Description scenario::') + 1
3 ) as result
4 from tbl_error;
RESULT
--------------------------------------------------------------------------------
Lorem ipsum dolor sit amet. Est ducimus magnam qui culpa internos in Quis neque
et quibusdam ipsa. Aut dolorum omnis qui doloribus eveniet aut neque impedit est
expedita consectetur et omnis nulla non sunt sequi. Hic dolor incidunt aut itaq
ue ipsam autem fuga in rerum molestiae. A accusantium facere ad impedit quasi et
dolorem quia cum veniam dolores et odit voluptate aut animi illum.
SQL>
You do not need (slow) regular expressions and can use simple string functions:
SELECT SUBSTR(
description,
INSTR(description, 'Description scenario::') + LENGTH('Description scenario::')
) AS description_scenario
FROM tbl_error;
Which, for the sample data:
CREATE TABLE tbl_error (description) AS
SELECT 'Error Details
Report steps Error:: WEB
Contributor name:: Lorem Lorem
Description scenario:: Lorem ipsum dolor sit amet. Est ducimus magnam qui culpa internos in Quis neque et quibusdam ipsa. Aut dolorum omnis qui doloribus eveniet aut neque impedit est expedita consectetur et omnis nulla non sunt sequi. Hic dolor incidunt aut itaque ipsam autem fuga in rerum molestiae. A accusantium facere ad impedit quasi et dolorem quia cum veniam dolores et odit voluptate aut animi illum.'
FROM DUAL
Outputs:
DESCRIPTION_SCENARIO
Lorem ipsum dolor sit amet. Est ducimus magnam qui culpa internos in Quis neque et quibusdam ipsa. Aut dolorum omnis qui doloribus eveniet aut neque impedit est expedita consectetur et omnis nulla non sunt sequi. Hic dolor incidunt aut itaque ipsam autem fuga in rerum molestiae. A accusantium facere ad impedit quasi et dolorem quia cum veniam dolores et odit voluptate aut animi illum.
If all the values are on individual lines and the separator between the key and the value is :: then you can extract all the key-value pairs (again, without regular expressions) using:
WITH bounds (description, spos, epos) AS (
SELECT description,
1,
INSTR(description, CHR(10), 1)
FROM tbl_error
UNION ALL
SELECT description,
epos + 1,
INSTR(description, CHR(10), epos + 1)
FROM bounds
WHERE epos > 0
),
lines (line) AS (
SELECT CASE epos
WHEN 0
THEN SUBSTR(description, spos)
ELSE SUBSTR(description, spos, epos - spos)
END
FROM bounds
),
separators (line, sep_pos) AS (
SELECT line,
INSTR(line, '::')
FROM lines
)
SELECT SUBSTR(line, 1, sep_pos - 1) AS type,
LTRIM(SUBSTR(line, sep_pos + 2)) AS value
FROM separators
WHERE sep_pos > 0
Which, for the sample data, outputs:
TYPE
VALUE
Report steps Error
WEB
Contributor name
Lorem Lorem
Description scenario
Lorem ipsum dolor sit amet. Est ducimus magnam qui culpa internos in Quis neque et quibusdam ipsa. Aut dolorum omnis qui doloribus eveniet aut neque impedit est expedita consectetur et omnis nulla non sunt sequi. Hic dolor incidunt aut itaque ipsam autem fuga in rerum molestiae. A accusantium facere ad impedit quasi et dolorem quia cum veniam dolores et odit voluptate aut animi illum.
db<>fiddle here

Padding around tick labels

I'm doing a bar chart.
sns_plot = sns.barplot(years, yields, ax=axes[0, 0])
sns_plot.set_xticklabels(years, rotation=90)
sns_plot.xaxis.set_tick_params(pad=10)
But the text is too bunched up. I.e. need separation between the labels. How can I do this? The pad=10 seems to push the labels from the axis rather then separate labels.
After the labels are vertical (90 deg), they are still a bit bunched up. I guess finding the right lever to pull...
Test Data:
In [1]:
import numpy as np
import re
x = """Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Cras nibh turpis, ullamcorper ac lectus vel,
aliquet consectetur odio. Cras vel scelerisque tortor.
Interdum et malesuada fames ac ante ipsum primis in faucibus.
Proin id dignissim ante, a dictum ipsum. Fusce at lacus ac purus
pulvinar dignissim eget a quam. Sed quis mollis ligula, sed
ullamcorper velit. Curabitur vel congue metus. Ut placerat
ipsum non leo posuere, non vestibulum eros posuere.
Donec eu viverra augue, sit amet tempus ex. Vivamus
sit amet tempus ipsum. Fusce consequat, augue a mollis
hendrerit, quam neque dapibus ligula, vitae blandit ipsum
lorem eu mauris. """
x = pd.Series(x.split(' '))
x = x.apply(lambda x: re.sub('\W+', '', x))
y = np.random.randn(x.shape[0])
df = pd.DataFrame({'X': x, 'Y': y})
df.head()
Out [1]:
X Y
0 Lorem -0.562246
1 ipsum 1.085094
2 dolor 1.044887
3 sit -1.424002
4 amet -0.87682
Test plot:
In [2]:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(9, 6))
ax.plot(df.X, df.Y, 'ks')
ax.tick_params(axis='x', rotation=90)
Out [2]:
So to summarize comments to the original post, there are multiple ways to remove cluttered ticklabels you have multiple options:
1) Smaller label text: ax.tick_params(axis='x', labelsize=6)
2) Less labels:
for label in ax.xaxis.get_ticklabels()[::2]:
label.set_visible(False)
3) Longer Axis: fig.set_size_inches((15, 4))
And so on...

JSON path title doesn't match

I write a simple test using rest-assured, code below
#Test
public void exampleRestTest() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com/";
Response res = RestAssured.get("posts/1");
res.print();
res.then()
.body("id", equalTo(1))
.body("userId", equalTo(1))
.body("title",contains("sunt aut facere repellat provident occaecati excepturi optio reprehenderit"));
JSON from res.print() is:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
}
Test output:
java.lang.AssertionError: 1 expectation failed.
JSON path title doesn't match.
Expected: iterable containing ["sunt aut facere repellat provident occaecati excepturi optio reprehenderit"]
Actual: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Why?
I must escape from iterable containing?
Do you want to use 'contains' matcher only?
'contains' matcher checks that expected Iterable object is contained in the actual collection object.
You should use 'containsString' matcher as follows:
.body("title",containsString("sunt aut facere repellat provident occaecati excepturi optio reprehenderit"))

PostgreSQL Pick one single random row from multiple tables

How can we pick a random row from 3 tables, whereas the table row count for each table may vary. This would need to be fair if there not same count. This means if one table had only one row and the other table has 10 rows, then were much more likely get row from table with 10 rows. Each row in all tables get chance at winning
I was trying to convert this SQL code which I got from another Stack Overflow post here
SELECT preview_id, review_id
FROM (
select preview.*, row_number() over (order by newid()) as seqnum from
preview
) preview
JOIN (
select review.*, row_number() over (order by newid()) as seqnum
from review
) review ON preview.seqnum = review.seqnum;
3 Table schemas.
CREATE TABLE preview
(
preview_id SERIAL PRIMARY KEY NOT NULL,
preview_header VARCHAR(90) NOT NULL,
preview_text TEXT NOT NULL
);
INSERT INTO preview(preview_header, preview_text) VALUES ('Preview Header One', '"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.");
INSERT INTO preview(preview_header, preview_text) VALUES ('Preview Header Two', '"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.");
INSERT INTO preview(preview_header, preview_text) VALUES ('Preview Header Three', '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
INSERT INTO preview(preview_header, preview_text) VALUES ('Preview Header Four', '"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" );
INSERT INTO preview(preview_header, preview_text) VALUES ('Preview Header Five', '"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?");
INSERT INTO preview(preview_header, preview_text) VALUES ('Preview Header Six', '"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.");
CREATE TABLE article
(
article_id SERIAL PRIMARY KEY NOT NULL,
article_header VARCHAR(90) NOT NULL,
article_text TEXT NOT NULL
);
SELECT * FROM article;
INSERT INTO article(article_header, article_text) VALUES ('Article Header One', '"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.");
INSERT INTO article(article_header, article_text) VALUES ('Article Header Two', '"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.");
INSERT INTO article(article_header, article_text) VALUES ('Article Header Three', '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
INSERT INTO article(article_header, article_text) VALUES ('Article Header Four', '"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?");
INSERT INTO article(article_header, article_text) VALUES ('Article Header Five', '"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?");
INSERT INTO article(article_header, article_text) VALUES ('Article Header Six', '"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.");
CREATE TABLE review
(
review_id SERIAL PRIMARY KEY NOT NULL,
review_header VARCHAR(90) NOT NULL,
review_text TEXT NOT NULL
);
INSERT INTO review(review_header, review_text) VALUES ('Preview Header One', '"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains." );
INSERT INTO review(review_header, review_text) VALUES ('Preview Header Two', '"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.");
INSERT INTO review(review_header, review_text) VALUES ('Preview Header Three', '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." );
INSERT INTO review(review_header, review_text) VALUES ('Preview Header Four', '"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?");
INSERT INTO review(review_header, review_text) VALUES ('Preview Header Five', '"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" );
INSERT INTO review(review_header, review_text) VALUES ('Preview Header Six', '"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.");
The desired result will be a single full row from any one these tables. So each row has a fair chance at been the winner
If tables has similar structure just use UNION ALL
SELECT *,
row_number() over (order by newid()) as seqnum
FROM ( SELECT preview.* FROM preview
UNION ALL
SELECT review.* FROM review
) T
if doesnt have similar structure you need to do some tricks to make the union with same number of columns.
SELECT *,
row_number() over (order by newid()) as seqnum
FROM ( SELECT 'preview' as `source`, p.field1, p.field2, null , null
FROM preview P
UNION ALL
SELECT 'review' as `source`, null , null , r.field1, r.field2
FROM review R
) T
EDIT: for you new request
SELECT *, row_number() over (order by random()) as seqnum
FROM (SELECT 'preview' as `source`, preview_id as winning_id
FROM `preview`
UNION ALL
SELECT 'article' as `source`, article_id
FROM `preview`
UNION ALL
SELECT 'review' as `source`, review_id
FROM `preview`
) T
--LIMIT 1;

Kivy ScrollView for paragraphs of text

I am unable to get ScrollView in Kivy to scroll through paragraphs of text. I have attached a code example below. Can anyone state what is wrong? Thank you.
import kivy
import string
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
class longTextLabelApp(App):
def build(self):
scrollViewLayout = ScrollView(do_scroll_x=False)
childLayout = GridLayout(cols = 1, size_hint_x = 1, size_hint_y = None)
childLayout.bind(minimum_height=childLayout.setter('height'))
def longTextLabel():
_long_text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus odio nisi, pellentesque molestie adipiscing vitae, aliquam at tellus. Fusce quis est ornare erat pulvinar elementum ut sed felis. Donec vel neque mauris. In sit amet nunc sit amet diam dapibus lacinia. In sodales placerat mauris, ut euismod augue laoreet at. Integer in neque non odio fermentum volutpat nec nec nulla. Donec et risus non mi viverra posuere. Phasellus cursus augue purus, eget volutpat leo. Phasellus sed dui vitae ipsum mattis facilisis vehicula eu justo.
Quisque neque dolor, egestas sed venenatis eget, porta id ipsum. Ut faucibus, massa vitae imperdiet rutrum, sem dolor rhoncus magna, non lacinia nulla risus non dui. Nulla sit amet risus orci. Nunc libero justo, interdum eu pulvinar vel, pulvinar et lectus. Phasellus sed luctus diam. Pellentesque non feugiat dolor. Cras at dolor velit, gravida congue velit. Aliquam erat volutpat. Nullam eu nunc dui, quis sagittis dolor. Ut nec dui eget odio pulvinar placerat. Pellentesque mi metus, tristique et placerat ac, pulvinar vel quam. Nam blandit magna a urna imperdiet molestie. Nullam ut nisi eget enim laoreet sodales sit amet a felis.
"""
reallyLongText = _long_text + _long_text + _long_text + _long_text +_long_text
myLabel = Label(text = reallyLongText, text_size = (700,None), line_height=1.5)
return myLabel
childLayout.add_widget(longTextLabel())
scrollViewLayout.add_widget(childLayout)
return scrollViewLayout
if __name__ == '__main__':
longTextLabelApp().run()
The default size of a Label (and Widget) is (100,100). It doesn't matter if you are seeing all the text on the screen. If you print myLabel.size you will realize of this. You need to be sure to set the height of the Label (myLabel.height: 2200) but first set the size_hint_y to None first (myLabel.size_hint_y=None). The following code should work:
import kivy
import string
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.graphics import Rectangle, Color
class longTextLabelApp(App):
def build(self):
scrollViewLayout = ScrollView(do_scroll_x=False)
childLayout = GridLayout(cols = 1, size_hint_x = 1, size_hint_y = None)
childLayout.bind(minimum_height=childLayout.setter('height'))
def longTextLabel():
_long_text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus odio nisi, pellentesque molestie adipiscing vitae, aliquam at tellus. Fusce quis est ornare erat pulvinar elementum ut sed felis. Donec vel neque mauris. In sit amet nunc sit amet diam dapibus lacinia. In sodales placerat mauris, ut euismod augue laoreet at. Integer in neque non odio fermentum volutpat nec nec nulla. Donec et risus non mi viverra posuere. Phasellus cursus augue purus, eget volutpat leo. Phasellus sed dui vitae ipsum mattis facilisis vehicula eu justo.
Quisque neque dolor, egestas sed venenatis eget, porta id ipsum. Ut faucibus, massa vitae imperdiet rutrum, sem dolor rhoncus magna, non lacinia nulla risus non dui. Nulla sit amet risus orci. Nunc libero justo, interdum eu pulvinar vel, pulvinar et lectus. Phasellus sed luctus diam. Pellentesque non feugiat dolor. Cras at dolor velit, gravida congue velit. Aliquam erat volutpat. Nullam eu nunc dui, quis sagittis dolor. Ut nec dui eget odio pulvinar placerat. Pellentesque mi metus, tristique et placerat ac, pulvinar vel quam. Nam blandit magna a urna imperdiet molestie. Nullam ut nisi eget enim laoreet sodales sit amet a felis.
"""
reallyLongText = _long_text + _long_text + _long_text + _long_text +_long_text
myLabel = Label(text = reallyLongText, text_size = (700,None), line_height=1.5)
print "The label size is ", myLabel.size
myLabel.size_hint_y = None
myLabel.height = 2200
return myLabel
childLayout.add_widget(longTextLabel())
scrollViewLayout.add_widget(childLayout)
return scrollViewLayout
if __name__ == '__main__':
longTextLabelApp().run()
EDIT - RST Document
Depending on your objectives it might be better to use a RSTDocument. Label are just that, labels. They don't adjust to content or text. Think of them as stickers. The (RSTDocment)[http://kivy.org/docs/api-kivy.uix.rst.html], still indicated as highly experimental though is more suitable for long texts, specially if they are dynamic. They actually includes the Scroll.
from kivy.app import App
from kivy.uix.rst import RstDocument
class RstDocumentApp(App):
def build(self):
_long_text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus odio nisi, pellentesque molestie adipiscing vitae, aliquam at tellus. Fusce quis est ornare erat pulvinar elementum ut sed felis. Donec vel neque mauris. In sit amet nunc sit amet diam dapibus lacinia. In sodales placerat mauris, ut euismod augue laoreet at. Integer in neque non odio fermentum volutpat nec nec nulla. Donec et risus non mi viverra posuere. Phasellus cursus augue purus, eget volutpat leo. Phasellus sed dui vitae ipsum mattis facilisis vehicula eu justo.
Quisque neque dolor, egestas sed venenatis eget, porta id ipsum. Ut faucibus, massa vitae imperdiet rutrum, sem dolor rhoncus magna, non lacinia nulla risus non dui. Nulla sit amet risus orci. Nunc libero justo, interdum eu pulvinar vel, pulvinar et lectus. Phasellus sed luctus diam. Pellentesque non feugiat dolor. Cras at dolor velit, gravida congue velit. Aliquam erat volutpat. Nullam eu nunc dui, quis sagittis dolor. Ut nec dui eget odio pulvinar placerat. Pellentesque mi metus, tristique et placerat ac, pulvinar vel quam. Nam blandit magna a urna imperdiet molestie. Nullam ut nisi eget enim laoreet sodales sit amet a felis.
"""
reallyLongText = _long_text + _long_text + _long_text + _long_text +_long_text
return RstDocument(text = reallyLongText)
if __name__ == '__main__':
RstDocumentApp().run()
You can set the Label to be of the size of the texture inside it like this.
FloatLayout:
Label:
# adding a background to see the amount of space the label takes
canvas.before:
Color:
rgba: .5, .5, .5, .5
Rectangle:
size: self.size
pos: self.pos
text: "How can the only thing constant in the universe be `change` when\nchange itself is by it's very nature `not constant`?"
pos_hint: {'center_x': .5, 'center_y': .5}
size_hint: None, None
size: self.texture_size
However with this you would only get a label that just expands how much text is in it and would require you to add \n yourself to make it wrap. A better approach would be to let the text inside the label auto wrap at a certain width by setting text_size something like the following::
FloatLayout:
ScrollView:
# take half of parents size
size_hint: .5, .5
pos_hint: {'center_x': .5, 'center_y': .5}
Label:
canvas.before:
Color:
rgba: .5, .5, .5, .5
Rectangle:
size: self.size
pos: self.pos
text: "\n1. Two hunters are out in the woods when one of them collapses. He doesn't seem to be breathing and his eyes are glazed. The other guy whips out his phone and calls the emergency services. He gasps, `My friend is dead! What can I do?`\n\n The operator says `Calm down. I can help. First, let's make sure he's dead.`\n\n There is a silence, then a gun shot is heard. Back on the phone, the guy says `OK, now what?`\n\n\n2. Sherlock Holmes and Dr Watson were going camping. They pitched their tent under the stars and went to sleep. Sometime in the middle of the night Holmes woke Watson up and said:\n\n `Watson, look up at the sky, and tell me what you see.`\n\n Watson replied: `I see millions and millions of stars.`\n\n Holmes said: `And what do you deduce from that?`\n\n Watson replied: `Well, if there are millions of stars, and if even a few of those have planets, it’s quite likely there are some planets like Earth out there. And if there are a few planets like Earth out there, there might also be life.`\n\n And Holmes said: `Watson, you idiot, it means that somebody stole our tent.`\n\n\n3. Three women talk about their husband is performance as lovers.\n\nThe first woman says, `My husband is a marriage counselor, so he always buys me flowers and candy before we make love.`\n\nThe second woman says, `My husband is a motorcycle mechanic. He likes to play rough and use leather sometimes.`\n\nThe third woman shakes her head and says, `My husband works for an Internet company. He just sits on the edge of the bed and tells me how great it's going to be when I get it.` \n\n\n4. As within, so outside. Fractals equations show the possibility of having infinity within minutia. Each and every cell can be a image of the whole; merging the micro and the macro into one.\n"
pos_hint: {'center_x': .5, 'center_y': .5}
size_hint: 1, None
text_size: self.width, None
height: self.texture_size[1]