问:
How do i print a for i in range loop to a PySimpleGUI window?
I am trying to make a programm that tells you a input amount of the words rhymig with the word you choose. i am doing it in PySimpleGUI and i dont know how to print the loop in to a PySimpleGUI window. Could someone help. Thanks in advance -Josh</p>

```<code>import PySimpleGUI as sg
import requests

layout = [[sg.Text('What would you like to hear rhymes about: '), sg.InputText()],
      [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

rhyme = values[0]

words = requests.get('https://api.datamuse.com/words?rel_rhy=' + rhyme)

words_json = words.json()
window.close()

layout = [[sg.Text(f'How many rhymes about {rhyme} would you like to hear: '), sg.InputText()],
          [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

num = values[0]

window.close()

layout = [[sg.Text(#I dont Know how to print the list here)
</code>```

答:
It was a good exercise for me. Github
I customized this as a reference.</p>

```<code>import PySimpleGUI as sg
import requests
from bs4 import BeautifulSoup
import json

def get_rhyme(rhyme):
    url = ('https://api.datamuse.com/words?rel_rhy={}').format(rhyme)
    words = requests.get(url)
    soup = BeautifulSoup(words.text, 'lxml')
    words_json = []
    words_json = words.json()
    return words_json

def gui():
    layout = [[sg.Text('What would you like to hear rhymes about: ', size=(20,1))],
              [sg.Input('', key='-INPUT-'), sg.Submit(), sg.Cancel()],
              [sg.Output(size=(50,50), key='-OUTPUT-')],
              [sg.Button('Clear'), sg.Button('Exit')]]

    window = sg.Window('Rhyme Search beta', keep_on_top=True, layout=layout)

    output_elem = window.FindElement('-OUTPUT-')

    while True:
        event, values = window.Read()    # read with a 5 second timeout

        print(event, values)
        if event in ('Exit', None):
            break
        elif event == 'Submit':
            out_json = get_rhyme(values['-INPUT-'])
            output_elem.update(out_json)
        elif event == 'Clear':
            window['-OUTPUT-'].update('')

    window.close()

gui()
</code>```

Body:
I am trying to make a programm that tells you a input amount of the words rhymig with the word you choose. i am doing it in PySimpleGUI and i dont know how to print the loop in to a PySimpleGUI window. Could someone help. Thanks in advance -Josh

import PySimpleGUI as sg
import requests

