问:
I want to store input data in object but can't be able to do so?
html

```<code><form name="AdminForm" onsubmit="return Updateit()">
      <input type="text" id="name" required>
      <input type="email" id="email" required>
      <input type="number" id="phoneNumb" required>
      <input type="text" id="address" required>
      <input type="submit" value="Submit" class="btn">
      <input type="reset" value="Reset">
</form>
</code>```

Javascript

```<code>var database = {}
function Updateit(){
    const Name = document.forms["AdminForm"]["name"].value;
    const Email = document.forms["AdminForm"]["email"].value;
    const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
    const Address = document.forms["AdminForm"]["address"].value;

    database[Name] = [Email,PhoneNumb.toString(),Address];
    console.log(database[Name]);
}
</code>```

the data in object is vanished after a Millisecond
After input data in form i used to save that data in database object but is not shown in it when i try to display in console or alert.

答:
```<code>var database = {}

    database.Name = document.forms["AdminForm"]["name"].value;
    database.Email = document.forms["AdminForm"]["email"].value;
    database.PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
    database.Address = document.forms["AdminForm"]["address"].value;
function Updateit(){
    console.log(database[Name]);
}
}
</code>```

Body:
html

<form name="AdminForm" onsubmit="return Updateit()">
      <input type="text" id="name" required>
      <input type="email" id="email" required>
      <input type="number" id="phoneNumb" required>
      <input type="text" id="address" required>
      <input type="submit" value="Submit" class="btn">
      <input type="reset" value="Reset">
</form>

Javascript

var database = {}
function Updateit(){
    const Name = document.forms["AdminForm"]["name"].value;
    const Email = document.forms["AdminForm"]["email"].value;
    const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
    const Address = document.forms["AdminForm"]["address"].value;

    database[Name] = [Email,PhoneNumb.toString(),Address];
    console.log(database[Name]);
}

the data in object is vanished after a Millisecond
After input data in form i used to save that data in database object but is not shown in it when i try to display in console or alert.


来源: stackexchange

问:
Sending time in influxdb with python
I am sending data in influx through python. Everything works fine but the time column. I am sending different time values each time.

Suppose if I want to send now-15m time into influx, then I am using the below code to do that:-

```<code>time = (datetime.datetime.utcnow() - datetime.timedelta(minutes=15)).strftime('%Y-%m-%dT%H:%M:%SZ')

json_stats = [{"measurement": "test", "tags": {"domain": domain}, "fields": {"tot_record": tot_record,
                                                                                "time":time
                                                                                }}]
</code>```

Before sending it into influx i am using print to confirm the timestamp and it prints the expected value but it is getting overwritten with the current time.

Influx is replacing the time column with its own time which is the time on which the values are being stored.

Why influx is replacing my time values with the current timestamp and how I can resolve this.

答:
I was able to solve this by passing time outside of the field column :-</p>

