问:
Login status in React

I created authorization in javascript. Then if success login I redirect to React project with url parameter http://localhost:3000/?phoneNum=%2B77072050399

Then in React I get userId by using the passed url parameter => phoneNumber using axios.

I realized it in App.js. Code below:

```<code>let url = window.location.href;
    let params = (new URL(url)).searchParams;
    const userPhoneNum = encodeURIComponent(params.get('phoneNum'));

    const [userToken, setUserToken] = useState(null);
    const getUserToken = async() => {
        try {
            const data = await axios
                .get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
                .then(response => {
                    setUserToken(response.data);
                })
                .catch(function(error) {
                    console.log('No such user! Error in getting token!');
                });
        } catch (e) {
            console.log(e);
        }
    }

    useEffect(() => {
        getUserToken();
        console.log(userToken);
    }, userToken);
</code>```

So, when I go to next page localhost:3000/places, it is requesting for userToken again with parameter null, because there is no param phoneNum.

How to make it to request only one time and save the userId after it is taken in main page. So, then only when I click LogOut button reset the variable where userID is saved.

答:
You can easily achieve this by using the react-cookie library

```<code>npm i react-cookie
</code>```

Can be easily implemented in your code by

```<code>cookies.set('key', value, { path: '/' });
cookies.get('key')
</code>```

After getting the userNumber form the param

const userPhoneNum = encodeURIComponent(params.get('phoneNum'));
 cookies.set('userphoneNum', userPhoneNum);

View the documentation for more information

https://www.npmjs.com/package/react-cookie

Title: Login status in React

Body:
I created authorization in javascript. Then if success login I redirect to React project with url parameter http://localhost:3000/?phoneNum=%2B77072050399

Then in React I get userId by using the passed url parameter => phoneNumber using axios.

I realized it in App.js. Code below:

let url = window.location.href;
    let params = (new URL(url)).searchParams;
    const userPhoneNum = encodeURIComponent(params.get('phoneNum'));

    const [userToken, setUserToken] = useState(null);
    const getUserToken = async() => {
        try {
            const data = await axios
                .get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
                .then(response => {
                    setUserToken(response.data);
                })
                .catch(function(error) {
                    console.log('No such user! Error in getting token!');
                });
        } catch (e) {
            console.log(e);
        }
    }

    useEffect(() => {
        getUserToken();
        console.log(userToken);
    }, userToken);

So, when I go to next page localhost:3000/places, it is requesting for userToken again with parameter null, because there is no param phoneNum.

How to make it to request only one time and save the userId after it is taken in main page. So, then only when I click LogOut button reset the variable where userID is saved.

Body:
You can easily achieve this by using the react-cookie library

npm i react-cookie

Can be easily implemented in your code by

cookies.set('key', value, { path: '/' });
cookies.get('key')

After getting the userNumber form the param

const userPhoneNum = encodeURIComponent(params.get('phoneNum'));
 cookies.set('userphoneNum', userPhoneNum);

View the documentation for more information

https://www.npmjs.com/package/react-cookie


来源: stackexchange

问:
How to create a tiled map in Java?
So I have a tile image tile.png and I'm trying to create a tiled map all across the window. I'm building this as an applet. This is what my paint method looks like, but its not effective. When I run the applet it takes about 2 seconds and the entire screen is painted from left to right with the image, rather than everything rendered at once. Also, it all looks like one large tile.png rather than 40 small instances of tile.png

```<code>public void paint(Graphics g)
{
    Image tile=getImg("tile.png");
    int width=this.getWidth();
    int height=this.getHeight();

    int x;
    int y;
    for (x=0; x<= width; x++)
    {
        for (y=0; y<= height; y++)
        {
            g.drawImage(tile, x, y, this);
        }
    }
}
</code>```

Btw the tile.png file is 10 x 10 pixels, this is the actual img:

tile.png http://img12.imageshack.us/img12/1368/tile.png

Edit: Using the code below and by improving the tile image i fixed this. Here's my new tile img in case it helps someone:

答:
```<code>    for (x=0; x<= width / tileWidth; x++)
    {
            for (y=0; y<= height / tileHeight ; y++)
            {
                    g.drawImage(tile, x * tileWidth, y * tileHeight, this);
            }
    }
</code>```

<p>You need to offset by the width/height of the tile. </p>

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 4.0

Title: How to create a tiled map in Java?

Body:
So I have a tile image tile.png and I'm trying to create a tiled map all across the window. I'm building this as an applet. This is what my paint method looks like, but its not effective. When I run the applet it takes about 2 seconds and the entire screen is painted from left to right with the image, rather than everything rendered at once. Also, it all looks like one large tile.png rather than 40 small instances of tile.png

public void paint(Graphics g)
{
    Image tile=getImg("tile.png");
    int width=this.getWidth();
    int height=this.getHeight();

    int x;
    int y;
    for (x=0; x<= width; x++)
    {
        for (y=0; y<= height; y++)
        {
            g.drawImage(tile, x, y, this);
        }
    }
}

Btw the tile.png file is 10 x 10 pixels, this is the actual img:

tile.png http://img12.imageshack.us/img12/1368/tile.png

Edit: Using the code below and by improving the tile image i fixed this. Here's my new tile img in case it helps someone:

LastEditorDisplayName: Click Upvote

Body:
    for (x=0; x<= width / tileWidth; x++)
    {
            for (y=0; y<= height / tileHeight ; y++)
            {
                    g.drawImage(tile, x * tileWidth, y * tileHeight, this);
            }
    }

You need to offset by the width/height of the tile.

OwnerDisplayName: FlySwat

ContentLicense: CC BY-SA 2.5


问:
How to configure a running Mule service's properties dynamically?
I would like a recommendation/idea on a method to configure properties for a running Mule service dynamically, i.e. I want the service to pick up the new settings without the need to restart Mule. Typically the kind of properties/settings I would like to change are FTP connector user ID, passwords, service URLs etc.

Any idea would be welcome.

Regards, Ola

答:
Mule exposes all service configuration via JMX, but I don't see any obvious way to reconfigure the connectors without a restart. They are internally managing pools of connections.

If there is a limited, you can create connectors for each and reconfigure the routes via jmx attributes.

If it is to be fully dynamic you likely need to implement your own service component to manage the ftp connection. Exposing the connection management, configuration, and restarting via JMX should be pretty straight forward.

ContentLicense: CC BY-SA 3.0


