问:
Backref in list?
I'm trying to make a regex that matches strings in which the characters are arranged alphabetically, e.g. "ab", but not "ba". Here's my attempt: (.)[\1-z]. It captures the first character and uses that for the beginning of the range in the list. However, in the [], \1 means U+0001, so it matches any two characters:

>>> re.search("(.)[\1-z]", "ab")
<re.Match object; span=(0, 2), match='ab'>
>>> re.search("(.)[\1-z]", "ba")
<re.Match object; span=(0, 2), match='ba'>
```

How can I backref a captured character in a character list?

答:
I suppose you could create a long regex which just checks each letter to make sure it's not succeeded by a letter of lower lexicographic rank. For example:

```<code>^
  (?=.{2,}) # assert length of two or more?
  (?:a(?=.*))*
  (?:b(?=.*[^a].*))*
  (?:c(?=.*[^a-b].*))*
  (?:d(?=.*[^a-c].*))*
  # add in the rest...
$

</code>```

Here would be a link to a working example:

Title: Backref in list?

Body:
I'm trying to make a regex that matches strings in which the characters are arranged alphabetically, e.g. "ab", but not "ba". Here's my attempt: (.)[\1-z]. It captures the first character and uses that for the beginning of the range in the list. However, in the [], \1 means U+0001, so it matches any two characters:

>>> re.search("(.)[\1-z]", "ab")
<re.Match object; span=(0, 2), match='ab'>
>>> re.search("(.)[\1-z]", "ba")
<re.Match object; span=(0, 2), match='ba'>

How can I backref a captured character in a character list?

Body:
I suppose you could create a long regex which just checks each letter to make sure it's not succeeded by a letter of lower lexicographic rank. For example:

^
  (?=.{2,}) # assert length of two or more?
  (?:a(?=.*))*
  (?:b(?=.*[^a].*))*
  (?:c(?=.*[^a-b].*))*
  (?:d(?=.*[^a-c].*))*
  # add in the rest...
$

Here would be a link to a working example:


来源: stackexchange

问:
AttributeError: 'function' object has no attribute 'json'
I am attempting to code some auto quote image generation code using the PaperQuotes API and Pillow, but this little piece of code is screwing everything up. (I am sorry if the code is bad, I am still a newbie to coding)

Code:

```<code>import requests
import os

url = "https://api.paperquotes.com/apiv1/quotes/?lang=en&limit=1&offset=0&order=-likes&page=1&tags=love%2Clife%2Cdepression%2Csuicide%2Csad%2Clonely"

my_secret = os.environ['authorization']

headers = {
    'authorization': my_secret,
    }

response = requests.get(url, headers=headers).json

info = response.json
print(info["results"])
</code>```

Error:

```<code>AttributeError: 'function' object has no attribute 'json'
</code>```

I've tried searching Stackoverflow, but I was not able to understand any of the answers I got.

答:
Json its function, not property.
Also info = response because you was geted the json.

```<code>import requests
import os

url = "https://api.paperquotes.com/apiv1/quotes/?lang=en&limit=1&offset=0&order=-likes&page=1&tags=love%2Clife%2Cdepression%2Csuicide%2Csad%2Clonely"

my_secret = os.environ['authorization']

headers = {
    'authorization': my_secret,
    }

response = requests.get(url, headers=headers).json()

info = response
print(info["results"])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to code some auto quote image generation code using the PaperQuotes API and Pillow, but this little piece of code is screwing everything up. (I am sorry if the code is bad, I am still a newbie to coding)

Code:

import requests
import os

url = "https://api.paperquotes.com/apiv1/quotes/?lang=en&limit=1&offset=0&order=-likes&page=1&tags=love%2Clife%2Cdepression%2Csuicide%2Csad%2Clonely"

my_secret = os.environ['authorization']

headers = {
    'authorization': my_secret,
    }

response = requests.get(url, headers=headers).json

info = response.json
print(info["results"])

Error:

AttributeError: 'function' object has no attribute 'json'

I've tried searching Stackoverflow, but I was not able to understand any of the answers I got.

Body:
Json its function, not property.
Also info = response because you was geted the json.

import requests
import os

url = "https://api.paperquotes.com/apiv1/quotes/?lang=en&limit=1&offset=0&order=-likes&page=1&tags=love%2Clife%2Cdepression%2Csuicide%2Csad%2Clonely"

my_secret = os.environ['authorization']

headers = {
    'authorization': my_secret,
    }

response = requests.get(url, headers=headers).json()

info = response
print(info["results"])


问:
Recursively find and replace string in text files
I want to recursively search through a directory with subdirectories of text files and replace every occurrence of {$replace} within the files with the contents of a multi line string. How can this be achieved with Python?

So far all I have is the recursive code using os.walk to get a list of files that are required to be changed.

```<code>import os
import sys
fileList = []
rootdir = "C:\\test"
for root, subFolders, files in os.walk(rootdir):
  if subFolders != ".svn":
    for file in files:
      fileParts = file.split('.')
      if len(fileParts) > 1:
        if fileParts[1] == "php":
          fileList.append(os.path.join(root,file))

print fileList
</code>```

答:
This is an old question but I figured I'd provide an updated and simpler answer using current libraries in python3.8.</p>
```<code>from pathlib import Path
import re

rootdir = Path("C:\\test")
pattern = r'REGEX for the text you want to replace'
replace = r'REGEX for what to replace it with'

for file in [ f for f in rootdir.glob("**.php") ]: #modify glob pattern as needed
  file_contents = file.read_text()
  new_file_contents = re.sub(f"{pattern}", f"{replace}", file_contents)
  file.write_text(new_file_contents)
</code>```

Body:
I want to recursively search through a directory with subdirectories of text files and replace every occurrence of {$replace} within the files with the contents of a multi line string. How can this be achieved with Python?

So far all I have is the recursive code using os.walk to get a list of files that are required to be changed.

import os
import sys
fileList = []
rootdir = "C:\\test"
for root, subFolders, files in os.walk(rootdir):
  if subFolders != ".svn":
    for file in files:
      fileParts = file.split('.')
      if len(fileParts) > 1:
        if fileParts[1] == "php":
          fileList.append(os.path.join(root,file))

print fileList

Body:
This is an old question but I figured I'd provide an updated and simpler answer using current libraries in python3.8.

from pathlib import Path
import re

rootdir = Path("C:\\test")
pattern = r'REGEX for the text you want to replace'
replace = r'REGEX for what to replace it with'

for file in [ f for f in rootdir.glob("**.php") ]: #modify glob pattern as needed
  file_contents = file.read_text()
  new_file_contents = re.sub(f"{pattern}", f"{replace}", file_contents)
  file.write_text(new_file_contents)


问:
Time Conversion of seconds to HH:mm:SS
I need help with understanding how to convert seconds in integers to a HH:mm:ss format to be displayed in Quicksight Analysis.

My org is pulling its own data from REST APIs of tools being provided to us as a service from various vendors. Some of this data has time spent data measured in seconds. I know this is an easy fix in Power BI, however, i am still new to Quicksight and trying to understand how this can be achieved here.
I need to be able to do aggregations on the time in seconds and then display the result in the HH:mm:ss format. For e.g. Handle time of 184, 436, 346 seconds respectively should give an Average Handle time of 00:05:22 and total handle time of 00:16:06. I cannot make changes to the tables in Athena using SQL and need to be able to do this at the dataset level or Analysis level in Quicksight. Please help me understand how this can be achieved.

Thanks in advance!!

答:
Currently conversion of seconds to hh:mm:ss in AWS QuickSight is only available by creating a calculated field with the following function:

```<code>concat(toString(floor({field_with_seconds}/3600)),':',toString(floor(({field_with_seconds}%3600)/60)),':',toString({field_with_seconds}%60))
</code>```

Title: Time Conversion of seconds to HH:mm:SS

Body:
Currently conversion of seconds to hh:mm:ss in AWS QuickSight is only available by creating a calculated field with the following function:

concat(toString(floor({field_with_seconds}/3600)),':',toString(floor(({field_with_seconds}%3600)/60)),':',toString({field_with_seconds}%60))


问:
json_decode creates unnecessary arrays
I got this JSON which I need to convert to associative PHP array

```<code>[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]
</code>```

$decoded = json_decode($json, true) creates unnecessary arrays [0] and [1], so I can't access $decoded[32] without double looping.

```<code>Array
(
    [0] => Array
        (
            [32] => Array
                (
                    [name] => Price File Jan 2022.xlsx
                    [datastartingrow] => 1
                )

        )

    [1] => Array
        (
            [33] => Array
                (
                    [name] => Price File Feb 2022.xlsx
                    [datastartingrow] => 2
                )

        )

)
</code>```

Is there an elegant way of accessing each array by using key [32] and [33]?

Thanks.

答:
```<code>$jsonStr = '[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]';
$decoded = json_decode($jsonStr,true);
</code>```

Direct access to the array with key 32:

```<code>$a32 = array_column($decoded,32)[0];
/*
array (
  'name' => "Price File Jan 2022.xlsx",
  'datastartingrow' => "1",
)
*/
</code>```

Similarly for key 33

```<code>$a33 = array_column($decoded,33)[0];
</code>```

Title: json_decode creates unnecessary arrays

Body:
I got this JSON which I need to convert to associative PHP array

[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]

$decoded = json_decode($json, true) creates unnecessary arrays [0] and [1], so I can't access $decoded[32] without double looping.

Array
(
    [0] => Array
        (
            [32] => Array
                (
                    [name] => Price File Jan 2022.xlsx
                    [datastartingrow] => 1
                )

        )

    [1] => Array
        (
            [33] => Array
                (
                    [name] => Price File Feb 2022.xlsx
                    [datastartingrow] => 2
                )

        )

)

Is there an elegant way of accessing each array by using key [32] and [33]?

Thanks.

Body:
$jsonStr = '[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]';
$decoded = json_decode($jsonStr,true);

Direct access to the array with key 32:

$a32 = array_column($decoded,32)[0];
/*
array (
  'name' => "Price File Jan 2022.xlsx",
  'datastartingrow' => "1",
)
*/

Similarly for key 33

$a33 = array_column($decoded,33)[0];


问:
Beginning at the end of 'a', insert 'b' after every 3rd character of 'a'
I've been trying to solve this challenge (found at jschallenger.com):

Write a function that takes two strings (a and b) as arguments

Beginning at the end of 'a', insert 'b' after every 3rd character of
'a'

Return the resulting string

This is my solution so far (Which I was sure would work):

