问:
Select your grade from the list

so what i'm trying to do is:
When you select a grade
, a function will be triggered and output the book covers (images of the book covers)  of the selected grade.

    const select = document.querySelector('#my');
    const img = document.querySelectorAll('img');

    select.addEventListener('change', e => {

        const gradeString = e.target.value;
        const url = `history covers/grade${gradeString}.jpeg`;
        // images in array so i need to loop through all of the imgs and update each one at a time
        img.src = url;
        img.alt = `grade${gradeString}`;
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Select your grade from the list.</p>

    <p>When you select a grade, a function is triggered which outputs the book covers of the selected grade.</p>

    <select id="my">
        <option class="btn" value="all">All Grades</option>
        <option class="btn" value="1">Grade 1</option>
        <option class="btn" value="2">Grade 2</option>
        <option class="btn" value="3">Grade 3</option>
        <option class="btn" value="4">Grade 4</option>
        <option class="btn" value="5">Grade 5</option>
        <option class="btn" value="6">Grade 6</option>
        <option class="btn" value="7">Grade 7</option>
        <option class="btn" value="8">Grade 8</option>
      </select>

      <img src="history covers/grade6-dor.jpeg">
      <img src="history covers/grade8.jpeg">
      <img src="history covers/grade7.jpeg">
      <img src="history covers/grade6-mahavak.jpeg">

      </code>```

答:
add all your images to your html and set the css to display none.  Then in your js just change the style to block for the image you want.  That image will be your gradeString - 1

const select = document.querySelector('#my');
    const img = document.querySelectorAll('img');

    select.addEventListener('change', e => {

        const gradeString = e.target.value;

        img[gradeString-1].style.display='block'

    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.images{
   display:none;
}</code>```

Select your grade from the list.

When you select a grade, a function is triggered which outputs the book covers of the selected grade.

    <select id="my">
        <option class="btn" value="all">All Grades</option>
        <option class="btn" value="1">Grade 1</option>
        <option class="btn" value="2">Grade 2</option>
        <option class="btn" value="3">Grade 3</option>
        <option class="btn" value="4">Grade 4</option>
        <option class="btn" value="5">Grade 5</option>
        <option class="btn" value="6">Grade 6</option>
        <option class="btn" value="7">Grade 7</option>
        <option class="btn" value="8">Grade 8</option>
      </select>

      ```

Title: Select your grade from the list

Body:
so what i'm trying to do is:
When you select a grade
, a function will be triggered and output the book covers (images of the book covers)  of the selected grade.

    const select = document.querySelector('#my');
    const img = document.querySelectorAll('img');

    select.addEventListener('change', e => {

        const gradeString = e.target.value;
        const url = `history covers/grade${gradeString}.jpeg`;
        // images in array so i need to loop through all of the imgs and update each one at a time
        img.src = url;
        img.alt = `grade${gradeString}`;
    })

Select your grade from the list.

When you select a grade, a function is triggered which outputs the book covers of the selected grade.

    <select id="my">
        <option class="btn" value="all">All Grades</option>
        <option class="btn" value="1">Grade 1</option>
        <option class="btn" value="2">Grade 2</option>
        <option class="btn" value="3">Grade 3</option>
        <option class="btn" value="4">Grade 4</option>
        <option class="btn" value="5">Grade 5</option>
        <option class="btn" value="6">Grade 6</option>
        <option class="btn" value="7">Grade 7</option>
        <option class="btn" value="8">Grade 8</option>
      </select>

Body:
add all your images to your html and set the css to display none.  Then in your js just change the style to block for the image you want.  That image will be your gradeString - 1

const select = document.querySelector('#my');
    const img = document.querySelectorAll('img');

    select.addEventListener('change', e => {

        const gradeString = e.target.value;

        img[gradeString-1].style.display='block'

    })

.images{
   display:none;
}

<p>Select your grade from the list.</p>

    <p>When you select a grade, a function is triggered which outputs the book covers of the selected grade.</p>

    <select id="my">
        <option class="btn" value="all">All Grades</option>
        <option class="btn" value="1">Grade 1</option>
        <option class="btn" value="2">Grade 2</option>
        <option class="btn" value="3">Grade 3</option>
        <option class="btn" value="4">Grade 4</option>
        <option class="btn" value="5">Grade 5</option>
        <option class="btn" value="6">Grade 6</option>
        <option class="btn" value="7">Grade 7</option>
        <option class="btn" value="8">Grade 8</option>
      </select>

      <img class='images' src="https://via.placeholder.com/150">
      <img class='images' src="https://via.placeholder.com/150">
      <img class='images' src="https://via.placeholder.com/150">
      <img class='images' src="https://via.placeholder.com/150">
      <img class='images' src="https://via.placeholder.com/150">
      <img class='images' src="https://via.placeholder.com/150">
      <img class='images' src="https://via.placeholder.com/150">
      <img class='images' src="https://via.placeholder.com/150">


来源: stackexchange

问:
Size to fit font on a canvas
I currently have this http://jsfiddle.net/dgAEY/ which works perfectly, I just need to figure out a way to size the font when it gets too long. I've looked into Auto-size dynamic text to fill fixed size container and I've tried to apply the Jquery function they posted but I couldn't get it to work.

HTML

```<code><form action="" method="POST" id="nametag" class="nametag">
    Line1:
    <input type="text" id="line1" name="line1" style="width:250px;" /><br>
    Line2:
    <input type="text" id="line2" name="line2" style="width:250px;" /><br>
    Line3:
    <input type="text" id="line3" name="line3" style="width:250px;" /><br>
    Line4:
    <input type="text" id="line4" name="line4" style="width:250px;" /><br>

    <br><br><b>Name Tag</b><br>
    <canvas width="282px" height="177px" id="myCanvas" style="border: black thin solid;"></canvas>
</form>
</code>```

JavaScript

```<code>$(document).ready(function () {
    var canvas = $('#myCanvas')[0];
    var context = canvas.getContext('2d');

    var imageObj = new Image();
    imageObj.onload = function() {
        context.drawImage(imageObj, 0, 0);
    };
    imageObj.src = "http://dummyimage.com/282x177/FFF/FFF";

    $('#nametag').bind('change keyup input', updateCanvas);
    $('#line2').bind('click', updateCanvas);
    $('#line3').bind('click', updateCanvas);
    $('#line4').bind('click', updateCanvas);

    function updateCanvas() {

        context.clearRect(0, 0, canvas.width, canvas.height);
        context.drawImage(imageObj, 0, 0);
        context.textAlign = "center";

        context.font = "bold 18pt Arial";
        context.fillText($('#line1').val(), canvas.width * 0.5, 70);

        context.font = "12pt Arial";
        context.fillText($('#line2').val(), canvas.width * 0.5, 90);
        context.fillText($('#line3').val(), canvas.width * 0.5, 120);
        context.fillText($('#line4').val(), canvas.width * 0.5, 140);

    }
});
</code>```

答:
If you wanna do it the other way around (size the canvas to the font, not the font to the canvas), you can do something like the following (not fully tested):</p>
```<code>var canvas    = document.getElementById('canvas00')
var ctx       = canvas.getContext('2d')
var str       = 'Jesus is God Almighty'
ctx.font      = 'bold 3em'

var metrics   = ctx.measureText(str)
canvas.width  = metrics.width
canvas.height = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent  // Use *fontBoundingBox* or *actualBoundingBox*, depending on your needs
ctx.font      = 'bold 3em'  // For some reason you have to call this again?
ctx.fillStyle = '#3240ff'

ctx.fillText(str, 0, canvas.height - metrics.fontBoundingBoxDescent)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Size to fit font on a canvas

Body:
I currently have this http://jsfiddle.net/dgAEY/ which works perfectly, I just need to figure out a way to size the font when it gets too long. I've looked into Auto-size dynamic text to fill fixed size container and I've tried to apply the Jquery function they posted but I couldn't get it to work.

HTML

<form action="" method="POST" id="nametag" class="nametag">
    Line1:
    <input type="text" id="line1" name="line1" style="width:250px;" />

    Line2:
    <input type="text" id="line2" name="line2" style="width:250px;" />

    Line3:
    <input type="text" id="line3" name="line3" style="width:250px;" />

    Line4:
    <input type="text" id="line4" name="line4" style="width:250px;" />

Name Tag

    <canvas width="282px" height="177px" id="myCanvas" style="border: black thin solid;"></canvas>
</form>

JavaScript

$(document).ready(function () {
    var canvas = $('#myCanvas')[0];
    var context = canvas.getContext('2d');

    var imageObj = new Image();
    imageObj.onload = function() {
        context.drawImage(imageObj, 0, 0);
    };
    imageObj.src = "http://dummyimage.com/282x177/FFF/FFF";

    $('#nametag').bind('change keyup input', updateCanvas);
    $('#line2').bind('click', updateCanvas);
    $('#line3').bind('click', updateCanvas);
    $('#line4').bind('click', updateCanvas);

    function updateCanvas() {

        context.clearRect(0, 0, canvas.width, canvas.height);
        context.drawImage(imageObj, 0, 0);
        context.textAlign = "center";

        context.font = "bold 18pt Arial";
        context.fillText($('#line1').val(), canvas.width * 0.5, 70);

        context.font = "12pt Arial";
        context.fillText($('#line2').val(), canvas.width * 0.5, 90);
        context.fillText($('#line3').val(), canvas.width * 0.5, 120);
        context.fillText($('#line4').val(), canvas.width * 0.5, 140);

    }
});

Body:
If you wanna do it the other way around (size the canvas to the font, not the font to the canvas), you can do something like the following (not fully tested):

var canvas    = document.getElementById('canvas00')
var ctx       = canvas.getContext('2d')
var str       = 'Jesus is God Almighty'
ctx.font      = 'bold 3em'

var metrics   = ctx.measureText(str)
canvas.width  = metrics.width
canvas.height = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent  // Use *fontBoundingBox* or *actualBoundingBox*, depending on your needs
ctx.font      = 'bold 3em'  // For some reason you have to call this again?
ctx.fillStyle = '#3240ff'

ctx.fillText(str, 0, canvas.height - metrics.fontBoundingBoxDescent)

ContentLicense: CC BY-SA 4.0


问:
Issues with Modals React Native
everyone. I'm new in this new tecnology and I'm having a little problem with modals.

I'm programming a modal that only shows when a condition is true, in the first click it's all ok, but in the second the modal won't show, then when I click again, the window appears again, and continue successively.

The code works as follow: I have 3 states, each represent a different text to show in the modal. Then, I have a modal, that recieves a message (to print) and the state to identifies what state i need to show. And finally, in the main, I have a condition who calls the modal and show it ONLY if the state is true.

I checked the states with console.log and the only issue i find is that in some cases, the state is set in true, when is false, but i don't know why!

Thanks for read!

Here i detach part of the code.

Declare of the states in the main

```<code>const [modalVisibleEnTermino, setModalVisibleEnTermino] = useState(false)

const [modalVisibleFueraTermino, setModalVisibleFueraTermino] = useState(false)

const [modalVisibleRefuerzoTermino, setModalVisibleRefuezoTermino] = useState(false)
</code>```

Condtition in main to show the apropiate state of modal

```<code>const setModal = () => {
    vacunas ===2 && (days>6 && days<150) ? setModalVisibleEnTermino(true) : setModalVisibleFueraTermino(true)
    if(vacunas == 3)
        setModalVisibleRefuezoTermino(true)
}
</code>```

Function to reset the states after showing modal (IDK if its ok)

```<code> const restoreModals = () => {
    if (modalVisibleEnTermino) setModalVisibleEnTermino(false)
    if (modalVisibleFueraTermino) setModalVisibleFueraTermino(false)
    if (modalVisibleRefuerzoTermino) setModalVisibleRefuezoTermino(false)
}
</code>```

After set the modal, I checked what state it's true, and I passed the values in this condition

```<code>{modalVisibleEnTermino && <MyModal
                    message={"Mensaje1"}
                    state={modalVisibleEnTermino}
                    />
                }

                {modalVisibleFueraTermino && <MyModal
                    message={"Mensaje2."}
                    state={modalVisibleFueraTermino}
                    />
                }

                {modalVisibleRefuerzoTermino && <MyModal
                    message={"Mensaje3."}
                    state={modalVisibleRefuerzoTermino}
                    />
                }
</code>```

Modal

```<code>export const MyModal = (props) => {

const [visibleModal, setVisibleModal] = useState(props.state)
return (
  <Modal visible={visibleModal}
        transparent={true}
        animationType='slide'
        >
      <View style={styles.container}>
        <Text style={styles.titulo_label}>¡IMPORTANTE!</Text>
        <Text style={styles.info_label}>{props.message}</Text>
        <TouchableOpacity style={styles.button_aceptar} onPress={() => setVisibleModal(false)}>
          <Text style={styles.text_button}>Aceptar</Text>
        </TouchableOpacity>
      </View>
  </Modal>
);
</code>```

答:
Add a restore property to your MyModal component

```<code>{modalVisibleEnTermino && <MyModal
                    message={"Mensaje1"}
                    state={modalVisibleEnTermino}
                    restore={restoreModals}
                    />
                }

                {modalVisibleFueraTermino && <MyModal
                    message={"Mensaje2."}
                    state={modalVisibleFueraTermino}
                    restore={restoreModals}
                    />
                }

                {modalVisibleRefuerzoTermino && <MyModal
                    message={"Mensaje3."}
                    state={modalVisibleRefuerzoTermino}
                    restore={restoreModals}
                    />
                }
</code>```

In the MyModal Component remove the useState and pass the props.state to visible and use the props.restore on the onPress callback like so

```<code>export const MyModal = (props) => {

return (
  <Modal visible={props.state}
        transparent={true}
        animationType='slide'
        >
      <View style={styles.container}>
        <Text style={styles.titulo_label}>¡IMPORTANTE!</Text>
        <Text style={styles.info_label}>{props.message}</Text>
        <TouchableOpacity style={styles.button_aceptar} onPress={() => props.restore()}>
          <Text style={styles.text_button}>Aceptar</Text>
        </TouchableOpacity>
      </View>
  </Modal>
);

</code>```

In your original MyModal Component, by passing the props.state to useState, you are creating a new state within that component. Setting onPress to setVisibleModal(false) will not change the states of modalVisibleEnTermino, modalVisibleFueraTermino, and  modalVisibleRefuerzoTermino. By passing restoreModals as a prop to MyModal you can change the states in the Main component from inside MyModal.

One more thing, remove the if statements in your restoreModals function

```<code> const restoreModals = () => {
    setModalVisibleEnTermino(false)
    setModalVisibleFueraTermino(false)
    setModalVisibleRefuezoTermino(false)
}
</code>```

Title: Issues with Modals React Native

Body:
everyone. I'm new in this new tecnology and I'm having a little problem with modals.

I'm programming a modal that only shows when a condition is true, in the first click it's all ok, but in the second the modal won't show, then when I click again, the window appears again, and continue successively.

The code works as follow: I have 3 states, each represent a different text to show in the modal. Then, I have a modal, that recieves a message (to print) and the state to identifies what state i need to show. And finally, in the main, I have a condition who calls the modal and show it ONLY if the state is true.

I checked the states with console.log and the only issue i find is that in some cases, the state is set in true, when is false, but i don't know why!

Thanks for read!

Here i detach part of the code.

Declare of the states in the main

const [modalVisibleEnTermino, setModalVisibleEnTermino] = useState(false)

const [modalVisibleFueraTermino, setModalVisibleFueraTermino] = useState(false)

const [modalVisibleRefuerzoTermino, setModalVisibleRefuezoTermino] = useState(false)

Condtition in main to show the apropiate state of modal

const setModal = () => {
    vacunas ===2 && (days>6 && days<150) ? setModalVisibleEnTermino(true) : setModalVisibleFueraTermino(true)
    if(vacunas == 3)
        setModalVisibleRefuezoTermino(true)
}

Function to reset the states after showing modal (IDK if its ok)

 const restoreModals = () => {
    if (modalVisibleEnTermino) setModalVisibleEnTermino(false)
    if (modalVisibleFueraTermino) setModalVisibleFueraTermino(false)
    if (modalVisibleRefuerzoTermino) setModalVisibleRefuezoTermino(false)
}

After set the modal, I checked what state it's true, and I passed the values in this condition

{modalVisibleEnTermino && <MyModal
                    message={"Mensaje1"}
                    state={modalVisibleEnTermino}
                    />
                }

                {modalVisibleFueraTermino && <MyModal
                    message={"Mensaje2."}
                    state={modalVisibleFueraTermino}
                    />
                }

                {modalVisibleRefuerzoTermino && <MyModal
                    message={"Mensaje3."}
                    state={modalVisibleRefuerzoTermino}
                    />
                }

Modal

export const MyModal = (props) => {

const [visibleModal, setVisibleModal] = useState(props.state)
return (
  <Modal visible={visibleModal}
        transparent={true}
        animationType='slide'
        >
      <View style={styles.container}>
        <Text style={styles.titulo_label}>¡IMPORTANTE!</Text>
        <Text style={styles.info_label}>{props.message}</Text>
        <TouchableOpacity style={styles.button_aceptar} onPress={() => setVisibleModal(false)}>
          <Text style={styles.text_button}>Aceptar</Text>
        </TouchableOpacity>
      </View>
  </Modal>
);

Body:
Add a restore property to your MyModal component

{modalVisibleEnTermino && <MyModal
                    message={"Mensaje1"}
                    state={modalVisibleEnTermino}
                    restore={restoreModals}
                    />
                }

                {modalVisibleFueraTermino && <MyModal
                    message={"Mensaje2."}
                    state={modalVisibleFueraTermino}
                    restore={restoreModals}
                    />
                }

                {modalVisibleRefuerzoTermino && <MyModal
                    message={"Mensaje3."}
                    state={modalVisibleRefuerzoTermino}
                    restore={restoreModals}
                    />
                }

In the MyModal Component remove the useState and pass the props.state to visible and use the props.restore on the onPress callback like so

export const MyModal = (props) => {

return (
  <Modal visible={props.state}
        transparent={true}
        animationType='slide'
        >
      <View style={styles.container}>
        <Text style={styles.titulo_label}>¡IMPORTANTE!</Text>
        <Text style={styles.info_label}>{props.message}</Text>
        <TouchableOpacity style={styles.button_aceptar} onPress={() => props.restore()}>
          <Text style={styles.text_button}>Aceptar</Text>
        </TouchableOpacity>
      </View>
  </Modal>
);

In your original MyModal Component, by passing the props.state to useState, you are creating a new state within that component. Setting onPress to setVisibleModal(false) will not change the states of modalVisibleEnTermino, modalVisibleFueraTermino, and  modalVisibleRefuerzoTermino. By passing restoreModals as a prop to MyModal you can change the states in the Main component from inside MyModal.

One more thing, remove the if statements in your restoreModals function

 const restoreModals = () => {
    setModalVisibleEnTermino(false)
    setModalVisibleFueraTermino(false)
    setModalVisibleRefuezoTermino(false)
}


问:
Python - Two player dice game
Using Pythons random number generator, 2 players rolls two dice and generates the score (formula in play_game function). Prompt both players and their names, as well as their score.</p>

答:
```<code>from random import randint
p1 = input("What is player one's name? ")
p2 = input("What is player two's name? ")
print(f"Player 1 got {randint(1, 6)}")
print(f"Player 2 got {randint(1, 6)}")
</code>```

This will do what you want.
Output would be:

```<code>>>>Player 1 got <number>
>>>Player 2 got <number>
</code>```

Title: Python - Two player dice game

Body:
from random import randint
p1 = input("What is player one's name? ")
p2 = input("What is player two's name? ")
print(f"Player 1 got {randint(1, 6)}")
print(f"Player 2 got {randint(1, 6)}")

This will do what you want.
Output would be:

>>>Player 1 got <number>
>>>Player 2 got <number>


问:
cocoa release nswindowcontroller
I am loading a window with it's controller from a window nib file. The window has a "release when closed" option enabled. How could i release the controller as soon as the window closes?

Thank you

答: In your windowWillClose: code don't forget that you'll need to removeObserver: or your controller will never be released because the NSNotificationCenter has retained it.

Title: cocoa release nswindowcontroller


问:
'Timestamp' object is not subscriptable
This is my code, I am trying to get months for a new column

```<code>import pandas as pd
df = pd.read_excel("..\Data.xlsx")
df.head(4)
p = df["Month"][0]
p[0:3]

</code>```

I don't know what's the issue is here but it was working well for other datasets with the same attributes

Dataset:

```<code>        Month  Passengers
0  1995-01-01         112
1  1995-02-01         118
2  1995-03-01         132
3  1995-04-01         129
4  1995-05-01         121

</code>```

P.S: In the excel data set month values are in Jan-1995 Feb-1995 format, it changed to YY:MM:DAY format because of pandas.

```<code>Traceback (most recent call last):

  File "C:\Users\sreen\AppData\Local\Temp/ipykernel_27276/630478717.py", line 1, in <module>
    p[0:3]

TypeError: 'Timestamp' object is not subscriptable
</code>```

答:
This shall work for you:</p>
```<code>df.rename(columns = {'Month':'Date'}, inplace = True)
df['Month'] = pd.DatetimeIndex(df['Date']).month

</code>```

Title: 'Timestamp' object is not subscriptable

Body:
This is my code, I am trying to get months for a new column

import pandas as pd
df = pd.read_excel("..\Data.xlsx")
df.head(4)
p = df["Month"][0]
p[0:3]

I don't know what's the issue is here but it was working well for other datasets with the same attributes

Dataset:

        Month  Passengers
0  1995-01-01         112
1  1995-02-01         118
2  1995-03-01         132
3  1995-04-01         129
4  1995-05-01         121

P.S: In the excel data set month values are in Jan-1995 Feb-1995 format, it changed to YY:MM:DAY format because of pandas.

Traceback (most recent call last):

  File "C:\Users\sreen\AppData\Local\Temp/ipykernel_27276/630478717.py", line 1, in <module>
    p[0:3]

TypeError: 'Timestamp' object is not subscriptable

Body:
This shall work for you:

df.rename(columns = {'Month':'Date'}, inplace = True)
df['Month'] = pd.DatetimeIndex(df['Date']).month


问:
How to add space beetween a pair of consecutive letters and not add space beetween two characters that are not both letters?
For example:
The string BINGO!
should be B I N G O!

I have already tried:

```<code>s = "BINGO!"
print(" ".join(s[::1]))
</code>```

答:
I like what esramish had said, however that is a bit overcomplicated for your goal. It is as easy as this:

```<code>string = "BINGO"

print(" ".join(string))

</code>```

This returns your desired output.

Body:
For example:
The string BINGO!
should be B I N G O!

I have already tried:

s = "BINGO!"
print(" ".join(s[::1]))

Body:
I like what esramish had said, however that is a bit overcomplicated for your goal. It is as easy as this:

string = "BINGO"

print(" ".join(string))

This returns your desired output.


问:
Get a list of numbers that adds up to a number "n" (using repetition of number) - how would one consider the case of using same number multiple times?
```<code>def getList(n, input_list, caching_list):
</code>```

The function should return a list that adds up to a number "n" using numbers from the input_list, given that numbers can be repeated. Looking to use recursion.

current code:

```<code>def getList(n, input_list, caching_list):
  if n == 0 :
    return caching_list
  if n < 0 or len(input_list) == 0:
    return []

  for i in input_list:
    if find_sum(n-i,input_list,caching_list) == caching_list:
        caching_list.append(i)
        return caching_list
  return []
</code>```

example
n = 13, input_list= [2,3,5] should result in [2,2,2,2,2,3] or [5,5,2] or anything that adds to 13.

Doing this with using a number just 1 time is easy, but how would one consider the case of using same number multiple times?

答:
I find itertools can be very handy for stuff like this. I am sure there are better ways to do it, but this might get you want you need:

```<code>import itertools

def find_sum(n, p_list):
    max_len = n // min(p_list)
    min_len = n // max(p_list)

    for i in range(min_len, max_len+1):
        I = itertools.combinations_with_replacement(p_list, i)
        for j in I:
            if(sum(j) == n):
                return(list(j))
    return([])

print(find_sum(17,[2,3,5]))
# [2, 5, 5, 5]
print(find_sum(7, [3, 5]))
# []
</code>```

You could easily alter the code to give you all combinations.

```<code>
def find_sum(n, p_list):
    max_len = n // min(p_list)
    min_len = n // max(p_list)
    answers = []
    for i in range(min_len, max_len+1):
        I = itertools.combinations_with_replacement(p_list, i)
        for j in I:
            if(sum(j) == n):
                answers.append(list(j))
    return(answers)
</code>```
```<code>find_sum(17,[2,3,5])
#[[2, 5, 5, 5], [2, 2, 3, 5, 5], [3, 3, 3, 3, 5], [2, 2, 2, 3, 3, 5], [2, 3, 3, 3, 3, 3], [2, 2, 2, 2, 2, 2, 5], [2, 2, 2, 2, 3, 3, 3], [2, 2, 2, 2, 2, 2, 2, 3]]
</code>```

Regarding @dantebarba's comment, I haven't really looked to see how it will scale for large problems and there may be more efficient approaches.

Body:
def getList(n, input_list, caching_list):

The function should return a list that adds up to a number "n" using numbers from the input_list, given that numbers can be repeated. Looking to use recursion.

current code:

def getList(n, input_list, caching_list):
  if n == 0 :
    return caching_list
  if n < 0 or len(input_list) == 0:
    return []

  for i in input_list:
    if find_sum(n-i,input_list,caching_list) == caching_list:
        caching_list.append(i)
        return caching_list
  return []

example
n = 13, input_list= [2,3,5] should result in [2,2,2,2,2,3] or [5,5,2] or anything that adds to 13.

Doing this with using a number just 1 time is easy, but how would one consider the case of using same number multiple times?

Body:
I find itertools can be very handy for stuff like this. I am sure there are better ways to do it, but this might get you want you need:

import itertools

def find_sum(n, p_list):
    max_len = n // min(p_list)
    min_len = n // max(p_list)

    for i in range(min_len, max_len+1):
        I = itertools.combinations_with_replacement(p_list, i)
        for j in I:
            if(sum(j) == n):
                return(list(j))
    return([])

print(find_sum(17,[2,3,5]))
# [2, 5, 5, 5]
print(find_sum(7, [3, 5]))
# []

You could easily alter the code to give you all combinations.

def find_sum(n, p_list):
    max_len = n // min(p_list)
    min_len = n // max(p_list)
    answers = []
    for i in range(min_len, max_len+1):
        I = itertools.combinations_with_replacement(p_list, i)
        for j in I:
            if(sum(j) == n):
                answers.append(list(j))
    return(answers)

find_sum(17,[2,3,5])
#[[2, 5, 5, 5], [2, 2, 3, 5, 5], [3, 3, 3, 3, 5], [2, 2, 2, 3, 3, 5], [2, 3, 3, 3, 3, 3], [2, 2, 2, 2, 2, 2, 5], [2, 2, 2, 2, 3, 3, 3], [2, 2, 2, 2, 2, 2, 2, 3]]

Regarding @dantebarba's comment, I haven't really looked to see how it will scale for large problems and there may be more efficient approaches.


问:
Forge API to translate InventorParams of {URL}/workitems into supported format like svf,dwg
Didn't get idea to translate the model InventorParams.url to any supported formats like SVF,DWG,Obj

sending data:{InventorParams.url} on endpoint /workitems by axios

axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/da/us-east/v3/workitems',
        headers: {
            'Authorization': 'Bearer ******',
            'content-type': 'application/json'
        },
        data: JSON.stringify({
        activityId: 'BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta',
        arguments: {
          InventorDoc: {
             url: 'https://developer.api.autodesk.com/oss/v2/signedresources/1a2ac1d9-a8af-4aa2-b9d1-8b0fde21bcf3?region=US',
             pathInZip: 'MasterAssembly.iam'
          },
          InventorParams: {
            url: 'data:application/json,{"ProjectNumber":"12345","ProjectName":"8000-2016","PreparedBy":"Nami","DrawingNumber":"Nami","CommissionNumber":"","ElevatorDesignation":"","ElevatorNumber":"","Logo":"NamiLift","LanguageOptions":"ENG","Standard":"PL400","NumberOfFloor":2,"LengthOfCar":2000,"WidthOfCar":1100,"Pits":true,"PitHeight":50,"ZoneSectionStart":239,"HeightAboveTopElevator":0,"ElectricBoxSide":"a","ElectricBoxFloorNo":"0","ElectricBoxDefault":false,"OuterRoof":false,"OuterRoofSide":"A","WindowsSectionA":"0-0","WindowsSectionB":"0-5000","WindowsSectionC":"0-0","WindowsSectionD":"0-0","DefaultDoorSize":false,"Colorelevator":"RAL 9001","Colordoor":"RAL 9001","Safelinemx2":false,"Safelinemx2gsm":false,"Schoolcontrolassa":false,"Schoolcontrol":false,"Intercom":false,"Callsend":false,"Firealarmdrive":false,"Folderseat":false,"Floorvoiceannouncement":false,"Lsfcable":false,"Telephone":false,"Keyswitch":false,"Ups":false,"Comments":"-","LiftHeightLevel0":0,"DoorSideLevel0":"A","TypeOfDoorLevel0":"A1","DoorHingeLevel0":"Right","DoorSizeLevel0":900,"DoorHeightLevel0":2000,"DoorCloserLevel0":true,"CanopyLevel0":true,"CallBoxLevel0":true,"LiftHeightLevel1":5000,"DoorSideLevel1":"A","TypeOfDoorLevel1":"A1","DoorHingeLevel1":"Right","DoorSizeLevel1":900,"DoorHeightLevel1":2000,"DoorCloserLevel1":false,"CanopyLevel1":false,"CallBoxLevel1":false}',
            'OutputPDF': {
                    'url': fileName.resultZipUrl,
                    'headers': {
                        'Authorization': 'Bearer ' + values.access_token,
                        'Content-type': 'application/octet-stream'
                    },
                    'verb': 'put'
            },
            onComplete: 'onComplete': {
                    'verb': 'post',
                    'url': config.credentials.callback_url +'/api/forge/datamanagement/signanddownload'
            }
       }
    }
})
```
<hr />
<p><em><strong>WorkItem Output</strong></em></p>
<pre class="lang-js prettyprint-override"><code>{"status":"pending","stats":{"timeQueued":"2022-02-09T03:31:43.525012Z"},"id":"27fa82758b794111a91025ed69da6fec"}
</code>```

This is the workitem/:id response for that InventorParams

This is the txt file which i am getting from reportUrl of workitem/:id response

From report.txt file oss/v2/signedresources GET ZIP (InventorDoc.pathInZip name) with this content

答:
The activity you pasted seems to only be about creating a PDF for the drawing of a given Inventor model - see OutputPDF output parameter.

InventorParams simply provides a json file for the work item that the code in your app bundle can read, and use the values in it to modify the model accordingly using the Inventor API.

To better understand how the input and output parameters, inc the json file are used exactly by the app bundle, please have a look at the tutorial here:
https://learnforge.autodesk.io/#/tutorials/modifymodels

Body:
Didn't get idea to translate the model InventorParams.url to any supported formats like SVF,DWG,Obj

sending data:{InventorParams.url} on endpoint /workitems by axios

axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/da/us-east/v3/workitems',
        headers: {
            'Authorization': 'Bearer ******',
            'content-type': 'application/json'
        },
        data: JSON.stringify({
        activityId: 'BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta',
        arguments: {
          InventorDoc: {
             url: 'https://developer.api.autodesk.com/oss/v2/signedresources/1a2ac1d9-a8af-4aa2-b9d1-8b0fde21bcf3?region=US',
             pathInZip: 'MasterAssembly.iam'
          },
          InventorParams: {
            url: 'data:application/json,{"ProjectNumber":"12345","ProjectName":"8000-2016","PreparedBy":"Nami","DrawingNumber":"Nami","CommissionNumber":"","ElevatorDesignation":"","ElevatorNumber":"","Logo":"NamiLift","LanguageOptions":"ENG","Standard":"PL400","NumberOfFloor":2,"LengthOfCar":2000,"WidthOfCar":1100,"Pits":true,"PitHeight":50,"ZoneSectionStart":239,"HeightAboveTopElevator":0,"ElectricBoxSide":"a","ElectricBoxFloorNo":"0","ElectricBoxDefault":false,"OuterRoof":false,"OuterRoofSide":"A","WindowsSectionA":"0-0","WindowsSectionB":"0-5000","WindowsSectionC":"0-0","WindowsSectionD":"0-0","DefaultDoorSize":false,"Colorelevator":"RAL 9001","Colordoor":"RAL 9001","Safelinemx2":false,"Safelinemx2gsm":false,"Schoolcontrolassa":false,"Schoolcontrol":false,"Intercom":false,"Callsend":false,"Firealarmdrive":false,"Folderseat":false,"Floorvoiceannouncement":false,"Lsfcable":false,"Telephone":false,"Keyswitch":false,"Ups":false,"Comments":"-","LiftHeightLevel0":0,"DoorSideLevel0":"A","TypeOfDoorLevel0":"A1","DoorHingeLevel0":"Right","DoorSizeLevel0":900,"DoorHeightLevel0":2000,"DoorCloserLevel0":true,"CanopyLevel0":true,"CallBoxLevel0":true,"LiftHeightLevel1":5000,"DoorSideLevel1":"A","TypeOfDoorLevel1":"A1","DoorHingeLevel1":"Right","DoorSizeLevel1":900,"DoorHeightLevel1":2000,"DoorCloserLevel1":false,"CanopyLevel1":false,"CallBoxLevel1":false}',
            'OutputPDF': {
                    'url': fileName.resultZipUrl,
                    'headers': {
                        'Authorization': 'Bearer ' + values.access_token,
                        'Content-type': 'application/octet-stream'
                    },
                    'verb': 'put'
            },
            onComplete: 'onComplete': {
                    'verb': 'post',
                    'url': config.credentials.callback_url +'/api/forge/datamanagement/signanddownload'
            }
       }
    }
})

WorkItem Output

{"status":"pending","stats":{"timeQueued":"2022-02-09T03:31:43.525012Z"},"id":"27fa82758b794111a91025ed69da6fec"}

This is the workitem/:id response for that InventorParams

This is the txt file which i am getting from reportUrl of workitem/:id response

From report.txt file oss/v2/signedresources GET ZIP (InventorDoc.pathInZip name) with this content


问:
Override external plugin version in precompiled script plugin
I am using Gradle build tool. I have a precompiled Gradle script plugin X, lets say this is a convention plugin. In build.gradle of plugin I define dependency on another external plugin Y.

plugin X:build.gradle:

```<code>dependencies {
  implementation "com.rivancic.y:y-gradle-plugin:${versionYPlugin}"
}
</code>```

plugin X:gradle.properties

```<code>versionYPlugin:1.0.0
</code>```

Then in my main project, I apply precompiled script plugin X and I want to manually set version of external plugin Y. Is that possible? I can't find a way to override the plugin Y version from A.

If I define in project A:gradle.properties the version

```<code>versionYPlugin=1.1.0
</code>```

it doesn't help, still version 1.0.0 is being resolved.

Is there any other way if I want that external plugin version can be dynamically set?

答:
You are confusing projects and build time vs. application time.

X:build.gradle is the build file of your plugin.

Before build A can apply X, X needs to be built.

The build of X is a totally separate build.

A project property you have on project A has nothing to do with the build of X, so cannot influence the build of X, no matter whether this is buildSrc, an included build, or a standalone build.

If X is buildSrc or an included build, you could consider some way to reuse the gradle.properties of A during the build time, but as you want to influence from the consumer, I guess it is as standalone build or you could change it in the build of X directly.

So as X is probably a standalone build, when A wants to apply it, it is already built and has a metadata file where the version of Y is contained that was defined in X when building it.

To use a different version of Y, you have to make sure it is in the build script class path of A. You could for example do plugins { id("com.rivancic.y") version "3.1.0" apply false } so that it is in the build script class path of A and is used instead of the version that X depends on.

Or you could define it as buildSrc runtimeOnly dependency just to put it to the class path of all the build scripts.

...

Body:
I am using Gradle build tool. I have a precompiled Gradle script plugin X, lets say this is a convention plugin. In build.gradle of plugin I define dependency on another external plugin Y.

plugin X:build.gradle:

dependencies {
  implementation "com.rivancic.y:y-gradle-plugin:${versionYPlugin}"
}

plugin X:gradle.properties

versionYPlugin:1.0.0

Then in my main project, I apply precompiled script plugin X and I want to manually set version of external plugin Y. Is that possible? I can't find a way to override the plugin Y version from A.

If I define in project A:gradle.properties the version

versionYPlugin=1.1.0

it doesn't help, still version 1.0.0 is being resolved.

Is there any other way if I want that external plugin version can be dynamically set?


问:
'module' object has no attribute 'basicConfig'
I have the following code, copied from the Python manual:

```<code>import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)

logging.debug('This message should go to the log file')
</code>```

When I try to run the script (via python.exe script.py) I get an error of 'module' object has no attribute 'basicConfig'.

However when I copy and paste the code in interactive mode (via python.exe then copy and pasting the actual code) I get no error. The code runs fine.

I have python 2.6.6.

Thank you!

答:
This is a mere side-note for those coding Python in a Google Cloud Function who do not use the Python logging module but import google.cloud.logging and who still get the same error.

It is obvious for the reader, but it took me some time to understand this, therefore sharing this.

I thought that the import google.cloud.logging would be a kind of wrapper of the Python built-in logging module so that it would need the same:

    # Config the logger
    logging.basicConfig(
        level=logging.INFO, format="%(asctime)s [%(levelname)s]: %(message)s"
    )
```
<p>But no, the default <code>Client()</code> without parameters is enough and text output is either <code>log_struct</code> or <code>log_text</code>, no log level parameter like <code>INFO</code> needed.</p>
<p><strong>In Google Cloud Function edit mode</strong> (not for a local Python script!)</p>
<p>"requirements.txt":</p>
```google-cloud-logging==3.0.0
```
<p>"main.py":</p>
<pre class="lang-py prettyprint-override"><code>    logging_client = gcloud_logger.Client()
    # The name of the log to write to
    log_name = environ['LOG_NAME']
    # Selects the log to write to
    logger = logging_client.logger(log_name)
</code>```

https://cloud.google.com/logging/docs/reference/libraries#log-entries

ContentLicense: CC BY-SA 2.5

Body:
I have the following code, copied from the Python manual:

import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)

logging.debug('This message should go to the log file')

When I try to run the script (via python.exe script.py) I get an error of 'module' object has no attribute 'basicConfig'.

However when I copy and paste the code in interactive mode (via python.exe then copy and pasting the actual code) I get no error. The code runs fine.

I have python 2.6.6.

Thank you!

Body:
This is a mere side-note for those coding Python in a Google Cloud Function who do not use the Python logging module but import google.cloud.logging and who still get the same error.

It is obvious for the reader, but it took me some time to understand this, therefore sharing this.

I thought that the import google.cloud.logging would be a kind of wrapper of the Python built-in logging module so that it would need the same:

    # Config the logger
    logging.basicConfig(
        level=logging.INFO, format="%(asctime)s [%(levelname)s]: %(message)s"
    )

But no, the default Client() without parameters is enough and text output is either log_struct or log_text, no log level parameter like INFO needed.

In Google Cloud Function edit mode (not for a local Python script!)

"requirements.txt":

google-cloud-logging==3.0.0

"main.py":

    logging_client = gcloud_logger.Client()
    # The name of the log to write to
    log_name = environ['LOG_NAME']
    # Selects the log to write to
    logger = logging_client.logger(log_name)

https://cloud.google.com/logging/docs/reference/libraries#log-entries


问:
Nuxt-Laravel-Sanctum CSRF token mismatch 419 error
I have a Nuxt-Laravel-Sanctum CSRF token mismatch 419 error while Laravel is hosted on a server and Nuxt is on localhost on a PC. I have uploaded my Laravel project for getting API on api.repairtofix.com.

And I am trying to log in from localhost in my pc from Nuxt. While clicking on the login button I get the following error.

{message: "CSRF token mismatch.", exception:
"Symfony\Component\HttpKernel\Exception\HttpException",…}

Login method

```<code>login() {
    this.$auth.loginWith('laravelSanctum', {
        data: this.form
    })
    .then(response => console.log(response))
    .catch(error => console.log(response))
}
</code>```

.env

```<code>APP_URL=http://api.repairtofix.com
SESSION_DOMAIN=api.repairtofix.com
SANCTUM_STATEFUL_DOMAINS=.repairtofix.com,localhost:3000
</code>```

Kernel.php

```<code>'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
</code>```

sanctum.php

```<code>'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS',
    'api.repairtofix.com,localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1'
)),
</code>```

cors.php

```<code>'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'signup', 'getUser'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
</code>```

api.php

```<code>Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

// register
Route::get('register', function(Request $request){
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password)
    ]);

    return $user;
});

// login
Route::post('login', function(Request $request){
    $credentials = $request->only('email', 'password');
    if(!auth()->attempt($credentials)){
        throw ValidationException::withMessages([
            'email' => 'Invalid credentials'
        ]);
    }

    $request->session()->regenerate();
    return response()->json(null, 201);
});

// logout
Route::post('logout', function(Request $request){
    auth()->guard('web')->logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return response()->json(null, 201);
});
</code>```

nuxt.config.js

```<code>modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/auth-next',
    '@nuxtjs/toast',
],

auth:{
    strategies: {
        'laravelSanctum': {
            provider: 'laravel/sanctum',
            url: 'http://api.repairtofix.com',
            endpoints: {
                login: {
                    url: '/api/login'
                },
                logout: {
                    url: '/api/logout'
                },
                user: {
                    url: '/api/user'
                },
            },
            user: {
                property: false
            }
        },
    },
    redirect: {
        login: "/login",
        logout: "/",
        home: "/"
    }
},
</code>```

答:
It is maybe a little bit late but others in future.
1-check the api/config/sanctum in laravel and make the ports correct on localhost:xxxx and 127.0.0.1:xxxx
2-on .env file make coorection for SANCTUM_STATEFUL_DOMAINS=localhost:xxxx</p>

Body:
I have a Nuxt-Laravel-Sanctum CSRF token mismatch 419 error while Laravel is hosted on a server and Nuxt is on localhost on a PC. I have uploaded my Laravel project for getting API on api.repairtofix.com.

And I am trying to log in from localhost in my pc from Nuxt. While clicking on the login button I get the following error.

{message: "CSRF token mismatch.", exception:
"Symfony\Component\HttpKernel\Exception\HttpException",…}

Login method

login() {
    this.$auth.loginWith('laravelSanctum', {
        data: this.form
    })
    .then(response => console.log(response))
    .catch(error => console.log(response))
}

.env

APP_URL=http://api.repairtofix.com
SESSION_DOMAIN=api.repairtofix.com
SANCTUM_STATEFUL_DOMAINS=.repairtofix.com,localhost:3000

Kernel.php

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS',
    'api.repairtofix.com,localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1'
)),

cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'signup', 'getUser'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

// register
Route::get('register', function(Request $request){
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password)
    ]);

    return $user;
});

