问:
mapbox-gl popup styling problem on tailwind and nuxt
I need help getting the style right for this popup on hover example which I'm porting to a Vue (Nuxt) app that uses Tailwind CSS. I think my problem is because I'm not correctly importing Mapbox's css. However, I'm not sure how to do it or if its an issue with Tailwind. I've tried importing in the following ways:

If I import this way:

```<code><style scoped>
@import "mapbox-gl/dist/mapbox-gl.css";
</style>
</code>```

The map shows like this:

The map doesn't show at all if I import like this:

```<code>import mapboxgl from "mapbox-gl";
import 'mapbox-gl/dist/mapbox-gl.css';
</code>```

Finally, without importing any Mapbox's CSS:

This is my map component:

```<code><template>
  <div>
      <div id="map" class="w-full h-full"></div>
  </div>
</template>

<script>
import mapboxgl from "mapbox-gl";
//import 'mapbox-gl/dist/mapbox-gl.css';
export default {
  data() {
    return {
      access_token:
        "pk.eyJ1Ijoic2FtcGFvbGl0byIsImEiOiJja3c1Z2g1anowZ3Y1MnRwOGtieWRkdjNkIn0.wkW06MEvxRmyL3jfZYBTWA",
    };
  },
  mounted() {
    this.createMap();
  },
  methods: {
    createMap() {
      mapboxgl.accessToken = this.access_token;
      const map = new mapboxgl.Map({
        container: "map",
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [-77.04, 38.907],
        zoom: 11.15
      });
      map.on("load", () => {
        map.addSource("places", {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: [
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Make it Mount Pleasant</strong><p>Make it Mount Pleasant is a handmade and vintage market and afternoon of live entertainment and kids activities. 12:00-6:00 p.m.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.038659, 38.931567],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Mad Men Season Five Finale Watch Party</strong><p>Head to Lounge 201 (201 Massachusetts Avenue NE) Sunday for a Mad Men Season Five Finale Watch Party, complete with 60s costume contest, Mad Men trivia, and retro food and drink. 8:00-11:00 p.m. $10 general admission, $20 admission and two hour open bar.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.003168, 38.894651],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Big Backyard Beach Bash and Wine Fest</strong><p>EatBar (2761 Washington Boulevard Arlington VA) is throwing a Big Backyard Beach Bash and Wine Fest on Saturday, serving up conch fritters, fish tacos and crab sliders, and Red Apron hot dogs. 12:00-3:00 p.m. $25.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.090372, 38.881189],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Ballston Arts & Crafts Market</strong><p>The Ballston Arts & Crafts Market sets up shop next to the Ballston metro this Saturday for the first of five dates this summer. Nearly 35 artists and crafters will be on hand selling their wares. 10:00-4:00 p.m.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.111561, 38.882342],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Seersucker Bike Ride and Social</strong><p>Feeling dandy? Get fancy, grab your bike, and take part in this year's Seersucker Social bike ride from Dandies and Quaintrelles. After the ride enjoy a lawn party at Hillwood with jazz, cocktails, paper hat-making, and more. 11:00-7:00 p.m.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.052477, 38.943951],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Capital Pride Parade</strong><p>The annual Capital Pride Parade makes its way through Dupont this Saturday. 4:30 p.m. Free.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.043444, 38.909664],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Muhsinah</strong><p>Jazz-influenced hip hop artist Muhsinah plays the Black Cat (1811 14th Street NW) tonight with Exit Clov and Gods’illa. 9:00 p.m. $12.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.031706, 38.914581],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>A Little Night Music</strong><p>The Arlington Players' production of Stephen Sondheim's <em>A Little Night Music</em> comes to the Kogod Cradle at The Mead Center for American Theater (1101 6th Street SW) this weekend and next. 8:00 p.m.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.020945, 38.878241],
                },
              },
              {
                type: "Feature",
                properties: {
                  description:
                    "<strong>Truckeroo</strong><p>Truckeroo brings dozens of food trucks, live music, and games to half and M Street SE (across from Navy Yard Metro Station) today from 11:00 a.m. to 11:00 p.m.</p>",
                },
                geometry: {
                  type: "Point",
                  coordinates: [-77.007481, 38.876516],
                },
              },
            ],
          },
        });
        // Add a layer showing the places.
        map.addLayer({
          id: "places",
          type: "circle",
          source: "places",
          paint: {
            "circle-color": "#4264fb",
            "circle-radius": 6,
            "circle-stroke-width": 2,
            "circle-stroke-color": "#ffffff",
          },
        });

        // Create a popup, but don't add it to the map yet.
        const popup = new mapboxgl.Popup({
          closeButton: false,
          closeOnClick: false,
        });

        map.on("mouseenter", "places", (e) => {
          // Change the cursor style as a UI indicator.
          map.getCanvas().style.cursor = "pointer";

          // Copy coordinates array.
          const coordinates = e.features[0].geometry.coordinates.slice();
          const description = e.features[0].properties.description;

          console.log(coordinates, description);

          // Ensure that if the map is zoomed out such that multiple
          // copies of the feature are visible, the popup appears
          // over the copy being pointed to.
          while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
            coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
          }

          // Populate the popup and set its coordinates
          // based on the feature found.
          popup.setLngLat(coordinates).setHTML(description).addTo(map);
        });

        map.on("mouseleave", "places", () => {
          map.getCanvas().style.cursor = "";
          popup.remove();
        });
      });
    },
  },
};
</script>

<style scoped>
/*
@import "mapbox-gl/dist/mapbox-gl.css";
*/
</style>
</code>```

答:
Solved by using:

```<code>import 'mapbox-gl/dist/mapbox-gl.css';
</code>```

and adding some height to my map container :)

```<code><div id="map" class="w-full h-96 mb-6"></div>
</code>```

Body:
I need help getting the style right for this popup on hover example which I'm porting to a Vue (Nuxt) app that uses Tailwind CSS. I think my problem is because I'm not correctly importing Mapbox's css. However, I'm not sure how to do it or if its an issue with Tailwind. I've tried importing in the following ways:

If I import this way:

The map shows like this:

The map doesn't show at all if I import like this:

import mapboxgl from "mapbox-gl";
import 'mapbox-gl/dist/mapbox-gl.css';

Finally, without importing any Mapbox's CSS:

This is my map component:

<template>

</template>

Body:
Solved by using:

import 'mapbox-gl/dist/mapbox-gl.css';

and adding some height to my map container :)

<div id="map" class="w-full h-96 mb-6"></div>


来源: stackexchange

问:
Host 'X' is not allowed to connect to this MySQL server
I wanna deploy MySQL+PHPMyAdmin. My docker-compose.yml:

```<code>version: "3"
services:
  db:
    image: mysql:5.7
    restart: always
    container_name: db
    volumes:
      - ./~mysql:/var/lib/mysql
      - ./mysql.cnf:/etc/mysql/conf.d/my.cnf
    environment:
      MYSQL_DATABASE: "dbtest"
      MYSQL_ROOT_PASSWORD: "123456"
      MYSQL_ROOT_HOST: "%"
    networks:
      - db
    command: --default-authentication-plugin=mysql_native_password
    healthcheck:
      test: "mysqladmin ping -h localhost"
      interval: 1s
      timeout: 1s
      retries: 60

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:4.7
    restart: always
    container_name: phpmyadmin
    ports:
      - 8080:80
    networks:
      - external-net
      - db
    environment:
      PMA_HOST: db
    depends_on:
      - db

networks:
  external-net:
    external:
      name: external-net
  db:
    driver: bridge
</code>```

After some time later I getting subject error. MYSQL_ROOT_HOST don't helped. When I trying to connect to mysql from db-container:

```<code>ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
</code>```

I really don't know what to do with this magic... Thx.

答:
You can pass an extra environment variable when starting the MySQL container MYSQL_ROOT_HOST= this will create a root user with permission to login from given IP address. In case where you want to allow login from any IP you can specify MYSQL_ROOT_HOST=%.

This will work only for a newly created containers.

When spinning new container:

```<code>docker run --name some-mysql -e MYSQL_ROOT_HOST=% -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest
</code>```

In compose file it would be

```<code>version: '2'
services:

  ### Mysql container
  mysql:
    image: mysql:latest
    ports:
      - "3306:3306"
    volumes:
      - /var/lib/mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: test_db
      MYSQL_USER: test
      MYSQL_PASSWORD: test_pass
      MYSQL_ROOT_HOST: '%'  # needs to be enclosed with quotes
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wanna deploy MySQL+PHPMyAdmin. My docker-compose.yml:

version: "3"
services:
  db:
    image: mysql:5.7
    restart: always
    container_name: db
    volumes:
      - ./~mysql:/var/lib/mysql
      - ./mysql.cnf:/etc/mysql/conf.d/my.cnf
    environment:
      MYSQL_DATABASE: "dbtest"
      MYSQL_ROOT_PASSWORD: "123456"
      MYSQL_ROOT_HOST: "%"
    networks:
      - db
    command: --default-authentication-plugin=mysql_native_password
    healthcheck:
      test: "mysqladmin ping -h localhost"
      interval: 1s
      timeout: 1s
      retries: 60

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:4.7
    restart: always
    container_name: phpmyadmin
    ports:
      - 8080:80
    networks:
      - external-net
      - db
    environment:
      PMA_HOST: db
    depends_on:
      - db

networks:
  external-net:
    external:
      name: external-net
  db:
    driver: bridge

After some time later I getting subject error. MYSQL_ROOT_HOST don't helped. When I trying to connect to mysql from db-container:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I really don't know what to do with this magic... Thx.

Body:
You can pass an extra environment variable when starting the MySQL container MYSQL_ROOT_HOST= this will create a root user with permission to login from given IP address. In case where you want to allow login from any IP you can specify MYSQL_ROOT_HOST=%.

This will work only for a newly created containers.

When spinning new container:

docker run --name some-mysql -e MYSQL_ROOT_HOST=% -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest

In compose file it would be

version: '2'
services:

  ### Mysql container
  mysql:
    image: mysql:latest
    ports:
      - "3306:3306"
    volumes:
      - /var/lib/mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: test_db
      MYSQL_USER: test
      MYSQL_PASSWORD: test_pass
      MYSQL_ROOT_HOST: '%'  # needs to be enclosed with quotes


问:
Printing a multidimensional array in C
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

```<code>#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}
</code>```

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

答:
You are trying to access the value in the wrong way, The two-dimensional array is saved as a continuous block in the memory. So, if we increment the value of ptr by 1 we will move to the next block in the allocated memory.</p>
```<code>int arr[2][3] = {{1,2,3},{4,5,6}};
int *ptr = arr;