layout = [[sg.Text('What would you like to hear rhymes about: '), sg.InputText()],
      [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

rhyme = values[0]

words = requests.get('https://api.datamuse.com/words?rel_rhy=' + rhyme)

words_json = words.json()
window.close()

layout = [[sg.Text(f'How many rhymes about {rhyme} would you like to hear: '), sg.InputText()],
          [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

num = values[0]

window.close()

layout = [[sg.Text(#I dont Know how to print the list here)

Body:
It was a good exercise for me. Github
I customized this as a reference.

import PySimpleGUI as sg
import requests
from bs4 import BeautifulSoup
import json

def get_rhyme(rhyme):
    url = ('https://api.datamuse.com/words?rel_rhy={}').format(rhyme)
    words = requests.get(url)
    soup = BeautifulSoup(words.text, 'lxml')
    words_json = []
    words_json = words.json()
    return words_json

def gui():
    layout = [[sg.Text('What would you like to hear rhymes about: ', size=(20,1))],
              [sg.Input('', key='-INPUT-'), sg.Submit(), sg.Cancel()],
              [sg.Output(size=(50,50), key='-OUTPUT-')],
              [sg.Button('Clear'), sg.Button('Exit')]]

    window = sg.Window('Rhyme Search beta', keep_on_top=True, layout=layout)

    output_elem = window.FindElement('-OUTPUT-')

    while True:
        event, values = window.Read()    # read with a 5 second timeout

        print(event, values)
        if event in ('Exit', None):
            break
        elif event == 'Submit':
            out_json = get_rhyme(values['-INPUT-'])
            output_elem.update(out_json)
        elif event == 'Clear':
            window['-OUTPUT-'].update('')

    window.close()

gui()


来源: stackexchange

问:
How can i use CodeQL on partial c source code?
I have a partial c source code of a project which as a result i can't build.
Does anyone know if possible to run codeql on that project?

Normally, to create a database, the codeql cli requires to specify the command that builds the project and i wasn't able to bypass that, even though i would say it doesn't look very important being able to build the project.

I could be wrong though, any insights welcome.

答:
CodeQL needs to know how to process each compilation unit you want to analyze, in order to get things like include paths, macros from the compiler command-line, C/C++ dialect and language version, and data model right. Because of this, there's no direct way of importing a project you can't build; interpreting arbitrary partial C/C++ source code accurately is just not possible.

Depending on your exact situation, you may be able to work around in various ways. For example, you could write a bash script that invokes gcc or clang on all the source files you care about, with your best-guess of options that should be passed, and suppressing the error exit code with || true or similar after each command. If you then give this script as the "build command" for CodeQL, it will follow your lead and interpret the code as your compiler invocations would. Even if you get compilation errors, you'll still get a (partial) CodeQL database which you can use.

ContentLicense: CC BY-SA 4.0


问:
What is perform_async in sidekiq
I want to know about perform_async in sidekiq. As I could not found any documentation on this while everyone is using this.

So can someone please explain this to me or provide a resource.

答:
perform_async - a method that push your job with your params in the async queue (create a record in your async backend, Redis by default), to allow Sidekiq catch and perform it on the order of queue

Source: https://github.com/mperham/sidekiq/blob/e2f92e8279d1947aa45eb86acc73f9ebe7a92c9c/lib/sidekiq/worker.rb#L6-L43

Title: What is perform_async in sidekiq


问:
Spark: Merging 2 columns of a DataSet into a single column
I have a table with ids as 2 different columns. I have another table which contains objects associated with the ids. I would like filter out the ids from the table2 for which id exists in either id1 or id2 in Table 1.

Table 1:

```<code>| id1  | id2 |
|  1   |  1  |
|  1   |  1  |
|  1   |  3  |
|  2   |  5  |
|  3   |  1  |
|  3   |  2  |
|  3   |  3  |
</code>```

Table 2:

```<code>| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  4  |  'D'  |
|  5  |  'E'  |
|  6  |  'F'  |
|  7  |  'G'  |
</code>```

What I am thinking is to create out a list from table1 containing the unique ids which will be [1, 2, 3, 5] from above example.

Then filter out the data frame on the basis of the list, which will give the result.

```<code>| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  5  |  'E'  |
</code>```

Though I have concerns regarding the scalability of the solution. The list can be large and it may even fail to load into memory for some cases. Any recommendations here in this case?

Thanks.

答:
Use spark SQL - Note - joins in spark come with a whole set of performance considerations including DF size, key distribution etc. so please familiarise yourself.

Generally though:

```<code>table2.as("t2")
  .join(
    table1.as("t1"),
    $"t2.id" === $"t1.id1" || $"t2.id" === $"t1.id2",
    "left"
  )
  .where($"t1.id1".isNull)
  .select("t2.*")
</code>```

Body:
I have a table with ids as 2 different columns. I have another table which contains objects associated with the ids. I would like filter out the ids from the table2 for which id exists in either id1 or id2 in Table 1.

Table 1:

| id1  | id2 |
|  1   |  1  |
|  1   |  1  |
|  1   |  3  |
|  2   |  5  |
|  3   |  1  |
|  3   |  2  |
|  3   |  3  |

Table 2:

| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  4  |  'D'  |
|  5  |  'E'  |
|  6  |  'F'  |
|  7  |  'G'  |

What I am thinking is to create out a list from table1 containing the unique ids which will be [1, 2, 3, 5] from above example.

Then filter out the data frame on the basis of the list, which will give the result.

| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  5  |  'E'  |

Though I have concerns regarding the scalability of the solution. The list can be large and it may even fail to load into memory for some cases. Any recommendations here in this case?

Thanks.

Body:
Use spark SQL - Note - joins in spark come with a whole set of performance considerations including DF size, key distribution etc. so please familiarise yourself.

Generally though:

table2.as("t2")
  .join(
    table1.as("t1"),
    $"t2.id" === $"t1.id1" || $"t2.id" === $"t1.id2",
    "left"
  )
  .where($"t1.id1".isNull)
  .select("t2.*")


问:
Trying to load chrome webdriver with extension installed,
I'm trying to load my chrome webdriver with extension installed(following the steps mentioned in 'How to load extension within chrome driver in selenium with python') but unable to find the extension installed can you please help me on this, the code I'm trying is.

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_extension('C:/Users/john/Desktop/john/v1.10.0.0.crx')
driver = webdriver.Chrome()
driver.get('https://www.google.co.in')
</code>```

It just launches and opens the chrome webdriver with google page, I'm trying to open with extension installed is this possible using selenium, can anyone help

答:
I can provide you the code written with java, which is working fine</p>

```<code>File file = new File("path_to_your_extension");

String path = file.getAbsolutePath();

ChromeOptions options = new ChromeOptions();

options.addExtensions(new File(path))

WebDriver driver = new ChromeDriver(options);

driver.get("https://www.google.co.in")
</code>```

Body:
I'm trying to load my chrome webdriver with extension installed(following the steps mentioned in 'How to load extension within chrome driver in selenium with python') but unable to find the extension installed can you please help me on this, the code I'm trying is.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_extension('C:/Users/john/Desktop/john/v1.10.0.0.crx')
driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

It just launches and opens the chrome webdriver with google page, I'm trying to open with extension installed is this possible using selenium, can anyone help

Body:
I can provide you the code written with java, which is working fine

File file = new File("path_to_your_extension");

String path = file.getAbsolutePath();

ChromeOptions options = new ChromeOptions();

options.addExtensions(new File(path))

WebDriver driver = new ChromeDriver(options);

driver.get("https://www.google.co.in")


问:
Verifying tokens in real-time to store in NgRx state?
I have an "authenticated" boolean in my NgRx store keeping track of whether a user is valid or not.
But this variable can only be toggled when an action is taken -- logging in, logging out, or sending a POST, for instance -- because I have to verify it on my back-end as well as client-side. Therefor, it cannot be used the way I intend (as a reliable State variable in my Store). I want to know if there is a way to keep this boolean real-time?</p>

答:
Usually you do like that: you have a store for the auth state that has this boolean value with the default value undefined, it means the state isn't clear and all guards and other pieces of the app should wait to the boolean.

When the app is loading you need to verify the auth state via issuing a request /me or /ping for example and based on its response you set the variable to true / false via related actions.

Also you should have an interceptor that knows if a request was declined due to expired / wrong auth state and this interceptor also sets the variable to true / false via related actions.


问:
Function that sorts multiple arguments
I need to write a function sort_gradebook(gradebook), which has next arguments: [first_name, last_name, grade_1, grade_2, ..., grade_n, final_grade]. Function must sort by:

Final grade

If final grades are equal - by first grade

If first grades are equal - by second grade, etc

If all grades are equal - by second name

If second names are equal - by name.

Everything I could do:

```<code>from operator import itemgetter

def sort_gradebook(*gradebook):
    length = len([str(i) for i in gradebook[0]])
    a = [i for i in range(length)]
    for i in a:
        s = sorted(gradebook, key = itemgetter(i))

    return s
</code>```

For test:

```<code>from itertools import permutations

def test_sort(inp, outp):
    for i in permutations(inp):
        assert sort_gradebook(list(i)) == outp

test_sort([['Alice', 'Smith', 2, 3, 4],
    ['John', 'Smith', 2, 3, 5]], [['John', 'Smith', 2, 3, 5],
    ['Alice', 'Smith', 2, 3, 4]
])
</code>```

答:
Sorting

you want to sort on multiple parameters, that are the different indices. You can use itemgetter(0,1,2), and in your case itemgetter(4,3,2,1,0) which need to be built dynamically regarding the size

add reverse=True to get John, who has higher final grade, before Alice

```<code>def sort_gradebooks(*gradebooks):
    nb_attributes = len(gradebooks[0])
    s = itemgetter(*[i for i in range(nb_attributes - 1, -1, -1)]) # itemgetter(4,3,2,1,0)
    return sorted(gradebooks, key=s, reverse=True)
</code>```

Call it

You need to call the sort with *i and i to pass the flatten the parameters and not pass one list, but rather multiple items

```<code>def test_sort(inp, outp):
    for i in permutations(inp):
        print(sort_gradebooks(*i) == outp)
</code>```

```<code>print(sort_gradebooks(*[['Alice', 'Smith', 2, 3, 4], ['John', 'Smith', 2, 3, 5]])) # John / Alice because final grade
print(sort_gradebooks(*[['Alice', 'Smith', 2, 3, 5], ['John', 'Smith', 2, 3, 5]])) # John / Alice because name
print(sort_gradebooks(*[['Alice', 'Smith', 2, 5, 5], ['John', 'Smith', 2, 3, 5]])) # Alice / John because 2ng grade
</code>```

Title: Function that sorts multiple arguments

Body:
I need to write a function sort_gradebook(gradebook), which has next arguments: [first_name, last_name, grade_1, grade_2, ..., grade_n, final_grade]. Function must sort by:

Final grade

If final grades are equal - by first grade

If first grades are equal - by second grade, etc

If all grades are equal - by second name

If second names are equal - by name.

Everything I could do:

from operator import itemgetter

def sort_gradebook(*gradebook):
    length = len([str(i) for i in gradebook[0]])
    a = [i for i in range(length)]
    for i in a:
        s = sorted(gradebook, key = itemgetter(i))

    return s

For test:

from itertools import permutations

def test_sort(inp, outp):
    for i in permutations(inp):
        assert sort_gradebook(list(i)) == outp

test_sort([['Alice', 'Smith', 2, 3, 4],
    ['John', 'Smith', 2, 3, 5]], [['John', 'Smith', 2, 3, 5],
    ['Alice', 'Smith', 2, 3, 4]
])

Body:
Sorting

you want to sort on multiple parameters, that are the different indices. You can use itemgetter(0,1,2), and in your case itemgetter(4,3,2,1,0) which need to be built dynamically regarding the size

add reverse=True to get John, who has higher final grade, before Alice

def sort_gradebooks(*gradebooks):
    nb_attributes = len(gradebooks[0])
    s = itemgetter(*[i for i in range(nb_attributes - 1, -1, -1)]) # itemgetter(4,3,2,1,0)
    return sorted(gradebooks, key=s, reverse=True)

Call it

You need to call the sort with *i and i to pass the flatten the parameters and not pass one list, but rather multiple items

def test_sort(inp, outp):
    for i in permutations(inp):
        print(sort_gradebooks(*i) == outp)

print(sort_gradebooks(*[['Alice', 'Smith', 2, 3, 4], ['John', 'Smith', 2, 3, 5]])) # John / Alice because final grade
print(sort_gradebooks(*[['Alice', 'Smith', 2, 3, 5], ['John', 'Smith', 2, 3, 5]])) # John / Alice because name
print(sort_gradebooks(*[['Alice', 'Smith', 2, 5, 5], ['John', 'Smith', 2, 3, 5]])) # Alice / John because 2ng grade


问:
Unable to resolve deprecation notice with composer
I have asked my hosting provider to switch the operating system on my server from Centos to Ubuntu. Upon downloading all my files from GitHub and running "composer install" I am getting the following error in terminal:

Deprecation Notice: The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence in /usr/share/php/Composer/Downloader/GitDownloader.php:223
  Deprecation Notice: The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence in /usr/share/php/Composer/Downloader/SvnDownloader.php:132

After this composer quits so I need to be able to resolve this not worked around it.

Already tried solutions:

Uninstall and re-install composer.

Upgrade, update, and install commands attempted.

A fresh install of Laravel in case of corruption on Git clone.

答:
If composer self-update is not solve your problem, re-installing composer is best way.

https://getcomposer.org/download/

My composer also gave these errors and self-update not worked.


问:
How to get a precise id from the array of objects?
Making an application (react + redux). It contains a few photos. When you click a photo you get a modal window with bigger photo and comments.

App component is:

```<code>class App extends Component {
  componentDidMount() {
    const { getPhotos } = this.props
    getPhotos()
  }

  getPhoto = (id) => {
    const { openModal } = this.props
    openModal(id)
  }

  render() {
    const { photos, isOpen, isFetching } = this.props
    return (
      <div className="container">
        <Header />
        <div className="list__content">
          {isFetching ? (
            <p>Loading...</p>
          ) : (
            photos.map((photo) => (
              <List
                key={photo.id}
                src={photo.url}
                id={photo.id}
                onClick={this.getPhoto}
              />
            ))
          )}
        </div>
        <Footer />
        {isOpen && <ModalContainer />}
      </div>
    )
  }
}

export default connect(
  ({ photos, modal }) => ({
    photos: photos.photos,
    isFetching: photos.isFetching,
    isOpen: modal.isOpen,
  }),
  { getPhotos, openModal }
)(App)
</code>```

List component:

```<code>const List = ({ src, onClick }) => {
  return (
    <div className="list__item">
      <img src={src} alt={src} onClick={onClick} />
    </div>
  )
}

export default List
</code>```

You can see the prop onClick={this.getPhoto} in the List component. If I change it like this onClick={this.getPhoto(photo.id)} it won't work correctly because it gets id's of all photos and shows them all (one by one) in my modal window.

So, how to get a precise id of the photo in that case with my method getPhoto?

答:
set onClick to function that call getPhoto

```<code>photos.map((photo) => (
  <List
    key={photo.id}
    src={photo.url}
    id={photo.id}
    onClick={() => this.getPhoto(photo.id)}
  />
))
</code>```

Body:
Making an application (react + redux). It contains a few photos. When you click a photo you get a modal window with bigger photo and comments.

App component is:

class App extends Component {
  componentDidMount() {
    const { getPhotos } = this.props
    getPhotos()
  }

  getPhoto = (id) => {
    const { openModal } = this.props
    openModal(id)
  }

  render() {
    const { photos, isOpen, isFetching } = this.props
    return (

          {isFetching ? (

Loading...

          ) : (
            photos.map((photo) => (
              <List
                key={photo.id}
                src={photo.url}
                id={photo.id}
                onClick={this.getPhoto}
              />
            ))
          )}

        {isOpen && <ModalContainer />}

    )
  }
}

export default connect(
  ({ photos, modal }) => ({
    photos: photos.photos,
    isFetching: photos.isFetching,
    isOpen: modal.isOpen,
  }),
  { getPhotos, openModal }
)(App)

List component:

const List = ({ src, onClick }) => {
  return (

  )
}

export default List

You can see the prop onClick={this.getPhoto} in the List component. If I change it like this onClick={this.getPhoto(photo.id)} it won't work correctly because it gets id's of all photos and shows them all (one by one) in my modal window.

So, how to get a precise id of the photo in that case with my method getPhoto?

Body:
set onClick to function that call getPhoto

photos.map((photo) => (
  <List
    key={photo.id}
    src={photo.url}
    id={photo.id}
    onClick={() => this.getPhoto(photo.id)}
  />
))


问:
`flip` function implementation in JavaScript?
Anyone please share the implementation of flip function in JavaScript. What I need is to reverse the first and the second parameters of a function.

Let's assume I have:

```<code>const funcName = (arg1) => (arg2) => (arg3) => { ... }
</code>```

I want it turns to:

```<code>const funcName = (arg2) => (arg1) => (arg3) => { ... }
</code>```

And like this:

```<code>const funcName = (arg3) => (arg2) => (arg1) => { ... }
</code>```

答:
From https://github.com/ramda/ramda/blob/master/source/flip.js

You could do something like this

function flip(fn) {
   return function(a, b) {
       var args = Array.prototype.slice.call(arguments, 0);
       args[0] = b;
       args[1] = a;
       return fn.apply(this, args);
   }
}
```

Body:
Anyone please share the implementation of flip function in JavaScript. What I need is to reverse the first and the second parameters of a function.

Let's assume I have:

const funcName = (arg1) => (arg2) => (arg3) => { ... }

I want it turns to:

const funcName = (arg2) => (arg1) => (arg3) => { ... }

And like this:

const funcName = (arg3) => (arg2) => (arg1) => { ... }


问:
How to search for patterns that are not exactly same each time?
I have a list like this:

```<code> list <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )
</code>```

The searching patter in this case is "any-number cut".  Thus, to visualize the list in a better way, the list is in the following pattern

```<code>"before item (=xxx) "  "any number cut (= 23 cut)"
"after item (=yyy)"
"after item (=zzz)"
"before item (=www) "  "any number cut (= 55 cut)"
"after item (=kkk)"
"after item (=ggg)"
"after items (=yyy)"
"before item (=eee) "  "any number cut (= 7cut)"
"after item (=cce)"
</code>```

I want place the "before items" to column 1, until it found another "any number cut" pattern, and put the "after items" to column 2.  The final results would as follows:

```<code>xxx yyy
xxx zzz
www kkk
www ggg
www yyy
eee ccd
</code>```

Could experts teach me how to do it with R?  I learn from previous stackoverflow messages that R can search for fixed items (e.g. cut) and strsplit them into different cells.  The challenge here (to me) is the searching pattern is changing that the number before the word "cut" is different for each of them.  what is the most efficient way to search and cut it in the right place using R?

答:
Below we use x to represent your list variable. " \d+ cut$" matches any string with space, digits, space and cut at the end so that no.cut is a logical vector that is TRUE for each component of x with no cut. We then pick out the first word of each component by removing the first space and  everything after it.  This gives first.word.  Finally we replace each component of first.word with NA if it has no cut and use na.locf from the zoo package to move the remaining words (the ones that were not replaced by NA) forward into the NA spots to give us the tentative before vector.  We use first.word as the tentative after vector.  The positions corresponding to no.cut in the tentative  before and after vectors form the required result.   This works with your example data.  Depending on the precise nature of your actual data you may need to revise some of this slightly; however, the overall pattern of the solution should still hold.

```<code>> library(zoo)
> no.cut <- !grepl(" \\d+ cut$", x)
> first.word <- sub(" .*", "", x)
> cbind(before = na.locf(replace(first.word, no.cut, NA)),
+  after = first.word)[no.cut, ]
     before after
[1,] "xxx"  "yyy"
[2,] "xxx"  "zzz"
[3,] "www"  "kkk"
[4,] "www"  "ggg"
[5,] "www"  "yyy"
[6,] "eee"  "ccd"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list like this:

 list <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )

The searching patter in this case is "any-number cut".  Thus, to visualize the list in a better way, the list is in the following pattern

"before item (=xxx) "  "any number cut (= 23 cut)"
"after item (=yyy)"
"after item (=zzz)"
"before item (=www) "  "any number cut (= 55 cut)"
"after item (=kkk)"
"after item (=ggg)"
"after items (=yyy)"
"before item (=eee) "  "any number cut (= 7cut)"
"after item (=cce)"

I want place the "before items" to column 1, until it found another "any number cut" pattern, and put the "after items" to column 2.  The final results would as follows:

xxx yyy
xxx zzz
www kkk
www ggg
www yyy
eee ccd

Could experts teach me how to do it with R?  I learn from previous stackoverflow messages that R can search for fixed items (e.g. cut) and strsplit them into different cells.  The challenge here (to me) is the searching pattern is changing that the number before the word "cut" is different for each of them.  what is the most efficient way to search and cut it in the right place using R?

Body:
Below we use x to represent your list variable. " \d+ cut$" matches any string with space, digits, space and cut at the end so that no.cut is a logical vector that is TRUE for each component of x with no cut. We then pick out the first word of each component by removing the first space and  everything after it.  This gives first.word.  Finally we replace each component of first.word with NA if it has no cut and use na.locf from the zoo package to move the remaining words (the ones that were not replaced by NA) forward into the NA spots to give us the tentative before vector.  We use first.word as the tentative after vector.  The positions corresponding to no.cut in the tentative  before and after vectors form the required result.   This works with your example data.  Depending on the precise nature of your actual data you may need to revise some of this slightly; however, the overall pattern of the solution should still hold.

> library(zoo)
> no.cut <- !grepl(" \\d+ cut$", x)
> first.word <- sub(" .*", "", x)
> cbind(before = na.locf(replace(first.word, no.cut, NA)),
+  after = first.word)[no.cut, ]
     before after
[1,] "xxx"  "yyy"
[2,] "xxx"  "zzz"
[3,] "www"  "kkk"
[4,] "www"  "ggg"
[5,] "www"  "yyy"
[6,] "eee"  "ccd"


问:
Why do I get Call to function "file" failed: no file exists?
I've created a straighforward module:

```<code>.
├── inputs.tf
└── main.tf
</code>```

Input variables are declared in inputs.tf:

```<code>variable "workers" {
    type = number
    description = "Amount of spark workers"
}
variable "values_values_path" {}
</code>```

main.tf is:

```<code>resource "helm_release" "spark" {
    name       = "spark"
    repository = "https://charts.bitnami.com/bitnami"
    chart      = "spark"
    version    = "1.2.21"
    namespace  = ...

    set {
        name  = "worker.replicaCount"
        value = var.workers
    }

    values = [
        "${file("${var.custom_values_path}")}"
    ]
}
</code>```

As you can see I'm trying to deploy a helm release. I'd like to set a custom values file parameterized as custom_values_path:

```<code>.
├── main.tf
├── provider.tf
└── spark-values.yaml
</code>```

My main.tf here is:

```<code>module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values_path = "./spark_values.yaml"
}
</code>```

However, I'm getting:

```<code>Error: Error in function call

  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.
</code>```

Complete directory structure is:

```<code>.
├── stash
│   ├── main.tf
│   ├── provider.tf
│   └── spark-values.yaml
└── modules
    └── spark
        ├── inputs.tf
        └── main.tf
</code>```

When I perform terraform plan I'm in ./stash.

So complete commands would be:

$ > cd ./stash
   $ stash > terraform plan
    Error: Error in function call

```<code>  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.
</code>```

Why do I get Call to function "file" failed: no file exists?

答:
I think what I happening here is a problem with the relative path. You are passing the variable to the module and relative to the module path, the file spark_values.yaml is located at "../../stash/spark_values.yaml".

When working with the file module, I usually use ${path.module}. I would name the variable just as the file name: spark_values.yaml. Then I would call it as follows: file("${path.module}/${var.file_name}". Can you double check if that works for your case?

Body:
I've created a straighforward module:

.
├── inputs.tf
└── main.tf

Input variables are declared in inputs.tf:

variable "workers" {
    type = number
    description = "Amount of spark workers"
}
variable "values_values_path" {}

main.tf is:

resource "helm_release" "spark" {
    name       = "spark"
    repository = "https://charts.bitnami.com/bitnami"
    chart      = "spark"
    version    = "1.2.21"
    namespace  = ...

    set {
        name  = "worker.replicaCount"
        value = var.workers
    }

    values = [
        "${file("${var.custom_values_path}")}"
    ]
}

As you can see I'm trying to deploy a helm release. I'd like to set a custom values file parameterized as custom_values_path:

.
├── main.tf
├── provider.tf
└── spark-values.yaml

My main.tf here is:

module "spark" {
    source = "../modules/spark"

    workers = 1
    custom_values_path = "./spark_values.yaml"
}

However, I'm getting:

Error: Error in function call

  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.

Complete directory structure is:

.
├── stash
│   ├── main.tf
│   ├── provider.tf
│   └── spark-values.yaml
└── modules
    └── spark
        ├── inputs.tf
        └── main.tf

When I perform terraform plan I'm in ./stash.

So complete commands would be:

$ > cd ./stash
   $ stash > terraform plan
    Error: Error in function call

  on ../modules/spark/main.tf line 14, in resource "helm_release" "spark":
  14:         "${file("${var.custom_values_path}")}"
    |----------------
    | var.custom_values_path is "./spark_values.yaml"

Call to function "file" failed: no file exists at spark_values.yaml.

Why do I get Call to function "file" failed: no file exists?


问:
Two Dependent Combo Boxes

**Edit:** Managed to find the solution to it thanks to fellow user @Tin Bum

I'm trying to make 2 Combo Box where the the first one (Cmb1) will show only unique values from Column 1 and then (Cmb2) will show a list of values from Column 2 that are related to Column 1.

Populating the Cmb1 has been successful however the problem lies with populating Cmb2.
```<code>Column 1    Column 2
1             a
1             b
1             c
2             d
2             e
</code>```

The problem lies with populating Cmb2

```<code>Private Sub UserForm_Activate()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")
With wslk
t1 = .Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).row

On Error Resume Next
For y = 2 To t1
Set c = .Cells(y, 2)
Set t1rng = .Range(.Cells(2, 2), .Cells(y, 2))
x = Application.WorksheetFunction.CountIf(t1rng, c)
If x = 1 Then Cmb1.AddItem c
Next y
On Error GoTo 0
End With

End Sub

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Cmb2.ListIndex = -1
If Cmb1.ListIndex > -1 Then
'Currently I am stuck over here
Cmb2.List =

**Solution:**
Dim i As Integer
    Cmb2.Clear

For i = 2 To wslk.Range("B" & Application.Rows.Count).End(xlUp).row
    If wslk.Range("B" & i).Value = Cmb1.Value Then
    Cmb2.AddItem wslk.Range("C" & i)
End If

End If
End Sub
</code>```

答:
You could use a Dictionary to get your unique values and also populate this on your Initialize Sub. Making this a Public variable in the scope of the Userform will allow you to then use it later on the Change event as well to get your list values

```<code>Option Explicit
Private Uniques As Object
Private Sub UserForm_Initialize()
    Dim c As Range, InputRng As Range
    Dim tmp As Variant
    Dim k As String

    Set Uniques = CreateObject("Scripting.Dictionary")
    With Worksheets("w1")
        Set InputRng = .Range(.Cells(2, 2), .Cells(.Cells(.Rows.Count, 2).End(xlUp).Row, 2))

        For Each c In InputRng
            k = c.Value2
            If Uniques.exists(k) Then
                tmp = Uniques(k)
                ReDim Preserve tmp(LBound(tmp) To UBound(tmp) + 1)
                tmp(UBound(tmp)) = c.Offset(0, 1).Value2
                Uniques(k) = tmp
            Else
                ReDim tmp(0)
                tmp(0) = c.Offset(0, 1).Value2
                Uniques.Add Key:=k, Item:=tmp
            End If
        Next c

        Cmb1.List = Uniques.keys
    End With

End Sub
Private Sub Cmb1_Change()
    Cmb2.ListIndex = -1
    If Cmb1.ListIndex > -1 Then
        Cmb2.List = Uniques(Cmb1.Value)
    End If
End Sub
</code>```

Title: Two Dependent Combo Boxes

Body:
**Edit:** Managed to find the solution to it thanks to fellow user @Tin Bum

I'm trying to make 2 Combo Box where the the first one (Cmb1) will show only unique values from Column 1 and then (Cmb2) will show a list of values from Column 2 that are related to Column 1.

Populating the Cmb1 has been successful however the problem lies with populating Cmb2.

Column 1    Column 2
1             a
1             b
1             c
2             d
2             e

The problem lies with populating Cmb2

Private Sub UserForm_Activate()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")
With wslk
t1 = .Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).row

On Error Resume Next
For y = 2 To t1
Set c = .Cells(y, 2)
Set t1rng = .Range(.Cells(2, 2), .Cells(y, 2))
x = Application.WorksheetFunction.CountIf(t1rng, c)
If x = 1 Then Cmb1.AddItem c
Next y
On Error GoTo 0
End With

End Sub

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Cmb2.ListIndex = -1
If Cmb1.ListIndex > -1 Then
'Currently I am stuck over here
Cmb2.List =

**Solution:**
Dim i As Integer
    Cmb2.Clear

For i = 2 To wslk.Range("B" & Application.Rows.Count).End(xlUp).row
    If wslk.Range("B" & i).Value = Cmb1.Value Then
    Cmb2.AddItem wslk.Range("C" & i)
End If

End If
End Sub

Body:
You could use a Dictionary to get your unique values and also populate this on your Initialize Sub. Making this a Public variable in the scope of the Userform will allow you to then use it later on the Change event as well to get your list values

Option Explicit
Private Uniques As Object
Private Sub UserForm_Initialize()
    Dim c As Range, InputRng As Range
    Dim tmp As Variant
    Dim k As String

    Set Uniques = CreateObject("Scripting.Dictionary")
    With Worksheets("w1")
        Set InputRng = .Range(.Cells(2, 2), .Cells(.Cells(.Rows.Count, 2).End(xlUp).Row, 2))

        For Each c In InputRng
            k = c.Value2
            If Uniques.exists(k) Then
                tmp = Uniques(k)
                ReDim Preserve tmp(LBound(tmp) To UBound(tmp) + 1)
                tmp(UBound(tmp)) = c.Offset(0, 1).Value2
                Uniques(k) = tmp
            Else
                ReDim tmp(0)
                tmp(0) = c.Offset(0, 1).Value2
                Uniques.Add Key:=k, Item:=tmp
            End If
        Next c

        Cmb1.List = Uniques.keys
    End With

End Sub
Private Sub Cmb1_Change()
    Cmb2.ListIndex = -1
    If Cmb1.ListIndex > -1 Then
        Cmb2.List = Uniques(Cmb1.Value)
    End If
End Sub


问:
How to limit width of multiple TextFields inside a Column? Wrapping the latter with a SizedBox doesn't work
This is my tree:

Scaffold(-> Column(-> Expanded(-> ListView(-> Column(-> TextFields)))));

I want to limit the width of these TextFields (say, to 200px), but using SizedBox/Container/ConstrainedBox and setting a width/maxWidth on the Column isn't working; I have to wrap each individual TextField with a SizedBox for it to work- which adds a lot of fluff to my code.

Is there a better way to do this?

答:
The issue is that TextField don't have a defined width so the Column doesn't know how to handle it and the Column needs to know the size of its child elements to properly render them. You best bet is wrapping your TextField in:
 1. An Expanded widget (here the TextField will expand to fill the
    available space)
 2. A Flexible widget, or
 3. Better still wrap it in a Container since you already know the width
    you want (i.e. 200px).</p>


问:
How to extract UK postcodes from an address column in a pandas DataFrame?
I have a DataFrame that contains information, in particular addresses like the DataFrame below:

```<code>    col1   col2
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE
</code>```

These are all different formats, with some having commas and others not, and there are also examples of addresses from other countries. I was wondering how would I extract the addresses from here as I want to merge them with location data.

This could mean a merge on substring or just extracting the

I have tried:

```<code>df["postcodes"] = df["address"].str.extract(r'^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$')
</code>```

to extract the postcodes but this doesn't seem to work coming up with the error of 9 arguments given where 1 should be taken.

I have also attempted:

```<code>rhs = (df1.address
          .apply(lambda x: df2[df2.Postcode.str.find(x).ge(0)]['location'])
          .bfill(axis=1)
          .iloc[:, 0])

(pd.concat([df1.app_nbr, rhs], axis=1, ignore_index=True)
 .rename(columns={0: 'app_nbr', 1: 'location'}))
</code>```

from here: How to merge pandas on string contains? but it is taking a long time to run on my machine given there are 1.7million postcodes in the second dataframe to match on.

The expected output would be either:

```<code>    col1   col2                                                  col3
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY   CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       CD7 9HE
</code>```

Or (matching with the second dataframe based on postcode):

```<code>    col1   col2                                              col3 (coords)
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   50.00, 1.00
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       51.23, 1.05
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            54.65, 1.07
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY    51.23, 0.95
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               54.6,  2.23
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       49.25, 1.23
</code>```

Any help would be appreciated or to be pointed in the right direction.

Thank you

*addresses have been altered so are not real but the format is the same

答:
If you always need the 2 last values , convert string to list by using split , and take the last two values in the list .

Adress="Yellow Gardens,Tunbridge Wells, Kent TN5 4NP"

Adresslist=Adress.split()

Zip = Adresslist[len(Adresslist)-1]+" "+ Adresslist[len(Adresslist)]

Body:
I have a DataFrame that contains information, in particular addresses like the DataFrame below:

    col1   col2
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE

These are all different formats, with some having commas and others not, and there are also examples of addresses from other countries. I was wondering how would I extract the addresses from here as I want to merge them with location data.

This could mean a merge on substring or just extracting the

I have tried:

df["postcodes"] = df["address"].str.extract(r'^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$')

to extract the postcodes but this doesn't seem to work coming up with the error of 9 arguments given where 1 should be taken.

I have also attempted:

rhs = (df1.address
          .apply(lambda x: df2[df2.Postcode.str.find(x).ge(0)]['location'])
          .bfill(axis=1)
          .iloc[:, 0])

(pd.concat([df1.app_nbr, rhs], axis=1, ignore_index=True)
 .rename(columns={0: 'app_nbr', 1: 'location'}))

from here: How to merge pandas on string contains? but it is taking a long time to run on my machine given there are 1.7million postcodes in the second dataframe to match on.

The expected output would be either:

    col1   col2                                                  col3
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY   CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       CD7 9HE

Or (matching with the second dataframe based on postcode):

    col1   col2                                              col3 (coords)
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   50.00, 1.00
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       51.23, 1.05
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            54.65, 1.07
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY    51.23, 0.95
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               54.6,  2.23
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       49.25, 1.23

Any help would be appreciated or to be pointed in the right direction.

Thank you

*addresses have been altered so are not real but the format is the same


问:
How to style Ionic input type file as a Button
I want to style a ionic file chooser button. </p>

```<code><input type="file" id="myFileInput">
</code>```

<p>But Ionic don't have an Input type file button.
So how can I get a better looking button than the standard Button with a Choose a File text ? </p>

答:
what about this kind of solution (it worked for me):

```<code> <ion-button (click)="f.click">Upload</ion-button
</code>```

```<code>.inputFile {
   width: 0;
   height: 0;
 }
</code>```

& style your button as you like, if you click on the ion-button you will actually click on the input file

Body:
I want to style a ionic file chooser button.

<input type="file" id="myFileInput">

But Ionic don't have an Input type file button.
So how can I get a better looking button than the standard Button with a Choose a File text ?

Body:
what about this kind of solution (it worked for me):

 <ion-button (click)="f.click">Upload</ion-button

.inputFile {
   width: 0;
   height: 0;
 }

& style your button as you like, if you click on the ion-button you will actually click on the input file


问:
Why an error is being showed on top when I open my settings on Google Play Console?
When I go to settings of google play console I see an error on top saying "An unexpected error occurred. Please try again later. (4600000)". I am assuming it is because of a problem with my merchant account.

In "Account details" tab of settings my merchant account is showing active status.

But in "Payment settings" tab an error is shown saying "Uh oh. There was a problem.
This payments profile has been closed. To continue paying, contact the Support team for this product. [OR-CAC-13]"

Previously I deleted this email account and recently recovered it. Is this the reason behind my described problem?
If so, how can I get recovered from it and add a new merchant account to it?

I am providing necessary screenshots:

Image of "Account details" tab of settings

Image of "Payment settings" tab of settings

答: The problem was automatically solved after chatting with google support team about my problem.</p>


问:
Should I stop breaking .NET events guidelines?
Over and over I find myself implementing events in C# following the guidelines and then falling back to a simpler implementation using just Action when the client code does not need any of the benefits added by the guidelines.

Arguably, I'll add that omitting the sender object unless it is actually required is a good thing because it promotes decoupling of triggers and handlers. More in general, I think it is a good habit to avoid writing code that is not needed.

I don't mean that the guidelines should be always dismissed, there are benefits in following them (see links below). My question is if I should always follow it.

The example below shows how terse the "naive events" patterns is compared to the guidelines pattern.

```<code>// This is neat
class NaiveEvents
{
    public event Action<string> OnAlert;
    public void TriggerOnAlert(string message)
    {
        OnAlert(message);
    }
}

// Is this bloated?
class ProperEvents
{
    public event EventHandler<OnAlertEventArgs> OnAlertEvent;

    public void TriggerOnAlert(string message)
    {
        OnAlertEvent(this, new OnAlertEventArgs(message));
    }

    public class OnAlertEventArgs : EventArgs
    {
        private readonly string _message;
        public OnAlertEventArgs(string message)
        {
            _message = message;
        }
        public string Message { get { return _message; } }
    }
}

class EventsDemo
{
    public static void DemoNaiveEvents()
    {
        var ev = new NaiveEvents();
        ev.OnAlert += (msg) => { Console.WriteLine(msg); };
        ev.TriggerOnAlert("Hello World");
    }

    public static void DemoProperEvents()
    {
        var ev = new ProperEvents();
        ev.OnAlertEvent += (sender, args) => Console.WriteLine(args.Message);
        ev.TriggerOnAlert("Hello World");
    }
}
</code>```

See the Guidelines: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx

Benefits: What are the benefits of having events conforming to Net guidelines?

Thanks!

答:
From my point of view the biggest benefit of following the pattern is that you can have interchangeable event handlers. For example if you have defined a

```<code>public void OnClick(object sender, EventArgs e)
</code>```

method that handles a click event somewhere it would be trivial to wire it to your OnAlert event if needed without having to wrap the signature. This is however trivial to do in C# > 3.0 using lambdas so the gain can be small. Back in the day before anonymous delegates this was harder to do so it made sense to follow the guideline

Body:
Over and over I find myself implementing events in C# following the guidelines and then falling back to a simpler implementation using just Action when the client code does not need any of the benefits added by the guidelines.

Arguably, I'll add that omitting the sender object unless it is actually required is a good thing because it promotes decoupling of triggers and handlers. More in general, I think it is a good habit to avoid writing code that is not needed.

I don't mean that the guidelines should be always dismissed, there are benefits in following them (see links below). My question is if I should always follow it.

The example below shows how terse the "naive events" patterns is compared to the guidelines pattern.

// This is neat
class NaiveEvents
{
    public event Action<string> OnAlert;
    public void TriggerOnAlert(string message)
    {
        OnAlert(message);
    }
}

// Is this bloated?
class ProperEvents
{
    public event EventHandler<OnAlertEventArgs> OnAlertEvent;

    public void TriggerOnAlert(string message)
    {
        OnAlertEvent(this, new OnAlertEventArgs(message));
    }

    public class OnAlertEventArgs : EventArgs
    {
        private readonly string _message;
        public OnAlertEventArgs(string message)
        {
            _message = message;
        }
        public string Message { get { return _message; } }
    }
}

class EventsDemo
{
    public static void DemoNaiveEvents()
    {
        var ev = new NaiveEvents();
        ev.OnAlert += (msg) => { Console.WriteLine(msg); };
        ev.TriggerOnAlert("Hello World");
    }

    public static void DemoProperEvents()
    {
        var ev = new ProperEvents();
        ev.OnAlertEvent += (sender, args) => Console.WriteLine(args.Message);
        ev.TriggerOnAlert("Hello World");
    }
}

See the Guidelines: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx

Benefits: What are the benefits of having events conforming to Net guidelines?

Thanks!

Body:
From my point of view the biggest benefit of following the pattern is that you can have interchangeable event handlers. For example if you have defined a

public void OnClick(object sender, EventArgs e)

method that handles a click event somewhere it would be trivial to wire it to your OnAlert event if needed without having to wrap the signature. This is however trivial to do in C# > 3.0 using lambdas so the gain can be small. Back in the day before anonymous delegates this was harder to do so it made sense to follow the guideline


问:
TypeError: Cannot read property 'state' of undefined, even though already binded
im trying to print a state in my reactjs web page, i already bind the function just like the other answer says but it still gave me the same error, here is my code

```<code>export class Tambah extends React.Component{
  constructor(){
    super();
    this.add = this.add.bind(this);
  }

  add(event){
    this.setState({company: event.target.value})
  }
}

function FormTambah(){
  return(
    <div className="konten container-sm">
    <br></br><br></br>
    <div className="tabel card rounded">
      <div className="card-body">
      <p className="head panel-body">Add User</p>
      <br/><br/>
      <form>
        <p>Email*</p>
        <input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>
        <br/>
        <p>Full Name*</p>
        <input type="text" className="email form-control col-sm-7" placeholder="Enter Fullname" onChange={this.FullName}></input>
        <br/>
        <div className="stat custom-control custom-switch">
          <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1"/>
          <label className="custom-control-label" for="customSwitch1">Active Status</label>
        </div>
        <br/>
        <button type="submit" className="submit btn col-sm-1">Save</button>
      </form>
    </div>
      </div>
    </div>
  )
}
</code>```

the error happens right here :

```<code><input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>
</code>```

i already bind the add method after i saw the other question but it still gave me the same error, thanks before, any help will be appreciated

答:
Put FormTambah into render:

```<code>export class Tambah extends React.Component {
    constructor() {
        super();
        this.add = this.add.bind(this);
    }

    add(event) {
        this.setState({ company: event.target.value });
    }

    render() {
        return (
            <div className="konten container-sm">
                <br></br>
                <br></br>
                <div className="tabel card rounded">
                    <div className="card-body">
                        <p className="head panel-body">Add User</p>
                        <br />
                        <br />
                        <form>
                            <p>Email*</p>
                            <input
                                type="text"
                                value={this.state.company}
                                onChange={this.add}
                                className="email form-control col-sm-6"
                            />
                            <br />
                            <p>Full Name*</p>
                            <input
                                type="text"
                                className="email form-control col-sm-7"
                                placeholder="Enter Fullname"
                                onChange={this.FullName}
                            ></input>
                            <br />
                            <div className="stat custom-control custom-switch">
                                <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1" />
                                <label className="custom-control-label" htmlFor="customSwitch1">
                                    Active Status
                                </label>
                            </div>
                            <br />
                            <button type="submit" className="submit btn col-sm-1">
                                Save
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        );
    }
}
</code>```

Body:
im trying to print a state in my reactjs web page, i already bind the function just like the other answer says but it still gave me the same error, here is my code

export class Tambah extends React.Component{
  constructor(){
    super();
    this.add = this.add.bind(this);
  }

  add(event){
    this.setState({company: event.target.value})
  }
}

function FormTambah(){
  return(

Add User

      <form>

Email*

        <input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>

Full Name*

        <input type="text" className="email form-control col-sm-7" placeholder="Enter Fullname" onChange={this.FullName}></input>

          <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1"/>
          Active Status

        <button type="submit" className="submit btn col-sm-1">Save</button>
      </form>

  )
}

the error happens right here :

<input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>

i already bind the add method after i saw the other question but it still gave me the same error, thanks before, any help will be appreciated

Body:
Put FormTambah into render:

export class Tambah extends React.Component {
    constructor() {
        super();
        this.add = this.add.bind(this);
    }

    add(event) {
        this.setState({ company: event.target.value });
    }

    render() {
        return (
            <div className="konten container-sm">
                <br></br>
                <br></br>
                <div className="tabel card rounded">
                    <div className="card-body">
                        <p className="head panel-body">Add User</p>
                        <br />
                        <br />
                        <form>
                            <p>Email*</p>
                            <input
                                type="text"
                                value={this.state.company}
                                onChange={this.add}
                                className="email form-control col-sm-6"
                            />
                            <br />
                            <p>Full Name*</p>
                            <input
                                type="text"
                                className="email form-control col-sm-7"
                                placeholder="Enter Fullname"
                                onChange={this.FullName}
                            ></input>
                            <br />
                            <div className="stat custom-control custom-switch">
                                <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1" />
                                <label className="custom-control-label" htmlFor="customSwitch1">
                                    Active Status
                                </label>
                            </div>
                            <br />
                            <button type="submit" className="submit btn col-sm-1">
                                Save
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        );
    }
}


问:
Synchronization and/or mutual exclusion for storage class in services
I need to concurrently read and write a common file with different jobIntentServices in my APP. One service (producer) writes data in the file, while another service (consumer) checks if there is data in the shared file. If there is data, it sends it and, if the data transfer was successful, it deletes the file. I have created the following storage controller class:

```<code>public class Storage {
private static final String TAG = "Storage";

public void writeToFile(String filePath, String data, Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filePath, Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e(TAG, "File write failed: " + e.toString());
    }
}

public String readFromFile(String filePath, Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput(filePath);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "Can not read file: " + e.toString());
    }

    return ret;
}

public boolean fileExists(String filename, Context context) {
    File file = context.getFileStreamPath(filename);
    if(file == null || !file.exists()) {
        return false;
    }
    return true;
}

public boolean deleteFile(String filename, Context context){
    File file = context.getFileStreamPath(filename);
    return file.delete();
}
</code>```

The class isn't singleton.

答:
I solved it with a singleton class and using locks:</p>

```<code>Lock lockDeviceData = new ReentrantLock();
</code>```

Body:
I need to concurrently read and write a common file with different jobIntentServices in my APP. One service (producer) writes data in the file, while another service (consumer) checks if there is data in the shared file. If there is data, it sends it and, if the data transfer was successful, it deletes the file. I have created the following storage controller class:

public class Storage {
private static final String TAG = "Storage";

public void writeToFile(String filePath, String data, Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filePath, Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e(TAG, "File write failed: " + e.toString());
    }
}

public String readFromFile(String filePath, Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput(filePath);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "Can not read file: " + e.toString());
    }

    return ret;
}

public boolean fileExists(String filename, Context context) {
    File file = context.getFileStreamPath(filename);
    if(file == null || !file.exists()) {
        return false;
    }
    return true;
}

public boolean deleteFile(String filename, Context context){
    File file = context.getFileStreamPath(filename);
    return file.delete();
}

The class isn't singleton.

Body:
I solved it with a singleton class and using locks:

Lock lockDeviceData = new ReentrantLock();


问:
Ldap Authentication not working with spring boot
I am able to get LDAP authentication working with spring boot ActiveDirectoryLdapAuthenticationProvider. Same code works in other client environments, but somehow with one client it is not working.
I am able to connect to LDAP and bind and also reach the roodn, all is working fine.

In search filter, in place of using default one i.e.:

```<code>(&(objectClass=user)(userPrincipalName={0}))
</code>```

I am using:

```<code>(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))
</code>```

I have tried a lot of search filters, but nothing seems to work.

Can anyone please help on this, don't have much knowledge on LDAP.

答:
@gariel user is expecting to strictly login only using sAMAccountName. I got the login working with email ID (&(objectClass=user)(userPrincipalName={0})) filter. But to make it work with sAMAccountName with their LDAP, changing it to (&(objectClass=user)(sAMAccountName={0})) just doesn't work. Their sAMAccountName and userprincipalname are not same.

As a work around, instead of completely depending on spring security for authentication,
user inputs the sAMAccoutName, and i intercept the request using a custom filter. In the custom filter, using JAVA code i query LDAP to provide me with the emailId of that sAMAccountName. Once i have the emailID of the user, i update the username field in the request from sAMAccountName to emailID and then proceed the authentication request forward(remember i already had the LDAP authentication working with emailID).

In SecurityConfig file : .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
CustomFilter is where i am doing everything mentioned above.

Now everything works fine, but i have new issue. When user successfully authenticates, if user is not present in local db and doesn't require any authority it works fine. But the user is defined to be ADMIN in local db, and post authentication we provide it with the ADMIN authority, for some reason because of the custom filter it goes into a loop.

Body:
I am able to get LDAP authentication working with spring boot ActiveDirectoryLdapAuthenticationProvider. Same code works in other client environments, but somehow with one client it is not working.
I am able to connect to LDAP and bind and also reach the roodn, all is working fine.

In search filter, in place of using default one i.e.:

(&(objectClass=user)(userPrincipalName={0}))

I am using:

(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))

I have tried a lot of search filters, but nothing seems to work.

Can anyone please help on this, don't have much knowledge on LDAP.


问:
Iterate array elements in specific order
I am trying to iterate a 1D-array/vector of integers in a specific order, but I can't wrap my head around it, to get the loop conditions right.

The input data is a one-dimensional vector of integers:

```<code>{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48}
</code>```

This input data is essentially a one dimensional representation of a 2D array/grid with subgroups:

```<code>+----+----+----+----+----+----+
| 1  | 5  | 9  | 13 | 17 | 21 |
+----+----+----+----+----+----+
| 2  | 6  | 10 | 14 | 18 | 22 |
+----+----+----+----+----+----+
| 3  | 7  | 11 | 15 | 19 | 23 |
+----+----+----+----+----+----+
| 4  | 8  | 12 | 16 | 20 | 24 |
+----+----+----+----+----+----+
| 25 | 29 | 33 | 37 | 41 | 45 |
+----+----+----+----+----+----+
| 26 | 30 | 34 | 38 | 42 | 46 |
+----+----+----+----+----+----+
| 27 | 31 | 35 | 39 | 43 | 47 |
+----+----+----+----+----+----+
| 28 | 32 | 36 | 40 | 44 | 48 |
+----+----+----+----+----+----+
</code>```

This table is is grouped into multiple 2x4 subgroups:

I want to iterate this 1D input vector/array in the order that is indicated by the numbers. (Essentially going through every 2x4 subgroup, one after another).
Inside of the loop, I want to load the 8 elements of the currently processed subgroup in a vector/int for further processing.
So in the end I should process 6 subgroups, the first one holding the numbers 1 to 8, the second one 9 to 16 and so fourth ..
The groups should be processed from left to right.

Note: The numbers in the input data just serve as an example, to make clear in which order the data should be processed. The input data could contain totally random values. The order of the values in each group should be kept. There should be no sorting/reordering inside a group. What is important are the constraints for the subgroup/array dimensions etc.

Together with the 1D array/vector I do know the dimensions of the grid and the size of the subgroups:

```<code>int grid_width = 6; // Variable, but will always be a multiple of 2, to match subgroup width
int grid_height = 8;  // Variable, but will always be a multiple of 4, to match subgroup height
const int group_width = 2; // Constant, subgroup width is always 2.
const int group_height = 4; // Constant, subgroup height is always 4.
</code>```

My idea was to have one loop that iterates over the entire data, and then two loops that process the subgroups accordingly. But I really struggle getting the loop conditions and indices for the elements correct. My thought-process was something like this:

```<code>// Iterate over entire data
for (int i = 0; i < grid_width * grid_height; i += (group_width * group_height))
{
    int block[8];
    // Iterate groups in correct order
    for (int j = 0; j < group_height; j++)
    {
        for (int k = 0; k < group_width; k++)
        {
            // Grab current element in group
            int value = input_array[i * grid_width + j]; // ?? This ain't right

            // Add element to group array/vector
            block[??] = ??;
        }
    }

    // Do further processing with the group array
}
</code>```

Can someone help me to loop over this correctly?
I hope the question is clear enough. If not, let me know.

答:
I suppose this will do the job:

Edit: I added this explanation since some people could not understand this solution so far although it just contains some simple linear index calculation, and since I did not see any non-TL;DR but complete solution :
We iterate through the input data front to back. We always calculate the indices of where the value we read belongs to. We store the value to the appropriate indices.
Groups are quadratic blocks. We use group_position_x to store our horizontal position inside each group. Analoguously we use group_position_y for the vertical position inside a group, starting from the left upper corner.
We use col to state we are in the colth group in a row.
Analoguously we use row to state we are in the rowth group in a column.
We then can easily calculate where the value read from input has to be stored.
The group is the col + [col-size] * rowth group of all.
In a similar way we use the x and y corrdinates inside the group to see at which index inside the group the value just read has to be stored.
Note that indices start at 0. Also, see the comments in the code below.
The new values for col, row and the coordinates inside the groups are so to say incremented in each step. Of course, we talk about increment modulo some integer in each case. In some cases the "+1" happens if some overflow conditions of other indices are met.

```<code>
using data_type = int // change type to correctly group data not being integers
using group = std::vector<data_type>; // reprensents the values of one group
const data_type DEFAULT{ -1 };

/**
@param data_begin begin iterator of the input data
@param data_end end iterator of the input data
@return a vector of all groups from top to bottom, from left to right.
*/
template<class _Const_Iterator>
std::vector<group> grouping(int grid_width, int grid_height, int group_width, int group_height, _Const_Iterator data_begin, _Const_Iterator data_end){
 const int GROUPS_PER_ROW{ grid_width / group_width };
 const int GROUPS_PER_COL{ grid_height / group_height };
 const int NUMBER_GROUPS{ GROUPS_PER_ROW * GROUPS_PER_COL };
 const int GROUP_SIZE{ group_width * group_height };
 std::vector<group> result(NUMBER_GROUPS, group(GROUP_SIZE, DEFAULT)); // create empty result vector with correct size.
 std::size_t group_index{ 0 }; // id of the current group
 std::size_t group_position_y{ 0 }; // currrent vertical position inside a group block
 std::size_t group_position_x{ 0 }; // current horizontal position inside a group block
 std::size_t row{ 0 }; // current row with respect to the groups
 std::size_t col{ 0 }; // current column with respect to the groups

 // iterate through all input data, copy data cell to target structur (result), calculate the correct indices for the next input data cell
 for (_Const_Iterator it{data_begin}; it != data_end; ++it){
  result[group_index][group_position_y + group_height * group_position_x] = *it;

  group_position_x = (group_position_x + 1) % group_width; // new horizontal position inside group
  auto old_col{ col };
  col = (col + (group_position_x == 0)) % GROUPS_PER_ROW; // new column with respect to the groups
  auto old_group_position_y{ group_position_y };
  group_position_y = (group_position_y  + (col == 0 && col != old_col)) % group_height; // new vertical position inside group
  row = (row + (group_position_y == 0 && group_position_y != old_group_position_y)) % GROUPS_PER_COL ; // new row with respect to the groups
  group_index = col + GROUPS_PER_ROW * row;
 }
 return result;
}
</code>```

In my personal opinion, it is better to not use too many nested loops and to do index calculation instead.

Body:
I am trying to iterate a 1D-array/vector of integers in a specific order, but I can't wrap my head around it, to get the loop conditions right.

The input data is a one-dimensional vector of integers:

{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48}

This input data is essentially a one dimensional representation of a 2D array/grid with subgroups:

+----+----+----+----+----+----+
| 1  | 5  | 9  | 13 | 17 | 21 |
+----+----+----+----+----+----+
| 2  | 6  | 10 | 14 | 18 | 22 |
+----+----+----+----+----+----+
| 3  | 7  | 11 | 15 | 19 | 23 |
+----+----+----+----+----+----+
| 4  | 8  | 12 | 16 | 20 | 24 |
+----+----+----+----+----+----+
| 25 | 29 | 33 | 37 | 41 | 45 |
+----+----+----+----+----+----+
| 26 | 30 | 34 | 38 | 42 | 46 |
+----+----+----+----+----+----+
| 27 | 31 | 35 | 39 | 43 | 47 |
+----+----+----+----+----+----+
| 28 | 32 | 36 | 40 | 44 | 48 |
+----+----+----+----+----+----+

This table is is grouped into multiple 2x4 subgroups:

I want to iterate this 1D input vector/array in the order that is indicated by the numbers. (Essentially going through every 2x4 subgroup, one after another).
Inside of the loop, I want to load the 8 elements of the currently processed subgroup in a vector/int for further processing.
So in the end I should process 6 subgroups, the first one holding the numbers 1 to 8, the second one 9 to 16 and so fourth ..
The groups should be processed from left to right.

Note: The numbers in the input data just serve as an example, to make clear in which order the data should be processed. The input data could contain totally random values. The order of the values in each group should be kept. There should be no sorting/reordering inside a group. What is important are the constraints for the subgroup/array dimensions etc.

Together with the 1D array/vector I do know the dimensions of the grid and the size of the subgroups:

int grid_width = 6; // Variable, but will always be a multiple of 2, to match subgroup width
int grid_height = 8;  // Variable, but will always be a multiple of 4, to match subgroup height
const int group_width = 2; // Constant, subgroup width is always 2.
const int group_height = 4; // Constant, subgroup height is always 4.

My idea was to have one loop that iterates over the entire data, and then two loops that process the subgroups accordingly. But I really struggle getting the loop conditions and indices for the elements correct. My thought-process was something like this:

// Iterate over entire data
for (int i = 0; i < grid_width * grid_height; i += (group_width * group_height))
{
    int block[8];
    // Iterate groups in correct order
    for (int j = 0; j < group_height; j++)
    {
        for (int k = 0; k < group_width; k++)
        {
            // Grab current element in group
            int value = input_array[i * grid_width + j]; // ?? This ain't right

            // Add element to group array/vector
            block[??] = ??;
        }
    }

    // Do further processing with the group array
}

Can someone help me to loop over this correctly?
I hope the question is clear enough. If not, let me know.

Body:
I suppose this will do the job:

Edit: I added this explanation since some people could not understand this solution so far although it just contains some simple linear index calculation, and since I did not see any non-TL;DR but complete solution :
We iterate through the input data front to back. We always calculate the indices of where the value we read belongs to. We store the value to the appropriate indices.
Groups are quadratic blocks. We use group_position_x to store our horizontal position inside each group. Analoguously we use group_position_y for the vertical position inside a group, starting from the left upper corner.
We use col to state we are in the colth group in a row.
Analoguously we use row to state we are in the rowth group in a column.
We then can easily calculate where the value read from input has to be stored.
The group is the col + [col-size] * rowth group of all.
In a similar way we use the x and y corrdinates inside the group to see at which index inside the group the value just read has to be stored.
Note that indices start at 0. Also, see the comments in the code below.
The new values for col, row and the coordinates inside the groups are so to say incremented in each step. Of course, we talk about increment modulo some integer in each case. In some cases the "+1" happens if some overflow conditions of other indices are met.

using data_type = int // change type to correctly group data not being integers
using group = std::vector<data_type>; // reprensents the values of one group
const data_type DEFAULT{ -1 };

/**
@param data_begin begin iterator of the input data
@param data_end end iterator of the input data
@return a vector of all groups from top to bottom, from left to right.
*/
template<class _Const_Iterator>
std::vector<group> grouping(int grid_width, int grid_height, int group_width, int group_height, _Const_Iterator data_begin, _Const_Iterator data_end){
 const int GROUPS_PER_ROW{ grid_width / group_width };
 const int GROUPS_PER_COL{ grid_height / group_height };
 const int NUMBER_GROUPS{ GROUPS_PER_ROW * GROUPS_PER_COL };
 const int GROUP_SIZE{ group_width * group_height };
 std::vector<group> result(NUMBER_GROUPS, group(GROUP_SIZE, DEFAULT)); // create empty result vector with correct size.
 std::size_t group_index{ 0 }; // id of the current group
 std::size_t group_position_y{ 0 }; // currrent vertical position inside a group block
 std::size_t group_position_x{ 0 }; // current horizontal position inside a group block
 std::size_t row{ 0 }; // current row with respect to the groups
 std::size_t col{ 0 }; // current column with respect to the groups

 // iterate through all input data, copy data cell to target structur (result), calculate the correct indices for the next input data cell
 for (_Const_Iterator it{data_begin}; it != data_end; ++it){
  result[group_index][group_position_y + group_height * group_position_x] = *it;

  group_position_x = (group_position_x + 1) % group_width; // new horizontal position inside group
  auto old_col{ col };
  col = (col + (group_position_x == 0)) % GROUPS_PER_ROW; // new column with respect to the groups
  auto old_group_position_y{ group_position_y };
  group_position_y = (group_position_y  + (col == 0 && col != old_col)) % group_height; // new vertical position inside group
  row = (row + (group_position_y == 0 && group_position_y != old_group_position_y)) % GROUPS_PER_COL ; // new row with respect to the groups
  group_index = col + GROUPS_PER_ROW * row;
 }
 return result;
}

In my personal opinion, it is better to not use too many nested loops and to do index calculation instead.


问:
iOS: centering CAShapeLayer inside a constrained subview
I'm trying to render a shape in the center of Circle, a custom subclass of UIView (first snippet). Then I'm adding the Circle as a subview in my VC and adding constraints (second snippet).

When height and width is constrained, the rendered shape has its center (undesirably) in the top left corner of the Circle view (picture bellow). When only X and Y of the Circle view are constrained, the shape is in center as expected.

Why does this happen and what do I do to be able to constrain Circle as I please but still have the shape render in the center of Circle ? Thanks.

Circle:

```<code>class Circle: UIView {

func render(){
    let shapeLayer = CAShapeLayer()
    let center = self.center
    let endAngle = 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)

    shapeLayer.path = circularPath.cgPath
    self.layer.addSublayer(shapeLayer)
  }
}
</code>```

VC:

```<code>class VC: UIViewController {
let circle = Circle()

override func viewDidLoad() {
    super.viewDidLoad()
    configure()
    circle.render()
}

func configure(){
    view.backgroundColor = .white
    view.addSubview(progressCircle)
    progressCircle.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        progressCircle.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        progressCircle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        progressCircle.heightAnchor.constraint(equalToConstant: 200),
        progressCircle.widthAnchor.constraint(equalToConstant: 200)
    ])
  }
}
</code>```

Result:

答:
Ended up with this solution bellow (different shape this time but the principle applies). Work as expected, the view can now be constrained and moved in the VC however wanted.</p>

```<code>class Circle: UIView {

private var layer: CAShapeLayer!
override func draw(_ rect: CGRect) {

    let width =  rect.width
    let height = rect.height
    let lineWidth = 0.1 * min(width, height)
    let center = CGPoint(x: width / 2, y: height / 2)
    let radius = (min(width, height) - lineWidth) / 2
    let startAngle = -CGFloat.pi / 2
    let endAngle = startAngle + 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

    layer = CAShapeLayer()
    layer.path = circularPath.cgPath
    layer.strokeColor = UIColor.lightGray.cgColor
    layer.lineWidth = lineWidth
    layer.fillColor = UIColor.clear.cgColor
    layer.lineCap = .round

    layer.addSublayer(backbroundLayer)

  }
}
</code>```

Body:
I'm trying to render a shape in the center of Circle, a custom subclass of UIView (first snippet). Then I'm adding the Circle as a subview in my VC and adding constraints (second snippet).

When height and width is constrained, the rendered shape has its center (undesirably) in the top left corner of the Circle view (picture bellow). When only X and Y of the Circle view are constrained, the shape is in center as expected.

Why does this happen and what do I do to be able to constrain Circle as I please but still have the shape render in the center of Circle ? Thanks.

Circle:

class Circle: UIView {

func render(){
    let shapeLayer = CAShapeLayer()
    let center = self.center
    let endAngle = 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)

    shapeLayer.path = circularPath.cgPath
    self.layer.addSublayer(shapeLayer)
  }
}

VC:

class VC: UIViewController {
let circle = Circle()

override func viewDidLoad() {
    super.viewDidLoad()
    configure()
    circle.render()
}

func configure(){
    view.backgroundColor = .white
    view.addSubview(progressCircle)
    progressCircle.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        progressCircle.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        progressCircle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        progressCircle.heightAnchor.constraint(equalToConstant: 200),
        progressCircle.widthAnchor.constraint(equalToConstant: 200)
    ])
  }
}

Result:

Body:
Ended up with this solution bellow (different shape this time but the principle applies). Work as expected, the view can now be constrained and moved in the VC however wanted.

class Circle: UIView {

private var layer: CAShapeLayer!
override func draw(_ rect: CGRect) {

    let width =  rect.width
    let height = rect.height
    let lineWidth = 0.1 * min(width, height)
    let center = CGPoint(x: width / 2, y: height / 2)
    let radius = (min(width, height) - lineWidth) / 2
    let startAngle = -CGFloat.pi / 2
    let endAngle = startAngle + 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

    layer = CAShapeLayer()
    layer.path = circularPath.cgPath
    layer.strokeColor = UIColor.lightGray.cgColor
    layer.lineWidth = lineWidth
    layer.fillColor = UIColor.clear.cgColor
    layer.lineCap = .round

    layer.addSublayer(backbroundLayer)

  }
}


问:
How to save a ggplot so that it can entirely occupy a div with fixed height and width as background
I want to create a Shiny app where the background picture of a div will be some ggplot graph saved earlier. Below is one such prototype -

```<code>library(shiny)
library(ggplot2)