// login
Route::post('login', function(Request $request){
    $credentials = $request->only('email', 'password');
    if(!auth()->attempt($credentials)){
        throw ValidationException::withMessages([
            'email' => 'Invalid credentials'
        ]);
    }

    $request->session()->regenerate();
    return response()->json(null, 201);
});

// logout
Route::post('logout', function(Request $request){
    auth()->guard('web')->logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return response()->json(null, 201);
});

nuxt.config.js

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/auth-next',
    '@nuxtjs/toast',
],

auth:{
    strategies: {
        'laravelSanctum': {
            provider: 'laravel/sanctum',
            url: 'http://api.repairtofix.com',
            endpoints: {
                login: {
                    url: '/api/login'
                },
                logout: {
                    url: '/api/logout'
                },
                user: {
                    url: '/api/user'
                },
            },
            user: {
                property: false
            }
        },
    },
    redirect: {
        login: "/login",
        logout: "/",
        home: "/"
    }
},


问:
How do you return a specific row per group by some criteria in BigQuery?
I have a table of people with firstname, surname, and age. I would like to retrieve the oldest person in each family (by surname). I don't want to just return the surname and age (via MAX(age) and GROUP BY surname) I want the entire row.

For example if my data is:

```<code>firstname, surname, age
john, smith, 31
sally, smith, 33
bob, smith, 34
john wayne, 35
bob wayne, 31
</code>```