function insertEveryThree(a, b) {
  let arr = a.split('')

  for (let i = arr.length - 3; i > 0; i -= 3) {

    arr.splice(i, 0, b)

  }
  return arr.join('')
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz```

Where am I failing at?

答:
You could replace the string with a regular expression.

function insertEveryThree(a, b) {
    return a.replace(/(?=(...)+$)/g, b);
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz```

Body:
I've been trying to solve this challenge (found at jschallenger.com):

Write a function that takes two strings (a and b) as arguments

Beginning at the end of 'a', insert 'b' after every 3rd character of
'a'

Return the resulting string

This is my solution so far (Which I was sure would work):

function insertEveryThree(a, b) {
  let arr = a.split('')

  for (let i = arr.length - 3; i > 0; i -= 3) {

    arr.splice(i, 0, b)

  }
  return arr.join('')
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz

Where am I failing at?


问:
Very slow filtering with multiple conditions in pandas dataframe
UPDATE: I have edited the question (and code) to make the problem clearer. I use here synthetic data but imagine a large df of floods and a small one of significant floods. I want add a reference to every row (of the large_df) if it is somewhat close to the significant flood.

I have 2 pandas dataframes (1 large and 1 small).
In every iteration I want to create a subset of the small dataframe based on a few conditions that are dependent on each row (of the large df):

```<code>import numpy as np
import pandas as pd
import time

SOME_THRESHOLD = 10.5

MUMBER_OF_ROWS = 2e4
large_df = pd.DataFrame(index=np.arange(MUMBER_OF_ROWS), data={'a': np.arange(MUMBER_OF_ROWS)})
small_df = large_df.loc[np.random.randint(0, MUMBER_OF_ROWS, 5)]
large_df['past_index'] = None

count_time = 0
for ind, row in large_df.iterrows():
  start = time.time()
  # This line takes forever.
  df_tmp = small_df[(small_df.index<ind) & (small_df['a']>(row['a']-SOME_THRESHOLD)) & (small_df['a']<(row['a']+SOME_THRESHOLD))]
  count_time += time.time()-start
  if not df_tmp.empty:
    past_index = df_tmp.loc[df_tmp.index.max()]['a']
    large_df.loc[ind, 'similar_past_flood_tag'] = f'Similar to the large flood of {past_index}'

print(f'The total time of creating the subset df for 2e4 rows is: {count_time} seconds.')
</code>```

The line that creates the subset takes a long time to compute:

The total time of creating the subset df for 2e4 rows is: 18.276793956756592 seconds.

This seems to me to be an too long. I have found similar questions but non of the answers seemed to work (e.g query and numpy conditions).
Is there a way to optimize this?

Note: the code does what is expected - just very slow.

答:
While your code is logically correct, building the many boolean arrays and slicing the DataFrame accumulates to some time..

Here are some stats with %timeit:

(small_df.index<ind): ~30μs

(small_df['a']>(row['a']-SOME_THRESHOLD)): ~100μs

(small_df['a']<(row['a']+SOME_THRESHOLD)): ~100μs

After '&'-ing all three: ~500μs

Including the DataFrame slice: ~700μs

That, multiplied by 20K times is indeed 14 seconds.. :)

What you could do is take advantage of numpy's broadcast to compute the boolean matrix more efficiently, and then reconstruct the "valid" DataFrame. See below:

```<code>l_ind = np.array(large_df.index)
s_ind = np.array(small_df.index)
l_a = np.array(large_df.a)
s_a = np.array(small_df.a)

arr1 = (l_ind[:, None] < s_ind[None, :])
arr2 = (((l_a[:, None] - SOME_THRESHOLD) < s_a[None, :]) &
        (s_a[None, :] < (l_a[:, None] + SOME_THRESHOLD)))

arr = arr1 & arr2
large_valid_inds, small_valid_inds = np.where(arr)

pd.DataFrame({'large_ind': np.take(l_ind, large_valid_inds),
              'small_ind': np.take(s_ind, small_valid_inds)})
</code>```

That gives you the following DF, which if I understood the question properly, is the expected solution:

large_ind
small_ind

0
1621
1631

1
1622
1631

2
1623
1631

3
1624
1631

4
1625
1631

5
1626
1631

6
1627
1631

7
1628
1631

8
1629
1631

9
1630
1631

10
1992
2002

11
1993
2002

12
1994
2002

13
1995
2002

14
1996
2002

15
1997
2002

16
1998
2002

17
1999
2002

18
2000
2002

19
2001
2002

20
8751
8761

21
8752
8761

22
8753
8761

23
8754
8761

24
8755
8761

25
8756
8761

26
8757
8761

27
8758
8761

28
8759
8761

29
8760
8761

30
10516
10526

31
10517
10526

32
10518
10526

33
10519
10526

34
10520
10526

35
10521
10526

36
10522
10526

37
10523
10526

38
10524
10526

39
10525
10526

40
18448
18458

41
18449
18458

42
18450
18458

43
18451
18458

44
18452
18458

45
18453
18458

46
18454
18458

47
18455
18458

48
18456
18458

49
18457
18458

Body:
UPDATE: I have edited the question (and code) to make the problem clearer. I use here synthetic data but imagine a large df of floods and a small one of significant floods. I want add a reference to every row (of the large_df) if it is somewhat close to the significant flood.

I have 2 pandas dataframes (1 large and 1 small).
In every iteration I want to create a subset of the small dataframe based on a few conditions that are dependent on each row (of the large df):

import numpy as np
import pandas as pd
import time

SOME_THRESHOLD = 10.5

MUMBER_OF_ROWS = 2e4
large_df = pd.DataFrame(index=np.arange(MUMBER_OF_ROWS), data={'a': np.arange(MUMBER_OF_ROWS)})
small_df = large_df.loc[np.random.randint(0, MUMBER_OF_ROWS, 5)]
large_df['past_index'] = None

count_time = 0
for ind, row in large_df.iterrows():
  start = time.time()
  # This line takes forever.
  df_tmp = small_df[(small_df.index<ind) & (small_df['a']>(row['a']-SOME_THRESHOLD)) & (small_df['a']<(row['a']+SOME_THRESHOLD))]
  count_time += time.time()-start
  if not df_tmp.empty:
    past_index = df_tmp.loc[df_tmp.index.max()]['a']
    large_df.loc[ind, 'similar_past_flood_tag'] = f'Similar to the large flood of {past_index}'

print(f'The total time of creating the subset df for 2e4 rows is: {count_time} seconds.')

The line that creates the subset takes a long time to compute:

The total time of creating the subset df for 2e4 rows is: 18.276793956756592 seconds.

This seems to me to be an too long. I have found similar questions but non of the answers seemed to work (e.g query and numpy conditions).
Is there a way to optimize this?

Note: the code does what is expected - just very slow.

Body:
While your code is logically correct, building the many boolean arrays and slicing the DataFrame accumulates to some time..

Here are some stats with %timeit:

(small_df.index<ind): ~30μs

(small_df['a']>(row['a']-SOME_THRESHOLD)): ~100μs

(small_df['a']<(row['a']+SOME_THRESHOLD)): ~100μs

After '&'-ing all three: ~500μs

Including the DataFrame slice: ~700μs

That, multiplied by 20K times is indeed 14 seconds.. :)

What you could do is take advantage of numpy's broadcast to compute the boolean matrix more efficiently, and then reconstruct the "valid" DataFrame. See below:

l_ind = np.array(large_df.index)
s_ind = np.array(small_df.index)
l_a = np.array(large_df.a)
s_a = np.array(small_df.a)

arr1 = (l_ind[:, None] < s_ind[None, :])
arr2 = (((l_a[:, None] - SOME_THRESHOLD) < s_a[None, :]) &
        (s_a[None, :] < (l_a[:, None] + SOME_THRESHOLD)))

arr = arr1 & arr2
large_valid_inds, small_valid_inds = np.where(arr)

pd.DataFrame({'large_ind': np.take(l_ind, large_valid_inds),
              'small_ind': np.take(s_ind, small_valid_inds)})

That gives you the following DF, which if I understood the question properly, is the expected solution:

large_ind
small_ind

0
1621
1631

1
1622
1631

2
1623
1631

3
1624
1631

4
1625
1631

5
1626
1631

6
1627
1631

7
1628
1631

8
1629
1631

9
1630
1631

10
1992
2002

11
1993
2002

12
1994
2002

13
1995
2002

14
1996
2002

15
1997
2002

16
1998
2002

17
1999
2002

18
2000
2002

19
2001
2002

20
8751
8761

21
8752
8761

22
8753
8761

23
8754
8761

24
8755
8761

25
8756
8761

26
8757
8761

27
8758
8761

28
8759
8761

29
8760
8761

30
10516
10526

31
10517
10526

32
10518
10526

33
10519
10526

34
10520
10526

35
10521
10526

36
10522
10526

37
10523
10526

38
10524
10526

39
10525
10526

40
18448
18458

41
18449
18458

42
18450
18458

43
18451
18458

44
18452
18458

45
18453
18458

46
18454
18458

47
18455
18458

48
18456
18458

49
18457
18458


问:
XML tag not found
After extracting XML from CDATA I can't find tags in the extracted XML. If I convert to string and then back to an ElementTree I can find the tags I'm looking for (un-comment the lines marked "UNCOMMENT ME"). Looking for a better / more correct way.</p>
```<code>    import xml.etree.ElementTree as ElementTree

    XML = '''<?xml version="1.0" encoding="UTF-8"?>
    <Catalog>
    <Data><![CDATA[
    <Book>
        <Author>George Orwell</Author>
        <Title>1984</Title>
    </Book>
    ]]></Data>
    </Catalog>
    '''
    def get_cdata_xml(xml_str: str) -> ElementTree:
        xml_root = ElementTree.fromstring(xml_str)
        cdata_xml = xml_root.find('.//Data')
        return cdata_xml

    if __name__ == '__main__':
        cdata_xml = get_cdata_xml(XML)

        #xml_str = cdata_xml.text  # UNCOMMENT ME
        #cdata_xml = ElementTree.fromstring(xml_str) #UNCOMMENT ME

        # type(cdata_xml) = xml.etree.ElementTree.Element
        author = cdata_xml.find('.//Author')

        print(author.text)
</code>```

答:
A CDATA block is just a string; it's not XML content. You would need to parse the cdata content with another call to `ElementTree.fromstring:

```<code>cdata_xml = get_cdata_xml(XML)
book = ElementTree.fromstring(cdata_xml.text)
author = book.find(".//Author")
print(author.text)
</code>```

Title: XML tag not found

Body:
After extracting XML from CDATA I can't find tags in the extracted XML. If I convert to string and then back to an ElementTree I can find the tags I'm looking for (un-comment the lines marked "UNCOMMENT ME"). Looking for a better / more correct way.

    import xml.etree.ElementTree as ElementTree

    XML = '''<?xml version="1.0" encoding="UTF-8"?>
    <Catalog>
    <Data><![CDATA[
    <Book>
        <Author>George Orwell</Author>
        <Title>1984</Title>
    </Book>
    ]]></Data>
    </Catalog>
    '''
    def get_cdata_xml(xml_str: str) -> ElementTree:
        xml_root = ElementTree.fromstring(xml_str)
        cdata_xml = xml_root.find('.//Data')
        return cdata_xml

    if __name__ == '__main__':
        cdata_xml = get_cdata_xml(XML)

        #xml_str = cdata_xml.text  # UNCOMMENT ME
        #cdata_xml = ElementTree.fromstring(xml_str) #UNCOMMENT ME

        # type(cdata_xml) = xml.etree.ElementTree.Element
        author = cdata_xml.find('.//Author')

        print(author.text)

Body:
A CDATA block is just a string; it's not XML content. You would need to parse the cdata content with another call to `ElementTree.fromstring:

cdata_xml = get_cdata_xml(XML)
book = ElementTree.fromstring(cdata_xml.text)
author = book.find(".//Author")
print(author.text)


问:
Uncaught SyntaxErrror: Unexpected token ILLEGAL in chrome
I'm having a problem within the jQuery ajax function. The following code works fine in Mozilla but doesn't work in IE or Chrome, when I try to identify the problem using Developer Tools in chrome I get the error:

```<code>Uncaught SyntaxError: Unexpected token ILLEGAL \n
$.ajax.success
</code>```

and when I click on it it directs me to the var obj = JSON.parse(data); line.

```<code>function getdata(){
    $.ajax({
        type:"GET",
        url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
        data: "",
        success: function(data) {
            var obj = JSON.parse(data);
            displayPlaylists(obj);
        }

    });
}
</code>```

