问:
Very Low "Used Log Space Percentage" for SQL Server database transaction file
Prologue

I have always read/observed that we should not shrink database file as they tend to grow back. There will be a performance penalty when DB will try to grow these files if there is not enough space already.

Situation

When I am executing following query for few of my databases -

```<code>select * from sys.dm_db_log_space_usage
</code>```

Some of my databases are taking around 20 GB space. Catch is column used_log_space_in_percent is showing values between .1 to 10 %. If I shrink these databases I can actually gain around 100 GB space immediately. Also please note that LogReuseWaitDesc is "nothing" for some of DBs if not all.

Due to some reason, transaction log backups are not possible in near future. (Convincing in progress)

It will be really helpful if you can provide recommendations as well as reasoning in such cases whether its a good idea to shrink files or not.

If you are taking time to think about this, THANK YOU!

答:
ldf files grow if you don't get backup, as soon as you create backup, SQL Server truncates log file. Shrinking log files is not a good idea unless you have a backup.
Please read the followings :

https://www.sqlshack.com/sql-server-transaction-log-backup-truncate-and-shrink-operations/

https://www.brentozar.com/archive/2009/08/stop-shrinking-your-database-files-seriously-now/

Body:
Prologue

I have always read/observed that we should not shrink database file as they tend to grow back. There will be a performance penalty when DB will try to grow these files if there is not enough space already.

Situation

When I am executing following query for few of my databases -

select * from sys.dm_db_log_space_usage

Some of my databases are taking around 20 GB space. Catch is column used_log_space_in_percent is showing values between .1 to 10 %. If I shrink these databases I can actually gain around 100 GB space immediately. Also please note that LogReuseWaitDesc is "nothing" for some of DBs if not all.

Due to some reason, transaction log backups are not possible in near future. (Convincing in progress)

It will be really helpful if you can provide recommendations as well as reasoning in such cases whether its a good idea to shrink files or not.

If you are taking time to think about this, THANK YOU!


来源: stackexchange

问:
Xarray group by multiple runs and time
I have an xarray Dataset that looks like this:

<xarray.Dataset>
Dimensions:          (lat: 100, lon: 130, model: 7, month: 240)
Coordinates:
    lev              float64 1.0
  * month            (month) datetime64[ns] 2040-01-01 2040-02-01 ... 2059-12-01
  * lon              (lon) float32 -99.375 -99.291664 ... -88.708336 -88.625
  * lat              (lat) float32 49.78038 49.696426 ... 41.552795 41.46884
  * model            (model) object 'bcc-csm1-1' 'CCSM4' ... 'MRI-CGCM3'
Data variables:
    month_mean_snow  (month, lat, lon) float32 ...
    month_mean_tmin  (model, month, lat, lon) float32 nan nan ... -6.0107846
    month_mean_tmax  (model, month, lat, lon) float32 nan nan ... -0.30793613
    month_mean_prec  (model, month, lat, lon) float32 nan nan ... 0.5480785
    month_mean_relh  (model, month, lat, lon) float32 nan ... 69.789246
    month_mean_wspd  (model, month, lat, lon) float32 nan 4.9480243 ... 9.585804
    month_mean_rads  (model, month, lat, lon) float32 nan 21.520756 ... 34.00794```
</div>
</div>
</p>

<p>The use case is that I have 7 different climate runs for data and then I resampled it to be at a monthly time scale. </p>

<p>Question: How do I groupby both the models and the months at the same time? </p>

<p>Expected Result: Dimensions (lat: 100, lon: 130, month=12)</p>

<p>What I get when I run this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>res.groupby('month.month', 'model').mean('month', 'model')</code>```

are dimensions (lat: 100, lon:130, model: 7, month: 12).

Do I need to squeeze or somehow expand model/ month before the groupby and then just do it on month?

答:
Try this:</p>

```<code>res.groupby('month.month').mean(dim=['model','month'])
</code>```

ContentLicense: CC BY-SA 4.0

Title: Xarray group by multiple runs and time

Body:
I have an xarray Dataset that looks like this:

<xarray.Dataset>
Dimensions:          (lat: 100, lon: 130, model: 7, month: 240)
Coordinates:
    lev              float64 1.0
  * month            (month) datetime64[ns] 2040-01-01 2040-02-01 ... 2059-12-01
  * lon              (lon) float32 -99.375 -99.291664 ... -88.708336 -88.625
  * lat              (lat) float32 49.78038 49.696426 ... 41.552795 41.46884
  * model            (model) object 'bcc-csm1-1' 'CCSM4' ... 'MRI-CGCM3'
Data variables:
    month_mean_snow  (month, lat, lon) float32 ...
    month_mean_tmin  (model, month, lat, lon) float32 nan nan ... -6.0107846
    month_mean_tmax  (model, month, lat, lon) float32 nan nan ... -0.30793613
    month_mean_prec  (model, month, lat, lon) float32 nan nan ... 0.5480785
    month_mean_relh  (model, month, lat, lon) float32 nan ... 69.789246
    month_mean_wspd  (model, month, lat, lon) float32 nan 4.9480243 ... 9.585804
    month_mean_rads  (model, month, lat, lon) float32 nan 21.520756 ... 34.00794

The use case is that I have 7 different climate runs for data and then I resampled it to be at a monthly time scale.

Question: How do I groupby both the models and the months at the same time?

Expected Result: Dimensions (lat: 100, lon: 130, month=12)

What I get when I run this:

res.groupby('month.month', 'model').mean('month', 'model')

are dimensions (lat: 100, lon:130, model: 7, month: 12).

Do I need to squeeze or somehow expand model/ month before the groupby and then just do it on month?

Body:
Try this:

res.groupby('month.month').mean(dim=['model','month'])


问:
How to POST a file using Curl from Jenkins to a Go server across a Docker net bridge?
As a part of a Jenkins freestyle project I am attempting to execute the following Post Step shell command:

```<code>curl -X POST -i -F "SimpleTest=@target/surefire-reports/TEST-junitfaq.SimpleTest.xml" 127.0.0.1:9090/
</code>```

This request is targeting the following, simple, Go server:

```<code>package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    router := mux.NewRouter()
    router.
        Path("/").
        Methods("POST").
        HandlerFunc(UploadFile)

    fmt.Println("Starting...")

    log.Fatal(http.ListenAndServe(":9090", router))
}

func UploadFile(w http.ResponseWriter, r *http.Request) {
    (w).Header().Set("Access-Control-Allow-Origin", "*")

    err := r.ParseForm()
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    file, _, err := r.FormFile("SimpleTest")
    defer file.Close()
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    bytes := make([]byte, 100)
    n, err := file.Read(bytes)
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    fmt.Printf("%d bytes: %s\n", n, string(bytes[:n]))
}

</code>```

Both Jenkins and the Go server are running in Docker containers created using the following Docker-compose file:

```<code>version: '3'

services:

  foobar:
    container_name: foobar
    image: foobar:latest
    hostname: foobar
    build:
      context: .
      dockerfile: Dockerfile
    networks:
      - foobar-net
    ports:
      - 9090:9090
    labels:
      kompose.service.type: LoadBalancer

  jenkins:
    container_name: jenkins
    image: jenkinsci/blueocean
    restart: always
    hostname: foobar
    ports:
      - 7070:8080
    networks:
      - foobar-net
    depends_on:
      - foobar
    links:
      - foobar
    volumes:
      - $PWD/data/jenkins:/var/jenkins_home

networks:
  foobar-net:
    driver: bridge
</code>```

When I execute this job, the Curl command fails and I am returned this result:

```<code>curl -X POST -i -F 'SimpleTest=@target/surefire-reports/TEST-junitfaq.SimpleTest.xml' 127.0.0.1:9090/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (7) Failed to connect to 127.0.0.1 port 9090: Connection refused
Build step 'Execute shell' marked build as failure
</code>```

What could be the issue that's causing my connection to be refused?

答: In the Jenkins container, curl to 127.0.0.1:9090 will attempt to connect to a service inside the same container, but it looks like you're running this service in another container. You'll probably want to curl to foobar:9090

Body:
As a part of a Jenkins freestyle project I am attempting to execute the following Post Step shell command:

curl -X POST -i -F "SimpleTest=@target/surefire-reports/TEST-junitfaq.SimpleTest.xml" 127.0.0.1:9090/

This request is targeting the following, simple, Go server:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    router := mux.NewRouter()
    router.
        Path("/").
        Methods("POST").
        HandlerFunc(UploadFile)

    fmt.Println("Starting...")

    log.Fatal(http.ListenAndServe(":9090", router))
}

func UploadFile(w http.ResponseWriter, r *http.Request) {
    (w).Header().Set("Access-Control-Allow-Origin", "*")

    err := r.ParseForm()
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    file, _, err := r.FormFile("SimpleTest")
    defer file.Close()
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    bytes := make([]byte, 100)
    n, err := file.Read(bytes)
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    fmt.Printf("%d bytes: %s\n", n, string(bytes[:n]))
}

Both Jenkins and the Go server are running in Docker containers created using the following Docker-compose file:

version: '3'

services:

  foobar:
    container_name: foobar
    image: foobar:latest
    hostname: foobar
    build:
      context: .
      dockerfile: Dockerfile
    networks:
      - foobar-net
    ports:
      - 9090:9090
    labels:
      kompose.service.type: LoadBalancer

  jenkins:
    container_name: jenkins
    image: jenkinsci/blueocean
    restart: always
    hostname: foobar
    ports:
      - 7070:8080
    networks:
      - foobar-net
    depends_on:
      - foobar
    links:
      - foobar
    volumes:
      - $PWD/data/jenkins:/var/jenkins_home