int i,j;
for (i = 0; i < 6; i++) {
    printf("%d ", *(ptr + i));
}
return 0;
</code>```

Title: Printing a multidimensional array in C

Body:
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

Body:
You are trying to access the value in the wrong way, The two-dimensional array is saved as a continuous block in the memory. So, if we increment the value of ptr by 1 we will move to the next block in the allocated memory.

int arr[2][3] = {{1,2,3},{4,5,6}};
int *ptr = arr;

int i,j;
for (i = 0; i < 6; i++) {
    printf("%d ", *(ptr + i));
}
return 0;


问:
What has a larger big-O: O(m^2n) or O(n^2)
Given that m <= n, is O(n^2) in O(m^2n)? I know that O(mn) is in O(n^2) but I do not know what happens when you add the extra term</p>

答:
Given that m <= n, is O(n^2) in O((m^2)n)

No, even if m grows with n.

Let m = sqrt(sqrt(n)).

O(n^2) is not contained in O((m^2)n) = O(((sqrt(sqrt(n)))^2)n) = O(sqrt(n)n)


问:
How to set C++ version with Bazel in a cross platform way?
I would like my Bazel project to use c++17. There is a similar question (How to set C++ standard version when build with Bazel?) but the accepted answer does not port to MSCV.

MSCV needs --cxxopt='/std:c++17' while gcc needs --cxxopt='--std=c++17'.

Does anyone have a minimal example configuration that builds on the most popular Windows and Linux compilers (gcc, MSCV, clang) that sets the version to c++17? I am having a real hard time understanding the toolchain documentation.

The following did not work.

```<code># .bazelrc

build --cxxopt=select({
    "@bazel_tools//src/conditions:windows": "/std:c++17",
    "//conditions:default": "--std=c++17",
})
</code>```

答:
In each and every cc_binary target of your project, include the following.

```<code># BUILD

COPTS = select({
    "@bazel_tools//src/conditions:windows": ["/std:c++17"],
    "//conditions:default": ["--std=c++17"],
})

...

cc_binary(
    name = "example",
    srcs = ["example.cc"],
    ...
    copts=COPTS
)

</code>```

Of course this is very tedious and will break if someone tries to, say, use gcc on Windows. I'd be very happy to accept a better answer.

Body:
I would like my Bazel project to use c++17. There is a similar question (How to set C++ standard version when build with Bazel?) but the accepted answer does not port to MSCV.

MSCV needs --cxxopt='/std:c++17' while gcc needs --cxxopt='--std=c++17'.

Does anyone have a minimal example configuration that builds on the most popular Windows and Linux compilers (gcc, MSCV, clang) that sets the version to c++17? I am having a real hard time understanding the toolchain documentation.

The following did not work.

# .bazelrc

build --cxxopt=select({
    "@bazel_tools//src/conditions:windows": "/std:c++17",
    "//conditions:default": "--std=c++17",
})

Body:
In each and every cc_binary target of your project, include the following.

# BUILD

COPTS = select({
    "@bazel_tools//src/conditions:windows": ["/std:c++17"],
    "//conditions:default": ["--std=c++17"],
})

...

cc_binary(
    name = "example",
    srcs = ["example.cc"],
    ...
    copts=COPTS
)

Of course this is very tedious and will break if someone tries to, say, use gcc on Windows. I'd be very happy to accept a better answer.


问:
How to verify if the IP is replaced with proxy server(selenium, python)
How can I verify if the actual IP address is replaced by the proxy server. I attached the code. I made the program with selenium and python.

# selenium imports
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import random

PROXY ="88.157.149.250:8080";

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
# //a[starts-with(@href, 'https://www.amazon.com/')]/@href
LINKS_XPATH = '//*[contains(@id,"result")]/div/div[3]/div[1]/a'
browser = webdriver.Chrome(chrome_options=chrome_options)
browser.get(
    'https://www.amazon.com/s/ref=lp_11444071011_nr_p_8_1/132-3636705-4291947?rh=n%3A3375251%2Cn%3A%213375301%2Cn%3A10971181011%2Cn%3A11444071011%2Cp_8%3A2229059011')
links = browser.find_elements_by_xpath(LINKS_XPATH)
for link in links:
    href = link.get_attribute('href')
    print(href)```

答:
Just visit a page that shows it like the one Loïc showed. Then after that, you go on to visit Amazon, or whatever website you want, knowing you are using the correct IP address.

from selenium.webdriver.common.by import By

driver.get('https://api.ipify.org/')
ip_address = navigator.driver.find_element(By.TAG_NAME, "body").text
print(ip_address)
```

ContentLicense: CC BY-SA 3.0


问:
Can't update JLabels of minutes and hours for my chronometer in java.swing
I'm trying to make a stopwatch with java.swing and a stopwatch
I have already tried the swing.Timer and TimerTask.
Could you help me?

This is the stopwatch.java class

```<code>    public class Cronometro {
    private int secondi;
    private int minuti;
    private int ore;
    private boolean state=true;

    public Cronometro(){

    }

    public void crono(JLabel s, JLabel m, JLabel h, ActionEvent evt){
        state=true;

        Thread t = new Thread(){
            public void run(){
                for(;;){
                    if(state==true){
                       try{
                           sleep(10);
                           secondi++;
                           if(secondi>60){
                               secondi=0;
                               minuti++;

                           }
                           if(minuti>60){
                               secondi=0;
                               minuti=0;
                               ore++;
                           }
                           s.setText(" :"+secondi);
                           m.setText(" : "+minuti);
                           h.setText(""+ore);
                       } catch(Exception e){

                       }
                    }
                    else{
                        break;
                    }
                }
            }
        };

        t.start();
    }

    public void setState(boolean state){
        this.state=state;
    }

}
</code>```

The gui/main.java was generated almost all by netbeans

答:
This is how you can use a Swing Timer to run update every second:

```<code>class Cronometro {
    private int secondi;
    private int minuti;
    private int ore;
    private boolean state=true;
    private Timer timer;

    private final JLabel s, m,  h;

    public Cronometro(JLabel s, JLabel m, JLabel h) {
        this.s = s;
        this.m = m;
        this.h = h;
    }

    public void crono(JLabel s, JLabel m, JLabel h){
        state=true;
        if(timer != null) {
            timer.stop();
        }

        timer = new Timer(1000, e->update());
        timer.start();
    }

    public void update(){

        if(! state) return;
        secondi++;
        if(secondi>60){
            secondi=0;
            minuti++;
        }

        if(minuti>60){
            secondi=0;
            minuti=0;
            ore++;
        }
        s.setText(" :"+secondi);
        m.setText(" : "+minuti);
        h.setText(""+ore);
    }

    public void setState(boolean state){
        this.state=state;
    }
}
</code>```

Side note: to improve the application structure introduce a model class that encapsulates the needed information (seconds, minutes, hours). Share this model between Cronometro and the GUI.

Body:
I'm trying to make a stopwatch with java.swing and a stopwatch
I have already tried the swing.Timer and TimerTask.
Could you help me?

This is the stopwatch.java class

    public class Cronometro {
    private int secondi;
    private int minuti;
    private int ore;
    private boolean state=true;

    public Cronometro(){

    }

    public void crono(JLabel s, JLabel m, JLabel h, ActionEvent evt){
        state=true;

        Thread t = new Thread(){
            public void run(){
                for(;;){
                    if(state==true){
                       try{
                           sleep(10);
                           secondi++;
                           if(secondi>60){
                               secondi=0;
                               minuti++;

                           }
                           if(minuti>60){
                               secondi=0;
                               minuti=0;
                               ore++;
                           }
                           s.setText(" :"+secondi);
                           m.setText(" : "+minuti);
                           h.setText(""+ore);
                       } catch(Exception e){

                       }
                    }
                    else{
                        break;
                    }
                }
            }
        };

        t.start();
    }

    public void setState(boolean state){
        this.state=state;
    }

}

The gui/main.java was generated almost all by netbeans

Body:
This is how you can use a Swing Timer to run update every second:

class Cronometro {
    private int secondi;
    private int minuti;
    private int ore;
    private boolean state=true;
    private Timer timer;

    private final JLabel s, m,  h;

    public Cronometro(JLabel s, JLabel m, JLabel h) {
        this.s = s;
        this.m = m;
        this.h = h;
    }

    public void crono(JLabel s, JLabel m, JLabel h){
        state=true;
        if(timer != null) {
            timer.stop();
        }

        timer = new Timer(1000, e->update());
        timer.start();
    }

    public void update(){

        if(! state) return;
        secondi++;
        if(secondi>60){
            secondi=0;
            minuti++;
        }

        if(minuti>60){
            secondi=0;
            minuti=0;
            ore++;
        }
        s.setText(" :"+secondi);
        m.setText(" : "+minuti);
        h.setText(""+ore);
    }

    public void setState(boolean state){
        this.state=state;
    }
}

Side note: to improve the application structure introduce a model class that encapsulates the needed information (seconds, minutes, hours). Share this model between Cronometro and the GUI.


问:
Is it possible to override @DisabledIfEnvironmentVariable in jUnit 5?
I have a class of jUnit 5 tests that is not allowed to run in the main pipeline (for multiple reasons). In order to disabled those tests in the pipeline but work on a developer machine I introduced @DisabledIfEnvironmentVariable for the test class (and it works great):

```<code>@DisabledIfEnvironmentVariable(named = "USER", matches = "(.*jenkins.*|.*tomcat.*)")
@SpringBootTest(classes = {BigApplication.class}, webEnvironment = RANDOM_PORT)
class LongRunningApplicationTest { ... }
</code>```

How can I override @DisabledIfEnvironmentVariable if I want to run the test class on an occasion?

I tried adding @EnabledIfEnvironmentVariable hoping that it will override @DisabledIfEnvironmentVariable annotation, therefore providing me with a convenient way to run the test in the pipeline on occasion:

```<code>@EnabledIfEnvironmentVariable(named = "applicationTest", matches = "true")
@DisabledIfEnvironmentVariable(named = "USER", matches = "(.*jenkins.*|.*tomcat.*)")
@SpringBootTest(classes = {BigApplication.class}, webEnvironment = RANDOM_PORT)
class LongRunningApplicationTest { ... }
</code>```

However the above approach doesn't work. Is there a way to override @DisabledIf... ?

答:
One solution is to introduce your own conditions using following annotations:
@EnabledIf or @DisabledIf.

```<code>@EnabledIf("EnabledIfAnnotationUtils#shouldRun")
class ApplicationTest {