EDIT:
Ive found a solution that works in chrome but still not in IE

```<code>function getdata(){
        $.ajax({
                type:"GET",
                url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
                dataType:"json",
                success: function(data) {
                    displayPlaylists(data);
                }

            });
    }
</code>```

the addition of dataType:"json" means that the function expects json data to be returned and therefore parses it on arrival (it is equivalent to using jQuery.parseJSON), however as i said this solution still doesn't work in IE

答:
Since jQuery already assumes it's JSON (from the HTTP header), data already is passed as JSON.

So what happens is that you're using JSON.parse on an object (the JSON).

This fais with the same reason:

```<code>JSON.parse({}); // parse an object
</code>```

because the {} becomes a string:

```<code>[object Object]
</code>```

which is not valid JSON at all.

So, just remove the JSON.parse.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a problem within the jQuery ajax function. The following code works fine in Mozilla but doesn't work in IE or Chrome, when I try to identify the problem using Developer Tools in chrome I get the error:

Uncaught SyntaxError: Unexpected token ILLEGAL \n
$.ajax.success

and when I click on it it directs me to the var obj = JSON.parse(data); line.

function getdata(){
    $.ajax({
        type:"GET",
        url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
        data: "",
        success: function(data) {
            var obj = JSON.parse(data);
            displayPlaylists(obj);
        }

    });
}

EDIT:
Ive found a solution that works in chrome but still not in IE

function getdata(){
        $.ajax({
                type:"GET",
                url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
                dataType:"json",
                success: function(data) {
                    displayPlaylists(data);
                }

            });
    }

the addition of dataType:"json" means that the function expects json data to be returned and therefore parses it on arrival (it is equivalent to using jQuery.parseJSON), however as i said this solution still doesn't work in IE

Body:
Since jQuery already assumes it's JSON (from the HTTP header), data already is passed as JSON.

So what happens is that you're using JSON.parse on an object (the JSON).

This fais with the same reason:

JSON.parse({}); // parse an object

because the {} becomes a string:

[object Object]

which is not valid JSON at all.

So, just remove the JSON.parse.


问:
Encountering an error while calling a non built-in function in R
I made a function in R which basically takes certain values from a column of my dataframe according to the dates specified and returns their sum:

```<code> <<>>=
    dmon.function = function(y, m, d){
      result = sum(dmystatedf$Deceased[Dategood>="y-m-01" & Dategood<="y-m-d"])
    }
    dmon.function(2021, 04, 03)
    @
</code>```

Now when I pass the function, I get no error, but when I call the function, I get this error:

```<code>> dmon.function(2021, 04, 03)
 Error in charToDate(x) :
character string is not in a standard unambiguous format
</code>```

How do I resolve this error? How to I make functions that takes arguments and use them as dates, months, or years in general?

EDIT 1: Here are the first few rows of the data I'm using:

```<code>> head(dmystatedf[c("Deceased", "Dategood")])
    Deceased   Dategood
61         0 2020-03-09
74         0 2020-03-10
87         0 2020-03-11
101        0 2020-03-12
115        1 2020-03-13
130        1 2020-03-14
</code>```

Here is the output of the code dput(head(dmystatedf[c("Deceased", "Dategood")])) as requested by Rui Barradas in comments:

```<code>> dput(head(dmystatedf[c("Deceased", "Dategood")]))
structure(list(Deceased = c(0L, 0L, 0L, 0L, 1L, 1L), Dategood = structure(18330:18335, class = "Date")), row.names = c(61L,
74L, 87L, 101L, 115L, 130L), class = "data.frame")
</code>```

THANK YOU

答:
You don't need contributed packages, base R alone is enough to solve the question's problem.

Base function ISOdate accepts year, month and day and returns an oject of class "POSIXt" "POSIXct". Then the comparisons to the column of class "Date" will give warnings so coerce the start and end dates with as.Date.

dmon.function <- function(y, m, d){
  start <- as.Date(ISOdate(y, m, 1))
  end <- as.Date(ISOdate(y, m, d))
  sum(dmystatedf$Deceased[dmystatedf$Dategood >= start & dmystatedf$Dategood <= end])
}

dmon.function(2021, 04, 03)
#> [1] 0
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I made a function in R which basically takes certain values from a column of my dataframe according to the dates specified and returns their sum:

 <<>>=
    dmon.function = function(y, m, d){
      result = sum(dmystatedf$Deceased[Dategood>="y-m-01" & Dategood<="y-m-d"])
    }
    dmon.function(2021, 04, 03)
    @

Now when I pass the function, I get no error, but when I call the function, I get this error:

> dmon.function(2021, 04, 03)
 Error in charToDate(x) :
character string is not in a standard unambiguous format

How do I resolve this error? How to I make functions that takes arguments and use them as dates, months, or years in general?

EDIT 1: Here are the first few rows of the data I'm using:

> head(dmystatedf[c("Deceased", "Dategood")])
    Deceased   Dategood
61         0 2020-03-09
74         0 2020-03-10
87         0 2020-03-11
101        0 2020-03-12
115        1 2020-03-13
130        1 2020-03-14

Here is the output of the code dput(head(dmystatedf[c("Deceased", "Dategood")])) as requested by Rui Barradas in comments:

> dput(head(dmystatedf[c("Deceased", "Dategood")]))
structure(list(Deceased = c(0L, 0L, 0L, 0L, 1L, 1L), Dategood = structure(18330:18335, class = "Date")), row.names = c(61L,
74L, 87L, 101L, 115L, 130L), class = "data.frame")

THANK YOU

Body:
You don't need contributed packages, base R alone is enough to solve the question's problem.

Base function ISOdate accepts year, month and day and returns an oject of class "POSIXt" "POSIXct". Then the comparisons to the column of class "Date" will give warnings so coerce the start and end dates with as.Date.

dmon.function <- function(y, m, d){
  start <- as.Date(ISOdate(y, m, 1))
  end <- as.Date(ISOdate(y, m, d))
  sum(dmystatedf$Deceased[dmystatedf$Dategood >= start & dmystatedf$Dategood <= end])
}

dmon.function(2021, 04, 03)
#> [1] 0

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
Xcode not showing commits in Repository
So, I made a few commits today, but they are not showing in the Xcode Repository.

The curious thing is that the version of the project changes after every commit, but it just shows yesterday's commit.

I made a test commit showing the progress.

Image 1 - Repository before commit

Image 2 - commiting

Image 3 - Repository after committing. (you can see the changed version of the project, but not on the repository.)

I have no idea what changed from yesterday.

Thanks in advance.

答: You have a detached head, so your commits do not get onto main. To commit to main, first you need to be on main.

Title: Xcode not showing commits in Repository


问:
No matching distribution found for xyzservices during installation
When I try pip3 install xyzservices I receive:

```<code>Collecting xyzservices
  Could not find a version that satisfies the requirement xyzservices (from versions: )
No matching distribution found for xyzservices
</code>```

python --version returns:

```<code>Python 3.6.8
</code>```

pip3 --version returns:

```<code>pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip (python 3.6)
</code>```

What is going on here?

答: All versions of xyzservices require Python >= 3.7. Even the oldest version 2021.7. See the code at the oldest tag 2021.7.

Body:
When I try pip3 install xyzservices I receive:

Collecting xyzservices
  Could not find a version that satisfies the requirement xyzservices (from versions: )
No matching distribution found for xyzservices

python --version returns:

Python 3.6.8

pip3 --version returns:

pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip (python 3.6)

What is going on here?


问:
Benchmarking VBA Code
What is considered the most accurate way to benchmark VBA code (in my case, I am testing code in Excel)? Are there any other techniques for benchmarking code besides the 2 below, and if so, what are the pros/cons of the method?

Here are 2 popular methods.

First: Timer

Sub TimerBenchmark()

Dim benchmark As Double
benchmark = Timer

'Do your code here

MsgBox Timer - benchmark

End Sub
```

<p>And <strong>Tick</strong> (which I see argued as the most accurate):</p>

```Option Explicit
Private Declare Function GetTickCount Lib "kernel32" () As Long

Sub TickBenchmark()

Dim Start As Long
Dim Finish As Long

Start = GetTickCount()

'Do your code here

Finish = GetTickCount()
MsgBox CStr((Finish - Start) / 1000)

End Sub
```

答:
Interesting question. This is not really a full answer but this is too long to be posted as a comment.

What i use is this kind of procedure:

```<code>Option Explicit
Public Time As Double
Sub Chrono()
If Time = 0 Then
    Time = Now()
Else
    MsgBox "Total time :" & Application.Text(Now() - _
        Time, "mm:ss") & "."  'or whatever if not a msgbox
    Time = 0
End If
End Sub
</code>```

That way, you can put your code wherever you want and only have to call it twice (for instance):

```<code>If C_DEBUG Then Call Chrono
</code>```

At the beginning and at the end of the part of code you want to test.

Yet, i would say there is no real "accurate" method because it also depends on what is running on your computer. I'd say these methods would mostly help telling which code is better than another.

Title: Benchmarking VBA Code

Body:
What is considered the most accurate way to benchmark VBA code (in my case, I am testing code in Excel)? Are there any other techniques for benchmarking code besides the 2 below, and if so, what are the pros/cons of the method?

Here are 2 popular methods.

First: Timer

Sub TimerBenchmark()

Dim benchmark As Double
benchmark = Timer

'Do your code here

MsgBox Timer - benchmark

End Sub

And Tick (which I see argued as the most accurate):

Option Explicit
Private Declare Function GetTickCount Lib "kernel32" () As Long

Sub TickBenchmark()

Dim Start As Long
Dim Finish As Long

Start = GetTickCount()

'Do your code here

Finish = GetTickCount()
MsgBox CStr((Finish - Start) / 1000)

End Sub

Body:
Interesting question. This is not really a full answer but this is too long to be posted as a comment.

What i use is this kind of procedure:

Option Explicit
Public Time As Double
Sub Chrono()
If Time = 0 Then
    Time = Now()
Else
    MsgBox "Total time :" & Application.Text(Now() - _
        Time, "mm:ss") & "."  'or whatever if not a msgbox
    Time = 0
End If
End Sub

That way, you can put your code wherever you want and only have to call it twice (for instance):

If C_DEBUG Then Call Chrono

At the beginning and at the end of the part of code you want to test.

Yet, i would say there is no real "accurate" method because it also depends on what is running on your computer. I'd say these methods would mostly help telling which code is better than another.


问:
for loop to list comprehension[nested for loop)
After a few tries I am not able to convert this for loop into a single line[list comprehension]

```<code>        print(cells_don[0])

        cells_v_don = list()
        for cell in cells_don:
            row = list()
            for i in range(0, len(cell)):
                row.append(cell[i].value)
            cells_v_don.append(row)