networks:
  foobar-net:
    driver: bridge

When I execute this job, the Curl command fails and I am returned this result:

curl -X POST -i -F 'SimpleTest=@target/surefire-reports/TEST-junitfaq.SimpleTest.xml' 127.0.0.1:9090/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (7) Failed to connect to 127.0.0.1 port 9090: Connection refused
Build step 'Execute shell' marked build as failure

What could be the issue that's causing my connection to be refused?


问:
How do I import Three.js into my Nuxt project
I want to import modules in examples folder in THREE.js such as OBJLoader into my Nuxt Project.

I can import main folder of THREE, but error occurs when trying to import modules in examples folder.

Tried these steps in official docs.

https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules

I'm getting error below

SyntaxError
Unexpected token {

```<code><template>
</template>
<script>
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
export default{
}
</script>
</code>```

here are my github repository
https://github.com/ksuhara/threejs-test

答: Threejs must be run on the client side so enclosed the component with <client-only> tag and loaded it dynamically with const MyComponent = () => import('~/path/to/MyComponent.vue'); but now I am getting the error on server side.

Body:
I want to import modules in examples folder in THREE.js such as OBJLoader into my Nuxt Project.

I can import main folder of THREE, but error occurs when trying to import modules in examples folder.

Tried these steps in official docs.

https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules

I'm getting error below

SyntaxError
Unexpected token {

<template>
</template>

here are my github repository
https://github.com/ksuhara/threejs-test


问:
I dont know what is wrong with my tkinter project
it has worked in the past and i have no clue what has happened. please helpenter image description here</p>

答:
Close the parenthesis at the end of line, should be y = 170)).

When IDE with syntax highlighting isn't available, you might install pylint or other linter package to check your code. Linters could help  a lot.


问:
envp in execve system call contain nothing execpt of the string" LS_C"
I bullied simple monitor that print the path of the file that been execute so i hooked the execve system call but the problem was that the file name parameter contain only the file name and not the all path. any way i copied the envp parameter and i printed every string in it
but the out put was just LS_C so i am wondering where do the execve system call get path from
this is my code:

```<code>static asmlinkage long our_execl(const char __user * filename,
            const char __user * const __user * argv,
            const char __user * const __user * envp) {
copy_from_user(mid,envp,sizeof(envp));
 printk("okdotk:%d\n",sizeof(envp));
for(i=0;i<sizeof(envp);i++)
{
strncpy_from_user(env, mid[i], sizeof(mid[i]));
env[255]='\0';
printk("%s\n",env);

reset_envp(sizeof(env));
}
</code>```

return original_call(filename,argv,envp)
}

答:
sizeof(envp) is the sizeof a pointer which on your system is 4. It's not the length of the array.

Therefore, your code merely shows the first 4 letters LS_C of a single environment variable LS_COLOR=..

You should instead iterate until envp[i] is NULL, signaling the end of the environment. For each environment variable, you should copy until you see a \0, and again not stop after the first 4 bytes.

Body:
I bullied simple monitor that print the path of the file that been execute so i hooked the execve system call but the problem was that the file name parameter contain only the file name and not the all path. any way i copied the envp parameter and i printed every string in it
but the out put was just LS_C so i am wondering where do the execve system call get path from
this is my code:

static asmlinkage long our_execl(const char __user * filename,
            const char __user * const __user * argv,
            const char __user * const __user * envp) {
copy_from_user(mid,envp,sizeof(envp));
 printk("okdotk:%d\n",sizeof(envp));
for(i=0;i<sizeof(envp);i++)
{
strncpy_from_user(env, mid[i], sizeof(mid[i]));
env[255]='\0';
printk("%s\n",env);

reset_envp(sizeof(env));
}

return original_call(filename,argv,envp)
}


问:
dropdown stuck behind other elements despite z-index
If you click on the speciesSelector dropdown, you'll see that it's getting stuck behind other elements despite setting z-index.

I found several other questions with a similar issue, but none of the solutions I've found have fixed the issue in my instance yet.

const speciesTypes = ['Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian'];

function multiSelectHeaderFilter() {
  var select = document.createElement("select");
  select.multiple = "multiple";
  select.id = 'speciesSelector';
  speciesTypes.forEach(species => {
    select.innerHTML += "<option value='" + species + "'>" + species + "</option>";
  });
  return select;
}

new Tabulator("#tabulator", {
  layout: "fitColumns",
  data: [{
    name: 'Geordi La Forge',
    species: 'Human'
  }, {
    name: 'Dathon',
    species: 'Tamarian'
  }, {
    name: 'Jean-Luc Picard',
    species: 'Human'
  }, {
    name: 'Worf, son of Mogh',
    species: 'Klingon'
  }, {
    name: 'Tasha Yarr',
    species: 'Human'
  }, {
    name: 'Data',
    species: 'Android'
  }, {
    name: 'Wesley Crusher',
    species: 'Human'
  }, {
    name: 'Jalad',
    species: 'Tamarian'
  }, {
    name: 'Lwaxana Troi',
    species: 'Betazoid'
  }, {
    name: 'Temba',
    species: 'Tamarian'
  }, {
    name: 'T\'Kuvma',
    species: 'Klingon'
  }, {
    name: 'Lore',
    species: 'Android'
  }, {
    name: 'Noonian Soongh',
    species: 'Human'
  }, {
    name: 'Darmok',
    species: 'Tamarian'
  }, {
    name: 'Reittan Grax',
    species: 'Betazoid'
  }, {
    name: 'Quark',
    species: 'Ferengi'
  }],
  headerSort: true,
  columns: [{
    title: 'Name',
    field: 'name',
    sorter: 'string'
  }, {
    title: 'Species',
    field: 'species',
    sorter: 'string',
    headerFilter: multiSelectHeaderFilter
  }, ],
});

document.multiselect('#speciesSelector');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabulator-table {
  z-index: 0;
}

.tabulator-header {
  z-index: 1000;
}

.multiselect-list {
  z-index: 1000;
}</code>```

<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">

<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">

```

Link to JSFiddle: https://jsfiddle.net/jjech/3th28pv0/89/

答:
Problem is with overflow: hidden;. Remove overflow: hidden; from

 and

.

Basically add to your CSS:

```<code>.tabulator .tabulator-header, .tabulator .tabulator-header .tabulator-col {
    overflow: unset;
}
</code>```

This styles should be added after other CSS imports in order to take effect. Make sure to place that CSS after all included CSS files.

const speciesTypes = ['Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian'];

function multiSelectHeaderFilter() {
  var select = document.createElement("select");
  select.multiple = "multiple";
  select.id = 'speciesSelector';
  speciesTypes.forEach(species => {
    select.innerHTML += "<option value='" + species + "'>" + species + "</option>";
  });
  return select;
}

new Tabulator("#tabulator", {
  layout: "fitColumns",
  data: [{
    name: 'Geordi La Forge',
    species: 'Human'
  }, {
    name: 'Dathon',
    species: 'Tamarian'
  }, {
    name: 'Jean-Luc Picard',
    species: 'Human'
  }, {
    name: 'Worf, son of Mogh',
    species: 'Klingon'
  }, {
    name: 'Tasha Yarr',
    species: 'Human'
  }, {
    name: 'Data',
    species: 'Android'
  }, {
    name: 'Wesley Crusher',
    species: 'Human'
  }, {
    name: 'Jalad',
    species: 'Tamarian'
  }, {
    name: 'Lwaxana Troi',
    species: 'Betazoid'
  }, {
    name: 'Temba',
    species: 'Tamarian'
  }, {
    name: 'T\'Kuvma',
    species: 'Klingon'
  }, {
    name: 'Lore',
    species: 'Android'
  }, {
    name: 'Noonian Soongh',
    species: 'Human'
  }, {
    name: 'Darmok',
    species: 'Tamarian'
  }, {
    name: 'Reittan Grax',
    species: 'Betazoid'
  }, {
    name: 'Quark',
    species: 'Ferengi'
  }],
  headerSort: true,
  columns: [{
    title: 'Name',
    field: 'name',
    sorter: 'string'
  }, {
    title: 'Species',
    field: 'species',
    sorter: 'string',
    headerFilter: multiSelectHeaderFilter
  }, ],
});

document.multiselect('#speciesSelector');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabulator-table {
  z-index: 0;
}

.tabulator-header {
  z-index: 1000;
}

.multiselect-list {
  z-index: 1000;
}</code>```

<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">

<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">

```

Body:
If you click on the speciesSelector dropdown, you'll see that it's getting stuck behind other elements despite setting z-index.

I found several other questions with a similar issue, but none of the solutions I've found have fixed the issue in my instance yet.

const speciesTypes = ['Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian'];

function multiSelectHeaderFilter() {
  var select = document.createElement("select");
  select.multiple = "multiple";
  select.id = 'speciesSelector';
  speciesTypes.forEach(species => {
    select.innerHTML += "<option value='" + species + "'>" + species + "</option>";
  });
  return select;
}

new Tabulator("#tabulator", {
  layout: "fitColumns",
  data: [{
    name: 'Geordi La Forge',
    species: 'Human'
  }, {
    name: 'Dathon',
    species: 'Tamarian'
  }, {
    name: 'Jean-Luc Picard',
    species: 'Human'
  }, {
    name: 'Worf, son of Mogh',
    species: 'Klingon'
  }, {
    name: 'Tasha Yarr',
    species: 'Human'
  }, {
    name: 'Data',
    species: 'Android'
  }, {
    name: 'Wesley Crusher',
    species: 'Human'
  }, {
    name: 'Jalad',
    species: 'Tamarian'
  }, {
    name: 'Lwaxana Troi',
    species: 'Betazoid'
  }, {
    name: 'Temba',
    species: 'Tamarian'
  }, {
    name: 'T\'Kuvma',
    species: 'Klingon'
  }, {
    name: 'Lore',
    species: 'Android'
  }, {
    name: 'Noonian Soongh',
    species: 'Human'
  }, {
    name: 'Darmok',
    species: 'Tamarian'
  }, {
    name: 'Reittan Grax',
    species: 'Betazoid'
  }, {
    name: 'Quark',
    species: 'Ferengi'
  }],
  headerSort: true,
  columns: [{
    title: 'Name',
    field: 'name',
    sorter: 'string'
  }, {
    title: 'Species',
    field: 'species',
    sorter: 'string',
    headerFilter: multiSelectHeaderFilter
  }, ],
});