    @Test
    void renameMe() {
        assertThat(false).isTrue();
    }
}
</code>```

Where EnabledIfAnnotationUtils - is external class (in case you have multiple tests under same condition) and #shouldRun - name of static method. Example:

```<code>public class EnabledIfAnnotationUtils {

    static boolean shouldRun() {
        boolean override = getPropertySafely("run-long-tests").equalsIgnoreCase("true");
        if(override) return true;

        String user = getEnvSafely("USER");
        boolean isOnJenkins = user.toLowerCase().contains("jenkins") || user.toLowerCase().contains("tomcat");

        return !isOnJenkins;
    }

    private static String getPropertySafely(String name) {
        return "" + System.getProperty(name);
    }

    private static String getEnvSafely(String name) {
        return "" + System.getenv(name);
    }
}
</code>```

Now tests will NOT run on Jenkins unless override parameter passed, example:

```<code>mvn test -Drun-long-tests=true
</code>```

Body:
I have a class of jUnit 5 tests that is not allowed to run in the main pipeline (for multiple reasons). In order to disabled those tests in the pipeline but work on a developer machine I introduced @DisabledIfEnvironmentVariable for the test class (and it works great):

@DisabledIfEnvironmentVariable(named = "USER", matches = "(.*jenkins.*|.*tomcat.*)")
@SpringBootTest(classes = {BigApplication.class}, webEnvironment = RANDOM_PORT)
class LongRunningApplicationTest { ... }

How can I override @DisabledIfEnvironmentVariable if I want to run the test class on an occasion?

I tried adding @EnabledIfEnvironmentVariable hoping that it will override @DisabledIfEnvironmentVariable annotation, therefore providing me with a convenient way to run the test in the pipeline on occasion:

@EnabledIfEnvironmentVariable(named = "applicationTest", matches = "true")
@DisabledIfEnvironmentVariable(named = "USER", matches = "(.*jenkins.*|.*tomcat.*)")
@SpringBootTest(classes = {BigApplication.class}, webEnvironment = RANDOM_PORT)
class LongRunningApplicationTest { ... }

However the above approach doesn't work. Is there a way to override @DisabledIf... ?

Body:
One solution is to introduce your own conditions using following annotations:
@EnabledIf or @DisabledIf.

@EnabledIf("EnabledIfAnnotationUtils#shouldRun")
class ApplicationTest {

    @Test
    void renameMe() {
        assertThat(false).isTrue();
    }
}

Where EnabledIfAnnotationUtils - is external class (in case you have multiple tests under same condition) and #shouldRun - name of static method. Example:

public class EnabledIfAnnotationUtils {

    static boolean shouldRun() {
        boolean override = getPropertySafely("run-long-tests").equalsIgnoreCase("true");
        if(override) return true;

        String user = getEnvSafely("USER");
        boolean isOnJenkins = user.toLowerCase().contains("jenkins") || user.toLowerCase().contains("tomcat");

        return !isOnJenkins;
    }

    private static String getPropertySafely(String name) {
        return "" + System.getProperty(name);
    }

    private static String getEnvSafely(String name) {
        return "" + System.getenv(name);
    }
}

Now tests will NOT run on Jenkins unless override parameter passed, example:

mvn test -Drun-long-tests=true


问:
Issue with multiple custom events firing, second event not working in Vue
I am emitting two different custom events from child, and for some reason the second event doesn't work.

I have checked on the Vue console and both events are being fired, however, nothing happens for the second event. When I comment out the first one, the second works correctly, as if the first one was blocking the second one.

```<code><child-component
 @upload="handleUpload"
 @uploading="mediaUploading"
/>

 methods: {
    handleUpload(response) { //doesn't work
      this.mediaLoading = false;
      console.log(this.mediaLoading);
    },

    mediaUploading() { //works
      this.mediaLoading = true;
    },
}
</code>```

In child component

```<code> this.$emit('uploading');
  try {
    data = await this.$api.get('/photo');
  } catch (e) {
    console.log(e)
  }
 this.$emit('upload', data);

</code>```

答:
i have pasted the code on my machine and both are working fine

parent

```<code>  <template>
  <child-component @upload="handleUpload" @uploading="mediaUploading" />
</template>

<script>
import childComponent from "./page4child.vue";
export default {
  components: {
    childComponent,
  },
  data() {
    return {
      mediaLoading: true,
    };
  },
  methods: {
    handleUpload(response) {
      //works
      this.mediaLoading = false;
      console.log(this.mediaLoading);
    },

    mediaUploading() {
      //works
      this.mediaLoading = true;
      console.log(this.mediaLoading);
    },
  },
};
</script>
</code>```

Child

```<code><template>
  <div>
    <button @click="trigger('item')">run</button>
  </div>
</template>

<script>
export default {
  methods: {
    async trigger(uploadedItem) {
      this.$emit("uploading");
      await new Promise((res) => {
        console.log("duck");
        res();
      });
      this.$emit("upload", uploadedItem);
    },
  },
};
</script>
</code>```

Body:
I am emitting two different custom events from child, and for some reason the second event doesn't work.

I have checked on the Vue console and both events are being fired, however, nothing happens for the second event. When I comment out the first one, the second works correctly, as if the first one was blocking the second one.

<child-component
 @upload="handleUpload"
 @uploading="mediaUploading"
/>

 methods: {
    handleUpload(response) { //doesn't work
      this.mediaLoading = false;
      console.log(this.mediaLoading);
    },

    mediaUploading() { //works
      this.mediaLoading = true;
    },
}

In child component

 this.$emit('uploading');
  try {
    data = await this.$api.get('/photo');
  } catch (e) {
    console.log(e)
  }
 this.$emit('upload', data);

Body:
i have pasted the code on my machine and both are working fine

parent

  <template>
  <child-component @upload="handleUpload" @uploading="mediaUploading" />
</template>

<script>
import childComponent from "./page4child.vue";
export default {
  components: {
    childComponent,
  },
  data() {
    return {
      mediaLoading: true,
    };
  },
  methods: {
    handleUpload(response) {
      //works
      this.mediaLoading = false;
      console.log(this.mediaLoading);
    },

    mediaUploading() {
      //works
      this.mediaLoading = true;
      console.log(this.mediaLoading);
    },
  },
};
</script>

Child

<template>
  <div>
    <button @click="trigger('item')">run</button>
  </div>
</template>

<script>
export default {
  methods: {
    async trigger(uploadedItem) {
      this.$emit("uploading");
      await new Promise((res) => {
        console.log("duck");
        res();
      });
      this.$emit("upload", uploadedItem);
    },
  },
};
</script>


问:
Qt project files and PREFIX variable
I included

PREFIX = /usr/local
```

<p>inside my project file and then I run</p>

<pre class="lang-cpp prettyprint-override"><code>qmake myproject.pro
</code>```

The makefile doesn't say anything about PREFIX though so I assume that i'm doing something wrong. Any ideas?

答:
PREFIX doesn't mean anything in qmake files. The target for files is done via the target parameter. So if you want to make PREFIX determine the base location, such as /usr/local, you can do do something like this:

```<code>isEmpty(PREFIX) {
 PREFIX = /usr/local
}
TARGET = myapp
TARGET.path = $$PREFIX/
</code>```

The isEmpty(PREFIX) will allow it to be changed during the command line call to qmake, e.g.

```<code>qmake PREFIX=/opt
</code>```

Title: Qt project files and PREFIX variable

Body:
I included

PREFIX = /usr/local

inside my project file and then I run

qmake myproject.pro

The makefile doesn't say anything about PREFIX though so I assume that i'm doing something wrong. Any ideas?

Body:
PREFIX doesn't mean anything in qmake files. The target for files is done via the target parameter. So if you want to make PREFIX determine the base location, such as /usr/local, you can do do something like this:

isEmpty(PREFIX) {
 PREFIX = /usr/local
}
TARGET = myapp
TARGET.path = $$PREFIX/

The isEmpty(PREFIX) will allow it to be changed during the command line call to qmake, e.g.

qmake PREFIX=/opt


问:
Remove stop words from sentences and pad sentences from a list of lists in the data frame
Is there an easy way to remove certain (stop) words from sentences in a list of lists in a dataframe column and (right)-pad them if they have a length less than the maximum length?

Example:

```<code>import pandas as pd

stopwords = ['the', 'a', 'an']
df = pd.DataFrame(data={'sentence': [[["the", "deer", 'was', 'a', 'tasty', 'meal'], ["the", "girl", 'walks'], ["thanks", "for", "all", "the", "gifts"]]]})
</code>```
```<code>|    | sentence                                                                                |
|---:|:-------------------------------------------------------------------------------------------------------------------|
|  0 | [['the', 'deer', 'was', 'a', 'tasty', 'meal'], ['the', 'girl', 'walks'], ['thanks', 'for', 'all', 'the', 'gifts']] |
</code>```

Expected result:

|    | sentence                            |
|---:|:------------------------------------|
|  0 | ['deer', 'was', 'tasty', 'meal']    |
|  1 | ['girl', 'walks', '<pad>', '<pad>'] |
|  2 | ['thanks', 'for', 'all', 'gifts']   |
```

答:
Try this:

```<code>x = df['sentence'].explode().reset_index(drop=True).explode().pipe(lambda x: x[~x.isin(stopwords)])
MAX = x.groupby(level=0).agg(len).max()
new_df = x.groupby(level=0).apply(lambda x: x.reset_index(drop=True).reindex(np.arange(MAX)).fillna('<pad>')).groupby(level=0).agg(list).to_frame()
</code>```

Output:

```<code>>>> new_df
                      sentence
0     [deer, was, tasty, meal]
1  [girl, walks, <pad>, <pad>]
2    [thanks, for, all, gifts]
</code>```

It uses explode twice to get the sub arrays all flattened, and then via pipe filters out the stop words. Then, we get the length of the longest group, and reindex each group to be as long as that. Note the fill value is <pad>, but you can change it to whatever you'd like, or even get rid of the fillna call altogether.