I would like my query to return:

```<code>firstname, surname, age
bob, smith, 34
john wayne, 35
</code>```

答:
Consider below approach

```<code>select surname, array_agg(struct(firstname, age) order by age desc limit 1)[offset(0)].*
from your_table
group by surname
</code>```

if applied to sample data in your question - output is

Body:
I have a table of people with firstname, surname, and age. I would like to retrieve the oldest person in each family (by surname). I don't want to just return the surname and age (via MAX(age) and GROUP BY surname) I want the entire row.

For example if my data is:

firstname, surname, age
john, smith, 31
sally, smith, 33
bob, smith, 34
john wayne, 35
bob wayne, 31

I would like my query to return:

firstname, surname, age
bob, smith, 34
john wayne, 35

Body:
Consider below approach

select surname, array_agg(struct(firstname, age) order by age desc limit 1)[offset(0)].*
from your_table
group by surname

if applied to sample data in your question - output is


问:
Extract URL Query Value in Excel
I'm looking to extract a query value q= from a URL using Excel. The main challenge I'm facing is that the query value isn't always in the same position. I can have multiple parameters before or after the query value. All I know is that I need to start from the &q= position, and end at the next & symbol, or the end of line if no other & follows.

For example: in the URL below, I'm looking to extract the query value of: This_Is_My_Query_value