</code>```

Output: It s just a tuple collecting data from a excel table:

(<Cell 'ede_ser'.C13>, <Cell 'ede_ser'.D13>, <Cell 'ede_ser'.E13>, <Cell 'ede_ser'.F13>, <Cell 'ede_ser'.G13>, <Cell 'ede_ser'.H13>, <Cell 'ede_ser'.I13>, <Cell 'ede_ser'.J13>, <Cell 'ede_ser'.K13>, <Cell 'ede_ser'.L13>, <Cell 'ede_ser'.M13>, <Cell 'ede_ser'.N13>, <Cell 'ede_ser'.O13>, <Cell 'ede_ser'.P13>, <Cell 'ede_ser'.Q13>, <Cell 'ede_ser'.R13>, <Cell 'ede_ser'.S13>, <Cell 'ede_ser'.T13>)

How can I convert this code into a list comprehension?

Thank you!

答:
```<code>cells_v_don = [
    [cell[i].value for i in range(0, len(cell))]
    for cell in cells_don
]
</code>```

Body:
After a few tries I am not able to convert this for loop into a single line[list comprehension]

        print(cells_don[0])

        cells_v_don = list()
        for cell in cells_don:
            row = list()
            for i in range(0, len(cell)):
                row.append(cell[i].value)
            cells_v_don.append(row)

Output: It s just a tuple collecting data from a excel table:

(<Cell 'ede_ser'.C13>, <Cell 'ede_ser'.D13>, <Cell 'ede_ser'.E13>, <Cell 'ede_ser'.F13>, <Cell 'ede_ser'.G13>, <Cell 'ede_ser'.H13>, <Cell 'ede_ser'.I13>, <Cell 'ede_ser'.J13>, <Cell 'ede_ser'.K13>, <Cell 'ede_ser'.L13>, <Cell 'ede_ser'.M13>, <Cell 'ede_ser'.N13>, <Cell 'ede_ser'.O13>, <Cell 'ede_ser'.P13>, <Cell 'ede_ser'.Q13>, <Cell 'ede_ser'.R13>, <Cell 'ede_ser'.S13>, <Cell 'ede_ser'.T13>)

How can I convert this code into a list comprehension?

Thank you!


问:
How to locate nodes in the middle in plotly sankey diagram
With plotly sankey diagram I want to locate a node in the middle using code, but since this node does not have a flow for another node, plotly places it at the right end. I have the next code:

```<code>import plotly.graph_objects as go

fig1 = go.Figure(
    go.Sankey(
        node={"label": ["A", "B", "C", "D", "E", "F"]},
        link={
            "source": [0, 0, 0, 1, 2, 2],
            "target": [1, 2, 3, 4, 4, 5],
            "value": [20, 10, 20, 20, 5, 15]
        }
    )
)
fig1.show()
</code>```

The output:

For example, for the image I would like to locate node D below nodes B and C.

答:
You can create groups of nodes using the groups key in the node dictionary:

```<code>fig1 = go.Figure(
    go.Sankey(
        node={
             "label": ["A", "B", "C", "D", "E", "F"],
             "groups": [[0], [1, 2, 3], [4, 5]]
        },
        link={
            "source": [0, 0, 0, 1, 2, 2],
            "target": [1, 2, 3, 4, 4, 5],
            "value": [20, 10, 20, 20, 5, 15]
        }
    )
)
</code>```

Body:
With plotly sankey diagram I want to locate a node in the middle using code, but since this node does not have a flow for another node, plotly places it at the right end. I have the next code:

import plotly.graph_objects as go

fig1 = go.Figure(
    go.Sankey(
        node={"label": ["A", "B", "C", "D", "E", "F"]},
        link={
            "source": [0, 0, 0, 1, 2, 2],
            "target": [1, 2, 3, 4, 4, 5],
            "value": [20, 10, 20, 20, 5, 15]
        }
    )
)
fig1.show()

The output:

For example, for the image I would like to locate node D below nodes B and C.

Body:
You can create groups of nodes using the groups key in the node dictionary:

fig1 = go.Figure(
    go.Sankey(
        node={
             "label": ["A", "B", "C", "D", "E", "F"],
             "groups": [[0], [1, 2, 3], [4, 5]]
        },
        link={
            "source": [0, 0, 0, 1, 2, 2],
            "target": [1, 2, 3, 4, 4, 5],
            "value": [20, 10, 20, 20, 5, 15]
        }
    )
)


问:
What is the minimum necessary code to keep a session alive in classic ASP?
I have a classic ASP site that I would like the sessions to stay alive as long as the user has a page open. So I used some Javascript to periodically call a 'keepalive' ASP page to keep the session alive so the timeout is not reached.

What do I need to put in the ASP page code to make sure it renews the session timer? Can it be a blank page or do I need to hit the Session object?

答:
It has been my experience that as long as you perform some kind of server process periodically, the session doesn't end.

What I do is have a javascript function that is periodically run via a setInterval() function call in the onLoad process of the  tag.

In that function I execute a server-side SQL query.

I place this inside the  section with all of javascript and styleshooe loads:

Then I place the following lines right after my  tag:

               -->
RSEnableRemoteScripting("."); -->


问:
Failed to find data source: com.mongodb.spark.sql.DefaultSource
I'm trying to connect spark (pyspark) to mongodb as follows:

```<code>conf = SparkConf()
conf.set('spark.mongodb.input.uri', default_mongo_uri)
conf.set('spark.mongodb.output.uri', default_mongo_uri)
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
spark = SparkSession \
    .builder \
    .appName("my-app") \
    .config("spark.mongodb.input.uri", default_mongo_uri) \
    .config("spark.mongodb.output.uri", default_mongo_uri) \
    .getOrCreate()
</code>```

But when I do the following:

```<code>users = spark.read.format("com.mongodb.spark.sql.DefaultSource") \
        .option("uri", '{uri}.{col}'.format(uri=mongo_uri, col='users')).load()
</code>```

I get this error:

java.lang.ClassNotFoundException: Failed to find data source:
  com.mongodb.spark.sql.DefaultSource

I did the same thing from pyspark shell and I was able to retrieve data. This is the command I ran:

```<code>pyspark --conf "spark.mongodb.input.uri=mongodb_uri" --conf "spark.mongodb.output.uri=mongodburi" --packages org.mongodb.spark:mongo-spark-connector_2.11:2.2.2
</code>```

But here we have the option to specify the package we need to use. But what about standalone apps and scripts. how can I configure mongo-spark-connector there.

Any ideas?

答:
Here is how this error got resolved by downloading the jar files below. (Used the solution of this question.)

1.Downloaded the jar files below.

mongo-spark-connector_2.11-2.4.1 from here

mongo-java-driver-3.9.0 from here

copy and paste both these jar files into 'jars' location in spark directory.

Pyspark Code in jupiter notebook:

```<code>import pyspark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("mongo").\
config("spark.mongodb.input.uri","mongodb://127.0.0.1:27017/$database.$table_name").\
config("spark.mongodb.output.uri","mongodb://127.0.0.1:27017/$database.$table_name").\
getOrCreate()

df=spark.read.format('com.mongodb.spark.sql.DefaultSource')\
    .option( "uri", "mongodb://127.0.0.1:27017/$database.$table_name") \
    .load()

df.printSchema()

#create Temp view of df to view the data
table = df.createOrReplaceTempView("df")

#to read table present in mongodb
query1 = spark.sql("SELECT * FROM df ")
query1.show(10)

</code>```

Body:
I'm trying to connect spark (pyspark) to mongodb as follows:

conf = SparkConf()
conf.set('spark.mongodb.input.uri', default_mongo_uri)
conf.set('spark.mongodb.output.uri', default_mongo_uri)
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
spark = SparkSession \
    .builder \
    .appName("my-app") \
    .config("spark.mongodb.input.uri", default_mongo_uri) \
    .config("spark.mongodb.output.uri", default_mongo_uri) \
    .getOrCreate()

But when I do the following:

users = spark.read.format("com.mongodb.spark.sql.DefaultSource") \
        .option("uri", '{uri}.{col}'.format(uri=mongo_uri, col='users')).load()

I get this error:

java.lang.ClassNotFoundException: Failed to find data source:
  com.mongodb.spark.sql.DefaultSource

I did the same thing from pyspark shell and I was able to retrieve data. This is the command I ran:

pyspark --conf "spark.mongodb.input.uri=mongodb_uri" --conf "spark.mongodb.output.uri=mongodburi" --packages org.mongodb.spark:mongo-spark-connector_2.11:2.2.2

But here we have the option to specify the package we need to use. But what about standalone apps and scripts. how can I configure mongo-spark-connector there.

Any ideas?

Body:
Here is how this error got resolved by downloading the jar files below. (Used the solution of this question.)

1.Downloaded the jar files below.

mongo-spark-connector_2.11-2.4.1 from here

mongo-java-driver-3.9.0 from here

copy and paste both these jar files into 'jars' location in spark directory.

Pyspark Code in jupiter notebook:

import pyspark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("mongo").\
config("spark.mongodb.input.uri","mongodb://127.0.0.1:27017/$database.$table_name").\
config("spark.mongodb.output.uri","mongodb://127.0.0.1:27017/$database.$table_name").\
getOrCreate()

df=spark.read.format('com.mongodb.spark.sql.DefaultSource')\
    .option( "uri", "mongodb://127.0.0.1:27017/$database.$table_name") \
    .load()

df.printSchema()

#create Temp view of df to view the data
table = df.createOrReplaceTempView("df")

#to read table present in mongodb
query1 = spark.sql("SELECT * FROM df ")
query1.show(10)


问:
Oracle Reverse Engineer ERD for Mac
I have a large database, over 100 tables, and I would like to reverse-engineer it into an ERD. I would like to do this automatically. OracleDataModeler works fine for me but seems to only let me select one table at a time. With my large database, I want to find a tool that will apply the ERD to the entire database, at once.

However, my employer has us using only MacOs (I'm on Monterey) and I can't find anything that will work for me. It doesn't have to be a free tool, I'm willing to pay for it, but all tools that I find seem to be only for Windows systems.

As a side tip, I had used RedGate software to do this with SQLServer databases and it is really easy to use. It worked great. If I could find something like that, it would be exactly what I'm looking for.

答:
OracleDataModeler works fine for me but seems to only let me select
one table at a time.

No...use the Import wizard, point to your connection, select your schema/objects, and Voila.

Step By Steps

Connect to your datbase, pick your schemas and object types, and then...pick your objects...Click the 'Select All' button to grab everything.

Let it work it's magic..it may take awhile depending on how many objects you selected.

Disclaimer: I'm an Oracle employee and the product manager for SQL Developer / Data Modeler.

Title: Oracle Reverse Engineer ERD for Mac


问:
Visualizing a project tracker in R
Does anyone have any ideas on how to visualize something like this using R?

Basically I want to make a plot to track the percentage completeness of different jobs in a few projects. The percentage completeness should be color coded (in the example, dark blue means the job is 100% complete, white means 0% complete etc.)
Here's some sample code to make the dataframe:

```<code>project <- c('Project 1', 'Project 2', 'Project 3', 'Project 4')

job1 <- c(100, 100, NA, 100)

job2 <- c(100, 100, NA, 100)

job3 <- c(100, NA, NA, NA)

job4 <- c(NA, 100, 100, 100)

job5 <- c(50, 100, 100, 100)

job6 <- c(0, 40, 100, 100)

df <- data.frame(project, job1, job2, job3, job4, job5, job6)
</code>```

I've tried a gantt chart but couldn't get that to work as there is no time data. I've tried a bar chart but that didn't work as some of the projects have NA or 0 values followed by 100/50 etc. so the jobs don't line up. I also tried a heatmap but that doesn't really work either, as there needs to be a visible distinction between the NA values and the 0 values i.e. NA means that a job isn't applicable to that project, whereas 0 means the job hasn't started yet.

Any suggestions would be really appreciated!

答:
DT (datatable) based solution:

```<code>library(DT)
options(DT.options = list(pageLength = 5))
df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))

# create 19 breaks and 20 rgb color values ranging from white to red
brks <- quantile(df, probs = seq(.05, .95, .05), na.rm = TRUE)
clrs <- round(seq(255, 40, length.out = length(brks) + 1), 0) %>%
  {paste0("rgb(255,", ., ",", ., ")")}