Body:
Is there an easy way to remove certain (stop) words from sentences in a list of lists in a dataframe column and (right)-pad them if they have a length less than the maximum length?

Example:

import pandas as pd

stopwords = ['the', 'a', 'an']
df = pd.DataFrame(data={'sentence': [[["the", "deer", 'was', 'a', 'tasty', 'meal'], ["the", "girl", 'walks'], ["thanks", "for", "all", "the", "gifts"]]]})

|    | sentence                                                                                |
|---:|:-------------------------------------------------------------------------------------------------------------------|
|  0 | [['the', 'deer', 'was', 'a', 'tasty', 'meal'], ['the', 'girl', 'walks'], ['thanks', 'for', 'all', 'the', 'gifts']] |

Expected result:

|    | sentence                            |
|---:|:------------------------------------|
|  0 | ['deer', 'was', 'tasty', 'meal']    |
|  1 | ['girl', 'walks', '<pad>', '<pad>'] |
|  2 | ['thanks', 'for', 'all', 'gifts']   |

Body:
Try this:

x = df['sentence'].explode().reset_index(drop=True).explode().pipe(lambda x: x[~x.isin(stopwords)])
MAX = x.groupby(level=0).agg(len).max()
new_df = x.groupby(level=0).apply(lambda x: x.reset_index(drop=True).reindex(np.arange(MAX)).fillna('<pad>')).groupby(level=0).agg(list).to_frame()

Output:

>>> new_df
                      sentence
0     [deer, was, tasty, meal]
1  [girl, walks, <pad>, <pad>]
2    [thanks, for, all, gifts]

It uses explode twice to get the sub arrays all flattened, and then via pipe filters out the stop words. Then, we get the length of the longest group, and reindex each group to be as long as that. Note the fill value is <pad>, but you can change it to whatever you'd like, or even get rid of the fillna call altogether.


问:
SQL Server Service not available in service list after installation of SQL Server Management Studio
I have Windows 7 Home edition SP1 installed on my system, and downloaded SQL Server 2008 R2 Management Studio and got it installed. But when I try to connect via .\SQLEXPRESS, SSMS shows error

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1&LinkId=20476.

I go back to check the local services there I don't find any SQL Server service running.

What I have to do for this? DO I need to install any SQL service on my system? or how I should proceed?

答:
Updated link to install Sql server Database in local machine. Once it is installed you can get access to local database and you can see SQL Server windows services instance up and running in your services list window.

https://www.microsoft.com/en-us/sql-server/sql-server-downloads


问:
Test DB schema different than production DB (doctrine:schema:create)
I am setting up a test environment for unit tests, following Symfony's Test-Guide.
However each time I deploy the test-DB the final tables look slightly different than the originals from the production db.

That means

some columns appear on another position in table

some indexes/keys are missing or added

some indexes/keys copied from prod-db are unique in test-db but the originals are not

I use migration files to build up the production-db.
Maybe I am doing the test-db setup in wrong order regarding the production db setup?

This is what I am doing:

Step
Action
Command

1
Remove all databases
mysql -e "DROP DATABASE prod_db" //...

2
Add production db
mysql -e "CREATE DATABASE prod_db"

3
Execute migrations for production db
php bin/console doctrine:migrations:migrate

4
Add test-db
php bin/console --env=test doctrine:database:create

5
Create test-db schema
php bin/console --env=test doctrine:schema:create

Q: What is the cause of the differences?

答:
The simplest answer is that the schemas do, in fact, differ: While doctrine:schema:create generates the required DDL on the fly against your entities, the doctrine:migrations:migrate executes a series of SQL sentences that you (probably with the help of the make:migration command) previously defined.

It's all to easy to do a small change to your entities and forget to create the corresponding migration.

To check what's different in production (i.e. what you forgot to add to the migrations) you can either:

Create a new migration with bin/console make:migration. This will create a new migration with the missing sentences.

Just inspect the changes with bin/console doctrine:schema:update --dump-sql.

TL;DR
To just make your test database match the production one, use the following command in place of your 5th command:

```<code>bin/console doctrine:migrations:migrate -e test
</code>```

This will load the same SQL, making them match.

Bonus: you can also truncate your databases using symfony commands: in the event that you change your database engine, doctrine will take care of it (add the -e flag as needed):

```<code>bin/console doctrine:database:drop --force && bin/console doctrine:database:create
</code>```

Body:
The simplest answer is that the schemas do, in fact, differ: While doctrine:schema:create generates the required DDL on the fly against your entities, the doctrine:migrations:migrate executes a series of SQL sentences that you (probably with the help of the make:migration command) previously defined.

It's all to easy to do a small change to your entities and forget to create the corresponding migration.

To check what's different in production (i.e. what you forgot to add to the migrations) you can either:

Create a new migration with bin/console make:migration. This will create a new migration with the missing sentences.

Just inspect the changes with bin/console doctrine:schema:update --dump-sql.

TL;DR
To just make your test database match the production one, use the following command in place of your 5th command:

bin/console doctrine:migrations:migrate -e test

This will load the same SQL, making them match.

Bonus: you can also truncate your databases using symfony commands: in the event that you change your database engine, doctrine will take care of it (add the -e flag as needed):

bin/console doctrine:database:drop --force && bin/console doctrine:database:create


答:
Here is a way using reshaping:

```<code>df2 = (df.explode('sentence')
         .assign(group=lambda d: d.groupby(d.index).cumcount())
         .explode('sentence')
         .loc[lambda d: ~d['sentence'].isin(stopwords)]         # filter words
         .rename_axis('index')
         .assign(idx=lambda d: d.groupby(['index', 'group']).cumcount())
         .set_index(['group', 'idx'], append=True)
         .unstack('group')        # unstack/stack
         .fillna('<pad>')         # to pad
         .stack('group')          # missing words
         .groupby(level=[0, 'group']).agg(list)
         .reset_index('group', drop=True)
      )
</code>```

output:

```<code>                      sentence
0     [deer, was, tasty, meal]
0  [girl, walks, <pad>, <pad>]
0    [thanks, for, all, gifts]
</code>```

NB. this solution should also work on multiple input lines:

```<code>df = pd.concat([df]*3, ignore_index=True)

#                                             sentence
# 0  [[the, deer, was, a, tasty, meal], [the, girl,...
# 1  [[the, deer, was, a, tasty, meal], [the, girl,...
# 2  [[the, deer, was, a, tasty, meal], [the, girl,...
</code>```

output:

```<code>                          sentence
index
0         [deer, was, tasty, meal]
0      [girl, walks, <pad>, <pad>]
0        [thanks, for, all, gifts]
1         [deer, was, tasty, meal]
1      [girl, walks, <pad>, <pad>]
1        [thanks, for, all, gifts]
2         [deer, was, tasty, meal]
2      [girl, walks, <pad>, <pad>]
2        [thanks, for, all, gifts]
</code>```

Title: Remove stop words from sentences and pad sentences from a list of lists in the data frame

Body:
Here is a way using reshaping:

df2 = (df.explode('sentence')
         .assign(group=lambda d: d.groupby(d.index).cumcount())
         .explode('sentence')
         .loc[lambda d: ~d['sentence'].isin(stopwords)]         # filter words
         .rename_axis('index')
         .assign(idx=lambda d: d.groupby(['index', 'group']).cumcount())
         .set_index(['group', 'idx'], append=True)
         .unstack('group')        # unstack/stack
         .fillna('<pad>')         # to pad
         .stack('group')          # missing words
         .groupby(level=[0, 'group']).agg(list)
         .reset_index('group', drop=True)
      )

output:

                      sentence
0     [deer, was, tasty, meal]
0  [girl, walks, <pad>, <pad>]
0    [thanks, for, all, gifts]

NB. this solution should also work on multiple input lines:

df = pd.concat([df]*3, ignore_index=True)

#                                             sentence
# 0  [[the, deer, was, a, tasty, meal], [the, girl,...
# 1  [[the, deer, was, a, tasty, meal], [the, girl,...
# 2  [[the, deer, was, a, tasty, meal], [the, girl,...

output:

                          sentence
index
0         [deer, was, tasty, meal]
0      [girl, walks, <pad>, <pad>]
0        [thanks, for, all, gifts]
1         [deer, was, tasty, meal]
1      [girl, walks, <pad>, <pad>]
1        [thanks, for, all, gifts]
2         [deer, was, tasty, meal]
2      [girl, walks, <pad>, <pad>]
2        [thanks, for, all, gifts]


问:
Python Pandas: How to find element in a column with a matching string object of other column
I have this string object:

```<code>code = '1002'
</code>```

And i also have the following Pandas Data Frame:

```<code>pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})
</code>```

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

答:
basically to solve this u have to get the index of the code first, after converting data frame value into list, I think my following code might help u.</p>
```<code> import pandas as pd
 code = '1001'
 df = pd.DataFrame({'Code':['1001','1002','1003','1004'],
          'Place':['Chile','Peru','Colombia','Argentina']})

 code_index = list(df['Code']).index(code)
 print(code_index)
 area = df['Place'][code_index]
 print(area)
</code>```

Body:
I have this string object:

code = '1002'

And i also have the following Pandas Data Frame:

pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

Body:
basically to solve this u have to get the index of the code first, after converting data frame value into list, I think my following code might help u.

 import pandas as pd
 code = '1001'
 df = pd.DataFrame({'Code':['1001','1002','1003','1004'],
          'Place':['Chile','Peru','Colombia','Argentina']})

 code_index = list(df['Code']).index(code)
 print(code_index)
 area = df['Place'][code_index]
 print(area)


问:
How to purge soft-deleted Text analytics?
To test ARM templates we first deploy them on test resource group. At 7PM those resource groups are automatically deleted. Yesterday it was working fine and today I can no longer deploy to the same test resource group name. I have not changed templates for a long time.

I'm not able to find this soft-deleted service anywhere in Azure Portal and don't know how to purge it.

```<code>14:43:17 - Error: Code=FlagMustBeSetForRestore; Message=An existing resource with ID
     | '/subscriptions/GUID/resourceGroups/myRG/providers/Microsoft.CognitiveServices/accounts/my-ta-zneztme4oqjb2' has been
     | soft-deleted. To restore the resource, you must specify 'restore' to be 'true' in the property. If you don't want to restore existing resource, please purge it first.
</code>```

答:
Only this worked for me:</p>
```<code>az cognitiveservices account purge -l northeurope -n your-service-name -g your-rg
</code>```