```<code>http://www.example.com/somepage?param1=one&param2=two&param3=three`&q=This_Is_My_Query_value`&A=Z&B=y&C=ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL
</code>```

Query string splitter:

'param1': one

'param2': two

'param3': three

'q': This_Is_My_Query_value

'A': Z

'B': y

'C': ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL

答:
You can do this in two stages:

```<code>A1      (Your URL)
        http://www.example.com/somepage?param1=one&param2=two&param3=three&q=This_Is_My_Query_value&A=Z&B=y&C=ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL

B1      =MID(@A:A,FIND("q=",@A:A)+2,999)
        This_Is_My_Query_value&A=Z&B=y&C=ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL

C1      =LEFT(@B:B,IFERROR(FIND("&",@B:B)-1,999))
        This_Is_My_Query_value
</code>```

Or you can do it in a single formula:

```<code>=LEFT(MID(@A:A,FIND("q=",@A:A)+2,999),IFERROR(FIND("&",MID(@A:A,FIND("q=",@A:A)+2,999))-1,999))
</code>```

Replace @A:A with the reference to the URL cell.

This won't work if there's another q= earlier in the URL - if that's a concern it'd be possible to look for a ?q= or &q= instead of for q=.

Title: Extract URL Query Value in Excel

Body:
I'm looking to extract a query value q= from a URL using Excel. The main challenge I'm facing is that the query value isn't always in the same position. I can have multiple parameters before or after the query value. All I know is that I need to start from the &q= position, and end at the next & symbol, or the end of line if no other & follows.