datatable(df) %>% formatStyle(names(df), backgroundColor = styleInterval(brks, clrs))
</code>```

Will give you a nice interactive html table looking like this

Example from, and for more info, visit:

https://rstudio.github.io/DT/010-style.html

Title: Visualizing a project tracker in R

Body:
Does anyone have any ideas on how to visualize something like this using R?

Basically I want to make a plot to track the percentage completeness of different jobs in a few projects. The percentage completeness should be color coded (in the example, dark blue means the job is 100% complete, white means 0% complete etc.)
Here's some sample code to make the dataframe:

project <- c('Project 1', 'Project 2', 'Project 3', 'Project 4')

job1 <- c(100, 100, NA, 100)

job2 <- c(100, 100, NA, 100)

job3 <- c(100, NA, NA, NA)

job4 <- c(NA, 100, 100, 100)

job5 <- c(50, 100, 100, 100)

job6 <- c(0, 40, 100, 100)

df <- data.frame(project, job1, job2, job3, job4, job5, job6)

I've tried a gantt chart but couldn't get that to work as there is no time data. I've tried a bar chart but that didn't work as some of the projects have NA or 0 values followed by 100/50 etc. so the jobs don't line up. I also tried a heatmap but that doesn't really work either, as there needs to be a visible distinction between the NA values and the 0 values i.e. NA means that a job isn't applicable to that project, whereas 0 means the job hasn't started yet.

Any suggestions would be really appreciated!

Body:
DT (datatable) based solution:

library(DT)
options(DT.options = list(pageLength = 5))
df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))

# create 19 breaks and 20 rgb color values ranging from white to red
brks <- quantile(df, probs = seq(.05, .95, .05), na.rm = TRUE)
clrs <- round(seq(255, 40, length.out = length(brks) + 1), 0) %>%
  {paste0("rgb(255,", ., ",", ., ")")}
datatable(df) %>% formatStyle(names(df), backgroundColor = styleInterval(brks, clrs))

Will give you a nice interactive html table looking like this

Example from, and for more info, visit:

https://rstudio.github.io/DT/010-style.html


问:
adding conditional visibility to WPF control ToolTip
i would like to make a textblock tooltip conditionally visible.

i have the tooltip defined as:

```<code><TextBlock>
    <TextBlock.ToolTip>
        <Grid>...</Grid>
    </TextBlock.ToolTip>
</TextBlock>
</code>```

where would visibility property go in that definition? it doesn't seem to like any of my guesses.

there are some suggestions of just working with grid visibility. the problem with that approach is making the grid invisible will still show empty tooltip box.. which is why i am trying to control tooltip visibility.

答:
The TextBlock with its ToolTip:

```<code><TextBlock Text="{Binding Path=TextBoxText}">
    <TextBlock.ToolTip>
        <ToolTip Visibility="{Binding Path=ToolTipText, Converter={StaticResource StringToVisibilityConverter}}">
            <Grid><TextBlock Text="{Binding Path=ToolTipText}" /></Grid>
        </ToolTip>
    </TextBlock.ToolTip>
</TextBlock>
</code>```

The object to are binding to the TextBlock:

```<code>public class TextBoxBindingObject
{
   public string TextBoxText{ get; set; }
   public string ToolTipText{ get; set; }
}
</code>```

The converter:

```<code>[ValueConversion(typeof(string), typeof(Visibility))]
public class StringToVisibilityConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if(value is string)
        {
            var stringValue = value as string;

            if(!String.IsNullOrEmpty(stringValue))
                return Visibility.Visible;
        }

        return Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i would like to make a textblock tooltip conditionally visible.

i have the tooltip defined as:

<TextBlock>
    <TextBlock.ToolTip>
        <Grid>...</Grid>
    </TextBlock.ToolTip>
</TextBlock>

where would visibility property go in that definition? it doesn't seem to like any of my guesses.

there are some suggestions of just working with grid visibility. the problem with that approach is making the grid invisible will still show empty tooltip box.. which is why i am trying to control tooltip visibility.

Body:
The TextBlock with its ToolTip:

<TextBlock Text="{Binding Path=TextBoxText}">
    <TextBlock.ToolTip>
        <ToolTip Visibility="{Binding Path=ToolTipText, Converter={StaticResource StringToVisibilityConverter}}">
            <Grid><TextBlock Text="{Binding Path=ToolTipText}" /></Grid>
        </ToolTip>
    </TextBlock.ToolTip>
</TextBlock>

The object to are binding to the TextBlock:

public class TextBoxBindingObject
{
   public string TextBoxText{ get; set; }
   public string ToolTipText{ get; set; }
}

The converter:

[ValueConversion(typeof(string), typeof(Visibility))]
public class StringToVisibilityConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if(value is string)
        {
            var stringValue = value as string;

            if(!String.IsNullOrEmpty(stringValue))
                return Visibility.Visible;
        }

        return Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}


问:
React: Updating shared state from one child component has unwanted side effects on other
I'm trying to make a piece of code to allow dynamic rule-making for Trading strategies. When it comes to selecting Indicators to use, I've bumped into a bit of a problem. You don't need to understand anything about Trading to help me out with this. (But to be honest, I know nothing either)

I have the following component, IndicatorSelector, which is the parent component.

```<code>import { Grid, Button, Stack, Typography } from '@mui/material';
import IndicatorBox from './indicatorBox';

export default function IndicatorSelector(props) {
    const [chosenIndicators, setChosenIndicators] = useState([]);

    const availableIndicators = // LOAD THESE FROM LOCAL FILE, EXAMPLE GIVEN BELOW.

    const addIndicator = (val) => {
        const temp = [...chosenIndicators];
        temp.push(val);
        setChosenIndicators(temp);
    }

    const updateOptions = (i, key, value) => {
        const newArray = [...chosenIndicators];
        newArray[i].arguments[key] = value;
        setChosenIndicators(newArray);
    }

    const chooseIndicator = (i, name) => {
        availableIndicators.forEach((val, index) => {
            if (val.name === name) {
                const temp = [...chosenIndicators];
                temp[i] = val;
                console.log("Choosing " + val.name);
                console.log(temp);
                setChosenIndicators(temp);
            }
        })
    }

    const deleteIndicator = (i) => {
        const temp = [...chosenIndicators];
        temp.splice(i, 1);
        setChosenIndicators(temp);
    }

    const handleSubmit = () => {
        if (chosenIndicators.length < 1) {
            alert("Please select an indicator!");
        } else {
            props.onComplete(chosenIndicators);
        }
    }

    return (
        <Stack>
            <Typography variant="h3" sx={{paddingBottom: 5}}>Step 1: Choose Your Indicators</Typography>
            <Grid item xs={12}>
                <Stack>
                    {chosenIndicators.map(
                        (indicator, i) => {
                            return <IndicatorBox key={i} indicator={indicator} chooseIndicator={chooseIndicator} updateOptions={updateOptions} onDelete={deleteIndicator} index={i} available={availableIndicators}></IndicatorBox>
                        }
                    )}
                </Stack>
            </Grid>
            <Grid item xs={12} sx={{display: 'flex', justifyContent: 'space-evenly'}}>
                <Button variant="contained" color="secondary" onClick={() => {addIndicator(availableIndicators[0])}}>Add Another</Button>
                <Button variant="contained" color="success" onClick={handleSubmit}>Submit</Button>
            </Grid>
        </Stack>
    )
}
</code>```

This component displays some buttons to allow you to add more indicators and to submit your choices. Then, the options for selecting indicators are displayed as multiple IndicatorBox components. This component is shown below.

```<code>import { Grid, Select, FormControl, InputLabel, MenuItem, TextField, Box, IconButton, Typography } from '@mui/material';
import ClearIcon from '@mui/icons-material/Clear';

export default function IndicatorBox(props) {

    const choose = (name) => {
        props.chooseIndicator(props.index, name);
    }

    return (
        <Box sx={{bgcolor: '#212121', padding: 1, borderRadius: 2, width: '90vw', diplay: 'flex', justifyContent: 'space-evenly'}}>
            <Grid container>
                <Typography variant="body2">{props.index}</Typography>
                <Grid item xs={11}>
                <FormControl sx={{width: '95%'}}>
                    <InputLabel id="indicator-selector">Indicator</InputLabel>
                    <Select labelId="indicator-selector"
                        value={props.indicator.name}
                        label="Indicator"
                        onChange={(e) => {choose(e.target.value)}}
                    >
                        {props.available.map((object, i) => {
                            return <MenuItem key={object.name} value={object.name}>{object.properName}</MenuItem>
                        })}
                    </Select>
                </FormControl>
                </Grid>
                <Grid item sx={{padding: 1}}>
                    <IconButton onClick={() => props.onDelete(props.index)}>
                        <ClearIcon />
                    </IconButton>
                </Grid>
                { (Object.keys(props.indicator).length > 0) ?
                    <Grid item xs={12} sx={{paddingTop: 1.5}}>
                        {Object.keys(props.indicator.arguments).map((key, i) => {
                            return <TextField
                                key={key}
                                label={key.toUpperCase()}
                                value={props.indicator.arguments[key] ? props.indicator.arguments[key] : 0}
                                variant="outlined"
                                onChange={(e) => props.updateOptions(props.index, key, parseInt(e.target.value))}
                            />
                        })}
                    </Grid>
                 : null}
            </Grid>
        </Box>
    )
}
</code>```

To add further detail, an example of the JSON structure of an 'indicator' is shown below.

```<code>[
    {
        "name": "rsi",
        "properName": "Relative Strength Index",
        "functionName": "talib.RSI",
        "plot": null,
        "data": ["close"],
        "arguments": {
            "timeperiod": 14
        },
        "output": [
            "rsi"
        ]
    }
]
</code>```

When running the code, one is presented with this screen.

When a user clicks "add another", then selects an indicator, the arguments for said indicator pop up underneath it, like so.

Now, here's where the problem arises. If the user selects a second indicator of the same type,  the options values become linked, with both of them changing when the user types in either text field. This occurs no matter how many indicators are selected, as long as two or more are of the same type.

The desired outcome: I want the IndicatorBoxes to have their values be independent of one another, and for the array in IndicatorSelector: 'chosenIndicators', to reflect their true, independent values. I want the user to be able to add as many indicators as they want to the array, with each of them having their own independently customisable options.

EDIT: To clarify, 'availableIndicators' is not a list that is meant to change during execution of the program. Think of it as a 'menu' of indicators that the user can select from. When they choose one, the indicator is found by name from 'availableIndicators', and copied into the array 'chosenIndicators'. I don't think this should affect availableIndicators, but for some reason, chosen indicators seem to be linked when two or more of the same are selected.

This issue has likely been caused by my lack of experience and knowledge with React, so you're more than welcome to rag on my appalling code. In fact, any advice on how to approach this problem better would be appreciated.

答:
This is not really a fulll answer but it way to long for a comment. If I am following your code correctly, it looks like you are filtering the inidicators here:

```<code>const chooseIndicator = (i, name) => {
        availableIndicators.forEach((val, index) => {
            if (val.name === name) {
                const temp = [...chosenIndicators];
                temp[i] = val;
                console.log("Choosing " + val.name);
                console.log(temp);
                setChosenIndicators(temp);
            }
        })
    }
</code>```

So if 2 or more indicators have the same name (you say type I assume you mean name?), Your filter condition is going to match both of them.

Instead of filtering by name you should inject a unique id onto the nested object using a library like uuid that way you can filter by something that you know will be unique .

So when you an indicator is created you would do something like:

```<code>indicatorData.id = uuid()
</code>```