Body:
To test ARM templates we first deploy them on test resource group. At 7PM those resource groups are automatically deleted. Yesterday it was working fine and today I can no longer deploy to the same test resource group name. I have not changed templates for a long time.

I'm not able to find this soft-deleted service anywhere in Azure Portal and don't know how to purge it.

14:43:17 - Error: Code=FlagMustBeSetForRestore; Message=An existing resource with ID
     | '/subscriptions/GUID/resourceGroups/myRG/providers/Microsoft.CognitiveServices/accounts/my-ta-zneztme4oqjb2' has been
     | soft-deleted. To restore the resource, you must specify 'restore' to be 'true' in the property. If you don't want to restore existing resource, please purge it first.

Body:
Only this worked for me:

az cognitiveservices account purge -l northeurope -n your-service-name -g your-rg


问:
cypress-file-upload attachFile is not a function
I want to test my file uploading function using Cypress-file-upload but I hurt myself against .attachFile is not a function

I tried two solutions and I still can't make it works :

```<code>// 1st one, "find file input" works

  it('find file input', () => {
    cy.get('input[type="file"')
  })

  const fileName = 'french_tweets_split.csv';
  it('Testing csv uploading', () => {
    cy.fixture(fileName, 'binary')
      .then(Cypress.Blob.binaryStringToBlob)
      .then(fileContent => {
        cy.get("input[type='file']").attachFile({ fileContent, fileName, mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', encoding:'utf8' })
    })
  })
</code>```
```<code>// 2nd one, "find file input" works
  it('find file input', () => {
    cy.get('input[type="file"')
  })

  it('Testing csv uploading', () => {
    cy.fixture('french_tweets_split.csv').then(fileContent => {
        cy.get('input[type="file"]').attachFile({
            fileContent: fileContent.toString(),
            fileName: 'french_tweets_split.csv',
            mimeType: 'text/csv'
        })
    })
  })

</code>```

What am I doing wrong ?

答: I am working with TypeScript. I had to import it in support/index.ts.

Body:
I want to test my file uploading function using Cypress-file-upload but I hurt myself against .attachFile is not a function

I tried two solutions and I still can't make it works :