问:
What is a nested structure in TensorFlow?
Going over the documentation for tf.data.Datasets, I see  that there is a frequent mention of "nested structures". What exactly is meant by that? Can any Python data type be considered a nested structure (e.g., (1,3, (7,6, (0), 5)) or dict(k=dict(3), 7, None) or does this specifically refer to TensorFlow data types?

答:
Providing answer here from the comment section for the benefit of the community.

Nested Structure in TensorFlow generally refers to a tuple or a dict containing tensor values, or other nested structures.

 The typical case is a dataset where each element is a (x, y) pair for training, but you could also have a dict {'x': x, 'y': y}, or a nested tuple if you have more than one input ((x1, x2), y).

 Datasets allow you to have structures of tensors in them for convenience.

 See Dataset structure of the guide on tf.data.


问:
what is the function of the method times in kotlin?
I am new to the world of programming and I am working on operator overload, I would like you to explain to me what function the times method fulfills in this exercise.    </p>

```<code>class Vector {
    val arreglo = IntArray(5)

    fun cargar() {
        for (i in arreglo.indices)
            arreglo[i] = (Math.random() * 11 + 1).toInt()
    }

    fun imprimir() {
        for (elemento in arreglo)
            print("$elemento ")
        println()
    }

    operator fun times(valor: Int): Vector {
        var suma = Vector()
        for (i in arreglo.indices)
            suma.arreglo[i] = arreglo[i] * valor
        return suma
    }
}

fun main(args: Array<String>) {
    val vec1 = Vector()
    vec1.cargar()
    vec1.imprimir()
    println("El producto de un vector con el número 10 es")
    val vecProductoEnt = vec1 * 10
    vecProductoEnt.imprimir()
}
</code>```

答: Function times overloads operator times (*) and lets you write expression vec1 * 10 to multiply every element of Vector by 10.</p>

Body:
I am new to the world of programming and I am working on operator overload, I would like you to explain to me what function the times method fulfills in this exercise.

class Vector {
    val arreglo = IntArray(5)

    fun cargar() {
        for (i in arreglo.indices)
            arreglo[i] = (Math.random() * 11 + 1).toInt()
    }

    fun imprimir() {
        for (elemento in arreglo)
            print("$elemento ")
        println()
    }

    operator fun times(valor: Int): Vector {
        var suma = Vector()
        for (i in arreglo.indices)
            suma.arreglo[i] = arreglo[i] * valor
        return suma
    }
}

fun main(args: Array<String>) {
    val vec1 = Vector()
    vec1.cargar()
    vec1.imprimir()
    println("El producto de un vector con el número 10 es")
    val vecProductoEnt = vec1 * 10
    vecProductoEnt.imprimir()
}


问:
Perform animation by adding a class to an element
I'm trying to create a menu which plays an animation on click (div with text flies in). When clicking another item in the menu the current div fades and the next one flies in.

I'm trying to do this by adding a class, transorm transiracy, and playing the animation. I've been trying for several hours now, yet nothing works. Can anyone see what I'm doing wrong?

document.getElementsByClassName('.link').onclick = function("myFunction");

function myFunction() {
  var element = document.getElementById("panel");
  element.classList.add("textcss");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</nav>
<div class="text">
  <div class="panel1" id='panel'>
    <p>PANEL1 <br><br></p>
  </div>
  <div class="panel2" id='panel'>
    <p>PANEL2</p>
  </div>
  <div class="panel3" id='panel'>
    <p>PANEL 3</p>
  </div>
</div></code>```

答:
Your requirements are a bit tricky, it will be very easy if you only want one effect, either fly or fade-out , but you need 2 of them, so you need to manipulate classes for fade-out and fly effect, you can change the left and top potions to change your flying effect.

$(document).ready(function(){
        $('.link').click(function(){
            $('.link').removeClass('active');
            $(this).addClass('active');
            var realtion = $(this).data('relation');
            $('.text .panel').removeClass('active').addClass('stayHere');
            $('.text').find('#' + realtion).addClass('active').removeClass('stayHere');
            setTimeout(function(){
                $('.text .panel').removeClass('stayHere')
            },1000);
        });

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text {
        position: relative;
    }
    .link {cursor: pointer;}
    .text .panel {
        position: absolute;
        left: 200px;
        transition: top 1s, left 1s, opacity 1s;
        top: -200px;
        opacity: 0;
    }
    .text .panel.active {
        top: 0;
        left: 0;
        display: block !important;
        opacity: 1;
    }
    .stayHere {
        top: 0 !important;
        left: 0 !important;
        opacity: 0 !important;
    }</code>```

1

2

3

PANEL1

PANEL2

PANEL 3

```

Body:
I'm trying to create a menu which plays an animation on click (div with text flies in). When clicking another item in the menu the current div fades and the next one flies in.

I'm trying to do this by adding a class, transorm transiracy, and playing the animation. I've been trying for several hours now, yet nothing works. Can anyone see what I'm doing wrong?

document.getElementsByClassName('.link').onclick = function("myFunction");

function myFunction() {
  var element = document.getElementById("panel");
  element.classList.add("textcss");
}

1

2

3

PANEL1

PANEL2

PANEL 3

Body:
Your requirements are a bit tricky, it will be very easy if you only want one effect, either fly or fade-out , but you need 2 of them, so you need to manipulate classes for fade-out and fly effect, you can change the left and top potions to change your flying effect.

$(document).ready(function(){
        $('.link').click(function(){
            $('.link').removeClass('active');
            $(this).addClass('active');
            var realtion = $(this).data('relation');
            $('.text .panel').removeClass('active').addClass('stayHere');
            $('.text').find('#' + realtion).addClass('active').removeClass('stayHere');
            setTimeout(function(){
                $('.text .panel').removeClass('stayHere')
            },1000);
        });

    });

.text {
        position: relative;
    }
    .link {cursor: pointer;}
    .text .panel {
        position: absolute;
        left: 200px;
        transition: top 1s, left 1s, opacity 1s;
        top: -200px;
        opacity: 0;
    }
    .text .panel.active {
        top: 0;
        left: 0;
        display: block !important;
        opacity: 1;
    }
    .stayHere {
        top: 0 !important;
        left: 0 !important;
        opacity: 0 !important;
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <ul>
    <li><a class="link" data-relation="panel1">1</a></li>
    <li><a class="link" data-relation="panel2">2</a></li>
    <li><a class="link" data-relation="panel3">3</a></li>
  </ul>
</nav>
<div class="text">
  <div class="panel" id='panel1'>
    <p>PANEL1 <br><br></p>
  </div>
  <div class="panel" id='panel2'>
    <p>PANEL2</p>
  </div>
  <div class="panel" id='panel3'>
    <p>PANEL 3</p>
  </div>
</div>


问:
How to access a service added to DI container from inside Asp.Net Core's ConfigureServices method
The code sample below is from Asp.Net Core ConfigureServices method in Startup.cs.

I am first registering a singleton service called AppState. Subsequent to that, I am configuring OpenIdConnect, and inside the OnTokenValidated lambda, I need to access the AppState service that I just registered in the DI container up above.

What is the most elegant way of accessing the AppState service instance?

I would prefer to not call services.BuildServiceProvider() inside the ConfigureServices method if at all possible.

```<code>services.AddSingleton<AppState>();

services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
            //How to get access to instance of AppState,
            //which was added to DI container up above
            AppState appState = //{get from DI somehow};
            appState.DoSomething();
        }
    };
});
</code>```

EDIT: Using the answer below, I edited the code like so, but I can confirm that the OnTokenValidated event is not firing, as opposed to the code above in my original question, which does fire:

```<code>services.AddOptions<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme)
            .Configure<IServiceScopeFactory>((options, sp) => {
                using (var scope = sp.CreateScope())
                {
                    options.Events = new OpenIdConnectEvents
                    {
                        OnTokenValidated = async ctx =>
                        {
                            var appState = scope.ServiceProvider.GetRequiredService<AppState>();

                            await appState.Dosomething();
                        }
                    };
                }
            });
</code>```

答:
You can access the DI service from the event context:</p>

```<code>services.AddSingleton<AppState>();

services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
            var appState = (AppState)ctx.HttpContext.RequestServices.GetService(typeof(AppState));
            appState.DoSomething();
        }
    };
});
</code>```

Body:
The code sample below is from Asp.Net Core ConfigureServices method in Startup.cs.

I am first registering a singleton service called AppState. Subsequent to that, I am configuring OpenIdConnect, and inside the OnTokenValidated lambda, I need to access the AppState service that I just registered in the DI container up above.

What is the most elegant way of accessing the AppState service instance?

I would prefer to not call services.BuildServiceProvider() inside the ConfigureServices method if at all possible.

services.AddSingleton<AppState>();

services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
            //How to get access to instance of AppState,
            //which was added to DI container up above
            AppState appState = //{get from DI somehow};
            appState.DoSomething();
        }
    };
});

EDIT: Using the answer below, I edited the code like so, but I can confirm that the OnTokenValidated event is not firing, as opposed to the code above in my original question, which does fire:

services.AddOptions<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme)
            .Configure<IServiceScopeFactory>((options, sp) => {
                using (var scope = sp.CreateScope())
                {
                    options.Events = new OpenIdConnectEvents
                    {
                        OnTokenValidated = async ctx =>
                        {
                            var appState = scope.ServiceProvider.GetRequiredService<AppState>();

                            await appState.Dosomething();
                        }
                    };
                }
            });

Body:
You can access the DI service from the event context:

services.AddSingleton<AppState>();

services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
            var appState = (AppState)ctx.HttpContext.RequestServices.GetService(typeof(AppState));
            appState.DoSomething();
        }
    };
});


问:
What's the Node's execution order in this example
The common example of presenting the functionality of setImmediate function in Node JS is the following code

console.log('1');
setImmediate(() => console.log('2'));
console.log('3');
```

<p>which evaluates to</p>

```1
3
2
```

As far as I know setImmediate callbacks are executed during check phase of event loop

However I don't understand where fetching new, sequential instruction fits there? Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2? If so - how many such instruction would Node execute before reaching check phase?

答:
However I don't understand where fetching new, sequential instruction fits there?

No need to fetch anything new because all the instructions have to be loaded already at that point, since we are already in the middle of executing them!

It is determined that your code should run

Your code (all 3 lines) runs

Event loop is entered and checks what else is there to do

It is determined that the callback should run

The callback (all "1 lines") runs

...

Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2?

Yes.

If so - how many such instruction would Node execute before reaching check phase?

Infinitely many.

JavaScript is single-threaded* and there nothing can preempt your code (other than a Ctrl+C).

So, the following code will keep outputting 3 in all eternity and never get to 2**:

console.log('1');
setImmediate(() => console.log('2'));
while (true) {
  console.log('3');
}
```

```1
3
3
3
3
... (forever)
```

<p>Similarly, the following code will for all eternity print <code>2A</code> and never get to <code>2B</code>:</p>

<pre class="lang-js prettyprint-override"><code>console.log('1');
setImmediate(() => {
  while (true) {
    console.log('2A');
  }
});
setImmediate(() => console.log('2B'));
console.log('3');
</code>```

```<code>1
3
2A
2A
2A
2A
... (forever)
</code>```

(The same applies if you were to move the setImmediate(() => console.log('2B')); inside the first callback instead of putting it below it.)

*: Yes there are worker threads in node.js and service workers in the browser, but they live in their own environments.

**: ...consuming 100% of one CPU core in the process and not reacting to any events or signals, so consider this an example of academic interest only, not something you would ever write in real code.

Body:
The common example of presenting the functionality of setImmediate function in Node JS is the following code

console.log('1');
setImmediate(() => console.log('2'));
console.log('3');

which evaluates to

1
3
2

As far as I know setImmediate callbacks are executed during check phase of event loop

However I don't understand where fetching new, sequential instruction fits there? Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2? If so - how many such instruction would Node execute before reaching check phase?

Body:
However I don't understand where fetching new, sequential instruction fits there?

No need to fetch anything new because all the instructions have to be loaded already at that point, since we are already in the middle of executing them!

It is determined that your code should run

Your code (all 3 lines) runs

Event loop is entered and checks what else is there to do

It is determined that the callback should run

The callback (all "1 lines") runs

...

Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2?

Yes.

If so - how many such instruction would Node execute before reaching check phase?

Infinitely many.

JavaScript is single-threaded* and there nothing can preempt your code (other than a Ctrl+C).

So, the following code will keep outputting 3 in all eternity and never get to 2**:

console.log('1');
setImmediate(() => console.log('2'));
while (true) {
  console.log('3');
}

1
3
3
3
3
... (forever)