before setting to state

now you can filter through them by something you know is unique.

Also, there is array.find and array.filter methods that are specifically meant for iterating over an array and returning elements based on a condition, no need to do array.forEach followed by an if-else

Body:
I'm trying to make a piece of code to allow dynamic rule-making for Trading strategies. When it comes to selecting Indicators to use, I've bumped into a bit of a problem. You don't need to understand anything about Trading to help me out with this. (But to be honest, I know nothing either)

I have the following component, IndicatorSelector, which is the parent component.

import { Grid, Button, Stack, Typography } from '@mui/material';
import IndicatorBox from './indicatorBox';

export default function IndicatorSelector(props) {
    const [chosenIndicators, setChosenIndicators] = useState([]);

    const availableIndicators = // LOAD THESE FROM LOCAL FILE, EXAMPLE GIVEN BELOW.

    const addIndicator = (val) => {
        const temp = [...chosenIndicators];
        temp.push(val);
        setChosenIndicators(temp);
    }

    const updateOptions = (i, key, value) => {
        const newArray = [...chosenIndicators];
        newArray[i].arguments[key] = value;
        setChosenIndicators(newArray);
    }

    const chooseIndicator = (i, name) => {
        availableIndicators.forEach((val, index) => {
            if (val.name === name) {
                const temp = [...chosenIndicators];
                temp[i] = val;
                console.log("Choosing " + val.name);
                console.log(temp);
                setChosenIndicators(temp);
            }
        })
    }

    const deleteIndicator = (i) => {
        const temp = [...chosenIndicators];
        temp.splice(i, 1);
        setChosenIndicators(temp);
    }

    const handleSubmit = () => {
        if (chosenIndicators.length < 1) {
            alert("Please select an indicator!");
        } else {
            props.onComplete(chosenIndicators);
        }
    }

    return (
        <Stack>
            <Typography variant="h3" sx={{paddingBottom: 5}}>Step 1: Choose Your Indicators</Typography>
            <Grid item xs={12}>
                <Stack>
                    {chosenIndicators.map(
                        (indicator, i) => {
                            return <IndicatorBox key={i} indicator={indicator} chooseIndicator={chooseIndicator} updateOptions={updateOptions} onDelete={deleteIndicator} index={i} available={availableIndicators}></IndicatorBox>
                        }
                    )}
                </Stack>
            </Grid>
            <Grid item xs={12} sx={{display: 'flex', justifyContent: 'space-evenly'}}>
                <Button variant="contained" color="secondary" onClick={() => {addIndicator(availableIndicators[0])}}>Add Another</Button>
                <Button variant="contained" color="success" onClick={handleSubmit}>Submit</Button>
            </Grid>
        </Stack>
    )
}

This component displays some buttons to allow you to add more indicators and to submit your choices. Then, the options for selecting indicators are displayed as multiple IndicatorBox components. This component is shown below.

import { Grid, Select, FormControl, InputLabel, MenuItem, TextField, Box, IconButton, Typography } from '@mui/material';
import ClearIcon from '@mui/icons-material/Clear';

export default function IndicatorBox(props) {

    const choose = (name) => {
        props.chooseIndicator(props.index, name);
    }

    return (
        <Box sx={{bgcolor: '#212121', padding: 1, borderRadius: 2, width: '90vw', diplay: 'flex', justifyContent: 'space-evenly'}}>
            <Grid container>
                <Typography variant="body2">{props.index}</Typography>
                <Grid item xs={11}>
                <FormControl sx={{width: '95%'}}>
                    <InputLabel id="indicator-selector">Indicator</InputLabel>
                    <Select labelId="indicator-selector"
                        value={props.indicator.name}
                        label="Indicator"
                        onChange={(e) => {choose(e.target.value)}}
                    >
                        {props.available.map((object, i) => {
                            return <MenuItem key={object.name} value={object.name}>{object.properName}</MenuItem>
                        })}
                    </Select>
                </FormControl>
                </Grid>
                <Grid item sx={{padding: 1}}>
                    <IconButton onClick={() => props.onDelete(props.index)}>
                        <ClearIcon />
                    </IconButton>
                </Grid>
                { (Object.keys(props.indicator).length > 0) ?
                    <Grid item xs={12} sx={{paddingTop: 1.5}}>
                        {Object.keys(props.indicator.arguments).map((key, i) => {
                            return <TextField
                                key={key}
                                label={key.toUpperCase()}
                                value={props.indicator.arguments[key] ? props.indicator.arguments[key] : 0}
                                variant="outlined"
                                onChange={(e) => props.updateOptions(props.index, key, parseInt(e.target.value))}
                            />
                        })}
                    </Grid>
                 : null}
            </Grid>
        </Box>
    )
}

To add further detail, an example of the JSON structure of an 'indicator' is shown below.

[
    {
        "name": "rsi",
        "properName": "Relative Strength Index",
        "functionName": "talib.RSI",
        "plot": null,
        "data": ["close"],
        "arguments": {
            "timeperiod": 14
        },
        "output": [
            "rsi"
        ]
    }
]

When running the code, one is presented with this screen.

When a user clicks "add another", then selects an indicator, the arguments for said indicator pop up underneath it, like so.

Now, here's where the problem arises. If the user selects a second indicator of the same type,  the options values become linked, with both of them changing when the user types in either text field. This occurs no matter how many indicators are selected, as long as two or more are of the same type.

The desired outcome: I want the IndicatorBoxes to have their values be independent of one another, and for the array in IndicatorSelector: 'chosenIndicators', to reflect their true, independent values. I want the user to be able to add as many indicators as they want to the array, with each of them having their own independently customisable options.

EDIT: To clarify, 'availableIndicators' is not a list that is meant to change during execution of the program. Think of it as a 'menu' of indicators that the user can select from. When they choose one, the indicator is found by name from 'availableIndicators', and copied into the array 'chosenIndicators'. I don't think this should affect availableIndicators, but for some reason, chosen indicators seem to be linked when two or more of the same are selected.

This issue has likely been caused by my lack of experience and knowledge with React, so you're more than welcome to rag on my appalling code. In fact, any advice on how to approach this problem better would be appreciated.

Body:
This is not really a fulll answer but it way to long for a comment. If I am following your code correctly, it looks like you are filtering the inidicators here:

const chooseIndicator = (i, name) => {
        availableIndicators.forEach((val, index) => {
            if (val.name === name) {
                const temp = [...chosenIndicators];
                temp[i] = val;
                console.log("Choosing " + val.name);
                console.log(temp);
                setChosenIndicators(temp);
            }
        })
    }

So if 2 or more indicators have the same name (you say type I assume you mean name?), Your filter condition is going to match both of them.

Instead of filtering by name you should inject a unique id onto the nested object using a library like uuid that way you can filter by something that you know will be unique .

So when you an indicator is created you would do something like:

indicatorData.id = uuid()

before setting to state

now you can filter through them by something you know is unique.

Also, there is array.find and array.filter methods that are specifically meant for iterating over an array and returning elements based on a condition, no need to do array.forEach followed by an if-else


问:
How do I make a helper method available to factories? (Rails, Rspec)
I am attempting to invoke a helper method inside of a factory, but it consistently comes back as method not found. Here is the helper method

/spec/helpers/factories.rb

```<code>module Helpers
  module Factories

    def array_of_fakers(faker_class, field, number_of_elements)
      faker_array = Array.new
      number_of_elements.times do
        factory_array.push(class_eval(faker_class).send(field))
      end
      faker_array
    end

  end
end
</code>```

it is called like this...

```<code>factory :salesman do
    clients { Helpers::Factories.array_of_fakers("Faker::Company", "name", rand(1..5)) }
    ...
end
</code>```

I have tried requiring in rails_helper, spec_helper and the file itself, but all return the same results. I have also tried it without including the module names and just the method name, but that doesn't work either. Is this possible?

答:
You can add this to your spec/factories folder

FactoryBot.define do
  sequence(:id) { SecureRandom.uuid }
  sequence(:email) { Faker::Internet.unique.safe_email }
  sequence(:name) { Faker::Name.name }
end
```
<p>And then just call it in your factories like this:</p>
<pre class="lang-rb prettyprint-override"><code>FactoryBot.define do
  factory :my_factory do
    uuid { generate(:id) }
    name { generate(:name) }
    email { generate(:email) }
...
</code>```

Body:
I am attempting to invoke a helper method inside of a factory, but it consistently comes back as method not found. Here is the helper method

/spec/helpers/factories.rb

module Helpers
  module Factories

    def array_of_fakers(faker_class, field, number_of_elements)
      faker_array = Array.new
      number_of_elements.times do
        factory_array.push(class_eval(faker_class).send(field))
      end
      faker_array
    end

  end
end

it is called like this...

factory :salesman do
    clients { Helpers::Factories.array_of_fakers("Faker::Company", "name", rand(1..5)) }
    ...
end

I have tried requiring in rails_helper, spec_helper and the file itself, but all return the same results. I have also tried it without including the module names and just the method name, but that doesn't work either. Is this possible?

Body:
You can add this to your spec/factories folder

FactoryBot.define do
  sequence(:id) { SecureRandom.uuid }
  sequence(:email) { Faker::Internet.unique.safe_email }
  sequence(:name) { Faker::Name.name }
end

And then just call it in your factories like this:

FactoryBot.define do
  factory :my_factory do
    uuid { generate(:id) }
    name { generate(:name) }
    email { generate(:email) }
...


问:
R: Delete ID if any of the rows within ID contain specific strings (or multiple partial strings) in longitudinal format?
I would like to delete ID in any row that contains certain strings (A or D) within ID.
Here is my data frame:

```<code>id   time   dx
1     1     C
1     2     B
2     1     A
2     2     C
2     3     B
3     1     D
</code>```

I would like the following:

```<code>id    time  dx
 1     1     C
 1     2     B
</code>```

Based on the earlier post regarding this (Delete rows containing specific strings in R), I tried d %>% filter(!grepl('A|D', dx)). However, it only deletes the rows that contain A or D, not the whole IDs. I'd appreciate any help!

##Update: All the below answers worked well for the above post. Thank you all! Note that for this post, I simplified my data frame, and later on, I realized that I actually needed R codes to delete the IDs with certain partial strings (e.g., A or B0) from the following data frame. I was able to achieve this by modifying the first r2evans' answer: d %>% group_by(id) %>% filter(!any(str_detect(dx, "A|B0"))) %>% ungroup(). I have included the note here in case someone needs it. I would appreciate any additional suggestions.

Data frame:

```<code>id time dx
1   1   C01
1   2   B1
2   1   A34
2   2   C01
2   3   B1
3   1   B01X
</code>```

The results I wanted:

```<code>id time dx
1   1   C01
1   2   B1
</code>```

答:
Another base R option using subset + ave

```<code>subset(
  df,
  !ave(dx %in% c("A", "D"), id, FUN = any)
)
</code>```

gives

```<code>  id time dx
1  1    1  C
2  1    2  B
</code>```

Body:
I would like to delete ID in any row that contains certain strings (A or D) within ID.
Here is my data frame:

id   time   dx
1     1     C
1     2     B
2     1     A
2     2     C
2     3     B
3     1     D

I would like the following:

id    time  dx
 1     1     C
 1     2     B

Based on the earlier post regarding this (Delete rows containing specific strings in R), I tried d %>% filter(!grepl('A|D', dx)). However, it only deletes the rows that contain A or D, not the whole IDs. I'd appreciate any help!