// 1st one, "find file input" works

  it('find file input', () => {
    cy.get('input[type="file"')
  })

  const fileName = 'french_tweets_split.csv';
  it('Testing csv uploading', () => {
    cy.fixture(fileName, 'binary')
      .then(Cypress.Blob.binaryStringToBlob)
      .then(fileContent => {
        cy.get("input[type='file']").attachFile({ fileContent, fileName, mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', encoding:'utf8' })
    })
  })

// 2nd one, "find file input" works
  it('find file input', () => {
    cy.get('input[type="file"')
  })

  it('Testing csv uploading', () => {
    cy.fixture('french_tweets_split.csv').then(fileContent => {
        cy.get('input[type="file"]').attachFile({
            fileContent: fileContent.toString(),
            fileName: 'french_tweets_split.csv',
            mimeType: 'text/csv'
        })
    })
  })

What am I doing wrong ?


问:
Jooq enum converter uses the ordinal number. How can I switch to use the enum value number instead?
We have an Enum class with customized values. The values are different from their ordinals intentionally for business purpose which I cannot change.

```<code>enum class Role(val value: Int) {
  EXECUTOR(1),
  MONITOR(3),
  ADMIN(5),

  companion object {
    private val map = Role.values().associateBy(Role::value)
    fun fromInt(role: Int) = map[role]
  }
}
</code>```

We are using JOOQ and postgres. We use the JOOQ default EnumConverter to convert db role integer values to objects.

```<code>ForcedType()
    .withUserType("com.company.enums.Role")
    .withEnumConverter(true)
    .withIncludeExpression("role"),
</code>```

However we noticed a problem -- the database stored the ordinals of the enum, instead of the values. For example we see in the db in roles column, the db value is 1, and the translated Enum is MONITOR, coz MONITOR has an ordinal of 1.

How can we store the values of Enum into db using JOOQ?

Thank you!

答:
You can of course implement a custom converter from scratch, as you suggested in your own answer. But do note that starting from jOOQ 3.16 and https://github.com/jOOQ/jOOQ/issues/12423, you can simplify that implementation by extending the org.jooq.impl.EnumConverter like this:

class RoleConverter : EnumConverter<Int, Role>(
  Int::class.java,
  Role::class.java,
  Role::value
)
```

Body:
We have an Enum class with customized values. The values are different from their ordinals intentionally for business purpose which I cannot change.

enum class Role(val value: Int) {
  EXECUTOR(1),
  MONITOR(3),
  ADMIN(5),

  companion object {
    private val map = Role.values().associateBy(Role::value)
    fun fromInt(role: Int) = map[role]
  }
}

We are using JOOQ and postgres. We use the JOOQ default EnumConverter to convert db role integer values to objects.

ForcedType()
    .withUserType("com.company.enums.Role")
    .withEnumConverter(true)
    .withIncludeExpression("role"),

However we noticed a problem -- the database stored the ordinals of the enum, instead of the values. For example we see in the db in roles column, the db value is 1, and the translated Enum is MONITOR, coz MONITOR has an ordinal of 1.

How can we store the values of Enum into db using JOOQ?

Thank you!


问:
ASP.Net SafeHandle - tasks and examples
I want to understand how to work with unmanaged resources and when I need the SafeHandle class. What can be the problem statement when you can say: "Oh, here I need the SafeHandle class!"?

I would be grateful for links to articles, examples, explanations

答:
I think MSDN is pretty clear in definition:

The SafeHandle class provides critical finalization of handle
resources, preventing handles from being reclaimed prematurely by
garbage collection and from being recycled by Windows to reference
unintended unmanaged objects. Before the .NET Framework version 2.0,
all operating system handles could only be encapsulated in the IntPtr
managed wrapper object.

The SafeHandle class contains a finalizer that ensures that the handle
is closed and is guaranteed to run, even during unexpected AppDomain
unloads when a host may not trust the consistency of the state of the
AppDomain.

For more information about the benefits of using a SafeHandle, see
Safe Handles and Critical Finalization.

This class is abstract because you cannot create a generic handle. To
implement SafeHandle, you must create a derived class. To create
SafeHandle derived classes, you must know how to create and free an
operating system handle. This process is different for different
handle types because some use CloseHandle, while others use more
specific methods such as UnmapViewOfFile or FindClose. For this
reason, you must create a derived class of SafeHandle for each
operating system handle type; such as MySafeRegistryHandle,
MySafeFileHandle, and MySpecialSafeFileHandle. Some of these derived
classes are prewritten and provided for you in the
Microsoft.Win32.SafeHandles namespace.

Title: ASP.Net SafeHandle - tasks and examples


问:
understanding lmer random effects in R
What is the point of the "1 +" in (1 + X1|X2) structure of the random effect of an lmer function in lme4 package of R, and how does this differ from (1|X1) + (1|X2)?</p>

答:
As the comment suggests, looking at the GLMM FAQ might be useful.

(1+X1|X2) is identical to (X1|X2) (due to R's default of adding an intercept). This fits a model where all of the effects of X1 (i.e. all of the predictors that we would get from a linear model using y ~ X1) vary across the groups/levels defined by X2, and all of the correlations among these varying effects are estimated.

if X1 is numeric, this fits a random-slopes model that estimates the variation in the intercept across groups, the variation in the slope across groups, and their covariance (correlation).

if X1 is categorical (a factor), this estimates variation based on the contrasts used for X1. Suppose X1 has three levels {A, B, C} and the default treatment contrasts are being used. Then a 3x3 covariance matrix is estimated which includes

the variation in the intercept (== the expected value in level A) across groups

the variation in the difference between A and B across groups

the variation in the difference between A and C across groups

all three pairwise covariances/correlations (A vs A-B, A vs A-C, A-B vs A-C)

The formula (1|X1) + (1|X2) only makes sense if X1 is categorical (only categorical variables, or variables that can be treated as categorical, make sense as grouping variables). This estimates the variation in the intercept (baseline response) among levels of X2 and the variation in the intercept (baseline response) among levels of X1.

As a final note, it's hard for me to think of a case where the latter formula ((1|X1) + (1|X2)) would make sense as an alternative to (X1|X2) ...

Title: understanding lmer random effects in R


问:
Azure Logic app, AzureAD remove group members, insuficcient permission
I'm creating a Azure Logic app to replace members of defined Azure AD group. I have used this blog  (https://geekshangout.com/logic-app-remove-azure-ad-group-members/) as of base for my job, but so far remove-member fails with insufficient permissions.

Basically logic app does:

Retrieve list of users from Azure SQL table with specific query: OK

Get list of users from AzureAD group : OK

For-each member:

remove member.objectID from azure group object ID:: Fails with following error:

```<code>"body": {
    "error": {
        "code": "Authorization_RequestDenied",
        "message": "Insufficient privileges to complete the operation.",
        "innerError": {
            "date": "2022-02-10T07:32:44",
            "request-id": "--------------",
            "client-request-id": "------------"
        }
    }
}
</code>```

So far: I re-created the logic app and taking care of:

Admin consent is given as described in the blog, by using the Global Admin account.

I can see in the 'Enterprise Applications' blade this 'logic app' created

permissions should be correct: API name: Microsoft graph, Claims: Directory.readwrite.all, group.readwrite.all, user.readwrite.all, offline_access , as of Microsoft documentation describes (https://learn.microsoft.com/en-us/connectors/azuread/)

Awaited now about 24 hours, so no 'cloud-lag' should be problem.

Should this 'Enterprise Application' have an additional permissions? If so, what and where?

Already tried to create a custom role with permissions described here: https://learn.microsoft.com/en-us/azure/active-directory/roles/custom-group-permissions

"Life is not a problem to be solved, but a reality to be experienced"
~T

答:
Assuming the user with which you set up the Logic Apps connection for Azure AD is authorized to manage this group's membership (e.g. which would be the case if this was a Global Administrator), the most likely cause for this is that the group you are trying to change membership for is a role-assignable group.

Role-assignable groups are special groups to which directory roles can be assigned. Adding a member to the group is equivalent to assigning a directory role to that member, so neither of the delegated permissions Directory.ReadWrite.All nor Group.ReadWrite.All allow this. (For regular groups, either of them would be sufficient.) The app would also need to be granted the delegated permission RoleManagement.ReadWrite.Directory.

From the look of things, the built-in Logic Apps connector for Azure AD is not built to handle group membership for role-assignable groups.

If you really do need to be able to do this, you could update the delegated permissions granted to the connector to include RoleManagement.ReadWrite.Directory, but you should be very careful about this (and your entire solution, including the SQL database and the Logic App), as misuse could carry significant security risks.

Body:
I'm creating a Azure Logic app to replace members of defined Azure AD group. I have used this blog  (https://geekshangout.com/logic-app-remove-azure-ad-group-members/) as of base for my job, but so far remove-member fails with insufficient permissions.

Basically logic app does:

Retrieve list of users from Azure SQL table with specific query: OK

Get list of users from AzureAD group : OK

For-each member:

remove member.objectID from azure group object ID:: Fails with following error:

"body": {
    "error": {
        "code": "Authorization_RequestDenied",
        "message": "Insufficient privileges to complete the operation.",
        "innerError": {
            "date": "2022-02-10T07:32:44",
            "request-id": "--------------",
            "client-request-id": "------------"
        }
    }
}

So far: I re-created the logic app and taking care of:

Admin consent is given as described in the blog, by using the Global Admin account.

I can see in the 'Enterprise Applications' blade this 'logic app' created

permissions should be correct: API name: Microsoft graph, Claims: Directory.readwrite.all, group.readwrite.all, user.readwrite.all, offline_access , as of Microsoft documentation describes (https://learn.microsoft.com/en-us/connectors/azuread/)

Awaited now about 24 hours, so no 'cloud-lag' should be problem.

Should this 'Enterprise Application' have an additional permissions? If so, what and where?

Already tried to create a custom role with permissions described here: https://learn.microsoft.com/en-us/azure/active-directory/roles/custom-group-permissions

"Life is not a problem to be solved, but a reality to be experienced"
~T


问:
Cross Browser Compatible HTML
Is there any tool available which will check my html page for different browsers and also suggest the changes I should make to make them cross browser compatible?

Some of my html pages are not working fine with IE and some in Chrome.

答:
You can use something like http://browsershots.org/ to see how it looks in all kind of browsers. But it stop there, it will not give you any solutions for the problems.
You just don't need to install all kind of browsers on all kind of operating systems.</p>

Title: Cross Browser Compatible HTML


问:
Create a table without a header in Markdown
Is it possible to create a table without a header in Markdown?

The HTML would look like this:

    Key 1
    Value 1

    Key 2
    Value 2

```

答:
what works in GitHub issue editor is

```<code>  |
------ | ---
Foo    | Bar
</code>```

But it does show an empty header

Foo
Bar

Body:
what works in GitHub issue editor is

&nbsp; |&nbsp;
------ | ---
Foo    | Bar

But it does show an empty header

Foo
Bar


问:
How to put debug/Breakpoint in Robot framework test in Pycharm?
My .py files in Robot-Framework allows me to introduce breakpoints but .robot file it doesn't allow. How do i introduce and toggle breakpoints in my .robot test files for debugging?</p>

答:
It is possible to add breakpoints to both .py and .robot files with Robot Framework Language Server.
There are plugins for both PyCharm and VS Code.


问:
Luigi not picking up next task to run, bunch of pending tasks left, no failed tasks
I am running a big Luigi workflow that is supposed run over a hundred tasks in total. The workflow goes well for quite a while, but at one stage it comes to a point where there are 15 pending tasks and all other tasks are successfully done, and no failed tasks. However, it doesn't seem to pick up any more of those pending tasks to execute. I have thoroughly looked at the logs and there are no errors. From that point on, it just periodically prints the following logs:

```<code>There are no more tasks to run at this time
There are 15 pending tasks possibly being run by other workers
There are 15 pending tasks unique to this worker
There are 15 pending tasks last scheduled by this worker
</code>```

The luigi version that I am using is 2.6.1. And here is a screenshot:

Any idea what might be going on here? Why would it think there is no task to run? Here is my luigi worker configuration:

```<code>[worker]
keep-alive = True
max-reschedules = 3
</code>```

答:
If the problem still persists, I have used this. After using the below code, the tasks are getting executed without issue.</p>
```<code>class TaskName(luigi.Task):
resources = {'max_workers': 1}
</code>```

Body:
I am running a big Luigi workflow that is supposed run over a hundred tasks in total. The workflow goes well for quite a while, but at one stage it comes to a point where there are 15 pending tasks and all other tasks are successfully done, and no failed tasks. However, it doesn't seem to pick up any more of those pending tasks to execute. I have thoroughly looked at the logs and there are no errors. From that point on, it just periodically prints the following logs:

There are no more tasks to run at this time
There are 15 pending tasks possibly being run by other workers
There are 15 pending tasks unique to this worker
There are 15 pending tasks last scheduled by this worker

The luigi version that I am using is 2.6.1. And here is a screenshot:

Any idea what might be going on here? Why would it think there is no task to run? Here is my luigi worker configuration:

[worker]
keep-alive = True
max-reschedules = 3

Body:
If the problem still persists, I have used this. After using the below code, the tasks are getting executed without issue.

class TaskName(luigi.Task):
resources = {'max_workers': 1}


问:
How to make the cell reference in Google App Script dynamic?
I am creating a macro for my repetitive work.

What I want to do:

Copy a current cell in Sheet1

Paste it to Sheet2

There will be a =filter formula running at the bottom, and I need to navigate to the bottom and copy the range of outputs

Have the cell return back to its original A1 cell position in Sheet2

Paste the outputs to Sheet3, and move down one row

Loop it until it meet an empty cell in the row of Sheet1

Challenges I face:

In Sheet1: The macro I created only refer to the cell I first run the macro with (even after I start from a different cell, the macro still copying the same initial cell)

In Sheet2: The outputs will possibly be a row or multiple rows of output, so it seems like Ctrl+A during the macro may not quite do the work.

For Loop: The macro only me to run once, but I will need it run repetitively until it meets an empty cell in Sheet1.

Challenge 1 and 2 are my main challenges, I can manually use hotkeys to run the macro if I can't get the macro to loop, but will be definitely grateful if someone can teach me how to loop it.

```<code>function CleanUp6() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet2'), true);
  spreadsheet.getRange('\'Sheet1\'!C2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getActiveRange().getDataRegion().activate();
  currentCell.activateAsCurrentCell();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.UP).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.UP).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.UP).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet3'), true);
  spreadsheet.getCurrentCell().offset(1, 0).activate();
  spreadsheet.getRange('\'Sheet2\'!A8:D8').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
</code>```

答:
Using macro recorder to try to develop a script is not a good idea.  It is recording mouse and keyboard actions, not code logic.  I think what you want is something like this.  Can't be sure but try it on a copy of your spreadsheet.  Add a menu option with the onOpen() trigger.</p>
```<code>function onOpen() {
  var menu = SpreadsheetApp.getUi().createMenu("File Picker");
  menu.addItem("Test","test");
  menu.addToUi();
}

function test() {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getActiveSheet();
    if( sh.getName() !== "Sheet1") {
      SpreadsheetApp.getUi().alert("Change to Sheet1");
      return;
    }
    if( sh.getActiveCell().getA1Notation() !== "A1" ) {
      SpreadsheetApp.getUi().alert("Change to cell A1");
      return;
    }
    // get the values in A:A
    var values = sh.getRange(1,1,sh.getLastRow(),1).getValues();
    sh = ss.getSheetByName("Sheet2");
    // copy values from Sheet1 to Sheet2
    // assumes the formulas are outside of the range values
    sh.getRange(1,1,values.length,1).setValues(values);
    // get the last row
    values = sh.getRange(sh.getLastRow(),1,1,sh.getLastColumn()).getValues();
    sh = ss.getSheetByName("Sheet3");
    // get the row following the last row .getLastRow()+1
    sh.getRange(sh.getLastRow()+1,1,values.length,values[0].length).setValues(values);
  }
  catch(err) {
    console.log(err);
  }
}
</code>```

Body:
I am creating a macro for my repetitive work.

What I want to do:

Copy a current cell in Sheet1

Paste it to Sheet2

There will be a =filter formula running at the bottom, and I need to navigate to the bottom and copy the range of outputs

Have the cell return back to its original A1 cell position in Sheet2

Paste the outputs to Sheet3, and move down one row

Loop it until it meet an empty cell in the row of Sheet1

Challenges I face:

In Sheet1: The macro I created only refer to the cell I first run the macro with (even after I start from a different cell, the macro still copying the same initial cell)

In Sheet2: The outputs will possibly be a row or multiple rows of output, so it seems like Ctrl+A during the macro may not quite do the work.

For Loop: The macro only me to run once, but I will need it run repetitively until it meets an empty cell in Sheet1.

Challenge 1 and 2 are my main challenges, I can manually use hotkeys to run the macro if I can't get the macro to loop, but will be definitely grateful if someone can teach me how to loop it.

function CleanUp6() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet2'), true);
  spreadsheet.getRange('\'Sheet1\'!C2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getActiveRange().getDataRegion().activate();
  currentCell.activateAsCurrentCell();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.UP).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.UP).activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.UP).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet3'), true);
  spreadsheet.getCurrentCell().offset(1, 0).activate();
  spreadsheet.getRange('\'Sheet2\'!A8:D8').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}

Body:
Using macro recorder to try to develop a script is not a good idea.  It is recording mouse and keyboard actions, not code logic.  I think what you want is something like this.  Can't be sure but try it on a copy of your spreadsheet.  Add a menu option with the onOpen() trigger.

function onOpen() {
  var menu = SpreadsheetApp.getUi().createMenu("File Picker");
  menu.addItem("Test","test");
  menu.addToUi();
}

function test() {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getActiveSheet();
    if( sh.getName() !== "Sheet1") {
      SpreadsheetApp.getUi().alert("Change to Sheet1");
      return;
    }
    if( sh.getActiveCell().getA1Notation() !== "A1" ) {
      SpreadsheetApp.getUi().alert("Change to cell A1");
      return;
    }
    // get the values in A:A
    var values = sh.getRange(1,1,sh.getLastRow(),1).getValues();
    sh = ss.getSheetByName("Sheet2");
    // copy values from Sheet1 to Sheet2
    // assumes the formulas are outside of the range values
    sh.getRange(1,1,values.length,1).setValues(values);
    // get the last row
    values = sh.getRange(sh.getLastRow(),1,1,sh.getLastColumn()).getValues();
    sh = ss.getSheetByName("Sheet3");
    // get the row following the last row .getLastRow()+1
    sh.getRange(sh.getLastRow()+1,1,values.length,values[0].length).setValues(values);
  }
  catch(err) {
    console.log(err);
  }
}


