问:
recording and printing arrays using pointers
I'm new to coding and started learning pointers and i'm stuck at a question.

How do I take the array input and print the same array using pointers?

Also it'll be great if you can guide me how to pass variables from function to main().
thanks

```<code>#include <stdio.h>
#include <stdlib.h>

int* record_array (int *size_ptr);
int* print_array (int *array_ptr [], int *size_ptr);

int* record_array (int *size_ptr)
{
    int *array_ptr = (int*) malloc(*size_ptr*sizeof(int));
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("Enter element at index %d", index);
        scanf("%d", &array_ptr[index]);

    }
    return array_ptr;

}

int* print_array (int *array_ptr [], int *size_ptr)
{
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("%d ",array_ptr[index]);
    }
    int *pass = array_ptr;
    return pass;
}

int main()
{
    int size = 0;

    printf("How many elements do you want?");
    scanf("%d", &size);
    record_array(&size);
    print_array(&array_ptr,&size);
    free(pass);

    return 0;
}
</code>```

答:
You are close, but you have used int *array_ptr [] in int* print_array (int *array_ptr [], int *size_ptr) incorrectly. You further have no pointer in main() to hold the address returned by int *record_array (int *size_ptr) to use in main() and free when it is no longer needed. print_array simply prints the array and returns nothing (it shouldn't return anything) so it should just be type void, e.g. void print_array (int *array_ptr, int *size_ptr)

On access, (subject to 4-exceptions not relevant here), an array is converted to a pointer to the first element C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3). When you want to pass an array, you simply pass the array as a parameter and it is converted to a pointer automatically.

Also note, there is NO array in the entirety of your code. You declare a pointer and then allocate a block of memory to hold your integer values and you assign the starting address for that block to your pointer. (e.g. the pointer holds the starting address for the allocated block as its value, it "points" to that block of memory)

For starters, in main(), you need a pointer to hold the address returned by record_array, e.g.

```<code>    int size = 0;
    int *array = NULL;  /* you need a pointer to hold the address of your array */
</code>```

In record_array (and for every allocation), you must check the return of malloc() to validate whether it succeeded or failed, e.g.

```<code>int *record_array (int *size_ptr)
{
    int *array_ptr = malloc (*size_ptr * sizeof *array_ptr);

    if (!array_ptr) {   /* validate EVERY allocation */
        perror ("malloc-array_ptr");
        return NULL;
    }
    ...
</code>```

(note: the use of the dereferenced pointer to set the type-size for the allocation. Using the dereference pointer -- you will never get it wrong. In C, there is no need to cast the return of malloc, it is unnecessary. See: Do I cast the result of malloc?)

With input, you must validate every input, e.g. in record_array() that would be:

```<code>    for (int index = 0; index < *size_ptr; index++)
    {
        printf ("Enter element at index %d: ", index);
        if (scanf ("%d", &array_ptr[index]) != 1) {
            fputs ("error: invalid integer input.\n", stderr);
            return NULL;
        }

    }
</code>```

Expanding a bit on the validations, every time you do something in your code that can fail (like take user input or allocation memory), it is imperative that you validate the return before using the results in your code. Above, if you simply do scanf ("%d", &array_ptr[index]) a simply slip and tapping 'r' instead of '5' would go unnoticed but lead to invalid results in your code (and perhaps Undefined Behavior if it occurred on the first character)

So to prevent using invalid data, you check the return of the function you are using. With scanf it returns the number of successful conversions or EOF if failure occurs before the first conversion takes place. So when taking input with scanf you always check that the return matched the number of conversions you specify in your format-string. With "%d" -- one conversion to int will take place. So to validate the input, you use:

```<code>         if (scanf ("%d", &array_ptr[index]) != 1) {
            fputs ("error: invalid integer input.\n", stderr);
            return NULL;
        }
</code>```