Similarly, the following code will for all eternity print 2A and never get to 2B:

console.log('1');
setImmediate(() => {
  while (true) {
    console.log('2A');
  }
});
setImmediate(() => console.log('2B'));
console.log('3');

1
3
2A
2A
2A
2A
... (forever)

(The same applies if you were to move the setImmediate(() => console.log('2B')); inside the first callback instead of putting it below it.)

*: Yes there are worker threads in node.js and service workers in the browser, but they live in their own environments.

**: ...consuming 100% of one CPU core in the process and not reacting to any events or signals, so consider this an example of academic interest only, not something you would ever write in real code.


问:
How to display nested data in v-select from VUEX Store
I have 2 v-select dropdown(Countries and States) that get filled in with data from database. For example, I'm trying to select a Country(CANADA) from the 1st v-select dropdown and I want the second v-select to show only CANADA states. I'm using VUEX STORE to fetch data from my Laravel backend API.

```<code>// VUEX STORE
import Axios from "axios";

export default {
namespaced: true,

//*******STATE*******//
state: {
   countries: [],
   states: []
},

//*********MUTATIONS**********//
SET_COUNTRIES(state, countries) {
  state.countries = countries;
},

SET_STATE(state, states) {
  state.states = states;
}
//********ACTIONS******//
actions: {
  async loadCountries({ commit }) {
    let response = await Axios.get("/dashboard/countries");
    let countries = response.data;
    countries.forEach(c => {
      c.state_ids = c.states.map(p => p.id);
    });
    console.log(response.data);
    commit("SET_COUNTRIES", countries);
  },

  async loadStates({ commit }) {
    let response = await Axios.get("/dashboard/states");
    let states = response.data;
    console.log(response.data);
    commit("SET_STATE", states);
  }
 }
};
</code>```

```<code> // CountryState.vue
</code>```

```<code><v-row>
      <v-col cols="4">
        <v-select
          v-model="selectedCountry"
          :items="countries"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.COUNTRY')"
          single-line
          return-object
        >
        </v-select>
      </v-col>
      <v-col cols="4">
        <v-select
          v-model="selectedState"
          :items="states"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.STATE')"
          single-line
          return-object
        >
        </v-select>
      </v-col>
      <v-col cols="4">
      <p>The selected Item is: {{ selectedCountry.name }}</p>
      <p>The selected Item is: {{ selectedState.name }}</p>
    </v-row>
<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      selectedCountry: [],
      selectedState: "",
      showScheduleForm: false
    };
  },

  computed: {
    ...mapState({
      countries: state => state.allCountries.countries,
      states: state => state.allCountries.states
    })
  },

  mounted() {
    this.$store.dispatch("allCountries/loadCountries");
    this.$store.dispatch("allCountries/loadStates");
  }
};
</script>
</code>```

Country Data in state look like this

```<code>{"id":1,"name":"Canada","short_code":"CA","states":[{"id":7,"name":"Ontario","country_id":1},{"id":8,"name":"Minnetoba","country_id":1},{"id":9,"name":"Columbia","country_id":1}],"state_ids":[7,8,9]}
</code>```

States Data in state look like this

```<code>{"id":7,"name":"Ontario","country_id":1,"country":{"id":1,"name":"Canada","short_code":"CA"}}
</code>```

答:
You could trigger a function to filter states onChange. Your v-select then displays a list of states depending on the selected country.

Step 1: add filter method

```<code>  methods: {
    filterStates(country) {
      this.selectedState = "";
      this.filteredStates = this.states.filter(state => state.country_id === country.id);
    }
  },
</code>```

Step 2: trigger onChange of country

```<code>@change="filterStates"
</code>```

Step 3: display filtered states

```<code> :items="filteredStates"
</code>```

Putting it together

```<code><v-row>
      <v-col cols="4">
        <v-select
          v-model="selectedCountry"
          :items="countries"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.COUNTRY')"
          single-line
          return-object
          @change="filterStates"
        >
        </v-select>
      </v-col>
      <v-col cols="4">
        <v-select
          v-model="selectedState"
          :items="filteredStates"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.STATE')"
          single-line
          return-object
        >
        </v-select>
      </v-col>
      <v-col cols="4">
      <p>The selected Item is: {{ selectedCountry.name }}</p>
      <p>The selected Item is: {{ selectedState.name }}</p>
    </v-row>
<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      selectedCountry: [],
      selectedState: "",
      showScheduleForm: false,
      filteredStates: []
    };
  },

  computed: {
    ...mapState({
      countries: state => state.allCountries.countries,
      states: state => state.allCountries.states
    })
  },
  methods: {
    filterStates(country) {
      this.selectedState = "";
      this.filteredStates = this.states.filter(state => state.country_id === country.id);
    }
  },
  mounted() {
    this.$store.dispatch("allCountries/loadCountries");
    this.$store.dispatch("allCountries/loadStates");
  }
};
</script>
</code>```

Body:
I have 2 v-select dropdown(Countries and States) that get filled in with data from database. For example, I'm trying to select a Country(CANADA) from the 1st v-select dropdown and I want the second v-select to show only CANADA states. I'm using VUEX STORE to fetch data from my Laravel backend API.

// VUEX STORE
import Axios from "axios";

export default {
namespaced: true,

//*******STATE*******//
state: {
   countries: [],
   states: []
},

//*********MUTATIONS**********//
SET_COUNTRIES(state, countries) {
  state.countries = countries;
},

SET_STATE(state, states) {
  state.states = states;
}
//********ACTIONS******//
actions: {
  async loadCountries({ commit }) {
    let response = await Axios.get("/dashboard/countries");
    let countries = response.data;
    countries.forEach(c => {
      c.state_ids = c.states.map(p => p.id);
    });
    console.log(response.data);
    commit("SET_COUNTRIES", countries);
  },

  async loadStates({ commit }) {
    let response = await Axios.get("/dashboard/states");
    let states = response.data;
    console.log(response.data);
    commit("SET_STATE", states);
  }
 }
};

 // CountryState.vue

<v-row>
      <v-col cols="4">
        <v-select
          v-model="selectedCountry"
          :items="countries"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.COUNTRY')"
          single-line
          return-object
        >
        </v-select>
      </v-col>
      <v-col cols="4">
        <v-select
          v-model="selectedState"
          :items="states"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.STATE')"
          single-line
          return-object
        >
        </v-select>
      </v-col>
      <v-col cols="4">

The selected Item is: {{ selectedCountry.name }}

The selected Item is: {{ selectedState.name }}

    </v-row>

Country Data in state look like this

{"id":1,"name":"Canada","short_code":"CA","states":[{"id":7,"name":"Ontario","country_id":1},{"id":8,"name":"Minnetoba","country_id":1},{"id":9,"name":"Columbia","country_id":1}],"state_ids":[7,8,9]}

States Data in state look like this

{"id":7,"name":"Ontario","country_id":1,"country":{"id":1,"name":"Canada","short_code":"CA"}}

Body:
You could trigger a function to filter states onChange. Your v-select then displays a list of states depending on the selected country.

Step 1: add filter method

  methods: {
    filterStates(country) {
      this.selectedState = "";
      this.filteredStates = this.states.filter(state => state.country_id === country.id);
    }
  },

Step 2: trigger onChange of country

@change="filterStates"

Step 3: display filtered states

 :items="filteredStates"

Putting it together

<v-row>
      <v-col cols="4">
        <v-select
          v-model="selectedCountry"
          :items="countries"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.COUNTRY')"
          single-line
          return-object
          @change="filterStates"
        >
        </v-select>
      </v-col>
      <v-col cols="4">
        <v-select
          v-model="selectedState"
          :items="filteredStates"
          item-value="name"
          item-text="name"
          :label="$t('GENERAL.FORM.STATE')"
          single-line
          return-object
        >
        </v-select>
      </v-col>
      <v-col cols="4">
      <p>The selected Item is: {{ selectedCountry.name }}</p>
      <p>The selected Item is: {{ selectedState.name }}</p>
    </v-row>
<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      selectedCountry: [],
      selectedState: "",
      showScheduleForm: false,
      filteredStates: []
    };
  },

  computed: {
    ...mapState({
      countries: state => state.allCountries.countries,
      states: state => state.allCountries.states
    })
  },
  methods: {
    filterStates(country) {
      this.selectedState = "";
      this.filteredStates = this.states.filter(state => state.country_id === country.id);
    }
  },
  mounted() {
    this.$store.dispatch("allCountries/loadCountries");
    this.$store.dispatch("allCountries/loadStates");
  }
};
</script>


问:
how to access json via jquery
i have this json in my request

```<code>    $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity,
        function(data) {
            var standard_price     = data.standard_price;
            var professional_price = data.professional_price;
            var premium_price      = data.premium_price;
                        console.log(data);
                    $prettyCheckBox0.text(standard_price);
                    $prettyCheckBox1.text(professional_price);
                    $prettyCheckBox2.text(premium_price);
    });
</code>```

the problem is that the data.standard_price returns undefined but in the console.log i have this

```<code> "{"standard_price":"included","professional_price":"add $792.00","premium_price":"add $3372.00"}"
</code>```

whats the deal

答:
You should use $.parseJSON(string), like this:

```<code> $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity,
        function(data) {data = $.parseJSON(data);
            var standard_price     = data.standard_price;
            var professional_price = data.professional_price;
            var premium_price      = data.premium_price;
                        console.log(data);
                    $prettyCheckBox0.text(standard_price);
                    $prettyCheckBox1.text(professional_price);
                    $prettyCheckBox2.text(premium_price);
    });
</code>```