问:
Can i use native javascript for loop within jquery code?
Can i use native javascript for loop within jquery code? I have a construct in which $.each does not seem feasible. How can I loop in this situation?

the code inside the for loop is not working. any advice would be appreciated.

```<code>if (item.relate){
    $(prodHeading).append(item.name);
    if (item.image) {$(prodContent).append(item.image);}
    if (item.description) {
        $(prodContentText).append(item.description);
        $(prodContent).append(prodContentText);
    }
    $(prodBox).append(prodHeading);
    $(prodBox).append(prodContent);

    //going to look for other attached items

    for (j=0; j<10; j++){
        var prodBox = $(document.createElement('div')).attr('class','productBox');
        var prodHeading = $(document.createElement('div')).attr('class','productBoxHeading');
        var prodContent = $(document.createElement('div')).attr('class','productBoxContent');
        var prodContentText = $(document.createElement('div')).attr('class','text');

        if ('item.image'+j) {$(prodContent).append(item.image);}
        if ('item.description'+j) {
            $(prodContentText).append(item.description);
            $(prodContent).append(prodContentText);
        }
        $(prodBox).append(prodHeading);
        $(prodBox).append(prodContent);
    }
}
</code>```

答:
```<code>  for (var j=0; j<10; j++){
                    var prodBox = $(document.createElement('div')).attr('class','productBox');
                    var prodHeading = $("<div/>",{class:'productBoxHeading'});
                    var prodContent = $("<div/>",{class:'productBoxContent'});
                    var prodContentText = $("<div/>",{class:'text'});

                    if (item.image+j) {prodContent.append(item.image);}
                    if (item.description+j) {
                        prodContentText.append(item.description);
                        prodContent.append(prodContentText);
                        }
                    prodBox.append(prodHeading);
                    prodBox.append(prodContent);
                    }
</code>```

Body:
Can i use native javascript for loop within jquery code? I have a construct in which $.each does not seem feasible. How can I loop in this situation?

the code inside the for loop is not working. any advice would be appreciated.

if (item.relate){
    $(prodHeading).append(item.name);
    if (item.image) {$(prodContent).append(item.image);}
    if (item.description) {
        $(prodContentText).append(item.description);
        $(prodContent).append(prodContentText);
    }
    $(prodBox).append(prodHeading);
    $(prodBox).append(prodContent);

    //going to look for other attached items

    for (j=0; j<10; j++){
        var prodBox = $(document.createElement('div')).attr('class','productBox');
        var prodHeading = $(document.createElement('div')).attr('class','productBoxHeading');
        var prodContent = $(document.createElement('div')).attr('class','productBoxContent');
        var prodContentText = $(document.createElement('div')).attr('class','text');

        if ('item.image'+j) {$(prodContent).append(item.image);}
        if ('item.description'+j) {
            $(prodContentText).append(item.description);
            $(prodContent).append(prodContentText);
        }
        $(prodBox).append(prodHeading);
        $(prodBox).append(prodContent);
    }
}


问:
Is declaring a field volatile enough in case of a single writing thread?
Consider the following code:

```<code>public class MyAtomicInteger {
    private volatile int value;

    public int get() {
        return value;
    }

    public void increment() {
        value++;
    }

}
</code>```

I was asked the following question during an interview: is this code thread-safe if only one thread calls increment() and multiple threads can call get()?

I understand that if we have multiple writing threads, race conditions can occur. However, when there is a single writing thread in each reading thread we will get the values in order, i.e. we won't read 0 after 1 because write of 1 happens before the first read of 1 and, consequently, all subsequent reads in the same thread. Is this reasoning correct, or I am missing something?

答:
Normally problems come from needing atomicity for the read-modify-write that is value++;. Since a single thread is doing it, it's just one thread writing value, other threads reading value.

That's what volatile provides (visibility from changes done by threads) and that's all what is required.

Of course everyone knows that it's still not safe to design code like that. Someone adds another thread and *bam* your code is broken without you noticing anything.

Body:
Consider the following code:

public class MyAtomicInteger {
    private volatile int value;

    public int get() {
        return value;
    }

    public void increment() {
        value++;
    }

}

I was asked the following question during an interview: is this code thread-safe if only one thread calls increment() and multiple threads can call get()?

I understand that if we have multiple writing threads, race conditions can occur. However, when there is a single writing thread in each reading thread we will get the values in order, i.e. we won't read 0 after 1 because write of 1 happens before the first read of 1 and, consequently, all subsequent reads in the same thread. Is this reasoning correct, or I am missing something?


问:
Python variable with multilines
I'm pretty new to Python and I'm trying to do the following thing:
I made this code, which works fine:

```<code>import csv
import os

#Création fichiers BD
with open('data.csv') as datas:
    reader = csv.reader(datas, delimiter=';')
    for row in reader:
        vlanid = row[0]
        vlanname = row[1]

        config = '''\
        resource "aci_bridge_domain" "vlan_%s_bd" {
          name               = "VLAN-%s-BD"
          tenant_dn          = aci_tenant.l2transit.id
          name_alias         = "%s"
          arp_flood          = "yes"
          relation_fv_rs_ctx = aci_vrf.l2transit.id
        }

        ''' % (vlanid, vlanid, vlanname)

        file_name = 'vlan-%s-bd.tf'% (vlanid)
        file_path = 'C:\iac\script_aci\\bd'
        file_complete = os.path.join(file_path, file_name)

        with open(file_complete, 'w') as f:
           f.writelines(config)
</code>```

Only thing that bother me is how variable shown in the "config" block.
Using the %s method works fine, but lets say that this block had like 100 variables in it, it would be a nightmare to understand which variable is what.

My goal here is to have the variables names in the block directly instead of the "%s"

Could you guys help a newbie in the need?

Thanks!

答:
thanks for the reply. I've been doing some research and test about f-strings and was having some issues. Until I understand how to escape a single curly brace.

Here is the modifications that now works.
Thanks a lot for the reply !

```<code>import csv
import os

#Création fichiers BD
with open('data.csv') as datas:
    reader = csv.reader(datas, delimiter=';')
    for row in reader:
        vlan_id = row[0]
        vlan_name = row[1]

        config = \
        f'''resource "aci_bridge_domain" "vlan_{vlan_id}_bd" {{
          name               = "VLAN-{vlan_id}-BD"
          tenant_dn          = aci_tenant.l2transit.id
          name_alias         = "{vlan_name}"
          arp_flood          = "yes"
          relation_fv_rs_ctx = aci_vrf.l2transit.id
        }}
        '''

        file_name = f'vlan-{vlan_id}-bd.tf'
        file_path = 'C:\iac\script_aci\\bd'
        file_complete = os.path.join(file_path, file_name)

        with open(file_complete, 'w') as f:
           f.writelines(config)
</code>```

Title: Python variable with multilines

Body:
I'm pretty new to Python and I'm trying to do the following thing:
I made this code, which works fine:

import csv
import os

#Création fichiers BD
with open('data.csv') as datas:
    reader = csv.reader(datas, delimiter=';')
    for row in reader:
        vlanid = row[0]
        vlanname = row[1]

        config = '''\
        resource "aci_bridge_domain" "vlan_%s_bd" {
          name               = "VLAN-%s-BD"
          tenant_dn          = aci_tenant.l2transit.id
          name_alias         = "%s"
          arp_flood          = "yes"
          relation_fv_rs_ctx = aci_vrf.l2transit.id
        }

        ''' % (vlanid, vlanid, vlanname)

        file_name = 'vlan-%s-bd.tf'% (vlanid)
        file_path = 'C:\iac\script_aci\\bd'
        file_complete = os.path.join(file_path, file_name)

        with open(file_complete, 'w') as f:
           f.writelines(config)

Only thing that bother me is how variable shown in the "config" block.
Using the %s method works fine, but lets say that this block had like 100 variables in it, it would be a nightmare to understand which variable is what.

My goal here is to have the variables names in the block directly instead of the "%s"

Could you guys help a newbie in the need?

Thanks!

Body:
thanks for the reply. I've been doing some research and test about f-strings and was having some issues. Until I understand how to escape a single curly brace.

Here is the modifications that now works.
Thanks a lot for the reply !

import csv
import os

#Création fichiers BD
with open('data.csv') as datas:
    reader = csv.reader(datas, delimiter=';')
    for row in reader:
        vlan_id = row[0]
        vlan_name = row[1]

        config = \
        f'''resource "aci_bridge_domain" "vlan_{vlan_id}_bd" {{
          name               = "VLAN-{vlan_id}-BD"
          tenant_dn          = aci_tenant.l2transit.id
          name_alias         = "{vlan_name}"
          arp_flood          = "yes"
          relation_fv_rs_ctx = aci_vrf.l2transit.id
        }}
        '''

        file_name = f'vlan-{vlan_id}-bd.tf'
        file_path = 'C:\iac\script_aci\\bd'
        file_complete = os.path.join(file_path, file_name)

        with open(file_complete, 'w') as f:
           f.writelines(config)


问:
How to run VSCode from the command prompt
I for security reasons cannot run VSCode plainly. I have opened it in the past, but now due to specific reasons, I may only run VSCode from the command prompt. I've tried

start "path/to/file" code and start code "path/to/file"

but none work I'm on Microsoft Windows [Version 10.0.17134.407]

how may I run this by going to Windows+R then 'cmd' then start/ run?

Also it would be great if I could use this for a separate user.

I'm looking for something like:

Runas /user:user\admin /savecred "C:\Program Files (x86)\vs-code.exe"

答:
Maybe not the exact answer to the question, but...

To start Visual-Studio-Code from CMD into the current folder write:

```<code>code %cd%
</code>```

The environment variable cd tell VS-Code to open it with the current folder

Body:
Maybe not the exact answer to the question, but...

To start Visual-Studio-Code from CMD into the current folder write:

code %cd%

The environment variable cd tell VS-Code to open it with the current folder


问:
Cannot specify url in .env file vue cli 3
I'm referring to the documentation about environment variables in vue cli 3.

I'm able to set it up and get simple variables to show up but my url in the .env file doesn't show up.

Contents of the .env file:

```<code>FOO=bar
VUE_APP_SECRET=secret
API_URL="https://staging.something.org"
</code>```