For example: in the URL below, I'm looking to extract the query value of: This_Is_My_Query_value

http://www.example.com/somepage?param1=one&param2=two&param3=three`&q=This_Is_My_Query_value`&A=Z&B=y&C=ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL

Query string splitter:

'param1': one

'param2': two

'param3': three

'q': This_Is_My_Query_value

'A': Z

'B': y

'C': ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL

Body:
You can do this in two stages:

A1      (Your URL)
        http://www.example.com/somepage?param1=one&param2=two&param3=three&q=This_Is_My_Query_value&A=Z&B=y&C=ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL

B1      =MID(@A:A,FIND("q=",@A:A)+2,999)
        This_Is_My_Query_value&A=Z&B=y&C=ahUKEwjS09bhyPD1AhVihOAKHTQyBeEQwL

C1      =LEFT(@B:B,IFERROR(FIND("&",@B:B)-1,999))
        This_Is_My_Query_value

Or you can do it in a single formula:

=LEFT(MID(@A:A,FIND("q=",@A:A)+2,999),IFERROR(FIND("&",MID(@A:A,FIND("q=",@A:A)+2,999))-1,999))

Replace @A:A with the reference to the URL cell.

This won't work if there's another q= earlier in the URL - if that's a concern it'd be possible to look for a ?q= or &q= instead of for q=.


问:
OAuth token security
As far as I know, the OAuth standard is very lax on how OAuth really should behave, but...

I store OAuth access tokens for various OAuth services in a database. If these tokens were compromised, could they be used by a third party? I.e., are the given tokens bound to only my api and secret keys?

答:
The tokens are tied to a given service and user. With those, one can pretend to be that user.
It is not tied to any IP address or device UUID for example (although one could do that as an additional precaution, but that is not part of OAuth).

If they were compromised, you'd deauthorize them, thus making them worthless.

could they be used with different API and secret keys?

No. The access token are also tied to the application they were issued for.

This way the user can de-authorize on a by-application basis, and every app can have a different set of permissions (e.g. read-only access).

Title: OAuth token security


问:
How to debounce events in bloc?
How to debounce events in bloc? Let's say, I want to perform a search query on a backend, but before doing that wait for the user to stop typing? By "stop typing" I mean 1 second period until last key was pressed.

Example bloc event handler:

on<Search>(_handleSearchEvent);
```

答:
Each handler have an optional transformer: field which can do debouncing (and much more).

Using rxdart you can implement debouncing yourself:

on<Search>(
  _handleSearchEvent,
  transformer: (events, mapper) => events.debounceTime(Duration(seconds: 1)).switchMap(mapper),
);
```
<p>I wrote the bloc_event_transformers package to do popular transforms like throttle and debounce to reduce the boilerplate in my apps. It can be used like that:</p>
<pre class="lang-dart prettyprint-override"><code>on<Search>(
  _handleSearchEvent,
  transformer: debounce(Duration(seconds: 1)),
);
</code>```

Title: How to debounce events in bloc?

Body:
Each handler have an optional transformer: field which can do debouncing (and much more).

Using rxdart you can implement debouncing yourself:

on<Search>(
  _handleSearchEvent,
  transformer: (events, mapper) => events.debounceTime(Duration(seconds: 1)).switchMap(mapper),
);

I wrote the bloc_event_transformers package to do popular transforms like throttle and debounce to reduce the boilerplate in my apps. It can be used like that:

on<Search>(
  _handleSearchEvent,
  transformer: debounce(Duration(seconds: 1)),
);


问:
Laravel Sail: could not find driver (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE') --- Mac
I just recently replaced my macbook.  I setup the previous project I was working on.  Unfortunately I encountered this error.

```<code>
  could not find driver (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712
    708▕         // If an exception occurs when attempting to run a query, we'll format the error
    709▕         // message to include the bindings with SQL, which will make this exception a
    710▕         // lot more helpful to the developer instead of just the database's errors.
    711▕         catch (Exception $e) {
  ➜ 712▕             throw new QueryException(
    713▕                 $query, $this->prepareBindings($bindings), $e
    714▕             );
    715▕         }
    716▕     }