Another way is to use $.ajax an specify in dataType: 'json' see http://api.jquery.com/jQuery.ajax/

Title: how to access json via jquery

Body:
i have this json in my request

    $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity,
        function(data) {
            var standard_price     = data.standard_price;
            var professional_price = data.professional_price;
            var premium_price      = data.premium_price;
                        console.log(data);
                    $prettyCheckBox0.text(standard_price);
                    $prettyCheckBox1.text(professional_price);
                    $prettyCheckBox2.text(premium_price);
    });

the problem is that the data.standard_price returns undefined but in the console.log i have this

 "{"standard_price":"included","professional_price":"add $792.00","premium_price":"add $3372.00"}"

whats the deal

Body:
You should use $.parseJSON(string), like this:

 $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity,
        function(data) {data = $.parseJSON(data);
            var standard_price     = data.standard_price;
            var professional_price = data.professional_price;
            var premium_price      = data.premium_price;
                        console.log(data);
                    $prettyCheckBox0.text(standard_price);
                    $prettyCheckBox1.text(professional_price);
                    $prettyCheckBox2.text(premium_price);
    });

Another way is to use $.ajax an specify in dataType: 'json' see http://api.jquery.com/jQuery.ajax/


问:
Cannot access new Google Calendars created from the API using a Service account
We are using the Google Calendar API to create calendars and manage them on the behalf of the users.

For this, we create a calendar with an ACL rule like this:

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('/.../oauth_secret.json');
$client->setRedirectUri(REDIRECT_URI);
$client->authenticate($_GET['code']);
$accessToken = $client->getAccessToken();
$client->setAccessToken($accessToken);
$service = new Google_Service_Calendar($client);

$calendar = new Google_Service_Calendar_Calendar();
$calendar->setSummary($calendarName);
$calendar->setTimeZone('Europe/Paris');
$newCalendar = $service->calendars->insert($calendar);
$calendarId = $newCalendar->getId();

$rule = new Google_Service_Calendar_AclRule();
$scope = new Google_Service_Calendar_AclRuleScope();
$scope->setType("user");
$scope->setValue("295093256...012ulkk4oklusjh8...@developer.gserviceaccount.com");
$rule->setScope($scope);
$rule->setRole("owner");
$service->acl->insert($calendarId, $rule);
```

<p>Therefore we attempt to access the calendar like this:</p>

<pre class="lang-php prettyprint-override"><code>$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('/.../private_key.json');
if ($client->isAccessTokenExpired()) $client->refreshTokenWithAssertion();

$this->service = new Google_Service_Calendar(client);

$calendar = $service->calendarList->get($calendarId);
</code>```

Until a few months ago, this was working perfectly, but now we get this error:

google_runner error: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "Not Found"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}
```

It still works for calendars created before but not the new ones. I'm requesting help as I cannot find the reason why.

Note the ACL is properly created on the new calendars as you can see here:

Any idea?

答:
Found it!

Google does not automatically create anymore an entry to the user's calendar list when you create a calendar.

To check if the calendar exists, I just needed to replace:

```<code>$calendar = $service->calendarList->get($calendarId);
</code>```

By

```<code>$calendar = $service->calendars->get($calendarId);
</code>```

Body:
We are using the Google Calendar API to create calendars and manage them on the behalf of the users.

For this, we create a calendar with an ACL rule like this:

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('/.../oauth_secret.json');
$client->setRedirectUri(REDIRECT_URI);
$client->authenticate($_GET['code']);
$accessToken = $client->getAccessToken();
$client->setAccessToken($accessToken);
$service = new Google_Service_Calendar($client);

$calendar = new Google_Service_Calendar_Calendar();
$calendar->setSummary($calendarName);
$calendar->setTimeZone('Europe/Paris');
$newCalendar = $service->calendars->insert($calendar);
$calendarId = $newCalendar->getId();

$rule = new Google_Service_Calendar_AclRule();
$scope = new Google_Service_Calendar_AclRuleScope();
$scope->setType("user");
$scope->setValue("295093256...012ulkk4oklusjh8...@developer.gserviceaccount.com");
$rule->setScope($scope);
$rule->setRole("owner");
$service->acl->insert($calendarId, $rule);

Therefore we attempt to access the calendar like this:

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('/.../private_key.json');
if ($client->isAccessTokenExpired()) $client->refreshTokenWithAssertion();

$this->service = new Google_Service_Calendar(client);

$calendar = $service->calendarList->get($calendarId);

Until a few months ago, this was working perfectly, but now we get this error:

google_runner error: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "Not Found"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}

It still works for calendars created before but not the new ones. I'm requesting help as I cannot find the reason why.

Note the ACL is properly created on the new calendars as you can see here:

Any idea?

Body:
Found it!

Google does not automatically create anymore an entry to the user's calendar list when you create a calendar.

To check if the calendar exists, I just needed to replace:

$calendar = $service->calendarList->get($calendarId);

By

$calendar = $service->calendars->get($calendarId);


问:
How can we create asynchronous API in django?
I want to create a third party chatbot API which is asynchronous and replies "ok" after 10 seconds pause.

```<code>import time

def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    return wait()
</code>```

I have tried celery for the same as follows where I am waiting for celery response in view itself:

```<code>import time
from celery import shared_task

@shared_task
def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    a = wait.delay()
    work = AsyncResult(a.id)
    while True:
        if work.ready():
           return work.get(timeout=1)
</code>```

But this solution works synchronously and makes no difference. How can we make it asynchronous without asking our user to keep on requesting until the result is received?

答:
The best option is to use the futur async API, which will be proposed on Django in 3.1 release (which is already available in alpha)

https://docs.djangoproject.com/en/dev/releases/3.1/#asynchronous-views-and-middleware-support

(however, you will need to use an ASGI Web Worker to make it work properly)

Body:
I want to create a third party chatbot API which is asynchronous and replies "ok" after 10 seconds pause.

import time

def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    return wait()

I have tried celery for the same as follows where I am waiting for celery response in view itself:

import time
from celery import shared_task

@shared_task
def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    a = wait.delay()
    work = AsyncResult(a.id)
    while True:
        if work.ready():
           return work.get(timeout=1)

But this solution works synchronously and makes no difference. How can we make it asynchronous without asking our user to keep on requesting until the result is received?


问:
Unstacking a column into several columns with differing number of rows
I have a data frame with two columns:

```<code>dat_test <- data.frame(code     = c("A", "A", "A", "A", "B", "B", "B", "C", "C"),
                       response = c("A", "AA", "AB", "ABC", "BC", "AB", "B", "CDE", "BC"),
                       stringsAsFactors = FALSE)

dat_test

  code response  n
1    A        A 69
2    A       AA 85
3    A       AB 10
4    A      ABC 87
5    B       BC  3
6    B       AB 79
7    B        B 50
8    C      CDE 81
9    C       BC 32
</code>```

I now want to unstack/pivot_wider this data in a way (ideally in the tidyverse), where the code column is reshaped into three columns and rows would just be values from the response column. There is no logical link between the three codes, i.e. there is no identifier that would tell me which response of code "A" would belong to the same row for code "B" and "C", respectively.

So basically I just want three columns that lists all the responses as rows with everything else filled as NAs.

I tried tidyr's pivot_wider, but failed. I saw that there are some parameters in the pivot_wider function, likes values_fill and values_fn, but I don#t know if I could use these to get the desired behaviour.

Expected outcome would be:

```<code># A tibble: 4 x 3
  A     B     C
  <chr> <chr> <chr>
1 A     BC    CDE
2 AA    AB    BC
3 AB    B     NA
4 ABC   NA    NA
</code>```

Any ideas?

I guess I could first create an additional id column that goes from 1:4 for code "A", 1:3 for code "B" and 1:2 for code "C", but not sure how I could do this dynamically for any other data set (i.e. with a different number of codes and responses per code). But once I have such an id column, the pivoting should work.

答:
You gave me the answer yourself. :)

```<code>answer <- dat_test %>%
            group_by(code) %>%
            mutate(id=row_number()) %>%
            pivot_wider(names_from=code, values_from=response) %>%
            ungroup()
</code>```

Gives

```<code># A tibble: 4 x 4
     id A     B     C
  <int> <chr> <chr> <chr>