# create and save plot
if (!file.exists("www")) dir.create("www")
ggsave(filename = "www/Some_Plot.png",
        ggplot(mpg, aes(class)) + geom_bar(),
        device = 'png')

shinyApp(
  ui = fluidPage(
    div(style = "height: 550px; width: 550px; background: url('www/Some_Plot.png') no-repeat center center; background-size: cover;")
  ),
  server = function(input, output) {

  }
)
</code>```

Given the height and width of the div, I want to have it's background as that gg-plot which should occupy entire div while maintaining aspect ratio.

Any pointer how that can be achieved will be highly helpful.

Thanks,

答:
I don't know why, but I couldn't get this to work on your example, but on my own little example. Sorry about that.

I removed the check for the directory. Presumably, you will only do that once and you will do it when you set up the app.

It seems that the key to getting it to work was in the CSS styling you applied. A Shiny application looks in the www folder by default, so specifying that in the styling meant that Shiny couldn't locate the image. If you look at my example, I only call the file-name since it is already placed in the correct folder.

```<code># Load packages ----
pkgs <- c("shiny", "ggplot2")
invisible(lapply(pkgs, require, character.only = TRUE))

# Generate a plot ----
some_plot <- ggplot(mpg, aes(class)) +
  geom_bar()

ggsave(
  "www/some-plot.png",
  some_plot,
  device = "png"
)