##Update: All the below answers worked well for the above post. Thank you all! Note that for this post, I simplified my data frame, and later on, I realized that I actually needed R codes to delete the IDs with certain partial strings (e.g., A or B0) from the following data frame. I was able to achieve this by modifying the first r2evans' answer: d %>% group_by(id) %>% filter(!any(str_detect(dx, "A|B0"))) %>% ungroup(). I have included the note here in case someone needs it. I would appreciate any additional suggestions.

Data frame:

id time dx
1   1   C01
1   2   B1
2   1   A34
2   2   C01
2   3   B1
3   1   B01X

The results I wanted:

id time dx
1   1   C01
1   2   B1

Body:
Another base R option using subset + ave

subset(
  df,
  !ave(dx %in% c("A", "D"), id, FUN = any)
)

gives

  id time dx
1  1    1  C
2  1    2  B


问:
Priority Queue without insertion block
Assuming I have a custom class for which I would like to have a priority queue (having a fixed size, say 100 objects). But the problem with the standard queue.PriorityQueue is that having a maximum size blocks the insertion after the queue is full.

I would like the buffer to still allow for insertions by removing the least priority elements (as decided by my __cmp__(self, other) function implementation) from the queue. Does there exist any built-in implementations of the same?

答:
No, there is no built-in feature for that.

What's more, a priory queue is designed to identify the top priority entry fast, but is not designed to quickly identify which is the item with the least priority. If you would add logic to find it, it would kill the performance of the queue.

I would suggest implementing a so-called min-max heap, which can identify both the least and greatest element in an efficient manner.

On the other hand, if you are only targetting a maximum size of 100 elements, you should probably just work with a list and keep it sorted. For such small lists that will be fast enough, and it is easy to clip the list when it exceeds the maximum size.

Title: Priority Queue without insertion block


问:
Access GCP Secret during Cloud Build build step
Lets say I have a cloudbuild.yaml file that looks like this:

```<code>steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    args: ['build', '-t', 'us.gcr.io/${PROJECT_ID}/image_name', '--build-arg', 'secret=$$SECRET', '.']
    secretEnv: ['SECRET']

images:
  - 'us.gcr.io/${PROJECT_ID}/image_name'

availableSecrets:
  secretManager:
  - versionName: projects/project/secrets/my_secret/versions/latest
    env: 'SECRET'
</code>```

Right now, the --build-arg is assigning to the Docker secret arg the value $SECRET instead of the value actually stored in the secret. How can I access the secret value during this step? All of the examples I can find online say to add a bash entrypoint however only for steps that aren't actually doing the build call.

答:
It's a usual issue with Cloud Build and Secret Manager integration. You can access to the secret only in a script, not in entry-point and arguments (your case)

Try that

```<code>steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    entrypoint: 'bash'
    args:
      - -c
      - |
          docker build -t us.gcr.io/${PROJECT_ID}/image_name --build-arg secret=$$SECRET .
    secretEnv: ['SECRET']
</code>```

Body:
Lets say I have a cloudbuild.yaml file that looks like this:

steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    args: ['build', '-t', 'us.gcr.io/${PROJECT_ID}/image_name', '--build-arg', 'secret=$$SECRET', '.']
    secretEnv: ['SECRET']

images:
  - 'us.gcr.io/${PROJECT_ID}/image_name'

availableSecrets:
  secretManager:
  - versionName: projects/project/secrets/my_secret/versions/latest
    env: 'SECRET'

Right now, the --build-arg is assigning to the Docker secret arg the value $SECRET instead of the value actually stored in the secret. How can I access the secret value during this step? All of the examples I can find online say to add a bash entrypoint however only for steps that aren't actually doing the build call.

Body:
It's a usual issue with Cloud Build and Secret Manager integration. You can access to the secret only in a script, not in entry-point and arguments (your case)

Try that

steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    entrypoint: 'bash'
    args:
      - -c
      - |
          docker build -t us.gcr.io/${PROJECT_ID}/image_name --build-arg secret=$$SECRET .
    secretEnv: ['SECRET']


问:
Drawing a house using python opengl does not display
I want to draw a house with Python OpenGL.
It should look like this:

filled:

unfilled:

Further information: The house should rotate via key input around the x- and y-axis. By pressing the F-key, it should switch between filled and unfilled mode.

My Problem: The window opens up, but I don't see anything on it. I'm not sure what exactly is wrong here or what I'm missing for drawing. Can somebody explain it?

This is my code:

```<code>import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
# from OpenGL.GL import shaders
# from OpenGL.arrays import vbo

# import numpy as np

# general all vertices needed
vertices = (
# front wall
(2, 0, -1, 2, 1, -1, -2, 1, -1, -2, 0, -1),
# back wall
(2, 0, 1, 2, 1, 1, -2, 1, 1, -2, 0, 1, 2, 2, 0, -2, 2, 0),
# roof ridge
(2.2, 2, 0, -2.2, 2, 0),
# roof edges
(2.2, 0.9, -1.1, -2.2, 0.9, -1.1, 2.2, 0.9, 1.1, -2.2, 0.9, 1.1),
# chimney
(1, 0, 0.5, 1.25, 0, 0.5, 1.25, 0, 0.25, 1, 0, 0.25,
 1, 2.5, 0.5, 1.25, 2.5, 0.5, 1.25, 2.5, 0.25, 1, 2.5, 0.25)
)

def DrawHouse():
# house

# back wall
glBegin(GL_LINES)
glColor3f(0.5, 0.5, 0.5)
glVertex3f(2, 0, -1)  # top left
glVertex3f(2, 1, -1)  # top right
glVertex3f(-2, 1, -1)  # bottom right
glVertex3f(-2, 0, -1)  # bottom left
glEnd()

# front wall
glBegin(GL_LINES)
glColor3f(0.5, 0.5, 0.5)
glVertex3f(2, 0, 1)  # top left
glVertex3f(2, 1, 1)  # top right
glVertex3f(-2, 1, 1)  # bottom right
glVertex3f(-2, 0, 1)  # bottom right
glVertex3f(2, 2, 0)   # rooftop
glVertex3f(-2, 2, 0)  # rooftop
glEnd()

# roof
glBegin(GL_LINES)
# roof ridge
glColor3f(0, 0, 0)
glVertex3f(2.2, 2, 0)
glVertex3f(-2.2, 2, 0)
glEnd()

# roof edges
glBegin(GL_TRIANGLES)
glColor3f(0, 0, 0)
glVertex3f(2.2, 0.9, -1.1)
glVertex3f(-2.2, 0.9, -1.1)
glVertex3f(2.2, 0.9, 1.1)
glVertex3f(-2.2, 0.9, 1.1)
glEnd()

# chimney
glBegin(GL_POLYGON)
glColor3f(1, 1, 0)
glVertex3f(1, 0, 0.5)
glVertex3f(1.25, 0, 0.5)
glVertex3f(1.25, 0, 0.25)
glVertex3f(1, 0, 0.25)
glVertex3f(1, 2.5, 0.5)
glVertex3f(1.25, 2.5, 0.5)
glVertex3f(1.25, 2.5, 0.25)
glVertex3f(1, 2.5, 0.25)
glEnd()

def init():
# Switch on z-buffer for calculation of hidden surfaces
glEnable(GL_DEPTH_TEST)

# Display front and back of polygons as border lines only
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

def reshape():
# initialize projection matrix, to 60 degrees horizontal field of view
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, 1.0, 1.0, 200.0)  # angle, aspect, near and far clip

# make modelview matrix the current matrix again
glMatrixMode(GL_MODELVIEW)

def main():
pygame.init()
window = (800, 800)
display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
pygame.display.set_caption('Haus')
clock = pygame.time.Clock()
# GLUT.glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE)  # request render context with z-buffer, doublebuffer for rgb mode
gluOrtho2D(0, 800, 0, 800)

rotX = 0.0
rotY = 0.0
polygonMode = GL_LINE

while True:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    keys = pygame.key.get_pressed()  # checking pressed keys
    if keys[pygame.K_d]:  # The keys 'a' and 'd' should rotate the house around the y-axis
        rotX -= 5
    if keys[pygame.K_a]:
        rotX += 5
    if keys[pygame.K_w]:  # the keys 'w' and 'd' should rotate the house around the x-axis
        rotY -= 5
    if keys[pygame.K_d]:
        rotY += 5
    if keys[pygame.K_f]:  # Key 'f' is to switch between wireframe and filled surfaces
        if polygonMode is GL_FILL:
            polygonMode = GL_LINE
        else:
            polygonMode = GL_FILL

    # Switch polygon display between outline and filled
    glPolygonMode(GL_FRONT_AND_BACK, polygonMode)

    # GLUT.glutPostRedisplay()  # render image again

    # remove Framebuffer and Z-Buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # initialise Modelview Matrix
    glLoadIdentity()

    # execute Modeltransformation
    glTranslatef(0, 0, -3)  # shift by -3 in z-direction
    glRotatef(rotY, 0, 1, 0)  # rotate y-achse
    glRotatef(rotX, 1, 0, 0)  # rotate x-achse
    glTranslatef(-0.5, -0.5, -0.5)  # shift by -0.5 in all directions

    # copy Back-Buffer in Front-Buffer
    # swapBuffers()

    DrawHouse()

    # Show the screen
    pygame.display.flip()

    # callback functions
    # glutReshapeFunc(reshape)

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

答:
The coordinates of your geometry are in range [-2.2, 2.2]. However you set an orthographic projection in range [0, 800]:

gluOrtho2D(0, 800, 0, 800)
```
</blockquote>
<p>Actually there are 3 reasons why you don't see anything</p>
<ol>
<li>That results in only a few pixels being drawn on the bottom left of the screen.</li>
<li><code>gluOrtho2D</code> creates an orthographic projection with a near plane of -1 and a far plane of 1. This will clip your geometry.</li>
<li>You need to choose the <code>GL_PROJECTION</code> for the current matrix. Later in your code, the model view matrix is set to the identity matrix with <code>glLoadIdentity</code>.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def main():
    pygame.init()
    window = (800, 800)
    display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
    pygame.display.set_caption('Haus')
    clock = pygame.time.Clock()

    # gluOrtho2D(0, 800, 0, 800)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-5, 5, -5, 5, -5, 5)
    glMatrixMode(GL_MODELVIEW)

    # [...]
</code>```

Alternatively you can use the perspective projection from the reshape function:

def main():
    pygame.init()
    window = (800, 800)
    display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
    pygame.display.set_caption('Haus')
    clock = pygame.time.Clock()

    # gluOrtho2D(0, 800, 0, 800)

    reshape()

    # [...]
```

Body:
I want to draw a house with Python OpenGL.
It should look like this:

filled:

unfilled:

Further information: The house should rotate via key input around the x- and y-axis. By pressing the F-key, it should switch between filled and unfilled mode.

My Problem: The window opens up, but I don't see anything on it. I'm not sure what exactly is wrong here or what I'm missing for drawing. Can somebody explain it?

This is my code:

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
# from OpenGL.GL import shaders
# from OpenGL.arrays import vbo

# import numpy as np

# general all vertices needed
vertices = (
# front wall
(2, 0, -1, 2, 1, -1, -2, 1, -1, -2, 0, -1),
# back wall
(2, 0, 1, 2, 1, 1, -2, 1, 1, -2, 0, 1, 2, 2, 0, -2, 2, 0),
# roof ridge
(2.2, 2, 0, -2.2, 2, 0),
# roof edges
(2.2, 0.9, -1.1, -2.2, 0.9, -1.1, 2.2, 0.9, 1.1, -2.2, 0.9, 1.1),
# chimney
(1, 0, 0.5, 1.25, 0, 0.5, 1.25, 0, 0.25, 1, 0, 0.25,
 1, 2.5, 0.5, 1.25, 2.5, 0.5, 1.25, 2.5, 0.25, 1, 2.5, 0.25)
)