1     1 A     BC    CDE
2     2 AA    AB    BC
3     3 AB    B     NA
4     4 ABC   NA    NA
</code>```

Body:
I have a data frame with two columns:

dat_test <- data.frame(code     = c("A", "A", "A", "A", "B", "B", "B", "C", "C"),
                       response = c("A", "AA", "AB", "ABC", "BC", "AB", "B", "CDE", "BC"),
                       stringsAsFactors = FALSE)

dat_test

  code response  n
1    A        A 69
2    A       AA 85
3    A       AB 10
4    A      ABC 87
5    B       BC  3
6    B       AB 79
7    B        B 50
8    C      CDE 81
9    C       BC 32

I now want to unstack/pivot_wider this data in a way (ideally in the tidyverse), where the code column is reshaped into three columns and rows would just be values from the response column. There is no logical link between the three codes, i.e. there is no identifier that would tell me which response of code "A" would belong to the same row for code "B" and "C", respectively.

So basically I just want three columns that lists all the responses as rows with everything else filled as NAs.

I tried tidyr's pivot_wider, but failed. I saw that there are some parameters in the pivot_wider function, likes values_fill and values_fn, but I don#t know if I could use these to get the desired behaviour.

Expected outcome would be:

# A tibble: 4 x 3
  A     B     C
  <chr> <chr> <chr>
1 A     BC    CDE
2 AA    AB    BC
3 AB    B     NA
4 ABC   NA    NA

Any ideas?

I guess I could first create an additional id column that goes from 1:4 for code "A", 1:3 for code "B" and 1:2 for code "C", but not sure how I could do this dynamically for any other data set (i.e. with a different number of codes and responses per code). But once I have such an id column, the pivoting should work.

Body:
You gave me the answer yourself. :)

answer <- dat_test %>%
            group_by(code) %>%
            mutate(id=row_number()) %>%
            pivot_wider(names_from=code, values_from=response) %>%
            ungroup()

Gives

# A tibble: 4 x 4
     id A     B     C
  <int> <chr> <chr> <chr>
1     1 A     BC    CDE
2     2 AA    AB    BC
3     3 AB    B     NA
4     4 ABC   NA    NA


问:
how do I grep through a mysql database?
Looking for a nifty helper function/method for grepping through all defined tables, columns, stored procedures, etc, for a MySql database.

I had something similar for SQL Server.

答: mysqldump --compact --skip-extended-insert -u root -proot mydb | grep "interesting string"

OwnerDisplayName: someguy

Title: how do I grep through a mysql database?


问:
docker: executable file not found in $PATH": unknown
Using AWS instance based on ubuntu 18.04, Docker version 19.03.10, build 9424aeaee9.
I got the following error:

```<code>docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"python\": executable file not found in $PATH": unknown.
</code>```

after trying to execute the code:

```<code>docker run --name test1 c73eada5a5fa
</code>```

where "c73eada5a5fa" is my container id after being built using:

```<code>sudo docker build -t my_username/repository .
</code>```

Here is my docker:

```<code>FROM ubuntu:18.04
COPY . /PFE_exec
CMD ["make", "PFE_exec"]
CMD ["sudo","apt","install","unzip"]
CMD ["echo","requirements installed!"]
CMD ["unzip","home/ubuntu/PFE/aa.zip"]
CMD ["python","home/ubuntu/PFE/test.py"]
CMD ["python","home/ubuntu/PFE/test2.py"]
CMD ["python","home/ubuntu/PFE/test3.py"]
</code>```

Using python3 instead of python doesn't resolve the problem as well.
I don't understand where is the problem.
Any help?
Thank you in advance!

答:
There is no python or python3 pre-installed in ubuntu:18.04 image, if you want to use python in your Docker, you probably want to change your base image to python image, e.g. FROM python:3.

Besides, in your Dockerfile, there should be only one CMD, what you need is RUN instruction instead of CMD.

Body:
Using AWS instance based on ubuntu 18.04, Docker version 19.03.10, build 9424aeaee9.
I got the following error:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"python\": executable file not found in $PATH": unknown.

after trying to execute the code:

docker run --name test1 c73eada5a5fa

where "c73eada5a5fa" is my container id after being built using:

sudo docker build -t my_username/repository .

Here is my docker:

FROM ubuntu:18.04
COPY . /PFE_exec
CMD ["make", "PFE_exec"]
CMD ["sudo","apt","install","unzip"]
CMD ["echo","requirements installed!"]
CMD ["unzip","home/ubuntu/PFE/aa.zip"]
CMD ["python","home/ubuntu/PFE/test.py"]
CMD ["python","home/ubuntu/PFE/test2.py"]
CMD ["python","home/ubuntu/PFE/test3.py"]

Using python3 instead of python doesn't resolve the problem as well.
I don't understand where is the problem.
Any help?
Thank you in advance!


问:
SwiftUI Representable TextField changes Font on disappear
I am using a Representable ViewController for a custom NSTextField in SwiftUI for MacOS. I am applying a customized, increased font size for that TextField. That works fine, I had a question regarding that topic in my last question here.

I am setting the Font of the TextField in my viewDidAppear() method now, which works fine. I can see a bigger font. The problem is now, when my view is not being in focus, the text size is shrinking back to normal. When I go back and activate the window again, I see the small font size. When I type again, it gets refreshed and I see the correct font size.

That is my code I am using:

```<code>class AddTextFieldController: NSViewController {
    @Binding var text: String
    let textField = NSTextField()
    var isFirstResponder : Bool = true

    init(text: Binding<String>, isFirstResponder : Bool = true) {
        self._text = text
        textField.font = NSFont.userFont(ofSize: 16.5)
        super.init(nibName: nil, bundle: nil)
        NSLog("init")
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        textField.delegate = self
        //textField.font = NSFont.userFont(ofSize: 16.5)
        self.view = textField
    }

    override func viewDidAppear() {
        self.view.window?.makeFirstResponder(self.view)
        textField.font = NSFont.userFont(ofSize: 16.5)
    }
}

extension AddTextFieldController: NSTextFieldDelegate {