# Define the user interface ----
ui <- fluidPage(
  div(
    style = "height: 550px; width = 550px;
             background: url('some-plot.png') no-repeat center center;
             background-size: cover;"
  )
)

# Define the server side ----
server <- function(input, output, session) {

}

# Combine into an app ----
shinyApp(ui = ui, server = server)
</code>```

I did delete the file, restart RStudio and re-ran the app and it was able to create the image and render it as a background using CSS styling. Please try the same with your code (modified ofc) and mine. Maybe I did something incorrect modifying your code or you spot what I missed.

Body:
I want to create a Shiny app where the background picture of a div will be some ggplot graph saved earlier. Below is one such prototype -

library(shiny)
library(ggplot2)

# create and save plot
if (!file.exists("www")) dir.create("www")
ggsave(filename = "www/Some_Plot.png",
        ggplot(mpg, aes(class)) + geom_bar(),
        device = 'png')

shinyApp(
  ui = fluidPage(
    div(style = "height: 550px; width: 550px; background: url('www/Some_Plot.png') no-repeat center center; background-size: cover;")
  ),
  server = function(input, output) {

  }
)

Given the height and width of the div, I want to have it's background as that gg-plot which should occupy entire div while maintaining aspect ratio.

Any pointer how that can be achieved will be highly helpful.

Thanks,

Body:
I don't know why, but I couldn't get this to work on your example, but on my own little example. Sorry about that.

I removed the check for the directory. Presumably, you will only do that once and you will do it when you set up the app.

It seems that the key to getting it to work was in the CSS styling you applied. A Shiny application looks in the www folder by default, so specifying that in the styling meant that Shiny couldn't locate the image. If you look at my example, I only call the file-name since it is already placed in the correct folder.

# Load packages ----
pkgs <- c("shiny", "ggplot2")
invisible(lapply(pkgs, require, character.only = TRUE))

# Generate a plot ----
some_plot <- ggplot(mpg, aes(class)) +
  geom_bar()

ggsave(
  "www/some-plot.png",
  some_plot,
  device = "png"
)

# Define the user interface ----
ui <- fluidPage(
  div(
    style = "height: 550px; width = 550px;
             background: url('some-plot.png') no-repeat center center;
             background-size: cover;"
  )
)

# Define the server side ----
server <- function(input, output, session) {

}

# Combine into an app ----
shinyApp(ui = ui, server = server)

I did delete the file, restart RStudio and re-ran the app and it was able to create the image and render it as a background using CSS styling. Please try the same with your code (modified ofc) and mine. Maybe I did something incorrect modifying your code or you spot what I missed.


问:
Open a Facebook post URL in android Facebook app programmatically
I'm coding an android - java app which can open a Facebook post url
(ex: https://www.facebook.com/BaHangXom.0/videos/2377836809193490).
I tried some ways to start Facebook app with intent but unsuccessfully.

```<code>    Intent intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + "https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
    intent.setPackage("com.facebook.katana");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