```<code>time = (datetime.datetime.utcnow() - datetime.timedelta(minutes=15)).strftime('%Y-%m-%dT%H:%M:%SZ')

json_stats = [{"measurement": "test", "tags": {"domain": domain},"time":time, "fields": {"tot_record": tot_record,
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sending time in influxdb with python

Body:
I am sending data in influx through python. Everything works fine but the time column. I am sending different time values each time.

Suppose if I want to send now-15m time into influx, then I am using the below code to do that:-

time = (datetime.datetime.utcnow() - datetime.timedelta(minutes=15)).strftime('%Y-%m-%dT%H:%M:%SZ')

json_stats = [{"measurement": "test", "tags": {"domain": domain}, "fields": {"tot_record": tot_record,
                                                                                "time":time
                                                                                }}]

Before sending it into influx i am using print to confirm the timestamp and it prints the expected value but it is getting overwritten with the current time.

Influx is replacing the time column with its own time which is the time on which the values are being stored.

Why influx is replacing my time values with the current timestamp and how I can resolve this.

Body:
I was able to solve this by passing time outside of the field column :-

time = (datetime.datetime.utcnow() - datetime.timedelta(minutes=15)).strftime('%Y-%m-%dT%H:%M:%SZ')

json_stats = [{"measurement": "test", "tags": {"domain": domain},"time":time, "fields": {"tot_record": tot_record,


问:
rsync only folder without files inside and without scanning files
I would like to use rsync to sync only folder between folder a and b

```<code>> rsync -zaSH --delete -vv --delete -f"+ f/" -f"- f/*" a/ b
sending incremental file list
[sender] showing directory f because of pattern f/
[sender] hiding file f/1.data because of pattern f/*
[sender] hiding file f/4.data because of pattern f/*
[sender] hiding file f/8.data because of pattern f/*
[sender] hiding file f/10.data because of pattern f/*
[sender] hiding file f/6.data because of pattern f/*
[sender] hiding file f/3.data because of pattern f/*
[sender] hiding file f/5.data because of pattern f/*
[sender] hiding file f/9.data because of pattern f/*
[sender] hiding file f/7.data because of pattern f/*
[sender] hiding file f/2.data because of pattern f/*
delta-transmission disabled for local transfer or --whole-file
f/
total: matches=0  hash_hits=0  false_alarms=0 data=0

sent 88 bytes  received 90 bytes  356.00 bytes/sec
total size is 0  speedup is 0.00

> tree
.
├── a
│   └── f
│       ├── 10.data
│       ├── 1.data
│       ├── 2.data
│       ├── 3.data
│       ├── 4.data
│       ├── 5.data
│       ├── 6.data
│       ├── 7.data
│       ├── 8.data
│       └── 9.data
└── b
    └── f
</code>```

As can be seen from the verbose output, the files were still scanned. If there are millions of files in the folder that could take very long.
Is there a way to achieve the same goal without scanning files? Thanks.

答:
You can't stop it scanning the files directly inside a/f/, but it shouldn't scan any subdirectories of those unless they are also called f.

This command will exclude those too:

```<code>rsync -aSH --delete -vv --delete -f"+ /f/" -f"- /f/*" a/ b/
</code>```

Prefixing patterns with / means match the root of the source directory.

(I also removed -z because compression makes no sense for local copies.)

Body:
I would like to use rsync to sync only folder between folder a and b

> rsync -zaSH --delete -vv --delete -f"+ f/" -f"- f/*" a/ b
sending incremental file list
[sender] showing directory f because of pattern f/
[sender] hiding file f/1.data because of pattern f/*
[sender] hiding file f/4.data because of pattern f/*
[sender] hiding file f/8.data because of pattern f/*
[sender] hiding file f/10.data because of pattern f/*
[sender] hiding file f/6.data because of pattern f/*
[sender] hiding file f/3.data because of pattern f/*
[sender] hiding file f/5.data because of pattern f/*
[sender] hiding file f/9.data because of pattern f/*
[sender] hiding file f/7.data because of pattern f/*
[sender] hiding file f/2.data because of pattern f/*
delta-transmission disabled for local transfer or --whole-file
f/
total: matches=0  hash_hits=0  false_alarms=0 data=0

sent 88 bytes  received 90 bytes  356.00 bytes/sec
total size is 0  speedup is 0.00

> tree
.
├── a
│   └── f
│       ├── 10.data
│       ├── 1.data
│       ├── 2.data
│       ├── 3.data
│       ├── 4.data
│       ├── 5.data
│       ├── 6.data
│       ├── 7.data
│       ├── 8.data
│       └── 9.data
└── b
    └── f

As can be seen from the verbose output, the files were still scanned. If there are millions of files in the folder that could take very long.
Is there a way to achieve the same goal without scanning files? Thanks.

Body:
You can't stop it scanning the files directly inside a/f/, but it shouldn't scan any subdirectories of those unless they are also called f.

This command will exclude those too:

rsync -aSH --delete -vv --delete -f"+ /f/" -f"- /f/*" a/ b/

Prefixing patterns with / means match the root of the source directory.

(I also removed -z because compression makes no sense for local copies.)


问:
Correlation scatterplots using different factors in a data frame
Apologies in advance if the title was not clear. I have a DF RatingScores as follows:

```<code>head(RatingScores)

    PP Condition QuoteType Rating Correct
1  pp1 Disfluent        BS   3.15       7
2  pp1 Disfluent     Motiv   4.15       7
3 pp10 Disfluent     Motiv   3.75       6
4 pp10 Disfluent        BS   1.45       6
5 pp11    Fluent     Motiv   4.45       6
6 pp11    Fluent        BS   3.50       6
</code>```

My goal is to perform a correlational analysis between Rating and Correct, but I would require the Rating from each Condition * QuoteType factors. For example, correlating the Rating from Disfluent*BS with Correct (i.e. using lines 1 and 4). My second goal is to then plot these correlations on a scatterplot, with each correlation line on the graph.

My only solution so far has been to subset the data accordingly and then plot individual graphs using ggscatter, but I am not able to overlay them over each other using par(new=TRUE).

This is how I have subset the data so far:

```<code>DBS=subset(RatingScores,RatingScores$Condition=="Disfluent"&RatingScores$QuoteType=="BS")
FBS=subset(RatingScores,RatingScores$Condition=="Fluent"&RatingScores$QuoteType=="BS")
DMo=subset(RatingScores,RatingScores$Condition=="Disfluent"&RatingScores$QuoteType=="Motiv")
FMo=subset(RatingScores,RatingScores$Condition=="Fluent"&RatingScores$QuoteType=="Motiv")
</code>```

And then plot each one like so:

```<code>ggscatter(DMo, x = "Rating", y = "Correct",
                add = "reg.line",point = F,color = "green", conf.int = F,
                cor.coef = TRUE, cor.method = "pearson", title = "Disfluent Mo",
                xlab = "Rating", ylab = "CRT Score")
</code>```

If there is a more efficient and clearer way of doing this, I would highly appreciate any help. Thanks in advance.

答:
Are you looking for this?</p>

```<code>ggscatter(RatingScores, x = "Rating", y = "Correct",
          add = "reg.line",point = F,color = "green", conf.int = F,
          cor.coef = TRUE, cor.method = "pearson", title = "Disfluent Mo",
          xlab = "Rating", ylab = "CRT Score") +
  facet_wrap(Condition ~ QuoteType)
</code>```

Body:
Apologies in advance if the title was not clear. I have a DF RatingScores as follows:

head(RatingScores)

    PP Condition QuoteType Rating Correct
1  pp1 Disfluent        BS   3.15       7
2  pp1 Disfluent     Motiv   4.15       7
3 pp10 Disfluent     Motiv   3.75       6
4 pp10 Disfluent        BS   1.45       6
5 pp11    Fluent     Motiv   4.45       6
6 pp11    Fluent        BS   3.50       6

My goal is to perform a correlational analysis between Rating and Correct, but I would require the Rating from each Condition * QuoteType factors. For example, correlating the Rating from Disfluent*BS with Correct (i.e. using lines 1 and 4). My second goal is to then plot these correlations on a scatterplot, with each correlation line on the graph.

My only solution so far has been to subset the data accordingly and then plot individual graphs using ggscatter, but I am not able to overlay them over each other using par(new=TRUE).

This is how I have subset the data so far:

DBS=subset(RatingScores,RatingScores$Condition=="Disfluent"&RatingScores$QuoteType=="BS")
FBS=subset(RatingScores,RatingScores$Condition=="Fluent"&RatingScores$QuoteType=="BS")
DMo=subset(RatingScores,RatingScores$Condition=="Disfluent"&RatingScores$QuoteType=="Motiv")
FMo=subset(RatingScores,RatingScores$Condition=="Fluent"&RatingScores$QuoteType=="Motiv")

And then plot each one like so:

ggscatter(DMo, x = "Rating", y = "Correct",
                add = "reg.line",point = F,color = "green", conf.int = F,
                cor.coef = TRUE, cor.method = "pearson", title = "Disfluent Mo",
                xlab = "Rating", ylab = "CRT Score")

If there is a more efficient and clearer way of doing this, I would highly appreciate any help. Thanks in advance.

Body:
Are you looking for this?

ggscatter(RatingScores, x = "Rating", y = "Correct",
          add = "reg.line",point = F,color = "green", conf.int = F,
          cor.coef = TRUE, cor.method = "pearson", title = "Disfluent Mo",
          xlab = "Rating", ylab = "CRT Score") +
  facet_wrap(Condition ~ QuoteType)


问:
Bootstrap vue pagination styling
I need some help. I am trying to style bootstrap vue pagination and I am not able to achieve it. The only thing I was able to achieved was to moved the pagination 50% to the left. I can not style the ul, li and the button inside the li such as changing background for ul, li and button, text color and etc. I even use class name on them, but nothing is working.

var app = new Vue({
  el: '#app',
  data: () => ({
    currentPage: 1,
    rows: 50
  }),
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pagination {
      margin-left: 50%;

      ul {
        text-align: right;
        li {
          float: right !important;
        }
      }

      .page-item {
        color: $color-red;
      }

      .page-link {
        color: $color-red;
      }
}</code>```

        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css"
        />
        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"
        />

```

答:
compile your sass file, and inspect the elements to get to the selectors

var app = new Vue({
  el: '#app',
  data: () => ({
    currentPage: 1,
    rows: 50
  }),
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pagination {
      margin-left: 50%;

}

 .pagination ul {
        text-align: right;

      }

     .pagination li {
          float: right !important;
        }
.pagination .page-item {
        color: red;
}

.pagination .page-link {
        color: red;
}

.pagination .page-item.active .page-link {
        color: #000;
        background-color:red;
}</code>```

        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css"
        />
        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"
        />

```

Title: Bootstrap vue pagination styling

Body:
I need some help. I am trying to style bootstrap vue pagination and I am not able to achieve it. The only thing I was able to achieved was to moved the pagination 50% to the left. I can not style the ul, li and the button inside the li such as changing background for ul, li and button, text color and etc. I even use class name on them, but nothing is working.

var app = new Vue({
  el: '#app',
  data: () => ({
    currentPage: 1,
    rows: 50
  }),
})

.pagination {
      margin-left: 50%;

      ul {
        text-align: right;
        li {
          float: right !important;
        }
      }

      .page-item {
        color: $color-red;
      }

      .page-link {
        color: $color-red;
      }
}

        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css"
        />
        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"
        />

Body:
compile your sass file, and inspect the elements to get to the selectors

var app = new Vue({
  el: '#app',
  data: () => ({
    currentPage: 1,
    rows: 50
  }),
})

.pagination {
      margin-left: 50%;

}

 .pagination ul {
        text-align: right;

      }

     .pagination li {
          float: right !important;
        }
.pagination .page-item {
        color: red;
}

.pagination .page-link {
        color: red;
}

.pagination .page-item.active .page-link {
        color: #000;
        background-color:red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
 <!-- Required Stylesheets -->
        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css"
        />
        <link
          type="text/css"
          rel="stylesheet"
          href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"
        />

        <!-- Required scripts -->
        <script src="https://unpkg.com/vue"></script>
        <script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>

<div id='app'>
<b-container
class="pagination-container">
<b-pagination
:container-class="'pagination'"
:pageClass="'page-item'"
:pageLinkClass="'page-link-item'"
v-model="currentPage"
pills :total-rows="rows">
</b-pagination>
</b-container>
</div>


问:
Max value of for each column for distinct rows of data frame in r
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

```<code>ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77
</code>```

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

```<code>my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]
</code>```

To finally give me:

```<code>all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94
</code>```

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

```<code>#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D
</code>```

答:
Here's a dplyr solution that will handle duplicate IDs. First, we pivot_longer to get all the letters into a single column. Then we group_by these letters. Finally, within each letter, we sort by the value (and rating for ties in value) and select the first element to get each ID.

```<code>library(dplyr)

df %>%
  pivot_longer(cols = c("A", "B", "C", "D")) %>%
  group_by(Group = name) %>%
  summarise(ID = ID[order(-value, -Rating)[1]])
#> # A tibble: 4 x 2
#>   Group    ID
#>   <chr> <dbl>
#> 1 A       123
#> 2 B       721
#> 3 C       123
#> 4 D        21
</code>```

Body:
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]

To finally give me:

all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D

Body:
Here's a dplyr solution that will handle duplicate IDs. First, we pivot_longer to get all the letters into a single column. Then we group_by these letters. Finally, within each letter, we sort by the value (and rating for ties in value) and select the first element to get each ID.

library(dplyr)

df %>%
  pivot_longer(cols = c("A", "B", "C", "D")) %>%
  group_by(Group = name) %>%
  summarise(ID = ID[order(-value, -Rating)[1]])
#> # A tibble: 4 x 2
#>   Group    ID
#>   <chr> <dbl>
#> 1 A       123
#> 2 B       721
#> 3 C       123
#> 4 D        21


问:
Couldn't read data from json config file using curl
I am trying to setup a new connector to read file using using REST API. Instead of passing file configuration in the command line, I am trying to pass it through file. But, while reading this file, I am getting an error. This file is placed in /usr/share directory.

Command :

```<code>curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/usr/share/fileConfigSource.json

Warning: Couldn't read data from file "/usr/share/fileConfigSource.json", this
Warning: makes an empty POST.
{"error_code":500,"message":null}
</code>```

fileConfigSource.json :

```<code>{
    "name": "file_source",
    "config": {
        "connector.class": "org.apache.kafka.connect.file.FileStreamSourceConnector",
        "tasks.max": "1",
        "file": "/usr/share/details.txt",
        "topics": "KTest",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "value.converter": "org.apache.kafka.connect.storage.StringConverter"
    }
}
</code>```

答:
Here's the cause:

Couldn't read data from file

Reasons could include:

The file doesn't exist. For example:

```<code>➜ cat /this/doesnot/exist
cat: /this/doesnot/exist: No such file or directory

➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/this/doesnot/exist

Warning: Couldn't read data from file "/this/doesnot/exist", this makes an
Warning: empty POST.
{"error_code":500,"message":null}%
</code>```

The file does exist but the user that is executing the curl command does not have permission to access it

```<code>➜ ls -l /tmp/foo.json
--w-r--r--  1 rmoff  wheel  390  2 Jun 17:50 /tmp/foo.json

➜ cat /tmp/foo.json
cat: /tmp/foo.json: Permission denied

➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/tmp/foo.json

Warning: Couldn't read data from file "/tmp/foo.json", this makes an empty
Warning: POST.
{"error_code":500,"message":null}%
</code>```

If you have the file in the correct place and accessible you'll get this kind of response:

```<code>➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/tmp/foo.json

{"error_code":400,"message":"Connector configuration is invalid and contains the following 1 error(s):\nMissing required configuration \"topic\" which has no default value.\nYou can also find the above list of errors at the endpoint `/connector-plugins/{connectorType}/config/validate`"}%
</code>```

To fix that error change

```<code>"topics": "KTest",
</code>```

for

```<code>"topic": "KTest",
</code>```

This then succeeds:

```<code>➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/tmp/foo.json

{"name":"file_source","config":{"connector.class":"org.apache.kafka.connect.file.FileStreamSourceConnector","tasks.max":"1","file":"/usr/share/details.txt","topic":"KTest","key.converter":"org.apache.kafka.connect.storage.StringConverter","value.converter":"org.apache.kafka.connect.storage.StringConverter","name":"file_source"},"tasks":[],"type":"source"}%
</code>```

Body:
I am trying to setup a new connector to read file using using REST API. Instead of passing file configuration in the command line, I am trying to pass it through file. But, while reading this file, I am getting an error. This file is placed in /usr/share directory.

Command :

curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/usr/share/fileConfigSource.json

Warning: Couldn't read data from file "/usr/share/fileConfigSource.json", this
Warning: makes an empty POST.
{"error_code":500,"message":null}

fileConfigSource.json :

{
    "name": "file_source",
    "config": {
        "connector.class": "org.apache.kafka.connect.file.FileStreamSourceConnector",
        "tasks.max": "1",
        "file": "/usr/share/details.txt",
        "topics": "KTest",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "value.converter": "org.apache.kafka.connect.storage.StringConverter"
    }
}

Body:
Here's the cause:

Couldn't read data from file

Reasons could include:

The file doesn't exist. For example:

➜ cat /this/doesnot/exist
cat: /this/doesnot/exist: No such file or directory

➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/this/doesnot/exist

Warning: Couldn't read data from file "/this/doesnot/exist", this makes an
Warning: empty POST.
{"error_code":500,"message":null}%

The file does exist but the user that is executing the curl command does not have permission to access it

➜ ls -l /tmp/foo.json
--w-r--r--  1 rmoff  wheel  390  2 Jun 17:50 /tmp/foo.json

➜ cat /tmp/foo.json
cat: /tmp/foo.json: Permission denied

➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/tmp/foo.json

Warning: Couldn't read data from file "/tmp/foo.json", this makes an empty
Warning: POST.
{"error_code":500,"message":null}%

If you have the file in the correct place and accessible you'll get this kind of response:

➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/tmp/foo.json

{"error_code":400,"message":"Connector configuration is invalid and contains the following 1 error(s):\nMissing required configuration \"topic\" which has no default value.\nYou can also find the above list of errors at the endpoint `/connector-plugins/{connectorType}/config/validate`"}%

To fix that error change

"topics": "KTest",

for

"topic": "KTest",

This then succeeds:

➜ curl -X POST "http://localhost:8083/connectors" -H "Content-type:application/json" --data @/tmp/foo.json

{"name":"file_source","config":{"connector.class":"org.apache.kafka.connect.file.FileStreamSourceConnector","tasks.max":"1","file":"/usr/share/details.txt","topic":"KTest","key.converter":"org.apache.kafka.connect.storage.StringConverter","value.converter":"org.apache.kafka.connect.storage.StringConverter","name":"file_source"},"tasks":[],"type":"source"}%


问:
Polymorphic variants and let%bind type error
I'm trying to use the technique in Composable Error Handling in OCaml (Result type with polymorphic variants for errors) for some code I've written. The types of the functions I'm trying to use look like this:

val parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t
```

<p>My attempt at composing them is this:</p>

<pre class="lang-ml prettyprint-override"><code>let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    let open Result.Let_syntax in
    let%bind tokens = lex lexer input in
    parse parser tokens
</code>```

Unfortunately the compiler (4.09.0) reports a type error:

```<code>File "src/Pratt.ml", line 147, characters 4-23:
147 |     parse parser tokens
          ^^^^^^^^^^^^^^^^^^^
Error: This expression has type
         (Nominal.term, [ `ParseError of string ]) result
       but an expression was expected of type
         (Nominal.term, [> `LexError of string ]) result
       The first variant type does not allow tag(s) `LexError
</code>```

Note that if I do the equivalent by hand, the code compiles:

let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    match lex lexer input with
      | Error (`LexError err) -> Error (`LexError err)
      | Ok tokens ->
        (match parse parser tokens with
        | Ok result -> Ok result
        | Error (`ParseError err) -> Error (`ParseError err))
```

<p>Actually, that's not quite true. The equivalent is this, which also fails to compile (in the same way):</p>

<pre class="lang-ml prettyprint-override"><code>    match lex lexer input with
      | Error err -> Error err
      | Ok tokens ->
        match parse parser tokens with
        | Ok result -> Ok result
        | Error err -> Error err
</code>```

```<code>File "src/Pratt.ml", line 155, characters 29-32:
155 |         | Error err -> Error err
                                   ^^^
Error: This expression has type [ `ParseError of string ]
       but an expression was expected of type
         [> `LexError of string | `ParseError of string ]
       The first variant type does not allow tag(s) `LexError
</code>```

So my question is this. Note that the error message says "This expression has type (Nominal.term, [ `ParseError of string ]) result". This is what I don't understand -- I never specify that type anywhere, in fact, both places ParseError is mentioned, it's with a > constraint. So where does this type come from? IE where does [>ParseError of string ]become[ ParseError of string ]?

Also:

What's the difference between my attempt and Vladimir's original (which I assume compiles)?

Is there a way to weaken a polymorphic variant from [ x ] to [> x ]? (other than mapping all the tags by hand from the first type to the second)

Edit:

I uploaded all of my code for context.

Edit 2 (sorry):

I did some exploration and came up with this implementation:

let parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks ->
    match expression parser toks with
    (* | [], result -> result *)
    (* | _, Error err -> Error err *)
    | _, Ok _ -> Error (`ParseError "leftover tokens")
    | _, _ -> Error (`ParseError "unimplemented")
```

If I remove either of the commented lines, the implementation of lex_and_parse starts to fail again. It's a bit disturbing to me that parse compiles and its type signature never changes, yet a caller can fail to typecheck. How is this possible? This kind of nonlocal effect seriously violates my expectation for how type checking / signatures (ought to) work. I'd really like to understand what's happening.

答:
So first of all, your intuition is right, your code shall work, e.g., the following code is accepted by 4.09.0 without any type errors:

```<code>open Base

module type S = sig
  type parser
  type lexer
  type token
  type term

  val parse : parser -> token list -> (term, [> `ParseError of string ]) Result.t
  val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t
end

module Test (P : S) = struct
  open P
  let lex_and_parse :
    parser -> lexer -> string -> (term, [> `ParseError of string | `LexError of string ]) Result.t
    = fun parser lexer input ->
      let open Result.Let_syntax in
      let%bind tokens = lex lexer input in
      parse parser tokens
end

module PL : S = struct
  type parser
  type lexer
  type token
  type term

  let parse _parser _tokens = Error (`ParseError "not implemented")
  let lex _ _ = Error (`LexError "not implemented")
end
</code>```

So my question is this. Note that the error message says "This expression has type (Nominal.term, [ `ParseError of string ]) result". This is what I don't understand -- I never specify that type anywhere, in fact, both places ParseError is mentioned, it's with a > constraint. So where does this type come from? IE where does [>ParseError of string ]become[ ParseError of string ]?

You are right, this is the main culprit. For some reason, your parse function returns a value of type

```<code>(term, [`ParseError of string])
</code>```

where the type of the error constituent is a ground type, i.e., it is not polymorphic and cannot be extended. It is hard to tell, why this has happened, but I bet that there should be some type annotation that you have put that stops the type checker from inferring the most general type for the parse function. In any case, the culprit is hiding somewhere and is not in the code that you have shown us.

Is there a way to weaken a polymorphic variant from [ x ] to [> x ]? (other than mapping all the tags by hand from the first type to the second)

Yes,

```<code># let weaken x = (x : [`T]  :> [> `T]);;
val weaken : [ `T ] -> [> `T ] = <fun>
</code>```

What's the difference between my attempt and Vladimir's original (which I assume compiles)?

Your parse function in fact returns a non-extensible type. Note that to turn an non-extensible type to extensible, you have to use the full form coercion, e.g., if you will define lex_and_parse as

```<code>  let lex_and_parse :
    parser -> lexer -> string -> (term, [> `ParseError of string | `LexError of string ]) Result.t
    = fun parser lexer input ->
      let open Result.Let_syntax in
      let parse = (parse
                   :  _ -> _ -> (_, [ `ParseError of string]) Result.t
                   :> _ -> _ -> (_, [> `ParseError of string]) Result.t) in

      let%bind tokens = lex lexer input in
      parse parser tokens
</code>```

it will compile. But again the main culprit is the type of your parse function.

Where the actual bug was hiding

After OP have uploaded the source code we were able to identify why and where the OCaml typechecker was denied from inferring the general and polymorphic type.

Here is the story, the parse function is implemented as

```<code>let parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> result
    | _, Ok _ -> Error (`ParseError "leftover tokens")
    | _, Error err -> Error err
</code>```

So its return type is a unification of the types of the folowing expressions:

result,

Error ('ParseError "leftover tokens")

Error err

in addition we have a type constraint

```<code>parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
</code>```

And here is an important thing to understand, a type constrained is not a definition, so when you say let x : 'a = 42 you are not defining x to have a universal polymorphic type 'a. A type constraint (expr : typeexpr) forces the type of expr to be compatible with typexpr. In other words, type constraint can only constrain the type, but the type itself is always inferred by the type checker. If the inferred type is more general, e.g., 'a list than the constraint, e.g., int list, then it will be constrained to int list. But you can't move the other way around as it will defeat the type soundness, e.g., if the inferred type is int list and your constraint is 'a list, then it will still be 'a list (treat it like intersection of types).  Again, the type inference will infer the most general type, and you can only make it less general.

So, finally, the return type of the parse subroutine is the result of unification of the three expressions above plus the user constraint. The type of result is the smallest type, since you have constrained the expression function here to return errors of the non-extensible ground type parse_error.

Now to mitigations.

The easiest solution is to remove type annotations at all and rely on the type checker, merlin, and well-defined interfaces (signatures) when you program. Indeed, the type annotation only confused you here. You wrote an extensible [> ...] type annotation and believed that the inferred type is extensible which wasn't true.

If you need to keep them or if you need to make the expression function a part of your interface, then you have two options, either make your parse_error extensible, and this means polymorphic or use type coercion to weaken the type of result and make it extensible, e.g.,

```<code>| [], result -> (result : parse_error :> [> parse_error])
</code>```

If you will decide to make your parse_error type extensible, you can't just say

```<code>type parse_error = [> `ParseError of string]
</code>```

because now parse_error denotes a whole family of types, so we need to represent this variability of type with a type variable, two syntaxes here are applicable,

```<code>type 'a parse_error = [>
  | `ParseError of string
  | `MoonPhaseError of int
] as 'a
</code>```

or a more verbose, but to my taste more precise,

```<code>type 'a parse_error = 'a constraint 'a = [>
    | `ParseError of string
    | `MoonPhaseError of int
  ]
</code>```

Both definitions are equivalent. The all mean that type 'a parser_error is a type variable 'a s.t. 'a includes the ParseError, the MoonPhaseError and infinitely more errors of unspecified genera.

Body:
I'm trying to use the technique in Composable Error Handling in OCaml (Result type with polymorphic variants for errors) for some code I've written. The types of the functions I'm trying to use look like this:

val parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t

My attempt at composing them is this:

let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    let open Result.Let_syntax in
    let%bind tokens = lex lexer input in
    parse parser tokens

Unfortunately the compiler (4.09.0) reports a type error:

File "src/Pratt.ml", line 147, characters 4-23:
147 |     parse parser tokens
          ^^^^^^^^^^^^^^^^^^^
Error: This expression has type
         (Nominal.term, [ `ParseError of string ]) result
       but an expression was expected of type
         (Nominal.term, [> `LexError of string ]) result
       The first variant type does not allow tag(s) `LexError

Note that if I do the equivalent by hand, the code compiles:

let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    match lex lexer input with
      | Error (`LexError err) -> Error (`LexError err)
      | Ok tokens ->
        (match parse parser tokens with
        | Ok result -> Ok result
        | Error (`ParseError err) -> Error (`ParseError err))

Actually, that's not quite true. The equivalent is this, which also fails to compile (in the same way):

    match lex lexer input with
      | Error err -> Error err
      | Ok tokens ->
        match parse parser tokens with
        | Ok result -> Ok result
        | Error err -> Error err

File "src/Pratt.ml", line 155, characters 29-32:
155 |         | Error err -> Error err
                                   ^^^
Error: This expression has type [ `ParseError of string ]
       but an expression was expected of type
         [> `LexError of string | `ParseError of string ]
       The first variant type does not allow tag(s) `LexError

So my question is this. Note that the error message says "This expression has type (Nominal.term, [ `ParseError of string ]) result". This is what I don't understand -- I never specify that type anywhere, in fact, both places ParseError is mentioned, it's with a > constraint. So where does this type come from? IE where does [>ParseError of string ]become[ ParseError of string ]?

Also:

What's the difference between my attempt and Vladimir's original (which I assume compiles)?

Is there a way to weaken a polymorphic variant from [ x ] to [> x ]? (other than mapping all the tags by hand from the first type to the second)

Edit:

I uploaded all of my code for context.

Edit 2 (sorry):

I did some exploration and came up with this implementation:

let parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks ->
    match expression parser toks with
    (* | [], result -> result *)
    (* | _, Error err -> Error err *)
    | _, Ok _ -> Error (`ParseError "leftover tokens")
    | _, _ -> Error (`ParseError "unimplemented")

If I remove either of the commented lines, the implementation of lex_and_parse starts to fail again. It's a bit disturbing to me that parse compiles and its type signature never changes, yet a caller can fail to typecheck. How is this possible? This kind of nonlocal effect seriously violates my expectation for how type checking / signatures (ought to) work. I'd really like to understand what's happening.

Body:
So first of all, your intuition is right, your code shall work, e.g., the following code is accepted by 4.09.0 without any type errors:

open Base

module type S = sig
  type parser
  type lexer
  type token
  type term

  val parse : parser -> token list -> (term, [> `ParseError of string ]) Result.t
  val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t
end

module Test (P : S) = struct
  open P
  let lex_and_parse :
    parser -> lexer -> string -> (term, [> `ParseError of string | `LexError of string ]) Result.t
    = fun parser lexer input ->
      let open Result.Let_syntax in
      let%bind tokens = lex lexer input in
      parse parser tokens
end

module PL : S = struct
  type parser
  type lexer
  type token
  type term

  let parse _parser _tokens = Error (`ParseError "not implemented")
  let lex _ _ = Error (`LexError "not implemented")
end

So my question is this. Note that the error message says "This expression has type (Nominal.term, [ `ParseError of string ]) result". This is what I don't understand -- I never specify that type anywhere, in fact, both places ParseError is mentioned, it's with a > constraint. So where does this type come from? IE where does [>ParseError of string ]become[ ParseError of string ]?

You are right, this is the main culprit. For some reason, your parse function returns a value of type

(term, [`ParseError of string])

where the type of the error constituent is a ground type, i.e., it is not polymorphic and cannot be extended. It is hard to tell, why this has happened, but I bet that there should be some type annotation that you have put that stops the type checker from inferring the most general type for the parse function. In any case, the culprit is hiding somewhere and is not in the code that you have shown us.

Is there a way to weaken a polymorphic variant from [ x ] to [> x ]? (other than mapping all the tags by hand from the first type to the second)

Yes,

# let weaken x = (x : [`T]  :> [> `T]);;
val weaken : [ `T ] -> [> `T ] = <fun>

What's the difference between my attempt and Vladimir's original (which I assume compiles)?

Your parse function in fact returns a non-extensible type. Note that to turn an non-extensible type to extensible, you have to use the full form coercion, e.g., if you will define lex_and_parse as

  let lex_and_parse :
    parser -> lexer -> string -> (term, [> `ParseError of string | `LexError of string ]) Result.t
    = fun parser lexer input ->
      let open Result.Let_syntax in
      let parse = (parse
                   :  _ -> _ -> (_, [ `ParseError of string]) Result.t
                   :> _ -> _ -> (_, [> `ParseError of string]) Result.t) in

      let%bind tokens = lex lexer input in
      parse parser tokens

it will compile. But again the main culprit is the type of your parse function.

Where the actual bug was hiding

After OP have uploaded the source code we were able to identify why and where the OCaml typechecker was denied from inferring the general and polymorphic type.

Here is the story, the parse function is implemented as

let parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> result
    | _, Ok _ -> Error (`ParseError "leftover tokens")
    | _, Error err -> Error err

So its return type is a unification of the types of the folowing expressions:

result,

Error ('ParseError "leftover tokens")

Error err

in addition we have a type constraint

parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t

And here is an important thing to understand, a type constrained is not a definition, so when you say let x : 'a = 42 you are not defining x to have a universal polymorphic type 'a. A type constraint (expr : typeexpr) forces the type of expr to be compatible with typexpr. In other words, type constraint can only constrain the type, but the type itself is always inferred by the type checker. If the inferred type is more general, e.g., 'a list than the constraint, e.g., int list, then it will be constrained to int list. But you can't move the other way around as it will defeat the type soundness, e.g., if the inferred type is int list and your constraint is 'a list, then it will still be 'a list (treat it like intersection of types).  Again, the type inference will infer the most general type, and you can only make it less general.

So, finally, the return type of the parse subroutine is the result of unification of the three expressions above plus the user constraint. The type of result is the smallest type, since you have constrained the expression function here to return errors of the non-extensible ground type parse_error.

Now to mitigations.

The easiest solution is to remove type annotations at all and rely on the type checker, merlin, and well-defined interfaces (signatures) when you program. Indeed, the type annotation only confused you here. You wrote an extensible [> ...] type annotation and believed that the inferred type is extensible which wasn't true.

If you need to keep them or if you need to make the expression function a part of your interface, then you have two options, either make your parse_error extensible, and this means polymorphic or use type coercion to weaken the type of result and make it extensible, e.g.,

| [], result -> (result : parse_error :> [> parse_error])

If you will decide to make your parse_error type extensible, you can't just say

type parse_error = [> `ParseError of string]

because now parse_error denotes a whole family of types, so we need to represent this variability of type with a type variable, two syntaxes here are applicable,

type 'a parse_error = [>
  | `ParseError of string
  | `MoonPhaseError of int
] as 'a

or a more verbose, but to my taste more precise,

type 'a parse_error = 'a constraint 'a = [>
    | `ParseError of string
    | `MoonPhaseError of int
  ]

Both definitions are equivalent. The all mean that type 'a parser_error is a type variable 'a s.t. 'a includes the ParseError, the MoonPhaseError and infinitely more errors of unspecified genera.


问:
A Future or coroutine is required - asyncio
I'm trying to asynchronously load content of a web page. I have used requests_html, as I face some problem installing it on my server so I am using asyncio

```<code>@asyncio.coroutine
async def extract_feature():
    try:
        count = 0
        key = ''
        loop = asyncio.get_event_loop()
        response = await loop.run_in_executor(None, requests.get, link)
        soup = BeautifulSoup(response, "html.parser")
        return soup
loop = asyncio.get_event_loop()
result = loop.run_until_complete(extract_feature)
</code>```

But this raises A Future or coroutine is required.

One thing to mentioned I'm using Python 3.5.0 (v3.5.0:374f501f4567) which doesn't support run.

答:
You need to call extract_feature before passing it to run_until_complete, i.e.:

```<code>result = loop.run_until_complete(extract_feature())
</code>```

Also, the asyncio.coroutine decorator shouldn't be used with functions already defined as async def - just omit it.

Body:
I'm trying to asynchronously load content of a web page. I have used requests_html, as I face some problem installing it on my server so I am using asyncio

@asyncio.coroutine
async def extract_feature():
    try:
        count = 0
        key = ''
        loop = asyncio.get_event_loop()
        response = await loop.run_in_executor(None, requests.get, link)
        soup = BeautifulSoup(response, "html.parser")
        return soup
loop = asyncio.get_event_loop()
result = loop.run_until_complete(extract_feature)

But this raises A Future or coroutine is required.

One thing to mentioned I'm using Python 3.5.0 (v3.5.0:374f501f4567) which doesn't support run.

Body:
You need to call extract_feature before passing it to run_until_complete, i.e.:

result = loop.run_until_complete(extract_feature())

Also, the asyncio.coroutine decorator shouldn't be used with functions already defined as async def - just omit it.


问:
Why is the value of alpha different between psych::omega and psych::alpha in R?
I have data from a five-item measure completed by about 260 participants and estimated internal consistency with the psych library in R. I got a value of -0.36 (I triple-checked for reverse-coded questions). My data doesn't cover a broad range of the possible scores -- due to the nature of the group I am sampling from -- so this is a plausible number. But the scale I'm using is well validated, admittedly with low typical values of alpha ranging from 0.5--0.7.

When looking for alternative methods to assess my data I used psych::omega. This returns an alpha value of 0.57 alongwith the omega statistic I was looking for. This alpha value is much more in keeping with other literature which uses the scale in question. I have also looked at other validated measures from my study and the alpha values from psych::alpha and psych::omega are equal. It is only on this particular measure which is known to have low internal consistency where the difference appears.

My question: why are the alpha values different between psych::alpha and psych::omega?

The code below includes the actual data and will spit a warning about negatively correlated items. I've checked and rechecked my score-coding and it's correct so I am confident we can ignore this warning.

```<code>library("psych")

data <- structure(list(rMEQQ01 = c(2, 3, 3, 3, 3, 3, 3, 1, 5, 3, 3, 3,
3, 3, 3, 3, 3, 5, 3, 2, 5, 2, 3, 3, 3, 3, 3, 2, 3, 2, 2, 1, 3,
5, 3, 4, 3, 4, 5, 4, 3, 3, 2, 5, 4, 2, 3, 3, 5, 3, 3, 5, 5, 4,
2, 2, 4, 1, 4, 1, 2, 1, 5, 2, 4, 3, 3, 1, 3, 3, 4, 2, 4, 2, 2,
3, 5, 4, 3, 3, 2, 5, 3, 5, 1, 5, 3, 5, 1, 3, 3, 3, 3, 3, 5, 3,
5, 5, 2, 5, 2,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2, 2, 4, 6, 4, 2, 6, 2, 6, 6, 2, 0,
    0, 4, 2, 6, 6, 4, 0, 4, 0, 6, 4, 0, 2, 2, 2, 2, 4, 0, 2,
    0, 0, 4, 0, 4, 2, 0, 0, 2, 2, 0, 0, 4, 6, 2, 4, 0, 2, 4,
    4, 0, 2, 6, 2, 4, 0, 0, 4, 0, 4, 2, 4, 2, 0, 4, 0, 0, 4,
    2, 0, 2, 2, 0, 0, 0, 4, 0, 4, 0, 4, 2, 6, 6, 0, 0, 4, 4,
    6, 2, 2, 4, 0, 0, 0, 2, 0, 2, 2, 2, 4, 2, 2, 6, 4, 2, 4,
    0, 0, 0, 0, 2, 0, 2, 0, 4, 4, 4, 4, 4, 2, 6, 4, 0, 4, 0,
    2, 0, 0, 0, 6, 2, 0, 6, 4, 2, 2, 0, 2, 0, 2, 6, 2, 2, 0,
    6, 2, 2, 0, 0, 0, 4, 0, 4, 2, 6, 2, 4, 2, 4, 2, 4, 6, 6,
    6, 4, 0, 0, 0, 4, 6, 2, 6, 6, 2, 2, 0, 0, 2, 2, 6, 2, 2,
    6, 6, 0, 0, 4, 2, 4, 4, 4, 0, 2, 0)), row.names = c(NA, -260L
), class = "data.frame")

alpha <- psych::alpha(data) # alpha$total$raw_alpha = -0.3665156
omega <- psych::omega(data) # omega$alpha = 0.5710576
```

```

答:
Please note the warning message that alpha gave you:

Warning message:
In psych::alpha(data) :
  Some items were negatively correlated with the total scale and probably
should be reversed.

To do this, run the function again with the 'check.keys=TRUE' option

Body:
I have data from a five-item measure completed by about 260 participants and estimated internal consistency with the psych library in R. I got a value of -0.36 (I triple-checked for reverse-coded questions). My data doesn't cover a broad range of the possible scores -- due to the nature of the group I am sampling from -- so this is a plausible number. But the scale I'm using is well validated, admittedly with low typical values of alpha ranging from 0.5--0.7.

When looking for alternative methods to assess my data I used psych::omega. This returns an alpha value of 0.57 alongwith the omega statistic I was looking for. This alpha value is much more in keeping with other literature which uses the scale in question. I have also looked at other validated measures from my study and the alpha values from psych::alpha and psych::omega are equal. It is only on this particular measure which is known to have low internal consistency where the difference appears.

My question: why are the alpha values different between psych::alpha and psych::omega?

The code below includes the actual data and will spit a warning about negatively correlated items. I've checked and rechecked my score-coding and it's correct so I am confident we can ignore this warning.

library("psych")

data <- structure(list(rMEQQ01 = c(2, 3, 3, 3, 3, 3, 3, 1, 5, 3, 3, 3,
3, 3, 3, 3, 3, 5, 3, 2, 5, 2, 3, 3, 3, 3, 3, 2, 3, 2, 2, 1, 3,
5, 3, 4, 3, 4, 5, 4, 3, 3, 2, 5, 4, 2, 3, 3, 5, 3, 3, 5, 5, 4,
2, 2, 4, 1, 4, 1, 2, 1, 5, 2, 4, 3, 3, 1, 3, 3, 4, 2, 4, 2, 2,
3, 5, 4, 3, 3, 2, 5, 3, 5, 1, 5, 3, 5, 1, 3, 3, 3, 3, 3, 5, 3,
5, 5, 2, 5, 2, 5, 3, 5, 3, 3, 5, 4, 3, 3, 4, 3, 3, 4, 3, 2, 3,
4, 3, 2, 3, 5, 5, 3, 4, 4, 3, 5, 3, 2, 3, 2, 5, 3, 3, 5, 3, 3,
3, 2, 5, 5, 4, 4, 5, 4, 1, 3, 3, 3, 4, 3, 3, 3, 3, 3, 2, 4, 3,
3, 3, 4, 4, 3, 3, 3, 4, 3, 1, 2, 3, 3, 5, 4, 3, 4, 2, 2, 3, 4,
2, 2, 1, 4, 3, 5, 3, 3, 3, 3, 3, 3, 3, 5, 3, 3, 4, 5, 2, 3, 5,
4, 3, 4, 4, 4, 3, 3, 3, 5, 2, 3, 3, 5, 5, 4, 2, 3, 3, 3, 3, 3,
3, 3, 2, 3, 1, 3, 2, 1, 2, 5, 3, 5, 1, 3, 3, 2, 3, 4, 5, 3, 3,
3, 4, 3, 1, 3, 3, 3, 3, 5, 1, 3, 4, 5, 3, 4, 3, 3), rMEQQ02 = c(2,
2, 2, 1, 2, 1, 2, 3, 2, 2, 3, 2, 1, 1, 2, 1, 2, 1, 2, 3, 4, 2,
1, 1, 3, 2, 3, 2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 4, 2, 4, 4, 4, 0, 2, 0)), row.names = c(NA, -260L
), class = "data.frame")

alpha <- psych::alpha(data) # alpha$total$raw_alpha = -0.3665156
omega <- psych::omega(data) # omega$alpha = 0.5710576
```


问:
How to do in SQL: one row from two rows with same value?
I have a table like this in SQL:

I would like to create simple rows from rows with the same game_id value.
Thus, I would like to have the first two rows in the first row; the third, fourth row as the second row, and so on. My table is huge.
Thanks for any help in advance.

答:
You can use conditional aggregation:

```<code>select game_id,
       max(case when seqnum = 1 then team_id end) as team_1,
       max(case when seqnum = 1 then score end) as score_1,
       max(case when seqnum = 2 then team_id end) as team_2,
       max(case when seqnum = 2 then score end) as score_2
from (select t.*, row_number() over (partition by game_id order by game_id) as seqnum
      from t
     ) t
group by game_id;
</code>```

I should note that SQL tables represent unordered sets, so the resulting columns might not be in the same order as the rows you have shown.  If you have an ordering, then you can use that in the order by.

Body:
You can use conditional aggregation:

select game_id,
       max(case when seqnum = 1 then team_id end) as team_1,
       max(case when seqnum = 1 then score end) as score_1,
       max(case when seqnum = 2 then team_id end) as team_2,
       max(case when seqnum = 2 then score end) as score_2
from (select t.*, row_number() over (partition by game_id order by game_id) as seqnum
      from t
     ) t
group by game_id;

I should note that SQL tables represent unordered sets, so the resulting columns might not be in the same order as the rows you have shown.  If you have an ordering, then you can use that in the order by.


问:
NSUserDefaults Saving Score
I am looking for some advice when it comes to saving a score in my app - I currently have a coin count working in which through my HUD class when I collide through Coins the value increases accordingly. My next step is trying to initiate a high-score that initiates, after some research I think the topic I am looking into is based around NSUserDefaults..

The current code :

```<code>   import SpriteKit

   class HUD: SKNode {

   //An SKLabelNode to print the coin score:
   let coinCountText = SKLabelNode(text: "000000")

   func createHUDNodes(){

   // Configure the coin text label:
   coinCountText.fontName = "STHupo-Heavy-Italic"
   let coinTextPosition = CGPoint(x: -cameraOrigin.x + 770, y: coinPosition.y)
   coinCountText.position = coinTextPosition

   coinCountText.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
   coinCountText.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center

   // Add the text label and coin icon to the HUD:
   self.addChild(coinCountText)

   }

   func setCoinCountDisplay(newCoinCount:Int) {

   let formatter = NumberFormatter()
   let number = NSNumber(value: newCoinCount)
   formatter.minimumIntegerDigits = 6
   if let coinStr =
        formatter.string(from: number) {

        // Update the label node with the new count:
        coinCountText.text = coinStr
    }
}
</code>```

Working in the HUD class I think naturally I would need to create another 'SKlabelNode'for the highscore node which I can duplicate from the code that works above.. my problem is how can I implement a highscore feature in the app, as when closed and re-opening the application it will remember the highscore..

I assume the following code would need to be added but I do not understand how it ties together in the class.

```<code>     var currentHighScore =
     NSUserDefaults.standardUserDefaults().integerForKey("coin_highscore")

     var highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.position = CGPoint(x: viewSize.width * 0.5, y: viewSize.height * 0.30)
     self.addChild(highScoreLabel)

     if (score > currentHighScore) {

        NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "player_highscore")
        NSUserDefaults.standardUserDefaults().synchronize()

        highScoreLabel.text = "New High Score: \(score) !"

    } else {

        highScoreLabel.text = "Better Luck Next Time: \(score)"
    }
}
</code>```

Any advice on how I could integrate this code would be much appreciated.

,  AJ

Revised :

```<code>     else if nodeTouched.name == "returnToMenu"{
     // Transition to the main menu scene
     self.view?.presentScene(MenuScene(size: self.size),transition.crossFade(withDuration: 0.6))

     let currentHighScore = UserDefaults.standard.integer(forKey: "Player_highscore")

     let highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = "Value: \ (String(describing: coin.value))"
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.zPosition = 100
     highScoreLabel.position = CGPoint(x: 50, y: 50)

     self.addChild(highScoreLabel)

     if (coin.value > currentHighScore) {

     UserDefaults.standard.set(coin.value, forKey: "Player_highscore")

     UserDefaults.standard.synchronize()

     highScoreLabel.text = "New High Value: \(String(describing: coin.value)) !"

     } else {

     highScoreLabel.text = "Better Luck Next Time: \(String(describing: coin.value))"

                            }
                    }
            }

}
</code>```

I am assuming it's the referencing to my original HUD that is causing the problem? In my coin class I declared the coin.value = 5, each time the coin is collected by coinCountDisplay increases accordingly. However still does not show - :/

答:
Add a property to your view controller with both get and set and use it in all the places. The get method should get the value from UserDefaults and the set should update the value in UserDefaults.

var coinHighscore: Int {
    get {
        UserDefaults.standard.integer(forKey: "coin_highscore")
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "coin_highscore")
    }
}
```

Title: NSUserDefaults Saving Score

Body:
I am looking for some advice when it comes to saving a score in my app - I currently have a coin count working in which through my HUD class when I collide through Coins the value increases accordingly. My next step is trying to initiate a high-score that initiates, after some research I think the topic I am looking into is based around NSUserDefaults..

The current code :

   import SpriteKit

   class HUD: SKNode {

   //An SKLabelNode to print the coin score:
   let coinCountText = SKLabelNode(text: "000000")

   func createHUDNodes(){

   // Configure the coin text label:
   coinCountText.fontName = "STHupo-Heavy-Italic"
   let coinTextPosition = CGPoint(x: -cameraOrigin.x + 770, y: coinPosition.y)
   coinCountText.position = coinTextPosition

   coinCountText.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
   coinCountText.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center

   // Add the text label and coin icon to the HUD:
   self.addChild(coinCountText)

   }

   func setCoinCountDisplay(newCoinCount:Int) {

   let formatter = NumberFormatter()
   let number = NSNumber(value: newCoinCount)
   formatter.minimumIntegerDigits = 6
   if let coinStr =
        formatter.string(from: number) {

        // Update the label node with the new count:
        coinCountText.text = coinStr
    }
}

Working in the HUD class I think naturally I would need to create another 'SKlabelNode'for the highscore node which I can duplicate from the code that works above.. my problem is how can I implement a highscore feature in the app, as when closed and re-opening the application it will remember the highscore..

I assume the following code would need to be added but I do not understand how it ties together in the class.

     var currentHighScore =
     NSUserDefaults.standardUserDefaults().integerForKey("coin_highscore")

     var highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.position = CGPoint(x: viewSize.width * 0.5, y: viewSize.height * 0.30)
     self.addChild(highScoreLabel)

     if (score > currentHighScore) {

        NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "player_highscore")
        NSUserDefaults.standardUserDefaults().synchronize()

        highScoreLabel.text = "New High Score: \(score) !"

    } else {

        highScoreLabel.text = "Better Luck Next Time: \(score)"
    }
}

Any advice on how I could integrate this code would be much appreciated.

,  AJ

Revised :

     else if nodeTouched.name == "returnToMenu"{
     // Transition to the main menu scene
     self.view?.presentScene(MenuScene(size: self.size),transition.crossFade(withDuration: 0.6))

     let currentHighScore = UserDefaults.standard.integer(forKey: "Player_highscore")

     let highScoreLabel = SKLabelNode(fontNamed:"STHupo-Heavy-Italic")
     highScoreLabel.text = "Value: \ (String(describing: coin.value))"
     highScoreLabel.text = ""
     highScoreLabel.fontSize = 45
     highScoreLabel.zPosition = 100
     highScoreLabel.position = CGPoint(x: 50, y: 50)

     self.addChild(highScoreLabel)

     if (coin.value > currentHighScore) {

     UserDefaults.standard.set(coin.value, forKey: "Player_highscore")

     UserDefaults.standard.synchronize()

     highScoreLabel.text = "New High Value: \(String(describing: coin.value)) !"

     } else {

     highScoreLabel.text = "Better Luck Next Time: \(String(describing: coin.value))"

                            }
                    }
            }

}

I am assuming it's the referencing to my original HUD that is causing the problem? In my coin class I declared the coin.value = 5, each time the coin is collected by coinCountDisplay increases accordingly. However still does not show - :/


问:
const_defined? vs. defined? in Ruby
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

```<code>if defined? :String
</code>```

or I can write

```<code>if self.class.const_defined? :String
</code>```

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

答:
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

if defined? :String
```

  <p>or I can write</p>

  <pre class="lang-rb prettyprint-override"><code>if self.class.const_defined? :String
</code>```

Is there a situation where I these two ways of testing would make a difference?

These two really do two completely different things. The first tests whether the Symbol literal :String is defined. Obviously, a literal will always be defined, so this expression will always be true.

The second will check whether the constant String is defined, but not starting at the current constant lookup scope, instead starting at the class of self.

Title: const_defined? vs. defined? in Ruby

Body:
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

if defined? :String

or I can write

if self.class.const_defined? :String

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

Body:
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

if defined? :String

or I can write

if self.class.const_defined? :String

Is there a situation where I these two ways of testing would make a difference?

These two really do two completely different things. The first tests whether the Symbol literal :String is defined. Obviously, a literal will always be defined, so this expression will always be true.

The second will check whether the constant String is defined, but not starting at the current constant lookup scope, instead starting at the class of self.


问:
How do I loop through columns in R?
I am trying to clean up my code for cleaning missing data. I have a dataset with 6 columns and the code works if I were to do them individually like this:

```<code>mammographic_masses <- mammographic_masses %>%
  mutate(birad = replace(birad, birad== "na", NA)) %>%
  mutate(birad = replace(birad, birad== "N/A", NA))
</code>```

But when I try to do it in a for loop like this:

```<code>for (i in ncol(mammographic_masses)){
  print(class(mammographic_masses[[i]]))
  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "na", NA)) %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
}
</code>```

I get an error:

```<code>Error: unexpected '=' in:
"  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] ="
>     mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
Error: unexpected '=' in "    mutate(mammographic_masses[[,i]] ="
> }
Error: unexpected '}' in "}"
</code>```

I also was reading up on other ways such as apply etc. but i cant figure a way to loop it per column

答:
To provide the "new" dplyr preferred across as well as str_replace_all (good point @Gregor)

library(dplyr)
library(stringr)

mammographic_masses %>%
  mutate(across(everything(),
         ~ str_replace_all(., c("na" = NA_character_, "N/A" = NA_character_))))

#>      V1   V2   V3   V4
#> 1     d    b <NA>    c
#> 2     d    b <NA> <NA>
#> 3  <NA> <NA>    d    b
#> 4     a <NA> <NA>    b
#> 5     a    b    d <NA>
#> 6     d    c    b    c
#> 7     b    b    d <NA>
#> 8  <NA> <NA> <NA>    d
#> 9     a    d    d <NA>
#> 10 <NA>    b    d <NA>
```

<p>Same data as Rui</p>

<pre class="lang-r prettyprint-override"><code>set.seed(2020)
n <- 10
mammographic_masses <- replicate(4, sample(c(letters[1:4], "na", "N/A"), n, TRUE))
mammographic_masses <- as.data.frame(mammographic_masses)

</code>```

Title: How do I loop through columns in R?

Body:
I am trying to clean up my code for cleaning missing data. I have a dataset with 6 columns and the code works if I were to do them individually like this:

mammographic_masses <- mammographic_masses %>%
  mutate(birad = replace(birad, birad== "na", NA)) %>%
  mutate(birad = replace(birad, birad== "N/A", NA))

But when I try to do it in a for loop like this:

for (i in ncol(mammographic_masses)){
  print(class(mammographic_masses[[i]]))
  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "na", NA)) %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
}

I get an error:

Error: unexpected '=' in:
"  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] ="
>     mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
Error: unexpected '=' in "    mutate(mammographic_masses[[,i]] ="
> }
Error: unexpected '}' in "}"

I also was reading up on other ways such as apply etc. but i cant figure a way to loop it per column

Body:
To provide the "new" dplyr preferred across as well as str_replace_all (good point @Gregor)

library(dplyr)
library(stringr)

mammographic_masses %>%
  mutate(across(everything(),
         ~ str_replace_all(., c("na" = NA_character_, "N/A" = NA_character_))))

#>      V1   V2   V3   V4
#> 1     d    b <NA>    c
#> 2     d    b <NA> <NA>
#> 3  <NA> <NA>    d    b
#> 4     a <NA> <NA>    b
#> 5     a    b    d <NA>
#> 6     d    c    b    c
#> 7     b    b    d <NA>
#> 8  <NA> <NA> <NA>    d
#> 9     a    d    d <NA>
#> 10 <NA>    b    d <NA>

Same data as Rui

set.seed(2020)
n <- 10
mammographic_masses <- replicate(4, sample(c(letters[1:4], "na", "N/A"), n, TRUE))
mammographic_masses <- as.data.frame(mammographic_masses)


问:
How to sort javascript array where first record should be specific and then follow by descending order
input array as list object like,  [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

Expected sorted descending order output as, "active" object should be first and all other descending sorted by numbers after "active" record.
Tried with below approach but it does not give me active as first entry. this sort the descending by number but active not coming first.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return (x['Active'] === true ? 1 : (y - x));
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))```

Expected output:
Active object to be first in result array and then all entries descending by numbers. like, [{ number: 2.3 , Active: true },{ number: 13.23 , Active: false },{ number: 2.21 , Active: false }]

答:
What happens if there are two or more that are "active"?

If so, I would sort also these and have all of them before the "inactive" ones (also sorted).

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }, { number: 4.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      if (a['Active'] && b['Active']) return b[key] - a[key];
      if (a['Active']) return -1;
      if (b['Active']) return +1;
      return b[key] - a[key];
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))```
</div>
</div>
</p>

<p>Output (with one more "active" added to input):</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "number": 4.3,
    "Active": true
  },
  {
    "number": 2.3,
    "Active": true
  },
  {
    "number": 13.23,
    "Active": false
  },
  {
    "number": 2.21,
    "Active": false
  }
]
</code>```

Example to show that @rahul-dwivedi's answer can produce unexpected results (to address the comment that my answer is doing too much):

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }, { number: 14.23 , Active: false }, { number: 1.3 , Active: true }];

arr.sort((a, b)=>{
  if(a.Active && !b.Active){
    return -1
  }
  return b.number - a.number //since you want in the descending number. For ascending order a.number - b.number
});

console.log(arr)```
</div>
</div>
</p>

<p>Output (of @rahul-dwivedi's answer with example input):</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "number": 14.23,
    "Active": false
  },
  {
    "number": 2.3,
    "Active": true
  },
  {
    "number": 1.3,
    "Active": true
  },
  {
    "number": 13.23,
    "Active": false
  },
  {
    "number": 2.21,
    "Active": false
  }
]
</code>```

Body:
input array as list object like,  [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

Expected sorted descending order output as, "active" object should be first and all other descending sorted by numbers after "active" record.
Tried with below approach but it does not give me active as first entry. this sort the descending by number but active not coming first.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return (x['Active'] === true ? 1 : (y - x));
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))

Expected output:
Active object to be first in result array and then all entries descending by numbers. like, [{ number: 2.3 , Active: true },{ number: 13.23 , Active: false },{ number: 2.21 , Active: false }]

Body:
What happens if there are two or more that are "active"?

If so, I would sort also these and have all of them before the "inactive" ones (also sorted).

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }, { number: 4.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      if (a['Active'] && b['Active']) return b[key] - a[key];
      if (a['Active']) return -1;
      if (b['Active']) return +1;
      return b[key] - a[key];
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))

Output (with one more "active" added to input):

[
  {
    "number": 4.3,
    "Active": true
  },
  {
    "number": 2.3,
    "Active": true
  },
  {
    "number": 13.23,
    "Active": false
  },
  {
    "number": 2.21,
    "Active": false
  }
]

Example to show that @rahul-dwivedi's answer can produce unexpected results (to address the comment that my answer is doing too much):

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }, { number: 14.23 , Active: false }, { number: 1.3 , Active: true }];

arr.sort((a, b)=>{
  if(a.Active && !b.Active){
    return -1
  }
  return b.number - a.number //since you want in the descending number. For ascending order a.number - b.number
});

console.log(arr)

Output (of @rahul-dwivedi's answer with example input):

[
  {
    "number": 14.23,
    "Active": false
  },
  {
    "number": 2.3,
    "Active": true
  },
  {
    "number": 1.3,
    "Active": true
  },
  {
    "number": 13.23,
    "Active": false
  },
  {
    "number": 2.21,
    "Active": false
  }
]


问:
Dynamic content inside fancybox via get
I have multiple instances of fancybox working at the same time like this:

```<code><a class="grupito" href="?id=1#various1">Group 1</a>
<a class="grupito" href="?id=2#various1">Group 2</a>
<a class="grupito" href="?id=3#various1">Group 3</a>
</code>```

Showing the following div:

```<code><div style="display: none;">
   <div id="various1">
       //Select that shows the people from the group here depending on the id
       //of the link with a $_GET['id'] variable (from database)
   </div>
</div>
</code>```

With this call:

```<code>$("a.grupito").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
});
</code>```

This doesn't work for me. Fancybox says "The requested content cannot be loaded.
Please try again later.". If I get rid of the ?id=1 part of the href it will show up but it won't have the content that I need. Is this that I'm trying even possible with fancybox?

EDIT: In fact, checking it with firebug I see I'm getting a 404 error. Anyone can point me out in the right direction to see how I can achieve this?

答: You can use jquery.load() to make a request to your server and load that content dynamically into one fancybox div. </p>

ContentLicense: CC BY-SA 3.0

Title: Dynamic content inside fancybox via get

Body:
I have multiple instances of fancybox working at the same time like this:

Group 1
Group 2
Group 3

Showing the following div:

       //Select that shows the people from the group here depending on the id
       //of the link with a $_GET['id'] variable (from database)

With this call:

$("a.grupito").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
});

This doesn't work for me. Fancybox says "The requested content cannot be loaded.
Please try again later.". If I get rid of the ?id=1 part of the href it will show up but it won't have the content that I need. Is this that I'm trying even possible with fancybox?

EDIT: In fact, checking it with firebug I see I'm getting a 404 error. Anyone can point me out in the right direction to see how I can achieve this?


问:
Angular: how resolve the error core.js:6185
I don't know what is this error. I work with Angular 9 with sidenav from material.
I have athis error:
core.js:6185 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'margin-left': '165'. Current value: '172'.

import { Component, OnInit, ViewChild } from "@angular/core";
import { Movie } from "src/app/models/movie.model";
import { MoviesService } from "src/app/services/movies.service";
import { MatPaginator } from "@angular/material/paginator";
import { MatTableDataSource } from "@angular/material/table";
import { MatSnackBar } from "@angular/material/snack-bar";
import { MatDialog, MatDialogConfig } from "@angular/material/dialog";
import { DialogComponent } from "src/app/dialog/dialog.component";
import { MatSort } from "@angular/material/sort";

@Component({
  selector: "app-movie-list",
  templateUrl: "./movie-list.component.html",
  styleUrls: ["./movie-list.component.scss"],
})
export class MovieListComponent implements OnInit {
  displayedColumns: string[] = [
    "poster",
    "title",
    "originalTitle",
    "date",
    "vote",
    "remove",
  ];
  movies: Movie[];
  size: number;

  dataSource: MatTableDataSource<Movie>;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(
    private moviesService: MoviesService,
    private _snackBar: MatSnackBar,
    public dialog: MatDialog
  ) {}

  ngOnInit(): void {
    this.size = 0;
    this.moviesService.getMovies().subscribe((res) => {
      this.movies = res;
      this.size = this.movies.length;
      this.dataSource = new MatTableDataSource(this.movies);
      this.dataSource.paginator = this.paginator;
    });
  }

  openSnackBar(item: string) {
    this._snackBar.open(item, "Close", {
      duration: 3000,
      horizontalPosition: "right",
      verticalPosition: "bottom",
    });
  }

  remove(movie: Movie) {
    const isMovie = true;
    const dialogConfig = new MatDialogConfig();

    dialogConfig.data = {movie, isMovie};

    const dialogRef = this.dialog.open(DialogComponent, dialogConfig);

    dialogRef.afterClosed().subscribe((data) => {
      if (data === true) {
        this.moviesService.deleteMovie(movie.id).subscribe();
        this.dataSource.data.splice(this.movies.indexOf(movie), 1);
        this.dataSource = new MatTableDataSource<Movie>(this.dataSource.data);
        this.dataSource.paginator = this.paginator;
        this.size--;
        this.openSnackBar("Movie removed !");
      }
    });
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  width: 100%;
  margin-top: 62px;
}

img {
  height: 140px;
  width: 100px;
  margin-top: 5%;
  margin-bottom: 5%;
}

.update {
  color: grey;
}

.notifications {
  text-align: center;
padding-top: 100px;
margin-left: 10px;
margin-right: 10px;
}

.example-container {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #eee;
}</code>```

<mat-sidenav-container class="example-container">
  <mat-sidenav mode="side" opened>

Movies List

Total movies : {{ size }}

  </mat-sidenav>
  <mat-sidenav-content>

        <ng-container matColumnDef="poster">
           Poster

            <ng-template #noPoster>

            </ng-template>

        </ng-container>

        <ng-container matColumnDef="title">
           French title
           {{element.title}}
        </ng-container>

        <ng-container matColumnDef="originalTitle">
           Original title
           {{element.original_title}}
        </ng-container>

        <ng-container matColumnDef="date">
           Release date
           {{element.release_date | date: 'dd MMMM, y'}}
        </ng-container>

        <ng-container matColumnDef="vote">
           Vote
           {{element.vote_average}}
        </ng-container>

        <ng-container matColumnDef="remove">
           Remove

            <button mat-icon-button color="warn" (click)="remove(element)">
              <mat-icon>delete</mat-icon>
            </button>

        </ng-container>

      <mat-paginator [pageSizeOptions]="[25, 50, 100]" showFirstLastButtons></mat-paginator>

  </mat-sidenav-content>
</mat-sidenav-container>```

If you have some idea to resolve I will be happy.
Thanks

答:
Change Your View Child like that:

```<code> @ViewChild(MatPaginator, {static : true}) paginator: MatPaginator;
</code>```

try this:

```<code>    ngAfterContentInit() {
    this.size = 0;
    this.moviesService.getMovies().subscribe((res) => {
      this.movies = res;
      this.size = this.movies.length;
      this.dataSource = new MatTableDataSource(this.movies);
      this.dataSource.paginator = this.paginator;
    });

}
</code>```

Body:
I don't know what is this error. I work with Angular 9 with sidenav from material.
I have athis error:
core.js:6185 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'margin-left': '165'. Current value: '172'.

import { Component, OnInit, ViewChild } from "@angular/core";
import { Movie } from "src/app/models/movie.model";
import { MoviesService } from "src/app/services/movies.service";
import { MatPaginator } from "@angular/material/paginator";
import { MatTableDataSource } from "@angular/material/table";
import { MatSnackBar } from "@angular/material/snack-bar";
import { MatDialog, MatDialogConfig } from "@angular/material/dialog";
import { DialogComponent } from "src/app/dialog/dialog.component";
import { MatSort } from "@angular/material/sort";

@Component({
  selector: "app-movie-list",
  templateUrl: "./movie-list.component.html",
  styleUrls: ["./movie-list.component.scss"],
})
export class MovieListComponent implements OnInit {
  displayedColumns: string[] = [
    "poster",
    "title",
    "originalTitle",
    "date",
    "vote",
    "remove",
  ];
  movies: Movie[];
  size: number;

  dataSource: MatTableDataSource<Movie>;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(
    private moviesService: MoviesService,
    private _snackBar: MatSnackBar,
    public dialog: MatDialog
  ) {}

  ngOnInit(): void {
    this.size = 0;
    this.moviesService.getMovies().subscribe((res) => {
      this.movies = res;
      this.size = this.movies.length;
      this.dataSource = new MatTableDataSource(this.movies);
      this.dataSource.paginator = this.paginator;
    });
  }

  openSnackBar(item: string) {
    this._snackBar.open(item, "Close", {
      duration: 3000,
      horizontalPosition: "right",
      verticalPosition: "bottom",
    });
  }

  remove(movie: Movie) {
    const isMovie = true;
    const dialogConfig = new MatDialogConfig();

    dialogConfig.data = {movie, isMovie};

    const dialogRef = this.dialog.open(DialogComponent, dialogConfig);

    dialogRef.afterClosed().subscribe((data) => {
      if (data === true) {
        this.moviesService.deleteMovie(movie.id).subscribe();
        this.dataSource.data.splice(this.movies.indexOf(movie), 1);
        this.dataSource = new MatTableDataSource<Movie>(this.dataSource.data);
        this.dataSource.paginator = this.paginator;
        this.size--;
        this.openSnackBar("Movie removed !");
      }
    });
  }
}

table {
  width: 100%;
  margin-top: 62px;
}

img {
  height: 140px;
  width: 100px;
  margin-top: 5%;
  margin-bottom: 5%;
}

.update {
  color: grey;
}

.notifications {
  text-align: center;
padding-top: 100px;
margin-left: 10px;
margin-right: 10px;
}

.example-container {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #eee;
}

<mat-sidenav-container class="example-container">
  <mat-sidenav mode="side" opened>

Movies List

Total movies : {{ size }}

  </mat-sidenav>
  <mat-sidenav-content>

        <ng-container matColumnDef="poster">
           Poster

            <ng-template #noPoster>

            </ng-template>

        </ng-container>

        <ng-container matColumnDef="title">
           French title
           {{element.title}}
        </ng-container>

        <ng-container matColumnDef="originalTitle">
           Original title
           {{element.original_title}}
        </ng-container>

        <ng-container matColumnDef="date">
           Release date
           {{element.release_date | date: 'dd MMMM, y'}}
        </ng-container>

        <ng-container matColumnDef="vote">
           Vote
           {{element.vote_average}}
        </ng-container>

        <ng-container matColumnDef="remove">
           Remove

            <button mat-icon-button color="warn" (click)="remove(element)">
              <mat-icon>delete</mat-icon>
            </button>

        </ng-container>

      <mat-paginator [pageSizeOptions]="[25, 50, 100]" showFirstLastButtons></mat-paginator>

  </mat-sidenav-content>
</mat-sidenav-container>

If you have some idea to resolve I will be happy.
Thanks

Body:
Change Your View Child like that:

 @ViewChild(MatPaginator, {static : true}) paginator: MatPaginator;

try this:

    ngAfterContentInit() {
    this.size = 0;
    this.moviesService.getMovies().subscribe((res) => {
      this.movies = res;
      this.size = this.movies.length;
      this.dataSource = new MatTableDataSource(this.movies);
      this.dataSource.paginator = this.paginator;
    });

}


问:
Append a string item to lists in a Pandas Column
For a pandas dataframe:

```<code>Name:        Tags:
'One'        ['tag1', 'tag3']
'Two'        []
'Three'      ['tag1']
</code>```

How can 'tag2' be appended to the tags lists?

I have tried the following (addtag2 is another df):

```<code>df['Tags'] = df['Tags'].astype(str) + ', ' + addtag2['Tags'].astype(str)
</code>```

and

```<code>df['Tags'] = df['Tags'].add(addtag2['Tags'].astype(str))
</code>```

But they append the string outside the list eg ['tag1'], tag2 or ['tag1']tag2

The desired output would be:

```<code>Name:        Tags:
'One'        ['tag1', 'tag3', 'tag2']
'Two'        ['tag2']
'Three'      ['tag1', 'tag2']
</code>```

答:
This is an instance where apply comes handy:

```<code>df['Tags'] = df['Tags'].apply(lambda x: x + ['tag2'])
</code>```

Or you can do a for loop:

```<code>for x in df.Tags: x.append('tag2')
</code>```

Output:

```<code>    Name                Tags
0    One  [tag1, tag3, tag2]
1    Two              [tag2]
2  Three        [tag1, tag2]
</code>```

Body:
For a pandas dataframe:

Name:        Tags:
'One'        ['tag1', 'tag3']
'Two'        []
'Three'      ['tag1']

How can 'tag2' be appended to the tags lists?

I have tried the following (addtag2 is another df):

df['Tags'] = df['Tags'].astype(str) + ', ' + addtag2['Tags'].astype(str)

and

df['Tags'] = df['Tags'].add(addtag2['Tags'].astype(str))

But they append the string outside the list eg ['tag1'], tag2 or ['tag1']tag2

The desired output would be:

Name:        Tags:
'One'        ['tag1', 'tag3', 'tag2']
'Two'        ['tag2']
'Three'      ['tag1', 'tag2']

Body:
This is an instance where apply comes handy:

df['Tags'] = df['Tags'].apply(lambda x: x + ['tag2'])

Or you can do a for loop:

for x in df.Tags: x.append('tag2')

Output:

    Name                Tags
0    One  [tag1, tag3, tag2]
1    Two              [tag2]
2  Three        [tag1, tag2]