  func controlTextDidChange(_ obj: Notification) {
    if let textField = obj.object as? NSTextField {
      self.text = textField.stringValue
    }
    textField.font = NSFont.userFont(ofSize: 16.5)

  }
}
</code>```

And this is the representable:

```<code>struct AddTextFieldRepresentable: NSViewControllerRepresentable {

  @Binding var text: String

  func makeNSViewController(
    context: NSViewControllerRepresentableContext<AddTextFieldRepresentable>
  ) -> AddTextFieldController {
    return AddTextFieldController(text: $text)
  }

  func updateNSViewController(
    _ nsViewController: AddTextFieldController,
    context: NSViewControllerRepresentableContext<AddTextFieldRepresentable>
  ) {
    }
}
</code>```

Here is a demo:

I thought about using Notification when the view is coming back, however not sure

```<code>NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: NSApplication.willBecomeActiveNotification, object: nil)
</code>```

答:
Here is a solution. Tested with Xcode 11.4 / macOS 10.15.4

```<code>class AddTextFieldController: NSViewController {
    @Binding var text: String
    let textField = MyTextField()  // << overridden field
</code>```

and required custom classes (both!!) for cell & control (in all other places just remove user font usage as not needed any more):

```<code>class MyTextFieldCell: NSTextFieldCell {
    override var font: NSFont? {
        get {
            return super.font
        }
        set {
            // system tries to reset font to default several
            // times (here!), so don't allow that
            super.font = NSFont.userFont(ofSize: 16.5)
        }
    }
}

class MyTextField: NSTextField {
    override class var cellClass: AnyClass? {
        get { MyTextFieldCell.self }
        set {}
    }

    override var font: NSFont? {
        get {
            return super.font
        }
        set {
            // system tries to reset font to default several
            // times (and here!!), so don't allow that
            super.font = NSFont.userFont(ofSize: 16.5)
        }
    }
}
</code>```

Body:
I am using a Representable ViewController for a custom NSTextField in SwiftUI for MacOS. I am applying a customized, increased font size for that TextField. That works fine, I had a question regarding that topic in my last question here.

I am setting the Font of the TextField in my viewDidAppear() method now, which works fine. I can see a bigger font. The problem is now, when my view is not being in focus, the text size is shrinking back to normal. When I go back and activate the window again, I see the small font size. When I type again, it gets refreshed and I see the correct font size.

That is my code I am using:

class AddTextFieldController: NSViewController {
    @Binding var text: String
    let textField = NSTextField()
    var isFirstResponder : Bool = true

    init(text: Binding<String>, isFirstResponder : Bool = true) {
        self._text = text
        textField.font = NSFont.userFont(ofSize: 16.5)
        super.init(nibName: nil, bundle: nil)
        NSLog("init")
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        textField.delegate = self
        //textField.font = NSFont.userFont(ofSize: 16.5)
        self.view = textField
    }

    override func viewDidAppear() {
        self.view.window?.makeFirstResponder(self.view)
        textField.font = NSFont.userFont(ofSize: 16.5)
    }
}

extension AddTextFieldController: NSTextFieldDelegate {

  func controlTextDidChange(_ obj: Notification) {
    if let textField = obj.object as? NSTextField {
      self.text = textField.stringValue
    }
    textField.font = NSFont.userFont(ofSize: 16.5)

  }
}

And this is the representable:

struct AddTextFieldRepresentable: NSViewControllerRepresentable {

  @Binding var text: String

  func makeNSViewController(
    context: NSViewControllerRepresentableContext<AddTextFieldRepresentable>
  ) -> AddTextFieldController {
    return AddTextFieldController(text: $text)
  }

  func updateNSViewController(
    _ nsViewController: AddTextFieldController,
    context: NSViewControllerRepresentableContext<AddTextFieldRepresentable>
  ) {
    }
}

Here is a demo:

I thought about using Notification when the view is coming back, however not sure

NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: NSApplication.willBecomeActiveNotification, object: nil)

Body:
Here is a solution. Tested with Xcode 11.4 / macOS 10.15.4

class AddTextFieldController: NSViewController {
    @Binding var text: String
    let textField = MyTextField()  // << overridden field

and required custom classes (both!!) for cell & control (in all other places just remove user font usage as not needed any more):

class MyTextFieldCell: NSTextFieldCell {
    override var font: NSFont? {
        get {
            return super.font
        }
        set {
            // system tries to reset font to default several
            // times (here!), so don't allow that
            super.font = NSFont.userFont(ofSize: 16.5)
        }
    }
}

class MyTextField: NSTextField {
    override class var cellClass: AnyClass? {
        get { MyTextFieldCell.self }
        set {}
    }

    override var font: NSFont? {
        get {
            return super.font
        }
        set {
            // system tries to reset font to default several
            // times (and here!!), so don't allow that
            super.font = NSFont.userFont(ofSize: 16.5)
        }
    }
}


问:
Python - count number of elements that are equal between two columns of two dataframes
I have two dataframes: df1, df2
that contain two columns, col1 and col2. I would like to calculate the number of elements in column col1 of df1 that are equal to col2 of df2. How can I do that?

答:
I assume you're using pandas.

One way is to simply use pd.merge and merge on the second column, and return the length of that column.

```<code>pd.merge(df1, df2, on="column_to_merge")
</code>```

Pandas does an inner merge by default.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

Body:
I assume you're using pandas.

One way is to simply use pd.merge and merge on the second column, and return the length of that column.

pd.merge(df1, df2, on="column_to_merge")

Pandas does an inner merge by default.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html


问:
Return a 2D Cython pointer to Python array
I am currently passing from Cython to C the following pointer of a pointer:

```<code>    #convert the input Python 2D array to a memory view
    cdef double[:,:] a_cython= np.asarray(a,order="C")
    #define a pointer of a pointer with dimensions of a
    cdef double** point_to_a = <double **>malloc(N * sizeof(double*))
    #initialize the pointer
    if not point_to_a: raise MemoryError
    #try:
    for i in range(N):
        point_to_a[i] = &a_cython[i, 0]

    #pass this double pointer to a C function
    logistic_sigmoid(&point_to_a[0], N,M)
</code>```

where a is a numpy array, whose dimensions are N x M, point_to_a is a Cython pointer of a pointer which is referring to Cython memoryview a_cython. Since the input a from Python is 2 dimensional array, I thought this was the best approach to pass the info directly to C.
The passage goes smoothly and the computation is done correctly. However, I am trying now to re-convert back point_to_a to a numpy array, but I am struggling a bit.

I am considering various solutions. I would like to explore if it's possible to keep a N dimensional array throughout the entire process, thus I was experimenting with this approach in Cython:

```<code>    #define a integer array for dimensions
    cdef np.npy_intp dims[2]
    dims[0]=  N
    dims[1] = M
    #create a new memory view and PyArray_SimpleNewFromData to deal with the pointer
    cdef np.ndarray[double, ndim=2] new_a =  np.PyArray_SimpleNewFromData(2, &dims[0], np.NPY_DOUBLE, point_to_a)
</code>```

however, when I am converting new_a to a np.array as array = np.asarray(new_a) I have an array with 0s only.
Do you have any ideas?

Thanks very much

答:
As soon as you use int** (or similar) your data is in so-called indirect memory layout. Cython's typed memory views support indirect memory layout (see for example Cython: understanding a typed memoryview with a indirect_contignuous memory layout), however there are not so many classes implementing this interface.

Numpy's ndarrays do not implement indirect memory layout - they only support direct memory layouts (e.g. pointer of type int* and not int**), so passing an int** to a numpy array will do no good.

The good thing is, that because you share the memory with a_cython, the values were already updated in-place. You can get the underlying numpy array by returning the base-object of the typed memory view, i.e.

```<code>return a_cython.base # returns 2d-numpy array.
</code>```

there is no need to copy memory at all!

There are however some issues with memory management (e.g. you need to free point_to_a).

This is maybe an overkill in your case, but I use the opportunity to shamelessly plug-in a library of mine indirect_buffer: Because alternatives for indirect memory layout buffers are scarce and from time to time one needs one, I've create one to avoid writing always the same code.

With indirect_buffer your function could look like following:

```<code>%%cython
#just an example for a c-function
cdef extern from *:
    """
    void fillit(int** ptr, int N, int M){
       int cnt=0;
       for(int i=0;i<N;i++){
          for(int j=0;j<M;j++){
            ptr[i][j]=cnt++;
          }
       }
    }
    """
    void fillit(int** ptr, int N, int M)

from indirect_buffer.buffer_impl cimport IndirectMemory2D
def py_fillit(a):
    #create collection, it is a view of a
    indirect_view=IndirectMemory2D.cy_view_from_rows(a, readonly=False)
    fillit(<int**>indirect_view.ptr, indirect_view.shape[0], indirect_view.shape[1])
    # values are updated directly in a
</code>```

which now can be used, for example:

```<code>import numpy as np
a=np.zeros((3,4), dtype=np.int32)
py_fillit(a)
print(a)
# prints as expected:
#  array([[ 0,  1,  2,  3],
#         [ 4,  5,  6,  7],
#         [ 8,  9, 10, 11]])
</code>```

The above version does a lot of things right: memory management, locking of buffers and so on.

Body:
I am currently passing from Cython to C the following pointer of a pointer:

    #convert the input Python 2D array to a memory view
    cdef double[:,:] a_cython= np.asarray(a,order="C")
    #define a pointer of a pointer with dimensions of a
    cdef double** point_to_a = <double **>malloc(N * sizeof(double*))
    #initialize the pointer
    if not point_to_a: raise MemoryError
    #try:
    for i in range(N):
        point_to_a[i] = &a_cython[i, 0]

    #pass this double pointer to a C function
    logistic_sigmoid(&point_to_a[0], N,M)

where a is a numpy array, whose dimensions are N x M, point_to_a is a Cython pointer of a pointer which is referring to Cython memoryview a_cython. Since the input a from Python is 2 dimensional array, I thought this was the best approach to pass the info directly to C.
The passage goes smoothly and the computation is done correctly. However, I am trying now to re-convert back point_to_a to a numpy array, but I am struggling a bit.

I am considering various solutions. I would like to explore if it's possible to keep a N dimensional array throughout the entire process, thus I was experimenting with this approach in Cython:

    #define a integer array for dimensions
    cdef np.npy_intp dims[2]
    dims[0]=  N
    dims[1] = M
    #create a new memory view and PyArray_SimpleNewFromData to deal with the pointer
    cdef np.ndarray[double, ndim=2] new_a =  np.PyArray_SimpleNewFromData(2, &dims[0], np.NPY_DOUBLE, point_to_a)

however, when I am converting new_a to a np.array as array = np.asarray(new_a) I have an array with 0s only.
Do you have any ideas?

Thanks very much

Body:
As soon as you use int** (or similar) your data is in so-called indirect memory layout. Cython's typed memory views support indirect memory layout (see for example Cython: understanding a typed memoryview with a indirect_contignuous memory layout), however there are not so many classes implementing this interface.

Numpy's ndarrays do not implement indirect memory layout - they only support direct memory layouts (e.g. pointer of type int* and not int**), so passing an int** to a numpy array will do no good.

The good thing is, that because you share the memory with a_cython, the values were already updated in-place. You can get the underlying numpy array by returning the base-object of the typed memory view, i.e.

return a_cython.base # returns 2d-numpy array.

there is no need to copy memory at all!

There are however some issues with memory management (e.g. you need to free point_to_a).

This is maybe an overkill in your case, but I use the opportunity to shamelessly plug-in a library of mine indirect_buffer: Because alternatives for indirect memory layout buffers are scarce and from time to time one needs one, I've create one to avoid writing always the same code.

With indirect_buffer your function could look like following:

%%cython
#just an example for a c-function
cdef extern from *:
    """
    void fillit(int** ptr, int N, int M){
       int cnt=0;
       for(int i=0;i<N;i++){
          for(int j=0;j<M;j++){
            ptr[i][j]=cnt++;
          }
       }
    }
    """
    void fillit(int** ptr, int N, int M)

from indirect_buffer.buffer_impl cimport IndirectMemory2D
def py_fillit(a):
    #create collection, it is a view of a
    indirect_view=IndirectMemory2D.cy_view_from_rows(a, readonly=False)
    fillit(<int**>indirect_view.ptr, indirect_view.shape[0], indirect_view.shape[1])
    # values are updated directly in a

which now can be used, for example:

import numpy as np
a=np.zeros((3,4), dtype=np.int32)
py_fillit(a)
print(a)
# prints as expected:
#  array([[ 0,  1,  2,  3],
#         [ 4,  5,  6,  7],
#         [ 8,  9, 10, 11]])

The above version does a lot of things right: memory management, locking of buffers and so on.


问:
How to add ref to a react styled component div using react and typescript?
i want to add ref to styled component div.

My code is like below,

```<code>const DragAndDrop: React.FC<any> = props => {
    const div_ref= React.createRef();
    return (
        <Zone ref={div_ref}/>
    );
}
</code>```

But this gives me error

Type RefObject  is not assignable to type {instance: htmlDivElement || null} => void || refObject|| null || undefined

could someone help me fix this. thanks.

答:
If you are working with functional components, you should be using the useRef hook instead, and initialise it with a value of null.

```<code>const DragAndDrop: React.FC<any> = (props) => {
  const div_ref= useRef(null);

  return (
    <Zone ref={div_ref}/>
  );
}
</code>```

In addition, try not to use any for the type genetic parameter of your component.

Body:
i want to add ref to styled component div.

My code is like below,

const DragAndDrop: React.FC<any> = props => {
    const div_ref= React.createRef();
    return (
        <Zone ref={div_ref}/>
    );
}

But this gives me error

Type RefObject  is not assignable to type {instance: htmlDivElement || null} => void || refObject|| null || undefined

could someone help me fix this. thanks.

Body:
If you are working with functional components, you should be using the useRef hook instead, and initialise it with a value of null.

const DragAndDrop: React.FC<any> = (props) => {
  const div_ref= useRef(null);

  return (
    <Zone ref={div_ref}/>
  );
}

In addition, try not to use any for the type genetic parameter of your component.


问:
Simple Framework Mechanics
I'm building a simple framework and hoping it will help me better understand OOP. Well, I've come across my first hurdle.

I'm naturally using MVC pattern and I have a user model. I then have a 'table' which manages the collection of user objects. I have an abstract model and table. Similar to Zend Framework layout.

Anyway, I'm now wondering what is the best way to execute a query? I have a database object which manages the database layer. Currently using mysqli object.

Trouble is my connection is a member of my application object, how do I access that from within my table object to execute a query? I obviously can't create a new object because that will connect to the database again. I need to reuse this same db object.

Any ideas? I understand if this isn't optimal design. Right now I'm just looking for advice.

Edit: Should I just use Doctrine?

答:
you should add such dependencies in constructor.

You are able to use a static db object too, but especially for a framework like project this will get you to hell, if you try to add unit-tests or you want to refactor.

In named Patterns, you want to use dependency injection for this

Title: Simple Framework Mechanics


问:
MSVC 2019: "the size of an array must be greater than zero"
I have migrated a (working) older project into MSVC 2019 using its .dsw file.
That appeared to go fine but I get the error message (shown in title) upon build.
The error occurred in "winnt.h".
Note: I have not declared any zero-length arrays.

How do I fix this?

答:
Despite the completely misleading error message, the problem has nothing to do with a zero-size array. Rather it is a struct packing issue.  To fix this:

Solution #1

Add the following line before including windows.h

```<code>  #define WINDOWS_IGNORE_PACKING_MISMATCH
  #include <windows.h>
</code>```

Solution #2

Change the packing in your project using

Project -> Properties -> C/C++ -> CodeGeneration ->
Struct Member Alignment = "8 Bytes"

Body:
Despite the completely misleading error message, the problem has nothing to do with a zero-size array. Rather it is a struct packing issue.  To fix this:

Solution #1

Add the following line before including windows.h

  #define WINDOWS_IGNORE_PACKING_MISMATCH
  #include <windows.h>

Solution #2

Change the packing in your project using

Project -> Properties -> C/C++ -> CodeGeneration ->
Struct Member Alignment = "8 Bytes"


问:
Null pointer exception trying to invoke onClick method from custom Adapter
I was trying to write own adapter class in Android Studio which looks something like this:

```<code>public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>{

    private List<Article> articles;
    private Context context;
    private OnItemClickListener onItemClickListener;

    public Adapter(List<Article> articles, Context context) {
        this.articles = articles;
        this.context = context;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements  View.OnClickListener {

        TextView title, desc, author, published_ad, source, time;
        ImageView imageView;
        ProgressBar progressBar;
        OnItemClickListener onItemClickListener;

        public MyViewHolder(View itemView, OnItemClickListener onItemClickListener) {

            super(itemView);

            itemView.setOnClickListener(this);
            title = itemView.findViewById(R.id.title);
            desc = itemView.findViewById(R.id.decs);
            author = itemView.findViewById(R.id.author);
            published_ad = itemView.findViewById(R.id.publishedAt);
            source = itemView.findViewById(R.id.source);
            time = itemView.findViewById(R.id.time);
            imageView = itemView.findViewById(R.id.img);
            progressBar = itemView.findViewById(R.id.progress_load_photo);

            this.onItemClickListener = onItemClickListener;

        }

        @Override
        public void onClick(View v) {
            onItemClickListener.onItemClick(v, getAdapterPosition());
        }
    }
}

</code>```

And the class in which I use my Adapter looks like this:

```<code>    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setNestedScrollingEnabled(false);

        adapter = new Adapter(articles, getActivity().getApplicationContext());
        recyclerView.setAdapter(adapter);
        LoadJson();

        return view;
    }

</code>```

I am getting an error about null pointer exception: "Attempt to invoke interface method 'void com.example.app2.Adapter$OnItemClickListener.onItemClick(android.view.View, int)' on a null object reference"

答:
Your field Adapter.onItemClickListener is null until you set it up (what you never do in your actual code)

So you should test if there is a listener before trying to notify it.

@Override
public void onClick(View v) {
    if (onItemClickListener != null)
        onItemClickListener.onItemClick(v, getAdapterPosition());
}
```

<p>And I guess you would use it in your <code>onCreateView</code> method :)</p>