(which just say if the return from scanf() isn't 1 -- handle the error -- which is to return failure (or NULL) in this case)

Finally in main(), you will validate the return of record_array is not NULL before using the allocated block in print_array(), e.g.

```<code>    if ((array = record_array (&size))) {   /* validate record_array succeeds */
        print_array (array, &size);         /* print array */
        free (array);                       /* free array */
    }
</code>```

(the comparison is shorthand for: if ((array = record_array (&size)) != NULL) {.... You could have done the assignment separately, e.g. array = record_array (&size); and then if (array != NULL) {... so long as you validate the return :)

Making those corrections (and providing a space in the prompt to separate the prompt and the input) you would have:

```<code>#include <stdio.h>
#include <stdlib.h>

int *record_array (int *size_ptr);
void print_array (int *array_ptr, int *size_ptr);

int *record_array (int *size_ptr)
{
    int *array_ptr = malloc (*size_ptr * sizeof *array_ptr);

    if (!array_ptr) {   /* validate EVERY allocation */
        perror ("malloc-array_ptr");
        return NULL;
    }

    for (int index = 0; index < *size_ptr; index++)
    {
        printf ("Enter element at index %d: ", index);
        if (scanf ("%d", &array_ptr[index]) != 1) {
            fputs ("error: invalid integer input.\n", stderr);
            return NULL;
        }

    }
    return array_ptr;
}

void print_array (int *array_ptr, int *size_ptr)
{
    for (int index = 0; index < *size_ptr; index++)
        printf ("%d ",array_ptr[index]);

    putchar ('\n');     /* tidy up with newline */
}

int main()
{
    int size = 0;
    int *array = NULL;  /* you need a pointer to hold the address of your array */

    printf("How many elements do you want? ");
    if (scanf("%d", &size) != 1) {          /* validate EVERY input */
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }

    if ((array = record_array (&size))) {   /* validate record_array succeeds */
        print_array (array, &size);         /* print array */
        free (array);                       /* free array */
    }
}
</code>```

Example Use/Output

```<code>$ ./bin/readarrayfunc
How many elements do you want? 5
Enter element at index 0: 1
Enter element at index 1: 2
Enter element at index 2: 3
Enter element at index 3: 4
Enter element at index 4: 5
1 2 3 4 5
</code>```

Note also with declarations the '*' goes with the variable, not the type. Why? Readability. Look at:

```<code>int* a, b, c;
</code>```

That certainly does not declare 3-pointers to int, it declares one pointer to int and two integers:

```<code>int *a, b, c;
</code>```

makes that clear.

Look things over and let me know if you have further questions.

Body:
I'm new to coding and started learning pointers and i'm stuck at a question.

How do I take the array input and print the same array using pointers?

Also it'll be great if you can guide me how to pass variables from function to main().
thanks

#include <stdio.h>
#include <stdlib.h>

int* record_array (int *size_ptr);
int* print_array (int *array_ptr [], int *size_ptr);

int* record_array (int *size_ptr)
{
    int *array_ptr = (int*) malloc(*size_ptr*sizeof(int));
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("Enter element at index %d", index);
        scanf("%d", &array_ptr[index]);

    }
    return array_ptr;

}

int* print_array (int *array_ptr [], int *size_ptr)
{
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("%d ",array_ptr[index]);
    }
    int *pass = array_ptr;
    return pass;
}

int main()
{
    int size = 0;

    printf("How many elements do you want?");
    scanf("%d", &size);
    record_array(&size);
    print_array(&array_ptr,&size);
    free(pass);

    return 0;
}

Body:
You are close, but you have used int *array_ptr [] in int* print_array (int *array_ptr [], int *size_ptr) incorrectly. You further have no pointer in main() to hold the address returned by int *record_array (int *size_ptr) to use in main() and free when it is no longer needed. print_array simply prints the array and returns nothing (it shouldn't return anything) so it should just be type void, e.g. void print_array (int *array_ptr, int *size_ptr)

On access, (subject to 4-exceptions not relevant here), an array is converted to a pointer to the first element C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3). When you want to pass an array, you simply pass the array as a parameter and it is converted to a pointer automatically.

Also note, there is NO array in the entirety of your code. You declare a pointer and then allocate a block of memory to hold your integer values and you assign the starting address for that block to your pointer. (e.g. the pointer holds the starting address for the allocated block as its value, it "points" to that block of memory)

For starters, in main(), you need a pointer to hold the address returned by record_array, e.g.

    int size = 0;
    int *array = NULL;  /* you need a pointer to hold the address of your array */

In record_array (and for every allocation), you must check the return of malloc() to validate whether it succeeded or failed, e.g.

int *record_array (int *size_ptr)
{
    int *array_ptr = malloc (*size_ptr * sizeof *array_ptr);

    if (!array_ptr) {   /* validate EVERY allocation */
        perror ("malloc-array_ptr");
        return NULL;
    }
    ...

(note: the use of the dereferenced pointer to set the type-size for the allocation. Using the dereference pointer -- you will never get it wrong. In C, there is no need to cast the return of malloc, it is unnecessary. See: Do I cast the result of malloc?)

With input, you must validate every input, e.g. in record_array() that would be:

    for (int index = 0; index < *size_ptr; index++)
    {
        printf ("Enter element at index %d: ", index);
        if (scanf ("%d", &array_ptr[index]) != 1) {
            fputs ("error: invalid integer input.\n", stderr);
            return NULL;
        }

    }

Expanding a bit on the validations, every time you do something in your code that can fail (like take user input or allocation memory), it is imperative that you validate the return before using the results in your code. Above, if you simply do scanf ("%d", &array_ptr[index]) a simply slip and tapping 'r' instead of '5' would go unnoticed but lead to invalid results in your code (and perhaps Undefined Behavior if it occurred on the first character)

So to prevent using invalid data, you check the return of the function you are using. With scanf it returns the number of successful conversions or EOF if failure occurs before the first conversion takes place. So when taking input with scanf you always check that the return matched the number of conversions you specify in your format-string. With "%d" -- one conversion to int will take place. So to validate the input, you use:

         if (scanf ("%d", &array_ptr[index]) != 1) {
            fputs ("error: invalid integer input.\n", stderr);
            return NULL;
        }

(which just say if the return from scanf() isn't 1 -- handle the error -- which is to return failure (or NULL) in this case)

Finally in main(), you will validate the return of record_array is not NULL before using the allocated block in print_array(), e.g.

    if ((array = record_array (&size))) {   /* validate record_array succeeds */
        print_array (array, &size);         /* print array */
        free (array);                       /* free array */
    }

(the comparison is shorthand for: if ((array = record_array (&size)) != NULL) {.... You could have done the assignment separately, e.g. array = record_array (&size); and then if (array != NULL) {... so long as you validate the return :)

Making those corrections (and providing a space in the prompt to separate the prompt and the input) you would have:

#include <stdio.h>
#include <stdlib.h>

int *record_array (int *size_ptr);
void print_array (int *array_ptr, int *size_ptr);

int *record_array (int *size_ptr)
{
    int *array_ptr = malloc (*size_ptr * sizeof *array_ptr);

    if (!array_ptr) {   /* validate EVERY allocation */
        perror ("malloc-array_ptr");
        return NULL;
    }

    for (int index = 0; index < *size_ptr; index++)
    {
        printf ("Enter element at index %d: ", index);
        if (scanf ("%d", &array_ptr[index]) != 1) {
            fputs ("error: invalid integer input.\n", stderr);
            return NULL;
        }

    }
    return array_ptr;
}

void print_array (int *array_ptr, int *size_ptr)
{
    for (int index = 0; index < *size_ptr; index++)
        printf ("%d ",array_ptr[index]);

    putchar ('\n');     /* tidy up with newline */
}

int main()
{
    int size = 0;
    int *array = NULL;  /* you need a pointer to hold the address of your array */

    printf("How many elements do you want? ");
    if (scanf("%d", &size) != 1) {          /* validate EVERY input */
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }

    if ((array = record_array (&size))) {   /* validate record_array succeeds */
        print_array (array, &size);         /* print array */
        free (array);                       /* free array */
    }
}

Example Use/Output

$ ./bin/readarrayfunc
How many elements do you want? 5
Enter element at index 0: 1
Enter element at index 1: 2
Enter element at index 2: 3
Enter element at index 3: 4
Enter element at index 4: 5
1 2 3 4 5

Note also with declarations the '*' goes with the variable, not the type. Why? Readability. Look at:

int* a, b, c;

That certainly does not declare 3-pointers to int, it declares one pointer to int and two integers:

int *a, b, c;

makes that clear.

Look things over and let me know if you have further questions.


来源: stackexchange

问:
Dagger2 Error in ViewModelFactory when change MutableMap to Map
I have problem when try to use dagger2
Here is my ViewModelFactory:

```<code>class ViewModelFactory @Inject constructor(
private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    val creator = viewModels[modelClass]
        ?: viewModels.asIterable().firstOrNull {
            modelClass.isAssignableFrom(it.key)
        }?.value ?: throw IllegalArgumentException("$UNKNOWN_MODEL_CLASS $modelClass")
    return try {
        @Suppress("UNCHECKED_CAST")
        creator.get() as T
    } catch (e: Exception) {
        throw RuntimeException(e)
    }
}
</code>```

}

When i change viewModels to Map it has following error:

```<code>public abstract interface AppComponent {
            ^
  java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,? extends javax.inject.Provider<androidx.lifecycle.ViewModel>> is injected at
      com.example.baseproject.utils.ViewModelFactory(viewModels)
  com.example.baseproject.utils.ViewModelFactory is injected at
      com.example.baseproject.di.ViewModelBuilder.bindViewModelFactory(viewModelFactory)
  androidx.lifecycle.ViewModelProvider.Factory is injected at
      com.example.baseproject.MainActivity.viewModelFactory
  com.example.baseproject.MainActivity is injected at
      dagger.android.AndroidInjector.inject(T) [com.example.baseproject.di.AppComponent → com.example.baseproject.di.ActivityModules_ContributeMainActivity.MainActivitySubcomponent]
</code>```

Please help me i don't know why it's happening

答:
You're missing a @JvmSuppressWildcards. You want to get a Provider<ViewModel>, not a Provider<? extends ViewModel>, but Kotlin would generate you a Provider<? extends ViewModel> without the annotation.

```<code>private val viewModels: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : ViewModelProvider.Factory {
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have problem when try to use dagger2
Here is my ViewModelFactory:

class ViewModelFactory @Inject constructor(
private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    val creator = viewModels[modelClass]
        ?: viewModels.asIterable().firstOrNull {
            modelClass.isAssignableFrom(it.key)
        }?.value ?: throw IllegalArgumentException("$UNKNOWN_MODEL_CLASS $modelClass")
    return try {
        @Suppress("UNCHECKED_CAST")
        creator.get() as T
    } catch (e: Exception) {
        throw RuntimeException(e)
    }
}

}

When i change viewModels to Map it has following error:

public abstract interface AppComponent {
            ^
  java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,? extends javax.inject.Provider<androidx.lifecycle.ViewModel>> is injected at
      com.example.baseproject.utils.ViewModelFactory(viewModels)
  com.example.baseproject.utils.ViewModelFactory is injected at
      com.example.baseproject.di.ViewModelBuilder.bindViewModelFactory(viewModelFactory)
  androidx.lifecycle.ViewModelProvider.Factory is injected at
      com.example.baseproject.MainActivity.viewModelFactory
  com.example.baseproject.MainActivity is injected at
      dagger.android.AndroidInjector.inject(T) [com.example.baseproject.di.AppComponent → com.example.baseproject.di.ActivityModules_ContributeMainActivity.MainActivitySubcomponent]

Please help me i don't know why it's happening

Body:
You're missing a @JvmSuppressWildcards. You want to get a Provider<ViewModel>, not a Provider<? extends ViewModel>, but Kotlin would generate you a Provider<? extends ViewModel> without the annotation.

private val viewModels: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : ViewModelProvider.Factory {


问:
How to install and run Theia, browser based IDE?
I want to develop remotely and read about Theia. I could install the program with pip

```<code>pip install theia
</code>```

But then there is no description available on how to start the program. Is it plug-in for Eclipse, or do I have to run it in docker or what?

答:
Theia is not an extension of the classic Eclipse project. This is not really an installable app.

If you want to run Theia locally, you can follow the tutorial of the official documentation : Official help to setup environement.

Be sure to have Node.js 10 installed. It is not currently compatible with Node.js 12. If you want to have more than one version of Node installed on you machine, I advise you nvm (nvm github) or nvm-windows (nvm windows github).

If it can be useful, I personnally have a small bat script to launch Theia at the manner of a desktop app

```<code>"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app=http://localhost:3000
yarn start
</code>```

Body:
I want to develop remotely and read about Theia. I could install the program with pip

pip install theia

But then there is no description available on how to start the program. Is it plug-in for Eclipse, or do I have to run it in docker or what?

Body:
Theia is not an extension of the classic Eclipse project. This is not really an installable app.

If you want to run Theia locally, you can follow the tutorial of the official documentation : Official help to setup environement.

Be sure to have Node.js 10 installed. It is not currently compatible with Node.js 12. If you want to have more than one version of Node installed on you machine, I advise you nvm (nvm github) or nvm-windows (nvm windows github).

If it can be useful, I personnally have a small bat script to launch Theia at the manner of a desktop app

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app=http://localhost:3000
yarn start


答:
What exactly can't you do? Extract the data from the URL? Convert the Base64 data to JSON? Convert JSON to data?

If your problem is simply decoding the Base64 data, you can try the JavaScript function btoa().

EDIT (from a suggestion of Sashisu Kumar):

You can also install the js-base64 package: npm install --save js-base64, then:

import { Base64 } from 'js-base64';
console.log("sssdecrpt",Base64.decode(sd))
```

Title: how to decrpt url parameter in reactjs

Body: i am getting parameter in url as p=eyJzIjoiWlIybnJVcGxVLUlGNnFZcW03cWVmUmo4MVVnIiwidiI6MSwicCI6IntcInVcIjozMDEwMTMzMixcInZcIjoxLFwidXJsXCI6XCJodHRwczpcXFwvXFxcL3Rlc3QudmFuaGV1c2VuaW5kaWEuY29tXFxcL3Jlc2V0cGFzc3dvcmRcXFwvY29udGVudFxcXC9zZWN1cmVfa2V5XFxcL2U5MmUzOWRlMDEwZmQyMTQ0ODg3NTJlODZkZTQ2NmFhXFxcL2lkX2N1c3RvbWVyXFxcLzE2OTM1ODVcXFwvc2VjXFxcLzE1OTA4MjYwMDQuNDU4XFxcL290cFxcXC8yNTgyMDE_dXRtX3NvdXJjZT1QaWdlb25fZm9yZ2V0X3Bhc3N3b3JkJnV0bV9tZWRpdW09ZW1haWwmdXRtX2NhbXBhaWduPWZvcmdldF9wYXNzd29yZFwiLFwiaWRcIjpcIjIzZGZkNDNiOGY1ODRlMmJiYTdjMzcyNGM2ZDgxMTY4XCIsXCJ1cmxfaWRzXCI6W1wiYTk4ZmEwMDgxYTk3ZjY3MGRmNDc3ZTI4MDFlYThlMzIzN2Q4YmQwMlwiXX0ifQ


问:
JS how to do a double each.for
for a gaming app, a player can select card types for his/her deck (first eachfor) and amount of each card type (2nd each.for). After this, I want to push this selection in an array.
Following part of my code works well:

```<code>//defining card types
let availableRoles = ["werwolf", "dorfbewohner", "seherin", "hexe", "jaeger", "armor", "heiler", "prinz"]
let gameState = {
  roles: {}
}
//set card amount 0
;(() => {
  availableRoles.forEach(role => gameState.roles[role] = 0)
})()
//adding & subtracting roles
const addRole = role => {
  gameState.roles[role]++
  document.getElementById(role + "_btn_remove").disabled = false;
  document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
  document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}

const removeRole = role => {
  gameState.roles[role]--
  if (gameState.roles[role] <= 0) {
    gameState.roles[role] = 0
    document.getElementById(role + "_btn_remove").disabled = true;
  }
  document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
  document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}

const totalNumberOfRolesInGame = () => Object.values(gameState.roles).reduce((a,c) => a + c)
</code>```

Now I want to hit every role and hit every number insider the role by using for each command. But it does not work.

```<code> var rollen = []

  function Holmir() {
  ;(() => {
      gameState.roles.forEach(element => element.forEach (myRole => rollen.push(myRole))
    ) })()
{
</code>```

I'm thankful for any help!

答:
forEach works with an array.

```<code>gameState = {
  roles: {}
}
</code>```

gameState.roles gives you an object so forEach won't work with this

Title: JS how to do a double each.for

Body:
for a gaming app, a player can select card types for his/her deck (first eachfor) and amount of each card type (2nd each.for). After this, I want to push this selection in an array.
Following part of my code works well:

//defining card types
let availableRoles = ["werwolf", "dorfbewohner", "seherin", "hexe", "jaeger", "armor", "heiler", "prinz"]
let gameState = {
  roles: {}
}
//set card amount 0
;(() => {
  availableRoles.forEach(role => gameState.roles[role] = 0)
})()
//adding & subtracting roles
const addRole = role => {
  gameState.roles[role]++
  document.getElementById(role + "_btn_remove").disabled = false;
  document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
  document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}

const removeRole = role => {
  gameState.roles[role]--
  if (gameState.roles[role] <= 0) {
    gameState.roles[role] = 0
    document.getElementById(role + "_btn_remove").disabled = true;
  }
  document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
  document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}

const totalNumberOfRolesInGame = () => Object.values(gameState.roles).reduce((a,c) => a + c)

Now I want to hit every role and hit every number insider the role by using for each command. But it does not work.

 var rollen = []

  function Holmir() {
  ;(() => {
      gameState.roles.forEach(element => element.forEach (myRole => rollen.push(myRole))
    ) })()
{

I'm thankful for any help!

Body:
forEach works with an array.

gameState = {
  roles: {}
}

gameState.roles gives you an object so forEach won't work with this


问:
Excel whole column reference in array formula too slow, not respecting UsedRange?
I have a worksheet with many array formulas referencing another small source data sheet with a couple of rows. Formulas are as follows:

```<code>{=INDEX(Source!$F:$F,MATCH(1, (Source!$A:$A=$B6)*(Source!$B:$B=H$1),0))}
</code>```

The calculation runs very slowly. When I replace the whole column references with ranges of 1000 cells, the workbook calculation speeds up significantly.

```<code>{=INDEX(Source!$F$1:$F$1000,MATCH(1, (Source!$A$1:$A$1000=$B6)*(Source!$B$1:$B$1000=H$1),0))}
</code>```

I have chcecked the UsedRange on the Source sheet and it is OK and just a few rows (using ctrl+end).
Using whole column reference is quite normal practice but it does not really work well here, since it does not respect UsedRange.

Found an article on this topic:
https://fastexcel.wordpress.com/2015/12/12/excel-full-column-references-and-used-range-good-idea-or-bad-idea/

that says:

But avoid array formula and SUMPRODUCT usage of whole column reference

But why? I cannot understand the reason why Excel is not capable to limit the calculation algorithm of array formulas to the used range? Is there any other workaround?

答:
Not sure if you are building this through VBA but if it's just formulas you are using you could try something like:

```<code>=INDEX(Source!$F$1:$F$1000,MATCH(1,INDEX((Source!$A$1:INDEX(Source!$A:$A,COUNTA(Source!$A:$A))=$B6)*(Source!$B$1:INDEX(Source!$B:$B,COUNTA(Source!$B:$B))=H$1),),0))
</code>```

Looks lengthy, but it basically is a dynamic way of limiting the column references to the last used row. Btw, another great tip done by @Chris in the comments is the use of an actual table instead which should speed things up even more.

Btw, you won't have to enter this through CtrlShiftEnter nomore due to the second INDEX

Body:
I have a worksheet with many array formulas referencing another small source data sheet with a couple of rows. Formulas are as follows:

{=INDEX(Source!$F:$F,MATCH(1, (Source!$A:$A=$B6)*(Source!$B:$B=H$1),0))}

The calculation runs very slowly. When I replace the whole column references with ranges of 1000 cells, the workbook calculation speeds up significantly.

{=INDEX(Source!$F$1:$F$1000,MATCH(1, (Source!$A$1:$A$1000=$B6)*(Source!$B$1:$B$1000=H$1),0))}

I have chcecked the UsedRange on the Source sheet and it is OK and just a few rows (using ctrl+end).
Using whole column reference is quite normal practice but it does not really work well here, since it does not respect UsedRange.

Found an article on this topic:
https://fastexcel.wordpress.com/2015/12/12/excel-full-column-references-and-used-range-good-idea-or-bad-idea/

that says:

But avoid array formula and SUMPRODUCT usage of whole column reference

But why? I cannot understand the reason why Excel is not capable to limit the calculation algorithm of array formulas to the used range? Is there any other workaround?

Body:
Not sure if you are building this through VBA but if it's just formulas you are using you could try something like:

=INDEX(Source!$F$1:$F$1000,MATCH(1,INDEX((Source!$A$1:INDEX(Source!$A:$A,COUNTA(Source!$A:$A))=$B6)*(Source!$B$1:INDEX(Source!$B:$B,COUNTA(Source!$B:$B))=H$1),),0))

Looks lengthy, but it basically is a dynamic way of limiting the column references to the last used row. Btw, another great tip done by @Chris in the comments is the use of an actual table instead which should speed things up even more.

Btw, you won't have to enter this through CtrlShiftEnter nomore due to the second INDEX


问:
I write the code in python to count digits of a number but It doesn't work for some numbers
In order to count digits of a number I write this code in python:

```<code>a=int(input('number: '))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')
</code>```

It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...

It say:

```<code>ValueError: invalid literal for int() with base 10: '3**21'
</code>```

3**21 is integer input So why it gives this erroer,and How Should I fix this?

答:
The int() constructor accepts string representation of ints, which 2**5 is not, this is an math operation, you may use eval to compute that. I've add an additionnal variable value to keep track of the initial value and print it at then end

```<code>value = eval(input('number: '))
a = value
count = 0
while a!=0:
    a = a//10
    count += 1
print(value, 'has', count, 'digits')
</code>```

⚠ CAREFULL eval is dangerous

Body:
In order to count digits of a number I write this code in python:

a=int(input('number: '))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')

It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...

It say:

ValueError: invalid literal for int() with base 10: '3**21'

3**21 is integer input So why it gives this erroer,and How Should I fix this?

Body:
The int() constructor accepts string representation of ints, which 2**5 is not, this is an math operation, you may use eval to compute that. I've add an additionnal variable value to keep track of the initial value and print it at then end

value = eval(input('number: '))
a = value
count = 0
while a!=0:
    a = a//10
    count += 1
print(value, 'has', count, 'digits')

⚠ CAREFULL eval is dangerous


问:
Is there a way to inject an object into an interface using Dagger2
In my activity class, I can inject a ViewModel using:

```<code>@Inject
GameViewModel gameViewModel;
</code>```

And it works fine. The problem is, that I want to use the object in an interface:

```<code>public interface SharedData {
    @Inject
    GameViewModel gameViewModel;

    default void createNewUser(User authenticatedUser) {
        gameViewModel.userLiveData.observe(this, user -> {
            Log.d("TAG", user.name);
        });
    }
}
</code>```

Is this even possible? Because I get:

Variable gameViewModel might not have been initialized

Isn't Dagger supposed to do that?

答: You cannot use fields in an interface. To use fields, you should be using a class, or an abstract class.</p>

Body:
In my activity class, I can inject a ViewModel using:

@Inject
GameViewModel gameViewModel;

And it works fine. The problem is, that I want to use the object in an interface:

public interface SharedData {
    @Inject
    GameViewModel gameViewModel;

    default void createNewUser(User authenticatedUser) {
        gameViewModel.userLiveData.observe(this, user -> {
            Log.d("TAG", user.name);
        });
    }
}

Is this even possible? Because I get:

Variable gameViewModel might not have been initialized

Isn't Dagger supposed to do that?


问:
Javascript regexp problem
I'm trying to use a pattern like this in a javascript regexp:

```<code>"foo.bar".match(/foo\.(buz|bar)/)
</code>```

but instead of returning foo.bar as I expect, it returns an array:

```<code>["foo.bar", "bar"]
</code>```

I don't get it. How do I match foo.bar and foo.buz?

答:
Regex matching works in that way, that the first element of group is a whole string that is matched by whole regex. The same way if you will make a "big" group.

```<code>/(foo\.(buz|bar))/
</code>```

The second and all next elements are those you matched by your own - so it is buz or bar:

```<code>(buz|bar)
</code>```

In that case if you want not to batch just buz/bar you can exclude this group using ?:

```<code>"foo.bar".match(/foo\.(?:buz|bar)/)
</code>```

Your result will looks like:

```<code>["foo.bar"]
</code>```

But it will still be an array with one element.

ContentLicense: CC BY-SA 3.0

Title: Javascript regexp problem

Body:
I'm trying to use a pattern like this in a javascript regexp:

"foo.bar".match(/foo\.(buz|bar)/)

but instead of returning foo.bar as I expect, it returns an array:

["foo.bar", "bar"]

I don't get it. How do I match foo.bar and foo.buz?

Body:
Regex matching works in that way, that the first element of group is a whole string that is matched by whole regex. The same way if you will make a "big" group.

/(foo\.(buz|bar))/

The second and all next elements are those you matched by your own - so it is buz or bar:

(buz|bar)

In that case if you want not to batch just buz/bar you can exclude this group using ?:

"foo.bar".match(/foo\.(?:buz|bar)/)

Your result will looks like:

["foo.bar"]

But it will still be an array with one element.


问:
React Native Deep Linking - Broken?
I'm using React-Native, and have react native navigation 5.0

I've tried looking all over and compared different fixes but:

Android dosen't seem to recognize xx:// paths as links on neither chrome, messages, or other apps (like whatsapp). The only way i could get it to actually work on the
actual device is by making the deeplink with https://xx.com. I have no problems with doing xx:// on CLI - but who cares about CLI when the actual device dosen't work. For example, you can try to see if you can open fb:// on your android device (facebook).

IOS seems to only work with xx:// and not https://xx.com because https: seems to be reserved for safari.

Does that mean that i'm forced to do universal links via the Browser way?

What is everyone else doing?

答: Decided to just do universal linking</p>

Title: React Native Deep Linking - Broken?

Body: Decided to just do universal linking


问:
Custom Fields affecting Wordpress theme
I've been trying to put custom fields into my posts on Wordpress, however whenever I put on this code onto my file, the post, custom field, and the content and code that goes after the supposed custom field does not run

```<code><?php echo get_post_meta($post->ID, 'instagram', true); ?>
</code>```

As well as this one

```<code><?php
        $instagram = get_post_meta($post=>ID, 'Instagram', true);
        if($instagram){ ?>
            <p>@sample.handle</p>
        <?php
        }else{ }
        ?>
</code>```

I also tried putting both on other themes even on Twenty Twenty and it still doesn't work. Even tried ACF but still nothing.

Would really appreciate the help in advance :)

答:
Have you tried echoing out your HTML instead of closing and opening the php as I think that is breaking the php function as it would be mixing its ends statements. </p>

```<code><?php
        $instagram = get_post_meta($post=>ID, 'Instagram', true);
        if($instagram){
           echo '<p>@sample.handle</p>';

        }else{ }
        ?>
</code>```

Title: Custom Fields affecting Wordpress theme

Body:
I've been trying to put custom fields into my posts on Wordpress, however whenever I put on this code onto my file, the post, custom field, and the content and code that goes after the supposed custom field does not run

<?php echo get_post_meta($post->ID, 'instagram', true); ?>

As well as this one

<?php
        $instagram = get_post_meta($post=>ID, 'Instagram', true);
        if($instagram){ ?>

@sample.handle

        <?php
        }else{ }
        ?>

I also tried putting both on other themes even on Twenty Twenty and it still doesn't work. Even tried ACF but still nothing.

Would really appreciate the help in advance :)

Body:
Have you tried echoing out your HTML instead of closing and opening the php as I think that is breaking the php function as it would be mixing its ends statements.

<?php
        $instagram = get_post_meta($post=>ID, 'Instagram', true);
        if($instagram){
           echo '<p>@sample.handle</p>';

        }else{ }
        ?>


问:
How to read UTF-8 XML with RapidXML and use it with C++
I work on a C++ application and implemented a translator class that uses data from a XML file to translate strings. I have now serious problems with special characters currently for German Umlauts ÖÄÜ for example...

On Visual Studio I see following in Debug view, it reads following sample string "Dateiäüö":

Because of this problem I found this post on Stackoverflow:
How to read Unicode XML values with rapidxml
and changed my RapidXML class to work with wchar_t:

```<code>std::string RapidXMLParser::getValueUTF8(const std::string path)
{
    std::vector<std::string> tags = splitPath(path);
    rapidxml::file<wchar_t> xmlFile(filename.data());
    docUTF8.parse<0>(xmlFile.data());
    rapidxml::xml_node<wchar_t>* element = findElementUTF8(path);
    if (element)
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
        std::wstring temp = element->value();
        std::string result = converter.to_bytes(temp);
        return result;
    }
    else
        return "";
}
</code>```

But this did not solve my problem:

The source XML file was checked by an UTF-8 validator and it is ok. If I change encoding to ANSI, everything works on Windows (but this is no solution!). If I compile same code on Linux I get empty strings for ANSI encoded XML with Umlauts and a crash for UTF-8 encoded XML...

The program uses wxwidgets for its interface and there this menu item renders the same characters as displayed by debugger. On Linux the empty strings leads to missing menu items or empty lines.

I hope someone has a good advice how to solve this or a suggestion for an alternative way to do UTF-8 translation with editable data source like an XML file.

EDIT:
My XML parser can switch between RapidXML and TinyXML. I've also tested this with TinyXML and I get the same problem:

答:
I think your findElementUTF8() should return a rapidxml::xml_node<char>*

```<code>rapidxml::xml_node<char>* element = findElementUTF8(path);
</code>```

because UTF8 is usually represented by char*. Following code is working for both windows API and codecvt

```<code>  // äüö UTF8 encoded
  byte b8[] = { 0xc3, 0xa4, 0xc3, 0xbc, 0xc3, 0xb6, 0x00 };

  std::string sb8 = (char*)b8;

  wchar_t win_conv[16]{ 0 };
  MultiByteToWideChar(CP_UTF8, 0, (char*)b8, -1, win_conv, ARRAYSIZE(win_conv));

  std::wstring utf16_conv = std::wstring_convert<
    std::codecvt_utf8_utf16<wchar_t>>{}.from_bytes(sb8);

  assert(utf16_conv == win_conv);
</code>```

Body:
I work on a C++ application and implemented a translator class that uses data from a XML file to translate strings. I have now serious problems with special characters currently for German Umlauts ÖÄÜ for example...

On Visual Studio I see following in Debug view, it reads following sample string "Dateiäüö":

Because of this problem I found this post on Stackoverflow:
How to read Unicode XML values with rapidxml
and changed my RapidXML class to work with wchar_t:

std::string RapidXMLParser::getValueUTF8(const std::string path)
{
    std::vector<std::string> tags = splitPath(path);
    rapidxml::file<wchar_t> xmlFile(filename.data());
    docUTF8.parse<0>(xmlFile.data());
    rapidxml::xml_node<wchar_t>* element = findElementUTF8(path);
    if (element)
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
        std::wstring temp = element->value();
        std::string result = converter.to_bytes(temp);
        return result;
    }
    else
        return "";
}

But this did not solve my problem:

The source XML file was checked by an UTF-8 validator and it is ok. If I change encoding to ANSI, everything works on Windows (but this is no solution!). If I compile same code on Linux I get empty strings for ANSI encoded XML with Umlauts and a crash for UTF-8 encoded XML...

The program uses wxwidgets for its interface and there this menu item renders the same characters as displayed by debugger. On Linux the empty strings leads to missing menu items or empty lines.

I hope someone has a good advice how to solve this or a suggestion for an alternative way to do UTF-8 translation with editable data source like an XML file.

EDIT:
My XML parser can switch between RapidXML and TinyXML. I've also tested this with TinyXML and I get the same problem:

Body:
I think your findElementUTF8() should return a rapidxml::xml_node<char>*

rapidxml::xml_node<char>* element = findElementUTF8(path);

because UTF8 is usually represented by char*. Following code is working for both windows API and codecvt

  // äüö UTF8 encoded
  byte b8[] = { 0xc3, 0xa4, 0xc3, 0xbc, 0xc3, 0xb6, 0x00 };

  std::string sb8 = (char*)b8;

  wchar_t win_conv[16]{ 0 };
  MultiByteToWideChar(CP_UTF8, 0, (char*)b8, -1, win_conv, ARRAYSIZE(win_conv));

  std::wstring utf16_conv = std::wstring_convert<
    std::codecvt_utf8_utf16<wchar_t>>{}.from_bytes(sb8);

  assert(utf16_conv == win_conv);


问:
how to colate a list of installed packages into a "one-liner" for re-installing later (using only grep / cut / sed / awk etc, no external tools)
Command:
apt list --installed

Output:

aapt/stable,now 7.1.2.33-7 aarch64 [installed]
abduco/stable,now 0.6-2 aarch64 [installed]
ack-grep/stable,now 3.3.1 all [installed]
antibody/stable,now 6.0.1 aarch64 [installed]
apt/stable,now 1.4.9-27 aarch64 [installed]
```

I would like:

aapt abduco ack-grep antibody apt

Therefore I need:

Only up-to the first / in the first field, but shown in one line, not multiple.

Background info:

I would like to backup a list of installed packages,

But only the name of the package, nothing else,

Shown on one line.

This list can then be appended with sudo apt install to make a quick one-liner for re-installing my packages later on, once I have wiped my system.

答:
Using awk</p>

```<code>$ apt list --installed | awk -F/ '{s=$1" "s} END{print s}'
apt antibody ack-grep abduco apt antibody ack-grep abduco aapt
</code>```

Body:
Command:
apt list --installed

Output:

aapt/stable,now 7.1.2.33-7 aarch64 [installed]
abduco/stable,now 0.6-2 aarch64 [installed]
ack-grep/stable,now 3.3.1 all [installed]
antibody/stable,now 6.0.1 aarch64 [installed]
apt/stable,now 1.4.9-27 aarch64 [installed]

I would like:

aapt abduco ack-grep antibody apt

Therefore I need:

Only up-to the first / in the first field, but shown in one line, not multiple.

Background info:

I would like to backup a list of installed packages,

But only the name of the package, nothing else,

Shown on one line.

This list can then be appended with sudo apt install to make a quick one-liner for re-installing my packages later on, once I have wiped my system.

Body:
Using awk

$ apt list --installed | awk -F/ '{s=$1" "s} END{print s}'
apt antibody ack-grep abduco apt antibody ack-grep abduco aapt


问:
Need Home component that re-renders every time i click in it from drawer [react native]
I have drawer screen named Home and it renders material top-tab navigator and other stack screen defined inside it.Problem is that i want to re-render home screen when i click it from other defined screens .Please help,this is the most general feature required in apps but i am unable to do it.
| iOS or Android | both
| @react-navigation/native 5.0.7
| @react-navigation/drawer 5.1.0
| react-native-reanimated 1.7.0
| react-native-gesture-handler 1.6.0
| react-native-safe-area-context 0.7.3
| react-native-screens 2.8.0
| react-native 0.61.5

enter image description here

答:
You should use navigation events to detect particular screen focus and blur.
focus - This event is emitted when the screen comes into focus
blur - This event is emitted when the screen goes out of focus

Usage

```<code>    function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      //This event is emitted when the screen comes into focus
      // do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}

    function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('blur', () => {
      //This event is emitted when the screen goes out of focus
      // do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}
</code>```

For more details, you can read docs here

Body:
You should use navigation events to detect particular screen focus and blur.
focus - This event is emitted when the screen comes into focus
blur - This event is emitted when the screen goes out of focus

Usage

    function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      //This event is emitted when the screen comes into focus
      // do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}

    function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('blur', () => {
      //This event is emitted when the screen goes out of focus
      // do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}

For more details, you can read docs here


问:
Question regarding multi-threaded environment of servlet
If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?

Do they have a local copy of the following variables?

1) private/protected/public final Semaphore permits = new Semaphore(50);

2) private/protected/public final static Semaphore permits = new Semaphore(50);

3) private/protected/public Semaphore permits = new Semaphore(50);

4) private/protected/public static Semaphore permits = new Semaphore(50);

How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.

答:
If you want to share a semaphore, it must be created by one thread, then handed out to the others (via some form of (possibly static) getter method) when they need it.

If you create the Semaphore object in each object, they'll all have different ones, defeating the purpose.


问:
Common BreakPoints for Reponsive Design
What are some common Breakpoints to achieve the responsive layout for web pages

I use basically

@media screen and (max-width: 480px) {
}

@media screen and (min-resolution: 150dpi) {
}

@media screen and (max-resolution: 300dpi) {
}

@media screen and (min-width: 150px) {
}

@media screen and (min-height: 100px){
}

@media screen and (max-height: 450px) {
}
```

I'm using above mentioned breakpoints but could not achieve complete responsive layout

答:
It is up to you and the usage of your website. Most of the websites designed today uses mobile first approach. The breakpoints can be same as bootstrap uses.</p>

```<code>// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
</code>```

Title: Common BreakPoints for Reponsive Design

Body:
What are some common Breakpoints to achieve the responsive layout for web pages

I use basically

@media screen and (max-width: 480px) {
}

@media screen and (min-resolution: 150dpi) {
}

@media screen and (max-resolution: 300dpi) {
}

@media screen and (min-width: 150px) {
}

@media screen and (min-height: 100px){
}

@media screen and (max-height: 450px) {
}

I'm using above mentioned breakpoints but could not achieve complete responsive layout

Body:
It is up to you and the usage of your website. Most of the websites designed today uses mobile first approach. The breakpoints can be same as bootstrap uses.

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }


问:
React Bootstrap Layout in Navbar
is there anyway to configure layout inside nav / navbar ?

i want to divide a 3 cols with the same size

what i expected should be look like this

Here's my code

<Navbar fixed="bottom" bg="light" variant="light">
  <Container>
   <Row>

      <Col sm>
        Browse Communities
      </Col>
      <Col sm >
        Tasks
      </Col>
      <Col sm>
        Profile
      </Col>

   </Row>
  </Container>
</Navbar>
```

答:
```<code>Try this way:
<Navbar fixed="bottom" bg="light" variant="light">
  <Container>
   <Row>
    <Nav>
      <Col sm={8}>
        <Nav.Link href="/communities">Browse Communities</Nav.Link>
      </Col>
      <Col sm={8}>
        <Nav.Link href="/tasks">Tasks</Nav.Link>
      </Col>
      <Col sm={8}>
        <Nav.Link href="/profile">Profile</Nav.Link>
      </Col>
    </Nav>
   </Row>
  </Container>
</Navbar>
</code>```

Title: React Bootstrap Layout in Navbar


问:
ORACLE SQL ORA-24344 - counting attendance function error
Hey guys I have a problem,
I want to create a function in ORACLE which will count number of attendance (how many subject has enrolled one student). Could you give me a tip I don't know if my syntax is even okay?</p>

```<code>CREATE OR REPLACE FUNCTION num_of_attendance (id_student IN NUMBER)
RETURN NUMBER
IS total_number_of_attendance NUMBER DEFAULT 0;
BEGIN
    WITH attendance AS
    (
        SELECT id_student, code_course, COUNT(DISTINCT code_subject)
        FROM STUDENT NATURAL INNER JOIN attendance NATURAL INNER JOIN course NATURAL INNER JOIN course_subject NATURAL INNER JOIN subject
    );
    RETURN total_number_of_attendance;
END;
/
</code>```

答:
First try to run the SQL statement outside the function.

Does this SQL statement runs without error ?

```<code>WITH attendance AS
    (
        SELECT id_student, code_course, COUNT(DISTINCT code_subject)
        FROM STUDENT NATURAL INNER JOIN attendance NATURAL INNER JOIN course NATURAL INNER JOIN course_subject NATURAL INNER JOIN subject
    );
</code>```

Second, if you need to return a value from a function you need to store this value using INTO variable clause with this general syntax:

```<code>SELECT ... INTO variable FROM ... WHERE ...
</code>```

Body:
Hey guys I have a problem,
I want to create a function in ORACLE which will count number of attendance (how many subject has enrolled one student). Could you give me a tip I don't know if my syntax is even okay?

CREATE OR REPLACE FUNCTION num_of_attendance (id_student IN NUMBER)
RETURN NUMBER
IS total_number_of_attendance NUMBER DEFAULT 0;
BEGIN
    WITH attendance AS
    (
        SELECT id_student, code_course, COUNT(DISTINCT code_subject)
        FROM STUDENT NATURAL INNER JOIN attendance NATURAL INNER JOIN course NATURAL INNER JOIN course_subject NATURAL INNER JOIN subject
    );
    RETURN total_number_of_attendance;
END;
/

Body:
First try to run the SQL statement outside the function.

Does this SQL statement runs without error ?

WITH attendance AS
    (
        SELECT id_student, code_course, COUNT(DISTINCT code_subject)
        FROM STUDENT NATURAL INNER JOIN attendance NATURAL INNER JOIN course NATURAL INNER JOIN course_subject NATURAL INNER JOIN subject
    );

Second, if you need to return a value from a function you need to store this value using INTO variable clause with this general syntax:

SELECT ... INTO variable FROM ... WHERE ...


问:
How to center an iframe horizontally?
Consider the following example: (live demo)

HTML:

```<code><div>div</div>
<iframe></iframe>
</code>```

CSS:

```<code>div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}
</code>```

Result:

Why the iframe is not centrally aligned like the div? How could I centrally align it?

答:
In my case solution was on iframe class adding:</p>

```<code>    display: block;
    margin-right: auto;
    margin-left: auto;
</code>```

Title: How to center an iframe horizontally?

Body:
Consider the following example: (live demo)

HTML:

div

CSS:

div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}

Result:

Why the iframe is not centrally aligned like the div? How could I centrally align it?

Body:
In my case solution was on iframe class adding:

    display: block;
    margin-right: auto;
    margin-left: auto;


问:
How to use mouse click in Processing?
I was working on an animation on processing. Then, I have a question about the lights. Normally, my code is more long. However, I made a simple code which can usefull also for the beginners.

```<code>boolean isOn = false;             // Variable keeping the state of the light
float sphereSize = 100;           // The size of Shpere
float xS = 200; yS = 200; zS = 0; // The coordinates of Sphere

void setup()
{
  size(400, 400, P3D);
  noStroke();
}

void draw()
{
  background(0);
  if (isOn)                       // Checks the state in which the light should be
    lights();
  translate(xS, yS, zS);          // Translate the sphere to the middle of window
  sphere(sphereSize);             // Making a sphere for see ligts
}

void mouseReleased() {            // This function is automatically called in draw method
  if (isOn)                       // After a click the state of the light is inverted
      isOn = false;
    else isOn = true;
}
</code>```

So, I want to work light only if the mouse click on the sphere. If the mouse click outside the sphere, it will not work. How to solve this problem? Thanks.

答:
Use dist() to compute the Euclidean distance between the mouse position (mouseX, mouseY) and the center of the sphere (xS, yS).

If the distance is less or equal than the radius (sphereSize), then switch the light:

void mouseReleased() {

    float distance = dist(xS, yS, mouseX, mouseY);
    if (distance <= sphereSize)
        isOn = !isOn;
}
```

Title: How to use mouse click in Processing?

Body:
I was working on an animation on processing. Then, I have a question about the lights. Normally, my code is more long. However, I made a simple code which can usefull also for the beginners.

boolean isOn = false;             // Variable keeping the state of the light
float sphereSize = 100;           // The size of Shpere
float xS = 200; yS = 200; zS = 0; // The coordinates of Sphere

void setup()
{
  size(400, 400, P3D);
  noStroke();
}

void draw()
{
  background(0);
  if (isOn)                       // Checks the state in which the light should be
    lights();
  translate(xS, yS, zS);          // Translate the sphere to the middle of window
  sphere(sphereSize);             // Making a sphere for see ligts
}

void mouseReleased() {            // This function is automatically called in draw method
  if (isOn)                       // After a click the state of the light is inverted
      isOn = false;
    else isOn = true;
}

So, I want to work light only if the mouse click on the sphere. If the mouse click outside the sphere, it will not work. How to solve this problem? Thanks.


问:
How to make bootstrap navbar work in my Rails movie review application
I included all the files that are needed to run the bootstrap, but the navbar is not working, it looks like normal HTML.

gemfile:

```<code>source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2', '>= 5.2.4.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'devise', '~> 4.7', '>= 4.7.1'
gem 'paperclip', '~> 6.1'
gem 'bootstrap-sass', '~> 3.4', '>= 3.4.1'
gem 'jquery-rails', '~> 4.4'
gem 'jquery-turbolinks', '~> 2.1'
gem 'rails-ujs', '~> 0.1.0'
gem 'sassc-rails', '~> 2.1', '>= 2.1.2'
</code>```

application.js:

```<code>//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
</code>```

application.scss:

```<code>@import "bootstrap-sprockets";
@import "bootstrap";
</code>```

This is the header file that I used for Navbar, _header.html.erb:

```<code><nav class="navbar" navbar-default role="navigation">
  <div class="container">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      <span class="sr-only"> Toggle Navigation</span>
      <span class="icon-bar"> </span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <%= link_to "Movies Reviews", root_path, class: "navbar-brand" %>
  </div>

  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
    <% if user_signed_in? %>
      <li><%= link_to "New Movie" , new_movie_path, class: "active" %> </li>
      <li> <%= link_to "Account", edit_user_registration_path %></li>
      <% else %>
        <li> <%= link_to "Sign Up", new_user_registration_path, class: "active" %></li>
        <li> <%= link_to "Sign In", new_user_session_path, class: "active" %></li>
      <% end %>
    </ul>
    <form class="navbar-form navbar-right">
      <div class="form_group">
        <input type="text" class="form-control" placeholder="search">
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
  </div>
  </div>
</nav>
</code>```

And application.html.erb:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Moviereview</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= render 'layouts/header' %>
    <% flash.each do |name, msg|%>
    <%= content_tag(:div ,msg, class:"alert alert_info")%>
    <% end %>
    <%= yield %>
  </body>
</html>
</code>```

I saw the same question and applied all the answers in that but don't get the proper result. Here is the output I am getting:

答:
Did you install bootstrap and its required dependencies with from the terminal?</p>

```<code>yarn add bootstrap jquery popper.js
</code>```

Body:
I included all the files that are needed to run the bootstrap, but the navbar is not working, it looks like normal HTML.

gemfile:

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2', '>= 5.2.4.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'devise', '~> 4.7', '>= 4.7.1'
gem 'paperclip', '~> 6.1'
gem 'bootstrap-sass', '~> 3.4', '>= 3.4.1'
gem 'jquery-rails', '~> 4.4'
gem 'jquery-turbolinks', '~> 2.1'
gem 'rails-ujs', '~> 0.1.0'
gem 'sassc-rails', '~> 2.1', '>= 2.1.2'

application.js:

//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

application.scss:

@import "bootstrap-sprockets";
@import "bootstrap";

This is the header file that I used for Navbar, _header.html.erb:

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
       Toggle Navigation

    </button>
    <%= link_to "Movies Reviews", root_path, class: "navbar-brand" %>

    <% if user_signed_in? %>

<%= link_to "New Movie" , new_movie_path, class: "active" %>

 <%= link_to "Account", edit_user_registration_path %>

      <% else %>

 <%= link_to "Sign Up", new_user_registration_path, class: "active" %>

 <%= link_to "Sign In", new_user_session_path, class: "active" %>

      <% end %>

    <form class="navbar-form navbar-right">

        <input type="text" class="form-control" placeholder="search">

      <button type="submit" class="btn btn-default">Submit</button>
    </form>

And application.html.erb:

<!DOCTYPE html>

    <title>Moviereview</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%= render 'layouts/header' %>
    <% flash.each do |name, msg|%>
    <%= content_tag(:div ,msg, class:"alert alert_info")%>
    <% end %>
    <%= yield %>

I saw the same question and applied all the answers in that but don't get the proper result. Here is the output I am getting:

Body:
Did you install bootstrap and its required dependencies with from the terminal?

yarn add bootstrap jquery popper.js


问:
What are the benefits of using the real image height and width?
What are the benefits to using an images real height and width when rendering HTML?  That is if I have an image that 100x100 pixels but I want to display something that is 95x95 pixels, should I resize the image on the server or can I let the browser handle this?  I'm really looking for a general rule along with the reason.  Thanks.</p>

```<code><img src="image.jpg" style="width: 95px; height: 95px;" alt="an image" />
</code>```

答:
Browsers handle resampling/interpolation of bitmap images differently when they're the ones resizing the images, which may or may not be controllable with CSS. This is elaborated on in detail in this post on Flickr's dev blog. If you resize the image in an image editor or by using server technology, you'll get consistent results across browsers.

In your case, a difference of under 5 pixels around will probably not be too much (unless you're concerned about pixel perfection!), but if you're trying to squeeze dimensionally or binarily large images into small rectangles, it's best to resize them beforehand. The reduced image dimensions and file size will help with bandwidth savings.


问:
Remove everything after the first whitespace in pandas dataframe
Here is the dataframe:

```<code>     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City
</code>```

I want the output to look like this:

```<code>     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix
</code>```

How to do it without using for loops ??

答:
Use Series.str.split with select first values by indexing:

```<code>print (df['RegionName'].str.split())
0             [New, York]
1          [Los, Angeles]
2          [Chicago, 865]
3    [Philadelphia, Wrin]
4         [Phoenix, City]
Name: RegionName, dtype: object

df['RegionName'] = df['RegionName'].str.split().str[0]
print (df)
  State    RegionName
0    NY           New
1    CA           Los
2    IL       Chicago
3    PA  Philadelphia
4    AZ       Phoeni
</code>```

Body:
Here is the dataframe:

     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City

I want the output to look like this:

     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix

How to do it without using for loops ??

Body:
Use Series.str.split with select first values by indexing:

print (df['RegionName'].str.split())
0             [New, York]
1          [Los, Angeles]
2          [Chicago, 865]
3    [Philadelphia, Wrin]
4         [Phoenix, City]
Name: RegionName, dtype: object

df['RegionName'] = df['RegionName'].str.split().str[0]
print (df)
  State    RegionName
0    NY           New
1    CA           Los
2    IL       Chicago
3    PA  Philadelphia
4    AZ       Phoeni


答:
With cut and tr:

```<code>apt list --installed | cut -f1 -d / | tr "\n" " "
</code>```

With sed:

```<code>apt list --installed | sed -E ':a;N;$!ba;s/\n/ /g;s/\/[^]]+\]//g'
</code>```

I think the first one is more readable and easier to understand.

Title: how to colate a list of installed packages into a "one-liner" for re-installing later (using only grep / cut / sed / awk etc, no external tools)

Body:
With cut and tr:

apt list --installed | cut -f1 -d / | tr "\n" " "

With sed:

apt list --installed | sed -E ':a;N;$!ba;s/\n/ /g;s/\/[^]]+\]//g'

I think the first one is more readable and easier to understand.


问:
How to display negative x values on the left side for barplot?
I would like to ask question regarding to barplot for seaborn.

I have a dataset returned from bigquery and converted to dataframe as below.

```<code>Sample data from `df.sort_values(by=['dep_delay_in_minutes']).to_csv(csv_file)`

,dep_delay_in_minutes,arrival_delay_in_minutes,numflights
1,-50.0,-38.0,2
2,-49.0,-59.5,4
3,-46.0,-28.5,4
4,-45.0,-44.0,4
5,-43.0,-53.0,4
6,-42.0,-35.0,6
7,-40.0,-26.0,4
8,-39.0,-33.5,4
9,-38.0,-21.5,4
10,-37.0,-37.666666666666664,12
11,-36.0,-35.0,2
12,-35.0,-32.57142857142857,14
13,-34.0,-30.0,18
14,-33.0,-26.200000000000003,10
15,-32.0,-34.8,10
16,-31.0,-28.769230769230766,26
17,-30.0,-34.93749999999999,32
18,-29.0,-31.375000000000004,48
19,-28.0,-24.857142857142854,70
20,-27.0,-28.837209302325583,86
</code>```

I wrote the code as below but the negative value is plotted on right hand side .

```<code>import matplotlib.pyplot as plt
import seaborn as sb
import pandas as pd
import numpy as np
import google.datalab.bigquery as bq
import warnings

# Disable warnings
warnings.filterwarnings('ignore')
sql="""
SELECT
  DEP_DELAY as dep_delay_in_minutes,
  AVG(ARR_DELAY) AS arrival_delay_in_minutes,
  COUNT(ARR_DELAY) AS numflights
FROM flights.simevents
GROUP BY DEP_DELAY
ORDER BY DEP_DELAY
"""

df = bq.Query(sql).execute().result().to_dataframe()
df = df.sort_values(['dep_delay_in_minutes'])

ax = sb.barplot(data=df, x='dep_delay_in_minutes', y='numflights', order=df['dep_delay_in_minutes'])
ax.set_xlim(-50, 0)
</code>```

How can I display x axis as numeric order with negative values on left hand side ?

I appreciate if I could get some adice.

答:
It doesn't work to specify left and right with ax.set_xlim(). It was displayed well with only one specification.

```<code>import matplotlib.pyplot as plt
import seaborn as sb
import pandas as pd
import numpy as np

df = df.sort_values(['dep_delay_in_minutes'])

ax = sb.barplot(x='dep_delay_in_minutes', y='numflights', data=df, order=df['dep_delay_in_minutes'])
ax.set_xlim(0.0)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45)

plt.show()
</code>```

A different notation was also possible.

```<code>ax.set_xlim(0.0,)
</code>```

Body:
I would like to ask question regarding to barplot for seaborn.

I have a dataset returned from bigquery and converted to dataframe as below.

Sample data from `df.sort_values(by=['dep_delay_in_minutes']).to_csv(csv_file)`

,dep_delay_in_minutes,arrival_delay_in_minutes,numflights
1,-50.0,-38.0,2
2,-49.0,-59.5,4
3,-46.0,-28.5,4
4,-45.0,-44.0,4
5,-43.0,-53.0,4
6,-42.0,-35.0,6
7,-40.0,-26.0,4
8,-39.0,-33.5,4
9,-38.0,-21.5,4
10,-37.0,-37.666666666666664,12
11,-36.0,-35.0,2
12,-35.0,-32.57142857142857,14
13,-34.0,-30.0,18
14,-33.0,-26.200000000000003,10
15,-32.0,-34.8,10
16,-31.0,-28.769230769230766,26
17,-30.0,-34.93749999999999,32
18,-29.0,-31.375000000000004,48
19,-28.0,-24.857142857142854,70
20,-27.0,-28.837209302325583,86

I wrote the code as below but the negative value is plotted on right hand side .

import matplotlib.pyplot as plt
import seaborn as sb
import pandas as pd
import numpy as np
import google.datalab.bigquery as bq
import warnings

# Disable warnings
warnings.filterwarnings('ignore')
sql="""
SELECT
  DEP_DELAY as dep_delay_in_minutes,
  AVG(ARR_DELAY) AS arrival_delay_in_minutes,
  COUNT(ARR_DELAY) AS numflights
FROM flights.simevents
GROUP BY DEP_DELAY
ORDER BY DEP_DELAY
"""

df = bq.Query(sql).execute().result().to_dataframe()
df = df.sort_values(['dep_delay_in_minutes'])

ax = sb.barplot(data=df, x='dep_delay_in_minutes', y='numflights', order=df['dep_delay_in_minutes'])
ax.set_xlim(-50, 0)

How can I display x axis as numeric order with negative values on left hand side ?

I appreciate if I could get some adice.

Body:
It doesn't work to specify left and right with ax.set_xlim(). It was displayed well with only one specification.

import matplotlib.pyplot as plt
import seaborn as sb
import pandas as pd
import numpy as np

df = df.sort_values(['dep_delay_in_minutes'])

ax = sb.barplot(x='dep_delay_in_minutes', y='numflights', data=df, order=df['dep_delay_in_minutes'])
ax.set_xlim(0.0)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45)

plt.show()

A different notation was also possible.

ax.set_xlim(0.0,)


问:
Flask babel not working on simple translation?
Ok I have the following app:

babel.cfg

```<code>[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
</code>```

lucy/init.py

```<code>babel = Babel()

def create_app(object_name):
  app = Flask(__name__)
  app.config.from_object(object_name)

  app.register_blueprint(main_blueprint)
  app.register_blueprint(category_blueprint)
  app.register_blueprint(item_blueprint)

  babel.init_app(app)
  db.init_app(app)
  return app

@babel.localeselector
def get_locale():
  return 'de'
</code>```

lucy/controllers/main.py

```<code>main_blueprint = Blueprint(
    'main',
    __name__,
    template_folder='../templates/main',
)

@main_blueprint.route('/debug')
def debug():
  print get_locale()
  return gettext('A simple string')
</code>```

I ran the following commands:

pybabel extract -F babel.cfg -o messages.pot .

pybabel init -i messages.pot -d translations -l de

pybabel compile -d translations/

This is what my project structure looks like:

```<code>.
|-- README.md
|-- babel.cfg
|-- fabfile.py
|-- lucy
|   |-- __init__.py
|   |-- config.py
|   |-- controllers
|   |   |-- __init__.py
|   |   |-- category.py
|   |   |-- item.py
|   |   `-- main.py
|   |-- forms.py
|   |-- models.py
|   |-- static
|   |   |-- css
|   |   `-- js
|   `-- templates
|       |-- boilerplate
|       |   |-- items.html
|       |   `-- layout.html
|       |-- category
|       |   `-- show.html
|       |-- item
|       |   |-- index.html
|       |   `-- show.html
|       `-- main
|           `-- signup.html
|-- manage.py
|-- messages.pot
|-- requirements.txt
|-- tests
|   |-- __init__.py
|   `-- test_models.py
`-- translations
    `-- de
        `-- LC_MESSAGES
            |-- messages.mo
            `-- messages.po
</code>```

These are the results from translation:

messages.pot

```<code># Translations template for PROJECT.
# Copyright (C) 2016 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2016.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2016-07-19 16:07+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.3.4\n"

#: lucy/controllers/main.py:20
msgid "A simple string"
msgstr ""
</code>```

translation/de/LC_MESSAGES/message.po

```<code># German translations for PROJECT.
# Copyright (C) 2016 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2016.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2016-07-19 16:07+0800\n"
"PO-Revision-Date: 2016-07-19 16:07+0800\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: de\n"
"Language-Team: de <LL@li.org>\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.3.4\n"

#: lucy/controllers/main.py:20
msgid "A simple string"
msgstr "german string berlin"
</code>```

translation/de/LC_MESSAGES/message.mo

```<code>??,<=?M?A simple stringProject-Id-Version: PROJECT VERSION
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 2016-07-19 16:07+0800
PO-Revision-Date: 2016-07-19 16:07+0800
Last-Translator: FULL NAME <EMAIL@ADDRESS>
Language: de
Language-Team: de <LL@li.org>
Plural-Forms: nplurals=2; plural=(n != 1)
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel 2.3.4
german string berlin
</code>```

When I visit /debug, I see that my locale is de. However, I still see A simple string being outputted. Any ideas why?

答:
My answer is the same as fmelan's, but I use absolute path:</p>

```<code>from flask import Flask
import os

base_dir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["BABEL_TRANSLATION_DIRECTORIES"] = os.path.join(base_dir, "app/translation")
</code>```

Body:
Ok I have the following app:

babel.cfg

[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_

lucy/init.py

babel = Babel()

def create_app(object_name):
  app = Flask(__name__)
  app.config.from_object(object_name)

  app.register_blueprint(main_blueprint)
  app.register_blueprint(category_blueprint)
  app.register_blueprint(item_blueprint)

  babel.init_app(app)
  db.init_app(app)
  return app

@babel.localeselector
def get_locale():
  return 'de'

lucy/controllers/main.py

main_blueprint = Blueprint(
    'main',
    __name__,
    template_folder='../templates/main',
)

@main_blueprint.route('/debug')
def debug():
  print get_locale()
  return gettext('A simple string')

I ran the following commands:

pybabel extract -F babel.cfg -o messages.pot .

pybabel init -i messages.pot -d translations -l de

pybabel compile -d translations/

This is what my project structure looks like:

.
|-- README.md
|-- babel.cfg
|-- fabfile.py
|-- lucy
|   |-- __init__.py
|   |-- config.py
|   |-- controllers
|   |   |-- __init__.py
|   |   |-- category.py
|   |   |-- item.py
|   |   `-- main.py
|   |-- forms.py
|   |-- models.py
|   |-- static
|   |   |-- css
|   |   `-- js
|   `-- templates
|       |-- boilerplate
|       |   |-- items.html
|       |   `-- layout.html
|       |-- category
|       |   `-- show.html
|       |-- item
|       |   |-- index.html
|       |   `-- show.html
|       `-- main
|           `-- signup.html
|-- manage.py
|-- messages.pot
|-- requirements.txt
|-- tests
|   |-- __init__.py
|   `-- test_models.py
`-- translations
    `-- de
        `-- LC_MESSAGES
            |-- messages.mo
            `-- messages.po

These are the results from translation:

messages.pot

# Translations template for PROJECT.
# Copyright (C) 2016 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2016.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2016-07-19 16:07+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.3.4\n"

#: lucy/controllers/main.py:20
msgid "A simple string"
msgstr ""

translation/de/LC_MESSAGES/message.po

# German translations for PROJECT.
# Copyright (C) 2016 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2016.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2016-07-19 16:07+0800\n"
"PO-Revision-Date: 2016-07-19 16:07+0800\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: de\n"
"Language-Team: de <LL@li.org>\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.3.4\n"

#: lucy/controllers/main.py:20
msgid "A simple string"
msgstr "german string berlin"

translation/de/LC_MESSAGES/message.mo

??,<=?M?A simple stringProject-Id-Version: PROJECT VERSION
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 2016-07-19 16:07+0800
PO-Revision-Date: 2016-07-19 16:07+0800
Last-Translator: FULL NAME <EMAIL@ADDRESS>
Language: de
Language-Team: de <LL@li.org>
Plural-Forms: nplurals=2; plural=(n != 1)
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel 2.3.4
german string berlin

When I visit /debug, I see that my locale is de. However, I still see A simple string being outputted. Any ideas why?

Body:
My answer is the same as fmelan's, but I use absolute path:

from flask import Flask
import os

base_dir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["BABEL_TRANSLATION_DIRECTORIES"] = os.path.join(base_dir, "app/translation")


问:
CSS complex grid auto layout
I am making a website with unknown number of cells in the layout and I would like to make the styles with CSS only.

My idea was using CSS grid, but is there a way of using it in a the manner shown on the image? I was thinking some kind of :nth-child kind of stuff? The number of "sections" (each 4 squares tall in this scenario) is always three in a row, but unknown number of rows.

I came up with this, but it puts the fourth section onto #1; and it does not work with unknown number of sections/rows.

.container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: repeat(3, [img-start] 200px [img-end basic-start] 200px [basic-end me-start] auto [me-end why-start] auto [why-end]);
    justify-content: center;
    align-items: center;
}
.container div:nth-child(12n-11), .container div:nth-child(12n-10), .container div:nth-child(12n-9), .container div:nth-child(12n-8) {
    grid-column: 1;
}
.container div:nth-child(12n-7), .container div:nth-child(12n-6), .container div:nth-child(12n-5), .container div:nth-child(12n-4) {
    grid-column: 2;
}
.container div:nth-child(12n-3), .container div:nth-child(12n-2), .container div:nth-child(12n-1), .container div:nth-child(12n) {
    grid-column: 3;
}

.container div:nth-child(4n-3) {
    grid-row: img;
}
.container div:nth-child(4n-2) {
    grid-row: basic;
}
.container div:nth-child(4n-1) {
    grid-row: me;
}
.container div:nth-child(4n) {
    grid-row: why;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div>div1</div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
<div>div5</div>
<div>div6</div>
<div>div7</div>
<div>div8</div>
<div>div9</div>
<div>div10</div>
<div>div11</div>
<div>div12</div>
</div></code>```

答:
You can try something like below:

.container {
  display: grid;
  grid-auto-flow:dense; /* don't leave any empty cell */
  grid-auto-rows:50px; /* 50px for each row */
  grid-auto-columns:1fr; /* 1fr for each column */
  counter-reset:num;
}
.container > * {
  grid-column:1; /* all of them in the first column by default*/
}

.container > *:nth-child(12n + 5),
.container > *:nth-child(12n + 6),
.container > *:nth-child(12n + 7),
.container > *:nth-child(12n + 8) {
  grid-column:2; /* 2nd column from 5 to 8*/
}
.container > *:nth-child(12n + 9),
.container > *:nth-child(12n + 10),
.container > *:nth-child(12n + 11),
.container > *:nth-child(12n + 12) {
  grid-column:3; /* 3rd column from 9 to 12 */
}

.container > *::before {
  content:counter(num);
  counter-increment:num;
  font-size:30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div></code>```

Title: CSS complex grid auto layout

Body:
I am making a website with unknown number of cells in the layout and I would like to make the styles with CSS only.

My idea was using CSS grid, but is there a way of using it in a the manner shown on the image? I was thinking some kind of :nth-child kind of stuff? The number of "sections" (each 4 squares tall in this scenario) is always three in a row, but unknown number of rows.

I came up with this, but it puts the fourth section onto #1; and it does not work with unknown number of sections/rows.

.container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: repeat(3, [img-start] 200px [img-end basic-start] 200px [basic-end me-start] auto [me-end why-start] auto [why-end]);
    justify-content: center;
    align-items: center;
}
.container div:nth-child(12n-11), .container div:nth-child(12n-10), .container div:nth-child(12n-9), .container div:nth-child(12n-8) {
    grid-column: 1;
}
.container div:nth-child(12n-7), .container div:nth-child(12n-6), .container div:nth-child(12n-5), .container div:nth-child(12n-4) {
    grid-column: 2;
}
.container div:nth-child(12n-3), .container div:nth-child(12n-2), .container div:nth-child(12n-1), .container div:nth-child(12n) {
    grid-column: 3;
}

.container div:nth-child(4n-3) {
    grid-row: img;
}
.container div:nth-child(4n-2) {
    grid-row: basic;
}
.container div:nth-child(4n-1) {
    grid-row: me;
}
.container div:nth-child(4n) {
    grid-row: why;
}

div1

div2

div3

div4

div5

div6

div7

div8

div9

div10

div11

div12

Body:
You can try something like below:

.container {
  display: grid;
  grid-auto-flow:dense; /* don't leave any empty cell */
  grid-auto-rows:50px; /* 50px for each row */
  grid-auto-columns:1fr; /* 1fr for each column */
  counter-reset:num;
}
.container > * {
  grid-column:1; /* all of them in the first column by default*/
}

.container > *:nth-child(12n + 5),
.container > *:nth-child(12n + 6),
.container > *:nth-child(12n + 7),
.container > *:nth-child(12n + 8) {
  grid-column:2; /* 2nd column from 5 to 8*/
}
.container > *:nth-child(12n + 9),
.container > *:nth-child(12n + 10),
.container > *:nth-child(12n + 11),
.container > *:nth-child(12n + 12) {
  grid-column:3; /* 3rd column from 9 to 12 */
}

.container > *::before {
  content:counter(num);
  counter-increment:num;
  font-size:30px;
}

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>


问:
Oreo: Broadcast receiver Not working
I was trying to get notification trigger on my application whenever the user makes a new call. I'm registering receiver in my activity and destroying it in onDestroy() method. Following is the code snippets for registering

```<code>registerReceiver(inComingCall = new IncomingCall(),new IntentFilter("android.intent.action.PHONE_STATE"));
</code>```

The issue I'm facing is I'm not getting any trigger in override onReceive() method for the Broadcast receiver. Kindly let me know whether any new implementations or the separate way I should do for receiving the broadcast especially for Oreo.

Thanks in Advance.

答:
None of the above answers seem to work for me.
Here is my solution but in kotlin. Paste the following parts of the code and change the necessary details as per your app.

After onCreate method in Mainactivity:

```<code>override fun onStart() {
    super.onStart()
    var intentfilter1: IntentFilter = IntentFilter("com.spotify.music.playbackstatechanged")

    intentfilter1.addCategory(Intent.CATEGORY_DEFAULT)
    registerReceiver(mreceiver, intentfilter1)

}

override fun onStop() {
    super.onStop()
    unregisterReceiver(mreceiver)
}
</code>```

In onCreate method:

```<code>mreceiver = SpotifyBroadcastReceiver()
</code>```

In MainAvtivity before onCreate method:

```<code>lateinit var mreceiver: SpotifyBroadcastReceiver
</code>```

Mainfest.xml file

```<code>     <receiver android:name=".SpotifyBroadcastReceiver" //name of the broadcast receiver class
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.spotify.music.playbackstatechanged" /> //Things required by my broadcast receiver class
        </intent-filter>
    </receiver>
</code>```

Let me know if i missed something or you need some other info related to the snippet.

P.S: Im new to kotlin too....im just sharing what worked for me. It might or might not work for you configuration so Happy coding!!

Title: Oreo: Broadcast receiver Not working

Body:
I was trying to get notification trigger on my application whenever the user makes a new call. I'm registering receiver in my activity and destroying it in onDestroy() method. Following is the code snippets for registering

registerReceiver(inComingCall = new IncomingCall(),new IntentFilter("android.intent.action.PHONE_STATE"));

The issue I'm facing is I'm not getting any trigger in override onReceive() method for the Broadcast receiver. Kindly let me know whether any new implementations or the separate way I should do for receiving the broadcast especially for Oreo.

Thanks in Advance.

Body:
None of the above answers seem to work for me.
Here is my solution but in kotlin. Paste the following parts of the code and change the necessary details as per your app.

After onCreate method in Mainactivity:

override fun onStart() {
    super.onStart()
    var intentfilter1: IntentFilter = IntentFilter("com.spotify.music.playbackstatechanged")

    intentfilter1.addCategory(Intent.CATEGORY_DEFAULT)
    registerReceiver(mreceiver, intentfilter1)

}

override fun onStop() {
    super.onStop()
    unregisterReceiver(mreceiver)
}

In onCreate method:

mreceiver = SpotifyBroadcastReceiver()

In MainAvtivity before onCreate method:

lateinit var mreceiver: SpotifyBroadcastReceiver

Mainfest.xml file

     <receiver android:name=".SpotifyBroadcastReceiver" //name of the broadcast receiver class
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.spotify.music.playbackstatechanged" /> //Things required by my broadcast receiver class
        </intent-filter>
    </receiver>

Let me know if i missed something or you need some other info related to the snippet.

P.S: Im new to kotlin too....im just sharing what worked for me. It might or might not work for you configuration so Happy coding!!


问:
JPA - Attempt to create NamedEntityGraph to avoid multiple selects (parent with OneToOne and OneToMany children)
I have been out of practice with JPA for years and I am now retrying things (using Spring boot/Hibernate)

I have the following (Kotlin)

```<code>@NamedEntityGraphs(*[
    NamedEntityGraph(
            name = "user-role",
            attributeNodes = [
                NamedAttributeNode("name") ,
                NamedAttributeNode("userRoles", subgraph = "roleproperties")] ,
            subgraphs = [
                NamedSubgraph (name="roleproperties", attributeNodes = [NamedAttributeNode("roleType")])]
    )
])

@Entity
@Table(name = "[user]")
class UserEntity(
        @Id  @Column(name="id")
        val id: UUID,
        val name: String,
        val email: String,
        @OneToMany(fetch= FetchType.LAZY) @JoinColumn(name="user_id")
        val userRoles: Set<UserRoleEntity> ,
        @OneToOne(fetch= FetchType.LAZY, optional = true ) @JoinColumn(name="id")
        val userProperties: UserPropertiesEntity
) { }

...

@Entity
@Table(name = "user_role")
class UserRoleEntity(
        @Id
        val id: UUID,
        val roleType: String
)
@Entity
@Table(name = "user_properties")
class UserPropertiesEntity(
    @Id
    val userId: UUID,
    val updatedBy: UUID?,
    val updatedAt: Timestamp?,
    val properties: String?
    ) {}

...
</code>```

When querying using the 'user-role' graph, and looking at the SQL, 2 statements are executed
The first joins user with user_role table (which is what I would expect)
The second query however is a select on the user_properties table. I don't understand why this second select is there. The idea is that nothing is needed from the user_properties table.

The user-role graph is used as follows

```<code>val graph = entityManager.getEntityGraph("user-properties")
val properties: MutableMap<String, Any> = HashMap()
properties["javax.persistence.fetchgraph"] = graph
val ue = entityManager.find(UserEntity::class.java, UUID.fromString(id), properties)
</code>```

All tips welcomed!

Tx

Peter

答:
The second query for fetching the user_properties is needed due to the fact that hibernate needs to know whether it should place a null or a proxy for the one-to-one relation of UserEntity for UserPropertiesEntity field.

To say in other words; even if you specified the relation as lazy, there is no way hibernate would know whether the relation is null or it should put a proxy for the corresponding userProperties field, hence it needs to execute the second query to fetch the user properties. In other words; hibernate is not able to respect the fetch strategy FetchType.LAZY for one-to-one relation.

You can look at the following post if you really want to make the association truely lazy.

Body:
I have been out of practice with JPA for years and I am now retrying things (using Spring boot/Hibernate)

I have the following (Kotlin)

@NamedEntityGraphs(*[
    NamedEntityGraph(
            name = "user-role",
            attributeNodes = [
                NamedAttributeNode("name") ,
                NamedAttributeNode("userRoles", subgraph = "roleproperties")] ,
            subgraphs = [
                NamedSubgraph (name="roleproperties", attributeNodes = [NamedAttributeNode("roleType")])]
    )
])

@Entity
@Table(name = "[user]")
class UserEntity(
        @Id  @Column(name="id")
        val id: UUID,
        val name: String,
        val email: String,
        @OneToMany(fetch= FetchType.LAZY) @JoinColumn(name="user_id")
        val userRoles: Set<UserRoleEntity> ,
        @OneToOne(fetch= FetchType.LAZY, optional = true ) @JoinColumn(name="id")
        val userProperties: UserPropertiesEntity
) { }

...

@Entity
@Table(name = "user_role")
class UserRoleEntity(
        @Id
        val id: UUID,
        val roleType: String
)
@Entity
@Table(name = "user_properties")
class UserPropertiesEntity(
    @Id
    val userId: UUID,
    val updatedBy: UUID?,
    val updatedAt: Timestamp?,
    val properties: String?
    ) {}

...

When querying using the 'user-role' graph, and looking at the SQL, 2 statements are executed
The first joins user with user_role table (which is what I would expect)
The second query however is a select on the user_properties table. I don't understand why this second select is there. The idea is that nothing is needed from the user_properties table.

The user-role graph is used as follows

val graph = entityManager.getEntityGraph("user-properties")
val properties: MutableMap<String, Any> = HashMap()
properties["javax.persistence.fetchgraph"] = graph
val ue = entityManager.find(UserEntity::class.java, UUID.fromString(id), properties)

All tips welcomed!

Tx

Peter


问:
Python3: Length of values does not match length of index
I'm trying to combine pandas to retrieve the values of a number of tables in the fixtures, but on the extraction I'm also willing to include the href tags contained within the tables, however I come across an error:

The code is:

```<code>import numpy as nd
import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-1'
df = pd.read_html(url, attrs={'class': 'calendaritable'})[0]

print(df)

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

links = []
for tr in soup.findAll("tr"):
    trs = tr.findAll("td")
    for each in trs:
        try:
            link = each.find('a')['href']
            links.append(link)
        except:
            pass

df['Links'] = links
print (df.to_string())
</code>```

答:
This is the code I have written and does the job for me:

```<code>import numpy as nd
import pandas as pd

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-{}'
hoja = 'grup-{}'

xlwriter = pd.ExcelWriter('Resultados.xlsx')

for i in range(1,19):
  converturl = url.format(i)
  # print(url)
  dfResultats = pd.read_html(converturl, header=0)
  numgrupo = hoja.format(i)
  tablelen = len (dfResultats)
  tablelen = tablelen - 1
  strrow = 0
  strcol = 0
  for x in range (1,tablelen):
   df = dfResultats[x]
   df.to_excel(xlwriter,sheet_name=numgrupo, index=False, startrow=strrow , startcol=strcol)
   strrow = strrow + 9

xlwriter.close()
</code>```

The idea was to enhance the code to include the hrefs on the excel sheet, as this includes to link to the game details which I need to extract later.

Body:
I'm trying to combine pandas to retrieve the values of a number of tables in the fixtures, but on the extraction I'm also willing to include the href tags contained within the tables, however I come across an error:

The code is:

import numpy as nd
import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-1'
df = pd.read_html(url, attrs={'class': 'calendaritable'})[0]

print(df)

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

links = []
for tr in soup.findAll("tr"):
    trs = tr.findAll("td")
    for each in trs:
        try:
            link = each.find('a')['href']
            links.append(link)
        except:
            pass

df['Links'] = links
print (df.to_string())

Body:
This is the code I have written and does the job for me:

import numpy as nd
import pandas as pd

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-{}'
hoja = 'grup-{}'

xlwriter = pd.ExcelWriter('Resultados.xlsx')

for i in range(1,19):
  converturl = url.format(i)
  # print(url)
  dfResultats = pd.read_html(converturl, header=0)
  numgrupo = hoja.format(i)
  tablelen = len (dfResultats)
  tablelen = tablelen - 1
  strrow = 0
  strcol = 0
  for x in range (1,tablelen):
   df = dfResultats[x]
   df.to_excel(xlwriter,sheet_name=numgrupo, index=False, startrow=strrow , startcol=strcol)
   strrow = strrow + 9

xlwriter.close()

The idea was to enhance the code to include the hrefs on the excel sheet, as this includes to link to the game details which I need to extract later.


问:
Newline character insertion in Java
How can I insert a newline character in a Java applet program if I am using "label" instead of System.out.println()?

Thanks in advance.

答:
JLabel?

If you're using JLabel, you can use basic HTML in it

Try the following:

```<code><html>Text<br>more text</html>
</code>```

See this other answer

And upvote it too ;)

OwnerDisplayName: harsha

Title: Newline character insertion in Java

Body:
JLabel?

If you're using JLabel, you can use basic HTML in it

Try the following:

<html>Text<br>more text</html>

See this other answer

And upvote it too ;)

OwnerDisplayName: Oscar Reyes

ContentLicense: CC BY-SA 2.5