document.multiselect('#speciesSelector');

.tabulator-table {
  z-index: 0;
}

.tabulator-header {
  z-index: 1000;
}

.multiselect-list {
  z-index: 1000;
}

<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">

<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">

Link to JSFiddle: https://jsfiddle.net/jjech/3th28pv0/89/

Body:
Problem is with overflow: hidden;. Remove overflow: hidden; from <div class="tabulator-col tabulator-sortable"></div> and <div class="tabulator-header"></div>.

Basically add to your CSS:

.tabulator .tabulator-header, .tabulator .tabulator-header .tabulator-col {
    overflow: unset;
}

This styles should be added after other CSS imports in order to take effect. Make sure to place that CSS after all included CSS files.

const speciesTypes = ['Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian'];

function multiSelectHeaderFilter() {
  var select = document.createElement("select");
  select.multiple = "multiple";
  select.id = 'speciesSelector';
  speciesTypes.forEach(species => {
    select.innerHTML += "<option value='" + species + "'>" + species + "</option>";
  });
  return select;
}

new Tabulator("#tabulator", {
  layout: "fitColumns",
  data: [{
    name: 'Geordi La Forge',
    species: 'Human'
  }, {
    name: 'Dathon',
    species: 'Tamarian'
  }, {
    name: 'Jean-Luc Picard',
    species: 'Human'
  }, {
    name: 'Worf, son of Mogh',
    species: 'Klingon'
  }, {
    name: 'Tasha Yarr',
    species: 'Human'
  }, {
    name: 'Data',
    species: 'Android'
  }, {
    name: 'Wesley Crusher',
    species: 'Human'
  }, {
    name: 'Jalad',
    species: 'Tamarian'
  }, {
    name: 'Lwaxana Troi',
    species: 'Betazoid'
  }, {
    name: 'Temba',
    species: 'Tamarian'
  }, {
    name: 'T\'Kuvma',
    species: 'Klingon'
  }, {
    name: 'Lore',
    species: 'Android'
  }, {
    name: 'Noonian Soongh',
    species: 'Human'
  }, {
    name: 'Darmok',
    species: 'Tamarian'
  }, {
    name: 'Reittan Grax',
    species: 'Betazoid'
  }, {
    name: 'Quark',
    species: 'Ferengi'
  }],
  headerSort: true,
  columns: [{
    title: 'Name',
    field: 'name',
    sorter: 'string'
  }, {
    title: 'Species',
    field: 'species',
    sorter: 'string',
    headerFilter: multiSelectHeaderFilter
  }, ],
});

document.multiselect('#speciesSelector');

.tabulator-table {
  z-index: 0;
}

.tabulator-header {
  z-index: 1000;
}

.multiselect-list {
  z-index: 1000;
}

<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.5.3/dist/js/tabulator.min.js"></script>
<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/mneofit/multiselect/multiselect.min.js"></script>
<style>
.tabulator .tabulator-header,
.tabulator .tabulator-header .tabulator-col
{
 overflow: unset;
}
</style>

<body>
  <div id="tabulator"></div>
</body>


问:
In a vectorized way in numpy: Cutting out chunks of data (of different sizes) conditionally dependent on whats inside the chunk
I have a vector of integers (a 1D numpy array) that looks like:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
```

<p>(In a vectorized way,) I want to filter out all of the data between 8's that contain at least one 99 value.  </p>

<p>So in this example, the data I want to cut out is listed in bold:</p>

```8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1```

<p>(i.e., it's data that's inbetween the 8's that contains at least one 99)</p>

<p>So if I made a boolean mask to crop out this data it would look like:</p>

```Data: 8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
Mask: T, T, T, T, F,  F, F, F, F, F, T, T, T, T, F,  F,  F, T, T, T```

<p>And data after cropping look like:</p>

<pre class="lang-none prettyprint-override"><code>Data(Mask) = 8, 1, 1, 2, 8, 2, 2, 2, 8, 1, 1
</code>```

I can come up with vectorized code that can do this if there is a guaranteed equal spacing between the 8's. Here's that code:

```<code>inputRaw = np.array([8, 2, 3, 2, 99, 2, 8, 2, 3, 2, 2, 2, 8, 2, 3, 3, 3, 3])
inputPartitioned = np.reshape(inputRaw, (3, 6))
# reshaping it into an array of the form: np.array([[8, 2, 3, 2, 99, 2], [8, 2, 3, 2, 2, 2], [8, 2, 3, 3, 3, 3]])
selectedSections = np.logical_not(np.any(inputPartitioned>8, axis=1))
outputPartitioned = inputPartitioned[selectedSections]
outputFlattened = outputPartitioned.flatten()
</code>```