<pre class="lang-java prettyprint-override"><code>adapter = new Adapter(articles, getActivity().getApplicationContext());
adapter.setOnItemClickListener(() -> { System.out.println("Click !") });
recyclerView.setAdapter(adapter);
</code>```

Body:
I was trying to write own adapter class in Android Studio which looks something like this:

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>{

    private List
 articles;
    private Context context;
    private OnItemClickListener onItemClickListener;

    public Adapter(List
 articles, Context context) {
        this.articles = articles;
        this.context = context;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements  View.OnClickListener {

        TextView title, desc, author, published_ad, source, time;
        ImageView imageView;
        ProgressBar progressBar;
        OnItemClickListener onItemClickListener;

        public MyViewHolder(View itemView, OnItemClickListener onItemClickListener) {

            super(itemView);

            itemView.setOnClickListener(this);
            title = itemView.findViewById(R.id.title);
            desc = itemView.findViewById(R.id.decs);
            author = itemView.findViewById(R.id.author);
            published_ad = itemView.findViewById(R.id.publishedAt);
            source = itemView.findViewById(R.id.source);
            time = itemView.findViewById(R.id.time);
            imageView = itemView.findViewById(R.id.img);
            progressBar = itemView.findViewById(R.id.progress_load_photo);

            this.onItemClickListener = onItemClickListener;

        }

        @Override
        public void onClick(View v) {
            onItemClickListener.onItemClick(v, getAdapterPosition());
        }
    }
}

And the class in which I use my Adapter looks like this:

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setNestedScrollingEnabled(false);

        adapter = new Adapter(articles, getActivity().getApplicationContext());
        recyclerView.setAdapter(adapter);
        LoadJson();

        return view;
    }

I am getting an error about null pointer exception: "Attempt to invoke interface method 'void com.example.app2.Adapter$OnItemClickListener.onItemClick(android.view.View, int)' on a null object reference"

Body:
Your field Adapter.onItemClickListener is null until you set it up (what you never do in your actual code)

So you should test if there is a listener before trying to notify it.

@Override
public void onClick(View v) {
    if (onItemClickListener != null)
        onItemClickListener.onItemClick(v, getAdapterPosition());
}

And I guess you would use it in your onCreateView method :)

adapter = new Adapter(articles, getActivity().getApplicationContext());
adapter.setOnItemClickListener(() -> { System.out.println("Click !") });
recyclerView.setAdapter(adapter);


问:
Getting errors on creating new project using command 'ng new <project_name>' after upgrading to version 9
Please find the stack over here...

Installing packages...npm WARN deprecated tslint@6.1.2: TSLint has been deprecated in favor of ESLint. Please see https://github.com/palantir/tslint/issues/4534 for more information.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated fsevents@1.2.12: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm ERR! Unexpected end of JSON input while parsing near '...iERRHPyU8nBqZB1+iv2Uh'

答:
I had the same Issue and Following steps worked for me.

Delete npm-cache in AppData/Roaming

Reinstall the angular cli by 'npm install -g @angular/cli'

Then Create the project


问:
Why does mysql_query() return TRUE with a SELECT statement?
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

```<code>if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}
</code>```

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

答:
You haven't mentioned data lengths but you should check to see if this is called by an exceeding of max_allowed_packet.

When a MySQL client or the mysqld
  server receives a packet bigger than
  max_allowed_packet bytes, it issues a
  Packet too large error and closes the
  connection. With some clients, you may
  also get a Lost connection to MySQL
  server during query error if the
  communication packet is too large.

[...]

Both the client and the server have
  their own max_allowed_packet variable,
  so if you want to handle big packets,
  you must increase this variable both
  in the client and in the server.

http://dev.mysql.com/doc/refman/5.5/en/packet-too-large.html

Not sure how mysql_query return value is affected by this but it's worth investigating. Setting it in my.cnf to see if it fixes the problem would be the best place to start.

Body:
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...


问:
QueryDSL intersection with Spring Boot Data JPA
I am using QueryDSL within a Spring Boot, Spring Data JPA project.
I have the following schema for a table called test:

| id | key  | value |
|----|------|-------|
| 1  | test | hello |
| 1  | test | world |
| 2  | test | hello |
| 2  | foo  | bar   |
| 3  | test | hello |
| 3  | test | world |
```

<p>Now I want to write the following SQL in QueryDSL:</p>

<pre class="lang-sql prettyprint-override"><code>select id from test where key = 'test' and value = 'hello'
INTERSECT
select id from test where key = 'test' and value = 'world'
</code>```

Which would give me all ids where key is 'test' and values are 'hello' and 'world'.

I did not find any way of declaring this kind of SQL in QueryDSL yet. I am able to write the two select statements but then I am stuck at combining them with an INTERSECT.

JPAQueryFactory queryFactory = new JPAQueryFactory(em); // em is an EntityManager

QTestEntity qTestEntity = QTestEntity.testEntity;

var q1 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("hello")));
var q2 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("world")));;
```

<p>In the end I want to retrieve a list of ids which match the given query. In general the amount of intersects can be something around 20 or 30, depending on the number of key/value-pairs I want to search for. </p>

<p>Does anyone know a way how to do something like this with QueryDSL ? </p>

<p>EDIT: </p>

<p>Assume the following schema now, with two tables: <code>test</code> and 'user':</p>

<pre class="lang-none prettyprint-override"><code>test:

| userId  | key  | value |
|---------|------|-------|
| 1       | test | hello |
| 1       | test | world |
| 2       | test | hello |
| 2       | foo  | bar   |
| 3       | test | hello |
| 3       | test | world |

user:

| id | name     |
|----|----------|
| 1  | John     |
| 2  | Anna     |
| 3  | Felicita |
</code>```

The correspond java classes look like this. TestEntity has a composite key consisting of all of its properties.

@Entity
public class TestEntity {
    @Id
    @Column(name = "userId", nullable = false)
    private String pubmedId;

    @Id
    @Column(name = "value", nullable = false)
    private String value;

    @Id
    @Column(name = "key", nullable = false)
    private String key;
}

@Entity
class User {
  @Id
  private int id;

  private String name;

  @ElementCollection
  private Set<TestEntity> keyValues;
}
```

How can I map the test table to the keyValues properties within the User class?

答:
In this case I'd probably just use an OR expression:

```<code>queryFactory
    .query()
    .from(qTestEntity) .select(qTestEntity.id)
    .where(qTestEntity.key("test").and(
        qTestEntity.value.eq("hello")
       .or(qTestEntity.value.eq("world")));
</code>```

However, you specifically mention wanting to use a set operation. I by the way think you want to perform an UNION operation instead of an INSERSECT operation, because the latter one would be empty with the example given.

JPA doesn't support set operations such as defined in ANSI SQL. However, Blaze-Persistence is an extension that integrates with most JPA implementations and does extend JPQL with set operations. I have recently written a QueryDSL extension for Blaze-Persistence. Using that extension, you can do:

```<code>List<Document> documents = new BlazeJPAQuery<Document>(entityManager, cbf)
    .union(
         select(document).from(document).where(document.id.eq(41L)),
         select(document).from(document).where(document.id.eq(42L))
    ).fetch();
</code>```

For more information about the integration and how to set it up, the documentation is available at https://persistence.blazebit.com/documentation/1.5/core/manual/en_US/index.html#querydsl-integration

Body:
I am using QueryDSL within a Spring Boot, Spring Data JPA project.
I have the following schema for a table called test:

| id | key  | value |
|----|------|-------|
| 1  | test | hello |
| 1  | test | world |
| 2  | test | hello |
| 2  | foo  | bar   |
| 3  | test | hello |
| 3  | test | world |

Now I want to write the following SQL in QueryDSL:

select id from test where key = 'test' and value = 'hello'
INTERSECT
select id from test where key = 'test' and value = 'world'

Which would give me all ids where key is 'test' and values are 'hello' and 'world'.

I did not find any way of declaring this kind of SQL in QueryDSL yet. I am able to write the two select statements but then I am stuck at combining them with an INTERSECT.

JPAQueryFactory queryFactory = new JPAQueryFactory(em); // em is an EntityManager

QTestEntity qTestEntity = QTestEntity.testEntity;

var q1 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("hello")));
var q2 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("world")));;

In the end I want to retrieve a list of ids which match the given query. In general the amount of intersects can be something around 20 or 30, depending on the number of key/value-pairs I want to search for.

Does anyone know a way how to do something like this with QueryDSL ?

EDIT:

Assume the following schema now, with two tables: test and 'user':

test:

| userId  | key  | value |
|---------|------|-------|
| 1       | test | hello |
| 1       | test | world |
| 2       | test | hello |
| 2       | foo  | bar   |
| 3       | test | hello |
| 3       | test | world |

user:

| id | name     |
|----|----------|
| 1  | John     |
| 2  | Anna     |
| 3  | Felicita |

The correspond java classes look like this. TestEntity has a composite key consisting of all of its properties.

@Entity
public class TestEntity {
    @Id
    @Column(name = "userId", nullable = false)
    private String pubmedId;

    @Id
    @Column(name = "value", nullable = false)
    private String value;

    @Id
    @Column(name = "key", nullable = false)
    private String key;
}

@Entity
class User {
  @Id
  private int id;

  private String name;

  @ElementCollection
  private Set<TestEntity> keyValues;
}

How can I map the test table to the keyValues properties within the User class?

Body:
In this case I'd probably just use an OR expression:

queryFactory
    .query()
    .from(qTestEntity) .select(qTestEntity.id)
    .where(qTestEntity.key("test").and(
        qTestEntity.value.eq("hello")
       .or(qTestEntity.value.eq("world")));

However, you specifically mention wanting to use a set operation. I by the way think you want to perform an UNION operation instead of an INSERSECT operation, because the latter one would be empty with the example given.

JPA doesn't support set operations such as defined in ANSI SQL. However, Blaze-Persistence is an extension that integrates with most JPA implementations and does extend JPQL with set operations. I have recently written a QueryDSL extension for Blaze-Persistence. Using that extension, you can do:

List<Document> documents = new BlazeJPAQuery<Document>(entityManager, cbf)
    .union(
         select(document).from(document).where(document.id.eq(41L)),
         select(document).from(document).where(document.id.eq(42L))
    ).fetch();

For more information about the integration and how to set it up, the documentation is available at https://persistence.blazebit.com/documentation/1.5/core/manual/en_US/index.html#querydsl-integration


问:
Login status in React

I created authorization in javascript. Then if success login I redirect to React project with url parameter http://localhost:3000/?phoneNum=%2B77072050399

Then in React I get userId by using the passed url parameter => phoneNumber using axios.

I realized it in App.js. Code below:

```<code>let url = window.location.href;
    let params = (new URL(url)).searchParams;
    const userPhoneNum = encodeURIComponent(params.get('phoneNum'));

    const [userToken, setUserToken] = useState(null);
    const getUserToken = async() => {
        try {
            const data = await axios
                .get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
                .then(response => {
                    setUserToken(response.data);
                })
                .catch(function(error) {
                    console.log('No such user! Error in getting token!');
                });
        } catch (e) {
            console.log(e);
        }
    }

    useEffect(() => {
        getUserToken();
        console.log(userToken);
    }, userToken);
</code>```

So, when I go to next page localhost:3000/places, it is requesting for userToken again with parameter null, because there is no param phoneNum.

How to make it to request only one time and save the userId after it is taken in main page. So, then only when I click LogOut button reset the variable where userID is saved.

答:
If you want to do that without using any third party libraries you can use browser's in built storage api

So, when you receive the token, you can store that in the local storage of the browser using localstorage.setItem and later when you wan to see if the token is there or not just read from there using localStorage.getItem

```<code> const getUserToken = async() => {
            try {
                const data = await axios
                    .get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
                    .then(response => {
                        setUserToken(response.data);
                        Storage.setItem('token',JSON.stringify(response.data))
                    })
                    .catch(function(error) {
                        console.log('No such user! Error in getting token!');
                    });
            } catch (e) {
                console.log(e);
            }
        }
</code>```

For Logout you can simply remove the token using localStorage.removeItem

Title: Login status in React

Body:
I created authorization in javascript. Then if success login I redirect to React project with url parameter http://localhost:3000/?phoneNum=%2B77072050399

Then in React I get userId by using the passed url parameter => phoneNumber using axios.

I realized it in App.js. Code below:

let url = window.location.href;
    let params = (new URL(url)).searchParams;
    const userPhoneNum = encodeURIComponent(params.get('phoneNum'));

    const [userToken, setUserToken] = useState(null);
    const getUserToken = async() => {
        try {
            const data = await axios
                .get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
                .then(response => {
                    setUserToken(response.data);
                })
                .catch(function(error) {
                    console.log('No such user! Error in getting token!');
                });
        } catch (e) {
            console.log(e);
        }
    }

    useEffect(() => {
        getUserToken();
        console.log(userToken);
    }, userToken);

So, when I go to next page localhost:3000/places, it is requesting for userToken again with parameter null, because there is no param phoneNum.

How to make it to request only one time and save the userId after it is taken in main page. So, then only when I click LogOut button reset the variable where userID is saved.

Body:
If you want to do that without using any third party libraries you can use browser's in built storage api

So, when you receive the token, you can store that in the local storage of the browser using localstorage.setItem and later when you wan to see if the token is there or not just read from there using localStorage.getItem

 const getUserToken = async() => {
            try {
                const data = await axios
                    .get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
                    .then(response => {
                        setUserToken(response.data);
                        Storage.setItem('token',JSON.stringify(response.data))
                    })
                    .catch(function(error) {
                        console.log('No such user! Error in getting token!');
                    });
            } catch (e) {
                console.log(e);
            }
        }

For Logout you can simply remove the token using localStorage.removeItem


问:
Save Screen (program) output to a file
I need to save the whole output of Screen to a file to check later all the content.

The reason is that I'm dumping a flash memory through a serial port, using Screen to interface with it. I would like to save it to a file to check memory structure.

I've tried:

```<code>screen /dev/ttyUSB0 115200 >> foo.txt
screen /dev/ttyUSB0 115200 | tee foo.txt
</code>```

And I've also tried to use bufferfile from screen, but I don't understand how to use it.

Is there an easy way?

答:
The existing screen log can be saved by:

Ctrl+A : hardcopy -h filename

Title: Save Screen (program) output to a file

Body:
I need to save the whole output of Screen to a file to check later all the content.

The reason is that I'm dumping a flash memory through a serial port, using Screen to interface with it. I would like to save it to a file to check memory structure.

I've tried:

screen /dev/ttyUSB0 115200 >> foo.txt
screen /dev/ttyUSB0 115200 | tee foo.txt

And I've also tried to use bufferfile from screen, but I don't understand how to use it.

Is there an easy way?