qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
186,111 | i have news site for about 7 months.
The site get new feeds every hour but google take about 1 day to index them and only few of them.
I see other sites that instantly index. "1 hours ago etc". Mine newest in google says "19 hours ago"+. And after some errors with sitemap, now i have 0 links last 2-3 days.
So, i wan't to share my configs and you tell me if something is wrong:
1. Feeds module import feeds every hour
2. cron runs every 3 hours
3. xmlsitemap sumbission time to search engines is every 3 hour
`I want to notice that i have arround 130.000 links. I have many feeds who import content. Maby are too much to index? idk`
So, what im doing wrong?
PS: Also, every time i submit xml sitemap, i must ping google? if yes, i ping home page or xmlsitemap? | 2016/01/08 | [
"https://drupal.stackexchange.com/questions/186111",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/55773/"
] | The indexing you are having is moderate / typical indeed. Only a small percentage of sites (from the 100% existing in the web right now) are being indexed every hour or so (some sites are indexed once smaller times like 20 minutes or even less - Wikipedia for example could be indexed in 10 minutes or less in some cases).
You should use various Drupal modules to raise the both PageRank and PQS (Page quality score) of your sites pages.
Use wisely the modules [MetaTag](https://www.drupal.org/project/metatag), [AdvAgg](https://www.drupal.org/project/advagg), [xml sitemap](https://www.drupal.org/project/xmlsitemap), [pathauto](https://www.drupal.org/project/pathauto), [search404](https://www.drupal.org/project/search404), [redirect](https://www.drupal.org/project/redirect) and others to insure you achieve that targets.
More ways to handle that many 404's - Either your could redirect all the nodes to the homepage or groups of them to some nodes with suitable context). Moreover, if you have the spare timenergy or resources you could make redirects to NID's 1x1 for all or most of your links. You could also delete some via WMT and than via robots.txt. It is recommended by some to make redirects not in Drupal but rather directly in the main .htaccess file for better performance. | If the site is largely linking back out to other sites, you may be appearing to be a link-farm and Google isn't going to re-index frequently.
If you have good reasons to be pulling lots of feeds with broken links in them I recommend adding a process that checks the new links before making them public. It'll make your users happier as well as Google. |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | You can use `lapply` to extract the three columns named `"Col1` in one go. Then set the names of the result.
```
col1 <- as.data.frame(lapply(df, '[[', "Col1"))
names(col1) <- letters[seq_along(col1)]
col1
# a b c
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
```
Choose any other column names that you might find better.
A `dplyr` way could be
```
df %>%
unlist(recursive = FALSE) %>%
as.data.frame %>%
select(., starts_with("Col1"))
# Col1 Col1.1 Col1.2
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
``` | ```
res<-1:nrow(df[[1]][1])
for(i in 1:length(df)){
print ( as.vector(df[[i]][1]))
res<-cbind(res,as.data.frame(df[[i]][1]))
}
res$res<-NULL
```
So, the output is:
```
Col1 Col1 Col1
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | With `map_dfc` from `purrr`:
```
library(purrr)
map_dfc(df, `[`, 1)
```
**Output:**
```
Col1 Col11 Col12
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` | ```
res<-1:nrow(df[[1]][1])
for(i in 1:length(df)){
print ( as.vector(df[[i]][1]))
res<-cbind(res,as.data.frame(df[[i]][1]))
}
res$res<-NULL
```
So, the output is:
```
Col1 Col1 Col1
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | ```
res<-1:nrow(df[[1]][1])
for(i in 1:length(df)){
print ( as.vector(df[[i]][1]))
res<-cbind(res,as.data.frame(df[[i]][1]))
}
res$res<-NULL
```
So, the output is:
```
Col1 Col1 Col1
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` | Using `dplyr`
```
library(dplyr)
df %>%
sapply('[[',1) %>%
as.data.frame
#returns
V1 V2 V3
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | Alternative use of `map_dfc` making use of `purrr`'s concise element extraction syntax that allows specifying elements of elements by name or position. The first is, for example, equivalent to
```
map_dfc(df, `[[`, 1)
```
which differs from the use of `[` in that the columns will not be named variations of `Col1` and just get `V` names instead, which may be desirable since names like `Col11` and `Col12` may be confusing.
```r
df <- list(structure(list(Col1 = structure(1:6, .Label = c("A", "B", "C", "D", "E", "F"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 5L, 6L, 2L, 3L), .Label = c("A", "E", "H", "M", "N", "P"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 6L, 5L, 2L, 3L), .Label = c("A", "W", "H", "M", "T", "U"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "S", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)))
library(purrr)
map_dfc(df, 1)
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
map_dfc(df, "Col1")
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
```
Created on 2018-09-19 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). | ```
res<-1:nrow(df[[1]][1])
for(i in 1:length(df)){
print ( as.vector(df[[i]][1]))
res<-cbind(res,as.data.frame(df[[i]][1]))
}
res$res<-NULL
```
So, the output is:
```
Col1 Col1 Col1
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | You can use `lapply` to extract the three columns named `"Col1` in one go. Then set the names of the result.
```
col1 <- as.data.frame(lapply(df, '[[', "Col1"))
names(col1) <- letters[seq_along(col1)]
col1
# a b c
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
```
Choose any other column names that you might find better.
A `dplyr` way could be
```
df %>%
unlist(recursive = FALSE) %>%
as.data.frame %>%
select(., starts_with("Col1"))
# Col1 Col1.1 Col1.2
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
``` | With `map_dfc` from `purrr`:
```
library(purrr)
map_dfc(df, `[`, 1)
```
**Output:**
```
Col1 Col11 Col12
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | You can use `lapply` to extract the three columns named `"Col1` in one go. Then set the names of the result.
```
col1 <- as.data.frame(lapply(df, '[[', "Col1"))
names(col1) <- letters[seq_along(col1)]
col1
# a b c
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
```
Choose any other column names that you might find better.
A `dplyr` way could be
```
df %>%
unlist(recursive = FALSE) %>%
as.data.frame %>%
select(., starts_with("Col1"))
# Col1 Col1.1 Col1.2
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
``` | Using `dplyr`
```
library(dplyr)
df %>%
sapply('[[',1) %>%
as.data.frame
#returns
V1 V2 V3
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | You can use `lapply` to extract the three columns named `"Col1` in one go. Then set the names of the result.
```
col1 <- as.data.frame(lapply(df, '[[', "Col1"))
names(col1) <- letters[seq_along(col1)]
col1
# a b c
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
```
Choose any other column names that you might find better.
A `dplyr` way could be
```
df %>%
unlist(recursive = FALSE) %>%
as.data.frame %>%
select(., starts_with("Col1"))
# Col1 Col1.1 Col1.2
#1 A A A
#2 B M M
#3 C N U
#4 D P T
#5 E E W
#6 F H H
``` | Alternative use of `map_dfc` making use of `purrr`'s concise element extraction syntax that allows specifying elements of elements by name or position. The first is, for example, equivalent to
```
map_dfc(df, `[[`, 1)
```
which differs from the use of `[` in that the columns will not be named variations of `Col1` and just get `V` names instead, which may be desirable since names like `Col11` and `Col12` may be confusing.
```r
df <- list(structure(list(Col1 = structure(1:6, .Label = c("A", "B", "C", "D", "E", "F"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 5L, 6L, 2L, 3L), .Label = c("A", "E", "H", "M", "N", "P"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 6L, 5L, 2L, 3L), .Label = c("A", "W", "H", "M", "T", "U"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "S", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)))
library(purrr)
map_dfc(df, 1)
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
map_dfc(df, "Col1")
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
```
Created on 2018-09-19 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | With `map_dfc` from `purrr`:
```
library(purrr)
map_dfc(df, `[`, 1)
```
**Output:**
```
Col1 Col11 Col12
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` | Using `dplyr`
```
library(dplyr)
df %>%
sapply('[[',1) %>%
as.data.frame
#returns
V1 V2 V3
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | With `map_dfc` from `purrr`:
```
library(purrr)
map_dfc(df, `[`, 1)
```
**Output:**
```
Col1 Col11 Col12
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` | Alternative use of `map_dfc` making use of `purrr`'s concise element extraction syntax that allows specifying elements of elements by name or position. The first is, for example, equivalent to
```
map_dfc(df, `[[`, 1)
```
which differs from the use of `[` in that the columns will not be named variations of `Col1` and just get `V` names instead, which may be desirable since names like `Col11` and `Col12` may be confusing.
```r
df <- list(structure(list(Col1 = structure(1:6, .Label = c("A", "B", "C", "D", "E", "F"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 5L, 6L, 2L, 3L), .Label = c("A", "E", "H", "M", "N", "P"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 6L, 5L, 2L, 3L), .Label = c("A", "W", "H", "M", "T", "U"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "S", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)))
library(purrr)
map_dfc(df, 1)
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
map_dfc(df, "Col1")
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
```
Created on 2018-09-19 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). |
52,411,739 | I have entities where one field has an one-to-many relationship.
It looks like this.
```
@Entity
@Table(name = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "short_name", nullable = false)
private String shortName;
@NotNull
@Column(name = "customer_number", nullable = false)
private String customerNumber;
@OneToMany(mappedBy = “company”)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<BusinessType> businessTypes = new HashSet<>();
… getters setters
}
@Entity
@Table(name = “business_type")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BusinessType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private BType type;
@ManyToOne(optional = false)
@NotNull
@JsonIgnore
private Company company;
… getters setters
}
public enum BType {
TYPE1, TYPE2, TYPE3
}
```
The database tables look like this:
**company(id, name, short\_name, customer\_number)**
**business\_type(id, type, company\_id)**
When I request a specific REST path I get the following JSON structure:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
“businessTypes" : null
}
```
But I'm expecting the following:
```
{
"id" : 1,
"name" : “Business name”,
"shortName" : "Business short name",
"customerNumber" : "1234",
"businessTypes" : [{
"id" : 1,
“type” : “TYPE1”
}]
}
```
Why is `businessTypes` `null` when the values are in the database?
What am I missing? | 2018/09/19 | [
"https://Stackoverflow.com/questions/52411739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9689221/"
] | Alternative use of `map_dfc` making use of `purrr`'s concise element extraction syntax that allows specifying elements of elements by name or position. The first is, for example, equivalent to
```
map_dfc(df, `[[`, 1)
```
which differs from the use of `[` in that the columns will not be named variations of `Col1` and just get `V` names instead, which may be desirable since names like `Col11` and `Col12` may be confusing.
```r
df <- list(structure(list(Col1 = structure(1:6, .Label = c("A", "B", "C", "D", "E", "F"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 5L, 6L, 2L, 3L), .Label = c("A", "E", "H", "M", "N", "P"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)), structure(list(Col1 = structure(c(1L, 4L, 6L, 5L, 2L, 3L), .Label = c("A", "W", "H", "M", "T", "U"), class = "factor"), Col2 = structure(c(1L, 2L, 3L, 2L, 4L, 5L), .Label = c("B", "C", "D", "S", "G"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)))
library(purrr)
map_dfc(df, 1)
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
map_dfc(df, "Col1")
#> # A tibble: 6 x 3
#> V1 V2 V3
#> <fct> <fct> <fct>
#> 1 A A A
#> 2 B M M
#> 3 C N U
#> 4 D P T
#> 5 E E W
#> 6 F H H
```
Created on 2018-09-19 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). | Using `dplyr`
```
library(dplyr)
df %>%
sapply('[[',1) %>%
as.data.frame
#returns
V1 V2 V3
1 A A A
2 B M M
3 C N U
4 D P T
5 E E W
6 F H H
``` |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | There is also ready to use [pyshadow](https://pypi.org/project/pyshadow/) pip module, which worked in my case, below example:
```
from pyshadow.main import Shadow
from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
shadow = Shadow(driver)
element = shadow.find_element("#Selector_level1")
element1 = shadow.find_element("#Selector_level2")
element2 = shadow.find_element("#Selector_level3")
element3 = shadow.find_element("#Selector_level4")
element4 = shadow.find_element("#Selector_level5")
element5 = shadow.find_element('#control-button') #target selector
element5.click()
``` | You can use the [`driver.executeScript()`](http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html#executeScript) method to access the HTML elements and JavaScript objects in your web page.
In the exemple below, `executeScript` will return in a `Promise` the Node List of all `<a>` elements present in the Shadow tree of element which `id` is `host`. Then you can perform you assertion test:
```
it( 'check shadow root content', function ()
{
return driver.executeScript( function ()
{
return host.shadowRoot.querySelectorAll( 'a' ).then( function ( n )
{
return expect( n ).to.have.length( 3 )
}
} )
} )
```
*Note:* I don't know Python so I've used the JavaScript syntax but it should work the same way. |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | There is also ready to use [pyshadow](https://pypi.org/project/pyshadow/) pip module, which worked in my case, below example:
```
from pyshadow.main import Shadow
from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
shadow = Shadow(driver)
element = shadow.find_element("#Selector_level1")
element1 = shadow.find_element("#Selector_level2")
element2 = shadow.find_element("#Selector_level3")
element3 = shadow.find_element("#Selector_level4")
element4 = shadow.find_element("#Selector_level5")
element5 = shadow.find_element('#control-button') #target selector
element5.click()
``` | I originally implemented Eduard's solution just slightly modified as a loop for simplicity. But when Chrome updated to 96.0.4664.45 selenium started returning a dict instead of a WebElement when calling `'return arguments[0].shadowRoot'`.
I did a little hacking around and found out I could get Selenium to return a WebElement by calling `return arguments[0].shadowRoot.querySelector("tag")`.
Here's what my final solution ended up looking like:
```
def get_balance_element(self):
# Loop through nested shadow root tags
tags = [
"tag2",
"tag3",
"tag4",
"tag5",
]
root = self.driver.find_element_by_tag_name("tag1")
for tag in tags:
root = self.expand_shadow_element(root, tag)
# Finally there. GOLD!
return [root]
def expand_shadow_element(self, element, tag):
shadow_root = self.driver.execute_script(
f'return arguments[0].shadowRoot.querySelector("{tag}")', element)
return shadow_root
```
Clean and simple, works for me.
Also, I could only get this working Selenium 3.141.0. 4.1 has a half baked shadow DOM implementation that just manages to break everything. |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | There is also ready to use [pyshadow](https://pypi.org/project/pyshadow/) pip module, which worked in my case, below example:
```
from pyshadow.main import Shadow
from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
shadow = Shadow(driver)
element = shadow.find_element("#Selector_level1")
element1 = shadow.find_element("#Selector_level2")
element2 = shadow.find_element("#Selector_level3")
element3 = shadow.find_element("#Selector_level4")
element4 = shadow.find_element("#Selector_level5")
element5 = shadow.find_element('#control-button') #target selector
element5.click()
``` | With selenium 4.1 there's a new attribute `shadow_root` for the [`WebElement`](https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement) class.
From the docs:
--------------
*Returns a shadow root of the element if there is one or an error. Only works from Chromium 96 onwards. Previous versions of Chromium based browsers will throw an assertion exception.*
*Returns:*
* *ShadowRoot object or*
* *NoSuchShadowRoot - if no shadow root was attached to element*
A [`ShadowRoot`](https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/webdriver/remote/shadowroot.html) object has the methods `find_element` and `find_elements` but they're currently limited to:
* By.ID
* By.CSS\_SELECTOR
* By.NAME
* By.CLASS\_NAME
Shadow roots and explicit waits
-------------------------------
You can also combine that with `WebdriverWait` and `expected_conditions` to obtain a decent behaviour. The only caveat is that you must use **EC** that accept `WebElement` objects. [At the moment](https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions) it's just one of the following ones:
* element\_selection\_state\_to\_be
* element\_to\_be\_clickable
* element\_to\_be\_selected
* invisibility\_of\_element
* staleness\_of
* visibility\_of
Example
-------
e.g. borrowing the example from [eduard-florinescu](https://stackoverflow.com/users/1577343/eduard-florinescu)
```py
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome()
timeout = 10
driver.get("chrome://settings")
root1 = driver.find_element_by_tag_name('settings-ui')
shadow_root1 = root1.shadow_root
root2 = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1.find_element(by=By.CSS_SELECTOR, value='[page-name="Settings"]')))
shadow_root2 = root2.shadow_root
root3 = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root2.find_element(by=By.ID, value='search')))
shadow_root3 = root3.shadow_root
search_button = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root3.find_element(by=By.ID, value="searchTerm")))
search_button.click()
text_area = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root3.find_element(by=By.ID, value='searchInput')))
text_area.send_keys("content settings")
root0 = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1.find_element(by=By.ID, value='main')))
shadow_root0_s = root0.shadow_root
root1_p = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root0_s.find_element(by=By.CSS_SELECTOR, value='settings-basic-page')))
shadow_root1_p = root1_p.shadow_root
root1_s = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1_p.find_element(by=By.CSS_SELECTOR, value='settings-privacy-page')))
shadow_root1_s = root1_s.shadow_root
content_settings_div = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1_s.find_element(by=By.CSS_SELECTOR, value='#site-settings-subpage-trigger')))
content_settings = WebDriverWait(driver, timeout).until(EC.visibility_of(content_settings_div.find_element(by=By.CSS_SELECTOR, value="button")))
content_settings.click()
``` |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | There is also ready to use [pyshadow](https://pypi.org/project/pyshadow/) pip module, which worked in my case, below example:
```
from pyshadow.main import Shadow
from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
shadow = Shadow(driver)
element = shadow.find_element("#Selector_level1")
element1 = shadow.find_element("#Selector_level2")
element2 = shadow.find_element("#Selector_level3")
element3 = shadow.find_element("#Selector_level4")
element4 = shadow.find_element("#Selector_level5")
element5 = shadow.find_element('#control-button') #target selector
element5.click()
``` | The ***downloaded*** items by [google-chrome](/questions/tagged/google-chrome "show questions tagged 'google-chrome'") are within multiple [#shadow-root (open)](https://stackoverflow.com/questions/56380091/how-to-locate-the-shadow-root-open-elements-through-cssselector).

---
Solution
--------
To extract the contents of the table you have to use [`shadowRoot.querySelector()`](https://stackoverflow.com/questions/55761810/how-to-automate-shadow-dom-elements-using-selenium/55763793#55763793) and you can use the following [locator strategy](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Code Block:
```
driver = webdriver.Chrome(service=s, options=options)
driver.execute("get", {'url': 'chrome://downloads/'})
time.sleep(5)
download = driver.execute_script("""return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.querySelector('a#file-link')""")
print(download.text)
``` |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | You can use the [`driver.executeScript()`](http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html#executeScript) method to access the HTML elements and JavaScript objects in your web page.
In the exemple below, `executeScript` will return in a `Promise` the Node List of all `<a>` elements present in the Shadow tree of element which `id` is `host`. Then you can perform you assertion test:
```
it( 'check shadow root content', function ()
{
return driver.executeScript( function ()
{
return host.shadowRoot.querySelectorAll( 'a' ).then( function ( n )
{
return expect( n ).to.have.length( 3 )
}
} )
} )
```
*Note:* I don't know Python so I've used the JavaScript syntax but it should work the same way. | The ***downloaded*** items by [google-chrome](/questions/tagged/google-chrome "show questions tagged 'google-chrome'") are within multiple [#shadow-root (open)](https://stackoverflow.com/questions/56380091/how-to-locate-the-shadow-root-open-elements-through-cssselector).

---
Solution
--------
To extract the contents of the table you have to use [`shadowRoot.querySelector()`](https://stackoverflow.com/questions/55761810/how-to-automate-shadow-dom-elements-using-selenium/55763793#55763793) and you can use the following [locator strategy](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Code Block:
```
driver = webdriver.Chrome(service=s, options=options)
driver.execute("get", {'url': 'chrome://downloads/'})
time.sleep(5)
download = driver.execute_script("""return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.querySelector('a#file-link')""")
print(download.text)
``` |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | I would add this as a comment but I don't have enough reputation points--
The answers by Eduard Florinescu works well with the caveat that once you're inside a shadowRoot, you only have the selenium methods available that correspond to the available JS methods--mainly select by id.
To get around this I wrote a longer JS function in a python string and used native JS methods and attributes (find by id, children + indexing etc.) to get the element I ultimately needed.
You can use this method to also access shadowRoots of child elements and so on when the JS string is run using driver.execute\_script() | The ***downloaded*** items by [google-chrome](/questions/tagged/google-chrome "show questions tagged 'google-chrome'") are within multiple [#shadow-root (open)](https://stackoverflow.com/questions/56380091/how-to-locate-the-shadow-root-open-elements-through-cssselector).

---
Solution
--------
To extract the contents of the table you have to use [`shadowRoot.querySelector()`](https://stackoverflow.com/questions/55761810/how-to-automate-shadow-dom-elements-using-selenium/55763793#55763793) and you can use the following [locator strategy](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Code Block:
```
driver = webdriver.Chrome(service=s, options=options)
driver.execute("get", {'url': 'chrome://downloads/'})
time.sleep(5)
download = driver.execute_script("""return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.querySelector('a#file-link')""")
print(download.text)
``` |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | Sometimes the shadow root elements are nested and the second shadow root is not visible in document root, but is available in its parent accessed shadow root. I think is better to use the selenium selectors and inject the script just to take the shadow root:
```
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
outer = expand_shadow_element(driver.find_element_by_css_selector("#test_button"))
inner = outer.find_element_by_id("inner_button")
inner.click()
```
To put this into perspective I just added a testable example with Chrome's download page, clicking the search button needs open 3 nested shadow root elements:
[](https://i.stack.imgur.com/jRtdz.png)
```
import selenium
from selenium import webdriver
driver = webdriver.Chrome()
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
driver.get("chrome://downloads")
root1 = driver.find_element_by_tag_name('downloads-manager')
shadow_root1 = expand_shadow_element(root1)
root2 = shadow_root1.find_element_by_css_selector('downloads-toolbar')
shadow_root2 = expand_shadow_element(root2)
root3 = shadow_root2.find_element_by_css_selector('cr-search-field')
shadow_root3 = expand_shadow_element(root3)
search_button = shadow_root3.find_element_by_css_selector("#search-button")
search_button.click()
```
Doing the same approach suggested in the other answers has the drawback that it hard-codes the queries, is less readable and you cannot use the intermediary selections for other actions:
```
search_button = driver.execute_script('return document.querySelector("downloads-manager").shadowRoot.querySelector("downloads-toolbar").shadowRoot.querySelector("cr-search-field").shadowRoot.querySelector("#search-button")')
search_button.click()
```
later edit:
-----------
I recently try to access the content settings(see code below) and it has more than one shadow root elements imbricated now you cannot access one without first expanding the other, when you usually have also dynamic content and more than 3 shadow elements one into another it makes impossible automation. The answer above use to work a few time ago but is enough for just one element to change position and you need to always go with inspect element an ho up the tree an see if it is in a shadow root, automation nightmare.
Not only was hard to find just the content settings due to the shadowroots and dynamic change when you find the button is not clickable at this point.
```
driver = webdriver.Chrome()
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
driver.get("chrome://settings")
root1 = driver.find_element_by_tag_name('settings-ui')
shadow_root1 = expand_shadow_element(root1)
root2 = shadow_root1.find_element_by_css_selector('[page-name="Settings"]')
shadow_root2 = expand_shadow_element(root2)
root3 = shadow_root2.find_element_by_id('search')
shadow_root3 = expand_shadow_element(root3)
search_button = shadow_root3.find_element_by_id("searchTerm")
search_button.click()
text_area = shadow_root3.find_element_by_id('searchInput')
text_area.send_keys("content settings")
root0 = shadow_root1.find_element_by_id('main')
shadow_root0_s = expand_shadow_element(root0)
root1_p = shadow_root0_s.find_element_by_css_selector('settings-basic-page')
shadow_root1_p = expand_shadow_element(root1_p)
root1_s = shadow_root1_p.find_element_by_css_selector('settings-privacy-page')
shadow_root1_s = expand_shadow_element(root1_s)
content_settings_div = shadow_root1_s.find_element_by_css_selector('#site-settings-subpage-trigger')
content_settings = content_settings_div.find_element_by_css_selector("button")
content_settings.click()
``` | You can use the [`driver.executeScript()`](http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html#executeScript) method to access the HTML elements and JavaScript objects in your web page.
In the exemple below, `executeScript` will return in a `Promise` the Node List of all `<a>` elements present in the Shadow tree of element which `id` is `host`. Then you can perform you assertion test:
```
it( 'check shadow root content', function ()
{
return driver.executeScript( function ()
{
return host.shadowRoot.querySelectorAll( 'a' ).then( function ( n )
{
return expect( n ).to.have.length( 3 )
}
} )
} )
```
*Note:* I don't know Python so I've used the JavaScript syntax but it should work the same way. |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | Sometimes the shadow root elements are nested and the second shadow root is not visible in document root, but is available in its parent accessed shadow root. I think is better to use the selenium selectors and inject the script just to take the shadow root:
```
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
outer = expand_shadow_element(driver.find_element_by_css_selector("#test_button"))
inner = outer.find_element_by_id("inner_button")
inner.click()
```
To put this into perspective I just added a testable example with Chrome's download page, clicking the search button needs open 3 nested shadow root elements:
[](https://i.stack.imgur.com/jRtdz.png)
```
import selenium
from selenium import webdriver
driver = webdriver.Chrome()
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
driver.get("chrome://downloads")
root1 = driver.find_element_by_tag_name('downloads-manager')
shadow_root1 = expand_shadow_element(root1)
root2 = shadow_root1.find_element_by_css_selector('downloads-toolbar')
shadow_root2 = expand_shadow_element(root2)
root3 = shadow_root2.find_element_by_css_selector('cr-search-field')
shadow_root3 = expand_shadow_element(root3)
search_button = shadow_root3.find_element_by_css_selector("#search-button")
search_button.click()
```
Doing the same approach suggested in the other answers has the drawback that it hard-codes the queries, is less readable and you cannot use the intermediary selections for other actions:
```
search_button = driver.execute_script('return document.querySelector("downloads-manager").shadowRoot.querySelector("downloads-toolbar").shadowRoot.querySelector("cr-search-field").shadowRoot.querySelector("#search-button")')
search_button.click()
```
later edit:
-----------
I recently try to access the content settings(see code below) and it has more than one shadow root elements imbricated now you cannot access one without first expanding the other, when you usually have also dynamic content and more than 3 shadow elements one into another it makes impossible automation. The answer above use to work a few time ago but is enough for just one element to change position and you need to always go with inspect element an ho up the tree an see if it is in a shadow root, automation nightmare.
Not only was hard to find just the content settings due to the shadowroots and dynamic change when you find the button is not clickable at this point.
```
driver = webdriver.Chrome()
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
driver.get("chrome://settings")
root1 = driver.find_element_by_tag_name('settings-ui')
shadow_root1 = expand_shadow_element(root1)
root2 = shadow_root1.find_element_by_css_selector('[page-name="Settings"]')
shadow_root2 = expand_shadow_element(root2)
root3 = shadow_root2.find_element_by_id('search')
shadow_root3 = expand_shadow_element(root3)
search_button = shadow_root3.find_element_by_id("searchTerm")
search_button.click()
text_area = shadow_root3.find_element_by_id('searchInput')
text_area.send_keys("content settings")
root0 = shadow_root1.find_element_by_id('main')
shadow_root0_s = expand_shadow_element(root0)
root1_p = shadow_root0_s.find_element_by_css_selector('settings-basic-page')
shadow_root1_p = expand_shadow_element(root1_p)
root1_s = shadow_root1_p.find_element_by_css_selector('settings-privacy-page')
shadow_root1_s = expand_shadow_element(root1_s)
content_settings_div = shadow_root1_s.find_element_by_css_selector('#site-settings-subpage-trigger')
content_settings = content_settings_div.find_element_by_css_selector("button")
content_settings.click()
``` | I originally implemented Eduard's solution just slightly modified as a loop for simplicity. But when Chrome updated to 96.0.4664.45 selenium started returning a dict instead of a WebElement when calling `'return arguments[0].shadowRoot'`.
I did a little hacking around and found out I could get Selenium to return a WebElement by calling `return arguments[0].shadowRoot.querySelector("tag")`.
Here's what my final solution ended up looking like:
```
def get_balance_element(self):
# Loop through nested shadow root tags
tags = [
"tag2",
"tag3",
"tag4",
"tag5",
]
root = self.driver.find_element_by_tag_name("tag1")
for tag in tags:
root = self.expand_shadow_element(root, tag)
# Finally there. GOLD!
return [root]
def expand_shadow_element(self, element, tag):
shadow_root = self.driver.execute_script(
f'return arguments[0].shadowRoot.querySelector("{tag}")', element)
return shadow_root
```
Clean and simple, works for me.
Also, I could only get this working Selenium 3.141.0. 4.1 has a half baked shadow DOM implementation that just manages to break everything. |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | With selenium 4.1 there's a new attribute `shadow_root` for the [`WebElement`](https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement) class.
From the docs:
--------------
*Returns a shadow root of the element if there is one or an error. Only works from Chromium 96 onwards. Previous versions of Chromium based browsers will throw an assertion exception.*
*Returns:*
* *ShadowRoot object or*
* *NoSuchShadowRoot - if no shadow root was attached to element*
A [`ShadowRoot`](https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/webdriver/remote/shadowroot.html) object has the methods `find_element` and `find_elements` but they're currently limited to:
* By.ID
* By.CSS\_SELECTOR
* By.NAME
* By.CLASS\_NAME
Shadow roots and explicit waits
-------------------------------
You can also combine that with `WebdriverWait` and `expected_conditions` to obtain a decent behaviour. The only caveat is that you must use **EC** that accept `WebElement` objects. [At the moment](https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions) it's just one of the following ones:
* element\_selection\_state\_to\_be
* element\_to\_be\_clickable
* element\_to\_be\_selected
* invisibility\_of\_element
* staleness\_of
* visibility\_of
Example
-------
e.g. borrowing the example from [eduard-florinescu](https://stackoverflow.com/users/1577343/eduard-florinescu)
```py
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome()
timeout = 10
driver.get("chrome://settings")
root1 = driver.find_element_by_tag_name('settings-ui')
shadow_root1 = root1.shadow_root
root2 = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1.find_element(by=By.CSS_SELECTOR, value='[page-name="Settings"]')))
shadow_root2 = root2.shadow_root
root3 = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root2.find_element(by=By.ID, value='search')))
shadow_root3 = root3.shadow_root
search_button = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root3.find_element(by=By.ID, value="searchTerm")))
search_button.click()
text_area = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root3.find_element(by=By.ID, value='searchInput')))
text_area.send_keys("content settings")
root0 = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1.find_element(by=By.ID, value='main')))
shadow_root0_s = root0.shadow_root
root1_p = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root0_s.find_element(by=By.CSS_SELECTOR, value='settings-basic-page')))
shadow_root1_p = root1_p.shadow_root
root1_s = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1_p.find_element(by=By.CSS_SELECTOR, value='settings-privacy-page')))
shadow_root1_s = root1_s.shadow_root
content_settings_div = WebDriverWait(driver, timeout).until(EC.visibility_of(shadow_root1_s.find_element(by=By.CSS_SELECTOR, value='#site-settings-subpage-trigger')))
content_settings = WebDriverWait(driver, timeout).until(EC.visibility_of(content_settings_div.find_element(by=By.CSS_SELECTOR, value="button")))
content_settings.click()
``` | I originally implemented Eduard's solution just slightly modified as a loop for simplicity. But when Chrome updated to 96.0.4664.45 selenium started returning a dict instead of a WebElement when calling `'return arguments[0].shadowRoot'`.
I did a little hacking around and found out I could get Selenium to return a WebElement by calling `return arguments[0].shadowRoot.querySelector("tag")`.
Here's what my final solution ended up looking like:
```
def get_balance_element(self):
# Loop through nested shadow root tags
tags = [
"tag2",
"tag3",
"tag4",
"tag5",
]
root = self.driver.find_element_by_tag_name("tag1")
for tag in tags:
root = self.expand_shadow_element(root, tag)
# Finally there. GOLD!
return [root]
def expand_shadow_element(self, element, tag):
shadow_root = self.driver.execute_script(
f'return arguments[0].shadowRoot.querySelector("{tag}")', element)
return shadow_root
```
Clean and simple, works for me.
Also, I could only get this working Selenium 3.141.0. 4.1 has a half baked shadow DOM implementation that just manages to break everything. |
37,384,460 | I can't figure out what's wrong with my index.html or main.css. I'm using Bootstrap with a custom stylesheet to add a few new things to my layout.
Anyways, I made a one-page website and all the menu items are going to the right section but only 1 link is going to another website, this link isn't working. If I right click it and click on open in a new tab it is working. But just clicking the menu item isn't possible.
Here is my navigation HTML:
```
<header id="header" role="banner">
<div class="container">
<div id="navbar" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#main-slider"><i class="icon-home"></i></a>
</li>
<li><a href="#services">Services</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#gallery">Gallery</a>
</li>
<li><a href="#brands">Brands</a>
</li>
<li><a href="#hours">Hours</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="http://stores.ebay.com/scactionsportsLLC">Store</a>
</li>
</ul>
</div>
</div>
</div>
</header>
```
Here is my navigation CSS:
```
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
z-index: 99999;
}
.navbar-default {
background: #fff;
border-radius: 0 0 5px 5px;
border: 0;
padding: 0;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2);
overflow: hidden;
}
.navbar-default .first a {
border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
margin-right: 50px;
margin-left: 20px;
width: 200px;
height: 78px;
background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
margin-left: 1px;
}
.navbar-default .navbar-nav > li > a {
padding: 30px 25px;
font-size: 16px;
line-height: 18px;
color: #999;
}
.navbar-default .navbar-nav > li > a > i {
display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
background-color: #f57e20;
color: #fff;
}
```
Here is a fiddle:
<https://jsfiddle.net/jh6ufp75/3/>
Is someone able to help me out with this problem?
Thanks a lot!
Kind regards. | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997179/"
] | Sometimes the shadow root elements are nested and the second shadow root is not visible in document root, but is available in its parent accessed shadow root. I think is better to use the selenium selectors and inject the script just to take the shadow root:
```
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
outer = expand_shadow_element(driver.find_element_by_css_selector("#test_button"))
inner = outer.find_element_by_id("inner_button")
inner.click()
```
To put this into perspective I just added a testable example with Chrome's download page, clicking the search button needs open 3 nested shadow root elements:
[](https://i.stack.imgur.com/jRtdz.png)
```
import selenium
from selenium import webdriver
driver = webdriver.Chrome()
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
driver.get("chrome://downloads")
root1 = driver.find_element_by_tag_name('downloads-manager')
shadow_root1 = expand_shadow_element(root1)
root2 = shadow_root1.find_element_by_css_selector('downloads-toolbar')
shadow_root2 = expand_shadow_element(root2)
root3 = shadow_root2.find_element_by_css_selector('cr-search-field')
shadow_root3 = expand_shadow_element(root3)
search_button = shadow_root3.find_element_by_css_selector("#search-button")
search_button.click()
```
Doing the same approach suggested in the other answers has the drawback that it hard-codes the queries, is less readable and you cannot use the intermediary selections for other actions:
```
search_button = driver.execute_script('return document.querySelector("downloads-manager").shadowRoot.querySelector("downloads-toolbar").shadowRoot.querySelector("cr-search-field").shadowRoot.querySelector("#search-button")')
search_button.click()
```
later edit:
-----------
I recently try to access the content settings(see code below) and it has more than one shadow root elements imbricated now you cannot access one without first expanding the other, when you usually have also dynamic content and more than 3 shadow elements one into another it makes impossible automation. The answer above use to work a few time ago but is enough for just one element to change position and you need to always go with inspect element an ho up the tree an see if it is in a shadow root, automation nightmare.
Not only was hard to find just the content settings due to the shadowroots and dynamic change when you find the button is not clickable at this point.
```
driver = webdriver.Chrome()
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
driver.get("chrome://settings")
root1 = driver.find_element_by_tag_name('settings-ui')
shadow_root1 = expand_shadow_element(root1)
root2 = shadow_root1.find_element_by_css_selector('[page-name="Settings"]')
shadow_root2 = expand_shadow_element(root2)
root3 = shadow_root2.find_element_by_id('search')
shadow_root3 = expand_shadow_element(root3)
search_button = shadow_root3.find_element_by_id("searchTerm")
search_button.click()
text_area = shadow_root3.find_element_by_id('searchInput')
text_area.send_keys("content settings")
root0 = shadow_root1.find_element_by_id('main')
shadow_root0_s = expand_shadow_element(root0)
root1_p = shadow_root0_s.find_element_by_css_selector('settings-basic-page')
shadow_root1_p = expand_shadow_element(root1_p)
root1_s = shadow_root1_p.find_element_by_css_selector('settings-privacy-page')
shadow_root1_s = expand_shadow_element(root1_s)
content_settings_div = shadow_root1_s.find_element_by_css_selector('#site-settings-subpage-trigger')
content_settings = content_settings_div.find_element_by_css_selector("button")
content_settings.click()
``` | There is also ready to use [pyshadow](https://pypi.org/project/pyshadow/) pip module, which worked in my case, below example:
```
from pyshadow.main import Shadow
from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
shadow = Shadow(driver)
element = shadow.find_element("#Selector_level1")
element1 = shadow.find_element("#Selector_level2")
element2 = shadow.find_element("#Selector_level3")
element3 = shadow.find_element("#Selector_level4")
element4 = shadow.find_element("#Selector_level5")
element5 = shadow.find_element('#control-button') #target selector
element5.click()
``` |
36,789,511 | I want my function to calculate the total cost of my shopping cart and then set the state of my component to those totals, but I need the calculation done first and then the state set after the calculations are complete. When I run the code below, the state never gets set.
```
renderCart: function() {
var newSubtotal = 0;
var newTotal = 0;
this.props.cart.map((product)=>{
newSubtotal += product.price;
newTotal += product.price;
newTotal *= 1.10;
console.log("New Total ", newTotal);
console.log("New Subtotal ", newSubtotal);
}, () => {
this.setState({
subtotal: newSubtotal,
total: newTotal
});
});
return (
<div>
<ul>
<li>Subtotal: ${this.state.subtotal}</li>
<li>Discount: {this.state.discount}%</li>
<li>Tax: {this.state.tax}%</li>
<li>Total: ${this.state.total}</li>
</ul>
<button className="success button">Pay</button>
</div>
);
}
});
``` | 2016/04/22 | [
"https://Stackoverflow.com/questions/36789511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264835/"
] | two points:
1. you should use .reduce function to calculate sum.
2. you should not use this.setState in your render(), I suggest ComponentDidMount or InitialState | Map is synchronous . Why you need setState, use variable enough.
```
renderCart: function() {
var newSubtotal = 0;
var newTotal = 0;
this.props.cart.map((product)=>{
newSubtotal += product.price;
newTotal += product.price;
newTotal *= 1.10;
console.log("New Total ", newTotal);
console.log("New Subtotal ", newSubtotal);
});
return (
<div>
<ul>
<li>Subtotal: ${newSubtotal}</li>
<li>Discount: {this.state.discount}%</li>
<li>Tax: {this.state.tax}%</li>
<li>Total: ${newTotal}</li>
</ul>
<button className="success button">Pay</button>
</div>
);
}
});
``` |
36,789,511 | I want my function to calculate the total cost of my shopping cart and then set the state of my component to those totals, but I need the calculation done first and then the state set after the calculations are complete. When I run the code below, the state never gets set.
```
renderCart: function() {
var newSubtotal = 0;
var newTotal = 0;
this.props.cart.map((product)=>{
newSubtotal += product.price;
newTotal += product.price;
newTotal *= 1.10;
console.log("New Total ", newTotal);
console.log("New Subtotal ", newSubtotal);
}, () => {
this.setState({
subtotal: newSubtotal,
total: newTotal
});
});
return (
<div>
<ul>
<li>Subtotal: ${this.state.subtotal}</li>
<li>Discount: {this.state.discount}%</li>
<li>Tax: {this.state.tax}%</li>
<li>Total: ${this.state.total}</li>
</ul>
<button className="success button">Pay</button>
</div>
);
}
});
``` | 2016/04/22 | [
"https://Stackoverflow.com/questions/36789511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264835/"
] | In pseudo code, the structure of your component should look more like:
```
MyCartTotalComponent => {
// no need for state: if your props contain cart, then every time cart changes
// your component gets new props, calculates total, and renders
render() {
// calculate stuff and store in local cart variable
var cart = {};
cart.total = this.props.cart.reduce(
function(prev,curr){
return prev + curr.price;
},0);
// render stuff
return (
<div>
...
<li>{cart.Total}</li>
...
</div>
);
}
}
``` | Map is synchronous . Why you need setState, use variable enough.
```
renderCart: function() {
var newSubtotal = 0;
var newTotal = 0;
this.props.cart.map((product)=>{
newSubtotal += product.price;
newTotal += product.price;
newTotal *= 1.10;
console.log("New Total ", newTotal);
console.log("New Subtotal ", newSubtotal);
});
return (
<div>
<ul>
<li>Subtotal: ${newSubtotal}</li>
<li>Discount: {this.state.discount}%</li>
<li>Tax: {this.state.tax}%</li>
<li>Total: ${newTotal}</li>
</ul>
<button className="success button">Pay</button>
</div>
);
}
});
``` |
36,789,511 | I want my function to calculate the total cost of my shopping cart and then set the state of my component to those totals, but I need the calculation done first and then the state set after the calculations are complete. When I run the code below, the state never gets set.
```
renderCart: function() {
var newSubtotal = 0;
var newTotal = 0;
this.props.cart.map((product)=>{
newSubtotal += product.price;
newTotal += product.price;
newTotal *= 1.10;
console.log("New Total ", newTotal);
console.log("New Subtotal ", newSubtotal);
}, () => {
this.setState({
subtotal: newSubtotal,
total: newTotal
});
});
return (
<div>
<ul>
<li>Subtotal: ${this.state.subtotal}</li>
<li>Discount: {this.state.discount}%</li>
<li>Tax: {this.state.tax}%</li>
<li>Total: ${this.state.total}</li>
</ul>
<button className="success button">Pay</button>
</div>
);
}
});
``` | 2016/04/22 | [
"https://Stackoverflow.com/questions/36789511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264835/"
] | In pseudo code, the structure of your component should look more like:
```
MyCartTotalComponent => {
// no need for state: if your props contain cart, then every time cart changes
// your component gets new props, calculates total, and renders
render() {
// calculate stuff and store in local cart variable
var cart = {};
cart.total = this.props.cart.reduce(
function(prev,curr){
return prev + curr.price;
},0);
// render stuff
return (
<div>
...
<li>{cart.Total}</li>
...
</div>
);
}
}
``` | two points:
1. you should use .reduce function to calculate sum.
2. you should not use this.setState in your render(), I suggest ComponentDidMount or InitialState |
13,870,213 | I'm using Autofill addon `https://addons.mozilla.org/pl/firefox/addon/autofill-262804/` and I want to fill my text field with random text from definied.
For example I want to fill `/* City */ city|town` field with one of the definied: `London, Paris, Amsterdam`
But I dont know how to do that.
The developer says:
>
> Variables – use special variables to output random words (text spinner), numbers, and alphanumeric characters
>
>
>
So it is possible.
Please help me.
edit
====
or maybe do you know any addon/method to autofill field with random text from definied | 2012/12/13 | [
"https://Stackoverflow.com/questions/13870213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743942/"
] | Despite putting a bounty on your question, I've managed to find the solution - I too had trouble finding it in the Google Groups pages and the dev's site, until I found his ["other" page](http://www.tohodo.com/autofill/help-firefox.html#other), which states:
Expand variables – If this box is checked, {...} will be replaced with the variable's output. There are currently three types of variables you can use:
```
{word1|word2|...} – This variable acts like a text spinner, randomly outputting one word from a list of words that you specify. Example: to output "house", "condo", "apartment", or "flat", you would enter {house|condo|apartment|flat}
{#} or {#number} – This variable outputs a random number. You can specify the number of digits after # ({#1} is equivalent to {#}). Example: to generate a random telephone number, you would enter ({#3}) {#3}-{#4}
{$} or {$number} – This variable outputs a random alphanumeric string. You can specify the number of characters after $ ({$1} is equivalent to {$}). Example: to generate a 16-character dummy text string, you would enter {$16}
```
So for example, in the value to autofill box for your element, putting:
```
{$6}@{$6}.com
```
would insert an email address of 6 random letters, followed by an @, then six random letters, followed by a .com. | Value to Autofill should be :
```
{London|Paris|Amsterdam}
``` |
42,995,973 | I am using template (**Full-text search via Algolia**) in Firebase Function.
[See here](https://github.com/firebase/functions-samples/tree/master/fulltext-search)
At the end of this link you will see > setting up the sample
Here it asks for algolia secret account and key. I have created account at Algolia when I go to my dashboard and select API KEYS then there are many keys.
Unable to know which one is account secret and which one is used as a key?
Please Indicate me secret account and key | 2017/03/24 | [
"https://Stackoverflow.com/questions/42995973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5737536/"
] | I believe the "secret" is what we call the "*Admin API key*" in the dashboard and the key must be the "*search only api key*". | The key is the id of your Algolia application.
The secret needs to be an API key that has read and write access (since the functions are doing both indexing and search). That can be your Admin API key or a specific API key you create with these permissions. |
3,505,739 | If two elliptic curves share the same j-invariant then they may not be isomorphic to each other over $\mathbb{Q}$.
Example:
>
> $E\_1: y^2 = x^3 + x$
>
>
> j-inavriat: $1728$
>
>
> Torsion points: $[(0 : 0 : 1), (0 : 1 : 0)]$
>
>
> Rank $0$.
>
>
>
$ $
>
> $E\_2: y^2 = x^3 + 3 x$
>
>
> j-inavriat: $1728$
>
>
> Torsion points: $[(0 : 0 : 1), (0 : 1 : 0)]$
>
>
> Rank $1$ - generator point $[(1 : 2 : 1)]$
>
>
>
**Is there some other invariant or can we define a new type of invariant that if two elliptic curves share the same such invariant then they are isomorphic over $\mathbb{Q}$?**
(they can be birationally transformed to each other over $\mathbb{Q}$) | 2020/01/12 | [
"https://math.stackexchange.com/questions/3505739",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/400836/"
] | You really don't need to use $L$-functions or representations. Let's work over a field $K$ of characteristic not equal to 2 or 3, so for example $K=\mathbb Q$. Then an elliptic curve $E/K$ always has a Weierstrass model
$$ E:y^2=x^3+Ax+B, $$
but the model is not unique. The $j$-invariant
$$ j(E) = 1728\cdot\frac{4A^3}{4A^3+27B^2} $$
classifies $E$ up to $\overline K$ isomorphism. You're interested in $K$-isomorphism. Assuming that $j(E)\ne0$ and $j(E)\ne1728$ (i.e., assume that $AB\ne0$), define a new invariant
$$ \gamma(E) = B/A \bmod{{K^\*}^2} \in K^\*/{K^\*}^2. $$
One can check that $\gamma(E)$ is well-defined modulo squares in $K$. Then
$$ \text{$E\cong E'$ over $K$}
\quad\Longleftrightarrow\quad
\text{$j(E)=j(E')$ and $\gamma(E)=\gamma(E')$.}
$$
If $j(E)=0$, then $A=0$ and there's a similar criterion in terms of $B$ modulo ${K^\*}^6$, and if $j(E)=1728$, then $B=0$ and there's a criterion in terms of $A$ modulo ${K^\*}^4$.
However, probably the right way to understand this is to use the fact that for a given $E/K$, the collection of $E'/K$ that are $\overline{K}$-isomorphic to $E$ are classified by the cohomology group
$$ H^1\bigl(\operatorname{Gal}(\overline K/K),\operatorname{Aut}(E)\bigr). $$
The three cases correspond to $\operatorname{Aut}(E)$ being $\mu\_2$, $\mu\_6$, and $\mu\_4$, respectively, and one knows (Hilbert Theorem 90) that
$$ H^1\bigl(\operatorname{Gal}(\overline K/K),\mu\_n\bigr)\cong K^\*/{K^\*}^n. $$
This unifies the three cases, and gives a quite general way to describe the $\overline{K}/K$-twists of an algebraic variety. | Since Silverman answered consider this as a comment, showing that it is a good thing to experiment with quadratic twists
* Given an elliptic curve $E/\Bbb{Q}$ we get an homomorphism $$\rho\_E: Gal(\overline{\Bbb{Q}}/\Bbb{Q})\to Aut(E\_{tors})$$
If $E$ is isomorphic to $E'$ over $\Bbb{Q}$ then $\rho\_{E'}= f \circ \rho\_E \circ f^{-1}$
* With $E:y^2=x^3+ax+b$, $E\_d : dy^2=x^3+ax+b$, $f(x,y)=(x,y/\sqrt{d})$ we get $$\rho\_{E\_d}(\sigma)= [\chi\_d(\sigma)]\circ f \circ \rho\_E(\sigma) \circ f^{-1}$$
where $\chi\_d(\sigma) = \frac{\sigma(\sqrt{d})}{\sqrt{d}}=\pm 1$ and $[-1](x,y)=(x,-y)$ commutes with $f,\rho\_E$.
>
> Thus $E\cong E\_d$ over $\Bbb{Q}$ iff $d\in (\Bbb{Q}^\*)^2$
>
>
>
And the so called quadratic twists $E\_d,d\in \Bbb{Q}^\*/(\Bbb{Q}^\*)^2$ are infinitely many pairwise distinct $\Bbb{Q}$-isomorphism classes of elliptic curves, they become isomorphic only over $\Bbb{Q}( \{ \sqrt{p}\})$.
This suggests that (in most cases...) a sufficient data determining the $\Bbb{Q}$-isomorphism class is the $j$-invariant plus the Galois module or the L-function. |
58,751,549 | I have a problem in my graduation project, I add Unity as a library to Android Studio it works fine with my mobile, but when I try on the other Android mobile I got some weird error (unable to load **libmain.so**), I search a lot but I didn't find the answer.
Note: there is no compile or build error, only when I click on the button(on android project) to go to Unity project. | 2019/11/07 | [
"https://Stackoverflow.com/questions/58751549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12107055/"
] | You can follow [this](https://medium.com/@davidbeloosesky/embedded-unity-within-android-app-7061f4f473a) link, I think it will help
```
dependencies {
compile project(":your_aar_file_name")
compile fileTree(dir: 'libs', include: ['*.jar'])
...
}
``` | Please add following line into your string.xml
```js
<string name="game_view_content_description">Game view</string>
```
After that add below snippet into your app level's gradle file
```js
defaultConfig {
ndk {
abiFilters 'armeabi-v7a', 'x86'
}
}
``` |
58,751,549 | I have a problem in my graduation project, I add Unity as a library to Android Studio it works fine with my mobile, but when I try on the other Android mobile I got some weird error (unable to load **libmain.so**), I search a lot but I didn't find the answer.
Note: there is no compile or build error, only when I click on the button(on android project) to go to Unity project. | 2019/11/07 | [
"https://Stackoverflow.com/questions/58751549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12107055/"
] | I had the same problem, in my case I solved by editing the project's gradle file which should be located in `your_project/Assets/Plugins/Android/mainTemplate.gradle`
For an unknown reason my gradle file had this lines that prevented to pack libmain.so inside the apk therefore giving the unable to load libmain.so error
```
// Android Resolver Exclusions Start
android {
packagingoptions {
exclude ('/lib/arm64-v8a/*' + '*')
exclude ('/lib/armeabi/*' + '*')
exclude ('/lib/mips/*' + '*')
exclude ('/lib/mips64/*' + '*')
exclude ('/lib/x86/*' + '*')
exclude ('/lib/x86_64/*' + '*')
}
}
// Android Resolver Exclusions End
```
If you find this in your gradle file, try to comment `//` or remove the block. | You can follow [this](https://medium.com/@davidbeloosesky/embedded-unity-within-android-app-7061f4f473a) link, I think it will help
```
dependencies {
compile project(":your_aar_file_name")
compile fileTree(dir: 'libs', include: ['*.jar'])
...
}
``` |
58,751,549 | I have a problem in my graduation project, I add Unity as a library to Android Studio it works fine with my mobile, but when I try on the other Android mobile I got some weird error (unable to load **libmain.so**), I search a lot but I didn't find the answer.
Note: there is no compile or build error, only when I click on the button(on android project) to go to Unity project. | 2019/11/07 | [
"https://Stackoverflow.com/questions/58751549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12107055/"
] | I had the same problem, in my case I solved by editing the project's gradle file which should be located in `your_project/Assets/Plugins/Android/mainTemplate.gradle`
For an unknown reason my gradle file had this lines that prevented to pack libmain.so inside the apk therefore giving the unable to load libmain.so error
```
// Android Resolver Exclusions Start
android {
packagingoptions {
exclude ('/lib/arm64-v8a/*' + '*')
exclude ('/lib/armeabi/*' + '*')
exclude ('/lib/mips/*' + '*')
exclude ('/lib/mips64/*' + '*')
exclude ('/lib/x86/*' + '*')
exclude ('/lib/x86_64/*' + '*')
}
}
// Android Resolver Exclusions End
```
If you find this in your gradle file, try to comment `//` or remove the block. | Please add following line into your string.xml
```js
<string name="game_view_content_description">Game view</string>
```
After that add below snippet into your app level's gradle file
```js
defaultConfig {
ndk {
abiFilters 'armeabi-v7a', 'x86'
}
}
``` |
19,659,969 | So I have to fill my picture box with lines, though I can't understand what I've done wrong.
```
public Form1()
{
InitializeComponent();
PictureBox pb = new PictureBox();
}
public void Zimet()
{
PictureBox pb = new PictureBox();
Graphics g = pb.CreateGraphics();
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` | 2013/10/29 | [
"https://Stackoverflow.com/questions/19659969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800433/"
] | First your `PictureBox` should be field of your `Form` and you should not create it every time you click a button. Second, your `DrawLine` call is bad, for instance if you want horizontal lines you would need to do something like this:
```
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
```
But this would be the same as filling the pictureBox with Red color. Instead I suggest you skipping every other line by updating i+=2.
```
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i+=2)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
```
Nevertheless, I would suggest you not using CreateGraphic() method but do all drawing in the Paint event handler. The reason for this is whenever your form is invalidated, your drawing will be erased. Use for instance some bool value that will be set when you click a button and then, if it is true do the drawing. Something like this:
```
public class Form1:Form
{
PictureBox pb;
bool drawLines = false;
public Form1()
{
InitializeComponent();
pb = new PictureBox();
pb.Size = new Size(100,100);
pb.Location = new Point(0,0);
pb.Paint+=new PaintEventHandler(pb_Paint);
this.Controls.Add(pb);
}
private void pb_Paint(object sender, PaintEventArgs e)
{
if(drawLines)
{
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i+=2)
{
e.Graphic.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
}
public void Zimet()
{
drawLines = true; //however this may look redundant, it is still OP's code
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` | Your `Zimet()` function creates a `Picturebox` and draws to it, and then throws it away at the end of the function.
You need to call `SomeUiObject.Controls.Add(pb);` to actually put it on the form. |
19,659,969 | So I have to fill my picture box with lines, though I can't understand what I've done wrong.
```
public Form1()
{
InitializeComponent();
PictureBox pb = new PictureBox();
}
public void Zimet()
{
PictureBox pb = new PictureBox();
Graphics g = pb.CreateGraphics();
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` | 2013/10/29 | [
"https://Stackoverflow.com/questions/19659969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800433/"
] | There are actually three reasons why this code won't work, two of which have been mentioned in other answers:
1. your PictureBox isn't a control on the form (see answer by patchandchat)
2. wrong coordinates used in draw-line (see answer by Nicola Davidovic)
The third issue is that you can't draw onto a PictureBox like that, since when the paint event fires, anything you drew is lost. Create an Image, draw onto that, and then set the image of your PictureBox to that image:
```
public void Zimet()
{
var image = new Bitmap(pb.Width, pb.Height);
Graphics g = Graphics.FromImage(image);
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
pb.Image = image;
}
``` | Your `Zimet()` function creates a `Picturebox` and draws to it, and then throws it away at the end of the function.
You need to call `SomeUiObject.Controls.Add(pb);` to actually put it on the form. |
19,659,969 | So I have to fill my picture box with lines, though I can't understand what I've done wrong.
```
public Form1()
{
InitializeComponent();
PictureBox pb = new PictureBox();
}
public void Zimet()
{
PictureBox pb = new PictureBox();
Graphics g = pb.CreateGraphics();
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` | 2013/10/29 | [
"https://Stackoverflow.com/questions/19659969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800433/"
] | First your `PictureBox` should be field of your `Form` and you should not create it every time you click a button. Second, your `DrawLine` call is bad, for instance if you want horizontal lines you would need to do something like this:
```
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
```
But this would be the same as filling the pictureBox with Red color. Instead I suggest you skipping every other line by updating i+=2.
```
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i+=2)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
```
Nevertheless, I would suggest you not using CreateGraphic() method but do all drawing in the Paint event handler. The reason for this is whenever your form is invalidated, your drawing will be erased. Use for instance some bool value that will be set when you click a button and then, if it is true do the drawing. Something like this:
```
public class Form1:Form
{
PictureBox pb;
bool drawLines = false;
public Form1()
{
InitializeComponent();
pb = new PictureBox();
pb.Size = new Size(100,100);
pb.Location = new Point(0,0);
pb.Paint+=new PaintEventHandler(pb_Paint);
this.Controls.Add(pb);
}
private void pb_Paint(object sender, PaintEventArgs e)
{
if(drawLines)
{
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i+=2)
{
e.Graphic.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
}
public void Zimet()
{
drawLines = true; //however this may look redundant, it is still OP's code
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` | You create a `PictureBox pb` in the form constructor, and then another one in your `Zimet()` method. The one in the `Zimet()` method is local in scope to that method, so goes out of scope when the method returns.
Are you trying to draw lines in the `PictureBox` created in your constructor? Because that goes out of scope once your constructor has completed. Maybe create a field in your class to hold the `PictureBox` and then draw in that in your `Zimet()` method. |
19,659,969 | So I have to fill my picture box with lines, though I can't understand what I've done wrong.
```
public Form1()
{
InitializeComponent();
PictureBox pb = new PictureBox();
}
public void Zimet()
{
PictureBox pb = new PictureBox();
Graphics g = pb.CreateGraphics();
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` | 2013/10/29 | [
"https://Stackoverflow.com/questions/19659969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800433/"
] | There are actually three reasons why this code won't work, two of which have been mentioned in other answers:
1. your PictureBox isn't a control on the form (see answer by patchandchat)
2. wrong coordinates used in draw-line (see answer by Nicola Davidovic)
The third issue is that you can't draw onto a PictureBox like that, since when the paint event fires, anything you drew is lost. Create an Image, draw onto that, and then set the image of your PictureBox to that image:
```
public void Zimet()
{
var image = new Bitmap(pb.Width, pb.Height);
Graphics g = Graphics.FromImage(image);
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
pb.Image = image;
}
``` | First your `PictureBox` should be field of your `Form` and you should not create it every time you click a button. Second, your `DrawLine` call is bad, for instance if you want horizontal lines you would need to do something like this:
```
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
```
But this would be the same as filling the pictureBox with Red color. Instead I suggest you skipping every other line by updating i+=2.
```
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i+=2)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
```
Nevertheless, I would suggest you not using CreateGraphic() method but do all drawing in the Paint event handler. The reason for this is whenever your form is invalidated, your drawing will be erased. Use for instance some bool value that will be set when you click a button and then, if it is true do the drawing. Something like this:
```
public class Form1:Form
{
PictureBox pb;
bool drawLines = false;
public Form1()
{
InitializeComponent();
pb = new PictureBox();
pb.Size = new Size(100,100);
pb.Location = new Point(0,0);
pb.Paint+=new PaintEventHandler(pb_Paint);
this.Controls.Add(pb);
}
private void pb_Paint(object sender, PaintEventArgs e)
{
if(drawLines)
{
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i+=2)
{
e.Graphic.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
}
public void Zimet()
{
drawLines = true; //however this may look redundant, it is still OP's code
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` |
19,659,969 | So I have to fill my picture box with lines, though I can't understand what I've done wrong.
```
public Form1()
{
InitializeComponent();
PictureBox pb = new PictureBox();
}
public void Zimet()
{
PictureBox pb = new PictureBox();
Graphics g = pb.CreateGraphics();
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, pb.Width, 0, 0, pb.Height);
}
}
private void button1_Click(object sender, EventArgs e)
{
Zimet();
}
``` | 2013/10/29 | [
"https://Stackoverflow.com/questions/19659969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800433/"
] | There are actually three reasons why this code won't work, two of which have been mentioned in other answers:
1. your PictureBox isn't a control on the form (see answer by patchandchat)
2. wrong coordinates used in draw-line (see answer by Nicola Davidovic)
The third issue is that you can't draw onto a PictureBox like that, since when the paint event fires, anything you drew is lost. Create an Image, draw onto that, and then set the image of your PictureBox to that image:
```
public void Zimet()
{
var image = new Bitmap(pb.Width, pb.Height);
Graphics g = Graphics.FromImage(image);
Pen pen1 = new Pen(Color.Red);
for (int i = 0; i < pb.Height; i++)
{
g.DrawLine(pen1, 0, i, pb.Width, i);
}
pb.Image = image;
}
``` | You create a `PictureBox pb` in the form constructor, and then another one in your `Zimet()` method. The one in the `Zimet()` method is local in scope to that method, so goes out of scope when the method returns.
Are you trying to draw lines in the `PictureBox` created in your constructor? Because that goes out of scope once your constructor has completed. Maybe create a field in your class to hold the `PictureBox` and then draw in that in your `Zimet()` method. |
70,640,256 | ```
/**
* A method that writes variables in a file for shows in the program.
*
* @author
* @version (1.2 2022.01.05)
*/
public void writeShowData(String fileName) throws FileNotFoundException{
String showPath = "c:\\Users\\COMPUTER\\bluej files\\projects\\chapter15\\willem\\CinemaReservationSystemFiles\\";
try
{
FileOutputStream fos = new FileOutputStream(showPath+fileName,true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(show);
oos.flush();
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method that reads variables in a file for shows setup use in the program.
*
* @author
* @version (1.2 2022.01.05)
*/
public void readShowData(String fileName) throws FileNotFoundException {
try
{ FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
List <Show>shows =(List<Show>)ois.readObject();
ois.close();
System.out.println(shows.toString());// for testing
}
catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
```
the line : `List <Show> shows= (List<Show>)ois.readObject();` gives a
>
> ClassCastexception :class Show cannot be cast to class java.util.List
> (etc etc....
>
>
>
I tried many things but can't get it working well.
I made the class show and related classes
`Serializable` and then write it to shows.ser but when it reads it goes wrong.
Who can help me out on this? | 2022/01/09 | [
"https://Stackoverflow.com/questions/70640256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9493669/"
] | You can use this method
>
> window.after(1000,<function\_name>)
>
>
>
It means the function call after 1 sec. If you are use recursion with this method then you can create timer. | I hope it works for you, cheer.
```
import time
# time.time() return in second
game_duration = float(input('duration: ')) + time.time()
game_is_running = True
while game_is_running:
if game_duration == time.time(): # this means: if now equal to game_duration
game_is_running = False
# note: it is quite critical where you place time.time()
```
One more example:
=================
```
# I used the following technique to build an explosion animation for 30 seconds, then it will do something else.
class Explosion(pygame.sprite.Sprite):
def __init__(self, center):
pygame.sprite.Sprite.__init__(self)
self.image = explosion_animation[0]
self.rect = self.image.get_rect()
self.rect.center = center
self.frame = 0
self.last_update = pygame.time.get_ticks()
self.duration = 30
def update(self):
now = pygame.time.get_ticks()
if now - self.last_update > self.duration:
self.last_update = now
self.frame += 1
if self.frame == len(explosion_animation):
self.kill()
else:
center = self.rect.center
self.image = explosion_animation[self.frame]
self.rect = self.image.get_rect()
self.rect.center = center
``` |
10,308,381 | Suppose I have the following code:
```
var X = XElement.Parse (@"
<ROOT>
<MUL v='2' />
<MUL v='3' />
</ROOT>
");
Enumerable.Range (1, 100)
.Select (s => X.Elements ()
.Select (t => Int32.Parse (t.Attribute ("v").Value))
.Aggregate (s, (t, u) => t * u)
)
.ToList ()
.ForEach (s => Console.WriteLine (s));
```
What is the .NET runtime actually doing here? Is it parsing and converting the attributes to integers each of the 100 times, or is it smart enough to figure out that it should cache the parsed values and not repeat the computation for each element in the range?
Moreover, how would I go about figuring out something like this myself?
Thanks in advance for your help. | 2012/04/25 | [
"https://Stackoverflow.com/questions/10308381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/631115/"
] | It has been a while since I dug through this code but, IIRC, the way `Select` works is to simply cache the `Func` you supply it and run it on the source collection one at a time. So, for each element in the outer range, it will run the inner `Select/Aggregate` sequence as if it were the first time. There isn't any built-in caching going on -- you would have to implement that yourself in the expressions.
If you wanted to figure this out yourself, you've got three basic options:
1. Compile the code and use `ildasm` to view the IL; it's the most accurate but, especially with lambdas and closures, what you get from IL may look nothing like what you put into the C# compiler.
2. Use something like dotPeek to decompile System.Linq.dll into C#; again, what you get out of these kinds of tools may only approximately resemble the original source code, but at least it will be C# (and dotPeek in particular does a pretty good job, and is free.)
3. My personal preference - download the .NET 4.0 [Reference Source](http://referencesource.microsoft.com/netframework.aspx) and look for yourself; this is what it's for :) You have to just trust MS that the reference source matches the actual source used to produce the binaries, but I don't see any good reason to doubt them.
4. As pointed out by @AllonGuralnek you can set breakpoints on specific lambda expressions within a single line; put your cursor somewhere inside the body of the lambda and press F9 and it will breakpoint just the lambda. (If you do it wrong, it will highlight the entire line in the breakpoint color; if you do it right, it will just highlight the lambda.) | LINQ and `IEnumerable<T>` is *pull based*. This means that the predicates and actions that are part of the LINQ statement in general are not executed until values are pulled. Furthermore the predicates and actions will execute each time values are pulled (e.g. there is no secret caching going on).
Pulling from an `IEnumerable<T>` is done by the `foreach` statement which really is syntactic sugar for getting an enumerator by calling `IEnumerable<T>.GetEnumerator()` and repeatedly calling `IEnumerator<T>.MoveNext()` to pull the values.
LINQ operators like `ToList()`, `ToArray()`, `ToDictionary()` and `ToLookup()` wraps a `foreach` statement so these methods will do a pull. The same can be said about operators like `Aggregate()`, `Count()` and `First()`. These methods have in common that they produce a single result that has to be created by executing a `foreach` statement.
Many LINQ operators produce a new `IEnumerable<T>` sequence. When an element is pulled from the resulting sequence the operator pulls one or more elements from the source sequence. The `Select()` operator is the most obvious example but other examples are `SelectMany()`, `Where()`, `Concat()`, `Union()`, `Distinct()`, `Skip()` and `Take()`. These operators don't do any caching. When then N'th element is pulled from a `Select()` it pulls the N´th element from the source sequence, applies the projection using the action supplied and returns it. Nothing secret going on here.
Other LINQ operators also produce new `IEnumerable<T>` sequences but they are implemented by actually pulling the entire source sequence, doing their job and then producing a new sequence. These methods include `Reverse()`, `OrderBy()` and `GroupBy()`. However, the pull done by the operator is only performed when the operator itself is pulled meaning that you still need a `foreach` loop "at the end" of the LINQ statement before anything is executed. You could argue that these operators use a cache because they immediately pull the entire source sequence. However, this cache is built each time the operator is iterated so it is really an implementation detail and not something that will magically detect that you are applying the same `OrderBy()` operation multiple times to the same sequence.
---
In your example the `ToList()` will do a pull. The action in the outer `Select` will execute 100 times. Each time this action is executed the `Aggregate()` will do another pull that will parse the XML attributes. In total your code will call `Int32.Parse()` 200 times.
You can improve this by pulling the attributes once instead of on each iteration:
```
var X = XElement.Parse (@"
<ROOT>
<MUL v='2' />
<MUL v='3' />
</ROOT>
")
.Elements ()
.Select (t => Int32.Parse (t.Attribute ("v").Value))
.ToList ();
Enumerable.Range (1, 100)
.Select (s => x.Aggregate (s, (t, u) => t * u))
.ToList ()
.ForEach (s => Console.WriteLine (s));
```
Now `Int32.Parse()` is only called 2 times. However, the cost is that a list of attribute values have to be allocated, stored and eventually garbage collected. (Not a big concern when the list contains two elements.)
Note that if you forget the first `ToList()` that pulls the attributes the code will still run but with the exact same performance characteristics as the original code. No space is used to store the attributes but they are parsed on each iteration. |
5,455,592 | Blocks are fine but what about writing C arrays?
Given this simplified situation:
```
CGPoint points[10];
[myArray forEachElementWithBlock:^(int idx) {
points[idx] = CGPointMake(10, 20); // error here
// Cannot refer to declaration with an array type inside block
}];
```
after searching a while found this possible solution, to put it in a struct:
```
__block struct {
CGPoint points[100];
} pointStruct;
[myArray forEachElementWithBlock:^(int idx) {
pointStruct.points[idx] = CGPointMake(10, 20);
}];
```
this would work but there is a little limitation I have to create the c array dynamically:
```
int count = [str countOccurencesOfString:@";"];
__block struct {
CGPoint points[count]; // error here
// Fields must have a constant size: 'variable length array in structure' extension will never be supported
} pointStruct;
```
How can I access my `CGPoint` array within a `block`?
OR
Is it even possible at all or do I have to rewrite the block method to get the full functionality? | 2011/03/28 | [
"https://Stackoverflow.com/questions/5455592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Maybe you can allocate the array on the heap?
```
// Allocates a plain C array on the heap. The array will have
// [myArray count] items, each sized to fit a CGPoint.
CGPoint *points = calloc([myArray count], sizeof(CGPoint));
// Make sure the allocation succeded, you might want to insert
// some more graceful error handling here.
NSParameterAssert(points != NULL);
// Loop over myArray, doing whatever you want
[myArray forEachElementWithBlock:^(int idx) {
points[idx] = …;
}];
// Free the memory taken by the C array. Of course you might
// want to do something else with the array, otherwise this
// excercise does not make much sense :)
free(points), points = NULL;
``` | Another simple answer which works for me is the following:
```
CGPoint points[10], *pointsPtr;
pointsPtr = points;
[myArray forEachElementWithBlock:^(int idx) {
pointsPtr[idx] = CGPointMake(10, 20);
}];
``` |
28,473,976 | The following example shows a `box` `div` with an `:after` content, which should be a separate block.
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.box:after {
content: "☑";
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="box">x</div>
```
But the after content is placed inside the scroll bars. My expectation was that it comes actually after the scrollable area. | 2015/02/12 | [
"https://Stackoverflow.com/questions/28473976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402322/"
] | The `:after` content comes within the scrollable area because even though the element is named `:after`, it is in actual terms a child of the `div.box` and hence will be positioned within the `.box` element (that is within the scrollable area).
>
> **From MDN:** The CSS ::after pseudo-element matches a ***virtual last child of the selected element***.
>
>
>
(emphasis mine)
So the code in question in essence becomes the same as the following snippet.
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.box .after {
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="box">x
<div class="after">☑</div>
</div>
```
---
If you want it positioned outside the `div.box` then you would have to use the `:after` on a container (or) use absolute positioning.
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.container:after {
content: "☑";
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="container">
<div class="box">x</div>
</div>
``` | I think you've become a little confused with pseudo elements, so i'll hopefully clear a few things up for you:
>
> The ::after pseudo-element can be used to describe generated content after an element's content.
>
>
>
A quick demonstration of this would be:
```css
p::after {
content: " :Note";
}
```
```html
<p>In CSS 2.1, it is not possible to refer to attribute values for other elements than the subject of the selector.</p>
```
See how, no matter where the div is, the pseudo element will be displayed *after* the element it is attached to. This is the way pseudo elements were designed for -to add content `before` or add content `after`.
---
This means that the :after is positioned relatively to the 'real' element, and **not** appear after the 'scrollbars'.
Instead, if you position your pseudo element ***absolutely***, then as you would expect with positioning a child element, you can 'move' it using the `left`, `right`, `top` and `bottom` properties:
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.box:after {
content: "☑";
position:absolute;
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="box">x</div>
```
**Note**
However, I would instead wrap the scrollable content in a div, and that way you would have much more control over the positioning of the element.
---
**The similarities in `::after` and `:after`**
>
> This [double-colon] notation is introduced … in order to establish a
> discrimination between pseudo-classes and pseudo-elements. For
> compatibility with existing style sheets, user agents must also accept
> the previous one-colon notation for pseudo-elements introduced in CSS
> levels 1 and 2 (namely, :first-line, :first-letter, :before and
> :after). This compatibility is not allowed for the new pseudo-elements
> introduced in CSS level 3. ~[Spec](http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#pseudo-elements)
>
>
>
*So, The short answer is..*
There is no difference between the two notations
*The slightly Long answer is...*
With the introduction of CSS3, in order to make a differentiation between pseudo-classes and pseudo-elements, in CSS3 all pseudo-elements must use the double-colon syntax (`::after`), and all pseudo-classes must use the single-colon syntax (`:first-child`).
However, since IE8 and below doesn't understand this 'double colon' syntax (amongst so many others), browsers will accept the single colon syntax anyway (allowing IE 8 and below to also understand it). This is why developers, on the broad side, have chosen to keep using the single colon syntax in order for IE8 (and below) to understand, giving your site better browser compatability.
---
**Further Reading**
* <http://www.w3.org/wiki/CSS/Selectors/pseudo-elements/:after> |
28,473,976 | The following example shows a `box` `div` with an `:after` content, which should be a separate block.
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.box:after {
content: "☑";
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="box">x</div>
```
But the after content is placed inside the scroll bars. My expectation was that it comes actually after the scrollable area. | 2015/02/12 | [
"https://Stackoverflow.com/questions/28473976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402322/"
] | The `:after` content comes within the scrollable area because even though the element is named `:after`, it is in actual terms a child of the `div.box` and hence will be positioned within the `.box` element (that is within the scrollable area).
>
> **From MDN:** The CSS ::after pseudo-element matches a ***virtual last child of the selected element***.
>
>
>
(emphasis mine)
So the code in question in essence becomes the same as the following snippet.
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.box .after {
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="box">x
<div class="after">☑</div>
</div>
```
---
If you want it positioned outside the `div.box` then you would have to use the `:after` on a container (or) use absolute positioning.
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.container:after {
content: "☑";
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="container">
<div class="box">x</div>
</div>
``` | >
> My expectation was that it comes actually after the scrollable area.
>
>
>
This expectation is wrong. Looking at the CSS2.1 specification, we find:
>
> Authors specify the style and location of generated content with the
> :before and :after pseudo-elements. As their names indicate, the
> :before and :after pseudo-elements specify the location of content
> before and after an element's document tree content.
>
>
>
And then:
>
> The formatting objects (e.g., boxes) generated by an element include generated content.
>
>
>
What this means is that the content you've added with your div.box:after rule is included *inside* the div. The "after" refers to it being placed after the div's normal *content*, not after the entire div.
Source: <http://www.w3.org/TR/CSS21/generate.html> |
28,473,976 | The following example shows a `box` `div` with an `:after` content, which should be a separate block.
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.box:after {
content: "☑";
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="box">x</div>
```
But the after content is placed inside the scroll bars. My expectation was that it comes actually after the scrollable area. | 2015/02/12 | [
"https://Stackoverflow.com/questions/28473976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402322/"
] | I think you've become a little confused with pseudo elements, so i'll hopefully clear a few things up for you:
>
> The ::after pseudo-element can be used to describe generated content after an element's content.
>
>
>
A quick demonstration of this would be:
```css
p::after {
content: " :Note";
}
```
```html
<p>In CSS 2.1, it is not possible to refer to attribute values for other elements than the subject of the selector.</p>
```
See how, no matter where the div is, the pseudo element will be displayed *after* the element it is attached to. This is the way pseudo elements were designed for -to add content `before` or add content `after`.
---
This means that the :after is positioned relatively to the 'real' element, and **not** appear after the 'scrollbars'.
Instead, if you position your pseudo element ***absolutely***, then as you would expect with positioning a child element, you can 'move' it using the `left`, `right`, `top` and `bottom` properties:
```css
div.box {
background-color: #FAA;
width: 10em;
overflow: scroll;
}
div.box:after {
content: "☑";
position:absolute;
display: block;
background-color: #AFA;
width: 5em;
overflow: auto;
}
```
```html
<div class="box">x</div>
```
**Note**
However, I would instead wrap the scrollable content in a div, and that way you would have much more control over the positioning of the element.
---
**The similarities in `::after` and `:after`**
>
> This [double-colon] notation is introduced … in order to establish a
> discrimination between pseudo-classes and pseudo-elements. For
> compatibility with existing style sheets, user agents must also accept
> the previous one-colon notation for pseudo-elements introduced in CSS
> levels 1 and 2 (namely, :first-line, :first-letter, :before and
> :after). This compatibility is not allowed for the new pseudo-elements
> introduced in CSS level 3. ~[Spec](http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#pseudo-elements)
>
>
>
*So, The short answer is..*
There is no difference between the two notations
*The slightly Long answer is...*
With the introduction of CSS3, in order to make a differentiation between pseudo-classes and pseudo-elements, in CSS3 all pseudo-elements must use the double-colon syntax (`::after`), and all pseudo-classes must use the single-colon syntax (`:first-child`).
However, since IE8 and below doesn't understand this 'double colon' syntax (amongst so many others), browsers will accept the single colon syntax anyway (allowing IE 8 and below to also understand it). This is why developers, on the broad side, have chosen to keep using the single colon syntax in order for IE8 (and below) to understand, giving your site better browser compatability.
---
**Further Reading**
* <http://www.w3.org/wiki/CSS/Selectors/pseudo-elements/:after> | >
> My expectation was that it comes actually after the scrollable area.
>
>
>
This expectation is wrong. Looking at the CSS2.1 specification, we find:
>
> Authors specify the style and location of generated content with the
> :before and :after pseudo-elements. As their names indicate, the
> :before and :after pseudo-elements specify the location of content
> before and after an element's document tree content.
>
>
>
And then:
>
> The formatting objects (e.g., boxes) generated by an element include generated content.
>
>
>
What this means is that the content you've added with your div.box:after rule is included *inside* the div. The "after" refers to it being placed after the div's normal *content*, not after the entire div.
Source: <http://www.w3.org/TR/CSS21/generate.html> |
34,544,396 | I installed Qt library and Qt creator in Linux Mint but when I try to run the designer I get the following error:
```
designer: could not exec '/usr/lib/x86_64-linux-gnu/qt5/bin/designer': No such file or directory
```
I cannot find the designer version 5 online, but I could find the version 4. I'm afraid that this older version could not handle all the Qt5 new features.
Is the Qt designer version 5 available for Linux? | 2015/12/31 | [
"https://Stackoverflow.com/questions/34544396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889762/"
] | The designer app is part of the `qttools5-dev-tools` package:
You can find the solution to answers like "where can I get binary X from" in Debian-based distros quite easily:
```
% apt-file search bin/designer
qt4-designer: /usr/bin/designer-qt4
qt4-designer: /usr/lib/x86_64-linux-gnu/qt4/bin/designer
qt4-designer: /usr/share/qt4/bin/designer
qtchooser: /usr/bin/designer
qttools5-dev-tools: /usr/lib/x86_64-linux-gnu/qt5/bin/designer
```
`qtchooser` just provides a wrapper for the *designer* binary, it will start either Qt4 or Qt5-based designer.
`qt4-designer` & `qttools5-dev-tools` contain the real binary. You can choose. | If you installed Qt using the installers provided by the Qt website, the designer can also be launched from
`~/Qt/<VERSION>/<COMPILER>/bin/designer` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | did you try `border-bottom:0!important` | Your problem is with your selector.
Doing `.table-subtitles td` means: The TD element inside the element with the "table-subtitles" class.
What you need is:
`td.table-subtitles { border-bottom:0; }` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | You might find want to make friends with `border-collapse` and `th`. | did you try `border-bottom:0!important` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | When I put just this table into a test HTML file I'm getting no borders by default. Therefore this is probably an inheritance issue with some previous table styling you have or are importing from your CSS. Normally, the solution to such problems is over riding whatever style its inheriting my making a more specific selector in CSS. So for example, give your table an ID and have your CSS style be:
```
#mytable .table-subtitles td { border-bottom: 0; }
```
Another great way to see exactly what's happening is to use Firebug in Firefox or the Chrome inspector see exactly what styles your table rows are picking up, inheriting or being overridden. | did you try `border-bottom:0!important` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | // is not a css comment. you must use /\* \*/ | did you try `border-bottom:0!important` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | You might find want to make friends with `border-collapse` and `th`. | Your problem is with your selector.
Doing `.table-subtitles td` means: The TD element inside the element with the "table-subtitles" class.
What you need is:
`td.table-subtitles { border-bottom:0; }` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | When I put just this table into a test HTML file I'm getting no borders by default. Therefore this is probably an inheritance issue with some previous table styling you have or are importing from your CSS. Normally, the solution to such problems is over riding whatever style its inheriting my making a more specific selector in CSS. So for example, give your table an ID and have your CSS style be:
```
#mytable .table-subtitles td { border-bottom: 0; }
```
Another great way to see exactly what's happening is to use Firebug in Firefox or the Chrome inspector see exactly what styles your table rows are picking up, inheriting or being overridden. | Your problem is with your selector.
Doing `.table-subtitles td` means: The TD element inside the element with the "table-subtitles" class.
What you need is:
`td.table-subtitles { border-bottom:0; }` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | // is not a css comment. you must use /\* \*/ | Your problem is with your selector.
Doing `.table-subtitles td` means: The TD element inside the element with the "table-subtitles" class.
What you need is:
`td.table-subtitles { border-bottom:0; }` |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | // is not a css comment. you must use /\* \*/ | You might find want to make friends with `border-collapse` and `th`. |
7,573,827 | I'm not sure why, but i can't seem to style a td element in my script. I'm trying to remove a border from all the td elements in the table-subtitles, and i guess my css is wrong somehow.
PS: I was able to remove the border by inline css only.
HTML:
```
<table>
<thead>
<tr>
<th width="100%" colspan="5">My Recent Activity</th>
</tr>
</thead>
<tbody>
<tr class="table-subtitles">
<td style="border: 0"><h4>Date</h4></td>
<td><h4>Description</h4></td>
<td><h4>Amount</h4></td>
<td><h4>Due</h4></td>
<td><h4>Status</h4></td>
</tr>
<?php foreach($this->payments as $payment): ?>
<tr>
</tr>
<?php endforeach; ?>
<?php
if ((count($this->payments)==0)) :
?>
<tr>
<td style="border: 0; text-align: center" colspan="6" class="info">No payments made yet</td>
</tr>
<?php endif; ?>
</tbody>
</table>
```
CSS:
```
#payments-content { width: 480px; float: left; margin-right: 20px; }
#payments-sidebar { width: 270px; float: left; }
.ui-button-large .ui-button-large-text { font-size: 20px; width: 270px; }
// new tables design
.table-subtitles td{ border-bottom: 0 !important; }
``` | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804671/"
] | // is not a css comment. you must use /\* \*/ | When I put just this table into a test HTML file I'm getting no borders by default. Therefore this is probably an inheritance issue with some previous table styling you have or are importing from your CSS. Normally, the solution to such problems is over riding whatever style its inheriting my making a more specific selector in CSS. So for example, give your table an ID and have your CSS style be:
```
#mytable .table-subtitles td { border-bottom: 0; }
```
Another great way to see exactly what's happening is to use Firebug in Firefox or the Chrome inspector see exactly what styles your table rows are picking up, inheriting or being overridden. |
34,680,920 | I have a variable in my view `$models` which I want to pass to my controller for a function which I'm calling using a submit button.
```
<?php echo CHtml::beginForm('', 'post');?>
<fieldset>
<?php echo CHtml::submitButton('Confirm', array('name'=>'confirm', 'class'=>'btn btn-danger')); ?>
</fieldset>
<?php echo CHtml::endForm(); ?>
```
how do I access the `$models` variable from the function in the controller.
I'm not entirely sure how this works and I would have thought I could just use `$_POST['models']` but it's saying it's an undefined variable (although I can var\_dump on the page and it's definitely not) so I think i'm just trying to access it incorrectly or not submitting it correctly. | 2016/01/08 | [
"https://Stackoverflow.com/questions/34680920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4375167/"
] | This is a html form submission and php syntax problem, but not yii-specific.
Whatever framework you use, even in plain static html, the basic idea of form submission is the same: if you want to send data to a page with a form, you need to put that data in your form, either as a form input the end-user can enter or select (text inputs, dragdown boxes, radios and checkboxes), or as a hidden input. Page2 doesn't care if $models was set on Page1. You need to send the data to Page2.
In PHP, you can't display an array with echo $arrayVar.
For your specific problem, I assume $models is an array of models. Do NOT pass the whole models' definition in your form, just pass their primary key ids. On your next action, just fetch back those models with YourMode::model()->findByPk(). I think you could do this two ways:
```
<?php
// Idea 1 (untested code)
// Convert an array of ids to a string
$tmp = array();
foreach($models as $model){
$tmp[] = $model->yourPrimaryKey;
}
echo '<input type="hidden" name="whateveryourparamis" value="'.CHtml::encode( implode('|',$tmp)).'">';
// $whateveryourparamis will be a string like: "47|388|638|877". Use explode() to convert it to an array
// Your could also use json_encode/json_decode instead of implode/explode
// Idea 2 (untested code)
// Pass an array of ids (yeah, this is possible)
foreach($models as $model){
echo '<input type="hidden" name="whateveryourparamis[]" value="'.CHtml::encode($model->yourPrimaryKey).'">';
}
// $whateveryourparamis will be an array like: array(47, 388, 638, 877)
?>
``` | I suppose this ain't the best way to achieve what you want, but you can always access the controller through:
```
$controller = Yii::app()->controller;
```
And then do with it whatever you want, for storing a variable in your controller, you probably will have to add a variable to your class.
Another variant would be to use CStatePersister <http://www.yiiframework.com/doc/api/1.1/CStatePersister> or you could also directly write in to $\_SESSION..
From what you write, I suppose you should use Sessions for storing that data. |
11,695,502 | I am trying to create a simple bar graph including two bars showing the average math scores of two groups of students. The averages are 363.2 and 377.4. creating bar graph is simple. What I'd like to do is to have my y-axis starts from 340 rather than 0. I do know how to change the limits of y-axis, but the issue is when I change the limit of y-axis to c(340, 380), R still draws the whole bar which most of it is below the x-axis!
Here is my code:
```
barplot(c(363.2, 377.4), beside = T, ylim = c(340,380), col = c("orange", "blue"))
```
I've also attached my plot: | 2012/07/27 | [
"https://Stackoverflow.com/questions/11695502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004102/"
] | Adding `xpd=FALSE` and re-adding the horizontal axis works, sort of:
```
b <- barplot(c(363.2, 377.4), beside = TRUE,
ylim = c(340,380), col = c("orange", "blue"),xpd=FALSE)
axis(side=1,at=b,labels=c("group 1", "group 2"))
box(bty="l")
```
I claim (I can't point you to a definitive reference, although [Googling "bar plot zero axis"](http://chandoo.org/wp/2008/10/21/reader-poll-axis-scaling-bar-charts/) seems to come up with useful stuff; perhaps others will chime in) that it is **bad practice** to draw bar graphs where the vertical axis does not include zero: the argument is that the viewer will assume that bar graphs are anchored to the origin (this argument is more commonly made when explaining why R doesn't make it easy to use a logarithmic axis for barplots: see [comments here](https://stackoverflow.com/questions/11646655/ggplot2-0-9-1-logarithmic-y-axis-scale-with-barchart), for example). Those who feel this way would say you should use points to indicate the value instead; in this case the implicit assumption of zero-anchoring does not hold as strongly.
In other words, "here's how you can do this -- but you shouldn't" ... | The following can be seen if you look at `?barplot`:
"xpd: logical. Should bars be allowed to go outside region?"
You just need to include `xpd=FALSE` in your parameters for the barplot. |
41,632,927 | I am trying to add some buttons programmatically. But for some reason long text pushes the entire button down in my linearlayout.
[](https://i.stack.imgur.com/jp1X2.png)
This is the code I use to replicate this behaviour.
The button:
```
public class MyButton : Button
{
public MyButton(Context ctx) : base(ctx)
{
SetTextColor(Color.White);
SetTextSize(Android.Util.ComplexUnitType.Dip, 20);
var llp = new LinearLayout.LayoutParams(0, 100, 1);
llp.SetMargins(4, 0, 4, 4);
LayoutParameters = llp;
SetBackgroundColor(Color.Black);
}
}
```
The row: (I have two rows of buttons)
```
public class MyRow : LinearLayout
{
public MyRow(Context context) : base(context)
{
if (LayoutParameters == null)
LayoutParameters = GenerateDefaultLayoutParams();
LayoutParameters.Height = ViewGroup.LayoutParams.WrapContent;
LayoutParameters.Width = ViewGroup.LayoutParams.MatchParent;
((LinearLayout.LayoutParams)LayoutParameters).Gravity = GravityFlags.Top;
((LinearLayout.LayoutParams)LayoutParameters).Weight = 0;
Orientation = Orientation.Horizontal;
}
}
```
The header:
```
public class MyHeader : LinearLayout
{
public MyHeader(Context context, IAttributeSet set) : base(context, set)
{
Orientation = Orientation.Vertical;
LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, 0);
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
Draw();
}
private void Draw()
{
for (int r = 0; r < 2; r++)
{
var row = new MyRow(Context);
for (int i = 0; i < 4; i++)
{
var btn = new MyButton(Context);
if (r == 0 && i == 0)
btn.Text = "long text long text long text ";
else
btn.Text = $"Btn {r}.{i}";
row.AddView(btn);
}
AddView(row);
}
}
}
```
And then I add the header in xaml like this:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:minHeight="25px">
<App1.Resources.layout.MyHeader
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/myHeader1" />
</LinearLayout>
```
As faar as I can see the content of the button should not move the position of the button. But it does. Any ideas? | 2017/01/13 | [
"https://Stackoverflow.com/questions/41632927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912169/"
] | Why do you try to declare a local variable named `MessageBoxButton`? This is the name of class that already exists in the framework. If the compiler says that it cannot find the type `MessageBoxButton`, you have to include the namespace where it can be found using a `using` clause at the top of the file:
```
using System.Windows;
```
Then you can just write:
```
public class Class1
{
public static void Demo()
{
MessageBoxResult dialogResult = MessageBox.Show("Text", "Caption", MessageBoxButton.YesNo, MessageBoxImage.Information);
if(dialogResult == MessageBoxResult.Yes)
{
MessageBox.Show("Yes was clicked");
}
else
{
MessageBox.Show("No was clicked");
}
}
}
```
Note that the Microsoft Styleguide says not to use `MessageBoxImage.Question`. Only use Information, Warning or Error instead (or no Icon at all). | Try
```
if (MessageBox.Show(String.Format("{0:0,0}", Convert.ToInt32(txtQuantity.Text)), "OK ??????", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
``` |
3,483,400 | I am studying predicate logic, and have been drawing regular venn diagrams for statements like (exists.x)(P(x) and Q(x)). They are invaluable to get what the expression is actually saying.
But, I ran into this expression:
(all.x)(all.y)(P(x) and Q(x) and R(x, y))
How can I represent the relation R(x, y) as a Venn diagram?
If its not possible to use Venn diagrams, what other visual representations of predicate logic are there? | 2019/12/21 | [
"https://math.stackexchange.com/questions/3483400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/386221/"
] | Peirce's [Existential Graphs](https://en.wikipedia.org/wiki/Existential_graph) is a more graphical/visual way of representing logical statements. Interestingly, his system is expressively complete for Predicate Logic.
Here's a very quick tutorial:
First, Peirce uses the notion of a 'Sheet of Assertion' ($SA$). This is basically a blank canvas, but anything that is put on that canvas is thereby asserted to be True. The location is irrelevant, and if you put multiple things on the $SA$ then they are all asserted to be true. As such, you get conjunction (and its commutative and associative properties) all for free.
Now, how do you actually represent claims? Well, for atomic claims, Peirce still uses letters, but other than that, there are only 'cuts'. A 'cut' is some enclosed figure (like a circle or rectangle) that works like a negation. To be specific, if you put a cut around some subgraph, then you thereby negate that subgraph. So, we have conjunction for free simply by physical juxtaposition, and together with the cut, we have an expressively complete system for propositional logic.
Here, for example, is the representation for $P \lor Q$ (equivalent to $\neg (\neg P \land \neg Q)$:
[](https://i.stack.imgur.com/ALnBb.png)
Note there is no one-to-one mapping between classical notation and Existential Graphs: typically, a single Existential Graph can be 'read' in multiple different ways. Here is a good example:
[](https://i.stack.imgur.com/IGRlC.png)
This Graph can be translated as $\neg (P \land \neg Q)$ ... or as $\neg (\neg Q \land P )$ ... but the 'conditional reading' of this kind of 'cut-inside-cut' would be $P \to Q$ (confirm that these are indeed all logically equivalent statements in classical logic)
Now, moving on to predicate logic. First, we need objects. For this, Peirce used a dot:
[](https://i.stack.imgur.com/D58VP.png)
The dot means "there is something".
(Note that an empty $SA$ does not assert the existence of anything, and indeed Existential Graophs is what is called a 'free logic': unlike most classical logics, it does not make the assumption of Existential Import, which is the assumption that the domain is never empty.)
The touching of dots is seen as an identity claim. For example:
[](https://i.stack.imgur.com/zIUOH.png)
would be the equivalent of:
$\exists x \exists y \exists z (x = y \land y = z)$
Of course, this means that any number of dots strung together effectively still refers to just $1$ object, and it is indeed more typical to use lines to represent objects:
[](https://i.stack.imgur.com/Zl3Zm.png)
(Again, note how unusual this is. Its equivalent in classical notation would be ... what? .... $\exists x$? ... $\exists x \top$ ... $\exists x x=x$? ... $\exists x \bigwedge \emptyset$?)
OK, but how do we predicate things of those objects? Well, you simply have a classical letter for a predicate symbol, but now 'attach' the object to it:
[](https://i.stack.imgur.com/FRqi4.png)
So this means: $\exists x \ P(x)$
You can also attach constant symbols to an object to give it a name:
[](https://i.stack.imgur.com/4vPfp.png)
So this would be $\exists x (x = a \land P(x))$ ... which of course is just equivalent to $P(a)$
For predicates that take multiple arguments, we attach multiple objects:
[](https://i.stack.imgur.com/p4qhd.png)
So this means: $\exists x \exists y R(x,y)$
Peirce's convention was to have the first argument come in on the left, the second on the right, the third on the top, and the fourth at the bottom. He didn't really consider predicates with more arguments, but of course one could adopt a more general convention of having the objects attach in clock-wise fashion, for example.
Now, if we use a cut, we can negate, and thus obtain universals. For example:
[](https://i.stack.imgur.com/SA6KH.png)
represents $\neg \exists x \ P(x)$, ... and thus $\forall x \ \neg P(x)$
We can also do this:
[](https://i.stack.imgur.com/7KVlN.png)
So this would be: $\exists x \ \neg P(x)$
And by negating that:
[](https://i.stack.imgur.com/Y7vLe.png)
We obtain $\neg \exists x \ \neg P(x)$ or $\forall x \ P(x)$
Note that we recognize a 'cut-inside-cut' structure here, and indeed the conditional reading of this graph would be: 'If there is something, then that something is a $P$' ... which is another way of saying 'Everything is a $P$'
OK, we are finally ready for your statement $\forall x \forall y (P(x) \land Q(y) \land R(x,y))$! Here it is:
[](https://i.stack.imgur.com/pf7Gp.png)
Now, Peirce also developed inference rules for this system, that work all purely graphically and, amazingly, his system turned out to be complete! However, that is a story for another time.... | As @Josue commented, there are no good visuals for more complex expressions. This answer discusses why that's true, and talks about some other ways of thinking about expressions in predicate logic.
When all our predicates have just one variable, like $P(x)$ and $Q(x)$, and we draw Venn diagrams of an expression, we're thinking in terms of a *model*, i.e. we have a *universe* of objects (the outside box of our Venn diagram) and our predicates are subsets of objects for which something is true (circles/regions in the Venn diagram). In set language, our universe is a set $U$ and our predicates $P$ and $Q$ are subsets of $U$. A non-visual alternative to understanding an expression might be to think of $U$ as a specific set, e.g. $U=$ set of all cats, and the one-variable predicates as objects for which something is true, e.g. $P(x)$ means the cat $x$ is white, and $Q(x)$ means the cat $x$ likes pizza, so you can think of the predicate $P$ as the set of all cats that are white, and $Q$ as the set of all cats that like pizza.
If all our predicates have two variables, like $R(x,y)$ and $T(x,y)$, we can still (sort of) do Venn diagrams: we think of $R$ and $T$ as being statements about *pairs* of objects. Here each point in our Venn diagram represents a pair of objects (technically an ordered pair), and like before predicates are subsets, but this time subsets of *pairs* of objects. In set notation, if you've encountered Cartesian products, we'd say that $R \subseteq U \times U$ and $T \subseteq U \times U$. So you *can* do a diagram with $R$ and $T$ being regions, but you don't really see the $x$ and $y$ parts as separate things on the diagram, just pairs of $(x,y)$ points. But the non-visual alternative of thinking of examples works just fine - we might stick with $U =$ set of all cats, and let $R(x,y)$ mean that cat $x$ is bigger than cat $y$ and $T(x,y)$ mean that cat $x$ is older than cat $y$.
You can try to "fix" the visualisation for the two-variable predicates by treating the $x$ and $y$ variables like the $x$ and $y$ axes on the bottom and left edges of the Venn diagram box, and this sort of works. (For a 3-variable predicate you'd have to visualise a 3D Venn "space" diagram, and for 4-variable predicates a 4D space!). The good thing about this visualisation is that you can also draw the one-variable predicates like $P(x)$ and $Q(x)$ as regions on the $x$-axis, but if you had a nice 2D Venn diagram talking about just $P$ and $Q$, it'd just get squashed down to a bunch of line segments on the $x$ axis in the 2D picture.
When I see a statement like $$(\forall x)(\forall y) ~~P(x) \text{ and } Q(x) \text { and } R(x,y),$$
I read that as $$\text{"for every $x$, for every $y$, $P(x)$ is true and $Q(x)$ is true and $R(x,y)$ is true".}$$ Then, probably through years of familiarity with this kind of stuff, that forms into the "picture" that $$\text{$P(x)$ is true for all $x$,}\\\text{$Q(x)$ is true for all $x$,}\\\text{$R(x,y)$ is true for all $x$ and all $y$.}$$
And if we translate that into the silly "cat" universe, that's $$\text{all cats are white,}\\\text{all cats like pizza,}\\\text{every cat $x$ is bigger than every cat $y$.}$$
The last bit isn't helpful, but then again I'd picked a meaning for $R(x,y)$ without knowing anything about it. It's easier to take a bunch of statements in English and translate them into predicate notation, harder to take a bunch of predicate calculus expressions and attempt to translate them into a meaningful model.
But thinking in terms of concrete "objects" (even if we don't know what kinds of things they are) can help to make sense of what's going on with quantifiers ($\forall$ and $\exists$), e.g. it's important when we see something like $$(\forall x)(\forall y) ~\text{blah-blah},$$ to remember that as the variables $x$ and $y$ take on the "value" of each "object" in turn, that we'll also have the case where $x$ and $y$ refer to the *same object*. |
12,022,665 | I am working on a desktop app with JPA(Eclipselink) and a remote mysql database directly.
My persistence.xml i have two PersistenceUnit one uses localhost the other uses my remote database. When i try to load EntityManagerFactory, it works fine on localhost but never gets connected to the remote and no error is provided just a very long wait. Here is part of my persistence.xml
REMOTE MYSQL ON Windows Server 2003.
```
<persistence-unit name="SOFALEnterprisePU3" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.10.138:3306/sofaldb"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
```
LOCAL MYSQL
```
<persistence-unit name="SOFALEnterprisePU2" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/sofaldb"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
``` | 2012/08/18 | [
"https://Stackoverflow.com/questions/12022665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337096/"
] | When you say remote do you mean the same LAN or accross the internet? Cause the IP 192.168.10.138 designates a private LAN so your remote machine has to have an address on the same network like 192.168.10.\*
First make sure to open port 3306 in your windows firewall.
If it is a different network, your router(s) will need to be configured to forward the port and you will have to connect to the public IP of the router.
If it is the same LAN then mysql might not have been setup to accept remote connections for that user name password combination. | In normal JPA, it uses only one persistence.xml per project.But you can try [Spring's JPA](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa) that can use multiple persistence.xml in one project.See this [link](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa-multiple-pu) to deal with multiple persistence units. |
30,710,114 | I have a div class where I want change the css class name when resolution of the user's screen changes. The following script works:
```
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
```
But it has a problem. When I open a browser with a width of 600px and change it to full screen, the mobile class version is not updated. It only works when I reload the page.
How can I make this work without reloading the page? | 2015/06/08 | [
"https://Stackoverflow.com/questions/30710114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4493242/"
] | Move this code into a resize handler:
```
function resize() {
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
}
$(window).on("resize", resize);
resize(); // call once initially
```
---
You can also consider using CSS3 media queries:
```
@media screen and (max-width: 739px) {
/* rules for small screens */
}
@media screen and (min-width: 740px) {
/* rules for large screens */
}
``` | You can simply achieve it using CSS as
```
<style>
@media (max-width: 600px) {
/* your code */
}
@media (min-width: 740px) {
/* your code */
}
</style>
```
[CSS media queries](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries) |
30,710,114 | I have a div class where I want change the css class name when resolution of the user's screen changes. The following script works:
```
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
```
But it has a problem. When I open a browser with a width of 600px and change it to full screen, the mobile class version is not updated. It only works when I reload the page.
How can I make this work without reloading the page? | 2015/06/08 | [
"https://Stackoverflow.com/questions/30710114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4493242/"
] | Move this code into a resize handler:
```
function resize() {
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
}
$(window).on("resize", resize);
resize(); // call once initially
```
---
You can also consider using CSS3 media queries:
```
@media screen and (max-width: 739px) {
/* rules for small screens */
}
@media screen and (min-width: 740px) {
/* rules for large screens */
}
``` | **Why your script does't work**
Your if-else statement will be called on site load and then will never be touched again. For it to work properly you would have to trigger it on a resize event.
**Why you should not use this solution**
Whenever you can solve something with CSS only you should avoid using Javascript. One reason is performance, but there are also edge cases where using Javascript instead of CSS can result in strange behaviour. For example when you use the maximize function of the browser and get the new window size right after this can result in wrong results.
**How you should solve the problem**
```
@media screen and (max-width: 739px) {
#default{
//css rules for smaller screens
}
}
@media screen and (min-width: 740px) {
#default{
//css rules for larger screens
}
}
``` |
30,710,114 | I have a div class where I want change the css class name when resolution of the user's screen changes. The following script works:
```
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
```
But it has a problem. When I open a browser with a width of 600px and change it to full screen, the mobile class version is not updated. It only works when I reload the page.
How can I make this work without reloading the page? | 2015/06/08 | [
"https://Stackoverflow.com/questions/30710114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4493242/"
] | Move this code into a resize handler:
```
function resize() {
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
}
$(window).on("resize", resize);
resize(); // call once initially
```
---
You can also consider using CSS3 media queries:
```
@media screen and (max-width: 739px) {
/* rules for small screens */
}
@media screen and (min-width: 740px) {
/* rules for large screens */
}
``` | Have you tried something like this, but as well as attaching to resize event, attach to load?
Also guys who are saying about media queries are right, but for JS it should be something like:
```
$(window).on('resize load', function () {
if ($(window).width() < 739) {
$("#default").addClass('classnew').removeClass('classold')
} else {
$("#default").addClass('classold').removeClass('classnew')
}
});
```
Hope this works for you =) |
16,647,846 | Is there a way to log the thread or queue that a method is running on / called from? Something like:
```
- (void)foo
{
NSLog(@"Running on %@ queue, %@ thread", queue, thread);
}
``` | 2013/05/20 | [
"https://Stackoverflow.com/questions/16647846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74118/"
] | You can get the current thread with `+[NSThread currentThread]`. That *could* have a `name` property, but if you didn't set one don't rely on it.
Queues are trickier because there are different meanings of "queue". A queue *could* be an `NSOperationQueue`, and you can grab its `name` from `+[NSOperationQueue currentQueue]` (again, assuming you set it).
Then there are *dispatch queues*. You can get the current queue with `dispatch_get_current_queue()`, but be warned that this function will succeed even if called from code that isn't associated with a queue(!). In that case it returns the default background queue Queues are labeled, so you can call `dispatch_queue_get_label()` and if you created the queue with a label, you will get that.
So basically, yes you can get the queue or thread—with the proviso that *all* code has an associated dispatch queue even if it isn't code that was dispatched. You can also usually get meaningful names for these threads and queues, which is handy for debugging: but it's your responsibility to name them. | To get the thread, you can use
```
NSLog(@"Running on %@ thread", [NSThread currentThread]);
``` |
16,647,846 | Is there a way to log the thread or queue that a method is running on / called from? Something like:
```
- (void)foo
{
NSLog(@"Running on %@ queue, %@ thread", queue, thread);
}
``` | 2013/05/20 | [
"https://Stackoverflow.com/questions/16647846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74118/"
] | Here's some Swift code that I'm currently using. This is partly based on another answer I previously posted here at Stack Overflow: <https://stackoverflow.com/a/41294559/253938>
```
/// Struct to contain either the thread name or an (arbitrary) thread number for the current thread.
/// This is partly inspired by code in BaseDestination.swift in XCGLogger. Main thread is
/// arbitrarily given thread number 0. If no thread name can be determined then the memory address
/// of the current Thread object is arbitrarily used as the thread number.
///
/// Re use of "__dispatch_queue_get_label(nil)" (seen in XCGLogger) see here:
/// https://stackoverflow.com/questions/40186868/get-gcd-label-in-swift-3
internal struct ThreadInfo : CustomStringConvertible {
var threadName : String? = nil
var threadNumber : Int64? = nil
/// Initializer.
public init() {
// Process main thread (call it thread 0) and threads whose name can be determined
if Thread.isMainThread {
threadNumber = 0
}
else if let threadName = Thread.current.name, !threadName.isEmpty {
self.threadName = threadName
}
else if let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil)),
!queueName.isEmpty {
threadName = queueName
}
else {
// Convert the memory address of the current Thread object into an Int64 and use it as the
// (arbitrary) thread number
let objPtr = Unmanaged.passUnretained(Thread.current).toOpaque()
let onePtr = UnsafeMutableRawPointer(bitPattern: 1)! // Absolute memory location 1
let rawAddress : Int64 = onePtr.distance(to: objPtr) + 1 // May include high-order bits
threadNumber = rawAddress % (256 * 1024 * 1024 * 1024) // Remove possible high-order bits
}
}
/// Method to implement CustomStringConvertible, returning either the thread name if possible or
/// else the (arbitrary) thread number.
public var description: String {
get {
return
threadName != nil ? String(describing: threadName!) : String(describing: threadNumber!)
}
}
}
```
To use this just instantiate ThreadInfo while running on the thread in question. Then you can display ThreadInfo or embed it in logging data.
```
let threadInfo = ThreadInfo()
print(threadInfo)
``` | To get the thread, you can use
```
NSLog(@"Running on %@ thread", [NSThread currentThread]);
``` |
16,647,846 | Is there a way to log the thread or queue that a method is running on / called from? Something like:
```
- (void)foo
{
NSLog(@"Running on %@ queue, %@ thread", queue, thread);
}
``` | 2013/05/20 | [
"https://Stackoverflow.com/questions/16647846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74118/"
] | You can get the current thread with `+[NSThread currentThread]`. That *could* have a `name` property, but if you didn't set one don't rely on it.
Queues are trickier because there are different meanings of "queue". A queue *could* be an `NSOperationQueue`, and you can grab its `name` from `+[NSOperationQueue currentQueue]` (again, assuming you set it).
Then there are *dispatch queues*. You can get the current queue with `dispatch_get_current_queue()`, but be warned that this function will succeed even if called from code that isn't associated with a queue(!). In that case it returns the default background queue Queues are labeled, so you can call `dispatch_queue_get_label()` and if you created the queue with a label, you will get that.
So basically, yes you can get the queue or thread—with the proviso that *all* code has an associated dispatch queue even if it isn't code that was dispatched. You can also usually get meaningful names for these threads and queues, which is handy for debugging: but it's your responsibility to name them. | You can get the current dispatch queue like this:
```
dispatch_queue_t dispatch_get_current_queue(void);
```
But the header has the following warnings:
>
> Recommended for debugging and logging purposes only:
>
>
> The code must not
> make any assumptions about the queue returned, unless it is one of the
> global queues or a queue the code has itself created. The code must
> not assume that synchronous execution onto a queue is safe from
> deadlock if that queue is not the one returned by
> dispatch\_get\_current\_queue().
>
>
>
so YMMV. |
16,647,846 | Is there a way to log the thread or queue that a method is running on / called from? Something like:
```
- (void)foo
{
NSLog(@"Running on %@ queue, %@ thread", queue, thread);
}
``` | 2013/05/20 | [
"https://Stackoverflow.com/questions/16647846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74118/"
] | You can get the current thread with `+[NSThread currentThread]`. That *could* have a `name` property, but if you didn't set one don't rely on it.
Queues are trickier because there are different meanings of "queue". A queue *could* be an `NSOperationQueue`, and you can grab its `name` from `+[NSOperationQueue currentQueue]` (again, assuming you set it).
Then there are *dispatch queues*. You can get the current queue with `dispatch_get_current_queue()`, but be warned that this function will succeed even if called from code that isn't associated with a queue(!). In that case it returns the default background queue Queues are labeled, so you can call `dispatch_queue_get_label()` and if you created the queue with a label, you will get that.
So basically, yes you can get the queue or thread—with the proviso that *all* code has an associated dispatch queue even if it isn't code that was dispatched. You can also usually get meaningful names for these threads and queues, which is handy for debugging: but it's your responsibility to name them. | Here's some Swift code that I'm currently using. This is partly based on another answer I previously posted here at Stack Overflow: <https://stackoverflow.com/a/41294559/253938>
```
/// Struct to contain either the thread name or an (arbitrary) thread number for the current thread.
/// This is partly inspired by code in BaseDestination.swift in XCGLogger. Main thread is
/// arbitrarily given thread number 0. If no thread name can be determined then the memory address
/// of the current Thread object is arbitrarily used as the thread number.
///
/// Re use of "__dispatch_queue_get_label(nil)" (seen in XCGLogger) see here:
/// https://stackoverflow.com/questions/40186868/get-gcd-label-in-swift-3
internal struct ThreadInfo : CustomStringConvertible {
var threadName : String? = nil
var threadNumber : Int64? = nil
/// Initializer.
public init() {
// Process main thread (call it thread 0) and threads whose name can be determined
if Thread.isMainThread {
threadNumber = 0
}
else if let threadName = Thread.current.name, !threadName.isEmpty {
self.threadName = threadName
}
else if let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil)),
!queueName.isEmpty {
threadName = queueName
}
else {
// Convert the memory address of the current Thread object into an Int64 and use it as the
// (arbitrary) thread number
let objPtr = Unmanaged.passUnretained(Thread.current).toOpaque()
let onePtr = UnsafeMutableRawPointer(bitPattern: 1)! // Absolute memory location 1
let rawAddress : Int64 = onePtr.distance(to: objPtr) + 1 // May include high-order bits
threadNumber = rawAddress % (256 * 1024 * 1024 * 1024) // Remove possible high-order bits
}
}
/// Method to implement CustomStringConvertible, returning either the thread name if possible or
/// else the (arbitrary) thread number.
public var description: String {
get {
return
threadName != nil ? String(describing: threadName!) : String(describing: threadNumber!)
}
}
}
```
To use this just instantiate ThreadInfo while running on the thread in question. Then you can display ThreadInfo or embed it in logging data.
```
let threadInfo = ThreadInfo()
print(threadInfo)
``` |
16,647,846 | Is there a way to log the thread or queue that a method is running on / called from? Something like:
```
- (void)foo
{
NSLog(@"Running on %@ queue, %@ thread", queue, thread);
}
``` | 2013/05/20 | [
"https://Stackoverflow.com/questions/16647846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74118/"
] | Here's some Swift code that I'm currently using. This is partly based on another answer I previously posted here at Stack Overflow: <https://stackoverflow.com/a/41294559/253938>
```
/// Struct to contain either the thread name or an (arbitrary) thread number for the current thread.
/// This is partly inspired by code in BaseDestination.swift in XCGLogger. Main thread is
/// arbitrarily given thread number 0. If no thread name can be determined then the memory address
/// of the current Thread object is arbitrarily used as the thread number.
///
/// Re use of "__dispatch_queue_get_label(nil)" (seen in XCGLogger) see here:
/// https://stackoverflow.com/questions/40186868/get-gcd-label-in-swift-3
internal struct ThreadInfo : CustomStringConvertible {
var threadName : String? = nil
var threadNumber : Int64? = nil
/// Initializer.
public init() {
// Process main thread (call it thread 0) and threads whose name can be determined
if Thread.isMainThread {
threadNumber = 0
}
else if let threadName = Thread.current.name, !threadName.isEmpty {
self.threadName = threadName
}
else if let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil)),
!queueName.isEmpty {
threadName = queueName
}
else {
// Convert the memory address of the current Thread object into an Int64 and use it as the
// (arbitrary) thread number
let objPtr = Unmanaged.passUnretained(Thread.current).toOpaque()
let onePtr = UnsafeMutableRawPointer(bitPattern: 1)! // Absolute memory location 1
let rawAddress : Int64 = onePtr.distance(to: objPtr) + 1 // May include high-order bits
threadNumber = rawAddress % (256 * 1024 * 1024 * 1024) // Remove possible high-order bits
}
}
/// Method to implement CustomStringConvertible, returning either the thread name if possible or
/// else the (arbitrary) thread number.
public var description: String {
get {
return
threadName != nil ? String(describing: threadName!) : String(describing: threadNumber!)
}
}
}
```
To use this just instantiate ThreadInfo while running on the thread in question. Then you can display ThreadInfo or embed it in logging data.
```
let threadInfo = ThreadInfo()
print(threadInfo)
``` | You can get the current dispatch queue like this:
```
dispatch_queue_t dispatch_get_current_queue(void);
```
But the header has the following warnings:
>
> Recommended for debugging and logging purposes only:
>
>
> The code must not
> make any assumptions about the queue returned, unless it is one of the
> global queues or a queue the code has itself created. The code must
> not assume that synchronous execution onto a queue is safe from
> deadlock if that queue is not the one returned by
> dispatch\_get\_current\_queue().
>
>
>
so YMMV. |
65,591,564 | I have an html form from which I need to collect data and call a POST on a rest api. I am trying to do this using javascript and $.ajax but confused on how to setup the URL and collect data as I am very new to it. Could someone explain this fully, with an example if possible as I'm having trouble finding detailed documentation. | 2021/01/06 | [
"https://Stackoverflow.com/questions/65591564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14949649/"
] | Try this:
```
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" value="3" name="id" id="GetId">
<button id="LoginBtn">login</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$("#LoginBtn").click(function (e){
e.preventDefault();
var settings = {
"url": "http://192.168.1.3:8071/user/login",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({"username":"user","password":"123456"}),
};
$.ajax({
...settings,
success: function (result) {
alert("success")
},
error : function (){
alert("error")
}
})
})
</script>
</body>
</html>
``` | Please read this simple article
<https://javascript.info/fetch>
You could use axios or jquery but fetch api is really simple |
16,388,516 | To scale an element with CSS based on various viewport heights is tedious to say the least, and should IMO not be needed. Then again, I might be totally wrong.
I am wondering if it is at all possible to use jQuery in order to automatically set the scale of an element based on the height of the viewport?
I have checked every link I can find here on Stackflow to no avail and I have checked out <http://ricostacruz.com/jquery.transit/> which seems like a viable option but I don't know how to calculate the height and turn it into a value so I can use it for CSS transformation scale.
I am not sure, but I might need "check points" so that a specific height will be a preset value.
I will also need to be able to adjust the scale manually so I can adjust the scaling to make the element fit most viewports.
This is my example:
<http://testsiten.se/modernaglas/images/showcase/bedroom/>
I need the whole content within the class .scales to scale according to the height of the viewport and also update if orientation is changed.
The width is the same as the height so it shouldn't pose a problem since it won't ever be wider than the height.
I do NOT want to change the height of `.scales` as that would break the whole design.
I have done some real crappy CSS media queries, which haven't been cleaned up since I figured it just HAVE to be easier to do all of this with jQuery.
This is my CSS.
```
body, html{ background-color: #333333; font-family: tahoma; margin: 0; padding: 0; }
img{background: none}
h1 {font-size: 18px; margin: 0; font-weight: normal; text-align: center}
#ChangableElements {width: 958px; margin:0 auto; }
#navigation {background-color: #bdc7c9; color: #6e7377;padding: 7px 8px 5px 21px;}
#navigation div div {display: inline-block;}
#navigation div div span{display: block;}
.nav_glas, .nav_ram {display: inline-block;font-size: 13px;text-align: center;}
.nav_glas div, .nav_ram div{padding: 1px 13px 0 10px;}
.nav_glas div a, .nav_ram div a{display: inline-block; margin: 8px 0 10px;}
.nav_ram{float: right;}
.work_area {margin-bottom: 0; background: url("images/bg_image.png") repeat scroll 0 0 transparent; height: auto;width: 958px;}
.border, .grid{margin-top: 0px;position: absolute;top: 0;}
.grid_on {width: 50px}
.headers h1{display: inline-block;}
.headers h1:first-child{float: left; margin-left: 10px; }
.headers{display: block!important;padding: 0 !important;}
.hidden {display: none;}
```
One of my Media Queries
```
@media only screen and (min-device-width : 719px) and (max-device-width : 721px) and (orientation : portrait) {
div.scales
{
transform: scale(0.37);
-ms-transform: scale(0.37); /* IE 9 */
-webkit-transform: scale(0.37); /* Safari and Chrome */
-o-transform: scale(0.37); /* Opera */
-moz-transform: scale(0.37); /* Firefox */
transform-origin: top center;
-ms-transform-origin: top center;
-webkit-transform-origin: top center;
-o-transform-origin: top center;
-moz-transform-origin: top center;
}
}
```
This is my jQuery:
```
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function changeImage(el, img_url) {
$(document).find(el).attr('src', img_url);
}
$(document).ready(function(){
// add color btns event
$('.nav_glas').find('a.spegel').click(function(){
changeImage('#mirror', 'images/spegel.png');
});
$('.nav_glas').find('a.vit_traskiva').click(function(){
changeImage('#mirror', 'images/vit_traskiva.png');
});
$('.nav_glas').find('a.vitt_glas').click(function(){
changeImage('#mirror', 'images/vitt_glas.png');
});
$('.nav_glas').find('a.metall_glas').click(function(){
changeImage('#mirror', 'images/metall_gra.png');
});
$('.nav_glas').find('a.gult_glas').click(function(){
changeImage('#mirror', 'images/gult_glas.png');
});
$('.nav_glas').find('a.rott_glas').click(function(){
changeImage('#mirror', 'images/rott_glas.png');
});
$('.nav_glas').find('a.svart_glas').click(function(){
changeImage('#mirror', 'images/svart_glas.png');
});
});
</script>
<script type="text/javascript">
function changeImage(el, img_url) {
$(document).find(el).attr('src', img_url);
}
var app = {
isActive: function(el){
if($(el).hasClass('active')) {
return true;
}
else {
return false;
}
},
whoActive: function(){
return $('.active').attr('id');
},
change_grid: function(image){
changeImage('#grid', image);
}
}
$(document).ready(function(){
// add color btns event
$('.nav_ram').find('a.vit').click(function(){
$('a').removeClass('active');
$(this).addClass('active');
changeImage('#border', 'images/vit_el.png');
app.change_grid('images/grid_vit.png');
});
$('.nav_ram').find('a.silvermatt').click(function(){
$('a').removeClass('active');
$(this).addClass('active');
changeImage('#border', 'images/silver_el.png');
app.change_grid('images/grid_silvermatt.png');
});
$('.nav_ram').find('a.svart').click(function(){
$('a').removeClass('active');
$(this).addClass('active');
changeImage('#border', 'images/svart_blank_el.png');
app.change_grid('images/grid_svart.png');
});
// grid_turn_on event
$('.grid_turn_on').click(function(event){
var grid_on = $('.grid_on'); // div el
var grid = $('#grid');
var is_hidden = false;
if(grid.hasClass('hidden')) {
is_hidden = true;
}
else {
is_hidden = false;
}
log(app.whoActive());
switch (app.whoActive()) {
case 'vit':
log('is vit');
if(is_hidden) {
grid.removeClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_on.jpg');
changeImage('#grid', 'images/grid_silvermatt.png');
} else {
grid.addClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_off.jpg');
}
break;
case 'silvermatt':
log('is silver');
if(is_hidden) {
grid.removeClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_on.jpg');
changeImage('#grid', 'images/grid_silvermatt.png');
} else {
grid.addClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_off.jpg');
}
break;
case 'svart':
log('is svart');
if(is_hidden) {
grid.removeClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_on.jpg');
changeImage('#grid', 'images/grid_svart.png');
} else {
grid.addClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_off.jpg');
}
break;
default:
if(is_hidden) {
grid.removeClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_on.jpg');
}
else {
grid.addClass('hidden');
grid_on.find('span').empty().append('Ja/Nej');
grid_on.find('img').attr('src','images/grid_off.jpg');
}
}
});
});
</script>
```
And this is my HTML.
```
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<title>mirror</title>
</head>
<body>
<div class="scales" id="ChangableElements">
<div class="work_area">
<img src="images/grid_svart.png" alt="" id="grid" class="grid">
<img src="images/svart_blank_el.png" alt="" id="border" class="border">
<img src="images/vitt_glas.png" alt="" id="mirror">
</div>
<div id="navigation">
<div class="nav_glas">
<h1>Välj färg på glas/skiva</h1>
<div><a class="spegel"><img src="images/pic1.jpg" alt=""></a><span>Spegel</span></div>
<div><a class="vit_traskiva"><img src="images/pic2.jpg" alt=""></a><span>Vit träskiva</span></div>
<div><a class="vitt_glas"><img src="images/pic3.jpg" alt=""></a><span>Vitt glas</span></div>
<div><a class="metall_glas"><img src="images/pic4.jpg" alt=""></a><span>Metallgrått glas</span></div>
<div><a class="gult_glas"><img src="images/pic5.jpg" alt=""></a><span>Gult glas</span></div>
<div><a class="rott_glas"><img src="images/pic6.jpg" alt=""></a><span>Rött glas</span></div>
<div><a class="svart_glas"><img src="images/pic7.jpg" alt=""></a><span>Svart glas</span></div>
</div>
<div class="nav_ram" id="tfoot">
<div class="headers">
<h1>Spröjs</h1>
<h1>Välj färg på dörrens ram</h1>
</div>
<div class="grid_on"><a class="grid_turn_on" ><img src="images/grid_on.jpg" alt=""></a><span>Ja/Nej</span></div>
<div><a class="vit" id="vit"><img src="images/pic2_1.jpg" alt=""></a><span>Vit blank</span></div>
<div><a class="silvermatt" id="silvermatt"><img src="images/pic2_2.jpg" alt=""></a><span>Silvermatt</span></div>
<div><a class="svart" id="svart"><img src="images/pic2_3.jpg" alt=""></a><span>Svart blank</span></div>
</div>
</div>
</div>
</body>
</html>
```
As one can see I have alot of elements inside the .scales and there is also a background image in there. This is why I need it to scale rather than to set the height because there are so many elements dependent on the scale of the .scales.
I hope I made myself understood now. :D
Edit:
Finally learned some jQ in order to get this functional.
```
<script type="text/javascript">
$(document).ready(function(){
$(window).on('resize', function(){
var vpheight = $(window).height();
var vpwidth = $(window).width();
if(vpwidth>vpheight) {
// Landscape
var height = $(window).height() * 0.00148;
var width = height / 2 * -958;
$('.scales').css('transform', 'scale(' + height + ')');
$('.scales').css('-ms-transform', 'scale(' + height + ')');
$('.scales').css('-webkit-transform', 'scale(' + height + ')');
$('.scales').css('-o-transform', 'scale(' + height + ')');
$('.scales').css('-moz-transform', 'scale(' + height + ')');
$('#ChangableElements').css({'left': width + 'px'});
} else if(vpwidth <=720 && vpheight > 569 ) {
var height = $(window).height() * 0.000675;
var width = height / 2 * -958;
$('.scales').css('transform', 'scale(' + height + ')');
$('.scales').css('-ms-transform', 'scale(' + height + ')');
$('.scales').css('-webkit-transform', 'scale(' + height + ')');
$('.scales').css('-o-transform', 'scale(' + height + ')');
$('.scales').css('-moz-transform', 'scale(' + height + ')');
$('#ChangableElements').css({'left': width + 'px'});
} else {
// Portrait
var height = $(window).height() * 0.000895;
var width = height / 2 * -958;
$('.scales').css('transform', 'scale(' + height + ')');
$('.scales').css('-ms-transform', 'scale(' + height + ')');
$('.scales').css('-webkit-transform', 'scale(' + height + ')');
$('.scales').css('-o-transform', 'scale(' + height + ')');
$('.scales').css('-moz-transform', 'scale(' + height + ')');
$('#ChangableElements').css({'left': width + 'px'});
}
}).resize()
});
</script>
```
The weird vpwidth <=720 && vpheight > 569 is for forcing my Samsung Galaxy S3 function properly. Strange resolution... | 2013/05/05 | [
"https://Stackoverflow.com/questions/16388516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1802982/"
] | It's easy enough to scale a top level element to some percentage of the viewport height. Just set the height property on the html and body elements to 100% and then any child of the body can use a percentage height and that will correspond to the viewport height.
For example, something like the CSS below would make a div with class *scale* fill the height of the viewport. [Example codepen](http://codepen.io/anon/pen/klnyp)
```
html, body {
height:100%;
margin:0;
}
.scale {
background-color:orange;
width:200px;
height:100%;
margin:0 auto;
}
```
If you aren't too worried about older browsers, you can also just viewport units anywhere in the markup. This makes things a lot easier, and also allows you to set a width based on the viewport hight or vice versa.
For example, a square with sides matching the viewport height could be implemented like this:
```
body {
margin:0;
}
.scale {
background-color:orange;
width:100vh;
height:100vh;
margin:0 auto;
}
```
That said, viewport units don't always respond immediately to resizing and can behave unexpectedly when scrollbars are involved, so there are tradeoffs. | You can use `$(window).height()`, like in:
```
var winHeight = $(window).height();
```
Then change the width according to the height and set both properties, something like:
```
$("#theElement").css({'width':varWidth, 'height':varHeight});
``` |
2,643,741 | I think complex number is really just 2D vector with product defined differently. But what is the significance of the way the product is defined for complex number: $(x\_1x\_2-y\_1y\_2,x\_1y\_2+x\_2y\_1)$? Why don't we go with say this $(-y\_2,x\_1y\_2+x\_2y\_1)$? We still have $i^2=-1$ right? | 2018/02/09 | [
"https://math.stackexchange.com/questions/2643741",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294291/"
] | When you deal with $(a,b)$, what you should really have in mind is $a + bi$, even if you haven't yet formally defined it that way. Now, having that in mind, the multiplication becomes completely natural from the need to satisfy distributivity, commutativity and associativity (and $i ^ 2 = -1$):
$$(a + bi)(c+di) = ac + adi + bic + bdi^2 = (ac - bd) + (ad + bc)i$$
So, in the formal definition of multiplication of complex numbers we would write
$$(a,b) \cdot (c,d) = (ac - bd, ad + bc)$$ | It is very useful to define the multiplication of the complex numbers so that you get a field. This multiplication needs to extend multiplication of the reals, be associative, have inverses for non-zero elements, and satisfy the distributive property. Defined in the usual way, the complex numbers have the incredibly useful property that every polynomial with coefficients in the complex numbers has a root. While there are other ways to define multiplication on the complex numbers (for example instead of adding $\sqrt{-1}$ to the real numbers, add a non-trivial cube root of 1) the rules for multiplying won't be nearly as nice. |
2,643,741 | I think complex number is really just 2D vector with product defined differently. But what is the significance of the way the product is defined for complex number: $(x\_1x\_2-y\_1y\_2,x\_1y\_2+x\_2y\_1)$? Why don't we go with say this $(-y\_2,x\_1y\_2+x\_2y\_1)$? We still have $i^2=-1$ right? | 2018/02/09 | [
"https://math.stackexchange.com/questions/2643741",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294291/"
] | When you deal with $(a,b)$, what you should really have in mind is $a + bi$, even if you haven't yet formally defined it that way. Now, having that in mind, the multiplication becomes completely natural from the need to satisfy distributivity, commutativity and associativity (and $i ^ 2 = -1$):
$$(a + bi)(c+di) = ac + adi + bic + bdi^2 = (ac - bd) + (ad + bc)i$$
So, in the formal definition of multiplication of complex numbers we would write
$$(a,b) \cdot (c,d) = (ac - bd, ad + bc)$$ | We already know how to multiply sums because multiplication distributes over addition, so this is the rule $(a+b)(c+d) = a(c+d) + b(c+d) = ac+ad+bc+bd$. If it is possible (it may not be!) we would like to use such a rule.
So we don't know what $\sqrt{-1}$ is. But if it were a number as we understand them (it may not be!) it should satisfy this multiplication. Then
$$(a+b\sqrt{-1})(c+d\sqrt{-1}) = a(c+d\sqrt{-1}) + b\sqrt{-1}(c+d\sqrt{-1}) \\
= ac + ad\sqrt{-1} + bc\sqrt{-1} + bd\sqrt{-1}\sqrt{-1}$$
Now by our understanding of what a square root means, we want $\sqrt{-1}\cdot \sqrt{-1} = -1$, so our product is just
$$(ac-bd) + (ad+bc)\sqrt{-1}$$
A complex number is indeed just a two component vector. When we define it this way have multiplication by a complex number $a+b\sqrt{-1}$ as multiplication by the matrix
$$\pmatrix{a & -b \\ b & a}$$
If you work through the algebra of $\pmatrix{a & -b \\ b & a}\times \pmatrix{c \\ d}$ then you will see these are identical. We can also use this to demonstrate that $A\times (B + C) = A\times B + A\times C$, that $A\times(B\times C) = (A\times B)\times C$, that $A\times B = B\times A$ and that if both $a$ and $b$ are nonzero then then $A^{-1}$ exists and $A\times A^{-1} = 1$.
So this is a very fruitful definition of multiplication. It's almost forced on us by our prior understanding. |
35,606,860 | I would like to schedule a function which will run every 3 seconds until my app exits. I don't use setInterval because If something goes wrong it shouldn't be scheduled anymore so i use setTimeout
i wrote something like this
```
function someWork(){
setTimeout(function(){
//do Stuff here
someWork();
},3000)
}
```
will it cause any memory , or performance leaks. or is there any better solution? | 2016/02/24 | [
"https://Stackoverflow.com/questions/35606860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | You are rounding to the nearest 10. You can use modulo 10 to get the remainder:
```
$totalRows = 54;
$remainder = $totalRows % 10;
print $remainder; //prints 4
``` | Simply do
```
print $totalRows - $v;
```
As far as I know, there's not a function to retrieve it, but pure mathematical operation should be good enough. |
267,593 | I want to get product collection for current category while I am on a list page.
I want to get current product collection for current category while ajax call **(i want the same collection in the controller which return some data based on collection)** so is there any way that I can get the same product collection which was used in **list.phtml**
Here is code, which returns product collection but results not match 100%
```
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Context;
class Model extends \Magento\Framework\App\Action\Action
{
protected $resultJsonFactory;
protected $request;
protected $store_manager;
protected $productRepository;
protected $searchCriteriaBuilder;
protected $eavConfig;
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\App\RequestInterface $request,
\Magento\Store\Model\StoreManagerInterface $store_manager,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collection,
\Magento\Catalog\Model\CategoryRepository $categoryRepository,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Eav\Model\Config $eavConfig)
{
$this->request = $request;
$this->resultJsonFactory = $resultJsonFactory;
$this->store_manager = $store_manager;
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->eavConfig = $eavConfig;
$this->productCollection = $collection;
$this->categoryRepository = $categoryRepository;
$this->_categoryFactory = $categoryFactory;
parent::__construct($context);
}
public function execute()
{
$data = $this->request->getParams();
$parent_category_id = $data['current_category_id'];
$productsCollection=$this->getProductCollection($parent_category_id);
$productsCollection->addAttributeToFilter('make',array('in'=>array(floatval($data['make']))));
}
private function getStoreCode()
{
return $this->store_manager->getStore()->getCode();
}
public function getProductCollection($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
$collection = $this->productCollection->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
}
}
```
Does anyone have any idea how can I achieve my above requirement?
Thanks | 2019/03/27 | [
"https://magento.stackexchange.com/questions/267593",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/42301/"
] | Try below code
```
namespace Vendor\Module\Block\Home;
use Magento\Catalog\Api\CategoryRepositoryInterface;
class Products extends \Magento\Catalog\Block\Product\ListProduct {
protected $_collection;
protected $categoryRepository;
protected $_resource;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Framework\Data\Helper\PostHelper $postDataHelper,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
CategoryRepositoryInterface $categoryRepository,
\Magento\Framework\Url\Helper\Data $urlHelper,
\Magento\Catalog\Model\ResourceModel\Product\Collection $collection,
\Magento\Framework\App\ResourceConnection $resource,
array $data = []
) {
$this->categoryRepository = $categoryRepository;
$this->_collection = $collection;
$this->_resource = $resource;
parent::__construct($context, $postDataHelper, $layerResolver, $categoryRepository, $urlHelper, $data);
}
public function getProducts() {
$count = $this->getProductCount();
$category_id = $this->getData("category_id");
$collection = clone $this->_collection;
$collection->clear()->getSelect()->reset(\Magento\Framework\DB\Select::WHERE)->reset(\Magento\Framework\DB\Select::ORDER)->reset(\Magento\Framework\DB\Select::LIMIT_COUNT)->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET)->reset(\Magento\Framework\DB\Select::GROUP);
if(!$category_id) {
$category_id = $this->_storeManager->getStore()->getRootCategoryId();
}
$category = $this->categoryRepository->get($category_id);
if(isset($category) && $category) {
$collection->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('small_image')
->addAttributeToSelect('thumbnail')
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->addUrlRewrite()
->addCategoryFilter($category)
->addAttributeToSort('created_at','desc');
} else {
$collection->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('small_image')
->addAttributeToSelect('thumbnail')
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->addUrlRewrite()
->addAttributeToFilter('is_saleable', 1, 'left')
->addAttributeToSort('created_at','desc');
}
$collection->getSelect()
->order('created_at','desc')
->limit($count);
return $collection;
}
public function getLoadedProductCollection() {
return $this->getProducts();
}
public function getProductCount() {
$limit = $this->getData("product_count");
if(!$limit)
$limit = 10;
return $limit;
}
}
```
Then you can use in the template this:
```
<?php foreach ($block->getLoadedProductCollection() as $product) : ?>
<!-- do something with $product -->
<?php endforeach;?>
``` | Try to use this below code in your block file :
```
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorName\ModuleName\Block;
class Data extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Catalog\Model\CategoryFactory
*/
protected $categoryFactory;
/**
* @var \Magento\Framework\Registry
*/
protected $registry;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->_categoryFactory = $categoryFactory;
$this->registry = $registry;
parent::__construct($context, $data);
}
public function getProductNameList($catUrlKey) {
$categoryId = $this->registry->registry('current_category')->getId();
$product = $this->categoryFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*');
$product->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_CATALOG);
$product->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $product;
}
}
?>
``` |
267,593 | I want to get product collection for current category while I am on a list page.
I want to get current product collection for current category while ajax call **(i want the same collection in the controller which return some data based on collection)** so is there any way that I can get the same product collection which was used in **list.phtml**
Here is code, which returns product collection but results not match 100%
```
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Context;
class Model extends \Magento\Framework\App\Action\Action
{
protected $resultJsonFactory;
protected $request;
protected $store_manager;
protected $productRepository;
protected $searchCriteriaBuilder;
protected $eavConfig;
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\App\RequestInterface $request,
\Magento\Store\Model\StoreManagerInterface $store_manager,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collection,
\Magento\Catalog\Model\CategoryRepository $categoryRepository,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Eav\Model\Config $eavConfig)
{
$this->request = $request;
$this->resultJsonFactory = $resultJsonFactory;
$this->store_manager = $store_manager;
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->eavConfig = $eavConfig;
$this->productCollection = $collection;
$this->categoryRepository = $categoryRepository;
$this->_categoryFactory = $categoryFactory;
parent::__construct($context);
}
public function execute()
{
$data = $this->request->getParams();
$parent_category_id = $data['current_category_id'];
$productsCollection=$this->getProductCollection($parent_category_id);
$productsCollection->addAttributeToFilter('make',array('in'=>array(floatval($data['make']))));
}
private function getStoreCode()
{
return $this->store_manager->getStore()->getCode();
}
public function getProductCollection($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
$collection = $this->productCollection->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
}
}
```
Does anyone have any idea how can I achieve my above requirement?
Thanks | 2019/03/27 | [
"https://magento.stackexchange.com/questions/267593",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/42301/"
] | Try to use this below code in your block file :
```
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorName\ModuleName\Block;
class Data extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Catalog\Model\CategoryFactory
*/
protected $categoryFactory;
/**
* @var \Magento\Framework\Registry
*/
protected $registry;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->_categoryFactory = $categoryFactory;
$this->registry = $registry;
parent::__construct($context, $data);
}
public function getProductNameList($catUrlKey) {
$categoryId = $this->registry->registry('current_category')->getId();
$product = $this->categoryFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*');
$product->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_CATALOG);
$product->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $product;
}
}
?>
``` | You can use a block like this. Loads the current catalog layer ( asuming you are in a category list page ) and from there you can get the loaded collection
```
namespace Vendor\Module\Block;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Framework\View\Element\Template;
class Category extends \Magento\Framework\View\Element\Template
{
private $registry;
private $catalogLayer;
public function __construct(
Template\Context $context,
\Magento\Framework\Registry $registry,
Resolver $layerResolver,
array $data = array()
)
{
$this->registry = $registry;
$this->catalogLayer = $layerResolver->get(); // This is where we get the catalog layer with the loaded data
parent::__construct($context, $data);
}
public function getAllVisibleProducts() {
$productsCollection = $this->catalogLayer->getProductCollection(); // This is where we load the category collection
$productData = [];
foreach ($productsCollection as $item) {
$productData[] = [
'id' => $item->getId(),
'name' => $item->getName(),
'price' => $item->getFinalPrice(),
];
}
return $productData;
}
}
``` |
267,593 | I want to get product collection for current category while I am on a list page.
I want to get current product collection for current category while ajax call **(i want the same collection in the controller which return some data based on collection)** so is there any way that I can get the same product collection which was used in **list.phtml**
Here is code, which returns product collection but results not match 100%
```
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Context;
class Model extends \Magento\Framework\App\Action\Action
{
protected $resultJsonFactory;
protected $request;
protected $store_manager;
protected $productRepository;
protected $searchCriteriaBuilder;
protected $eavConfig;
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\App\RequestInterface $request,
\Magento\Store\Model\StoreManagerInterface $store_manager,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collection,
\Magento\Catalog\Model\CategoryRepository $categoryRepository,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Eav\Model\Config $eavConfig)
{
$this->request = $request;
$this->resultJsonFactory = $resultJsonFactory;
$this->store_manager = $store_manager;
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->eavConfig = $eavConfig;
$this->productCollection = $collection;
$this->categoryRepository = $categoryRepository;
$this->_categoryFactory = $categoryFactory;
parent::__construct($context);
}
public function execute()
{
$data = $this->request->getParams();
$parent_category_id = $data['current_category_id'];
$productsCollection=$this->getProductCollection($parent_category_id);
$productsCollection->addAttributeToFilter('make',array('in'=>array(floatval($data['make']))));
}
private function getStoreCode()
{
return $this->store_manager->getStore()->getCode();
}
public function getProductCollection($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
$collection = $this->productCollection->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
}
}
```
Does anyone have any idea how can I achieve my above requirement?
Thanks | 2019/03/27 | [
"https://magento.stackexchange.com/questions/267593",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/42301/"
] | Try below code
```
namespace Vendor\Module\Block\Home;
use Magento\Catalog\Api\CategoryRepositoryInterface;
class Products extends \Magento\Catalog\Block\Product\ListProduct {
protected $_collection;
protected $categoryRepository;
protected $_resource;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Framework\Data\Helper\PostHelper $postDataHelper,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
CategoryRepositoryInterface $categoryRepository,
\Magento\Framework\Url\Helper\Data $urlHelper,
\Magento\Catalog\Model\ResourceModel\Product\Collection $collection,
\Magento\Framework\App\ResourceConnection $resource,
array $data = []
) {
$this->categoryRepository = $categoryRepository;
$this->_collection = $collection;
$this->_resource = $resource;
parent::__construct($context, $postDataHelper, $layerResolver, $categoryRepository, $urlHelper, $data);
}
public function getProducts() {
$count = $this->getProductCount();
$category_id = $this->getData("category_id");
$collection = clone $this->_collection;
$collection->clear()->getSelect()->reset(\Magento\Framework\DB\Select::WHERE)->reset(\Magento\Framework\DB\Select::ORDER)->reset(\Magento\Framework\DB\Select::LIMIT_COUNT)->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET)->reset(\Magento\Framework\DB\Select::GROUP);
if(!$category_id) {
$category_id = $this->_storeManager->getStore()->getRootCategoryId();
}
$category = $this->categoryRepository->get($category_id);
if(isset($category) && $category) {
$collection->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('small_image')
->addAttributeToSelect('thumbnail')
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->addUrlRewrite()
->addCategoryFilter($category)
->addAttributeToSort('created_at','desc');
} else {
$collection->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('small_image')
->addAttributeToSelect('thumbnail')
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->addUrlRewrite()
->addAttributeToFilter('is_saleable', 1, 'left')
->addAttributeToSort('created_at','desc');
}
$collection->getSelect()
->order('created_at','desc')
->limit($count);
return $collection;
}
public function getLoadedProductCollection() {
return $this->getProducts();
}
public function getProductCount() {
$limit = $this->getData("product_count");
if(!$limit)
$limit = 10;
return $limit;
}
}
```
Then you can use in the template this:
```
<?php foreach ($block->getLoadedProductCollection() as $product) : ?>
<!-- do something with $product -->
<?php endforeach;?>
``` | You can use a block like this. Loads the current catalog layer ( asuming you are in a category list page ) and from there you can get the loaded collection
```
namespace Vendor\Module\Block;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Framework\View\Element\Template;
class Category extends \Magento\Framework\View\Element\Template
{
private $registry;
private $catalogLayer;
public function __construct(
Template\Context $context,
\Magento\Framework\Registry $registry,
Resolver $layerResolver,
array $data = array()
)
{
$this->registry = $registry;
$this->catalogLayer = $layerResolver->get(); // This is where we get the catalog layer with the loaded data
parent::__construct($context, $data);
}
public function getAllVisibleProducts() {
$productsCollection = $this->catalogLayer->getProductCollection(); // This is where we load the category collection
$productData = [];
foreach ($productsCollection as $item) {
$productData[] = [
'id' => $item->getId(),
'name' => $item->getName(),
'price' => $item->getFinalPrice(),
];
}
return $productData;
}
}
``` |
51,398,335 | I am trying to create a record of `salesorderdetail` and got an error:
```
{
"error":
{
"code":"0x80040216",
"message":"An unexpected error occurred.",
"innererror":
{
"message":"An unexpected error occurred.",
"type":"System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
"stacktrace":" at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.CreateInternal(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.CreateOrganizationResponse(Entity entity)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
```
My request:
```
POST [Organization URI]/api/data/v9.0/salesorderdetails
Accept: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0
Authorization: Bearer *key*
Prefer: return=representation
Content-Type: application/json;IEEE754Compatible=true
{
"productname":"Test"
}
```
My guess is the error occurred because my `salesorderdetail` doesn't have `salesorderid`? If so, any way to create `salesorderdetail` alone? | 2018/07/18 | [
"https://Stackoverflow.com/questions/51398335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4476568/"
] | A type guard impacts the type of a parameter and must return a boolean. So a valid implementation would be:
```
function foo<T>(obj: T): obj is T & { bar: string }{
obj['bar'] = 'biz';
return true;
}
let o = { foo: "string" }
if(foo(o)) {
o.bar //valid
o.foo //valid
}
```
Unfortunately there isn't an assertion mode to type guards. A type guard must return a `booelan` and be used in an `if` statement to impact the type of a variable. | Thanks to the answer provided by @TitianCernicova-Dragomir I ended up doing it like this:
```
function foo<T>(obj: T): obj is T & { bar: string }{
obj['bar'] = 'biz';
return true;
}
const obj = { foo: "string" }
if(!foo(obj)) throw 'This will never happen';
o.bar //valid
o.foo //valid
``` |
258,862 | If you want to enter someone's bedroom and you want to avoid unpleasant situations(they're changing their clothes,for example) what would you say? | 2015/07/12 | [
"https://english.stackexchange.com/questions/258862",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/128884/"
] | You can simply knock on the door and wait to be invited. If they respond "Hello?" that may not be an invitation to enter, merely to announce yourself and why you wish to enter.
You could state your intentions:
>
> May I come in and... (do whatever it is you need access to their room to do)?
>
>
>
I assume, of course, that you have a good reason for entering their room!
If you particularly want to check if they are appropriately clothed, etc., you could ask:
>
> Are you [decent](http://dictionary.cambridge.org/dictionary/british/decent)?
>
>
>
Although is is safer to be more explicit that you want to come in rather than assuming you have the right to enter their room whenever they're clothed. | One strategy is to feign complete ignorance. Knock on the door, and say
>
> "Knock, knock? Anyone in there?"
>
>
>
This avoids the need to ask any specific question. Asking "Are you decent?" is for some a bit personal, especially if you are not on close terms. After all, it suggests that you have been considering the possibility that he or she is *not* decent. |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | This is a partial answer, but yes, if you are simply appending I would use:
```
cat extra.txt >> huge_file.txt
```
or
```
echo "Single line to add" >> huge_file.txt
```
For prepending I would do:
```
cat extra.txt huge_file.txt > huge_file_new.txt
``` | [UltraEdit](http://www.ultraedit.com) is capable of editing a file without loading it into memory. I haven't tested the Linux version of it yet, and neither have I tested a >4GB file, so I cannot give any guarantees, but I edited some huge (~1.5 GB) files with the Windows version (and long ago, too). |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | If all you need is to append, then `>>huge_file` is much better than what any editor can do, because it won't touch the existing data. Inserting data into a file requires rewriting everything after the insertion point, so it'll be slow even with the right tools.
With vim, make sure you try with the [LargeFile plugin](http://www.vim.org/scripts/script.php?script_id=1506).
[Bvi](http://bvi.sourceforge.net) is a version of vi that targets binary files. It can edit a slice of a file (i.e. from position x to position y).
The [wikipedia editor comparison page](http://en.wikipedia.org/wiki/Comparison_of_text_editors) has a column with large file support. The situation is pretty bleak. | [UltraEdit](http://www.ultraedit.com) is capable of editing a file without loading it into memory. I haven't tested the Linux version of it yet, and neither have I tested a >4GB file, so I cannot give any guarantees, but I edited some huge (~1.5 GB) files with the Windows version (and long ago, too). |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | Ultraedit is the only editor that does this well. I would, also, prefer an OSS. One doesn't exist. I'm particularly surprised that this isn't a capability of vi... it's such a swiss army knife. | [UltraEdit](http://www.ultraedit.com) is capable of editing a file without loading it into memory. I haven't tested the Linux version of it yet, and neither have I tested a >4GB file, so I cannot give any guarantees, but I edited some huge (~1.5 GB) files with the Windows version (and long ago, too). |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | Just because I found this via google looking for something similar this is another method I found.
Situation: You have a 4.0 GB file and you need to edit line number 120.
Solution: Using head and tail to get everything except the line you want to edit.
```
# cat origfile.txt
1
2
3
4
5
6
7
8
9
10
# head -n 5 origfile.txt >> newfile.txt
# echo "line 6" >> newfile.txt
# tail -n +7 origfile.txt >> newfile.txt
# cat newfile.txt
1
2
3
4
5
line 6
7
8
9
10
```
From my testing tail will not load the entire file into memory all at once. | [UltraEdit](http://www.ultraedit.com) is capable of editing a file without loading it into memory. I haven't tested the Linux version of it yet, and neither have I tested a >4GB file, so I cannot give any guarantees, but I edited some huge (~1.5 GB) files with the Windows version (and long ago, too). |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | This is a partial answer, but yes, if you are simply appending I would use:
```
cat extra.txt >> huge_file.txt
```
or
```
echo "Single line to add" >> huge_file.txt
```
For prepending I would do:
```
cat extra.txt huge_file.txt > huge_file_new.txt
``` | If all you need is to append, then `>>huge_file` is much better than what any editor can do, because it won't touch the existing data. Inserting data into a file requires rewriting everything after the insertion point, so it'll be slow even with the right tools.
With vim, make sure you try with the [LargeFile plugin](http://www.vim.org/scripts/script.php?script_id=1506).
[Bvi](http://bvi.sourceforge.net) is a version of vi that targets binary files. It can edit a slice of a file (i.e. from position x to position y).
The [wikipedia editor comparison page](http://en.wikipedia.org/wiki/Comparison_of_text_editors) has a column with large file support. The situation is pretty bleak. |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | This is a partial answer, but yes, if you are simply appending I would use:
```
cat extra.txt >> huge_file.txt
```
or
```
echo "Single line to add" >> huge_file.txt
```
For prepending I would do:
```
cat extra.txt huge_file.txt > huge_file_new.txt
``` | Ultraedit is the only editor that does this well. I would, also, prefer an OSS. One doesn't exist. I'm particularly surprised that this isn't a capability of vi... it's such a swiss army knife. |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | This is a partial answer, but yes, if you are simply appending I would use:
```
cat extra.txt >> huge_file.txt
```
or
```
echo "Single line to add" >> huge_file.txt
```
For prepending I would do:
```
cat extra.txt huge_file.txt > huge_file_new.txt
``` | Just because I found this via google looking for something similar this is another method I found.
Situation: You have a 4.0 GB file and you need to edit line number 120.
Solution: Using head and tail to get everything except the line you want to edit.
```
# cat origfile.txt
1
2
3
4
5
6
7
8
9
10
# head -n 5 origfile.txt >> newfile.txt
# echo "line 6" >> newfile.txt
# tail -n +7 origfile.txt >> newfile.txt
# cat newfile.txt
1
2
3
4
5
line 6
7
8
9
10
```
From my testing tail will not load the entire file into memory all at once. |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | If all you need is to append, then `>>huge_file` is much better than what any editor can do, because it won't touch the existing data. Inserting data into a file requires rewriting everything after the insertion point, so it'll be slow even with the right tools.
With vim, make sure you try with the [LargeFile plugin](http://www.vim.org/scripts/script.php?script_id=1506).
[Bvi](http://bvi.sourceforge.net) is a version of vi that targets binary files. It can edit a slice of a file (i.e. from position x to position y).
The [wikipedia editor comparison page](http://en.wikipedia.org/wiki/Comparison_of_text_editors) has a column with large file support. The situation is pretty bleak. | Ultraedit is the only editor that does this well. I would, also, prefer an OSS. One doesn't exist. I'm particularly surprised that this isn't a capability of vi... it's such a swiss army knife. |
171,118 | I am using Ubuntu and looking for a good editor to edit a file that is > 4GB. I just need to put content at the end and beginning of the file. I suppose I could use something like
```
cat "text to add" >> huge_file
```
To append to the file. Is that the route to go? What about prepending? In general, what is the best route if I wanted to edit somewhere in the middle?
I've tried VIM and it fails miserably. I assume emacs and nano would be even worse. What else is there? I assume to accomplish what I am looking for, the editor would have to be specifically designed for this by not keeping the entirety of the file's contents in memory. | 2010/08/02 | [
"https://superuser.com/questions/171118",
"https://superuser.com",
"https://superuser.com/users/44244/"
] | If all you need is to append, then `>>huge_file` is much better than what any editor can do, because it won't touch the existing data. Inserting data into a file requires rewriting everything after the insertion point, so it'll be slow even with the right tools.
With vim, make sure you try with the [LargeFile plugin](http://www.vim.org/scripts/script.php?script_id=1506).
[Bvi](http://bvi.sourceforge.net) is a version of vi that targets binary files. It can edit a slice of a file (i.e. from position x to position y).
The [wikipedia editor comparison page](http://en.wikipedia.org/wiki/Comparison_of_text_editors) has a column with large file support. The situation is pretty bleak. | Just because I found this via google looking for something similar this is another method I found.
Situation: You have a 4.0 GB file and you need to edit line number 120.
Solution: Using head and tail to get everything except the line you want to edit.
```
# cat origfile.txt
1
2
3
4
5
6
7
8
9
10
# head -n 5 origfile.txt >> newfile.txt
# echo "line 6" >> newfile.txt
# tail -n +7 origfile.txt >> newfile.txt
# cat newfile.txt
1
2
3
4
5
line 6
7
8
9
10
```
From my testing tail will not load the entire file into memory all at once. |
33,622,496 | I got an error in the following definition in typescript, may I know what is the problem?
```
interface Dictionary {
[index: string]: string;
length: number;
}
``` | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497720/"
] | In your `Dictionary` interface,
```
[index: string]: string;
```
is called a string index signature, and tells the compiler all properties of a `Dictionary` must be of type `string`. You would commonly use an index signature to avoid having an array of mixed types.
So then doing this is OK:
```
let d: Dictionary;
d["foo"] = "bar";
```
But this will give a compiler error:
```
let d: Dictionary;
d["foo"] = 1000;
```
You can define properties for `Dictionary`, as long as every property you define is of type `string`. For example, this is OK:
```
interface Dictionary {
[index: string]: string;
foo: string;
}
```
And will allow you to do this:
```
let d: Dictionary;
d.foo = "bar";
```
But in your case, you tried to define a property called `length` as a `number` after you already told the compiler that all properties would be of type `string`. That's why you got a compiler error. | Please see the TypeScript documentation on [array types](http://www.typescriptlang.org/Handbook#interfaces-array-types). All properties must have the same return type so you can't declare length with a return type number on the interface.
To get the length of the array you could cast back to a generic array type:
```
(<Array<any>>yourArray).length
``` |
58,163,850 | Access to XMLHttpRequest at '<http://10.131.12.49:8010/get.me.data?opt=All>' from origin '<http://localhost:1826>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am calling HttpRequest through Angular Framework.
I tried with [R Shiny - how to add Access-Control-Allow-Origin: \*](https://stackoverflow.com/questions/43230683/r-shiny-how-to-add-access-control-allow-origin/43230926)
but we can't say every user to install particular extension to use this.
As you all know shiny server pro is not open source & it would get out of budget of our project. So is there any permanent solution to fix this?
```
export class DashboardService {
private apiUrl = 'http://10.131.12.49:8010/get.me.data?opt=All';
//jsonp: any;
constructor(
// private http: Http,
private http:HttpClient,
) { }
CustReport() {
return this.http.get(this.apiUrl)
}
```
Expecting result:
```
[{"AVG_THROUGHPUT":1976.0432,"AVG_DCR":0.0919}]
``` | 2019/09/30 | [
"https://Stackoverflow.com/questions/58163850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11969143/"
] | >
> If parseFloat encounters a character other than a plus sign (+),
> minus sign (- U+002D HYPHEN-MINUS), numeral (0–9), decimal point (.),
> or exponent (e or E), it returns the value up to that character,
> ignoring the invalid character and characters following it.
>
>
>
```
parseFloat("10525142.25")
```
>
> 10525142.25
>
>
>
```
parseFloat("10525.25")
```
>
> 10525.25
>
>
>
[parseFloat specification](http://es5.github.com/#x15.1.2.3) | The parseFloat() function parses a string and returns a floating point number.
This function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.
Note: Only the first number in the string is returned,Leading and trailing spaces are allowed,If the first character cannot be converted to a number, parseFloat() returns NaN.
Content reference :
<https://www.w3schools.com/jsref/jsref_parsefloat.asp>
You can check this post for why its ignoring characters after comma.
[Javascript parse float is ignoring the decimals after my comma](https://stackoverflow.com/questions/7571553/javascript-parse-float-is-ignoring-the-decimals-after-my-comma) |
58,163,850 | Access to XMLHttpRequest at '<http://10.131.12.49:8010/get.me.data?opt=All>' from origin '<http://localhost:1826>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am calling HttpRequest through Angular Framework.
I tried with [R Shiny - how to add Access-Control-Allow-Origin: \*](https://stackoverflow.com/questions/43230683/r-shiny-how-to-add-access-control-allow-origin/43230926)
but we can't say every user to install particular extension to use this.
As you all know shiny server pro is not open source & it would get out of budget of our project. So is there any permanent solution to fix this?
```
export class DashboardService {
private apiUrl = 'http://10.131.12.49:8010/get.me.data?opt=All';
//jsonp: any;
constructor(
// private http: Http,
private http:HttpClient,
) { }
CustReport() {
return this.http.get(this.apiUrl)
}
```
Expecting result:
```
[{"AVG_THROUGHPUT":1976.0432,"AVG_DCR":0.0919}]
``` | 2019/09/30 | [
"https://Stackoverflow.com/questions/58163850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11969143/"
] | To complete the previous answers and apply them to your problem.
Remove dots from your string, then replace the comma with a dot.
```
// Your string values
var strA = "10.525.142,25";
var strB = "10.525,25";
function fromUSFormatToStandard(x) {
return x.replace(/\./g, "").replace(',', '.');
}
var a = parseFloat(fromUSFormatToStandard(strA)); // Output : 10525142.25 (float)
var b = parseFloat(fromUSFormatToStandard(strB)); // Output : 10525.25 (float)
```
Example : <https://jsfiddle.net/jm3fr9d4/> | The parseFloat() function parses a string and returns a floating point number.
This function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.
Note: Only the first number in the string is returned,Leading and trailing spaces are allowed,If the first character cannot be converted to a number, parseFloat() returns NaN.
Content reference :
<https://www.w3schools.com/jsref/jsref_parsefloat.asp>
You can check this post for why its ignoring characters after comma.
[Javascript parse float is ignoring the decimals after my comma](https://stackoverflow.com/questions/7571553/javascript-parse-float-is-ignoring-the-decimals-after-my-comma) |
59,939,098 | Propose the following situation:
```
function functionExists(functionName) {
if (typeof window[functionName] == 'function') console.log("It's a function");
}
```
What would be an equivalent function in `nodejs` for `functionExists` where there is no global `window` variable?
**CONCRETE SITUATION:**
My concrete situation uses `webpack` instead of `nodejs`, but basically the problem is the same. I could use `window` here, but it would be too complicated to implement everything cleanly, and it isn't advised by `webpack` to mitigate things out to the `window` global variable.
Basically, I have a `PHP` backend, which generates a html `<form>` adding some options to it via a `data` attribute. When the page is loaded, my javascript initializes this `<form>` and gives it a bunch of functionalities (like validation for example). Another thing javascript does with this form, is that it parses the data attribute of it, and instead of the normal page reload submit, it changes the form so it is being submited over an `ajax` request to the server.
When this submit happens, it is set up, that the button and the whole form gets disabled, until my `Ajax` script sends back a response. How this is done, is that I have a `Project_Form` class, which when it is initialized, attaches itself to the `jQuery` submit event, stops the basic submit event, and runs an inner function which sends an ajax request to an api method. The ajax request is set up, that when a response is received, the same instantiated class will receive this response, so I can continue working with it.
When the form receives the response, it must do something with it. In the most basic situation, it must show a success message to the user, but there are some more complex situation, where for example, it has to make a page redirect (for example a login form). Right now, it is set up, that as a default, it will show a message, but when I define this form in PHP, I have the option to "hijack" this default behaviour, and instead of it, send the ajax response to a custom function, which will resolve the situation specifically.
When I am rendering the form in PHP, I already know where the form should send a success response (to which javascript function), but I can only provide this information to javascript, via a string. So my `Project_Form` class, should fetch this string, and should try to fetch a function from it which it will use. This is where my problem is coming from. | 2020/01/27 | [
"https://Stackoverflow.com/questions/59939098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2691879/"
] | Unless you specifically KNOW that this is a global function (which is almost never the case in nodejs), functions by default in nodejs are scoped to the module and there is NO way to look them up by string name like you did with the `window` object in the browser, just like there is no way to look up local variables by name inside a function in Javascript.
In general, don't pass functions by string name. Or, if you have to, then you need to create a lookup table that you can check the function name against.
**I'd suggest you explain the real problem you're trying to solve here because passing the function by string name is not how you would generally want to do things.**
There is a bit of a hack using `eval()` that can see if a string represents a function name that is in scope:
```
// Warning, you must know that the argument f (if it is a string) does not
// contain harmful Javascript code because it will be used with eval()
function isFunction(f) {
// if already a function reference
if (typeof f === "function") {
return true;
// see if string represents a function name somewhere in scope
} else if (typeof f === "string") {
try {
return eval(`typeof ${f} === "function"`);
} catch(e) {
return false;
}
} else {
return false;
}
}
```
Note: This tests to see if the function is in the scope of the `isFunction()` function. If you want to test if it's in your current scope, then you need to do the:
```
eval(`typeof ${f} === "function"`)
```
inline in your current scope so it runs in the scope you want to do the lookup from.
To ever consider using this, you will HAVE to know that the source of your string is safe and cannot contain harmful code. But, as I said earlier, it's better to design your program differently so you aren't referring to functions by their string name.
And, here's a runnable snippet that shows it in action (also works in a node.js module):
```js
function test() {
console.log("in test");
}
function isFunction(f) {
// if already a function reference
if (typeof f === "function") {
return true;
// see if string represents a function name somewhere in scope
} else if (typeof f === "string") {
try {
return eval(`typeof ${f} === "function"`);
} catch(e) {
return false;
}
} else {
return false;
}
}
console.log(isFunction("test")); // true
console.log(isFunction(test)); // true
console.log(isFunction("notAFunction")); // false
```
---
**More added after question edit**
If you only have the function name as a string and the function that it points to is not a property of some known object, then the only way I know of to turn that string into a function reference is with `eval()`.
You could directly execute it with `eval()` such as `eval(functionName + "()")` or you could get a reference to the function with `eval("let fn = " + functionName)` and then use the newly defined `fn` variable to call the function.
If you control the various functions that could be referenced (because they're your Javascript), then you can make all those functions be a property of a known object in your Javsacript:
```
const functionDispatcher = {
function1,
function2,
function3,
function4
}
```
Then, instead of using `eval()`, you can reference them off the `functionDispatcher` object like you would have referenced before with `window` (except this isn't a global) as in:
```
functionDispatcher[someFunctionName]();
```
This would be a preferred option over using `eval()` since there is less risk of insertion of random code via an unsafe string. | In `node.js` you can achieve this like:
```
function functionExists(functionName) {
if(functionName && typeof functionName === "function")
console.log("It is a function");
}
```
Hope this works for you. |
101,396 | I have received a new laptop as a gift. I'd rather not open the package and carry the laptop onto the plane, so it seems I have two reasonable options:
1. Checking the package in as luggage.
People often believe that it's a terrible idea because thieves can easily steal checked luggage (even though a TSA lock is used), and it may get damaged due to the careless transfer of bags.
2. Bringing the laptop into the plane as carry-on.
In this case, I'm wondering whether security personnel will make me unpack the laptop to scan it or if I can bring the package untouched as my carry-on. Furthermore, I have a backpack including another laptop, so I have to carry (the package of) the new laptop in another bag (with the standard carry-on size associated with the airline). All in all, I don't know whether or not this plan is promising.
Which of these choices would be preferable? Are there others? Does anybody have a related experience? | 2017/09/03 | [
"https://travel.stackexchange.com/questions/101396",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/66356/"
] | Checking in your laptop is a terrible idea, as mentioned: the risks are just too great, both in terms of loss and breakage.
Moreover, option 2 isn't going to work in most places: you have to put laptops (and often tablets and phones) in trays. So you'd have to open the package anyway. Just take the laptop with you, and, if you really must, the empty packaging in your checked luggage.
Note also that arriving with a brand new laptop in its original packaging is going to get noticed by the Customs officers, who might very well ask you to pay taxes on that. | >
> Bringing the laptop into the plane as carry-on:
>
>
>
Personal experience here - myself and my wife picked up two Macbook Airs in Schiphol during transit from the UK to Uganda.
No one batted an eyelid at security at the gate - they were just x-rayed in their boxes, with shrink wrap undamaged, along with everything else.
No one batted an eyelid at Customs in Uganda.
However, your mileage may vary - there is no single golden answer to this question, it entirely depends on the individuals handling the security gate you go through on that particular day, and the Customs officials watching arriving passengers. |
101,396 | I have received a new laptop as a gift. I'd rather not open the package and carry the laptop onto the plane, so it seems I have two reasonable options:
1. Checking the package in as luggage.
People often believe that it's a terrible idea because thieves can easily steal checked luggage (even though a TSA lock is used), and it may get damaged due to the careless transfer of bags.
2. Bringing the laptop into the plane as carry-on.
In this case, I'm wondering whether security personnel will make me unpack the laptop to scan it or if I can bring the package untouched as my carry-on. Furthermore, I have a backpack including another laptop, so I have to carry (the package of) the new laptop in another bag (with the standard carry-on size associated with the airline). All in all, I don't know whether or not this plan is promising.
Which of these choices would be preferable? Are there others? Does anybody have a related experience? | 2017/09/03 | [
"https://travel.stackexchange.com/questions/101396",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/66356/"
] | Checking in your laptop is a terrible idea, as mentioned: the risks are just too great, both in terms of loss and breakage.
Moreover, option 2 isn't going to work in most places: you have to put laptops (and often tablets and phones) in trays. So you'd have to open the package anyway. Just take the laptop with you, and, if you really must, the empty packaging in your checked luggage.
Note also that arriving with a brand new laptop in its original packaging is going to get noticed by the Customs officers, who might very well ask you to pay taxes on that. | I've cleared security with a new, boxed laptop--although they were free to open it if they wanted to. They didn't look. (This was a timing issue. While synching files in preparation for the trip my laptop utterly died. I burned what I could to CDs, stopped by the computer store on the way to the airport and grabbed the most suitable thing they had. I hadn't had time to unbox it.)
I would **not** expect this to be possible these days, however, as it's normally laptops out at security. |
101,396 | I have received a new laptop as a gift. I'd rather not open the package and carry the laptop onto the plane, so it seems I have two reasonable options:
1. Checking the package in as luggage.
People often believe that it's a terrible idea because thieves can easily steal checked luggage (even though a TSA lock is used), and it may get damaged due to the careless transfer of bags.
2. Bringing the laptop into the plane as carry-on.
In this case, I'm wondering whether security personnel will make me unpack the laptop to scan it or if I can bring the package untouched as my carry-on. Furthermore, I have a backpack including another laptop, so I have to carry (the package of) the new laptop in another bag (with the standard carry-on size associated with the airline). All in all, I don't know whether or not this plan is promising.
Which of these choices would be preferable? Are there others? Does anybody have a related experience? | 2017/09/03 | [
"https://travel.stackexchange.com/questions/101396",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/66356/"
] | >
> Bringing the laptop into the plane as carry-on:
>
>
>
Personal experience here - myself and my wife picked up two Macbook Airs in Schiphol during transit from the UK to Uganda.
No one batted an eyelid at security at the gate - they were just x-rayed in their boxes, with shrink wrap undamaged, along with everything else.
No one batted an eyelid at Customs in Uganda.
However, your mileage may vary - there is no single golden answer to this question, it entirely depends on the individuals handling the security gate you go through on that particular day, and the Customs officials watching arriving passengers. | I've cleared security with a new, boxed laptop--although they were free to open it if they wanted to. They didn't look. (This was a timing issue. While synching files in preparation for the trip my laptop utterly died. I burned what I could to CDs, stopped by the computer store on the way to the airport and grabbed the most suitable thing they had. I hadn't had time to unbox it.)
I would **not** expect this to be possible these days, however, as it's normally laptops out at security. |
27,479,990 | I've been trying to run the following code but the callbacks [ok() and ko()] are not called.
Using Worklight 6.2 (Cordova 3.4).
```
function wlCommonInit() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
success, fail);
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory
+ "www/index.html", ok, ko);
}
function ko(e) {
alert("NO");
}
function ok(fileEntry) {
alert("OK");
}
```
On the other hand `requestFileSystem` callbacks are called regularly. | 2014/12/15 | [
"https://Stackoverflow.com/questions/27479990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293578/"
] | when you define
`font: 1.1em/1.5 ...` ;
you're using a shorthand property where the first value is the `font-size` and the second value is the `line-height` (which can be also unitless) | If `font` has two values separated by slash, the first one means `font-size`, the second one `line-height`.
Ex.
If parent has `font-size 10px`, this element will have `font-size 11px` and `line-height 16.5px` (11 \* 1.5). |
27,479,990 | I've been trying to run the following code but the callbacks [ok() and ko()] are not called.
Using Worklight 6.2 (Cordova 3.4).
```
function wlCommonInit() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
success, fail);
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory
+ "www/index.html", ok, ko);
}
function ko(e) {
alert("NO");
}
function ok(fileEntry) {
alert("OK");
}
```
On the other hand `requestFileSystem` callbacks are called regularly. | 2014/12/15 | [
"https://Stackoverflow.com/questions/27479990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293578/"
] | when you define
`font: 1.1em/1.5 ...` ;
you're using a shorthand property where the first value is the `font-size` and the second value is the `line-height` (which can be also unitless) | It means nothing, since the declaration `font-size: 1.1em/1.5` is syntactically malformed and browsers are required to ignore it.
A declaration like `font: 1.1em/1.5 serif` would be a different matter. But regarding the meaning of `/1.5` there, it has already been answered e.g. here: [Size of font in CSS with slash](https://stackoverflow.com/questions/701732/size-in-css-with-slash). |
27,479,990 | I've been trying to run the following code but the callbacks [ok() and ko()] are not called.
Using Worklight 6.2 (Cordova 3.4).
```
function wlCommonInit() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
success, fail);
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory
+ "www/index.html", ok, ko);
}
function ko(e) {
alert("NO");
}
function ok(fileEntry) {
alert("OK");
}
```
On the other hand `requestFileSystem` callbacks are called regularly. | 2014/12/15 | [
"https://Stackoverflow.com/questions/27479990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293578/"
] | It means nothing, since the declaration `font-size: 1.1em/1.5` is syntactically malformed and browsers are required to ignore it.
A declaration like `font: 1.1em/1.5 serif` would be a different matter. But regarding the meaning of `/1.5` there, it has already been answered e.g. here: [Size of font in CSS with slash](https://stackoverflow.com/questions/701732/size-in-css-with-slash). | If `font` has two values separated by slash, the first one means `font-size`, the second one `line-height`.
Ex.
If parent has `font-size 10px`, this element will have `font-size 11px` and `line-height 16.5px` (11 \* 1.5). |
47,263,550 | I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.
```
Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
```
Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality? | 2017/11/13 | [
"https://Stackoverflow.com/questions/47263550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6059393/"
] | Map doesn't throw any error or exception while trying to add new value with a key that is present in the map. In that case old value is simply being replaced with a new value.
If you want to add a functionality that will throw an error in that situation, you can use
```
if(map.containsKey(yourKey)) // here your error action
``` | >
> Map.put returns the previous value associated with key, or null if there was
> no mapping for key. (A null return can also indicate that the map
> previously associated null with key, if the implementation supports
> null values.)
>
>
>
So you can do this:
```
public void addItem ( Integer key, String value ) throws Exception {
String old = map.put( key, value );
if ( old != null) {
throw new Exception("Already exists!");
}
}
```
Beware: in this code the new value is instered anyway, even though the key already existed, you cannot add null as it will throw an exception. |
47,263,550 | I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.
```
Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
```
Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality? | 2017/11/13 | [
"https://Stackoverflow.com/questions/47263550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6059393/"
] | Check containsKey method.
```
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Value");
if (map.containsKey(1)) {
throw new Exception("Map already contains key 1");
}
```
For your question, you can create your own implementation like:
```
public class MyCustomMap extends HashMap {
@Override
public Object put(Object key, Object value) {
if (this.containsKey(key)) {
System.out.println("Do whatevery you want when key exists.");
return null;
} else {
return super.put(key, value);
}
}
}
```
And then use it:
```
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new MyCustomMap();
map.put(1, "Value");
map.put(1, "Another value");
}
```
*Note: This is example, without null checking etc.*
**But please, always try to check JavaDoc or basic data structure use cases before asking here, I believe that on Google is a ton of examples ;)** | >
> Map.put returns the previous value associated with key, or null if there was
> no mapping for key. (A null return can also indicate that the map
> previously associated null with key, if the implementation supports
> null values.)
>
>
>
So you can do this:
```
public void addItem ( Integer key, String value ) throws Exception {
String old = map.put( key, value );
if ( old != null) {
throw new Exception("Already exists!");
}
}
```
Beware: in this code the new value is instered anyway, even though the key already existed, you cannot add null as it will throw an exception. |
47,263,550 | I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.
```
Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
```
Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality? | 2017/11/13 | [
"https://Stackoverflow.com/questions/47263550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6059393/"
] | Using a contains-check prior to the put-operation is not an atomic-operation and therefore not thread-safe. Additionally, the map has to be accessed twice each time you add an entry.
To avoid this, use one of the functional methods like merge or compute:
```
map.merge(key, value, (v1, v2) -> {
throw new IllegalArgumentException("Duplicate key '" + key + "'.");
});
``` | >
> Map.put returns the previous value associated with key, or null if there was
> no mapping for key. (A null return can also indicate that the map
> previously associated null with key, if the implementation supports
> null values.)
>
>
>
So you can do this:
```
public void addItem ( Integer key, String value ) throws Exception {
String old = map.put( key, value );
if ( old != null) {
throw new Exception("Already exists!");
}
}
```
Beware: in this code the new value is instered anyway, even though the key already existed, you cannot add null as it will throw an exception. |
47,263,550 | I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.
```
Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
```
Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality? | 2017/11/13 | [
"https://Stackoverflow.com/questions/47263550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6059393/"
] | Check containsKey method.
```
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Value");
if (map.containsKey(1)) {
throw new Exception("Map already contains key 1");
}
```
For your question, you can create your own implementation like:
```
public class MyCustomMap extends HashMap {
@Override
public Object put(Object key, Object value) {
if (this.containsKey(key)) {
System.out.println("Do whatevery you want when key exists.");
return null;
} else {
return super.put(key, value);
}
}
}
```
And then use it:
```
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new MyCustomMap();
map.put(1, "Value");
map.put(1, "Another value");
}
```
*Note: This is example, without null checking etc.*
**But please, always try to check JavaDoc or basic data structure use cases before asking here, I believe that on Google is a ton of examples ;)** | Map doesn't throw any error or exception while trying to add new value with a key that is present in the map. In that case old value is simply being replaced with a new value.
If you want to add a functionality that will throw an error in that situation, you can use
```
if(map.containsKey(yourKey)) // here your error action
``` |
47,263,550 | I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.
```
Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
```
Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality? | 2017/11/13 | [
"https://Stackoverflow.com/questions/47263550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6059393/"
] | Using a contains-check prior to the put-operation is not an atomic-operation and therefore not thread-safe. Additionally, the map has to be accessed twice each time you add an entry.
To avoid this, use one of the functional methods like merge or compute:
```
map.merge(key, value, (v1, v2) -> {
throw new IllegalArgumentException("Duplicate key '" + key + "'.");
});
``` | Map doesn't throw any error or exception while trying to add new value with a key that is present in the map. In that case old value is simply being replaced with a new value.
If you want to add a functionality that will throw an error in that situation, you can use
```
if(map.containsKey(yourKey)) // here your error action
``` |
47,263,550 | I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.
```
Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
```
Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality? | 2017/11/13 | [
"https://Stackoverflow.com/questions/47263550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6059393/"
] | Using a contains-check prior to the put-operation is not an atomic-operation and therefore not thread-safe. Additionally, the map has to be accessed twice each time you add an entry.
To avoid this, use one of the functional methods like merge or compute:
```
map.merge(key, value, (v1, v2) -> {
throw new IllegalArgumentException("Duplicate key '" + key + "'.");
});
``` | Check containsKey method.
```
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Value");
if (map.containsKey(1)) {
throw new Exception("Map already contains key 1");
}
```
For your question, you can create your own implementation like:
```
public class MyCustomMap extends HashMap {
@Override
public Object put(Object key, Object value) {
if (this.containsKey(key)) {
System.out.println("Do whatevery you want when key exists.");
return null;
} else {
return super.put(key, value);
}
}
}
```
And then use it:
```
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new MyCustomMap();
map.put(1, "Value");
map.put(1, "Another value");
}
```
*Note: This is example, without null checking etc.*
**But please, always try to check JavaDoc or basic data structure use cases before asking here, I believe that on Google is a ton of examples ;)** |
225,858 | I am running Ubuntu 9.10 and 10.04 on MediaTemple (ve) servers.
On both of them, the **anacron** setup is broken, ... and they have been broken since I first installed Ubuntu. It has only come to my attention recently, when I realize my log files were not rotating.
I am hoping someone who has anacron working can help diagnose the problem and suggest a fix.
Here is **/etc/cron.d/anacron** ...
This part works correctly: Every morning at 7:30am, **cron** executes this command to start up anacron.
```
# /etc/cron.d/anacron: crontab entries for the anacron package
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
30 7 * * * root test -x /etc/init.d/anacron && /etc/init.d/anacron start >/dev/null
```
The problem is that **/etc/init.d/anacron start** fails:
```
# /etc/init.d/anacron start >/dev/null
start: Unknown job: anacron
```
Notice that /etc/init.d/anacron is a symbolic link to /lib/init/upstart-job:
```
# ls -l /etc/init.d/anacron
lrwxrwxrwx 1 root root 21 Jan 12 2010 /etc/init.d/anacron -> /lib/init/upstart-job
```
Now I am stumped. Anyone have any suggestions how to fix this?
Take a look in **/var/log** and see if your log files are being rotated (as opposed to growing indefinitely). If they **are** being rotated, then you probably have a working **anacron**, so please check your setup and let me know how it differs from mine.
Thanks in advance, ... | 2011/01/23 | [
"https://serverfault.com/questions/225858",
"https://serverfault.com",
"https://serverfault.com/users/51483/"
] | Upstart actually uses config files in `/etc/init` for each service, not `/etc/init.d`. I assume the /etc/init.d links are there to preserve compatibility with sysvinit. Here's the [upstart getting started guide](http://upstart.ubuntu.com/getting-started.html) which explains this.
I don't have an ubuntu system so I can't check the contents of `/etc/init/anacron.conf`, but I suspect from gooling it might just be `exec anacron -s`. Check in `/etc/init.removed/` and see if there is an anacron.conf there that was removed by some upgrade process. You might be able to reinstall anacron to fix this as well. | Ubuntu 10.04 /etc/cron.d/anacron:
```
# /etc/cron.d/anacron: crontab entries for the anacron package
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
#30 7 * * * root test -x /etc/init.d/anacron && /usr/sbin/invoke-rc.d anacron start >/dev/null
30 7 * * * root start -q anacron || :
```
/etc/init.d/anacron start:
```
# /etc/init.d/anacron start
Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service anacron start
Since the script you are attempting to invoke has been converted to an
Upstart job, you may also use the start(8) utility, e.g. start anacron
# ls -al /etc/init.d/anacron
lrwxrwxrwx 1 root root 21 2011-01-10 19:05 /etc/init.d/anacron -> /lib/init/upstart-job
anacron start/running, process 5446
```
/etc/cron.daily/logrotate can be started without anacron, when /usr/sbin/anacron not existed(/etc/crontab):
```
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.