</code>```

I'm using laravel/sail so all services are defined on docker-compose.yml.

All services are running properly without any errors via command $ sail up -d.

I can even connect to mysql service using TablePlus App.

Is there any new config I might have missed?

I tried checking DB connection using tinker and here is the output (no connection error found).

```<code>>>> DB::connection();
=> Illuminate\Database\MySqlConnection {#525}
>>>
</code>```

答:
I have the same issue using the new Mac (Apple M1 Max), This is how I solve it.

```<code>// docker-compose.yml file

I commented out this line and it worked.

services:
  mariadb:
    # MYSQL_ROOT_HOST: "%"
</code>```

when you run the migration, in the .env file modify the variable DB_HOST pointing to 127.0.0.1, once the migration is finished, put back the service name DB_HOST=mariadb. In my case I am using mariadb.

Hope this help.

Body:
I just recently replaced my macbook.  I setup the previous project I was working on.  Unfortunately I encountered this error.

  could not find driver (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712
    708▕         // If an exception occurs when attempting to run a query, we'll format the error
    709▕         // message to include the bindings with SQL, which will make this exception a
    710▕         // lot more helpful to the developer instead of just the database's errors.
    711▕         catch (Exception $e) {
  ➜ 712▕             throw new QueryException(
    713▕                 $query, $this->prepareBindings($bindings), $e
    714▕             );
    715▕         }
    716▕     }

I'm using laravel/sail so all services are defined on docker-compose.yml.

All services are running properly without any errors via command $ sail up -d.

I can even connect to mysql service using TablePlus App.

Is there any new config I might have missed?

I tried checking DB connection using tinker and here is the output (no connection error found).

>>> DB::connection();
=> Illuminate\Database\MySqlConnection {#525}
>>>

Body:
I have the same issue using the new Mac (Apple M1 Max), This is how I solve it.

// docker-compose.yml file

I commented out this line and it worked.

services:
  mariadb:
    # MYSQL_ROOT_HOST: "%"

when you run the migration, in the .env file modify the variable DB_HOST pointing to 127.0.0.1, once the migration is finished, put back the service name DB_HOST=mariadb. In my case I am using mariadb.

Hope this help.


问:
How to fix multiple definition erorr?
In my code (using code blocks) it kept saying multiple definition in every function in wagon.c

I try change so much var in .h and main but it useless.  I'm not that good in English nor in code ^^ so please any help or some sites to learn this chapter to improve my skills.

I have the .h and its good

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wagon.h"

void saisir_wagon(wagon *w) //here there is a multipel definition how``
{
  printf("donner un numero\n");
  scanf("%d", &w->num);
  do {
    printf("donner le type\n");
    gets(w->type);
  } while ((strcmp(w->type, "wagon") != 0)
      && (strcmp(w->type, "locomotive" != 0)));
  do {
    printf("donner l etat \n");
    scanf("%d", &w->ok);
  } while ((w->ok = !0) && (w->ok = !1));
}

LIST ajout_deb(wagon w, LIST l) {
  struct cellule *nouv;

  nouv = malloc(sizeof(wagon));

  if (l != NULL) {
    nouv->w = w;
    nouv->suiv = l;
  } else {
    nouv->suiv = NULL;
    l = nouv;
  }

  return l;
}

LIST ajout_queue(wagon W, LIST l) {
  struct cellule *nouv, *parc;

  nouv = malloc(sizeof(cellule));
  nouv->w = W;
  nouv->suiv = NULL;

  if (l == NULL) {
    l = nouv;
  } else {
    parc = l;
    while (parc->suiv != NULL) {
      parc = parc->suiv;
    }
    parc->suiv = nouv;
  }
  return (l);
}

void parkour_l(LIST l) {
  struct cellule *tmp = l;
  if (l == NULL)
    printf("liste vide /n");
  else {
    while (tmp != NULL) {
      printf("le numero :%d /n", tmp->w.num);
      printf("le type :%s /n", tmp->w.type);
      printf("l'etat: %d /n", tmp->w.ok);
      tmp = tmp->suiv;
    }
  }
}
</code>```

答:
The reason of the error is that you placed function definitions in a header that is included more than one module. As a result the functions are defined more than one time.

Remove the function definitions from the header and place them in a module.

The header should have only function declarations without their definitions if the functions are declared without the function specifier inline.

Pay attention to that the function gets is unsafe and is not supported by the C Standard.

Also in the condition expression

```<code> } while ((w->ok = !0) && (w->ok = !1));
</code>```

it seems there is a typo.

Maybe you mean

```<code> } while ((w->ok != 0) && (w->ok != 1));
</code>```

It seems there is another typo

```<code>  struct cellule *nouv;

  nouv = malloc(sizeof(wagon));
</code>```

Maybe you need to write

```<code>  nouv = malloc(sizeof( struct cellule ));
</code>```

And maybe this if-else statement

```<code>  if (l != NULL) {
    nouv->w = w;
    nouv->suiv = l;
  } else {
    nouv->suiv = NULL;
    l = nouv;
  }
</code>```

should be rewritten like one if statement.

```<code>  if (l != NULL) {
    nouv->w = w;
    nouv->suiv = l;
    l = nouv;
  }
</code>```

That is it seems there are several problems with your function definitions.

Title: How to fix multiple definition erorr?

Body:
In my code (using code blocks) it kept saying multiple definition in every function in wagon.c

I try change so much var in .h and main but it useless.  I'm not that good in English nor in code ^^ so please any help or some sites to learn this chapter to improve my skills.

I have the .h and its good

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wagon.h"

void saisir_wagon(wagon *w) //here there is a multipel definition how``
{
  printf("donner un numero\n");
  scanf("%d", &w->num);
  do {
    printf("donner le type\n");
    gets(w->type);
  } while ((strcmp(w->type, "wagon") != 0)
      && (strcmp(w->type, "locomotive" != 0)));
  do {
    printf("donner l etat \n");
    scanf("%d", &w->ok);
  } while ((w->ok = !0) && (w->ok = !1));
}

LIST ajout_deb(wagon w, LIST l) {
  struct cellule *nouv;

  nouv = malloc(sizeof(wagon));

  if (l != NULL) {
    nouv->w = w;
    nouv->suiv = l;
  } else {
    nouv->suiv = NULL;
    l = nouv;
  }

  return l;
}

LIST ajout_queue(wagon W, LIST l) {
  struct cellule *nouv, *parc;

  nouv = malloc(sizeof(cellule));
  nouv->w = W;
  nouv->suiv = NULL;

  if (l == NULL) {
    l = nouv;
  } else {
    parc = l;
    while (parc->suiv != NULL) {
      parc = parc->suiv;
    }
    parc->suiv = nouv;
  }
  return (l);
}

void parkour_l(LIST l) {
  struct cellule *tmp = l;
  if (l == NULL)
    printf("liste vide /n");
  else {
    while (tmp != NULL) {
      printf("le numero :%d /n", tmp->w.num);
      printf("le type :%s /n", tmp->w.type);
      printf("l'etat: %d /n", tmp->w.ok);
      tmp = tmp->suiv;
    }
  }
}

Body:
The reason of the error is that you placed function definitions in a header that is included more than one module. As a result the functions are defined more than one time.

Remove the function definitions from the header and place them in a module.

The header should have only function declarations without their definitions if the functions are declared without the function specifier inline.

Pay attention to that the function gets is unsafe and is not supported by the C Standard.

Also in the condition expression

 } while ((w->ok = !0) && (w->ok = !1));

it seems there is a typo.

Maybe you mean

 } while ((w->ok != 0) && (w->ok != 1));

It seems there is another typo

  struct cellule *nouv;

  nouv = malloc(sizeof(wagon));

Maybe you need to write

  nouv = malloc(sizeof( struct cellule ));

And maybe this if-else statement

  if (l != NULL) {
    nouv->w = w;
    nouv->suiv = l;
  } else {
    nouv->suiv = NULL;
    l = nouv;
  }

should be rewritten like one if statement.

  if (l != NULL) {
    nouv->w = w;
    nouv->suiv = l;
    l = nouv;
  }

That is it seems there are several problems with your function definitions.


问:
Android Studio Bumblebee Navigation can't access FragmentDirections for action
I create such action before Android Studio bumblebee update and it was working fine.

```<code>fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}
</code>```

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

```<code>buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My build.gradle App

```<code>plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}
</code>```

答:
okay so after bumblebee update gradle structure is changed.

but as mentioned above you can still add

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.1")
    }
}
</code>```

before the plugins{} in project level gradle.

but the better alternative is to just use

```<code>id 'androidx.navigation.safeargs.kotlin' version '2.4.1' apply false
</code>```

in plugins{} at project level gradle

both of above will cover first step you still need to add

```<code>id 'androidx.navigation.safeargs.kotlin'
</code>```

in plugins{} at app level gradle

**if you had already added these but now they are not resolving or cannot access fragment direction the reason might be because you have update you gradle to 7.1.0 and safe-args-plugin:2.4.0 is not compatible with that so make sure to use safe-args-plugin:2.4.1 or 2.5.0-alpha01 with gradle 7.1.0

Body:
I create such action before Android Studio bumblebee update and it was working fine.

fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My build.gradle App

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}

Body:
okay so after bumblebee update gradle structure is changed.

but as mentioned above you can still add

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.1")
    }
}

before the plugins{} in project level gradle.

but the better alternative is to just use

id 'androidx.navigation.safeargs.kotlin' version '2.4.1' apply false

in plugins{} at project level gradle

both of above will cover first step you still need to add

id 'androidx.navigation.safeargs.kotlin'

in plugins{} at app level gradle

**if you had already added these but now they are not resolving or cannot access fragment direction the reason might be because you have update you gradle to 7.1.0 and safe-args-plugin:2.4.0 is not compatible with that so make sure to use safe-args-plugin:2.4.1 or 2.5.0-alpha01 with gradle 7.1.0


问:
Sorted X axis ticks in Matplotlib when using multiple datasets
I have several datasets that I want to plot. The x values are "categorical" strings, in the sense that they have no particularly meaning, but they are sortable (alphanumeric). Each dataset has some X values that are unique, and some that are in common. The desired output is a graph where the xXtick labels are in sorted order.

Unfortunately I can't find a way to tell matplotlib what I want. It properly combines the Y values on the common X values, but puts the unique X values in the later datasets on the right side of the graph.

Here's an example to illustrate the issue:

```<code>import matplotlib.pyplot as plt
import numpy as np

# Create first data set
x1 = np.array(['a', 'c', 'e'])
y1 = np.array([1, 2, 5])

# Create second data set with some x values in common with first dataset
x2 = np.array(['a', 'b', 'd', 'e'])
y2 = np.array([2, 4, 1, 1])

# Plot both datasets
fig, ax = plt.subplots()
ax.plot(x1, y1, color='r', marker='+', linestyle='None')
ax.plot(x2, y2, color='b', marker='o', linestyle='None')
</code>```

This results in the graph below.

The values for "a" and "e" are properly combined for both datasets. But I'd like to have "b" and "d" show up in sorted order, such that the X tick labels are "a", "b", "c", "d", "e". I can produce a combined sorted set of X values using

```<code>sorted_x = np.sort(np.unique(np.hstack([x1, x2]))))
</code>```

But I'm unsure how to leverage this to tell matplotlib this is the desired order.

答:
You could first add a dummy plot using the x-values in the desired order. The following code creates the dummy plot, setting the x-values in the desired order. The plot is removed immediately to prevent that it interferes with other matplotlib functions.

import matplotlib.pyplot as plt
import numpy as np

# Create first data set
x1 = np.array(['a', 'c', 'e'])
y1 = np.array([1, 2, 5])

# Create second data set with some x values in common with first dataset
x2 = np.array(['a', 'b', 'd', 'e'])
y2 = np.array([2, 4, 1, 1])

# Plot both datasets
fig, ax = plt.subplots()

sorted_x = np.sort(np.unique(np.hstack([x1, x2])))