One extra thing that I need is a mask or index that tells me (in the original indices) the data that was cropped. (I need this because I have a second array I want to keep track of that has shared indices with the first array). I can code this mask (assumming equal spacing between the 8's) like so:

```<code>inputIndex = np.arange(inputRaw.size)
inputIndexPartitioned =  np.reshape(inputIndex, (3, 6))
outputPartitionedIndex = inputIndexPartitioned[selectedSections]
outputFlattenedIndex = outputPartitionedIndex.flatten()
</code>```

But I'm not sure how to do this in a vectorized way in the case where there's unequal spacing between the 8's.

Any ideas? These arrays are very long, so solutions that work fast for large arrays are helpful. Also, I'm fairly confident that these "99's" will always immediately after an 8, so maybe that might be helpful information in making the algorithm.

答:
Approach #1

Here's a vectorized one for a generic case when the 99's occur between two 8's and all those elements between those two 8's are then to be removed/masked-out -

```<code>def vectorized1_app(a):
    m1 = a==8
    m2 = a==99
    d = m1.cumsum()
    occ_mask = np.bincount(d,m2)<1
    if m1.argmax() > m2.argmax():
        occ_mask[0] = ~occ_mask[0]

    if m1[::-1].argmax() > m2[::-1].argmax():
        occ_mask[-1] = ~occ_mask[-1]
    mask = occ_mask[d]
    return mask
</code>```

Approach #2

We could also make use of JIT-compiled numba code for the specific case of 8's and 99's in sequence -

```<code>from numba import njit

@njit
def numba1(a, mask_out):
    N = len(a)
    fill = False
    last8_index = 0
    for i in range(N-1):
        if a[i]==8:
            if a[i+1]==99:
                fill = True
            else:
                fill = False
            last8_index = i

        if fill:
            mask_out[i] = False

    return mask_out, last8_index

def numba1_app(a):
    N = len(a)
    mask = np.ones(N, dtype=np.bool)
    mask, last8_index = numba1(a, mask)
    if a[-1]!=8:
        mask[last8_index:] = True
    return mask
</code>```

Approach #2-B

Some marginal perf. boost with pushing the last step of last element check to numba-part, like so -

```<code>@njit
def numba2(a, mask_out):
    N = len(a)
    fill = False
    last8_index = 0
    for i in range(N-1):
        if a[i]==8:
            if a[i+1]==99:
                fill = True
            else:
                fill = False
            last8_index = i

        if fill:
            mask_out[i] = False

    if a[N-1]!=8:
        for i in range(last8_index,N-1):
            mask_out[i] = True

    return mask_out

def numba2_app(a):
    return numba2(a, np.ones(len(a), dtype=np.bool))
</code>```

Note that the outputs off the posted approaches are mask, so that masking the input array with these would give us comparable results to Data(Mask).

Special case : Mask out until first 8, keep after last 8

We could modify app#1 with two ways to do so -

App#1-Mod#1 -

```<code>m1 = a==8
m2 = a==99
d = m1.cumsum()
occ_mask = np.bincount(d,m2)<1
occ_mask[0] = False
mask = occ_mask[d]
</code>```

If you have to modify the case such that you wish to mask after last 8 too, simply do : occ_mask[-1] = False.

App#1-Mod#2 -

```<code>m1 = a==8
m2 = a==99
d = m1.cumsum().clip(min=1)
occ_mask = np.bincount(d,m2)<1
mask = occ_mask[d]
</code>```

If you have to modify the case such that you wish to mask after last 8 too, do : m1c = m1.cumsum(); d = m1c.clip(min=1, max=m1c.max()-1).

Body:
I have a vector of integers (a 1D numpy array) that looks like:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1

(In a vectorized way,) I want to filter out all of the data between 8's that contain at least one 99 value.

So in this example, the data I want to cut out is listed in bold:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1

(i.e., it's data that's inbetween the 8's that contains at least one 99)

So if I made a boolean mask to crop out this data it would look like:

Data: 8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
Mask: T, T, T, T, F,  F, F, F, F, F, T, T, T, T, F,  F,  F, T, T, T

And data after cropping look like:

Data(Mask) = 8, 1, 1, 2, 8, 2, 2, 2, 8, 1, 1

I can come up with vectorized code that can do this if there is a guaranteed equal spacing between the 8's. Here's that code:

inputRaw = np.array([8, 2, 3, 2, 99, 2, 8, 2, 3, 2, 2, 2, 8, 2, 3, 3, 3, 3])
inputPartitioned = np.reshape(inputRaw, (3, 6))
# reshaping it into an array of the form: np.array([[8, 2, 3, 2, 99, 2], [8, 2, 3, 2, 2, 2], [8, 2, 3, 3, 3, 3]])
selectedSections = np.logical_not(np.any(inputPartitioned>8, axis=1))
outputPartitioned = inputPartitioned[selectedSections]
outputFlattened = outputPartitioned.flatten()

One extra thing that I need is a mask or index that tells me (in the original indices) the data that was cropped. (I need this because I have a second array I want to keep track of that has shared indices with the first array). I can code this mask (assumming equal spacing between the 8's) like so:

inputIndex = np.arange(inputRaw.size)
inputIndexPartitioned =  np.reshape(inputIndex, (3, 6))
outputPartitionedIndex = inputIndexPartitioned[selectedSections]
outputFlattenedIndex = outputPartitionedIndex.flatten()

But I'm not sure how to do this in a vectorized way in the case where there's unequal spacing between the 8's.

Any ideas? These arrays are very long, so solutions that work fast for large arrays are helpful. Also, I'm fairly confident that these "99's" will always immediately after an 8, so maybe that might be helpful information in making the algorithm.

Body:
Approach #1

Here's a vectorized one for a generic case when the 99's occur between two 8's and all those elements between those two 8's are then to be removed/masked-out -

def vectorized1_app(a):
    m1 = a==8
    m2 = a==99
    d = m1.cumsum()
    occ_mask = np.bincount(d,m2)<1
    if m1.argmax() > m2.argmax():
        occ_mask[0] = ~occ_mask[0]

    if m1[::-1].argmax() > m2[::-1].argmax():
        occ_mask[-1] = ~occ_mask[-1]
    mask = occ_mask[d]
    return mask

Approach #2

We could also make use of JIT-compiled numba code for the specific case of 8's and 99's in sequence -

from numba import njit

@njit
def numba1(a, mask_out):
    N = len(a)
    fill = False
    last8_index = 0
    for i in range(N-1):
        if a[i]==8:
            if a[i+1]==99:
                fill = True
            else:
                fill = False
            last8_index = i

        if fill:
            mask_out[i] = False

    return mask_out, last8_index

def numba1_app(a):
    N = len(a)
    mask = np.ones(N, dtype=np.bool)
    mask, last8_index = numba1(a, mask)
    if a[-1]!=8:
        mask[last8_index:] = True
    return mask

Approach #2-B

Some marginal perf. boost with pushing the last step of last element check to numba-part, like so -

@njit
def numba2(a, mask_out):
    N = len(a)
    fill = False
    last8_index = 0
    for i in range(N-1):
        if a[i]==8:
            if a[i+1]==99:
                fill = True
            else:
                fill = False
            last8_index = i

        if fill:
            mask_out[i] = False

    if a[N-1]!=8:
        for i in range(last8_index,N-1):
            mask_out[i] = True

    return mask_out

def numba2_app(a):
    return numba2(a, np.ones(len(a), dtype=np.bool))

Note that the outputs off the posted approaches are mask, so that masking the input array with these would give us comparable results to Data(Mask).

Special case : Mask out until first 8, keep after last 8

We could modify app#1 with two ways to do so -

App#1-Mod#1 -

m1 = a==8
m2 = a==99
d = m1.cumsum()
occ_mask = np.bincount(d,m2)<1
occ_mask[0] = False
mask = occ_mask[d]

If you have to modify the case such that you wish to mask after last 8 too, simply do : occ_mask[-1] = False.

App#1-Mod#2 -

m1 = a==8
m2 = a==99
d = m1.cumsum().clip(min=1)
occ_mask = np.bincount(d,m2)<1
mask = occ_mask[d]

If you have to modify the case such that you wish to mask after last 8 too, do : m1c = m1.cumsum(); d = m1c.clip(min=1, max=m1c.max()-1).


问:
Rails 6 has_one relation explicit class_name not working
I'm currently upgrading an app from rails 5.2 to 6.0.2. Using ruby 2.6.3
One of the issues I'm seeing is around the inferred class for a relation
I have two models

class Site::Page::Metadata < ApplicationRecord
  belongs_to :page, class_name: "Site::BlockPage"
end
```

<p>and</p>

<pre class="lang-rb prettyprint-override"><code>class Site::BlockPage < ApplicationRecord
  has_one :metadata, dependent: :destroy, class_name: "Site::Page::Metadata", foreign_key: "page_id"
end
</code>```

Since upgrading to rails 6 with the setup as above I get uninitialized constant error when trying to access a pages metadata.
ActionView::Template::Error: uninitialized constant Site::BlockPage::Site::Page::Metadata
Where it doesn't look to be correctly inferring the class of the relation.
However when I reflect on the association it looks correct

```<code>irb(main):001:0> Site::BlockPage.reflect_on_association(:metadata)
=> #<ActiveRecord::Reflection::HasOneReflection:0x00007fbeffea7020 @name=:metadata, @scope=nil, @options={:dependent=>:destroy, :class_name=>"Site::Page::Metadata", :foreign_key=>"page_id", :autosave=>true}, @active_record=Site::BlockPage (call 'Site::BlockPage.connection' to establish a connection), @klass=nil, @plural_name="metadata", @type=nil, @foreign_type=nil, @constructable=true, @association_scope_cache=#<Concurrent::Map:0x00007fbeffea6ee0 entries=0 default_proc=nil>>
</code>```

I then tried updating the relation on the Site::BlockPage to be

```<code>has_one :metadata, dependent: :destroy, class_name: "::Site::Page::Metadata", foreign_key: "page_id"
</code>```

With the root namespace prefix and it now references the ActiveStorageValidations::Metadata class from the active_storage_validations gem.

I'm assuming this is something incorrect in my autoloading setup but I'm a bit stuck on where to start digging.

答:
This is likely a result of changing to the new Zeitwerk autoloader. It has revealed a bug in your code that the old Rails autoloader was papering over.

```<code>class Site::BlockPage
  has_one :metadata, dependent: :destroy, class_name: "Site::Page::Metadata", foreign_key: "page_id"
end
</code>```

Here Site::Page::Metadata is ambiguous. It could mean Site::BlockPage::Site::Page::Metadata or Site::Page::Metadata.

If Site::Page::Metadata is already loaded, you're good.

If it isn't, the Rails autoloader takes over.

Prior to Zeitwerk this worked because of how the Rails autoloader worked. It would catch the exception when a constant was missing and then look around for a file path which matched. In this case it would try Site::BlockPage::Site::Page::Metadata, get an exception, and look for site/block_page/site/page/metadata.rb. This doesn't exist. That doesn't exist, so it tries Site::Page::Metadata and looks for site/page/metadata.rb. That exists and that's what gets loaded.

Zeitwerk does the opposite. When Rails starts up it scans your directories, infers the class name from the filename, and registers it to be autoloaded from that file. For example, if it finds app/models/site/page/metadata.rb it runs Site::Page.autoload(:Metadata, app/models/site/page/metadata.rb) registering references to Site::Page::Metadata to load app/models/site/page/metadata.rb. The Site::Page::Metadata constant exists, but its content hasn't yet been loaded.

When Rails 6 looks for Site::BlockPage::Site::Page::Metadata it gets an exception and that's it. Zeitwerk does not catch the exception and continue searching like the old autoloader did.

Because Zeitwerk creates constants for every class at startup it is much more reliable. It does not rely on the order classes are loaded. But it does not match the quirks of the old Rails autoloader.

For this reason, and others, it's preferable to spell out nested classes and modules. And it's very important that the file path matches Rails's expectations.

```<code># app/models/site/block_page.rb
module Site
  class BlockPage < ApplicationRecord
    has_one :metadata, dependent: :destroy, class_name: "Site::Page::Metadata", foreign_key: "page_id"
  end
end

# app/models/site/page/metadata.rb
module Site
  class Page
    class Metadata < ApplicationRecord
      belongs_to :page, class_name: "Site::BlockPage"
    end
  end
end
</code>```

You can see how Zeitwerk is loading your classes with Rails.autoloaders.main or by throwing Rails.autoloaders.log! into your config/application.rb. See Autloading and Reloading Constants (Zeitwerk Mode) - Troubleshooting.

tl;dr

Used nested namespaces. Avoid chaining.

Make ambiguous classes unambiguous with a leading ::.

Follow the Rails file path naming conventions.

See Understanding Zeitwerk in Rails 6 by Marcelo Casiraghi.

Body:
I'm currently upgrading an app from rails 5.2 to 6.0.2. Using ruby 2.6.3
One of the issues I'm seeing is around the inferred class for a relation
I have two models

class Site::Page::Metadata < ApplicationRecord
  belongs_to :page, class_name: "Site::BlockPage"
end

and

class Site::BlockPage < ApplicationRecord
  has_one :metadata, dependent: :destroy, class_name: "Site::Page::Metadata", foreign_key: "page_id"
end

Since upgrading to rails 6 with the setup as above I get uninitialized constant error when trying to access a pages metadata.
ActionView::Template::Error: uninitialized constant Site::BlockPage::Site::Page::Metadata
Where it doesn't look to be correctly inferring the class of the relation.
However when I reflect on the association it looks correct

irb(main):001:0> Site::BlockPage.reflect_on_association(:metadata)
=> #<ActiveRecord::Reflection::HasOneReflection:0x00007fbeffea7020 @name=:metadata, @scope=nil, @options={:dependent=>:destroy, :class_name=>"Site::Page::Metadata", :foreign_key=>"page_id", :autosave=>true}, @active_record=Site::BlockPage (call 'Site::BlockPage.connection' to establish a connection), @klass=nil, @plural_name="metadata", @type=nil, @foreign_type=nil, @constructable=true, @association_scope_cache=#<Concurrent::Map:0x00007fbeffea6ee0 entries=0 default_proc=nil>>

I then tried updating the relation on the Site::BlockPage to be

has_one :metadata, dependent: :destroy, class_name: "::Site::Page::Metadata", foreign_key: "page_id"

With the root namespace prefix and it now references the ActiveStorageValidations::Metadata class from the active_storage_validations gem.

I'm assuming this is something incorrect in my autoloading setup but I'm a bit stuck on where to start digging.

Body:
This is likely a result of changing to the new Zeitwerk autoloader. It has revealed a bug in your code that the old Rails autoloader was papering over.

class Site::BlockPage
  has_one :metadata, dependent: :destroy, class_name: "Site::Page::Metadata", foreign_key: "page_id"
end

Here Site::Page::Metadata is ambiguous. It could mean Site::BlockPage::Site::Page::Metadata or Site::Page::Metadata.

If Site::Page::Metadata is already loaded, you're good.

If it isn't, the Rails autoloader takes over.

Prior to Zeitwerk this worked because of how the Rails autoloader worked. It would catch the exception when a constant was missing and then look around for a file path which matched. In this case it would try Site::BlockPage::Site::Page::Metadata, get an exception, and look for site/block_page/site/page/metadata.rb. This doesn't exist. That doesn't exist, so it tries Site::Page::Metadata and looks for site/page/metadata.rb. That exists and that's what gets loaded.

Zeitwerk does the opposite. When Rails starts up it scans your directories, infers the class name from the filename, and registers it to be autoloaded from that file. For example, if it finds app/models/site/page/metadata.rb it runs Site::Page.autoload(:Metadata, app/models/site/page/metadata.rb) registering references to Site::Page::Metadata to load app/models/site/page/metadata.rb. The Site::Page::Metadata constant exists, but its content hasn't yet been loaded.

When Rails 6 looks for Site::BlockPage::Site::Page::Metadata it gets an exception and that's it. Zeitwerk does not catch the exception and continue searching like the old autoloader did.

Because Zeitwerk creates constants for every class at startup it is much more reliable. It does not rely on the order classes are loaded. But it does not match the quirks of the old Rails autoloader.

For this reason, and others, it's preferable to spell out nested classes and modules. And it's very important that the file path matches Rails's expectations.

# app/models/site/block_page.rb
module Site
  class BlockPage < ApplicationRecord
    has_one :metadata, dependent: :destroy, class_name: "Site::Page::Metadata", foreign_key: "page_id"
  end
end

# app/models/site/page/metadata.rb
module Site
  class Page
    class Metadata < ApplicationRecord
      belongs_to :page, class_name: "Site::BlockPage"
    end
  end
end

You can see how Zeitwerk is loading your classes with Rails.autoloaders.main or by throwing Rails.autoloaders.log! into your config/application.rb. See Autloading and Reloading Constants (Zeitwerk Mode) - Troubleshooting.

tl;dr

Used nested namespaces. Avoid chaining.

Make ambiguous classes unambiguous with a leading ::.

Follow the Rails file path naming conventions.

See Understanding Zeitwerk in Rails 6 by Marcelo Casiraghi.


问:
comparing two arrays to find results of assessment
I want to compare the following two arrays:

```<code>Array
(
    [0] => stdClass Object
        (
            [question_id] => 1
            [answer_id] => 21
        )

    [1] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 33
        )

    [2] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 36
        )

    [3] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 38
        )

    [4] => stdClass Object
        (
            [question_id] => 6
            [answer_id] => 49
        )

)
Array
(
    [0] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 38
        )

    [1] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 37
        )

    [2] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 33
        )

    [3] => stdClass Object
        (
            [question_id] => 1
            [answer_id] => 22
        )

    [4] => stdClass Object
        (
            [question_id] => 6
            [answer_id] => 49
        )

)
</code>```

One array is the correct answers to the assessment and the other is what the user has entered.

How can I compare these two arrays to product another which shows the question_id along with a Boolean to whether they got it right or not?

I currently experiencing the following problems:

Some of the questions have multiple answers to them.

the question_id orders are not the same, the correct order is the second array which isn't always in a numeric order.

答:
Here is a solution that I hope works for you.

First, I have re-created your objects from above:

```<code>class AnswerObject {
    public $question_id=0;
    public $answer_id=0;

    function __construct($q,$a){
        $this->question_id=$q;
        $this->answer_id=$a;
    }
}

$obj_student_vals = array(new AnswerObject(1,21), new AnswerObject(3,33), new AnswerObject(3,36), new AnswerObject(3,38), new AnswerObject(6,49));
$obj_answer_key   = array(new AnswerObject(1,22), new AnswerObject(3,33), new AnswerObject(3,37), new AnswerObject(3,38), new AnswerObject(6,49));
</code>```

Now, the solution I am providing is as follows, and continues from the above code:

```<code>$flat_student_vals = array();
$flat_answer_key   = array();

// flatten student vals to multi-dimensional array
// e.g. array('3'=>array(33,36,38),'6'=>array(49),'1'=>array(21))
foreach($obj_student_vals as $obj){
    if(!array_key_exists($obj->question_id,$flat_student_vals))
        $flat_student_vals[$obj->question_id]=array();
    $flat_student_vals[$obj->question_id][]=$obj->answer_id;
}

// flatten answer key to multi-dimensional array
// e.g. array('1'=>array(22),'3'=>array(33,37,38),'6'=>array(49))
foreach($obj_answer_key as $obj){
    if(!array_key_exists($obj->question_id,$flat_answer_key))
        $flat_answer_key[$obj->question_id]=array();
    $flat_answer_key[$obj->question_id][]=$obj->answer_id;
}

// the results for this student
$student_results = array();

// when we compare arrays between student vals and answer key,
// the order doesn't matter.  the array operator `==` is only concerned
// with equality (same keys/value pairs), not identity (in same order and of same type)
foreach($flat_student_vals as $qid=>$vals){
    $student_results[$qid]=($vals == $flat_answer_key[$qid]);
}

print_r($student_results);
</code>```

The comments in my code are fairly self-explanatory.  The bottom-line is that in order to efficiently compare student responses to the answer key, you need to flatten both of your original arrays of objects down to simple, multi-dimensional arrays.

ContentLicense: CC BY-SA 3.0

Body:
I want to compare the following two arrays:

Array
(
    [0] => stdClass Object
        (
            [question_id] => 1
            [answer_id] => 21
        )

    [1] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 33
        )

    [2] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 36
        )

    [3] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 38
        )

    [4] => stdClass Object
        (
            [question_id] => 6
            [answer_id] => 49
        )

)
Array
(
    [0] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 38
        )

    [1] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 37
        )

    [2] => stdClass Object
        (
            [question_id] => 3
            [answer_id] => 33
        )

    [3] => stdClass Object
        (
            [question_id] => 1
            [answer_id] => 22
        )

    [4] => stdClass Object
        (
            [question_id] => 6
            [answer_id] => 49
        )

)