Here is how I'm viewing the env:

```<code>console.log(process.env)
BASE_URL: "/"
NODE_ENV: "development"
VUE_APP_SECRET: "secret"
</code>```

The API_URL is not visible, am I doing something wrong?

答:
Since CLI 3, Vue recognizes variables in dotenv only when adding the prefix VUE_APP_

When making changes, restart CLI.

Body:
I'm referring to the documentation about environment variables in vue cli 3.

I'm able to set it up and get simple variables to show up but my url in the .env file doesn't show up.

Contents of the .env file:

FOO=bar
VUE_APP_SECRET=secret
API_URL="https://staging.something.org"

Here is how I'm viewing the env:

console.log(process.env)
BASE_URL: "/"
NODE_ENV: "development"
VUE_APP_SECRET: "secret"

The API_URL is not visible, am I doing something wrong?


问:
Is there any way to optimise this code?
I have a piece of code which will invert all the checkboxes on my form. I have multiple elements (not just checkboxes but also  <input type='text'>'s) in it. The reason I need it to be optimised is because it takes about two to three seconds to select all the checkboxes (275 right now).

Here's my code:

```<code>function FormInverse() {
    var iCheckbox = 1; // Because there are multiple input elements, we need to distinquish the input element ID and the row id
    var FormLength = document.FormFacturen.elements.length;
    for (i=0; i < FormLength; i++) {
        var FormElementType = document.FormFacturen.elements[i].type;
        if (FormElementType == "checkbox") {
            var Elements = document.getElementsByClassName('row' + iCheckbox); // Alle elementen in de array zetten
            var iNumElements = Elements.length;
            for (iElement=0; iElement < iNumElements; iElement++) {
                if (document.FormFacturen[i].checked == true) {
                    Elements[iElement].className = "invoice-tr-standard row" + iCheckbox;
                } else {
                    Elements[iElement].className = "invoice-tr-clicked row" + iCheckbox;
                }
            }
            iCheckbox++;
            document.FormFacturen[i].checked = !document.FormFacturen[i].checked;
        }
    }
}
</code>```

And here is the document.getElementsByClassName function:

```<code>document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = document.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};
</code>```

答:
Each call to getElementsByClassName is expensive, and it is being called on each pass of your for loop.

In addition to @Geoff's suggestion, you could call document.getElementsByTagName('input'); just once, instead of each time getElementsByClassName is called and cache the result for use within your loop.

That would require making a small modification to your getElementsByClassName function whereby it accepts an array of elements to search through.

```<code>document.getElementsByClassName = function(cl, eles) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var len = eles.length;
    for (var i = 0; i < len; i++) {
        var classes = eles[i].className;
        if (myclass.test(classes)) retnode.push(eles[i]);
    }
    return retnode;
};

function FormInverse() {
    // cache all inputs
    var inputs = document.getElementsByTagName("input");
    ...
    // later
    var Elements = document.getElementsByClassName('row' + iCheckbox, inputs);
</code>```

Title: Is there any way to optimise this code?

Body:
I have a piece of code which will invert all the checkboxes on my form. I have multiple elements (not just checkboxes but also  <input type='text'>'s) in it. The reason I need it to be optimised is because it takes about two to three seconds to select all the checkboxes (275 right now).

Here's my code:

function FormInverse() {
    var iCheckbox = 1; // Because there are multiple input elements, we need to distinquish the input element ID and the row id
    var FormLength = document.FormFacturen.elements.length;
    for (i=0; i < FormLength; i++) {
        var FormElementType = document.FormFacturen.elements[i].type;
        if (FormElementType == "checkbox") {
            var Elements = document.getElementsByClassName('row' + iCheckbox); // Alle elementen in de array zetten
            var iNumElements = Elements.length;
            for (iElement=0; iElement < iNumElements; iElement++) {
                if (document.FormFacturen[i].checked == true) {
                    Elements[iElement].className = "invoice-tr-standard row" + iCheckbox;
                } else {
                    Elements[iElement].className = "invoice-tr-clicked row" + iCheckbox;
                }
            }
            iCheckbox++;
            document.FormFacturen[i].checked = !document.FormFacturen[i].checked;
        }
    }
}

And here is the document.getElementsByClassName function:

document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = document.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};

Body:
Each call to getElementsByClassName is expensive, and it is being called on each pass of your for loop.

In addition to @Geoff's suggestion, you could call document.getElementsByTagName('input'); just once, instead of each time getElementsByClassName is called and cache the result for use within your loop.

That would require making a small modification to your getElementsByClassName function whereby it accepts an array of elements to search through.

document.getElementsByClassName = function(cl, eles) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var len = eles.length;
    for (var i = 0; i < len; i++) {
        var classes = eles[i].className;
        if (myclass.test(classes)) retnode.push(eles[i]);
    }
    return retnode;
};

function FormInverse() {
    // cache all inputs
    var inputs = document.getElementsByTagName("input");
    ...
    // later
    var Elements = document.getElementsByClassName('row' + iCheckbox, inputs);


问:
Calling a Rest-API using C#
I'm trying to call a rest-api in asp.net to test if people are trustworthy with paying by invoice. The problem is that i've never used any rest-api before and couldn't find a good example on how to call it in asp.net. Can someone help me?

Here are the values that the request needs.

```<code>/api/v1/RiskCube/claim

{
  "shopId": "20071992",
  "orderProcessId": "ref001",
  "ipAddress": null,
  "macAddress": null,
  "customerId": "cus001",
  "billingAddress": {
    "type": "Consumer",
    "businessName": null,
    "firstName": "Martin",
    "lastName": "Früh",
    "co": null,
    "street": "Funkenbüelstrasse",
    "houseNumber": "1",
    "postCode": "9243",
    "locationName": "Jonschwil",
    "country": "CH",
    "email": null,
    "phone": null,
    "dateOfBirth": null
  },
  "shippingAddress": null,
  "orderAmount": 1200
}
</code>```

答:
Thanks for all the answers in the end i came out with that result.

```<code>        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://service-zs.riskcube.ch/api/v1/RiskCube/claim");
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Headers.Add("Authorization", "X-API-KEY"); //Add a valid API Key
        if (creditReformModel != null)
        {
            string postData = JsonConvert.SerializeObject(creditReformModel);
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(postData);
            }
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
</code>```

I think for most people @Serhii answer is better than what i came up with.

Title: Calling a Rest-API using C#

Body:
I'm trying to call a rest-api in asp.net to test if people are trustworthy with paying by invoice. The problem is that i've never used any rest-api before and couldn't find a good example on how to call it in asp.net. Can someone help me?

Here are the values that the request needs.

/api/v1/RiskCube/claim

{
  "shopId": "20071992",
  "orderProcessId": "ref001",
  "ipAddress": null,
  "macAddress": null,
  "customerId": "cus001",
  "billingAddress": {
    "type": "Consumer",
    "businessName": null,
    "firstName": "Martin",
    "lastName": "Früh",
    "co": null,
    "street": "Funkenbüelstrasse",
    "houseNumber": "1",
    "postCode": "9243",
    "locationName": "Jonschwil",
    "country": "CH",
    "email": null,
    "phone": null,
    "dateOfBirth": null
  },
  "shippingAddress": null,
  "orderAmount": 1200
}

Body:
Thanks for all the answers in the end i came out with that result.

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://service-zs.riskcube.ch/api/v1/RiskCube/claim");
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Headers.Add("Authorization", "X-API-KEY"); //Add a valid API Key
        if (creditReformModel != null)
        {
            string postData = JsonConvert.SerializeObject(creditReformModel);
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(postData);
            }
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

I think for most people @Serhii answer is better than what i came up with.


问:
kotlin reflection get list of fields
is there an equivalent for the java reflection foo.getClass().getFields() in Kotlin? I could only find that I can access a field when I know it's name, but I would like to handle fields in a generic way.

答:
Regarding your example with a foo variable you may get its backing fields through:

val fields: List<Field?> = foo::class.memberProperties.map { it.javaField }
```

Title: kotlin reflection get list of fields


问:
how to configure 'send email' in jenkins by proxy
My Jenkins machine cannot connect to the internet. I want to configure Jenkins to work with a proxy server to send email. The startup parameter is:

```<code>-Dhttp.proxyHost=172.16.0.10 -Dhttp.proxyPort=3128
</code>```

But it doesn't work.

答:
You can configure the proxy properties on Manage Jenkins > System configurations. In this page you can find "Global Properties" configuration and in this part you have to push the "add" button and put there the HTTP_PROXY, HTTPS_PROXY and NO_PROXY properties. These proxy properties should contain the proxy configuration like in the operating system. You can see an example of this configuration in the next image:

You should replace the properties:

<$PROTOCOL>         ->  Proxy address protocol (http, https, ...)

<$USER>             ->  Proxy user authorization (If the proxy require it)

<$PASS>             ->  Proxy password (If the proxy require it)

<$PROXY_DNS>        -> Proxy URL or Proxy IP

<$PORT>             -> Proxy port

<$DNS1>,<$DNS2>,... -> URL where the proxy don't should be used

Body:
My Jenkins machine cannot connect to the internet. I want to configure Jenkins to work with a proxy server to send email. The startup parameter is:

-Dhttp.proxyHost=172.16.0.10 -Dhttp.proxyPort=3128

But it doesn't work.


问:
No such module 'IQKeyboardManagerSwift'
New to Xcode (dabble a little). I paid a developer to build an iOS app for me. He sent me the source code and I have opened it in Xcode 13.2.1. I needed to edit the info.plist to include a description why location was required (got this done). When I try to run the build, I get the error 'no such module 'IQKeyboardManagerSwift'. In AppDelegate, I see 'import IQKeyboardManagerSwift --- No such module 'IQKeyboardManagerSwift'. I went to the Podfile directory and ran 'pod install'. Output says:

Analyzing dependencies

Downloading dependencies

Generating Pods project

Integrating client project

Pod installation complete! There are 7 dependencies from the Podfile and 8 total pods installed.

I'm still getting the error when trying to run the build. I tried cleaning the build folder and running the build again but still, same error. What am I missing?

答: The missing module handles a number of keyboard behaviors so you don't have to reinvent that wheel.  Check out the developer's website and get it for yourself.  I've been using it for years.  The developer has helped me more than once get past some obstacles.</p>

Title: No such module 'IQKeyboardManagerSwift'