sorted_x = np.sort(np.unique(np.hstack([x1, x2])))
# create a dummy plot with the x-values in the desired order, and then remove the plot
ax.plot(sorted_x, np.full(len(sorted_x), np.NaN), color='none')[0].remove()
ax.plot(x1, y1, color='r', marker='+', linestyle='None')
ax.plot(x2, y2, color='b', marker='o', linestyle='None')
plt.show()
```

Body:
I have several datasets that I want to plot. The x values are "categorical" strings, in the sense that they have no particularly meaning, but they are sortable (alphanumeric). Each dataset has some X values that are unique, and some that are in common. The desired output is a graph where the xXtick labels are in sorted order.

Unfortunately I can't find a way to tell matplotlib what I want. It properly combines the Y values on the common X values, but puts the unique X values in the later datasets on the right side of the graph.

Here's an example to illustrate the issue:

import matplotlib.pyplot as plt
import numpy as np

# Create first data set
x1 = np.array(['a', 'c', 'e'])
y1 = np.array([1, 2, 5])

# Create second data set with some x values in common with first dataset
x2 = np.array(['a', 'b', 'd', 'e'])
y2 = np.array([2, 4, 1, 1])

# Plot both datasets
fig, ax = plt.subplots()
ax.plot(x1, y1, color='r', marker='+', linestyle='None')
ax.plot(x2, y2, color='b', marker='o', linestyle='None')

This results in the graph below.

The values for "a" and "e" are properly combined for both datasets. But I'd like to have "b" and "d" show up in sorted order, such that the X tick labels are "a", "b", "c", "d", "e". I can produce a combined sorted set of X values using

sorted_x = np.sort(np.unique(np.hstack([x1, x2]))))

But I'm unsure how to leverage this to tell matplotlib this is the desired order.


问:
CakePHP - Multiple paginated tables for the same model, on the same page
I get the impression this is not supported by Cake core yet, but has anyone managed to write their own code to do so?  Is it possible with Ajax? I don't mind having all my tables Ajax sortable if this is the only way to do it.

Yes, I am aware of the link everyone posts (http://debuggable.com/posts/how-to-have-multiple-paginated-widgets-on-the-same-page-with-cakephp) and it does not solve the problem.

答:
I ended up scrapping Cake's pagination system, and instead used a jQuery plugin called dataTables (http://www.datatables.net/).

It is quite frankly amazing what this guy has done to develop the plugin.  It supports server-side powered pagination, sorting, and even filtering of your tables.


问:
How can I null-check this?
```<code>FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) => Text(
    "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
    textAlign: TextAlign.center,
    style: TextStyle(fontSize: 20),
  ), // Text
), // FutureBuilder
</code>```

I have "An expression whose value can be 'null' must be null-checked before it can be dereferenced." error in snapshot.data. How can I null-check this?

GetLiter() func is here =>

```<code>Future<Object?> GetLiter() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");

  DatabaseEvent event = await ref.once();

  // print(event.snapshot.value);
  return event.snapshot.value;
}
</code>```

答:
While using FutureBuilder you need to await for data and handle loading state and null data.

child: FutureBuilder<Object?>(
  future: GetLiter(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    } else if (snapshot.hasData &&
        snapshot.connectionState == ConnectionState.done) {
      return Text("Got Data");
    } else if (!snapshot.hasData) {
      return Text("no Data");
    } else if (snapshot.hasError) {
      return Text(snapshot.error.toString());
    } else {
      return Text("others");
    }
  },
),
```

More about FutureBuilder

Title: How can I null-check this?

Body:
FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) => Text(
    "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
    textAlign: TextAlign.center,
    style: TextStyle(fontSize: 20),
  ), // Text
), // FutureBuilder

I have "An expression whose value can be 'null' must be null-checked before it can be dereferenced." error in snapshot.data. How can I null-check this?

GetLiter() func is here =>

Future<Object?> GetLiter() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");

  DatabaseEvent event = await ref.once();

  // print(event.snapshot.value);
  return event.snapshot.value;
}

Body:
While using FutureBuilder you need to await for data and handle loading state and null data.

child: FutureBuilder<Object?>(
  future: GetLiter(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    } else if (snapshot.hasData &&
        snapshot.connectionState == ConnectionState.done) {
      return Text("Got Data");
    } else if (!snapshot.hasData) {
      return Text("no Data");
    } else if (snapshot.hasError) {
      return Text(snapshot.error.toString());
    } else {
      return Text("others");
    }
  },
),

More about FutureBuilder


问:
Is there a more efficient way to compare two lists in python than O(m*n)?
I am trying to find a method for comparing two lists in python in a more efficient way than what I think is the current O(m*n) runtime. Right now I have a brute force approach of iterating each item in m and comparing it to n but is anything else possible? I have tried maybe sorting the lists first for maybe something faster but I am kind of stuck on whether anything else could work here.

In my function i take each item in m and compare it to n and count the number of times the item in m is greater than the item in n.

```<code>n = [1,3,7]
m = [2,9]

def comparison(n,m):
counter = 0
for i in m:
    for j in n:
        if i >= j:
            counter += 1

return counter

</code>```

答:
I wrote a code for you to test which one runs faster using the built-in "timeit" library. You can test others' advice using the same structure. There is the code:</p>
```<code>import timeit
import numpy as np

n = [1,3,7]
m = [9,2]

my_code = '''
def comparison(n,m):
    counter = 0
    for i in n:
        for j in m:
            if i >= j:
                counter += 1

    return counter
'''

mysetup = "import numpy as np"
my_code2 = '''
def comparison_with_numpy(n,m):
    x = np.array(n)
    y = np.array(m)

    smaller = np.array([x[i] > y[:] for i in range(x.shape[0])]).astype('int')

    return sum(smaller)[0]

'''

my_code3 = '''
def sort_first(n,m):
    sorted(n)
    sorted(m)
    count = 0

    if len(n) > len(m):
        iteration = len(n)
    else:
        iteration = len(m)

    for _ in range(iteration):
        if n != []:
            y = n.pop(0)
        if m != []:
            x = m.pop(0)

        if y > x:
            count += 1
    return count

'''

def comparison(n,m):
    counter = 0
    for i in n:
        for j in m:
            if i >= j:
                counter += 1

    print(counter)
    return counter

def comparison_with_numpy(n,m):
    x = np.array(n)
    y = np.array(m)

    smaller = np.array([x[i] > y[:] for i in range(x.shape[0])]).astype('int')

    return sum(smaller)[0]

def sort_first(n,m):
    sorted(n)
    sorted(m)
    count = 0

    if len(n) > len(m):
        iteration = len(n)
    else:
        iteration = len(m)

    for _ in range(iteration):
        if n != []:
            y = n.pop(0)
        if m != []:
            x = m.pop(0)

        if y > x:
            count += 1
    return count

def main():
    print('comparison /w sort\t\t',timeit.timeit(stmt = my_code3,number=10000))
    print('comparison\t\t',timeit.timeit(stmt = my_code,number=10000))
    print('comparison with numpy\t\t',timeit.timeit(setup = mysetup
                                                    ,stmt = my_code2
                                                    ,number=10000))

if __name__ == "__main__":
    main()
</code>```

Body:
I am trying to find a method for comparing two lists in python in a more efficient way than what I think is the current O(m*n) runtime. Right now I have a brute force approach of iterating each item in m and comparing it to n but is anything else possible? I have tried maybe sorting the lists first for maybe something faster but I am kind of stuck on whether anything else could work here.

In my function i take each item in m and compare it to n and count the number of times the item in m is greater than the item in n.

n = [1,3,7]
m = [2,9]

def comparison(n,m):
counter = 0
for i in m:
    for j in n:
        if i >= j:
            counter += 1

return counter

Body:
I wrote a code for you to test which one runs faster using the built-in "timeit" library. You can test others' advice using the same structure. There is the code:

import timeit
import numpy as np

n = [1,3,7]
m = [9,2]

my_code = '''
def comparison(n,m):
    counter = 0
    for i in n:
        for j in m:
            if i >= j:
                counter += 1

    return counter
'''

mysetup = "import numpy as np"
my_code2 = '''
def comparison_with_numpy(n,m):
    x = np.array(n)
    y = np.array(m)

    smaller = np.array([x[i] > y[:] for i in range(x.shape[0])]).astype('int')

    return sum(smaller)[0]

'''

my_code3 = '''
def sort_first(n,m):
    sorted(n)
    sorted(m)
    count = 0

    if len(n) > len(m):
        iteration = len(n)
    else:
        iteration = len(m)

    for _ in range(iteration):
        if n != []:
            y = n.pop(0)
        if m != []:
            x = m.pop(0)

        if y > x:
            count += 1
    return count

'''

def comparison(n,m):
    counter = 0
    for i in n:
        for j in m:
            if i >= j:
                counter += 1

    print(counter)
    return counter

def comparison_with_numpy(n,m):
    x = np.array(n)
    y = np.array(m)

    smaller = np.array([x[i] > y[:] for i in range(x.shape[0])]).astype('int')

    return sum(smaller)[0]

def sort_first(n,m):
    sorted(n)
    sorted(m)
    count = 0

    if len(n) > len(m):
        iteration = len(n)
    else:
        iteration = len(m)

    for _ in range(iteration):
        if n != []:
            y = n.pop(0)
        if m != []:
            x = m.pop(0)

        if y > x:
            count += 1
    return count

def main():
    print('comparison /w sort\t\t',timeit.timeit(stmt = my_code3,number=10000))
    print('comparison\t\t',timeit.timeit(stmt = my_code,number=10000))
    print('comparison with numpy\t\t',timeit.timeit(setup = mysetup
                                                    ,stmt = my_code2
                                                    ,number=10000))

if __name__ == "__main__":
    main()


问:
RXJS, How to watch mouse and keyboard and do something when when none has been used for some time?
I need run a function if neither the mouse has moved, nor the keyboard has been touched for 1mn.

I tried the code below but doesn't seem to work.
How can I fix it?
Thank you for your help.

```<code>mouseEvent$ = fromEvent(document, 'mouseMove');
keyPress$ = fromEvent(document, 'keyup');

merge(
    this.mouseEvent$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
    this.keyPress$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
).subscribe(() => console.log("----));
</code>```

答:
Here's my take on this:

 const mouseMove$ = fromEvent<MouseEvent>(document, 'mousemove');
 const keyPress$ = fromEvent<KeyboardEvent>(document, 'keyup');
 const mergeBothEvents = merge(keyPress$, mouseMove$);
 const interval$ = timer(60000);

 mergeBothEvents
     .pipe(
       startWith('initial'),
       switchMap(() => {
         return interval$;
       })
     )
     .subscribe(() => {
       console.log('60 seconds past');
       console.log('Perform function here');
     });