def DrawHouse():
# house

# back wall
glBegin(GL_LINES)
glColor3f(0.5, 0.5, 0.5)
glVertex3f(2, 0, -1)  # top left
glVertex3f(2, 1, -1)  # top right
glVertex3f(-2, 1, -1)  # bottom right
glVertex3f(-2, 0, -1)  # bottom left
glEnd()

# front wall
glBegin(GL_LINES)
glColor3f(0.5, 0.5, 0.5)
glVertex3f(2, 0, 1)  # top left
glVertex3f(2, 1, 1)  # top right
glVertex3f(-2, 1, 1)  # bottom right
glVertex3f(-2, 0, 1)  # bottom right
glVertex3f(2, 2, 0)   # rooftop
glVertex3f(-2, 2, 0)  # rooftop
glEnd()

# roof
glBegin(GL_LINES)
# roof ridge
glColor3f(0, 0, 0)
glVertex3f(2.2, 2, 0)
glVertex3f(-2.2, 2, 0)
glEnd()

# roof edges
glBegin(GL_TRIANGLES)
glColor3f(0, 0, 0)
glVertex3f(2.2, 0.9, -1.1)
glVertex3f(-2.2, 0.9, -1.1)
glVertex3f(2.2, 0.9, 1.1)
glVertex3f(-2.2, 0.9, 1.1)
glEnd()

# chimney
glBegin(GL_POLYGON)
glColor3f(1, 1, 0)
glVertex3f(1, 0, 0.5)
glVertex3f(1.25, 0, 0.5)
glVertex3f(1.25, 0, 0.25)
glVertex3f(1, 0, 0.25)
glVertex3f(1, 2.5, 0.5)
glVertex3f(1.25, 2.5, 0.5)
glVertex3f(1.25, 2.5, 0.25)
glVertex3f(1, 2.5, 0.25)
glEnd()

def init():
# Switch on z-buffer for calculation of hidden surfaces
glEnable(GL_DEPTH_TEST)

# Display front and back of polygons as border lines only
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

def reshape():
# initialize projection matrix, to 60 degrees horizontal field of view
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, 1.0, 1.0, 200.0)  # angle, aspect, near and far clip

# make modelview matrix the current matrix again
glMatrixMode(GL_MODELVIEW)

def main():
pygame.init()
window = (800, 800)
display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
pygame.display.set_caption('Haus')
clock = pygame.time.Clock()
# GLUT.glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE)  # request render context with z-buffer, doublebuffer for rgb mode
gluOrtho2D(0, 800, 0, 800)

rotX = 0.0
rotY = 0.0
polygonMode = GL_LINE

while True:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    keys = pygame.key.get_pressed()  # checking pressed keys
    if keys[pygame.K_d]:  # The keys 'a' and 'd' should rotate the house around the y-axis
        rotX -= 5
    if keys[pygame.K_a]:
        rotX += 5
    if keys[pygame.K_w]:  # the keys 'w' and 'd' should rotate the house around the x-axis
        rotY -= 5
    if keys[pygame.K_d]:
        rotY += 5
    if keys[pygame.K_f]:  # Key 'f' is to switch between wireframe and filled surfaces
        if polygonMode is GL_FILL:
            polygonMode = GL_LINE
        else:
            polygonMode = GL_FILL

    # Switch polygon display between outline and filled
    glPolygonMode(GL_FRONT_AND_BACK, polygonMode)

    # GLUT.glutPostRedisplay()  # render image again

    # remove Framebuffer and Z-Buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # initialise Modelview Matrix
    glLoadIdentity()

    # execute Modeltransformation
    glTranslatef(0, 0, -3)  # shift by -3 in z-direction
    glRotatef(rotY, 0, 1, 0)  # rotate y-achse
    glRotatef(rotX, 1, 0, 0)  # rotate x-achse
    glTranslatef(-0.5, -0.5, -0.5)  # shift by -0.5 in all directions

    # copy Back-Buffer in Front-Buffer
    # swapBuffers()

    DrawHouse()

    # Show the screen
    pygame.display.flip()

    # callback functions
    # glutReshapeFunc(reshape)

    if __name__ == "__main__":
         main()

Body:
The coordinates of your geometry are in range [-2.2, 2.2]. However you set an orthographic projection in range [0, 800]:

gluOrtho2D(0, 800, 0, 800)

Actually there are 3 reasons why you don't see anything

That results in only a few pixels being drawn on the bottom left of the screen.

gluOrtho2D creates an orthographic projection with a near plane of -1 and a far plane of 1. This will clip your geometry.

You need to choose the GL_PROJECTION for the current matrix. Later in your code, the model view matrix is set to the identity matrix with glLoadIdentity.

def main():
    pygame.init()
    window = (800, 800)
    display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
    pygame.display.set_caption('Haus')
    clock = pygame.time.Clock()

    # gluOrtho2D(0, 800, 0, 800)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-5, 5, -5, 5, -5, 5)
    glMatrixMode(GL_MODELVIEW)

    # [...]

Alternatively you can use the perspective projection from the reshape function:

def main():
    pygame.init()
    window = (800, 800)
    display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
    pygame.display.set_caption('Haus')
    clock = pygame.time.Clock()

    # gluOrtho2D(0, 800, 0, 800)

    reshape()

    # [...]


问:
What are the dimensions, file types, and ppi resolution of an iOS app icon?
What are the specifications for the icons required by Apple for a custom iPhone application published?

57x57, PNG, No Transparency, No Layers, 72 PPI

512x512, TIFF or JPEG, No Transparency, No Layers, 72 PPI

Note: iPhone OS applies rounded corners, optionally shine, and other effects

Also have a large version of your logo with the name of the application in case Apple contacts you needing a version for marketing purposes.

答: This blog post describes all icon sizes and where are they used.</p>

OwnerDisplayName: Jared Brown

LastEditorDisplayName: Jared Brown


问:
change dropdown text colour from selected text
i have a dropdown which contain list of text, then i want have different color of select text and color the text from the dropdown item.

```<code>    DropdownButton<String>(
                          hint: Text(
                            'Topic',
                            style: TextStyle(fontFamily: 'Cairo', fontSize: 20),
                          ),
                          isExpanded: true,
                          value: dropdownValue,
                          dropdownColor: Colors.black,
                          elevation: 4,
//notices 1
                          style: const TextStyle(
                              color: Colors.deepPurple, fontFamily: 'Cairo'),
                          onChanged: (String? newValue) {
                            setState(() {
                              dropdownValue = newValue;
                            });
                          },
                          items: tpoicList
                              .map<DropdownMenuItem<String>>((String value) {
                            return DropdownMenuItem<String>(
                              value: value,
                              child: Container(
                                // alignment: Alignment.centerRight,
                                child: Text(
                                  value,
                                  style: const
//notices 2
TextStyle(color: Colors.black),
                                ),
                              ),
                            );
                          }).toList(),
                        )
</code>```

i notices that in the notice 1 style is also affect the notice 2 style. All i want to is to have different color in the text dropdown and selected text

what i am trying to archive

In the image you will notices the background color is different from the text color also if i select a item from the select item, the text should be in another colors

答:
The DropdownButton has a selectedItemBuilder parameter that should solve your problem. Add something like this to your code:

  selectedItemBuilder: (context) {
    final List<DropdownMenuItem<String>> list = [];
    for (int i = 0; i < tpoicList.lenght; i++) {
      list.add(DropdownMenuItem<String>(
        value: tpoicList[i],
        child: Container(
          child: Text(
            value,
            style: i == dropdownValue?
            [YourNewTextStyle],
            const TextStyle(color: Colors.black),
          ),
        ),
      ));
    }
    return list;
  },

```

Body:
i have a dropdown which contain list of text, then i want have different color of select text and color the text from the dropdown item.

    DropdownButton<String>(
                          hint: Text(
                            'Topic',
                            style: TextStyle(fontFamily: 'Cairo', fontSize: 20),
                          ),
                          isExpanded: true,
                          value: dropdownValue,
                          dropdownColor: Colors.black,
                          elevation: 4,
//notices 1
                          style: const TextStyle(
                              color: Colors.deepPurple, fontFamily: 'Cairo'),
                          onChanged: (String? newValue) {
                            setState(() {
                              dropdownValue = newValue;
                            });
                          },
                          items: tpoicList
                              .map<DropdownMenuItem<String>>((String value) {
                            return DropdownMenuItem<String>(
                              value: value,
                              child: Container(
                                // alignment: Alignment.centerRight,
                                child: Text(
                                  value,
                                  style: const
//notices 2
TextStyle(color: Colors.black),
                                ),
                              ),
                            );
                          }).toList(),
                        )

i notices that in the notice 1 style is also affect the notice 2 style. All i want to is to have different color in the text dropdown and selected text

what i am trying to archive

In the image you will notices the background color is different from the text color also if i select a item from the select item, the text should be in another colors


问:
Protoc on mac os --goout is not recognized as an flag
i'm running osx

```<code>$ uname -rsv
Darwin 21.2.0 Darwin Kernel Version 21.2.0: Sun Nov 28 20:28:54 PST 2021; root:xnu-8019.61.5~1/RELEASE_X86_64
</code>```

installed with brew and from binaries both didn't work

```<code>$ brew install protobuf
</code>```
```<code>$ protoc --version
libprotoc 3.19.4
</code>```

i'm getting an error when i'm trying to generate code using protos and grpc it says --go-out unknown flag

```<code>$ protoc -I protos/ protos/curr.proto --go-out=plugins=grpc:protos/curr
Unknown flag: --go-out
make: *** [protos] Error 1
</code>```

After installing  from pre-compiled binaries ( didn't work )

```<code>$ PB_REL="https://github.com/protocolbuffers/protobuf/releases"
$ curl -LO $PB_REL/download/v3.15.8/protoc-3.15.8-linux-x86_64.zip
$ unzip protoc-3.15.8-linux-x86_64.zip -d $HOME/.local
$ export PATH="$PATH:$HOME/.local/bin"
</code>```

-bash: /$HOME/.local/bin/protoc: cannot execute binary file

Any idea how to solve this ?

答: You need the protoc-gen-go and protoc-gen-grpc plugins as stated on gRPC Go Quickstart</p>

Body:
i'm running osx

$ uname -rsv
Darwin 21.2.0 Darwin Kernel Version 21.2.0: Sun Nov 28 20:28:54 PST 2021; root:xnu-8019.61.5~1/RELEASE_X86_64

installed with brew and from binaries both didn't work

$ brew install protobuf

$ protoc --version
libprotoc 3.19.4

i'm getting an error when i'm trying to generate code using protos and grpc it says --go-out unknown flag

$ protoc -I protos/ protos/curr.proto --go-out=plugins=grpc:protos/curr
Unknown flag: --go-out
make: *** [protos] Error 1

After installing  from pre-compiled binaries ( didn't work )

$ PB_REL="https://github.com/protocolbuffers/protobuf/releases"
$ curl -LO $PB_REL/download/v3.15.8/protoc-3.15.8-linux-x86_64.zip
$ unzip protoc-3.15.8-linux-x86_64.zip -d $HOME/.local
$ export PATH="$PATH:$HOME/.local/bin"

-bash: /$HOME/.local/bin/protoc: cannot execute binary file

Any idea how to solve this ?