问:
Python exec() NameError: name 'o' is not defined
This code chunk here was intended to look for any occurrences of a letter in one list, and if it finds any, it replaces the value in the second list with the same index value.

iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{x}] = {y}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]
```
<p>Expected result:</p>
<pre class="lang-none prettyprint-override"><code>['_', 'o', 'o', '_']
</code>```

Actual result:

Traceback (most recent call last):
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <module>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <listcomp>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 10, in updateList
    exec(bomb)
  File "<string>", line 1, in <module>
NameError: name 'o' is not defined
PS C:\Users\night\Desktop\RGL>
```

答:
When you use string formatting, it doesn't include the quotes on strings. Rewrite your formatters to use the REPR-form of strings:

```<code>iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{x!r}] = {y!r}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]
</code>```

Alternatively, call repr() directly:

```<code>iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{repr(x)}] = {repr(y)}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]
</code>```

Body:
This code chunk here was intended to look for any occurrences of a letter in one list, and if it finds any, it replaces the value in the second list with the same index value.

iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{x}] = {y}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]

Expected result:

['_', 'o', 'o', '_']

Actual result:

Traceback (most recent call last):
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <module>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <listcomp>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 10, in updateList
    exec(bomb)
  File "<string>", line 1, in <module>
NameError: name 'o' is not defined
PS C:\Users\night\Desktop\RGL>

Body:
When you use string formatting, it doesn't include the quotes on strings. Rewrite your formatters to use the REPR-form of strings:

iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{x!r}] = {y!r}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]

Alternatively, call repr() directly:

iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{repr(x)}] = {repr(y)}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]


来源: stackexchange

问:
mouseOver ImageReplace in canvas
I am trying to replace a image I have added to a canvas with a mouseOver event. I don't think I am doing this right.

```<code><script>
function loadImage(){
     var canvas = document.getElementById("e");
     var context = canvas.getContext("2d");

     var cat = new Image();
     cat.src = "images/paul01.jpg";
     cat.onload = function() {
         context.drawImage(cat, 0, 0, 166, 276);
     };
}
</script>
<script>
function mouseOver(); {
    var canvas = document.getElementById("e");
    var context = canvas.getContext("2d");
    var cat = new Image();
    cat.src = "images/paul02.jpg";
    cat.onload = function() {
        context.drawImage(cat, 0, 0, 166, 276);
    };
}
</script>

<a href=""onmouseover="mouseOver"()>
 <div class="canvas">
  <canvas id="e" width="166" height="276">
   <p>No Canvas Support in Browser, old fashion image?</p>
   <img src="images/paul01.jpg">
  </canvas>
 </div>
</a>
</code>```

New Code:
I am trying to change the image in canvas ID 'A' with mouse out on canvas 'e' I have been able to get the mousover to work and add a image to canvas 'A', but not remove it.

```<code> <script>
        function init() {
            setImageOne();
        }

        function setImageOne() { setImage('images/paul01.jpg'); }

        <!--function setImageTwo() { setImage('images/paul02.jpg'); }-->

        function unsetImageOne() { largeImage('images/full/cartoonPaul02.jpg'); }

        function setImageTwo() { largeImage('images/full/cartoonPaul01.jpg'); }

        function setImage(src) {
            var canvas = document.getElementById("l");
            var context = canvas.getContext("2d");
            if (context == null) return;
            var img = new Image();
            img.src = src;
            context.drawImage(img, 0, 0, 166, 276);
        }

        function largeImage(src){
            var canvas = document.getElementById("A");
            var context = canvas.getContext("2d");
            if (context == null) return;
            var img = new Image();
            img.src = src;
            context.drawImage(img, 0, 0, 300, 400);
        }
</script>
    <div id="container">
        <header>
        <a href='../../'><h3>Everything else</h3></a>
        </header>
        <div id="main" role="main">
        <body onload="init()">

            <div class="canvas">
                <canvas id="l" width="166" height="276" onmouseover="setImageTwo()" onmouseout="unsetImageOne()"></canvas>
            </div>

            <div class="canvas">
                <canvas id="A" width="300" height="400"></canvas>
            </div>
</code>```

答:
There are a couple syntax errors and misconceptions in your code. Below is a simplified, working example. You can put the mouse handlers right onto the canvas element. Your loadImage() function isn't even used. I also added an onmouseout() to revert the image, although I'm not sure that's your intended behavior.</p>

```<code><!doctype html>
<html>
  <body>
    <head>
      <script>
        function init() {
            setImageOne();
        }

        function setImageOne() { setImage('one.jpg'); }

        function setImageTwo() { setImage('two.jpg'); }

        function setImage(src) {
            var canvas = document.getElementById("e");
            var context = canvas.getContext("2d");
            if (context == null) return;
            var img = new Image();
            img.src = src;
            context.drawImage(img, 0, 0, 166, 276);
        }
      </script>
    </head>
  <body onload="init()">
    <div>
      <canvas id="e" width="166" height="276" onmouseover="setImageTwo()" onmouseout="setImageOne()">
        <p>No Canvas Support in Browser</p>
      </canvas>
    </div>
  <body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Title: mouseOver ImageReplace in canvas

Body:
I am trying to replace a image I have added to a canvas with a mouseOver event. I don't think I am doing this right.

  <canvas id="e" width="166" height="276">

No Canvas Support in Browser, old fashion image?

  </canvas>

New Code:
I am trying to change the image in canvas ID 'A' with mouse out on canvas 'e' I have been able to get the mousover to work and add a image to canvas 'A', but not remove it.

Everything else

                <canvas id="l" width="166" height="276" onmouseover="setImageTwo()" onmouseout="unsetImageOne()"></canvas>

                <canvas id="A" width="300" height="400"></canvas>

Body:
There are a couple syntax errors and misconceptions in your code. Below is a simplified, working example. You can put the mouse handlers right onto the canvas element. Your loadImage() function isn't even used. I also added an onmouseout() to revert the image, although I'm not sure that's your intended behavior.

<!doctype html>
<html>
  <body>
    <head>
      <script>
        function init() {
            setImageOne();
        }

        function setImageOne() { setImage('one.jpg'); }

        function setImageTwo() { setImage('two.jpg'); }

        function setImage(src) {
            var canvas = document.getElementById("e");
            var context = canvas.getContext("2d");
            if (context == null) return;
            var img = new Image();
            img.src = src;
            context.drawImage(img, 0, 0, 166, 276);
        }
      </script>
    </head>
  <body onload="init()">
    <div>
      <canvas id="e" width="166" height="276" onmouseover="setImageTwo()" onmouseout="setImageOne()">
        <p>No Canvas Support in Browser</p>
      </canvas>
    </div>
  <body>
</html>


问:
Extract specific items from list
I would like to extract only the names that are from January, so that they appear in the January column, I've tried =left() and =right() but they don't seem to work. Any info on how to do this will help!

答:
In C2 (under the "January" header), place this formula:

=FILTER($A2:$A, $B2:$B=C1)

This one formula would work without the $ symbols. But I assume you're going to want to drag it to the right under other month names; so I wrote it accordingly.

ContentLicense: CC BY-SA 4.0

Title: Extract specific items from list


问:
How do I delete elements that are visible under Elementor?
I have created a WP page using the Astra theme.

I edit it using Elementor.

I have 2 lines in my page, and it took me very long to find out where they come from.

If I delete all elements with Elementor, I can still see the lines, so they must be part of the underlying page.

How would I remove them?

Thank you!

Edit:

I think I found what @Mtxz meant, it's under Global->Colors:

Change the image position does change the position of the lines.
But when I click "Remove Image", nothing happens: The lines stay there, so I wonder why they are still there.

答:
as per @Mtxz said without any access to the site we can't tell you where it's coming from. but for temporary if you want to hide rather than replace then you can use the below CSS.

Add this CSS to your active theme style.css file.

```<code>body, .ast-separate-container {
    background: none !important;
}
</code>```

Or you can add this CSS using the wp_head action hook. add this below code to your active theme functions.php file.

```<code>function add_custom_css(){
    ?>
    <style type="text/css">

        body, .ast-separate-container {
            background: none !important;
        }

    </style>
    <?php
}
add_action( 'wp_head', 'add_custom_css', 10, 1 );
</code>```

Tested and works.

Body:
as per @Mtxz said without any access to the site we can't tell you where it's coming from. but for temporary if you want to hide rather than replace then you can use the below CSS.

Add this CSS to your active theme style.css file.

body, .ast-separate-container {
    background: none !important;
}

Or you can add this CSS using the wp_head action hook. add this below code to your active theme functions.php file.

function add_custom_css(){
    ?>
    <style type="text/css">

        body, .ast-separate-container {
            background: none !important;
        }

    </style>
    <?php
}
add_action( 'wp_head', 'add_custom_css', 10, 1 );

Tested and works.


问:
Set Integers getItemViewType RecyclerView
I have an array list of integers[3,-3,7,9,8,1].

What I am trying to do is to get the same numbers that are positive and negative and make them type 1.
For example, The number "3" and "-3" will be type 1 and all the others will be type 2.

I did like the following:

override fun getItemViewType(position: Int): Int {

```<code>val positiveArray = ArrayList<Int>()
val negativeArray = ArrayList<Int>()

val currentNumber = numberList[position]

Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

for (number in numberList){
    if (number.singleNumber > 0){
        positiveArray.add(number.singleNumber)
    }else{
        negativeArray.add(number.singleNumber)
    }
}

Log.e("positiveArray","Result: $positiveArray")
Log.e("negativeArray","Result: $negativeArray")

return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
    Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
    RED_ROW
} else{
    ORANGE_ROW
}
</code>```

}

So the problem here is that when I run the app with this code,its only mark "3" as type 1 but the "-3" is type 2.