```

A bit of inside into what's happening in the code.

fromEvent<MouseEvent> used to capture the mouse movements.

fromEvent<KeyboardEvent> used to capture the keyboard key up click event.

merge(keyPress$, mouse$) is used to merge both the observables so that they can run in parallel.

timer(60000) is used to check the time of a minute before running the required function.

In mergeBothEvents we have used to more operators startWith() and switchMap

startWith() is used for the edge-case in which if the user doesn't do anything(mouse or keyboard) when he enters the page the mergeBothEvents event won't be emitted. Thanks @MrkSef to for pointing that out.

Finally switchMap is used to cancel the previous subscription of the event when the user moves the mouse or presses the keyboard so the timer restarts from 0th second.

Body:
I need run a function if neither the mouse has moved, nor the keyboard has been touched for 1mn.

I tried the code below but doesn't seem to work.
How can I fix it?
Thank you for your help.

mouseEvent$ = fromEvent(document, 'mouseMove');
keyPress$ = fromEvent(document, 'keyup');

merge(
    this.mouseEvent$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
    this.keyPress$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
).subscribe(() => console.log("----));

Body:
Here's my take on this:

 const mouseMove$ = fromEvent<MouseEvent>(document, 'mousemove');
 const keyPress$ = fromEvent<KeyboardEvent>(document, 'keyup');
 const mergeBothEvents = merge(keyPress$, mouseMove$);
 const interval$ = timer(60000);

 mergeBothEvents
     .pipe(
       startWith('initial'),
       switchMap(() => {
         return interval$;
       })
     )
     .subscribe(() => {
       console.log('60 seconds past');
       console.log('Perform function here');
     });

A bit of inside into what's happening in the code.

fromEvent<MouseEvent> used to capture the mouse movements.

fromEvent<KeyboardEvent> used to capture the keyboard key up click event.

merge(keyPress$, mouse$) is used to merge both the observables so that they can run in parallel.

timer(60000) is used to check the time of a minute before running the required function.

In mergeBothEvents we have used to more operators startWith() and switchMap

startWith() is used for the edge-case in which if the user doesn't do anything(mouse or keyboard) when he enters the page the mergeBothEvents event won't be emitted. Thanks @MrkSef to for pointing that out.

Finally switchMap is used to cancel the previous subscription of the event when the user moves the mouse or presses the keyboard so the timer restarts from 0th second.


问:
How to set default encoding in Python (setdefaultencoding() function does not exist)?

Possible Duplicate:

  Changing default encoding of python?

I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.

The setdefaultencoding is used in   python-installed-dir/site-packages/pyanaconda/sitecustomize.py

```<code>import sys
sys.setdefaultencoding('utf-8')
</code>```

But when I run the script, it raises:

```<code>AttributeError: 'module' object has no attribute 'setdefaultencoding'
</code>```

How to set the default encoding,anyway?

I am using python 2.7

Solution:
find the site.py in the python installation.

Edit the setencoding function

```<code>def setencoding():
    encoding = "ascii"
    if 0:
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0: #changes comes here, change 0 to 1
        encoding = "undefined" #the encoding you want
    if encoding != "ascii":
        sys.setdefaultencoding(encoding)
</code>```

I am using python 2.7

答:
Python's sys module has had a setdefaultencoding function since Python 2.0. However,

This function is only intended to be used by the site module implementation and, where needed, by sitecustomize. Once used by the site module, it is removed from the sys module’s namespace.

The docs back to at least Python 2.1 indicate this happens, so it was never appropriate for PyAnaconda to use this method, and I'm not sure why it ever worked.

Body:
Possible Duplicate:

  Changing default encoding of python?

I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.

The setdefaultencoding is used in   python-installed-dir/site-packages/pyanaconda/sitecustomize.py

import sys
sys.setdefaultencoding('utf-8')

But when I run the script, it raises:

AttributeError: 'module' object has no attribute 'setdefaultencoding'

How to set the default encoding,anyway?

I am using python 2.7

Solution:
find the site.py in the python installation.

Edit the setencoding function

def setencoding():
    encoding = "ascii"
    if 0:
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0: #changes comes here, change 0 to 1
        encoding = "undefined" #the encoding you want
    if encoding != "ascii":
        sys.setdefaultencoding(encoding)

I am using python 2.7


问:
How to escape a python interactive shell
I am trying to escape a python interactive shell within an ssh server without closing the ssh connection, using exit(), quit() ctrl D closes the ssh connection</p>

答:
ssh -t

-t flag forces use of ptty. Control sequences will be sent directly to remote process


问:
Cosmos SQL find items which has a string in array
I'm trying to write a query in CosmosDB using SQL for the following scenario. Let say I have a collection with items as follows

```<code>{
   "resource": "abc",
   "region": "east",
   "tags": ["tag1", "tag2"]
}

{
   "resource": "def",
   "region": "east",
   "tags": ["tag1", "tag2"]
}

{
   "resource": "xyz",
   "region": "east",
   "tags": ["tag3"]
}
</code>```

now I want to write a query that return all items that has a string "tag1" in tags property (I want to get/project all the properties in that item)

答:
You can make use of ARRAY_CONTAINS system function for that. So your query would be something like:

```<code>SELECT * FROM Root r where ARRAY_CONTAINS(r.tags, "tag1")
</code>```

and this would give a result like:

```<code>[
    {
        "id": "cd385b65c6b14b07eb157b72485b1260",
        "resource": "abc",
        "region": "east",
        "tags": [
            "tag1",
            "tag2"
        ],
    },
    {
        "id": "bb77e9ad1950467390cbc5ffac33cac3",
        "resource": "def",
        "region": "east",
        "tags": [
            "tag1",
            "tag2"
        ],
    }
]
</code>```

Body:
I'm trying to write a query in CosmosDB using SQL for the following scenario. Let say I have a collection with items as follows

{
   "resource": "abc",
   "region": "east",
   "tags": ["tag1", "tag2"]
}

{
   "resource": "def",
   "region": "east",
   "tags": ["tag1", "tag2"]
}

{
   "resource": "xyz",
   "region": "east",
   "tags": ["tag3"]
}

now I want to write a query that return all items that has a string "tag1" in tags property (I want to get/project all the properties in that item)

Body:
You can make use of ARRAY_CONTAINS system function for that. So your query would be something like:

SELECT * FROM Root r where ARRAY_CONTAINS(r.tags, "tag1")

and this would give a result like:

[
    {
        "id": "cd385b65c6b14b07eb157b72485b1260",
        "resource": "abc",
        "region": "east",
        "tags": [
            "tag1",
            "tag2"
        ],
    },
    {
        "id": "bb77e9ad1950467390cbc5ffac33cac3",
        "resource": "def",
        "region": "east",
        "tags": [
            "tag1",
            "tag2"
        ],
    }
]


问:
Focus On Input With Error on Form Submission
It would be nice to have functionality when the user submits a form that fails the validation, it will set focus on the first field with an error.

I have shouldFocusError : true set in the useForm configuration. When I click submit, the validation triggers, but the input is not focused.

Any suggestions on how I can achieve this?

For reference, I am using MUI and react-hook-form to create custom components in the form. For the components themselves, they are using the useController hook like so:

```<code>const { field, fieldState } = useController(props);
<TextField
    {...field}
    error={!!fieldState.error}
    helperText={fieldState.error?.message || ''}
/>
</code>```

答:
Solution:

Spreading the field object returned from the useController hook contains the following:

```<code>{
    value: ...
    name: ...
    onChange: ...
    onBlur: ...
    ref: ...
}
</code>```

The problem I described above was solved when I removed ref property from the object and passed it separately to inputRef. Like so:

```<code>const { field, fieldState } = useController(props);
const { ref, ...fieldProps } = field;
<TextField
    {...fieldProps}
    inputRef={ref} //or you can use field.ref
    id={field.name} //this solved other issues I was having
    error={!!fieldState.error}
    helperText={fieldState.error?.message || ''}
/>
</code>```

After doing this, React Hook Form set focus on the first field with an error when the user submits a form that fails the validation.

Body:
It would be nice to have functionality when the user submits a form that fails the validation, it will set focus on the first field with an error.

I have shouldFocusError : true set in the useForm configuration. When I click submit, the validation triggers, but the input is not focused.

Any suggestions on how I can achieve this?

For reference, I am using MUI and react-hook-form to create custom components in the form. For the components themselves, they are using the useController hook like so:

const { field, fieldState } = useController(props);
<TextField
    {...field}
    error={!!fieldState.error}
    helperText={fieldState.error?.message || ''}
/>

Body:
Solution:

Spreading the field object returned from the useController hook contains the following:

{
    value: ...
    name: ...
    onChange: ...
    onBlur: ...
    ref: ...
}

The problem I described above was solved when I removed ref property from the object and passed it separately to inputRef. Like so:

const { field, fieldState } = useController(props);
const { ref, ...fieldProps } = field;
<TextField
    {...fieldProps}
    inputRef={ref} //or you can use field.ref
    id={field.name} //this solved other issues I was having
    error={!!fieldState.error}
    helperText={fieldState.error?.message || ''}
/>

After doing this, React Hook Form set focus on the first field with an error when the user submits a form that fails the validation.


问:
YouCompleteMe: compile problem ycm core library not detected. VIM. Linux MInt
The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). YCM core library not detected; you need to compile YCM before using it.
I tried to compile ycm file using:

https://github.com/todaygood/go_repo/issues/5

Cannot run Python script using sudo

https://vimawesome.com/plugin/youcompleteme#linux-64-bit
and 2 more sources which include same info
but my problem starts when i try to run

python3 install.py

in terminal

Error:This script should not be run with sudo.

I have virtualenv, i have cmake, i tried to ran it in my env, i tried using different commands using pip, pip3, python, python3, sudo + <--(,,,,). Of course i tried to do it using root.

答:
YouCompleteMe build example with a clean Ubuntu 20.04.3, installed/updated 10 days ago

```<code>sudo apt install build-essential cmake vim-nox \
python3-dev golang openjdk-11-jdk rust-all npm

    ## in /home/[name]/tmp/
git clone https://github.com/ycm-core/YouCompleteMe.git
cd YouCompleteMe/
git submodule update --init --recursive

./install.py --all
Generating ycmd build configuration...OK
Compiling ycmd target: ycm_core...OK
Building regex module...OK
Building watchdog module...OK
Installing Omnisharp for C# support...OK
Building gopls for go completion...OK
Setting up Tern for JavaScript completion...OK
Installing rust-analyzer for Rust support...OK
Installing jdt.ls for Java support...OK
Setting up TSserver for TypeScript completion...OK
Setting up Clangd completer...OK
</code>```

(No issues with other OS´s either.)

Body:
YouCompleteMe build example with a clean Ubuntu 20.04.3, installed/updated 10 days ago

sudo apt install build-essential cmake vim-nox \
python3-dev golang openjdk-11-jdk rust-all npm

    ## in /home/[name]/tmp/
git clone https://github.com/ycm-core/YouCompleteMe.git
cd YouCompleteMe/
git submodule update --init --recursive

./install.py --all
Generating ycmd build configuration...OK
Compiling ycmd target: ycm_core...OK
Building regex module...OK
Building watchdog module...OK
Installing Omnisharp for C# support...OK
Building gopls for go completion...OK
Setting up Tern for JavaScript completion...OK
Installing rust-analyzer for Rust support...OK
Installing jdt.ls for Java support...OK
Setting up TSserver for TypeScript completion...OK
Setting up Clangd completer...OK

(No issues with other OS´s either.)


问:
How to connect mongodb with url
I am new to mongodb.
I have db url, and I want to connect to that server from my ubuntu terminal and access data on terminal.
can anyone please help me how to connect?</p>

答:
Assuming you have the URI and the mongo shell installed, you can connect using the following command:

mongo <uri>

For example, if you want to log in as admin with the password mypassword through example.com on the port 27017, you can do:

mongo mongodb://admin:mypassword@example.com:27017/?authSource=admin

See:
how can I connect to a remote mongo server from Mac OS terminal

Title: How to connect mongodb with url