One array is the correct answers to the assessment and the other is what the user has entered.

How can I compare these two arrays to product another which shows the question_id along with a Boolean to whether they got it right or not?

I currently experiencing the following problems:

Some of the questions have multiple answers to them.

the question_id orders are not the same, the correct order is the second array which isn't always in a numeric order.

Body:
Here is a solution that I hope works for you.

First, I have re-created your objects from above:

class AnswerObject {
    public $question_id=0;
    public $answer_id=0;

    function __construct($q,$a){
        $this->question_id=$q;
        $this->answer_id=$a;
    }
}

$obj_student_vals = array(new AnswerObject(1,21), new AnswerObject(3,33), new AnswerObject(3,36), new AnswerObject(3,38), new AnswerObject(6,49));
$obj_answer_key   = array(new AnswerObject(1,22), new AnswerObject(3,33), new AnswerObject(3,37), new AnswerObject(3,38), new AnswerObject(6,49));

Now, the solution I am providing is as follows, and continues from the above code:

$flat_student_vals = array();
$flat_answer_key   = array();

// flatten student vals to multi-dimensional array
// e.g. array('3'=>array(33,36,38),'6'=>array(49),'1'=>array(21))
foreach($obj_student_vals as $obj){
    if(!array_key_exists($obj->question_id,$flat_student_vals))
        $flat_student_vals[$obj->question_id]=array();
    $flat_student_vals[$obj->question_id][]=$obj->answer_id;
}

// flatten answer key to multi-dimensional array
// e.g. array('1'=>array(22),'3'=>array(33,37,38),'6'=>array(49))
foreach($obj_answer_key as $obj){
    if(!array_key_exists($obj->question_id,$flat_answer_key))
        $flat_answer_key[$obj->question_id]=array();
    $flat_answer_key[$obj->question_id][]=$obj->answer_id;
}

// the results for this student
$student_results = array();

// when we compare arrays between student vals and answer key,
// the order doesn't matter.  the array operator `==` is only concerned
// with equality (same keys/value pairs), not identity (in same order and of same type)
foreach($flat_student_vals as $qid=>$vals){
    $student_results[$qid]=($vals == $flat_answer_key[$qid]);
}

print_r($student_results);

The comments in my code are fairly self-explanatory.  The bottom-line is that in order to efficiently compare student responses to the answer key, you need to flatten both of your original arrays of objects down to simple, multi-dimensional arrays.


问:
How does one fix the issue of not writable paths with conda?
Why do I see the following error when using conda (usually when installing packages or making new envs) and how do I fix it:

```<code>Verifying transaction: | WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt
</code>```

or

```<code>Preparing transaction: done
Verifying transaction: - WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt

done
Executing transaction: - WARNING conda.core.envs_manager:register_env(52): Unable to register environment. Path not writable or missing.
  environment location: /Users/brandomiranda/miniconda3/envs/myenv
  registry file: /Users/brandomiranda/.conda/environments.txt
done
</code>```

a detailed outline of what I did can be found on the following gitissue:

https://github.com/conda/conda/issues/7267

which really isn't anything too fancy except re-install conda from scratch and run the following command:

```<code>bash Miniconda3-latest-MacOSX-x86_64.sh
</code>```

and it installed this version of conda:

```<code>❯ conda -V
conda 4.7.12
</code>```

Example of command causing me the warnings:

```<code>conda create -n myenv python=3.6
</code>```

More errors when I install packages with conda:

```<code>Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: /Users/brandomiranda/miniconda3/envs/automl

  added / updated specs:
    - jupyterlab

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    jupyter_client-5.3.4       |           py37_0         131 KB  conda-forge
    ------------------------------------------------------------
                                           Total:         131 KB

The following NEW packages will be INSTALLED:

  appnope            conda-forge/osx-64::appnope-0.1.0-py37_1000
  attrs              conda-forge/noarch::attrs-19.3.0-py_0
  backcall           conda-forge/noarch::backcall-0.1.0-py_0
  bleach             conda-forge/noarch::bleach-3.1.0-py_0
  decorator          conda-forge/noarch::decorator-4.4.1-py_0
  defusedxml         conda-forge/noarch::defusedxml-0.6.0-py_0
  entrypoints        conda-forge/osx-64::entrypoints-0.3-py37_1000
  importlib_metadata conda-forge/osx-64::importlib_metadata-1.3.0-py37_0
  ipykernel          conda-forge/osx-64::ipykernel-5.1.3-py37h5ca1d4c_0
  ipython            conda-forge/osx-64::ipython-7.11.1-py37h5ca1d4c_0
  ipython_genutils   conda-forge/noarch::ipython_genutils-0.2.0-py_1
  jedi               conda-forge/osx-64::jedi-0.15.2-py37_0
  jinja2             conda-forge/noarch::jinja2-2.10.3-py_0
  json5              conda-forge/noarch::json5-0.8.5-py_0
  jsonschema         conda-forge/osx-64::jsonschema-3.2.0-py37_0
  jupyter_client     conda-forge/osx-64::jupyter_client-5.3.4-py37_0
  jupyter_core       conda-forge/osx-64::jupyter_core-4.6.1-py37_0
  jupyterlab         conda-forge/noarch::jupyterlab-1.2.4-py_0
  jupyterlab_server  conda-forge/noarch::jupyterlab_server-1.0.6-py_0
  libsodium          conda-forge/osx-64::libsodium-1.0.17-h01d97ff_0
  markupsafe         conda-forge/osx-64::markupsafe-1.1.1-py37h0b31af3_0
  mistune            conda-forge/osx-64::mistune-0.8.4-py37h0b31af3_1000
  more-itertools     conda-forge/noarch::more-itertools-8.0.2-py_0
  nbconvert          conda-forge/osx-64::nbconvert-5.6.1-py37_0
  nbformat           conda-forge/noarch::nbformat-5.0.3-py_0
  notebook           conda-forge/osx-64::notebook-6.0.1-py37_0
  pandoc             conda-forge/osx-64::pandoc-2.9.1.1-0
  pandocfilters      conda-forge/noarch::pandocfilters-1.4.2-py_1
  parso              conda-forge/noarch::parso-0.5.2-py_0
  pexpect            conda-forge/osx-64::pexpect-4.7.0-py37_0
  pickleshare        conda-forge/osx-64::pickleshare-0.7.5-py37_1000
  prometheus_client  conda-forge/noarch::prometheus_client-0.7.1-py_0
  prompt_toolkit     conda-forge/noarch::prompt_toolkit-3.0.2-py_0
  ptyprocess         conda-forge/noarch::ptyprocess-0.6.0-py_1001
  pygments           conda-forge/noarch::pygments-2.5.2-py_0
  pyrsistent         conda-forge/osx-64::pyrsistent-0.15.7-py37h0b31af3_0
  python-dateutil    conda-forge/noarch::python-dateutil-2.8.1-py_0
  pyzmq              pkgs/main/osx-64::pyzmq-18.1.0-py37h0a44026_0
  send2trash         conda-forge/noarch::send2trash-1.5.0-py_0
  terminado          conda-forge/osx-64::terminado-0.8.3-py37_0
  testpath           conda-forge/noarch::testpath-0.4.4-py_0
  tornado            conda-forge/osx-64::tornado-6.0.3-py37h0b31af3_0
  traitlets          conda-forge/osx-64::traitlets-4.3.3-py37_0
  wcwidth            conda-forge/noarch::wcwidth-0.1.8-py_0
  webencodings       conda-forge/noarch::webencodings-0.5.1-py_1
  zeromq             conda-forge/osx-64::zeromq-4.3.2-h6de7cb9_2
  zipp               conda-forge/noarch::zipp-0.6.0-py_0

The following packages will be UPDATED:

  ca-certificates    pkgs/main::ca-certificates-2019.11.27~ --> conda-forge::ca-certificates-2019.11.28-hecc5488_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi                                         pkgs/main --> conda-forge
  openssl              pkgs/main::openssl-1.1.1d-h1de35cc_3 --> conda-forge::openssl-1.1.1d-h0b31af3_0

Proceed ([y]/n)? y

Downloading and Extracting Packages
jupyter_client-5.3.4 | 131 KB    | ################################################################################################################################################################# | 100%
Preparing transaction: done
Verifying transaction: | WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt

done
Executing transaction: - WARNING conda.core.envs_manager:register_env(52): Unable to register environment. Path not writable or missing.
  environment location: /Users/brandomiranda/miniconda3/envs/automl
  registry file: /Users/brandomiranda/.conda/environments.txt
done
</code>```

command that I ran:

```<code>(automl) brandomiranda~/automl-meta-learning ❯ conda install -c conda-forge jupyterlab
</code>```

I tried changing the permission according to the suggested answers, BUT it seems it won't work without sudo. Is it really safe to do sudo here? why isn't it writable to the correct set of users already?

```<code>(automl) brandomiranda~/.conda ❯ if [ -w "/Users/brandomiranda/.conda" ]; then echo "WRITABLE"; else echo "NOT WRITABLE"; fi
NOT WRITABLE
(automl) brandomiranda~/.conda ❯ chmod 775 /Users/brandomiranda/.conda
chmod: Unable to change file mode on /Users/brandomiranda/.conda: Operation not permitted
</code>```

Update after running suggested answers

I've ran the chmod command in sudo. I checked the permissions of that file and I got the following:

```<code>(automl-meta-learning) brandomiranda~/automl-meta-learning/automl/automl ❯ ls -lha /Users/brandomiranda/.conda
total 8
drwxrwxr-x    3 root           staff    96B Jan  5 16:57 .
drwxr-xr-x+ 117 brandomiranda  staff   3.7K Jan 19 17:25 ..
-rw-r--r--    1 root           staff    32B Jan  5 16:57 environments.txt
</code>```

I checked this because I tried to install conda-build with conda install conda-build command but got the error towards the end:

```<code>Preparing transaction: done
Verifying transaction: \ WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt
                                                                                done
Executing transaction: \ WARNING conda.core.envs_manager:register_env(52): Unable to register environment. Path not writable or missing.
  environment location: /Users/brandomiranda/miniconda3/envs/automl-meta-learning
  registry file: /Users/brandomiranda/.conda/environments.txt                                                                                done
</code>```

which seemed weird and that when I notice the environment.txt didn't have the same permissions as the other file/directories. I am tempted to chmod that file too but all this business seems to be putting a bandage on the problem. I feel this shouldn't have happened in the first place so I will ask:

How do we fix this properly?

How is one suppose to install conda (in the new Catalina OS for Mac using zsh)?

Regardless of anything, what are the permissions of the /Users/brandomiranda/.conda conda folder suppose to be and should all folders/files have the same permissions?

for now I will run:

```<code>Preparing transaction: done
Verifying transaction: - WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt

done
Executing transaction: - WARNING conda.core.envs_manager:register_env(52): Unable to register environment. Path not writable or missing.
  environment location: /Users/brandomiranda/miniconda3/envs/myenv
  registry file: /Users/brandomiranda/.conda/environments.txt
done
</code>```0

although, it makes me uneasy that I am having to run sudo for conda related stuff. Anyone know how to do this without requiring sudo or is sudo supposed to be required?