Edit:

Full adapter class:

```<code>class MainRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val ORANGE_ROW = 1
        private const val RED_ROW = 2
    }

    private lateinit var numberList : List<SingleNumber>

    inner class RedRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var redTextView : TextView

        fun bindRedRow(singleNumber: Int) {
            redTextView = itemView.findViewById<TextView>(R.id.redNumberTextView)
            redTextView.text = singleNumber.toString()
        }

    }

    inner class OrangeRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var orangeTextView : TextView

        fun bindOrangeRow(singleNumber: Int) {
            orangeTextView = itemView.findViewById<TextView>(R.id.orangeNumberTextView)
            orangeTextView.text = singleNumber.toString()
        }

    }

override fun getItemViewType(position: Int): Int {

    val positiveArray = ArrayList<Int>()
    val negativeArray = ArrayList<Int>()

    val currentNumber = numberList[position]

    Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

    for (number in numberList){
        if (number.singleNumber > 0){
            positiveArray.add(number.singleNumber)
        }else{
            negativeArray.add(number.singleNumber)
        }
    }

    Log.e("positiveArray","Result: $positiveArray")
    Log.e("negativeArray","Result: $negativeArray")

    return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
        Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
        RED_ROW
    } else{
        ORANGE_ROW
    }

}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        return if (viewType == RED_ROW){
            val redRow = LayoutInflater.from(parent.context).inflate(R.layout.red_row,parent,false)
            RedRowViewHolder(redRow)
        }else{
            val orangeRow = LayoutInflater.from(parent.context).inflate(R.layout.orange_row,parent,false)
            OrangeRowViewHolder(orangeRow)
        }

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (getItemViewType(position) == RED_ROW){
            (holder as RedRowViewHolder).bindRedRow(numberList[position].singleNumber)
        } else{
            (holder as OrangeRowViewHolder).bindOrangeRow(numberList[position].singleNumber)
        }
    }

    override fun getItemCount(): Int {
        return if (this::numberList.isInitialized){
            numberList.size
        } else 0
    }

    fun setList(newList : List<SingleNumber>){
        Log.e("ListSet","ListsET $newList")

        numberList = newList
        notifyDataSetChanged()
    }

}
</code>```

How can I overcome this ?
Do you think its build in the right way or you would do something different ? Thank you !

答:
Your return value isn't checking the value of the item. It's checking whether it's positive or negative.  So all your items are going to return one of two values.

If you want one group for the absolute value of each item, the easiest thing to do is:

```<code>override fun getItemViewType(position: Int): Int {
    return Math.abs(numberList[position])
}
</code>```

Why this works:  you don't need to start from 0, you just need to return a unique id per view type that you can map to quickly.  The absolute value of the number is unique, since both 1 and -1 map to the same group for every value.  So we just return that.

Body:
I have an array list of integers[3,-3,7,9,8,1].

What I am trying to do is to get the same numbers that are positive and negative and make them type 1.
For example, The number "3" and "-3" will be type 1 and all the others will be type 2.

I did like the following:

override fun getItemViewType(position: Int): Int {

val positiveArray = ArrayList<Int>()
val negativeArray = ArrayList<Int>()

val currentNumber = numberList[position]

Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

for (number in numberList){
    if (number.singleNumber > 0){
        positiveArray.add(number.singleNumber)
    }else{
        negativeArray.add(number.singleNumber)
    }
}

Log.e("positiveArray","Result: $positiveArray")
Log.e("negativeArray","Result: $negativeArray")

return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
    Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
    RED_ROW
} else{
    ORANGE_ROW
}

}

So the problem here is that when I run the app with this code,its only mark "3" as type 1 but the "-3" is type 2.

Edit:

Full adapter class:

class MainRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val ORANGE_ROW = 1
        private const val RED_ROW = 2
    }

    private lateinit var numberList : List<SingleNumber>

    inner class RedRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var redTextView : TextView

        fun bindRedRow(singleNumber: Int) {
            redTextView = itemView.findViewById<TextView>(R.id.redNumberTextView)
            redTextView.text = singleNumber.toString()
        }

    }

    inner class OrangeRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var orangeTextView : TextView

        fun bindOrangeRow(singleNumber: Int) {
            orangeTextView = itemView.findViewById<TextView>(R.id.orangeNumberTextView)
            orangeTextView.text = singleNumber.toString()
        }

    }

override fun getItemViewType(position: Int): Int {

    val positiveArray = ArrayList<Int>()
    val negativeArray = ArrayList<Int>()

    val currentNumber = numberList[position]

    Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

    for (number in numberList){
        if (number.singleNumber > 0){
            positiveArray.add(number.singleNumber)
        }else{
            negativeArray.add(number.singleNumber)
        }
    }

    Log.e("positiveArray","Result: $positiveArray")
    Log.e("negativeArray","Result: $negativeArray")

    return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
        Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
        RED_ROW
    } else{
        ORANGE_ROW
    }

}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        return if (viewType == RED_ROW){
            val redRow = LayoutInflater.from(parent.context).inflate(R.layout.red_row,parent,false)
            RedRowViewHolder(redRow)
        }else{
            val orangeRow = LayoutInflater.from(parent.context).inflate(R.layout.orange_row,parent,false)
            OrangeRowViewHolder(orangeRow)
        }

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (getItemViewType(position) == RED_ROW){
            (holder as RedRowViewHolder).bindRedRow(numberList[position].singleNumber)
        } else{
            (holder as OrangeRowViewHolder).bindOrangeRow(numberList[position].singleNumber)
        }
    }

    override fun getItemCount(): Int {
        return if (this::numberList.isInitialized){
            numberList.size
        } else 0
    }

    fun setList(newList : List<SingleNumber>){
        Log.e("ListSet","ListsET $newList")

        numberList = newList
        notifyDataSetChanged()
    }

}

How can I overcome this ?
Do you think its build in the right way or you would do something different ? Thank you !

Body:
Your return value isn't checking the value of the item. It's checking whether it's positive or negative.  So all your items are going to return one of two values.

If you want one group for the absolute value of each item, the easiest thing to do is:

override fun getItemViewType(position: Int): Int {
    return Math.abs(numberList[position])
}

Why this works:  you don't need to start from 0, you just need to return a unique id per view type that you can map to quickly.  The absolute value of the number is unique, since both 1 and -1 map to the same group for every value.  So we just return that.


问:
Chrome Extension - How to get HTTP Response Body?
It seems to be difficult problem (or impossible??).
I want to get and read HTTP Response, caused by HTTP Request in browser, under watching Chrome Extension background script.
We can get HTTP Request Body in this way

```<code>chrome.webRequest.onBeforeRequest.addListener(function(data){
    // data contains request_body
},{'urls':[]},['requestBody']);
</code>```

I also checked these stackoverflows

Chrome extensions - Other ways to read response bodies than chrome.devtools.network?

Chrome extension to read HTTP response

Is there any clever way to get HTTP Response Body in Chrome Extension?

答:
To get a XHR response body you can follow the instructions in this answer.

To get a FETCH response body you can check Solution 3 in this article and also this answer. Both get the response body without using chrome.debugger.

In a nutshell, you need to inject the following function into the page from the content script using the same method used for the XHR requests.

```<code>const constantMock = window.fetch;
 window.fetch = function() {
    return new Promise((resolve, reject) => {
        constantMock.apply(this, arguments)
            .then((response) => {
                if (response) {
                    response.clone().json() //the response body is a readablestream, which can only be read once. That's why we make a clone here and work with the clone
                    .then( (json) => {
                        console.log(json);
                        //Do whatever you want with the json
                        resolve(response);
                    })
                    .catch((error) => {
                        console.log(error);
                        reject(response);
                    })
                }
                else {
                    console.log(arguments);
                    console.log('Undefined Response!');
                    reject(response);
                }
            })
            .catch((error) => {
                console.log(error);
                reject(response);
            })
    })
}
</code>```

If response.clone().json() does not work, you can try response.clone().text()

Body:
It seems to be difficult problem (or impossible??).
I want to get and read HTTP Response, caused by HTTP Request in browser, under watching Chrome Extension background script.
We can get HTTP Request Body in this way

chrome.webRequest.onBeforeRequest.addListener(function(data){
    // data contains request_body
},{'urls':[]},['requestBody']);

I also checked these stackoverflows

Chrome extensions - Other ways to read response bodies than chrome.devtools.network?

Chrome extension to read HTTP response

Is there any clever way to get HTTP Response Body in Chrome Extension?

Body:
To get a XHR response body you can follow the instructions in this answer.

To get a FETCH response body you can check Solution 3 in this article and also this answer. Both get the response body without using chrome.debugger.

In a nutshell, you need to inject the following function into the page from the content script using the same method used for the XHR requests.

const constantMock = window.fetch;
 window.fetch = function() {
    return new Promise((resolve, reject) => {
        constantMock.apply(this, arguments)
            .then((response) => {
                if (response) {
                    response.clone().json() //the response body is a readablestream, which can only be read once. That's why we make a clone here and work with the clone
                    .then( (json) => {
                        console.log(json);
                        //Do whatever you want with the json
                        resolve(response);
                    })
                    .catch((error) => {
                        console.log(error);
                        reject(response);
                    })
                }
                else {
                    console.log(arguments);
                    console.log('Undefined Response!');
                    reject(response);
                }
            })
            .catch((error) => {
                console.log(error);
                reject(response);
            })
    })
}

If response.clone().json() does not work, you can try response.clone().text()


问:
Change panda date format into another date format?
How do I convert this format below into the result format ?

```<code>import pandas as pd
date = pd.date_range('2022-01-01',2022-01-31', freq = 'H')
</code>```

Result:

'2021-01-01T01%3A00%3A00',

What is the correct name for the result time format ? Have tried using urlilib.parse module, but it did not have T and it can take 1 date.

Thank you !

答:
This so called url encode , so we need urllib, notice here %3A = ':'

```<code>import urllib
date.astype(str).map(urllib.parse.quote)
Out[158]:
Index(['2022-01-01%2000%3A00%3A00', '2022-01-01%2001%3A00%3A00',
....
</code>```

Body:
How do I convert this format below into the result format ?

import pandas as pd
date = pd.date_range('2022-01-01',2022-01-31', freq = 'H')

Result:

'2021-01-01T01%3A00%3A00',

What is the correct name for the result time format ? Have tried using urlilib.parse module, but it did not have T and it can take 1 date.

Thank you !

Body:
This so called url encode , so we need urllib, notice here %3A = ':'

import urllib
date.astype(str).map(urllib.parse.quote)
Out[158]:
Index(['2022-01-01%2000%3A00%3A00', '2022-01-01%2001%3A00%3A00',
....


问:
Python JSON reader and parser not filtering results
I am trying to filter out specific results from the JSON file that is in one directory called "jsonfiles". This is my code:

```<code>import json

jsonFileN = open('jsonfiles\galaxy1.json', 'r', encoding="utf8")
jsonData = jsonFileN.read()

obj = json.loads(jsonData)
planets = [i for i in jsonData['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
print(planets)
</code>```

However, I do get the following error everytime I run the program in my PyCharm and I do not know why:

```<code>line 22, in <module>
    planets = [i for i in jsonData['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
TypeError: string indices must be integers
</code>```

Here is some of the content of my JSON file that I have tried to read and go through:

```<code>{
  "collection": {
    "version": "1.0",
    "href": "http://images-api.nasa.gov/search?q=galaxy&page=1",
    "items": [
      {
        "href": "https://images-assets.nasa.gov/image/PIA04921/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Andromeda Galaxy",
            "nasa_id": "PIA04921",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX"
            ],
            "date_created": "2003-12-10T22:41:32Z",
            "description_508": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way.",
            "secondary_creator": "NASA/JPL/California Institute of Technology",
            "description": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way."
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04921/PIA04921~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },
      {
        "href": "https://images-assets.nasa.gov/image/PIA04634/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Galaxy NGC5474",
            "nasa_id": "PIA04634",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX",
              "NGC5474"
            ],
            "date_created": "2003-07-25T16:20:14Z",
            "description_508": "NASA Galaxy Evolution Explorer took this ultraviolet color image of the galaxy NGC5474 on June 7, 2003. NGC5474 is located 20 million light-years from Earth and is within a group of galaxies dominated by the Messier 101 galaxy.",
            "secondary_creator": "NASA/JPL/Caltech",
            "description": "NASA Galaxy Evolution Explorer took this ultraviolet color image of the galaxy NGC5474 on June 7, 2003. NGC5474 is located 20 million light-years from Earth and is within a group of galaxies dominated by the Messier 101 galaxy. Star formation in this galaxy shows some evidence of a disturbed spiral pattern, which may have been induced by tidal interactions with Messier 101.  http://photojournal.jpl.nasa.gov/catalog/PIA04634"
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04634/PIA04634~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },
</code>```

答:
A couple things -

You are loading your json into obj but then you are trying to parse your jsonData object.

If you use json.load() instead of json.loads() you can get a dict obj from your json file like so:

```<code> import json

 with open('galaxy.json', 'r') as jsonFile:
     obj = json.load(jsonFile)
 planets = [i for i in obj['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
 print(planets)
</code>```

Body:
I am trying to filter out specific results from the JSON file that is in one directory called "jsonfiles". This is my code:

import json

jsonFileN = open('jsonfiles\galaxy1.json', 'r', encoding="utf8")
jsonData = jsonFileN.read()

obj = json.loads(jsonData)
planets = [i for i in jsonData['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
print(planets)

However, I do get the following error everytime I run the program in my PyCharm and I do not know why:

line 22, in <module>
    planets = [i for i in jsonData['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
TypeError: string indices must be integers

Here is some of the content of my JSON file that I have tried to read and go through:

{
  "collection": {
    "version": "1.0",
    "href": "http://images-api.nasa.gov/search?q=galaxy&page=1",
    "items": [
      {
        "href": "https://images-assets.nasa.gov/image/PIA04921/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Andromeda Galaxy",
            "nasa_id": "PIA04921",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX"
            ],
            "date_created": "2003-12-10T22:41:32Z",
            "description_508": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way.",
            "secondary_creator": "NASA/JPL/California Institute of Technology",
            "description": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way."
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04921/PIA04921~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },
      {
        "href": "https://images-assets.nasa.gov/image/PIA04634/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Galaxy NGC5474",
            "nasa_id": "PIA04634",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX",
              "NGC5474"
            ],
            "date_created": "2003-07-25T16:20:14Z",
            "description_508": "NASA Galaxy Evolution Explorer took this ultraviolet color image of the galaxy NGC5474 on June 7, 2003. NGC5474 is located 20 million light-years from Earth and is within a group of galaxies dominated by the Messier 101 galaxy.",
            "secondary_creator": "NASA/JPL/Caltech",
            "description": "NASA Galaxy Evolution Explorer took this ultraviolet color image of the galaxy NGC5474 on June 7, 2003. NGC5474 is located 20 million light-years from Earth and is within a group of galaxies dominated by the Messier 101 galaxy. Star formation in this galaxy shows some evidence of a disturbed spiral pattern, which may have been induced by tidal interactions with Messier 101.  http://photojournal.jpl.nasa.gov/catalog/PIA04634"
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04634/PIA04634~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },

Body:
A couple things -

You are loading your json into obj but then you are trying to parse your jsonData object.

If you use json.load() instead of json.loads() you can get a dict obj from your json file like so:

 import json

 with open('galaxy.json', 'r') as jsonFile:
     obj = json.load(jsonFile)
 planets = [i for i in obj['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
 print(planets)


问:
Setting credentials for https git clone in AWS CodeBuild
I am running a CodeBuild on a project that has private requirements stored in CodeCommit.

I need to add a command in buildspec.yml that loads the https git credentials so git clone works when CodeBuild runs pip install.

The build fails with fatal: could not read Username for 'https://git-codecommit.us-west-2.amazonaws.com': No such device or address

答:
List item

So I was looking for a method to do this as well.  I figured out two ways to clone the repo without the use of assume roles.  What I am gathering from your post you want to clone the repo via the buildspec.yml

The first option as mentioned in an earlier post is to use the native function that is offered by Codebuild.  The caveat is that it's limited to the AWS account you are in (at least that's where my research has led me without using Codepipeline).  I am providing a sample for you to review as well.

I will also assume that most of you have worked with AWS Codecommit before and know how to set up users to connect to repos.  If you haven't please visit this page and get familiar with Codecommit configurations.  Links are listed below that can help you with this.

Using One AWS Account to clone Codecommit repository inside that AWS Account:

```<code>version: 0.2
env:

  git-credential-helper: yes

phases:
  install:
    commands:
      - echo "STARTING PYTHON INSTALLATION"
      - "curl -s -qL -o python.tgz https://www.python.org/ftp/python/${PY_VERSION}/Python-${PY_VERSION}.tgz"
      - "tar xf python.tgz -C /usr/bin/"
      - "python --version"
      - python -m pip install -U pip
      - pip install git-remote-codecommit

  pre_build:
    commands:
      - aws --version
      - git --version

      # Clone directories
      - echo CLONE DIRECTORIES
      - mkdir /usr/bin/repo
      - cd /usr/bin/repo

      #Leveraging git remote clone for codecommit
      - git clone codecommit://your-repo1-name new-repo1-name

  build:
    commands:
      - cd /usr/bin/new-repo1-name
      - do your git commands from here
</code>```

The key for this to work is to make sure certain settings are enabled.

git-credential-helper: yes

Python

pip install git-remote-codecommit

git clone codecommit://your-repo1-name. (The command must be exactly like this)

Again I reiterate I have only made this work within one AWS Account. To date, I am not able to make this work cross-account without leveraging other AWS Services.  To avoid leveraging other services I was able to put this together which creates an AWS Codecommit user that can use SSH.  For this example, I stored my ssh private key in the parameter store as well as the ssh key ID.  There are other methods I will share that can leverage S3 buckets which I will attach but the example below is to build the RSA and the config on the fly.

The SSH method to connect to a different AWS account Codecommit repository

```<code>version: 0.2
env:

  parameter-store:
    ssh_key: variable_ssh_key
    cc_user: variable_codecommit_user

  git-credential-helper: yes

phases:
  install:
    commands:
      - echo UPDATING SSH CLIENT
      - "which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )"
      - echo "STARTING PYTHON INSTALLATION"
      - "curl -s -qL -o python.tgz https://www.python.org/ftp/python/${PY_VERSION}/Python-${PY_VERSION}.tgz"
      - "tar xf python.tgz -C /usr/bin/"
      - "python --version"
      - python -m pip install -U pip

  pre_build:
    commands:
      - aws --version
      - git --version

      # Adds a private SSH key to allow us to clone or npm install Git repositories
      - eval $(ssh-agent -s)
      - mkdir -p ~/.ssh

      # Configure SSH Key
      #- ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa <<< y. #generate a new ssh key on demand
      - echo "$ssh_key" > ~/.ssh/id_rsa
      - cd ~/.ssh/
      - cat id_rsa
      - |
        echo "Multiline command"
        cat > ~/.ssh/config <<EOL
        Host host-unique-name
            Hostname git-codecommit.us-east-1.amazonaws.com
            User ${cc_user}
            IdentityFile ~/.ssh/id_rsa
        EOL
      - cat ~/.ssh/config

      # Configure SSH Permissions
      - chmod 700 ~/.ssh
      - chmod 600 ~/.ssh/config
      - chmod 600 ~/.ssh/id_rsa
      - ssh-keyscan -t rsa1,rsa,dsa git-codecommit.us-east-1.amazonaws.com >> ~/.ssh/known_hosts

      # Clone directories
      - echo CLONE DIRECTORIES
      - mkdir /usr/bin/repo
      - cd /usr/bin/repo

      #leveraging typical git clone
      - git clone ssh://host-unique-name/v1/repos/your-repo1-name

  build:
    commands:
      - cd /usr/bin/new-repo1-name
      - do your git commands from here
</code>```

As you can see this will create the ssh key and allow Codebuild to clone the repositories locally.  Please note I am adding a link for a similar example that uses S3 to download the RSA_ID.

Sample SSH clone S3 Bucket:
https://gist.github.com/gemmadlou/36deec54dea3defbdd8cbd6574e0261d

The key for this to work is to make sure certain settings are enabled.

Env Phase

git-credential-helper: yes

Install Phase

"which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )"

Python

pip install git-remote-codecommit

pre_build:

Create .ssh directory

add rsa private key

Create AWS Config file

configure permissions for ssh key and config file

Create known_host file (critically important)

Here are additional links to reference for items that helped me put this together:

Setup steps for HTTPS Connections to AWS Codecommit

AWS Cross account access to Codecommit repo with roles only

Fetch AWS Secret keys from Bash script

CWN connecting to codecommit repos using AWS Pipeline (codecommit, codebuild, codepipeline)

Codecommit setup ssh key

Body:
List item

So I was looking for a method to do this as well.  I figured out two ways to clone the repo without the use of assume roles.  What I am gathering from your post you want to clone the repo via the buildspec.yml

The first option as mentioned in an earlier post is to use the native function that is offered by Codebuild.  The caveat is that it's limited to the AWS account you are in (at least that's where my research has led me without using Codepipeline).  I am providing a sample for you to review as well.

I will also assume that most of you have worked with AWS Codecommit before and know how to set up users to connect to repos.  If you haven't please visit this page and get familiar with Codecommit configurations.  Links are listed below that can help you with this.

Using One AWS Account to clone Codecommit repository inside that AWS Account:

version: 0.2
env:

  git-credential-helper: yes

phases:
  install:
    commands:
      - echo "STARTING PYTHON INSTALLATION"
      - "curl -s -qL -o python.tgz https://www.python.org/ftp/python/${PY_VERSION}/Python-${PY_VERSION}.tgz"
      - "tar xf python.tgz -C /usr/bin/"
      - "python --version"
      - python -m pip install -U pip
      - pip install git-remote-codecommit

  pre_build:
    commands:
      - aws --version
      - git --version

      # Clone directories
      - echo CLONE DIRECTORIES
      - mkdir /usr/bin/repo
      - cd /usr/bin/repo

      #Leveraging git remote clone for codecommit
      - git clone codecommit://your-repo1-name new-repo1-name

  build:
    commands:
      - cd /usr/bin/new-repo1-name
      - do your git commands from here

The key for this to work is to make sure certain settings are enabled.

git-credential-helper: yes

Python

pip install git-remote-codecommit

git clone codecommit://your-repo1-name. (The command must be exactly like this)

Again I reiterate I have only made this work within one AWS Account. To date, I am not able to make this work cross-account without leveraging other AWS Services.  To avoid leveraging other services I was able to put this together which creates an AWS Codecommit user that can use SSH.  For this example, I stored my ssh private key in the parameter store as well as the ssh key ID.  There are other methods I will share that can leverage S3 buckets which I will attach but the example below is to build the RSA and the config on the fly.

The SSH method to connect to a different AWS account Codecommit repository

version: 0.2
env:

  parameter-store:
    ssh_key: variable_ssh_key
    cc_user: variable_codecommit_user

  git-credential-helper: yes

phases:
  install:
    commands:
      - echo UPDATING SSH CLIENT
      - "which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )"
      - echo "STARTING PYTHON INSTALLATION"
      - "curl -s -qL -o python.tgz https://www.python.org/ftp/python/${PY_VERSION}/Python-${PY_VERSION}.tgz"
      - "tar xf python.tgz -C /usr/bin/"
      - "python --version"
      - python -m pip install -U pip

  pre_build:
    commands:
      - aws --version
      - git --version

      # Adds a private SSH key to allow us to clone or npm install Git repositories
      - eval $(ssh-agent -s)
      - mkdir -p ~/.ssh

      # Configure SSH Key
      #- ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa <<< y. #generate a new ssh key on demand
      - echo "$ssh_key" > ~/.ssh/id_rsa
      - cd ~/.ssh/
      - cat id_rsa
      - |
        echo "Multiline command"
        cat > ~/.ssh/config <<EOL
        Host host-unique-name
            Hostname git-codecommit.us-east-1.amazonaws.com
            User ${cc_user}
            IdentityFile ~/.ssh/id_rsa
        EOL
      - cat ~/.ssh/config

      # Configure SSH Permissions
      - chmod 700 ~/.ssh
      - chmod 600 ~/.ssh/config
      - chmod 600 ~/.ssh/id_rsa
      - ssh-keyscan -t rsa1,rsa,dsa git-codecommit.us-east-1.amazonaws.com >> ~/.ssh/known_hosts

      # Clone directories
      - echo CLONE DIRECTORIES
      - mkdir /usr/bin/repo
      - cd /usr/bin/repo

      #leveraging typical git clone
      - git clone ssh://host-unique-name/v1/repos/your-repo1-name

  build:
    commands:
      - cd /usr/bin/new-repo1-name
      - do your git commands from here

As you can see this will create the ssh key and allow Codebuild to clone the repositories locally.  Please note I am adding a link for a similar example that uses S3 to download the RSA_ID.

Sample SSH clone S3 Bucket:
https://gist.github.com/gemmadlou/36deec54dea3defbdd8cbd6574e0261d

The key for this to work is to make sure certain settings are enabled.

Env Phase

git-credential-helper: yes

Install Phase

"which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )"

Python

pip install git-remote-codecommit

pre_build:

Create .ssh directory

add rsa private key

Create AWS Config file

configure permissions for ssh key and config file

Create known_host file (critically important)

Here are additional links to reference for items that helped me put this together:

Setup steps for HTTPS Connections to AWS Codecommit

AWS Cross account access to Codecommit repo with roles only

Fetch AWS Secret keys from Bash script

CWN connecting to codecommit repos using AWS Pipeline (codecommit, codebuild, codepipeline)

Codecommit setup ssh key


答:
So if you want return multiple records for a month, then you can use any one of the following formulas as shown in image below,

FORMULA ALTERNATIVE ONE IN CELL C2

```<code> =IFERROR(INDEX($A$2:$A$8,AGGREGATE(15,6,(ROW($A$2:$A$8)-ROW($A$2)+1)/($C$1=$B$2:$B$8),ROW(A1))),"")
</code>```

FORMULA ALTERNATIVE TWO IN CELL D2

```<code>=IFERROR(INDEX($A$2:$A$8,SMALL(IF($C$1=$B$2:$B$8,ROW($A$2:$A$8)-ROW($A$2)+1),ROW(A1))),"")
</code>```

This is an array formula and requires to press CTRL SHIFT ENTER

FORMULA ALTERNATIVE THREE IN CELL E2 --> This works both in EXCEL(ONLY EXCEL 2021 & O365) & GOOGLE SHEET

```<code>=FILTER($A$2:$A$8,$E$1=$B$2:$B$8)
</code>```

Title: Extract specific items from list

Body: I would like to extract only the names that are from January, so that they appear in the January column, I've tried =left() and =right() but they don't seem to work. Any info on how to do this will help!

Body:
So if you want return multiple records for a month, then you can use any one of the following formulas as shown in image below,

FORMULA ALTERNATIVE ONE IN CELL C2

 =IFERROR(INDEX($A$2:$A$8,AGGREGATE(15,6,(ROW($A$2:$A$8)-ROW($A$2)+1)/($C$1=$B$2:$B$8),ROW(A1))),"")

FORMULA ALTERNATIVE TWO IN CELL D2

=IFERROR(INDEX($A$2:$A$8,SMALL(IF($C$1=$B$2:$B$8,ROW($A$2:$A$8)-ROW($A$2)+1),ROW(A1))),"")

This is an array formula and requires to press CTRL SHIFT ENTER

FORMULA ALTERNATIVE THREE IN CELL E2 --> This works both in EXCEL(ONLY EXCEL 2021 & O365) & GOOGLE SHEET

=FILTER($A$2:$A$8,$E$1=$B$2:$B$8)


问:
How do I stop text from moving when I resize the div
I've been working on this project for awhile, an article that holds multiple items within it. However, when resizing the web page to a smaller size, the "player-summary" class is pushed into the section with the "name" class. This is despite the "name" class having a fixed width of 250px. I'm not quite sure how to fix this so resizing the web page won't bleed into it.

Additionally, when resizing, why does my text overflow out of my container?

html,body{
    width: 100%;
    height: 100%;
}
.center{
    width:90%;
    margin: auto;

}

.big-board_inner{
  width: 80%;
  margin: auto;
  background-color: white;

}

article{
    border: solid 1px;
    border-radius: 10px;
}
.top-info{
 display: flex;
 flex-direction: row;
 width:100%;
 height: 100%;
 font-size: 15px;
}

.name{
    display: block;
    width: 250px;
    margin: .3em;
    padding-right: 3em;
    font-size: 20px;
    padding-left:.5em;

}

.player-summary{

    margin: .5em;
    padding-right: 2em;
}

.age{
    margin: .5em;
    border-left: solid 1px;
    padding-left: 1em;
}
.main-info{
    width: 50%;
    display: flex;
    flex-direction: column;

}
.profile img{
    width: 250px;
    height: auto;
    border-radius: 15px;
    padding: .5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div class = "center">
        <div class = "big-board_inner">
            <article>
                <div class="top-info">
                  <div class = "name">Dustin Harris <br> OF - Tex  </div>
                  <div class="player-summary">Summary: <br>Dustin Harris is as pure as hitter you can find, with a LF fit</div>
                  <div class="age">Highest Level: A+ <br> Age: 21</div>
                  <div class="age">Height: 6'1" <br> Weight: 215 lbs</div>
                 </div>
                 <div class="main-info">
                    <div class="profile">  <img src="images/Dustin Harris.jfif"></div>
                 </div>
            </article>
        </div>
       </div>
    </body>
    </html></code>```

答:
Use min-width. It would make your element have a minimum-width to maintain no matter the screen size if you set a static value, like in this case, 250px.

As for why your elements overflow out of your container, it's because you don't have any wrapping on your container. You can use flexbox's flex-wrap property to wrap your elements to fit the available space. See the snippet below:

html,
body {
  width: 100%;
  height: 100%;
}

.center {
  width: 90%;
  margin: auto;
}

.big-board_inner {
  width: 80%;
  margin: auto;
  background-color: white;
}

article {
  border: solid 1px;
  border-radius: 10px;
}

.top-info {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  width: 100%;
  height: 100%;
  font-size: 15px;
}

.name {
  display: block;
  min-width: 250px;
  margin: .3em;
  padding-right: 3em;
  font-size: 20px;
  padding-left: .5em;
}

.player-summary {
  margin: .5em;
  padding-right: 2em;
}

.age {
  margin: .5em;
  border-left: solid 1px;
  padding-left: 1em;
}

.main-info {
  width: 50%;
  display: flex;
  flex-direction: column;
}

.profile img {
  width: 250px;
  height: auto;
  border-radius: 15px;
  padding: .5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="center">
    <div class="big-board_inner">
      <article>
        <div class="top-info">
          <div class="name">Dustin Harris <br> OF - Tex </div>
          <div class="player-summary">Summary: <br>Dustin Harris is as pure as hitter you can find, with a LF fit</div>
          <div class="age">Highest Level: A+ <br> Age: 21</div>
          <div class="age">Height: 6'1" <br> Weight: 215 lbs</div>
        </div>
        <div class="main-info">
          <div class="profile"> <img src="images/Dustin Harris.jfif"></div>
        </div>
      </article>
    </div>
  </div>
</body>

</html></code>```

More on flex-wrap here.

If what you're looking for is text-wrapping, then refer here instead.

Body:
I've been working on this project for awhile, an article that holds multiple items within it. However, when resizing the web page to a smaller size, the "player-summary" class is pushed into the section with the "name" class. This is despite the "name" class having a fixed width of 250px. I'm not quite sure how to fix this so resizing the web page won't bleed into it.

Additionally, when resizing, why does my text overflow out of my container?

html,body{
    width: 100%;
    height: 100%;
}
.center{
    width:90%;
    margin: auto;

}

.big-board_inner{
  width: 80%;
  margin: auto;
  background-color: white;

}

article{
    border: solid 1px;
    border-radius: 10px;
}
.top-info{
 display: flex;
 flex-direction: row;
 width:100%;
 height: 100%;
 font-size: 15px;
}

.name{
    display: block;
    width: 250px;
    margin: .3em;
    padding-right: 3em;
    font-size: 20px;
    padding-left:.5em;

}

.player-summary{

    margin: .5em;
    padding-right: 2em;
}

.age{
    margin: .5em;
    border-left: solid 1px;
    padding-left: 1em;
}
.main-info{
    width: 50%;
    display: flex;
    flex-direction: column;

}
.profile img{
    width: 250px;
    height: auto;
    border-radius: 15px;
    padding: .5em;
}

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="styles.css">

Dustin Harris
 OF - Tex

Summary:
Dustin Harris is as pure as hitter you can find, with a LF fit

Highest Level: A+
 Age: 21

Height: 6'1"
 Weight: 215 lbs

Body:
Use min-width. It would make your element have a minimum-width to maintain no matter the screen size if you set a static value, like in this case, 250px.

As for why your elements overflow out of your container, it's because you don't have any wrapping on your container. You can use flexbox's flex-wrap property to wrap your elements to fit the available space. See the snippet below:

html,
body {
  width: 100%;
  height: 100%;
}

.center {
  width: 90%;
  margin: auto;
}

.big-board_inner {
  width: 80%;
  margin: auto;
  background-color: white;
}

article {
  border: solid 1px;
  border-radius: 10px;
}

.top-info {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  width: 100%;
  height: 100%;
  font-size: 15px;
}

.name {
  display: block;
  min-width: 250px;
  margin: .3em;
  padding-right: 3em;
  font-size: 20px;
  padding-left: .5em;
}

.player-summary {
  margin: .5em;
  padding-right: 2em;
}

.age {
  margin: .5em;
  border-left: solid 1px;
  padding-left: 1em;
}

.main-info {
  width: 50%;
  display: flex;
  flex-direction: column;
}

.profile img {
  width: 250px;
  height: auto;
  border-radius: 15px;
  padding: .5em;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="center">
    <div class="big-board_inner">
      <article>
        <div class="top-info">
          <div class="name">Dustin Harris <br> OF - Tex </div>
          <div class="player-summary">Summary: <br>Dustin Harris is as pure as hitter you can find, with a LF fit</div>
          <div class="age">Highest Level: A+ <br> Age: 21</div>
          <div class="age">Height: 6'1" <br> Weight: 215 lbs</div>
        </div>
        <div class="main-info">
          <div class="profile"> <img src="images/Dustin Harris.jfif"></div>
        </div>
      </article>
    </div>
  </div>
</body>

</html>

More on flex-wrap here.

If what you're looking for is text-wrapping, then refer here instead.


问:
Preparing Android API for distribution
I'm developing an API for Android and it works great but I'm not sure how to package/distribute it. I've gotten the "meat" of the API into a jarfile - that's all the classes and an XML file in res/values/attrs.xml (I'm not sure if there's a way users can reference to that without having to copy my attrs.xml into their /values folder, but that's another question).

While trying my API in a test case, I've added my .jar to the build path and I can import a class successfully if I want to, but I don't want to :P My API allows users to implement a custom View into their own XML files, so nothing is instantiated in code.

The question: How can users reference to a custom View in my API? For example, if my View is called FooView and is in package com.myfoo, the following XML fails to load:

```<code><com.myfoo.FooView
android:layout_width="fill_parent"
android:layout_height="100dp"
/>
</code>```

答:
You might want to look into Android Library Projects. These are basically normal android projects, which can be referenced as a library. This means you can define classes, layouts and resources as you would normally, and just use them in your main app (in this case in your clients app) as if they were defined in the same project. This allows you to reference views in XML like you tried above via <packagename.classname ... />.

There is one huge downside though (which is especially important when you create custom views):

styleable-resources simply don't work. This is a bug.
According to this question it's going to be fixed in the next devtool release though.

With that in mind I recommend setting up a small test project with a test library project and see if everything that you need works correctly.

Title: Preparing Android API for distribution

Body:
I'm developing an API for Android and it works great but I'm not sure how to package/distribute it. I've gotten the "meat" of the API into a jarfile - that's all the classes and an XML file in res/values/attrs.xml (I'm not sure if there's a way users can reference to that without having to copy my attrs.xml into their /values folder, but that's another question).

While trying my API in a test case, I've added my .jar to the build path and I can import a class successfully if I want to, but I don't want to :P My API allows users to implement a custom View into their own XML files, so nothing is instantiated in code.

The question: How can users reference to a custom View in my API? For example, if my View is called FooView and is in package com.myfoo, the following XML fails to load:

<com.myfoo.FooView
android:layout_width="fill_parent"
android:layout_height="100dp"
/>


问:
On Ubuntu an executable created with Pyinstaller doesn't run
I am on ubuntu 16.04. I am trying to make an executable from my python script (fez.py) using pyinstaller using pyinstaller --onefile fez.py.

The executable gets built without any error. I get the two folders dist and build with the .exe file in dist. I get the fez.spec file too.
But when I try to run the executable nothing seems to happen.

My question is:

Is there a problem with the pyinstaller process to create the executable that doesn't get displayed as an error OR is there a problem with my ubuntu that it can't run the executable? Whichever is the reason how to run my executable?

NB: I am well versed with the fact that pyinstaller is OS specific i.e. for an executable to work on ubuntu it should be prepared on ubuntu itself and that is exactly what I have done. I have used the pyinstaller command on ubuntu. This also rules out the fact that I should install wine or something else of that sort as wine is required to execute windows executables on ubuntu. (Files with .exe extension) The executable I am making using pyinstaller on ubuntu specifically builds executables for ubuntu. (In properties they show application\x-executable)

EDIT: To run the executable I had to first change the permission to allow as executable. Then I had to run from the terminal. But is there no way to run it using double clicks.

答:
You have to change chmod of the app. (For example chmod 777 custom_app_filename)

I believe it will work then.
Chmod command changes the permissions of one file
for example
1chmod a+x filename` makes the filename file to be executable

Reference lik: https://linuxize.com/post/chmod-command-in-linux/


问:
The named parameter initialData is required but there is no corresponding argument
In a Flutter provider I have this code which used to work but now gives this error at StreamProvider<User>.

The named parameter initialData is required but there is no corresponding argument

The User model doesn't have an initialData variable. How can I fix this?

```<code>List<SingleChildStatelessWidget> providers = [
  ...independentServices,
  ...dependentServices,
  ...uiConsumableProviders
];

List<SingleChildStatelessWidget> independentServices = [

  Provider(create: (_) => AppLanguage()),

  Provider(create: (_) => Api()),

];

List<SingleChildStatelessWidget> dependentServices = [

  ProxyProvider<Api, AuthenticationService>(

    update: (context, api, authenticationService) => AuthenticationService(api: api),

  ),
];

List<SingleChildStatelessWidget> uiConsumableProviders = [

  StreamProvider<User>(

    create: (context) => Provider.of<AuthenticationService>(context, listen: false).user,

    lazy: false

  ),

];
</code>```

答:
StreamProvider has an initialData named argument. If you want further you can check https://pub.dev/documentation/provider/latest/provider/StreamProvider-class.html

So, you should pass initialData named argument like below lines;

List<SingleChildStatelessWidget> uiConsumableProviders = [

  StreamProvider<User>(
    initialData: User(), // this line added !
    create: (context) => Provider.of<AuthenticationService>(context, listen: false).user,
    lazy: false
  ),

];
```

Body:
In a Flutter provider I have this code which used to work but now gives this error at StreamProvider<User>.

The named parameter initialData is required but there is no corresponding argument

The User model doesn't have an initialData variable. How can I fix this?

List<SingleChildStatelessWidget> providers = [
  ...independentServices,
  ...dependentServices,
  ...uiConsumableProviders
];

List<SingleChildStatelessWidget> independentServices = [

  Provider(create: (_) => AppLanguage()),

  Provider(create: (_) => Api()),

];

List<SingleChildStatelessWidget> dependentServices = [

  ProxyProvider<Api, AuthenticationService>(

    update: (context, api, authenticationService) => AuthenticationService(api: api),

  ),
];

List<SingleChildStatelessWidget> uiConsumableProviders = [

  StreamProvider<User>(

    create: (context) => Provider.of<AuthenticationService>(context, listen: false).user,

    lazy: false

  ),

];


问:
How do you determine the version of OCaml or Jane Street Core library at runtime
I am migrating to a recent version of OCaml (and Jane Street's Core modules), but would like my code to continue to compile with older versions. To do so, I would like to create a module with portable functions that map to either the old or new interfaces depending on the version. Querying both the version of OCaml and the version of Jane Street Core would work.

How can we look up the version of the compiler or of Jane Street Core at runtime? I know that I could pass the output of ocamlopt --version via my build system, but ideally I should not have to invoke my programs in a special way.

答:
You can retrieve the OCaml version number with Sys.ocaml_version.

utop # Sys.ocaml_version;;
- : string = "4.13.1"
```

I'm afraid after browsing the Jane Street Base and Core API docs, I don't see a way to query the version number at runtime.

Body:
You can retrieve the OCaml version number with Sys.ocaml_version.

utop # Sys.ocaml_version;;
- : string = "4.13.1"

I'm afraid after browsing the Jane Street Base and Core API docs, I don't see a way to query the version number at runtime.


问:
warning: '__builtin_snprintf' output may be truncated before the last format character [-Wformat-truncation=]
```<code>warning: ‘__builtin_snprintf’ output may be truncated before the last format character [-Wformat-truncation=]
  "%s", evspan->text);
     ^

len = strlen(evspan->text);
evspan->ent->content = malloc(len+1);

snprintf(evspan->ent->content, len,
"%s", evspan->text);
</code>```

I saw this warning on gcc 8. How do I prevent this without using -Wformat-truncation option?

答:
The second argument to snprintf is the length of the buffer, not the maximum string length.

The call should be:

```<code>snprintf(evspan->ent->content, len + 1, "%s", evspan->text);
</code>```

This matches the length passed to malloc.

The comments given on snprintf not being the best choice do apply, if your full code is as simple as what's shown here.

Body:
warning: ‘__builtin_snprintf’ output may be truncated before the last format character [-Wformat-truncation=]
  "%s", evspan->text);
     ^

len = strlen(evspan->text);
evspan->ent->content = malloc(len+1);

snprintf(evspan->ent->content, len,
"%s", evspan->text);

I saw this warning on gcc 8. How do I prevent this without using -Wformat-truncation option?

Body:
The second argument to snprintf is the length of the buffer, not the maximum string length.

The call should be:

snprintf(evspan->ent->content, len + 1, "%s", evspan->text);

This matches the length passed to malloc.

The comments given on snprintf not being the best choice do apply, if your full code is as simple as what's shown here.


问:
SQL join query using rows which only have date of today to sort
I'm sure this is really simple... just tired now.

I have a query

```<code>SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT JOIN votes
ON posts.id = votes.post_id
GROUP BY posts.id
ORDER BY votes DESC
</code>```

I need to fetch all posts on the left table whilst when counting votes on the votes table using the votes which happened today or between 1 hour and another hour of the same day. Does this make enough sense?

I have tried adding

```<code>WHERE DATE(votes.datetime) = DATE(NOW())
</code>```

But no luck, it just shows the rows which have votes which happened today and no other posts rows which have either no votes at all or votes that happened today.

I am using data type datetime for the datetime column

Any ideas how I can do this easily?

Thanks in advance!

-Stefan

答: Use a subquery in your LEFT JOIN votes expression, specifying the condition you seek as a WHERE clause within this. Then later, if necessary, optimise for performance by transforming away the subquery.</p>

Body:
I'm sure this is really simple... just tired now.

I have a query

SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT JOIN votes
ON posts.id = votes.post_id
GROUP BY posts.id
ORDER BY votes DESC

I need to fetch all posts on the left table whilst when counting votes on the votes table using the votes which happened today or between 1 hour and another hour of the same day. Does this make enough sense?

I have tried adding

WHERE DATE(votes.datetime) = DATE(NOW())

But no luck, it just shows the rows which have votes which happened today and no other posts rows which have either no votes at all or votes that happened today.

I am using data type datetime for the datetime column

Any ideas how I can do this easily?

Thanks in advance!

-Stefan


问:
CodePipeline how to deploy multiple CFN stacks
tldr; I can deploy a single CFN stack as part of my pipeline, but how do I deploy multiple dynamic stacks?

An even better tldr; How would you do this? forEach BuildStage.artifact invoke CloudFormation.build

I am using CodePipeline in a pretty conventional way. The goal is to source control my CloudFormation templates, push them through the pipeline when a template changes, and then automatically deploy the stack.

Source Stage (CodeCommit commit my CFN yaml templates)

Build Stage (CodeBuild finds the new files from the commit, and pushes them to S3)

Deploy Stage (CloudFormation deploys my templates as CFN stacks)

Almost everything is working great. I commit my template changes to CodeCommit, the build stage runs my codeBuild gatekeeper, which gathers only the files that have changed, and uploads them to S3. So far so good.

The challenge is that sometimes I have one template change, and sometimes I have multiple(n). I can detect changed files and get them up to S3 no problem in my build stage. If I commit a change for one template, everything works fine. I can create an exported variable with my template location on S3, pass that to my deploy stage, and have the CloudFormation deploy action use that file as the template source. But how would I handle this if I have 2 templates?

I can't just create endless exported variables in my build stage.

And if I can, AFAIK there is no way to iterate over each entry for the deploy stage.

My thought is I would need to do one of the following:

Inside of my current buildspec (after I upload the files to S3), use the AWS CLI to invoke a CFN stack build. I can add this as part of a loop, so it iterates on each file to be uploaded.  OR

After my build stage, use a Lambda to perform the same as #1. Loop through each file, and then use the CLI or SDK to invoke a CFN stack build.

Both of these options seem to defeat the purpose of the deploy stage altogether, which seems clunky to me.

Are there other options I am missing? What would you do?

答:
Just want to answer my own question, in case anyone else is trying to figure out how to do this.

I ended up going with option 1...just doing a cli CFN deployment directly from within CodeBuild. I was really trying to shoehorn the idea of using a CodePipeline deploy stage, but this works just fine.

If anyone else ends up coming along with a better solution, I am all ears.


问:
What should be the block value when I first create a database in TDengine
I know that block is determined by the system configuration parameter cache; The number of memory blocks in each vnode is determined by the configuration parameter blocks. But I still don't know the relationship between the size of the block and my data size?</p>

答: You can just use the default setting, which doesn't matter.</p>


问:
Snowflake: Configure Microsoft Azure AD for External OAuth - admin consent
I am using this guide to configure Microsoft Azure AD for external OAuth in Snowflake.
I'm pretty sure that I followed all the steps because tried that meticulously on three Azure subscriptions and got the same result.

Every time I got stuck at the testing procedure section where I'm supposed to send a request to Azure AD to get an access token:

```<code>curl -X POST -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
  --data-urlencode "client_id=<OAUTH_CLIENT_ID>" \
  --data-urlencode "client_secret=<OAUTH_CLIENT_SECRET>" \
  --data-urlencode "username=<AZURE_AD_USER>" \
  --data-urlencode "password=<AZURE_AD_USER_PASSWORD>" \
  --data-urlencode "grant_type=password" \
  --data-urlencode "scope=session:role:analyst" \
  '<AZURE_AD_OAUTH_TOKEN_ENDPOINT>'
</code>```

I am a subscription owner and definitely granted admin access to the session:role:analyst scope:

However, instead of the access token, I get the following response:

```<code>{
    "error": "invalid_grant",
    "error_description": "AADSTS65001: The user or administrator has not consented to use the application with ID '...' named 'Snowflake OAuth Client'. Send an interactive authorization request for this user and resource.\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        65001
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "...",
    "suberror": "consent_required"
}
</code>```

Tried to grant the consent by reaching https://login.microsoftonline.com/{{tenant_id}}/adminconsent?client_id={{client_id}} and after granting the consent, got an error: AADSTS500113: No reply address is registered for the application.

Found this and added the return URL http://localhost/ (without a clear understanding of why). Granted the consent again and was redirected to http://localhost/?admin_consent=True&tenant={{tenant_id}}# which, I suppose, is fine.

But I still get AADSTS65001: The user or administrator has not consented to use the application.

Reached to Microsoft documentation and figured out that using grant_type=password is not recommended - makes sense.

Tried grant_type=client credentials:

```<code>curl --location --request GET 'https://login.microsoftonline.com/{{tenant_id}}/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id={{client_id}}' \
--data-urlencode 'scope=https://graph.microsoft.com/.default' \
--data-urlencode 'client_secret={{client_secret}}'
</code>```

Got the access token, but attempts to connect to Snowflake with a connection string like:

```<code>connection.ConnectionString = $"account={account};host={host};authenticator=oauth;user={oauthUser};token={token};";
</code>```

Throw Snowflake.Data.Client.SnowflakeDbException: 'Invalid OAuth access token..

I suspect this is because scope=https://graph.microsoft.com/.default, but replacing it with session:scope:analyst brings this:

```<code>{
    "error": "invalid_scope",
    "error_description": "AADSTS1002012: The provided value for scope session:scope:analyst is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        1002012
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "..."
}
</code>```

Since I already deviated from the official Snowflake guide, I'm asking the community for help with this issue. Thank you in in advance!

答:
If the set up is still configured for "password" type grant credentials then the issue there is with the scope which should be set up on AAD and passed as follows:

```<code>**session:role-<name>**
</code>```

Note, that the hyphen between role and name and it's not a colon.

In your setup, it seems to be set up and passed as:

```<code>session:role:<name>
</code>```

I think, it would be much more easier to fix this issue by checking the steps done on your environment with the details here:
https://community.snowflake.com/s/article/External-oAuth-Token-Generation-using-Azure-AD

Body:
I am using this guide to configure Microsoft Azure AD for external OAuth in Snowflake.
I'm pretty sure that I followed all the steps because tried that meticulously on three Azure subscriptions and got the same result.

Every time I got stuck at the testing procedure section where I'm supposed to send a request to Azure AD to get an access token:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
  --data-urlencode "client_id=<OAUTH_CLIENT_ID>" \
  --data-urlencode "client_secret=<OAUTH_CLIENT_SECRET>" \
  --data-urlencode "username=<AZURE_AD_USER>" \
  --data-urlencode "password=<AZURE_AD_USER_PASSWORD>" \
  --data-urlencode "grant_type=password" \
  --data-urlencode "scope=session:role:analyst" \
  '<AZURE_AD_OAUTH_TOKEN_ENDPOINT>'

I am a subscription owner and definitely granted admin access to the session:role:analyst scope:

However, instead of the access token, I get the following response:

{
    "error": "invalid_grant",
    "error_description": "AADSTS65001: The user or administrator has not consented to use the application with ID '...' named 'Snowflake OAuth Client'. Send an interactive authorization request for this user and resource.\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        65001
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "...",
    "suberror": "consent_required"
}

Tried to grant the consent by reaching https://login.microsoftonline.com/{{tenant_id}}/adminconsent?client_id={{client_id}} and after granting the consent, got an error: AADSTS500113: No reply address is registered for the application.

Found this and added the return URL http://localhost/ (without a clear understanding of why). Granted the consent again and was redirected to http://localhost/?admin_consent=True&tenant={{tenant_id}}# which, I suppose, is fine.

But I still get AADSTS65001: The user or administrator has not consented to use the application.

Reached to Microsoft documentation and figured out that using grant_type=password is not recommended - makes sense.

Tried grant_type=client credentials:

curl --location --request GET 'https://login.microsoftonline.com/{{tenant_id}}/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id={{client_id}}' \
--data-urlencode 'scope=https://graph.microsoft.com/.default' \
--data-urlencode 'client_secret={{client_secret}}'

Got the access token, but attempts to connect to Snowflake with a connection string like:

connection.ConnectionString = $"account={account};host={host};authenticator=oauth;user={oauthUser};token={token};";

Throw Snowflake.Data.Client.SnowflakeDbException: 'Invalid OAuth access token..

I suspect this is because scope=https://graph.microsoft.com/.default, but replacing it with session:scope:analyst brings this:

{
    "error": "invalid_scope",
    "error_description": "AADSTS1002012: The provided value for scope session:scope:analyst is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        1002012
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "..."
}

Since I already deviated from the official Snowflake guide, I'm asking the community for help with this issue. Thank you in in advance!

Body:
If the set up is still configured for "password" type grant credentials then the issue there is with the scope which should be set up on AAD and passed as follows:

**session:role-<name>**

Note, that the hyphen between role and name and it's not a colon.

In your setup, it seems to be set up and passed as:

session:role:<name>

I think, it would be much more easier to fix this issue by checking the steps done on your environment with the details here:
https://community.snowflake.com/s/article/External-oAuth-Token-Generation-using-Azure-AD


问:
Removing the first and only the first '-' in the values of a string column
```<code>               1          2
0    ADRC-111-01    ADRC111
1  ADRC-11955-01  ADRC11955
2  ADRC-18133-01  ADRC18133
3    SWAN0023-03   SWAN0023
</code>```

In Column 1, I wish to get rid of the first - sign, regardless of how many are in the the cell. There are one or two - in each entry.

Desired output:

```<code>              1          2
0    ADRC111-01    ADRC111
1  ADRC11955-01  ADRC11955
2  ADRC18133-01  ADRC18133
3    SWAN002303   SWAN0023
</code>```

Body:
               1          2
0    ADRC-111-01    ADRC111
1  ADRC-11955-01  ADRC11955
2  ADRC-18133-01  ADRC18133
3    SWAN0023-03   SWAN0023

In Column 1, I wish to get rid of the first - sign, regardless of how many are in the the cell. There are one or two - in each entry.

Desired output:

              1          2
0    ADRC111-01    ADRC111
1  ADRC11955-01  ADRC11955
2  ADRC18133-01  ADRC18133
3    SWAN002303   SWAN0023

Body:
Use .str.replace with n=1:

df['1'] = df['1'].str.replace('-', '', n=1)

Output:

>>> df
              1          2
0    ADRC111-01    ADRC111
1  ADRC11955-01  ADRC11955
2  ADRC18133-01  ADRC18133
3    SWAN002303   SWAN0023


问:
How to use constants defined in javascript in an erb file as an argument in rails api method
I'm trying to play around with my code and I have hit a

I have a script tag in an erb file. I get the browser timezone and store it in a constant. I want to use the value of the constant in a rails API method as an argument but I get the error

undefined local variable or method `browser_time_zone' for #

```<code><script>
// this returns Eastern Time (US & Canada)

const browser_time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;

const timezone = <%= ActiveSupport::TimeZone::MAPPING.key(browser_time_zone) %>

</script>
</code>```

How can I use the value of browser_time_zone as an argument to the TimeZone Mapping method? Any help will be appreciated

答:
I don't think you can do what you want, because the execution of the Javascript and Ruby happen at different times (Ruby first when the page is being rendered/created, then javascript when the browser loads the HTML). Instead, you could try something like this:

```<code><script>
// this returns Eastern Time (US & Canada)

// https://stackoverflow.com/a/28191966/2543424
function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

const time_zone_mapping = <%= ActiveSupport::TimeZone::MAPPING.to_json.html_safe %>;

const browser_time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;

const timezone = getKeyByValue(time_zone_mapping, browser_time_zone);

</script>
</code>```

Here we are dumping the contents of ActiveSupport::TimeZone::MAPPING to a new javascript variable in the form of a JSON object, and then accessing it in much the same way as what you were trying to do, but all via Javascript.

Note, the ActiveSupport::TimeZone::MAPPING.to_json.html_safe syntax may not be 100% correct, but that's the general idea

Body:
I'm trying to play around with my code and I have hit a

I have a script tag in an erb file. I get the browser timezone and store it in a constant. I want to use the value of the constant in a rails API method as an argument but I get the error

undefined local variable or method `browser_time_zone' for #

How can I use the value of browser_time_zone as an argument to the TimeZone Mapping method? Any help will be appreciated

Body:
I don't think you can do what you want, because the execution of the Javascript and Ruby happen at different times (Ruby first when the page is being rendered/created, then javascript when the browser loads the HTML). Instead, you could try something like this:

<script>
// this returns Eastern Time (US & Canada)

// https://stackoverflow.com/a/28191966/2543424
function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

const time_zone_mapping = <%= ActiveSupport::TimeZone::MAPPING.to_json.html_safe %>;

const browser_time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;

const timezone = getKeyByValue(time_zone_mapping, browser_time_zone);

</script>

Here we are dumping the contents of ActiveSupport::TimeZone::MAPPING to a new javascript variable in the form of a JSON object, and then accessing it in much the same way as what you were trying to do, but all via Javascript.

Note, the ActiveSupport::TimeZone::MAPPING.to_json.html_safe syntax may not be 100% correct, but that's the general idea


问:
Python JSON parser and filterer getting a KeyError every time
I am writing a program that is supposed to filter specific results of the JSON file content in the URL. I wanted to filter out any description, keywords, and title with the name "Andromeda". I have written the program and it does run on some pages, whereas on other pages, I keep getting errors and I do not know why. Here is my code:

```<code>from urllib.request import urlopen
import json

#Page = (number change)
url = "https://images-api.nasa.gov/search?q=galaxy&page=10"

response = urlopen(url)
data_json = json.loads(response.read())
#Filtering out the results that relate to the word
planets = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
planets1 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['keywords']]
planets2 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['description']]
print(planets)
print("--------------------------------------------")
print(planets1)
print("--------------------------------------------")
print(planets2)
</code>```

Here is my error:

```<code>Traceback (most recent call last):
  File "C:Filter&Search.py", line 11, in <module>
    planets1 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['keywords']]
  File "C:Filter&Search.py", line 11, in <listcomp>
    planets1 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['keywords']]
KeyError: 'keywords'
</code>```

Here is some of the content of my JSON file that I have tried to read and go through:

```<code>{
  "collection": {
    "version": "1.0",
    "href": "http://images-api.nasa.gov/search?q=galaxy&page=1",
    "items": [
      {
        "href": "https://images-assets.nasa.gov/image/PIA04921/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Andromeda Galaxy",
            "nasa_id": "PIA04921",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX"
            ],
            "date_created": "2003-12-10T22:41:32Z",
            "description_508": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way.",
            "secondary_creator": "NASA/JPL/California Institute of Technology",
            "description": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way."
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04921/PIA04921~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },
      {
        "href": "https://images-assets.nasa.gov/image/PIA04634/collection.json",
        "data": [
          {
</code>```

答:
This will skip over those posts that don't have 'keywords' in the data dictionary

```<code>from urllib.request import urlopen
import json

#Page = (number change)
url = "https://images-api.nasa.gov/search?q=galaxy&page=10"

response = urlopen(url)
data_json = json.loads(response.read())
#Filtering out the results that relate to the word
planets = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
planets1 = [i for i in data_json['collection']['items'] if 'keywords' in i['data'][0] and 'Andromeda' in i['data'][0]['keywords']]
planets2 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['description']]
print(planets)
print("--------------------------------------------")
print(planets1)
print("--------------------------------------------")
print(planets2)
</code>```

You can use this to print out if the 'keywords' were not found in the dictionary

```<code>planets1 = []
for i in data_json['collection']['items']:
    if 'keywords' in i['data'][0] and 'Andromeda' in i['data'][0]['keywords']:
        planets1.append(i)
    else:
        print('keywords not found')
</code>```

if you want list comprehension you could do this:

```<code>planets1 = [i if 'keywords' in i['data'][0] and 'Andromeda' in i['data'][0]['keywords'] else print('keywords not found') for i in data_json['collection']['items']] # will generate None items (those items when it just printed out instead of when you wanted to add it with Andromeda)
planets1 = list(filter(lambda x: x, planets1)) # removes None from list
</code>```

Body:
I am writing a program that is supposed to filter specific results of the JSON file content in the URL. I wanted to filter out any description, keywords, and title with the name "Andromeda". I have written the program and it does run on some pages, whereas on other pages, I keep getting errors and I do not know why. Here is my code:

from urllib.request import urlopen
import json

#Page = (number change)
url = "https://images-api.nasa.gov/search?q=galaxy&page=10"

response = urlopen(url)
data_json = json.loads(response.read())
#Filtering out the results that relate to the word
planets = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
planets1 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['keywords']]
planets2 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['description']]
print(planets)
print("--------------------------------------------")
print(planets1)
print("--------------------------------------------")
print(planets2)

Here is my error:

Traceback (most recent call last):
  File "C:Filter&Search.py", line 11, in <module>
    planets1 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['keywords']]
  File "C:Filter&Search.py", line 11, in <listcomp>
    planets1 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['keywords']]
KeyError: 'keywords'

Here is some of the content of my JSON file that I have tried to read and go through:

{
  "collection": {
    "version": "1.0",
    "href": "http://images-api.nasa.gov/search?q=galaxy&page=1",
    "items": [
      {
        "href": "https://images-assets.nasa.gov/image/PIA04921/collection.json",
        "data": [
          {
            "center": "JPL",
            "title": "Andromeda Galaxy",
            "nasa_id": "PIA04921",
            "media_type": "image",
            "keywords": [
              "Galaxy Evolution Explorer GALEX"
            ],
            "date_created": "2003-12-10T22:41:32Z",
            "description_508": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way.",
            "secondary_creator": "NASA/JPL/California Institute of Technology",
            "description": "This image is from NASA Galaxy Evolution Explorer is an observation of the large galaxy in Andromeda, Messier 31. The Andromeda galaxy is the most massive in the local group of galaxies that includes our Milky Way."
          }
        ],
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/PIA04921/PIA04921~thumb.jpg",
            "rel": "preview",
            "render": "image"
          }
        ]
      },
      {
        "href": "https://images-assets.nasa.gov/image/PIA04634/collection.json",
        "data": [
          {

Body:
This will skip over those posts that don't have 'keywords' in the data dictionary

from urllib.request import urlopen
import json

#Page = (number change)
url = "https://images-api.nasa.gov/search?q=galaxy&page=10"

response = urlopen(url)
data_json = json.loads(response.read())
#Filtering out the results that relate to the word
planets = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['title']]
planets1 = [i for i in data_json['collection']['items'] if 'keywords' in i['data'][0] and 'Andromeda' in i['data'][0]['keywords']]
planets2 = [i for i in data_json['collection']['items'] if 'Andromeda' in i['data'][0]['description']]
print(planets)
print("--------------------------------------------")
print(planets1)
print("--------------------------------------------")
print(planets2)

You can use this to print out if the 'keywords' were not found in the dictionary

planets1 = []
for i in data_json['collection']['items']:
    if 'keywords' in i['data'][0] and 'Andromeda' in i['data'][0]['keywords']:
        planets1.append(i)
    else:
        print('keywords not found')

if you want list comprehension you could do this:

planets1 = [i if 'keywords' in i['data'][0] and 'Andromeda' in i['data'][0]['keywords'] else print('keywords not found') for i in data_json['collection']['items']] # will generate None items (those items when it just printed out instead of when you wanted to add it with Andromeda)
planets1 = list(filter(lambda x: x, planets1)) # removes None from list


问:
why is the sum = add() not working when is already defined?
I am new to python and my professor keeps posting this problem for the class to answer:

```<code> x = 2
 y = 3
 sum = add( x, y)
 print(sum)
 def add (num1 = 0, num2 = 0):
 total = num1 + num2
 return total
</code>```

edit:

I figure it out by placing the sum = add( x, y) after the add() was defined. here is the correct code?

```<code>x = 2
y = 3

def add (x, y):
    total = x + y
    return total

sum = add( x, y)
print(sum)
</code>```

答:
As you correctly identified, this code is calling the function add before it's defined.
Furthermore, the astrix in front of the first variable is out of place - that should make a list out of otherwise unassigned variables.
The double astrix on the return line is also out of place.

The question of "What is the code trying to do?" Is poorly phrased, but I'd wager that the answer your professor is looking for is "The code is trying to print the sum of the two given variables to the console."

Body:
I am new to python and my professor keeps posting this problem for the class to answer:

 x = 2
 y = 3
 sum = add( x, y)
 print(sum)
 def add (num1 = 0, num2 = 0):
 total = num1 + num2
 return total

edit:

I figure it out by placing the sum = add( x, y) after the add() was defined. here is the correct code?

x = 2
y = 3

def add (x, y):
    total = x + y
    return total

sum = add( x, y)
print(sum)


问:
MYSQL statement to quickly select group from n:n table
I have an n:n set of data (for example, 'programmers' and 'languages'.  Programmers write code in many languages, and a language can be used by many programmers).  This data is in a table programmers_languages

How do I quickly select programmers who code in all of a set of languages?

More information if this is confusing:

Jon codes in C++, Pascal, and Ruby.  Joe codes in C++ and Ruby.  Moe codes in Ruby and Pascal.  Steve Codes in C++ and Pascal.

If the set of languages in question is C++ and Pascal, I would want Jon and Steve from this list.

Note the size of this set can get pretty large, so I don't want to join the table to itself n times.

答:
Note the size of this set can get pretty large, so I don't want to join the table to itself n times.

Any way you shake it, there's going to be a join for each language.  You're looking for a value (programmer) for which there exists at least one row for each of another value (language).  That means that you need to think about N different perspectives of the same table.

In most cases, it's probably most efficient for you to just do the joins.  If the result set is sufficiently dense (really, most programmers speak python and c++), you could resort to some cleverness.  First query the disjunction, but uniquely, then group the resulting relation by programmer and filter out the ones that speak too few languages...

```<code>SELECT programmer
FROM ( SELECT DISTINCT programmer, language
       FROM speaks_table
       WHERE language in ('C++', 'python') ) AS disjunction
GROUP BY disjunction.programmer
HAVING count(disjunction.language) = 2
</code>```

But wether this outperforms a regular ol' multiway join is going to depend on the exact data in question.  This at least has the advantage of not requiring generative queries depending on the number of languages in question.

Body:
Note the size of this set can get pretty large, so I don't want to join the table to itself n times.

Any way you shake it, there's going to be a join for each language.  You're looking for a value (programmer) for which there exists at least one row for each of another value (language).  That means that you need to think about N different perspectives of the same table.

In most cases, it's probably most efficient for you to just do the joins.  If the result set is sufficiently dense (really, most programmers speak python and c++), you could resort to some cleverness.  First query the disjunction, but uniquely, then group the resulting relation by programmer and filter out the ones that speak too few languages...

SELECT programmer
FROM ( SELECT DISTINCT programmer, language
       FROM speaks_table
       WHERE language in ('C++', 'python') ) AS disjunction
GROUP BY disjunction.programmer
HAVING count(disjunction.language) = 2

But wether this outperforms a regular ol' multiway join is going to depend on the exact data in question.  This at least has the advantage of not requiring generative queries depending on the number of languages in question.