</code>```

Could you please give me any idea?
Thank you so much.

答:
You can open the facebook app using this code:</p>

```<code>public static Intent newFacebookIntent(PackageManager pm, String url) {
  Uri uri = Uri.parse(url);
  try {
    ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
    if (applicationInfo.enabled) {
      // http://stackoverflow.com/a/24547437/1048340
      uri = Uri.parse("fb://facewebmodal/f?href=" + url);
    }
  } catch (PackageManager.NameNotFoundException ignored) {
  }
  return new Intent(Intent.ACTION_VIEW, uri);
}
</code>```

Body:
I'm coding an android - java app which can open a Facebook post url
(ex: https://www.facebook.com/BaHangXom.0/videos/2377836809193490).
I tried some ways to start Facebook app with intent but unsuccessfully.

    Intent intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + "https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
    intent.setPackage("com.facebook.katana");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

Could you please give me any idea?
Thank you so much.

Body:
You can open the facebook app using this code:

public static Intent newFacebookIntent(PackageManager pm, String url) {
  Uri uri = Uri.parse(url);
  try {
    ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
    if (applicationInfo.enabled) {
      // http://stackoverflow.com/a/24547437/1048340
      uri = Uri.parse("fb://facewebmodal/f?href=" + url);
    }
  } catch (PackageManager.NameNotFoundException ignored) {
  }
  return new Intent(Intent.ACTION_VIEW, uri);
}


答: I don't know how irregular your data is and what your tolerance is for fiddling, but having faced pretty messy address data, sometimes you need some lateral thinking. Consider using the google maps API, throw the addresses at it, and take back the cleaned data using all the smarts of Google. For 1.7m addresses, you'll have to pay a bit, the free daily quota is pretty small. </p>

Title: How to extract UK postcodes from an address column in a pandas DataFrame?

Body:
I have a DataFrame that contains information, in particular addresses like the DataFrame below:

    col1   col2
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE

These are all different formats, with some having commas and others not, and there are also examples of addresses from other countries. I was wondering how would I extract the addresses from here as I want to merge them with location data.

This could mean a merge on substring or just extracting the

I have tried:

df["postcodes"] = df["address"].str.extract(r'^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$')

to extract the postcodes but this doesn't seem to work coming up with the error of 9 arguments given where 1 should be taken.

I have also attempted:

rhs = (df1.address
          .apply(lambda x: df2[df2.Postcode.str.find(x).ge(0)]['location'])
          .bfill(axis=1)
          .iloc[:, 0])

(pd.concat([df1.app_nbr, rhs], axis=1, ignore_index=True)
 .rename(columns={0: 'app_nbr', 1: 'location'}))

from here: How to merge pandas on string contains? but it is taking a long time to run on my machine given there are 1.7million postcodes in the second dataframe to match on.

The expected output would be either:

    col1   col2                                                  col3
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY   CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       CD7 9HE

Or (matching with the second dataframe based on postcode):

    col1   col2                                              col3 (coords)
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   50.00, 1.00
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       51.23, 1.05
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            54.65, 1.07
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY    51.23, 0.95
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               54.6,  2.23
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       49.25, 1.23

Any help would be appreciated or to be pointed in the right direction.

Thank you

*addresses have been altered so are not real but the format is the same