As a side comment, I am glad I never tried installing anything from conda using sudo and only changed the permissions of a few folders/files. That seems much safer than allowing conda to run arbitrary code in sudo (instead here it can run its stuff to a specific location while NOT running in sudo, so I guess changing folder permissions isn't that bad?).

答:
As I said in the conda #7267 github issue, I had the same problem on Ubuntu because I installed Anaconda as a superuser:
sudo bash Anaconda3-2019.10-Linux-x86_64.sh

[solution Ubuntu] remove Anaconda and install it without the superuser privileges:

```<code>sudo rm -rf ~/anaconda3
bash Anaconda3-2019.10-Linux-x86_64.sh
</code>```

This fixed the problem.

Body:
Why do I see the following error when using conda (usually when installing packages or making new envs) and how do I fix it:

Verifying transaction: | WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt

or

Preparing transaction: done
Verifying transaction: - WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt

done
Executing transaction: - WARNING conda.core.envs_manager:register_env(52): Unable to register environment. Path not writable or missing.
  environment location: /Users/brandomiranda/miniconda3/envs/myenv
  registry file: /Users/brandomiranda/.conda/environments.txt
done

a detailed outline of what I did can be found on the following gitissue:

https://github.com/conda/conda/issues/7267

which really isn't anything too fancy except re-install conda from scratch and run the following command:

bash Miniconda3-latest-MacOSX-x86_64.sh

and it installed this version of conda:

❯ conda -V
conda 4.7.12

Example of command causing me the warnings:

conda create -n myenv python=3.6

More errors when I install packages with conda:

Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: /Users/brandomiranda/miniconda3/envs/automl

  added / updated specs:
    - jupyterlab

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    jupyter_client-5.3.4       |           py37_0         131 KB  conda-forge
    ------------------------------------------------------------
                                           Total:         131 KB

The following NEW packages will be INSTALLED:

  appnope            conda-forge/osx-64::appnope-0.1.0-py37_1000
  attrs              conda-forge/noarch::attrs-19.3.0-py_0
  backcall           conda-forge/noarch::backcall-0.1.0-py_0
  bleach             conda-forge/noarch::bleach-3.1.0-py_0
  decorator          conda-forge/noarch::decorator-4.4.1-py_0
  defusedxml         conda-forge/noarch::defusedxml-0.6.0-py_0
  entrypoints        conda-forge/osx-64::entrypoints-0.3-py37_1000
  importlib_metadata conda-forge/osx-64::importlib_metadata-1.3.0-py37_0
  ipykernel          conda-forge/osx-64::ipykernel-5.1.3-py37h5ca1d4c_0
  ipython            conda-forge/osx-64::ipython-7.11.1-py37h5ca1d4c_0
  ipython_genutils   conda-forge/noarch::ipython_genutils-0.2.0-py_1
  jedi               conda-forge/osx-64::jedi-0.15.2-py37_0
  jinja2             conda-forge/noarch::jinja2-2.10.3-py_0
  json5              conda-forge/noarch::json5-0.8.5-py_0
  jsonschema         conda-forge/osx-64::jsonschema-3.2.0-py37_0
  jupyter_client     conda-forge/osx-64::jupyter_client-5.3.4-py37_0
  jupyter_core       conda-forge/osx-64::jupyter_core-4.6.1-py37_0
  jupyterlab         conda-forge/noarch::jupyterlab-1.2.4-py_0
  jupyterlab_server  conda-forge/noarch::jupyterlab_server-1.0.6-py_0
  libsodium          conda-forge/osx-64::libsodium-1.0.17-h01d97ff_0
  markupsafe         conda-forge/osx-64::markupsafe-1.1.1-py37h0b31af3_0
  mistune            conda-forge/osx-64::mistune-0.8.4-py37h0b31af3_1000
  more-itertools     conda-forge/noarch::more-itertools-8.0.2-py_0
  nbconvert          conda-forge/osx-64::nbconvert-5.6.1-py37_0
  nbformat           conda-forge/noarch::nbformat-5.0.3-py_0
  notebook           conda-forge/osx-64::notebook-6.0.1-py37_0
  pandoc             conda-forge/osx-64::pandoc-2.9.1.1-0
  pandocfilters      conda-forge/noarch::pandocfilters-1.4.2-py_1
  parso              conda-forge/noarch::parso-0.5.2-py_0
  pexpect            conda-forge/osx-64::pexpect-4.7.0-py37_0
  pickleshare        conda-forge/osx-64::pickleshare-0.7.5-py37_1000
  prometheus_client  conda-forge/noarch::prometheus_client-0.7.1-py_0
  prompt_toolkit     conda-forge/noarch::prompt_toolkit-3.0.2-py_0
  ptyprocess         conda-forge/noarch::ptyprocess-0.6.0-py_1001
  pygments           conda-forge/noarch::pygments-2.5.2-py_0
  pyrsistent         conda-forge/osx-64::pyrsistent-0.15.7-py37h0b31af3_0
  python-dateutil    conda-forge/noarch::python-dateutil-2.8.1-py_0
  pyzmq              pkgs/main/osx-64::pyzmq-18.1.0-py37h0a44026_0
  send2trash         conda-forge/noarch::send2trash-1.5.0-py_0
  terminado          conda-forge/osx-64::terminado-0.8.3-py37_0
  testpath           conda-forge/noarch::testpath-0.4.4-py_0
  tornado            conda-forge/osx-64::tornado-6.0.3-py37h0b31af3_0
  traitlets          conda-forge/osx-64::traitlets-4.3.3-py37_0
  wcwidth            conda-forge/noarch::wcwidth-0.1.8-py_0
  webencodings       conda-forge/noarch::webencodings-0.5.1-py_1
  zeromq             conda-forge/osx-64::zeromq-4.3.2-h6de7cb9_2
  zipp               conda-forge/noarch::zipp-0.6.0-py_0

The following packages will be UPDATED:

  ca-certificates    pkgs/main::ca-certificates-2019.11.27~ --> conda-forge::ca-certificates-2019.11.28-hecc5488_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi                                         pkgs/main --> conda-forge
  openssl              pkgs/main::openssl-1.1.1d-h1de35cc_3 --> conda-forge::openssl-1.1.1d-h0b31af3_0

Proceed ([y]/n)? y

Downloading and Extracting Packages
jupyter_client-5.3.4 | 131 KB    | ################################################################################################################################################################# | 100%
Preparing transaction: done
Verifying transaction: | WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt

done
Executing transaction: - WARNING conda.core.envs_manager:register_env(52): Unable to register environment. Path not writable or missing.
  environment location: /Users/brandomiranda/miniconda3/envs/automl
  registry file: /Users/brandomiranda/.conda/environments.txt
done

command that I ran:

(automl) brandomiranda~/automl-meta-learning ❯ conda install -c conda-forge jupyterlab

I tried changing the permission according to the suggested answers, BUT it seems it won't work without sudo. Is it really safe to do sudo here? why isn't it writable to the correct set of users already?

(automl) brandomiranda~/.conda ❯ if [ -w "/Users/brandomiranda/.conda" ]; then echo "WRITABLE"; else echo "NOT WRITABLE"; fi
NOT WRITABLE
(automl) brandomiranda~/.conda ❯ chmod 775 /Users/brandomiranda/.conda
chmod: Unable to change file mode on /Users/brandomiranda/.conda: Operation not permitted

Update after running suggested answers

I've ran the chmod command in sudo. I checked the permissions of that file and I got the following:

(automl-meta-learning) brandomiranda~/automl-meta-learning/automl/automl ❯ ls -lha /Users/brandomiranda/.conda
total 8
drwxrwxr-x    3 root           staff    96B Jan  5 16:57 .
drwxr-xr-x+ 117 brandomiranda  staff   3.7K Jan 19 17:25 ..
-rw-r--r--    1 root           staff    32B Jan  5 16:57 environments.txt

I checked this because I tried to install conda-build with conda install conda-build command but got the error towards the end:

Preparing transaction: done
Verifying transaction: \ WARNING conda.core.path_actions:verify(963): Unable to create environments file. Path not writable.
  environment location: /Users/brandomiranda/.conda/environments.txt
                                                                                done
Executing transaction: \ WARNING conda.core.envs_manager:register_env(52): Unable to register environment. Path not writable or missing.
  environment location: /Users/brandomiranda/miniconda3/envs/automl-meta-learning
  registry file: /Users/brandomiranda/.conda/environments.txt                                                                                done

which seemed weird and that when I notice the environment.txt didn't have the same permissions as the other file/directories. I am tempted to chmod that file too but all this business seems to be putting a bandage on the problem. I feel this shouldn't have happened in the first place so I will ask:

How do we fix this properly?

How is one suppose to install conda (in the new Catalina OS for Mac using zsh)?

Regardless of anything, what are the permissions of the /Users/brandomiranda/.conda conda folder suppose to be and should all folders/files have the same permissions?

for now I will run:

sudo chmod 775 /Users/brandomiranda/.conda/environments.txt

although, it makes me uneasy that I am having to run sudo for conda related stuff. Anyone know how to do this without requiring sudo or is sudo supposed to be required?

As a side comment, I am glad I never tried installing anything from conda using sudo and only changed the permissions of a few folders/files. That seems much safer than allowing conda to run arbitrary code in sudo (instead here it can run its stuff to a specific location while NOT running in sudo, so I guess changing folder permissions isn't that bad?).

Body:
As I said in the conda #7267 github issue, I had the same problem on Ubuntu because I installed Anaconda as a superuser:
sudo bash Anaconda3-2019.10-Linux-x86_64.sh

[solution Ubuntu] remove Anaconda and install it without the superuser privileges:

sudo rm -rf ~/anaconda3
bash Anaconda3-2019.10-Linux-x86_64.sh

This fixed the problem.


问:
Fuzzy set working directory from bookmarked directories in vim
Sometimes I need to change the current working directory to a different location (e.g. to search in different project). This can for example be achived with lcd /path/to/dir.
However writing out paths is ofter too slow and I often find myself using the same locations.
Ideally I'd have a fuzzy finder such as fzf popping up with a preset list of bookmarked directories to choose from. Fuzzy searching would allow to quickly select and change the working dir (obviously without changing the current file it was called from).

Shortly, I'm looking for the equivalent of the fzf-marks tool for vim.

答:
My ctrlp conf, especially for cache_dir and let g:ctrlp_cmd = 'CtrlPMixed'

```<code>    " Open buffer here
    let g:ctrlp_switch_buffer = ''
    " Cache
    let g:ctrlp_cache_dir ='$h/.cache/ctrlp'
    " replace $home by ~ in cache
    let g:ctrlp_tilde_homedir = 1
    let g:ctrlp_mruf_max = 50000
    " Use ag <- grep
    " if executable('ag')
    "   let g:ctrl_user_command = 'ag %s -l --nocolor -g ""'
    " endif
    " Ignore
    let g:ctrlp_cutom_ignore = {
      \ 'dir': '\.git$,undo/',
      \ 'file': 'log'
    \ }
    if $os !=? 'termux'
      " E like edit and closer to ctrl + <c-p> used to paste
      let g:ctrlp_map = '<C-E>'
      vnoremap <C-E> :<C-u>CtrlPMixed<CR>
    else
      " Because move up gives c-e
      let g:ctrlp_map = ',e'
    endif
    " Keep cache
    let g:ctrlp_clear_cache_on_exit = 0
    " Mixed to search in MRU, FIles, Buffers
    let g:ctrlp_types = ['buf', 'mru', 'fil']
    let g:ctrlp_cmd = 'CtrlPMixed'
    " Faster listing <- vim.globpath
    if $os ==? 'windows'
      let g:ctrlp_user_command = 'dir %s /-n /b /s /a-d'
    else
      let g:ctrlp_user_command = 'find %s -type f'
    endif
</code>```

Body:
My ctrlp conf, especially for cache_dir and let g:ctrlp_cmd = 'CtrlPMixed'

    " Open buffer here
    let g:ctrlp_switch_buffer = ''
    " Cache
    let g:ctrlp_cache_dir ='$h/.cache/ctrlp'
    " replace $home by ~ in cache
    let g:ctrlp_tilde_homedir = 1
    let g:ctrlp_mruf_max = 50000
    " Use ag <- grep
    " if executable('ag')
    "   let g:ctrl_user_command = 'ag %s -l --nocolor -g ""'
    " endif
    " Ignore
    let g:ctrlp_cutom_ignore = {
      \ 'dir': '\.git$,undo/',
      \ 'file': 'log'
    \ }
    if $os !=? 'termux'
      " E like edit and closer to ctrl + <c-p> used to paste
      let g:ctrlp_map = '<C-E>'
      vnoremap <C-E> :<C-u>CtrlPMixed<CR>
    else
      " Because move up gives c-e
      let g:ctrlp_map = ',e'
    endif
    " Keep cache
    let g:ctrlp_clear_cache_on_exit = 0
    " Mixed to search in MRU, FIles, Buffers
    let g:ctrlp_types = ['buf', 'mru', 'fil']
    let g:ctrlp_cmd = 'CtrlPMixed'
    " Faster listing <- vim.globpath
    if $os ==? 'windows'
      let g:ctrlp_user_command = 'dir %s /-n /b /s /a-d'
    else
      let g:ctrlp_user_command = 'find %s -type f'
    endif


问:
CLion: Keyboard cmd to switch between header and implementation files like in xcode
In xcode I type cmd-shift up/down to switch between .h and .c files. How do I do that in CLion? Or more usefully, what would that action be called in the keymap? I don't find the keymap names terribly usefully named. None stand out for this purpose, including after the usual googling.</p>

答:
To switch between .h and .c files I use F10 key or the Navigate menu in CLion in Linux system:

F10 Header/Source


问:
How to use Contact Form 7 with a custom HTML and CSS in Wordpress?
I am pretty new to the WordPress community and if it was up to me, I would've never stepped into it (I'm just not into CMSs). It's just a situation I'm currently dealing with for about a week now, so please assume that I have no knowledge on the subject.

So, I am converting an HTML template into a WordPress theme and a time has come to pay attention to the contact form. It appears on the bottom of (almost) all pages (but is not in the footer section). The designer made it very well-structured and appropriate for the purpose and, due to my former experience, I was thinking of using a plugin for the job, instead of trying to program the contact form myself. But, I did a research and found out that it is a common problem most people face, that the design of the generated form is too rigid to be styled appropriately. As far as I read, the easiest plugin to work with design-wise is Contact Form 7, because it generates merely a barebone of a form. I've also found this tutorial that explains the process. However, if I follow the instructions mentioned in it, I am still left with a barebone "classless" form. Keep in mind, that I have added the classes using the Contact Form 7 syntax in the WordPress backend, where one must create/edit forms, but they (the classes) are not present. I tried to place raw HTML in the plugin's wp backend editor, but I get the same result.

How you achieve a custom HTML and CSS design in Contact Form 7, or any other Contact Form plugin you use, I'm not stuck with Contact Form 7?

Any help on Contact Form 7 is greatly appreciated as well as any other ideas on how to approach the general "Custom design contact forms in WordPress" issue!

答:
You can use custom div and classes to design the Contact form 7.
Here is the example code :

```<code><div class="row">
    <div class="col-md-6 form-group">[text* your-name class:form-control placeholder "Name"]</div>
    <div class="col-md-6 form-group">[email* your-email class:form-control placeholder "Email"]</div>
</div>
</code>```

Hint* : You have to use default shortcodes generated by contact form 7 and cover that with your custom div's.

I hope it helps..

Body:
You can use custom div and classes to design the Contact form 7.
Here is the example code :

<div class="row">
    <div class="col-md-6 form-group">[text* your-name class:form-control placeholder "Name"]</div>
    <div class="col-md-6 form-group">[email* your-email class:form-control placeholder "Email"]</div>
</div>

Hint* : You have to use default shortcodes generated by contact form 7 and cover that with your custom div's.

I hope it helps..


问:
Parsing field access flags in java
I have an assignment wherein I have to parse the field access flags of a java .class file.
The specification for a .class file can be found here: Class File Format (page 26 & 27 have the access flags and hex vals).

This is fine, I can do this no worries.
My issue is that there is a large number of combinations.

I know the public, private and protected are mutually exclusive, which reduces the combinations somewhat. Final and transient are also mutually exclusive. The rest however are not.

At the moment, I have a large switch statement to do the comparison. I read in the hex value of the access flag and then increment a counter, depending on if it is public, private or protected. This works fine, but it seems quite messy to just have every combination listed in a switch statement. i.e. public static, public final, public static final, etc.

I thought of doing modulo on the access flag and the appropriate hex value for public, private or protected, but public is 0x0001, so that won't work.

Does anyone else have any ideas as to how I could reduce the amount of cases in my switch statement?

答:
I'm not sure that's what you're looking for, but I would use if-cases with binary AND to check if a flag is set:</p>

```<code>if (access_flag & ACC_PUBLIC != 0)
{
    // class is public
}
if (access_flag & ACC_FINAL != 0)
{
    // class is final
}
....
</code>```

Title: Parsing field access flags in java

Body:
I'm not sure that's what you're looking for, but I would use if-cases with binary AND to check if a flag is set:

if (access_flag & ACC_PUBLIC != 0)
{
    // class is public
}
if (access_flag & ACC_FINAL != 0)
{
    // class is final
}
....


问:
How Can i remove duplicate from a list in Groovy
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

```<code>["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]
</code>```

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

```<code>// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.
</code>```

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?

答: If I understand your issue right, you need to leave only one item with the same number( the number is the first word (let's call it leading number))? Firstly you can sort your list. In result strings with the same "leading number" will be placed in adjacent cells. Then you can iterate through the list, extract "leading number" (e.g. by regexp) from i-1 and i elements, and, if they are the same, just remove element i from the list.</p>

Body:
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?


问:
Generate Google API access_token in Google Colab from Python
I need to generate an access_token with some specific scopes ['https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform'] from Python inside Google Colab.

By default, Google Colab provides a function inside colabtools to authenticate the user.

from google.colab import auth
auth.authenticate_user()
print('Authenticated')
```

<p>But the credential file generated contains a list of fixed scopes, not including the ones I need.</p>

<pre class="lang-py prettyprint-override"><code>import os
with open(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) as f:
  print(f.read())
</code>```

```<code>...
"scopes": [
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/appengine.admin",
    "https://www.googleapis.com/auth/accounts.reauth",
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/compute",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
...
</code>```

I have tried to generate a valid Credentials token with the google-auth library enter code hereusing the google.auth.Credentials class and also the google.oauth2.Credentials class. I can generate valid instances of the classes, but when I check the token is None.

Is there a way to generate valid access_token for Google API with custom scopes from Python?

Thanks!

答:
If you are using a VM with Google Colab, you can set the scopes for the service account on that vm with the following command (example):

```<code>gcloud compute instances set-service-account example-instance \
   --service-account my-sa-123@my-project-123.iam.gserviceaccount.com \
   --scopes compute-rw,storage-ro
</code>```

Then, when authenticating from within Python, the generated credentials will contain the correct scopes.

Body:
I need to generate an access_token with some specific scopes ['https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform'] from Python inside Google Colab.

By default, Google Colab provides a function inside colabtools to authenticate the user.

from google.colab import auth
auth.authenticate_user()
print('Authenticated')

But the credential file generated contains a list of fixed scopes, not including the ones I need.

import os
with open(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) as f:
  print(f.read())

...
"scopes": [
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/appengine.admin",
    "https://www.googleapis.com/auth/accounts.reauth",
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/compute",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
...

I have tried to generate a valid Credentials token with the google-auth library enter code hereusing the google.auth.Credentials class and also the google.oauth2.Credentials class. I can generate valid instances of the classes, but when I check the token is None.

Is there a way to generate valid access_token for Google API with custom scopes from Python?

Thanks!

Body:
If you are using a VM with Google Colab, you can set the scopes for the service account on that vm with the following command (example):

gcloud compute instances set-service-account example-instance \
   --service-account my-sa-123@my-project-123.iam.gserviceaccount.com \
   --scopes compute-rw,storage-ro

Then, when authenticating from within Python, the generated credentials will contain the correct scopes.