问:
Git history is all messed up after rebase
We have a develop branch where we build features and then make PR targeting the develop branch and merge them in.

Then we merge the develop branch into a release branch. We use this release branch to QA test.

This release branch then gets merged into our prod branch, to know what's going on in our live version of the product and keep track.

the script we run for release is just:

```<code>git checkout release
git pull origin develop
git push release
</code>```

Nothing fancy. and I've been doing this for a good amount to know it's pretty routine...

but then yesterday I ran the same script and got this error:

```<code>warning: Pulling without specifying how to reconcile divergent branches is
discouraged. You can squelch this message by running one of the following
commands sometime before your next pull:

     git config pull.rebase false  # merge (the default strategy)
     git config pull.rebase true   # rebase
     git config pull.ff only       # fast-forward only

You can replace "git config" with "git config --global" to set a default
preference for all repositories. You can also pass --rebase, --no-rebase,
or --ff-only on the command line to override the configured default per
invocation.
</code>```

I've never seen this error before. So I manually ran the script actions, but instead of git push, I rebased. That got me so merge conflicts that needed to be resolved.

After resolving the conflicts, I saw that old commits (that were already merged in from way before (like few months ago?) showed up at the top of the commit history. The only commits that I should see in the release branch are "Merge pull request #XXX from /develop".

I don't even know where to look to see what the problem is. I don't know where it went wrong. I checked the PRs that were merged in to develop branch since the last time the release branch pulled from develop, and they all targeted develop as they should....

Body:
We have a develop branch where we build features and then make PR targeting the develop branch and merge them in.

Then we merge the develop branch into a release branch. We use this release branch to QA test.

This release branch then gets merged into our prod branch, to know what's going on in our live version of the product and keep track.

the script we run for release is just:

git checkout release
git pull origin develop
git push release

Nothing fancy. and I've been doing this for a good amount to know it's pretty routine...

but then yesterday I ran the same script and got this error:

warning: Pulling without specifying how to reconcile divergent branches is
discouraged. You can squelch this message by running one of the following
commands sometime before your next pull:

     git config pull.rebase false  # merge (the default strategy)
     git config pull.rebase true   # rebase
     git config pull.ff only       # fast-forward only

You can replace "git config" with "git config --global" to set a default
preference for all repositories. You can also pass --rebase, --no-rebase,
or --ff-only on the command line to override the configured default per
invocation.

I've never seen this error before. So I manually ran the script actions, but instead of git push, I rebased. That got me so merge conflicts that needed to be resolved.

After resolving the conflicts, I saw that old commits (that were already merged in from way before (like few months ago?) showed up at the top of the commit history. The only commits that I should see in the release branch are "Merge pull request #XXX from /develop".

I don't even know where to look to see what the problem is. I don't know where it went wrong. I checked the PRs that were merged in to develop branch since the last time the release branch pulled from develop, and they all targeted develop as they should....


来源: stackexchange

问:
Call the values by variables indirectly
I am trying to print the value stored in a variable without directly using the variable name

var1_str = "NASA"
var2 = "var1"
print (var2 + "_str")
```

The above code prints the string var1_str as output. However, I need it to print the string "NASA". I need to use (var2 + "_str") and print the value assigned for var1. I cannot directly call var1_str variable due to a requirement.

ContentLicense: CC BY-SA 4.0

Title: Call the values by variables indirectly

Body:
I am trying to print the value stored in a variable without directly using the variable name

var1_str = "NASA"
var2 = "var1"
print (var2 + "_str")

The above code prints the string var1_str as output. However, I need it to print the string "NASA". I need to use (var2 + "_str") and print the value assigned for var1. I cannot directly call var1_str variable due to a requirement.


问:
Why does this query result in deadlock in mysql?
Deadlock occurs when executing insert query after "select .. for update" in two sessions

Running the following queries sequentially in two sessions results in a dead lock error.

test setup

```<code>CREATE TABLE `tb_test` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `sub_id` INT(11) NULL DEFAULT NULL,
    `test_data` INT(11) NULL DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE,
    UNIQUE INDEX `sub_id` (`sub_id`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
</code>```
```<code>INSERT INTO `tb_test` (`id`, `sub_id`, `test_data`) VALUES (1, 100, 1);
</code>```

1. session A

```<code>SET AUTOCOMMIT = FALSE;
SELECT * FROM tb_test WHERE sub_id = 100 FOR UPDATE;
</code>```

2. session B

```<code>SET AUTOCOMMIT = FALSE;
SELECT * FROM tb_test WHERE sub_id = 100 FOR UPDATE;
</code>```

3. session A

```<code>INSERT INTO tb_test(sub_id,test_data) VALUES (100,200) ON DUPLICATE KEY UPDATE `test_data` = 1;
</code>```

When executing the above queries in two sessions sequentially, a deadlock error occurs in session B

show engine innodb status

```<code>SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 201
OS WAIT ARRAY INFO: signal count 205
RW-shared spins 0, rounds 96, OS waits 40
RW-excl spins 0, rounds 421, OS waits 3
RW-sx spins 0, rounds 0, OS waits 0
Spin rounds per wait: 96.00 RW-shared, 421.00 RW-excl, 0.00 RW-sx
------------------------
LATEST DETECTED DEADLOCK
------------------------
2022-12-09 13:11:47 0x2abf51a5e700
*** (1) TRANSACTION:
TRANSACTION 5072366, ACTIVE 3 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 1136, 1 row lock(s)
MySQL thread id 1897, OS thread handle 47000044201728, query id 25783927 220.72.132.220 admin statistics
SELECT * FROM tb_test WHERE sub_id = 100 FOR UPDATE
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 22 page no 4 n bits 0 index sub_id of table `sample`.`tb_test` trx id 5072366 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len=4; bufptr=0x2abf199b807e; hex= 80000064; asc    d;;
 1: len=4; bufptr=0x2abf199b8082; hex= 80000001; asc     ;;

*** (2) TRANSACTION:
TRANSACTION 5072363, ACTIVE 4 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 4 lock struct(s), heap size 1136, 3 row lock(s), undo log entries 1
MySQL thread id 1896, OS thread handle 47000043403008, query id 25783946 220.72.132.220 admin update
INSERT INTO tb_test(sub_id,test_data) VALUES (100,200) ON DUPLICATE KEY UPDATE `test_data` = 1
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 22 page no 4 n bits 0 index sub_id of table `sample`.`tb_test` trx id 5072363 lock_mode X locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len=4; bufptr=0x2abf199b807e; hex= 80000064; asc    d;;
 1: len=4; bufptr=0x2abf199b8082; hex= 80000001; asc     ;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 22 page no 4 n bits 0 index sub_id of table `sample`.`tb_test` trx id 5072363 lock_mode X waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len=4; bufptr=0x2abf199b807e; hex= 80000064; asc    d;;
 1: len=4; bufptr=0x2abf199b8082; hex= 80000001; asc     ;;

*** WE ROLL BACK TRANSACTION (1)
------------
TRANSACTIONS
------------
Trx id counter 5072623
Purge done for trx's n:o < 5072623 undo n:o < 0 state: running but idle
History list length 2759
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 328475110023416, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110022016, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110020616, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110019216, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110017816, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
</code>```

Body:
Deadlock occurs when executing insert query after "select .. for update" in two sessions

Running the following queries sequentially in two sessions results in a dead lock error.

test setup

CREATE TABLE `tb_test` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `sub_id` INT(11) NULL DEFAULT NULL,
    `test_data` INT(11) NULL DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE,
    UNIQUE INDEX `sub_id` (`sub_id`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

INSERT INTO `tb_test` (`id`, `sub_id`, `test_data`) VALUES (1, 100, 1);

1. session A

SET AUTOCOMMIT = FALSE;
SELECT * FROM tb_test WHERE sub_id = 100 FOR UPDATE;

2. session B

SET AUTOCOMMIT = FALSE;
SELECT * FROM tb_test WHERE sub_id = 100 FOR UPDATE;

3. session A

INSERT INTO tb_test(sub_id,test_data) VALUES (100,200) ON DUPLICATE KEY UPDATE `test_data` = 1;

When executing the above queries in two sessions sequentially, a deadlock error occurs in session B

show engine innodb status

SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 201
OS WAIT ARRAY INFO: signal count 205
RW-shared spins 0, rounds 96, OS waits 40
RW-excl spins 0, rounds 421, OS waits 3
RW-sx spins 0, rounds 0, OS waits 0
Spin rounds per wait: 96.00 RW-shared, 421.00 RW-excl, 0.00 RW-sx
------------------------
LATEST DETECTED DEADLOCK
------------------------
2022-12-09 13:11:47 0x2abf51a5e700
*** (1) TRANSACTION:
TRANSACTION 5072366, ACTIVE 3 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 1136, 1 row lock(s)
MySQL thread id 1897, OS thread handle 47000044201728, query id 25783927 220.72.132.220 admin statistics
SELECT * FROM tb_test WHERE sub_id = 100 FOR UPDATE
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 22 page no 4 n bits 0 index sub_id of table `sample`.`tb_test` trx id 5072366 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len=4; bufptr=0x2abf199b807e; hex= 80000064; asc    d;;
 1: len=4; bufptr=0x2abf199b8082; hex= 80000001; asc     ;;

*** (2) TRANSACTION:
TRANSACTION 5072363, ACTIVE 4 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 4 lock struct(s), heap size 1136, 3 row lock(s), undo log entries 1
MySQL thread id 1896, OS thread handle 47000043403008, query id 25783946 220.72.132.220 admin update
INSERT INTO tb_test(sub_id,test_data) VALUES (100,200) ON DUPLICATE KEY UPDATE `test_data` = 1
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 22 page no 4 n bits 0 index sub_id of table `sample`.`tb_test` trx id 5072363 lock_mode X locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len=4; bufptr=0x2abf199b807e; hex= 80000064; asc    d;;
 1: len=4; bufptr=0x2abf199b8082; hex= 80000001; asc     ;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 22 page no 4 n bits 0 index sub_id of table `sample`.`tb_test` trx id 5072363 lock_mode X waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len=4; bufptr=0x2abf199b807e; hex= 80000064; asc    d;;
 1: len=4; bufptr=0x2abf199b8082; hex= 80000001; asc     ;;

*** WE ROLL BACK TRANSACTION (1)
------------
TRANSACTIONS
------------
Trx id counter 5072623
Purge done for trx's n:o < 5072623 undo n:o < 0 state: running but idle
History list length 2759
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 328475110023416, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110022016, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110020616, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110019216, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 328475110017816, not started
0 lock struct(s), heap size 1136, 0 row lock(s)


问:
Kibana alert on two subqueries
What is the best way to create a Kibana alert to be triggered, when both conditions are met:

There is a set of documents that match a specific condition.

There are no documents matching another condition.

The problem is that these are two different queries, that should be combined. The solution I've found so far is to connect a webhook to 2 triggers and do the "AND NOT" part there. But this solution smells suboptimal.

Title: Kibana alert on two subqueries


问:
How to stub cascaded observables Outer(Inner)
i want to write a jest test for the following code:

```<code>getData(param: string): Observable<ReturnObj[]> {
    this.isLoading$.next(true))
    return this.httpClient.get<ReturnEl[]>(`endpointA/${param}`)
        .pipe(
            mergeMap((els) => {
              const el: Observable<el>[] = els.map(el => {
                return this.httpClient.get<ReturnEl2[]>(`endpointB/${el.param}`)
                    .pipe(
                        map((innerEl): mergedEl => {
                          return {
                            ...el,
                            param: innerEl.param
                          }
                        })
                    )
              })

              return forkJoin(appointmentCompany);
            }),
            finalize(() => this.isLoading$.next(false))
     )
}
</code>```

How do i mock the inner observable? After spending quiet some time trying to figure out how to test this code i think there must be a better way of organizing it.
I feel that i need to split the two observables and merge them out of the function.
The cascading does not feel ideal.

I am thankful and happy for every constructive comment on

how to test it

how to refactor it to make testing easier

Body:
i want to write a jest test for the following code:

getData(param: string): Observable<ReturnObj[]> {
    this.isLoading$.next(true))
    return this.httpClient.get<ReturnEl[]>(`endpointA/${param}`)
        .pipe(
            mergeMap((els) => {
              const el: Observable<el>[] = els.map(el => {
                return this.httpClient.get<ReturnEl2[]>(`endpointB/${el.param}`)
                    .pipe(
                        map((innerEl): mergedEl => {
                          return {
                            ...el,
                            param: innerEl.param
                          }
                        })
                    )
              })

              return forkJoin(appointmentCompany);
            }),
            finalize(() => this.isLoading$.next(false))
     )
}

How do i mock the inner observable? After spending quiet some time trying to figure out how to test this code i think there must be a better way of organizing it.
I feel that i need to split the two observables and merge them out of the function.
The cascading does not feel ideal.

I am thankful and happy for every constructive comment on

how to test it

how to refactor it to make testing easier


问:
error in applying curve_fit to the logistic function
I need to approximate the input data with two logistic functionsenter image description here

Tell me, please, what could be the reason for the incorrect finding of coefficients in the second case?

```<code>from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

t = np.array([1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 6])
y = np.array([3, 22, 272, 446, 896, 1222, 1540, 1870, 2072, 2562])

def logistic_1(t, beta_0, beta_1, beta_2):
    return beta_0 / (1 + beta_1 * np.exp(-1 * beta_2 * t))

def logistic_2(t, beta_0, beta_1, beta_2, t_0):
    return beta_0 / (1 + beta_1 * np.exp(-beta_2 * t + beta_2*t_0))

args, _ = curve_fit(logistic_1, t, y, method='trf')
beta_01, beta_11, beta_21 = args[0], args[1], args[2]
y_fit1 = logistic_1(t, beta_01, beta_11, beta_21)

args1, _ = curve_fit(logistic_2, t, y, method='trf')
beta_02, beta_12, beta_22, t_02 = args1[0], args1[1], args1[2], args1[3]
y_fit2 = logistic_2(t, beta_02, beta_12, beta_22, t_02)

plt.figure(figsize=(10, 6))
plt.plot(t, y, 'o', color='orange')
plt.plot(t, y_fit1, color='black')
plt.plot(t, y_fit2, marker='*')

</code>```

For the first function, by applying method='trf' in the curve_fit function, everything worked out. But for the second with similar data, everything is approximated by a horizontal lineenter image description here

Without method='trf' gives the error: warnings.warn('Covariance of the parameters could not be estimated',

Body:
I need to approximate the input data with two logistic functionsenter image description here

Tell me, please, what could be the reason for the incorrect finding of coefficients in the second case?

from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

t = np.array([1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 6])
y = np.array([3, 22, 272, 446, 896, 1222, 1540, 1870, 2072, 2562])

def logistic_1(t, beta_0, beta_1, beta_2):
    return beta_0 / (1 + beta_1 * np.exp(-1 * beta_2 * t))

def logistic_2(t, beta_0, beta_1, beta_2, t_0):
    return beta_0 / (1 + beta_1 * np.exp(-beta_2 * t + beta_2*t_0))

args, _ = curve_fit(logistic_1, t, y, method='trf')
beta_01, beta_11, beta_21 = args[0], args[1], args[2]
y_fit1 = logistic_1(t, beta_01, beta_11, beta_21)

args1, _ = curve_fit(logistic_2, t, y, method='trf')
beta_02, beta_12, beta_22, t_02 = args1[0], args1[1], args1[2], args1[3]
y_fit2 = logistic_2(t, beta_02, beta_12, beta_22, t_02)

plt.figure(figsize=(10, 6))
plt.plot(t, y, 'o', color='orange')
plt.plot(t, y_fit1, color='black')
plt.plot(t, y_fit2, marker='*')

For the first function, by applying method='trf' in the curve_fit function, everything worked out. But for the second with similar data, everything is approximated by a horizontal lineenter image description here

Without method='trf' gives the error: warnings.warn('Covariance of the parameters could not be estimated',


问:
Use Tor Browser with selenium python
I'm trying to use Tor Browser with selenium for scrapping data. From multiple answers, I have tried following solutions.
I have installed Tor Browser(12.0) ,Firefox Browser(latest) on my Windows 11 system. Also downloaded geckodriver(0.32.0).

```<code>from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
import time

options = Options()
options.binary_location = r'C:\Users\admin\Desktop\Tor Browser\Browser\firefox.exe'
options.set_preference('profile', r'C:\Users\admin\Desktop\Tor Browser\Browser\TorBrowser\Data\Browser\profile.default')
options.set_preference('network.proxy.type', 1)
options.set_preference('network.proxy.socks', '127.0.0.1')
options.set_preference('network.proxy.socks_port', 9010)
options.set_preference('network.proxy.socks_remote_dns', False)
service = Service(r'geckodriver.exe')
browser = webdriver.Firefox(options=options)
browser.get("https://httpbin.org/ip")
time.sleep(5)
browser.quit()
</code>```

When I use firefox binary which came with tor browser ,It throws below error saying Failed to decode response from marionette

```<code>Traceback (most recent call last):
  File "C:\Users\admin\Desktop\demo\tor_selenium.py", line 14, in <module>
    browser = webdriver.Firefox(options=options)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 197, in __init__
    super().__init__(command_executor=executor, options=options, keep_alive=True)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 288, in __init__
    self.start_session(capabilities, browser_profile)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 381, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Failed to decode response from marionette
</code>```

But When I use Firefox binary which is located at 'C:\Program Files\Mozilla Firefox\firefox.exe', it runs successfully.

Note: I have configured tor browser to listing on 9010 port and tor browser is running while executing above code.

So, Is there any way I can use Firefox binary (which is inside tor browser data) with selenium?

Title: Use Tor Browser with selenium python

Body:
I'm trying to use Tor Browser with selenium for scrapping data. From multiple answers, I have tried following solutions.
I have installed Tor Browser(12.0) ,Firefox Browser(latest) on my Windows 11 system. Also downloaded geckodriver(0.32.0).

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
import time

options = Options()
options.binary_location = r'C:\Users\admin\Desktop\Tor Browser\Browser\firefox.exe'
options.set_preference('profile', r'C:\Users\admin\Desktop\Tor Browser\Browser\TorBrowser\Data\Browser\profile.default')
options.set_preference('network.proxy.type', 1)
options.set_preference('network.proxy.socks', '127.0.0.1')
options.set_preference('network.proxy.socks_port', 9010)
options.set_preference('network.proxy.socks_remote_dns', False)
service = Service(r'geckodriver.exe')
browser = webdriver.Firefox(options=options)
browser.get("https://httpbin.org/ip")
time.sleep(5)
browser.quit()

When I use firefox binary which came with tor browser ,It throws below error saying Failed to decode response from marionette

Traceback (most recent call last):
  File "C:\Users\admin\Desktop\demo\tor_selenium.py", line 14, in <module>
    browser = webdriver.Firefox(options=options)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 197, in __init__
    super().__init__(command_executor=executor, options=options, keep_alive=True)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 288, in __init__
    self.start_session(capabilities, browser_profile)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 381, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "D:\demo\myenv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Failed to decode response from marionette

But When I use Firefox binary which is located at 'C:\Program Files\Mozilla Firefox\firefox.exe', it runs successfully.

Note: I have configured tor browser to listing on 9010 port and tor browser is running while executing above code.

So, Is there any way I can use Firefox binary (which is inside tor browser data) with selenium?


问:
I'm trying to include a SwiftUI chart in a UIkit viewController but i'ml not sure exactly how to do this
I have a viewController in a storyboard. In the storyboard I have a section where i'd like to include a SwiftUI chart. I've investigated this and took example code from various sources but it's not working out.
The code compiled but i'm not seeing anything in the UI.

Below is the user interface I refer to:

I want to include the chart here

Here is the code I have thats included in  super.viewDidLoad:

`

```<code>  // Revenue Chart

        // Create CGSize for a UIKit View and its sub view
        let size = CGSize(width: 400, height: 400)
        let sizeSubView = CGSize(width: 200, height: 200)

        // Create UIKit View
        let uiView = UIView(frame: CGRect(origin: .zero, size: size))
        uiView.backgroundColor = .systemBlue

        // Create a subview to be placed at the centre of above view
        // this will be a container view for the Swift UI View
        let centerPointForSubView = CGRect(origin: CGPoint(x: 100, y: 100), size: sizeSubView)
        let uiViewSubView = UIView(frame: centerPointForSubView)
        uiViewSubView.backgroundColor = .white

        // Add placeholder subview to UIKit View
        uiView.addSubview(uiViewSubView)

        struct Item: Identifiable {
            var id = UUID()
            let type: String
            let value: Double
        }

        struct ContentViewChart: View {
            let items: [Item] = [
            Item(type: "1", value: 100 ),
            Item(type: "2", value: 80 ),
            Item(type: "3", value: 120 ),
            Item(type: "4", value: 20 ),
            Item(type: "5", value: 55 ),
            Item(type: "6", value: 170 ),
            Item(type: "7", value: 20 ),
            Item(type: "8", value: 10 ),
            Item(type: "9", value: 5 ),
            Item(type: "10", value: 1 ),
            Item(type: "11", value: 500 ),
            Item(type: "12", value: 700 )
        ]
        var body: some View {
            NavigationView {
                ScrollView {

                    Chart(items) { item in
                        LineMark(
                            x: .value("Month", item.type),
                            y: .value("Revenue", item.value)
                        )
                        .foregroundStyle(Color.purple.gradient)
                    }
                    .frame(height: 200)
                    .padding()
                }
                    .navigationTitle("Charts")
                }
            }
        }

        // Create a SwiftUI View
        let swiftUIView = ContentView()

        // Define a hosting VC.
        // A UIKit view controller that manages a SwiftUI view hierarchy.
        let host = UIHostingController(rootView: swiftUIView)
        let hostView = host.view!

        // Add the SwiftUI view to the UIKit view
        uiViewSubView.addSubview(hostView)
</code>```

`

When I run the app with the code above I see nothing what so ever in my UI. But it does compile with no errors.

As can be seen the values for the chart are currently hardcoded. That will be replaced with real data once I get the UI to work.

I've been playing with the code, checking blogs etc.

On the other hand i'm on a tight schedule to get this exercise done so any expert advice is most welcome.

Body:
I have a viewController in a storyboard. In the storyboard I have a section where i'd like to include a SwiftUI chart. I've investigated this and took example code from various sources but it's not working out.
The code compiled but i'm not seeing anything in the UI.

Below is the user interface I refer to:

I want to include the chart here

Here is the code I have thats included in  super.viewDidLoad:

`

  // Revenue Chart

        // Create CGSize for a UIKit View and its sub view
        let size = CGSize(width: 400, height: 400)
        let sizeSubView = CGSize(width: 200, height: 200)

        // Create UIKit View
        let uiView = UIView(frame: CGRect(origin: .zero, size: size))
        uiView.backgroundColor = .systemBlue

        // Create a subview to be placed at the centre of above view
        // this will be a container view for the Swift UI View
        let centerPointForSubView = CGRect(origin: CGPoint(x: 100, y: 100), size: sizeSubView)
        let uiViewSubView = UIView(frame: centerPointForSubView)
        uiViewSubView.backgroundColor = .white

        // Add placeholder subview to UIKit View
        uiView.addSubview(uiViewSubView)

        struct Item: Identifiable {
            var id = UUID()
            let type: String
            let value: Double
        }

        struct ContentViewChart: View {
            let items: [Item] = [
            Item(type: "1", value: 100 ),
            Item(type: "2", value: 80 ),
            Item(type: "3", value: 120 ),
            Item(type: "4", value: 20 ),
            Item(type: "5", value: 55 ),
            Item(type: "6", value: 170 ),
            Item(type: "7", value: 20 ),
            Item(type: "8", value: 10 ),
            Item(type: "9", value: 5 ),
            Item(type: "10", value: 1 ),
            Item(type: "11", value: 500 ),
            Item(type: "12", value: 700 )
        ]
        var body: some View {
            NavigationView {
                ScrollView {

                    Chart(items) { item in
                        LineMark(
                            x: .value("Month", item.type),
                            y: .value("Revenue", item.value)
                        )
                        .foregroundStyle(Color.purple.gradient)
                    }
                    .frame(height: 200)
                    .padding()
                }
                    .navigationTitle("Charts")
                }
            }
        }

        // Create a SwiftUI View
        let swiftUIView = ContentView()

        // Define a hosting VC.
        // A UIKit view controller that manages a SwiftUI view hierarchy.
        let host = UIHostingController(rootView: swiftUIView)
        let hostView = host.view!

        // Add the SwiftUI view to the UIKit view
        uiViewSubView.addSubview(hostView)

`

When I run the app with the code above I see nothing what so ever in my UI. But it does compile with no errors.

As can be seen the values for the chart are currently hardcoded. That will be replaced with real data once I get the UI to work.

I've been playing with the code, checking blogs etc.

On the other hand i'm on a tight schedule to get this exercise done so any expert advice is most welcome.


问:
Why am I getting error NG8001: 'component' is not a known element, even if it is properly imported
I have a problem with using any other component inside a CreateToolDialog component. No matter what I do, I always get the same error. Same thin is happening for every other component which i try to use in CreateToolDialog given that most of thoes components are already used somewhere and working properly. Im not sure if the problem is in the CreateToolDialog component or somewhere else since it started happening now when I created her and it is happening only for her.

```<code>Error: src/app/components/blocks/create-tool-dialog/create-tool-dialog.component.html:2:5 - error NG8001: 'app-create-tool-form' is not a known element:
1. If 'app-create-tool-form' is an Angular component, then verify that it is part of this module.
2. If 'app-create-tool-form' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

2     <app-create-tool-form></app-create-tool-form>
</code>```

CreateToolForm  is imported in SharedModule and I want to use it in CreateToolDialog, so my code look like this:

create-tool-dialog.component.html

```<code><div class="dialog-wrapper">
    <app-create-tool-form></app-create-tool-form>
</div>
</code>```

create-tool-dialog.module.ts

```<code>@NgModule({
    declarations: [CreateToolDialogComponent],
    imports: [SharedModule],
    exports: [CreateToolDialogComponent],
})
export class CreateToolDialogModule {
}
</code>```

shared.module.ts

```<code>@NgModule({
    declarations: [
        InputComponent,
        ButtonComponent,
        DataBoxComponent,
        StatusBarComponent,
        ScannerSimulatorButtonComponent,
        LoginInputsComponent,
        LoginButtonComponent,
        ToolIconBlockComponent,
        EditStatusBlockComponent,
        SelectComponent,
        BrokenToolDialogComponent,
        AlertComponent,
        CreateToolFormComponent,  <--

    ],
    imports: [CommonModule, IconsModule, FormsModule, TranslateModule],
    exports: [
        InputComponent,
        ButtonComponent,
        IconsModule,
        CommonModule,
        DataBoxComponent,
        StatusBarComponent,
        ScannerSimulatorButtonComponent,
        LoginInputsComponent,
        LoginButtonComponent,
        ToolIconBlockComponent,
        EditStatusBlockComponent,
        SelectComponent,
        BrokenToolDialogComponent,
        AlertComponent,
        CreateToolFormComponent,  <--
    ],

})
export class SharedModule { }
</code>```

Body:
I have a problem with using any other component inside a CreateToolDialog component. No matter what I do, I always get the same error. Same thin is happening for every other component which i try to use in CreateToolDialog given that most of thoes components are already used somewhere and working properly. Im not sure if the problem is in the CreateToolDialog component or somewhere else since it started happening now when I created her and it is happening only for her.

Error: src/app/components/blocks/create-tool-dialog/create-tool-dialog.component.html:2:5 - error NG8001: 'app-create-tool-form' is not a known element:
1. If 'app-create-tool-form' is an Angular component, then verify that it is part of this module.
2. If 'app-create-tool-form' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

2     <app-create-tool-form></app-create-tool-form>

CreateToolForm  is imported in SharedModule and I want to use it in CreateToolDialog, so my code look like this:

create-tool-dialog.component.html

    <app-create-tool-form></app-create-tool-form>

create-tool-dialog.module.ts

@NgModule({
    declarations: [CreateToolDialogComponent],
    imports: [SharedModule],
    exports: [CreateToolDialogComponent],
})
export class CreateToolDialogModule {
}

shared.module.ts

@NgModule({
    declarations: [
        InputComponent,
        ButtonComponent,
        DataBoxComponent,
        StatusBarComponent,
        ScannerSimulatorButtonComponent,
        LoginInputsComponent,
        LoginButtonComponent,
        ToolIconBlockComponent,
        EditStatusBlockComponent,
        SelectComponent,
        BrokenToolDialogComponent,
        AlertComponent,
        CreateToolFormComponent,  <--

    ],
    imports: [CommonModule, IconsModule, FormsModule, TranslateModule],
    exports: [
        InputComponent,
        ButtonComponent,
        IconsModule,
        CommonModule,
        DataBoxComponent,
        StatusBarComponent,
        ScannerSimulatorButtonComponent,
        LoginInputsComponent,
        LoginButtonComponent,
        ToolIconBlockComponent,
        EditStatusBlockComponent,
        SelectComponent,
        BrokenToolDialogComponent,
        AlertComponent,
        CreateToolFormComponent,  <--
    ],

})
export class SharedModule { }


问:
AWS Cognito: Hosted UI how to customize the style of the Forgot Password in CSS Templete
I am using Hosted UI of AWS Cognito for the authentication in the application. I want to change the font size and add the left margin on the headings Forgot the Password and Enter your Email below and we will send a message to reset your password as shown in the picture.

AWS Cognito's Hosted UI provides the CSS template to style the page. How could I change its style in AWS Cognito Hosted UI CSS template.css? If I try to add a function out of the mentioned classes in the CSS template then it will throw an exception and doesn't upload the CSS template.

Kindly guide me on this problem. Thanks


问:
Is there a way to get the type of something thrown?
I have a code calling some Python from C++ (with Boost.Python). I have an exception thrown when trying to get the error from Python. But my question is quite general :

If the execution throws something in a try scope, is there a way to determine the type?

Example where I try all the possible kind of exceptions I know, without success :

```<code>try { instruction(); }
catch(my_own_namespace::Exception const& e) { /*...*/ }
catch(std::exception const& e) { /*...*/ }
catch(std::string const& s) { /*...*/ }
catch(char const* s) { /*...*/ }
catch(...) { /* I'm here, and I want information about what is thrown */ }
</code>```

Body:
I have a code calling some Python from C++ (with Boost.Python). I have an exception thrown when trying to get the error from Python. But my question is quite general :

If the execution throws something in a try scope, is there a way to determine the type?

Example where I try all the possible kind of exceptions I know, without success :

try { instruction(); }
catch(my_own_namespace::Exception const& e) { /*...*/ }
catch(std::exception const& e) { /*...*/ }
catch(std::string const& s) { /*...*/ }
catch(char const* s) { /*...*/ }
catch(...) { /* I'm here, and I want information about what is thrown */ }


问:
Dataframe meta-data not attaching with TextResuseCorpus command in R
I have a dataframe (twitterdata1) with two columns that looks something like this:

full_name
text

John
I love my wife, kids, and billiards club

Larry
Best damn veterinarian in the midwest

Tom
Professor of Social Work and Substance Abuse. Ohio State.

Tim
Retired trucker, family man.

Rob
Professor of linguistics. Ohio State.

Sam
Biobehavioral Health Ph.D. student at Penn State

I am trying to turn the dataframe above into a tokenized corpus, using the TextResuseCorpus command below:

```<code>corpus <- TextReuseCorpus(text = twitterdata1, meta = list("full_name" = "full_name"), tokenizer = tokenize_ngrams, n = 2)
</code>```

The code runs without any error. But when I try to find the attached metadata (full_names), it doesn't show up. I just get the output below. How can I get the full_names to attach as metadata in the dataframe, so I don't lose that data? I would even be happy if it would attach as the name of the document.

Any help would be greatly appreciated.

```<code>> meta(corpus[[224]])
$hash_func
[1] "hash_string"

$id
[1] "doc-228"

$minhash_func
NULL

$tokenizer
[1] "tokenize_ngrams"
</code>```

Body:
I have a dataframe (twitterdata1) with two columns that looks something like this:

full_name
text

John
I love my wife, kids, and billiards club

Larry
Best damn veterinarian in the midwest

Tom
Professor of Social Work and Substance Abuse. Ohio State.

Tim
Retired trucker, family man.

Rob
Professor of linguistics. Ohio State.

Sam
Biobehavioral Health Ph.D. student at Penn State

I am trying to turn the dataframe above into a tokenized corpus, using the TextResuseCorpus command below:

corpus <- TextReuseCorpus(text = twitterdata1, meta = list("full_name" = "full_name"), tokenizer = tokenize_ngrams, n = 2)

The code runs without any error. But when I try to find the attached metadata (full_names), it doesn't show up. I just get the output below. How can I get the full_names to attach as metadata in the dataframe, so I don't lose that data? I would even be happy if it would attach as the name of the document.

Any help would be greatly appreciated.

> meta(corpus[[224]])
$hash_func
[1] "hash_string"

$id
[1] "doc-228"

$minhash_func
NULL

$tokenizer
[1] "tokenize_ngrams"


问:
python, django, modelling with instaloader
the pic:

```<code>pic = instaloader.Instaloader(sleep=False, dirname_pattern='media/donor', save_metadata=False, compress_json=False)
pic.download_profile(profile_name=username, profile_pic_only=True)
</code>```

pic's class ===>>>    <class 'instaloader.instaloader.Instaloader'>

And I'm struggling with converting instaloader class into Contributors  <<ImageField()>> of django models.

```<code>class Contributor(models.Model):
    name = models.CharField(max_length=255, default=' ')
    username = models.CharField(max_length=255, unique=True)
    type = models.ForeignKey(ContributorType, on_delete=models.CASCADE, null=True)
    picture = models.ImageField(upload_to='images/donor', max_length=255)
    cont_village = models.ForeignKey(Village, on_delete=models.CASCADE, null=True)
</code>```

How can I do this?

I tried with this way:

```<code>Contributor.objects.create(
    username=url,
    picture=pic,
)

But recieved: AttributeError
Exception Value:

'Instaloader' object has no attribute '_committed'
</code>```

Body:
the pic:

pic = instaloader.Instaloader(sleep=False, dirname_pattern='media/donor', save_metadata=False, compress_json=False)
pic.download_profile(profile_name=username, profile_pic_only=True)

pic's class ===>>>    <class 'instaloader.instaloader.Instaloader'>

And I'm struggling with converting instaloader class into Contributors  <<ImageField()>> of django models.

class Contributor(models.Model):
    name = models.CharField(max_length=255, default=' ')
    username = models.CharField(max_length=255, unique=True)
    type = models.ForeignKey(ContributorType, on_delete=models.CASCADE, null=True)
    picture = models.ImageField(upload_to='images/donor', max_length=255)
    cont_village = models.ForeignKey(Village, on_delete=models.CASCADE, null=True)

How can I do this?

I tried with this way:

Contributor.objects.create(
    username=url,
    picture=pic,
)

But recieved: AttributeError
Exception Value:

'Instaloader' object has no attribute '_committed'


问:
The repository can't find what it saved
Entity:

```<code>@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public class OveroptimisationIdentifierEntity {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Getter
    @Column(name = "id", columnDefinition = "VARCHAR(255)")
    private UUID id;

    @CreationTimestamp
    @Column(unique = true)
    private LocalDate date;
}
</code>```

Repository:

```<code>import java.util.UUID;

public interface OveroptimisationIdentifierRepository extends JpaRepository<OveroptimisationIdentifierEntity, UUID> {
    OveroptimisationIdentifierEntity findFirstByOrderByDateDesc();
}
</code>```

Create:

```<code>public OveroptimisationIdentifierEntity createIdentifier() {
    OveroptimisationIdentifierEntity identifier = OveroptimisationIdentifierEntity.builder().build();
    try {
        overoptimisationIdentifierRepository.save(identifier);
    } catch (DataIntegrityViolationException e) {
// Date must be unique. Find the tuple with the current date, delete it, and save the entity anew.
        OveroptimisationIdentifierEntity currentIdentifier = overoptimisationIdentifierRepository.findFirstByOrderByDateDesc(); // Breakpoing.
        arsenkinOveroptimisationIdentifierRepository.delete(currentIdentifier);
        overoptimisationIdentifierRepository.save(identifier);
    }

    return identifier;
}
</code>```

I have createdd an identivier with the method above. It really worked: I can see that identifier in the database. But it was a case for a clear database.

Then I try to create another identifier. But I get this exception:

https://dpaste.org/MBry7

I have put a breakpoint (signified in the code). The debugger stops at the breakpoint.

The attempt to find the identifier in the database:

Even fidnAll doesn't work:

```<code>overoptimisationIdentifierRepository.findAll()
</code>```

Could you help me understand why the repository can't find what it saved itself?
And how should I modify the code for it to be able to work?

Title: The repository can't find what it saved

Body:
Entity:

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public class OveroptimisationIdentifierEntity {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Getter
    @Column(name = "id", columnDefinition = "VARCHAR(255)")
    private UUID id;

    @CreationTimestamp
    @Column(unique = true)
    private LocalDate date;
}

Repository:

import java.util.UUID;

public interface OveroptimisationIdentifierRepository extends JpaRepository<OveroptimisationIdentifierEntity, UUID> {
    OveroptimisationIdentifierEntity findFirstByOrderByDateDesc();
}

Create:

public OveroptimisationIdentifierEntity createIdentifier() {
    OveroptimisationIdentifierEntity identifier = OveroptimisationIdentifierEntity.builder().build();
    try {
        overoptimisationIdentifierRepository.save(identifier);
    } catch (DataIntegrityViolationException e) {
// Date must be unique. Find the tuple with the current date, delete it, and save the entity anew.
        OveroptimisationIdentifierEntity currentIdentifier = overoptimisationIdentifierRepository.findFirstByOrderByDateDesc(); // Breakpoing.
        arsenkinOveroptimisationIdentifierRepository.delete(currentIdentifier);
        overoptimisationIdentifierRepository.save(identifier);
    }

    return identifier;
}

I have createdd an identivier with the method above. It really worked: I can see that identifier in the database. But it was a case for a clear database.

Then I try to create another identifier. But I get this exception:

https://dpaste.org/MBry7

I have put a breakpoint (signified in the code). The debugger stops at the breakpoint.

The attempt to find the identifier in the database:

Even fidnAll doesn't work:

overoptimisationIdentifierRepository.findAll()

Could you help me understand why the repository can't find what it saved itself?
And how should I modify the code for it to be able to work?


问:
How GraphQL returns a custom json
Test table has some field,

```<code>Test{
    baike_url,
    baike_content
}
</code>```

i use this to test GraphQL

```<code>fragment Baike on Test{
    baike_causes
}
query MyQuery {
    Test(limit: 10) {
        ..Baike
    }
}
</code>```

but is error,i want return this data

```<code>{
  "data": {
    "Test": [
      {
        "baike": {
           "baike_url":baike_url
         }
      },
      {
        "baike": {
           "baike_url":baike_url
         }
      }
    ]
  }
}
</code>```

I tried many ways, but still can't solve it

Title: How GraphQL returns a custom json

Body:
Test table has some field,

Test{
    baike_url,
    baike_content
}

i use this to test GraphQL

fragment Baike on Test{
    baike_causes
}
query MyQuery {
    Test(limit: 10) {
        ..Baike
    }
}

but is error,i want return this data

{
  "data": {
    "Test": [
      {
        "baike": {
           "baike_url":baike_url
         }
      },
      {
        "baike": {
           "baike_url":baike_url
         }
      }
    ]
  }
}

I tried many ways, but still can't solve it


问:
sending CSV file through NESTJS controller, Interceptors throwing ERROR
I have to send a csv file to nestjs through controller.
This suggestion I have got from a blog.But It throwing errors.

CONTROLLER CODE -

```<code>@Post()
  @ApiDoc()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads/csv',
        filename: csvFileName,
      }),
      fileFilter: csvFileFilter,
    }),
  )
  async getCSV() {}
</code>```

POSTMAN -

if I send data through form data , it's showing

What's the issue and how to resolve it ?

Body:
I have to send a csv file to nestjs through controller.
This suggestion I have got from a blog.But It throwing errors.

CONTROLLER CODE -

@Post()
  @ApiDoc()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads/csv',
        filename: csvFileName,
      }),
      fileFilter: csvFileFilter,
    }),
  )
  async getCSV() {}

POSTMAN -

if I send data through form data , it's showing

What's the issue and how to resolve it ?


问:
Lookup tags for a given long URL in Bitly API v4
I have an app that is fed long URLs. I need to take the long URLs and use Bitly API v4 to see what tags are associated with each long URL. The feed does not include the short URL. Is there a way to query the API to lookup tags based on the long URL?

I've tried using the shorten and bitlinks endpoints in the hopes that they would return only data about the links but they overwrite the tags and so will not work. I only want to query, not edit. (I'm using PHP.)


问:
How can I link the logger of my main class to the ones present in another module when they can't acces its name?
I have a class that creates a self.logger (self.logger = logging.getLogger(str(uuid.uuid4()))) with a unique id in order to avoid my loggers to be mixed when multiple API calls are creating class instances at the same time.
However, I have another file with my utility functions that do not belong to the class, and those functions are supposed to produce logs too.
My question is : how to I make those functions use the same logger without having to give them the id of the main logger as an argument ? Is there a way to tell a logger created in a function to use the parent logger ?

In my utility file, since I don't want to pass the logger as argument to all the functions, I simply do a logging.info to create new logs, but it is using the root logger.


问:
MySql query is not returning correct results with inner join
I am working on a MySql query that will return a filtered result from a set of results. However, the result is not using the join as expected.

First, here is the query that returns my initial data:

```<code>select `jobs`.* from `jobs`
where exists (
    select * from `job_users`
    where `jobs`.`number` = `job_users`.`job_number`
    and `user_id` = 77
)
and `is_active` = 1
and `is_complete` = 0
order by `number` desc
limit 50
offset 0;
</code>```

This returns a dataset with 14 rows. I now wish to search within this and return a subset of my original data. This is what I have:

```<code>select `jobs`.* from `jobs`
inner join `clients` on `jobs`.`client_id` = `clients`.`id`
inner join `job_comments` on `jobs`.`client_id` = `job_comments`.`id`
where exists (
    select * from `job_users`
    where `jobs`.`number` = `job_users`.`job_number`
    and `user_id` = 77
)
and `is_active` = 1
and `is_complete` = 0
and `clients`.`title` like '%se%'
or `jobs`.`title` like '%se%'
or `jobs`.`number` like '%se%'
or `job_comments`.`comment` like '%se%'
order by `number` desc
limit 50
offset 0;
</code>```

This returns a dataset derived from the entire jobs table and not the subset of jobs belonging to the user with the id of 77.

using explain on this query i get:

```<code>id | select_type        | table        | partitions | type   | possible_keys                                      | key                        | key_len | ref                           | rows  | filtered | Extra
1  | PRIMARY            | jobs         | NULL       | index  | jobs_client_id_index                               | PRIMARY                    | 8       | NULL                          | 20799 | 100.00   | Using where; Backward index scan
1  | PRIMARY            | clients      | NULL       | eq_ref | PRIMARY                                            | PRIMARY                    | 8       | laravel_ja_dec.jobs.client_id | 1     | 100.00   | NULL
1  | PRIMARY            | job_comments | NULL       | eq_ref | PRIMARY                                            | PRIMARY                    | 8       | laravel_ja_dec.jobs.client_id | 1     | 100.00   | Using where
2  | DEPENDENT SUBQUERY | job_users    | NULL       | ref    | job_users_job_number_index,job_users_user_id_index | job_users_job_number_index | 8       | laravel_ja_dec.jobs.number    | 1     | 2.78     | Using where
</code>```

I tried adjusting the ordering (placing the inner join later but this failed with an error.

How do I achieve this result so that it is a subset of the first query and not over the entire jobs table?

Thanks

*** EDIT ***
Following suggestions in reponses i tried adding parenthesis around the or conditions and this looks better (result is 11 items)

```<code>select `jobs`.* from `jobs`
inner join `clients` on `jobs`.`client_id` = `clients`.`id`
inner join `job_comments` on `jobs`.`client_id` = `job_comments`.`id`
where exists (
    select * from `job_users`
    where `jobs`.`number` = `job_users`.`job_number`
    and `user_id` = 77
) and
`is_active` = 1 and
`is_complete` = 0 and
(
    `clients`.`title` like '%se%' or
    `jobs`.`title` like '%se%' or
    `jobs`.`number` like '%se%' or
    `job_comments`.`comment` like '%se%'
)
order by `jobs`.`number` desc;
</code>```

Thanks for the pointers guys!

Body:
I am working on a MySql query that will return a filtered result from a set of results. However, the result is not using the join as expected.

First, here is the query that returns my initial data:

select `jobs`.* from `jobs`
where exists (
    select * from `job_users`
    where `jobs`.`number` = `job_users`.`job_number`
    and `user_id` = 77
)
and `is_active` = 1
and `is_complete` = 0
order by `number` desc
limit 50
offset 0;

This returns a dataset with 14 rows. I now wish to search within this and return a subset of my original data. This is what I have:

select `jobs`.* from `jobs`
inner join `clients` on `jobs`.`client_id` = `clients`.`id`
inner join `job_comments` on `jobs`.`client_id` = `job_comments`.`id`
where exists (
    select * from `job_users`
    where `jobs`.`number` = `job_users`.`job_number`
    and `user_id` = 77
)
and `is_active` = 1
and `is_complete` = 0
and `clients`.`title` like '%se%'
or `jobs`.`title` like '%se%'
or `jobs`.`number` like '%se%'
or `job_comments`.`comment` like '%se%'
order by `number` desc
limit 50
offset 0;

This returns a dataset derived from the entire jobs table and not the subset of jobs belonging to the user with the id of 77.

using explain on this query i get:

id | select_type        | table        | partitions | type   | possible_keys                                      | key                        | key_len | ref                           | rows  | filtered | Extra
1  | PRIMARY            | jobs         | NULL       | index  | jobs_client_id_index                               | PRIMARY                    | 8       | NULL                          | 20799 | 100.00   | Using where; Backward index scan
1  | PRIMARY            | clients      | NULL       | eq_ref | PRIMARY                                            | PRIMARY                    | 8       | laravel_ja_dec.jobs.client_id | 1     | 100.00   | NULL
1  | PRIMARY            | job_comments | NULL       | eq_ref | PRIMARY                                            | PRIMARY                    | 8       | laravel_ja_dec.jobs.client_id | 1     | 100.00   | Using where
2  | DEPENDENT SUBQUERY | job_users    | NULL       | ref    | job_users_job_number_index,job_users_user_id_index | job_users_job_number_index | 8       | laravel_ja_dec.jobs.number    | 1     | 2.78     | Using where

I tried adjusting the ordering (placing the inner join later but this failed with an error.

How do I achieve this result so that it is a subset of the first query and not over the entire jobs table?

Thanks

*** EDIT ***
Following suggestions in reponses i tried adding parenthesis around the or conditions and this looks better (result is 11 items)

select `jobs`.* from `jobs`
inner join `clients` on `jobs`.`client_id` = `clients`.`id`
inner join `job_comments` on `jobs`.`client_id` = `job_comments`.`id`
where exists (
    select * from `job_users`
    where `jobs`.`number` = `job_users`.`job_number`
    and `user_id` = 77
) and
`is_active` = 1 and
`is_complete` = 0 and
(
    `clients`.`title` like '%se%' or
    `jobs`.`title` like '%se%' or
    `jobs`.`number` like '%se%' or
    `job_comments`.`comment` like '%se%'
)
order by `jobs`.`number` desc;

Thanks for the pointers guys!


问:
WCF When responding via Message.CreateMessage tags are swapped
I am implementing the IDispatchMessageInspector in the BeforeSendReply method, in which the signed xml is loaded. For clarity, an xml document without a signature.

```<code>string testXml = System.IO.File.ReadAllText("C:\\test\\test.xml");
XmlReader reader = XmlReader.Create(new StringReader(testXml));
var message = Message.CreateMessage(reader, int.MaxValue, reply.Version);
reply = message;
</code>```

After receiving the response in SoapUI, the tags are swapped. The upper xml loaded from the file, the lower response in SoapUI This response does not pass validation, by checksum.

Please tell me, is it possible to return the data without changes?

The function for the signature returns a string. Maybe there are other ways to return the answer?

Body:
I am implementing the IDispatchMessageInspector in the BeforeSendReply method, in which the signed xml is loaded. For clarity, an xml document without a signature.

string testXml = System.IO.File.ReadAllText("C:\\test\\test.xml");
XmlReader reader = XmlReader.Create(new StringReader(testXml));
var message = Message.CreateMessage(reader, int.MaxValue, reply.Version);
reply = message;

After receiving the response in SoapUI, the tags are swapped. The upper xml loaded from the file, the lower response in SoapUI This response does not pass validation, by checksum.

Please tell me, is it possible to return the data without changes?

The function for the signature returns a string. Maybe there are other ways to return the answer?


问:
searching within a specific folder for an item in onedrive, not working
I try to search for a file within a specific folder.

I'm using a 3de party software called make that is a low/no code program for creating automations. to be sure it was not a problem with the integration they made i used the development tool of microsoft https://developer.microsoft.com/en-us/graph/graph-explorer and got the same problem.

When I search for it from the root directory I'm able to find the file

search for file from root

but when I try to search for it in the folder that contains the file I get nothing back.

search for file from folder

I don't know what i'm missing or doing wrong here.


问:
Send direct message on Instagram using Instagrapi Python
I'm trying to use the Instagrapi Python library to send a DM to a user on Instagram. Here is the code I'm using:

```<code>from instagrapi import Client

username = "username"
password = "password"
arrayOfUsers = [1234567890] * 1

cl = Client()
cl.login(username, password)
cl.direct_send('Hello', arrayOfUsers) #direct_send(text: str, user_ids: List[int] = [], thread_ids: List[int] = [])
</code>```

However, I'm getting the following error:

```<code>Status 429: Too many requests
Ignore 429: Continue login
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 302, in _send_private_request
    response.raise_for_status()
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://i.instagram.com/api/v1/accounts/login/

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 438, in private_request
    self._send_private_request(endpoint, **kwargs)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 334, in _send_private_request
    raise ChallengeRequired(**last_json)
instagrapi.exceptions.ChallengeRequired: challenge_required

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\Desktop\sid PY\sid3.py", line 8, in <module>
    cl.login(username, password)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\auth.py", line 390, in login
    logged = self.private_request("accounts/login/", data, login=True)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 449, in private_request
    self.challenge_resolve(self.last_json)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\challenge.py", line 78, in challenge_resolve
    return self.challenge_resolve_simple(challenge_url)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\challenge.py", line 425, in challenge_resolve_simple
    raise ChallengeUnknownStep(f'ChallengeResolve: Unknown step_name "{step_name}" for "{self.username}" in challenge resolver: {self.last_json}')
instagrapi.exceptions.ChallengeUnknownStep: ChallengeResolve: Unknown step_name "select_contact_point_recovery" for "MYIGUSERNAME" in challenge resolver: {'step_name': 'select_contact_point_recovery', 'step_data': {'choice': '1', 'email': 'EMAIL@gmail.com', 'hl_co_enabled': False, 'sigp_to_hl': False}, 'flow_render_type': 3, 'bloks_action': 'com.instagram.challenge.navigation.take_challenge', 'nonce_code': 'NONCE_CODE', 'user_id': USER_ID, 'cni': USER_CNI, 'challenge_context': '{"step_name": "select_contact_point_recovery", "nonce_code": "NONCE_CODE", "user_id": USER_ID, "cni": USER_CNI, "is_stateless": false, "challenge_type_enum": "HACKED_LOCK", "present_as_modal": false}', 'challenge_type_enum_str': 'HACKED_LOCK', 'status': 'ok'}
</code>```

Why do I get Status 429: Too many requests when I login only once? Can someone please explain what this error means and how I can fix it? Thank you!

Body:
I'm trying to use the Instagrapi Python library to send a DM to a user on Instagram. Here is the code I'm using:

from instagrapi import Client

username = "username"
password = "password"
arrayOfUsers = [1234567890] * 1

cl = Client()
cl.login(username, password)
cl.direct_send('Hello', arrayOfUsers) #direct_send(text: str, user_ids: List[int] = [], thread_ids: List[int] = [])

However, I'm getting the following error:

Status 429: Too many requests
Ignore 429: Continue login
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 302, in _send_private_request
    response.raise_for_status()
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://i.instagram.com/api/v1/accounts/login/

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 438, in private_request
    self._send_private_request(endpoint, **kwargs)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 334, in _send_private_request
    raise ChallengeRequired(**last_json)
instagrapi.exceptions.ChallengeRequired: challenge_required

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\Desktop\sid PY\sid3.py", line 8, in <module>
    cl.login(username, password)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\auth.py", line 390, in login
    logged = self.private_request("accounts/login/", data, login=True)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\private.py", line 449, in private_request
    self.challenge_resolve(self.last_json)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\challenge.py", line 78, in challenge_resolve
    return self.challenge_resolve_simple(challenge_url)
  File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\instagrapi\mixins\challenge.py", line 425, in challenge_resolve_simple
    raise ChallengeUnknownStep(f'ChallengeResolve: Unknown step_name "{step_name}" for "{self.username}" in challenge resolver: {self.last_json}')
instagrapi.exceptions.ChallengeUnknownStep: ChallengeResolve: Unknown step_name "select_contact_point_recovery" for "MYIGUSERNAME" in challenge resolver: {'step_name': 'select_contact_point_recovery', 'step_data': {'choice': '1', 'email': 'EMAIL@gmail.com', 'hl_co_enabled': False, 'sigp_to_hl': False}, 'flow_render_type': 3, 'bloks_action': 'com.instagram.challenge.navigation.take_challenge', 'nonce_code': 'NONCE_CODE', 'user_id': USER_ID, 'cni': USER_CNI, 'challenge_context': '{"step_name": "select_contact_point_recovery", "nonce_code": "NONCE_CODE", "user_id": USER_ID, "cni": USER_CNI, "is_stateless": false, "challenge_type_enum": "HACKED_LOCK", "present_as_modal": false}', 'challenge_type_enum_str': 'HACKED_LOCK', 'status': 'ok'}

Why do I get Status 429: Too many requests when I login only once? Can someone please explain what this error means and how I can fix it? Thank you!


问:
DEVELOPER_ERROR in my google sigin android app react native firebase when choosing the google account?
 I am working on this error for last 4 days but unable to solve .
When i am choose account while using react native google signin after choosing any account it shows DEVELOPER_ERROR in console and alert i even check my sha-1 key both are same in project and firebase project and even re download and use google json file again and check web client id all is fine but error is same i even create a new web credential and use it id but noting work for me what should i do now i spend 4 days on it till now

```<code>import React, { useState,useEffect } from 'react';
import { View, StyleSheet, TextInput,Button, TouchableOpacity, Text } from 'react-native'
import {
    GoogleSignin,
    GoogleSigninButton,
    statusCodes,
    } from '@react-native-google-signin/google-signin';

const GoogleLogin = ({navigation}) => {
    const [loggedIn, setloggedIn] = useState(false);
    const [userInfo, setuserInfo] = useState([]);

    useEffect(() => {
      GoogleSignin.configure({
        scopes: ['email'], // what API you want to access on behalf of the user, default is email and profile
        // androidClientId: '429291652902-u76oe5ffntn1m79h10lv56ecm9bq83n1.apps.googleusercontent.com',

        webClientId:
          '429291652902-u1cu4i0n83a9cn4pqrh965kvi21odv82.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
        offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
      });

    }, []);

    const signIn = async () => {
      await GoogleSignin.signOut();
      await GoogleSignin.hasPlayServices();
      await GoogleSignin.signIn()
      .then((response) => {
          console.log("ye aya google ka response", response);
          setisloading(true);
          const body = {
            email: response?.user?.email,
            socialId: response?.user?.id,
            phoneNumber: "",
            FCMtoken: FCM,
          };
          checkUserExistence(body);
        })
        .catch((err) => {
          console.log(err);
          alert(err.message);
          if (err.code === statusCodes.SIGN_IN_CANCELLED) {
          } else if (err.code === statusCodes.IN_PROGRESS) {

          } else if (err.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
          } else {
          }
        });
    };

     const signOut = async () => {
        try {
          await GoogleSignin.revokeAccess();
          await GoogleSignin.signOut();
          setloggedIn(false);
          setuserInfo([]);
        } catch (error) {
          console.error(error);
        }
      };

    return (
        <View style={styles.container}>

           <GoogleSigninButton
                style={{width: 192, height: 48}}
                size={GoogleSigninButton.Size.Wide}
                color={GoogleSigninButton.Color.Dark}
                onPress={()=>signIn()}
              />

{!loggedIn && <Text>You are currently logged out</Text>}
              {loggedIn && (
                <Button
                  onPress={()=>signOut()}
                  title="LogOut"
                  color="red"></Button>
              )}
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        padding: 10,
        marginTop: 100,
    },

});

export default GoogleLogin;
</code>```

Body:
 I am working on this error for last 4 days but unable to solve .
When i am choose account while using react native google signin after choosing any account it shows DEVELOPER_ERROR in console and alert i even check my sha-1 key both are same in project and firebase project and even re download and use google json file again and check web client id all is fine but error is same i even create a new web credential and use it id but noting work for me what should i do now i spend 4 days on it till now

import React, { useState,useEffect } from 'react';
import { View, StyleSheet, TextInput,Button, TouchableOpacity, Text } from 'react-native'
import {
    GoogleSignin,
    GoogleSigninButton,
    statusCodes,
    } from '@react-native-google-signin/google-signin';

const GoogleLogin = ({navigation}) => {
    const [loggedIn, setloggedIn] = useState(false);
    const [userInfo, setuserInfo] = useState([]);

    useEffect(() => {
      GoogleSignin.configure({
        scopes: ['email'], // what API you want to access on behalf of the user, default is email and profile
        // androidClientId: '429291652902-u76oe5ffntn1m79h10lv56ecm9bq83n1.apps.googleusercontent.com',

        webClientId:
          '429291652902-u1cu4i0n83a9cn4pqrh965kvi21odv82.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
        offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
      });

    }, []);

    const signIn = async () => {
      await GoogleSignin.signOut();
      await GoogleSignin.hasPlayServices();
      await GoogleSignin.signIn()
      .then((response) => {
          console.log("ye aya google ka response", response);
          setisloading(true);
          const body = {
            email: response?.user?.email,
            socialId: response?.user?.id,
            phoneNumber: "",
            FCMtoken: FCM,
          };
          checkUserExistence(body);
        })
        .catch((err) => {
          console.log(err);
          alert(err.message);
          if (err.code === statusCodes.SIGN_IN_CANCELLED) {
          } else if (err.code === statusCodes.IN_PROGRESS) {

          } else if (err.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
          } else {
          }
        });
    };

     const signOut = async () => {
        try {
          await GoogleSignin.revokeAccess();
          await GoogleSignin.signOut();
          setloggedIn(false);
          setuserInfo([]);
        } catch (error) {
          console.error(error);
        }
      };

    return (
        <View style={styles.container}>

           <GoogleSigninButton
                style={{width: 192, height: 48}}
                size={GoogleSigninButton.Size.Wide}
                color={GoogleSigninButton.Color.Dark}
                onPress={()=>signIn()}
              />

{!loggedIn && <Text>You are currently logged out</Text>}
              {loggedIn && (
                <Button
                  onPress={()=>signOut()}
                  title="LogOut"
                  color="red"></Button>
              )}
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        padding: 10,
        marginTop: 100,
    },

});

export default GoogleLogin;


问:
How does the period attribute work in seasonal_decompose()
I am new to seasonal decomposition. I read some interesting articles on the net regarding the python function responsible for doing that, yet I do not understand how the "period" attribute works. Obviously, it is an Integer but what does it mean if I, for example, choose it to be 12? How does it influence the seasonal decomposition of the concerned data frame?

Let's say that I have a periodic(100,) shaped decompose_lift.lift with a column "date", with the following format YYYY-MM:
meaning that I have the data structured monthly like this:

```<code>date        values
2010-01-01  0.182
2010-02-01  0.1
2010-03-01  0.233
2010-04-01  0.34
.
.
.
2018-10-01 0.182
2018-11-01 0.736
2018-12-01 0.915

</code>```

I am using the following function obviously:

```<code>decomposition_lift = seasonal_decompose(decompose_lift.lift, model = 'multiplicative',period=???)

</code>```

Please feel free to tell me if my question is not well stated.
Thanks

Body:
I am new to seasonal decomposition. I read some interesting articles on the net regarding the python function responsible for doing that, yet I do not understand how the "period" attribute works. Obviously, it is an Integer but what does it mean if I, for example, choose it to be 12? How does it influence the seasonal decomposition of the concerned data frame?

Let's say that I have a periodic(100,) shaped decompose_lift.lift with a column "date", with the following format YYYY-MM:
meaning that I have the data structured monthly like this:

date        values
2010-01-01  0.182
2010-02-01  0.1
2010-03-01  0.233
2010-04-01  0.34
.
.
.
2018-10-01 0.182
2018-11-01 0.736
2018-12-01 0.915

I am using the following function obviously:

decomposition_lift = seasonal_decompose(decompose_lift.lift, model = 'multiplicative',period=???)

Please feel free to tell me if my question is not well stated.
Thanks


问:
Boostrap 5 dropdown not working when adding specific line in Typescript
I have this dropdown which shows several buttons, one of them opens a modal. The dropdown is in the template of app-component and the modal is in the template of login-modal.

app.component.html:

```<code><app-login-modal (validLogin)="changeCredentials($event)"></app-login-modal>

<div class="dropdown">
      <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
        <img src="https://github.com/mdo.png" alt="" width="32" height="32" class="rounded-circle me-2">
        <strong>mdo</strong>
      </a>
      <ul class="dropdown-menu dropdown-menu-dark text-small shadow">
        <li><a class="dropdown-item" href="#">New project...</a></li>
        <li><a class="dropdown-item" href="#">Settings</a></li>
        <li><button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#loginModal" *ngIf="!this.logged">Log in</button></li>
        <li><button class="dropdown-item" (click)="logout()" type="button" *ngIf="this.logged">Log out</button></li>
      </ul>
    </div>
</code>```

It works perfectly until I add this line of code in the component of the login modal:

login-modal.component.ts

```<code>    let modal : bootstrap.Modal | null = bootstrap.Modal.getInstance(modalElement!);
</code>```

After adding that line, the dropdow does not show anymore. Why?

PD: angular.json:

```<code>"scripts": [
              "@popperjs/core/dist/umd/popper.min.js",
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]
</code>```

I really cant understand why a line of code which is not even in the same component is breaking my dropdown menu

Body:
I have this dropdown which shows several buttons, one of them opens a modal. The dropdown is in the template of app-component and the modal is in the template of login-modal.

app.component.html:

<app-login-modal (validLogin)="changeCredentials($event)"></app-login-modal>

        mdo

New project...

Settings

<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#loginModal" *ngIf="!this.logged">Log in</button>

<button class="dropdown-item" (click)="logout()" type="button" *ngIf="this.logged">Log out</button>

It works perfectly until I add this line of code in the component of the login modal:

login-modal.component.ts

    let modal : bootstrap.Modal | null = bootstrap.Modal.getInstance(modalElement!);

After adding that line, the dropdow does not show anymore. Why?

PD: angular.json:

"scripts": [
              "@popperjs/core/dist/umd/popper.min.js",
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]

I really cant understand why a line of code which is not even in the same component is breaking my dropdown menu


问:
Not able to create unique symbology in R shiny leaflet based on unique type in a field and radio button interaction not working
Problem 1: I want to add unique colors to every factor type (this is also what I am selecting from the dropdown)
for example if a person selects "Mall" the mall points are getting selected but the colors are not changing on a different feature type say "Restaurant"

Problem 2: When I select my recreation type from the dropdown, The data is being subset, I want subset this data further based on "If there is a metrostation within 5km of the leisure spot". I have 3 options of the radio button.
Option 1. I don't care: No further subset is required
Option 2: Yes: Keep only those features selected by the dropdown that have a metro within 5km proximity
Option 3: No: Keep only those features selected by the dropdown that "do not" have a metro within 5km proximity

I am unable to add pallet colors and do the second level of filtering. Please help me, I am new to Shiny and R!

My code and the sample data is attached below

```<code>``` {r}
#Gobal.r

library(shiny)
library(leaflet)
library(rgdal)
library(shinyWidgets)
library(sf)
library(dplyr)
#install.packages("shinydashboard")
library(shinydashboard)
leisure <-  st_read("D:/geomatics/umich/Sem1/geoviz/project/shpefiles/All_Leisure_Spaces.shp")

final_rec <- st_transform(leisure, 4326)

```

``` {r}
# ui.r

ui <- dashboardPage(

      dashboardHeader(title = "Leisure space"),

      dashboardSidebar(

      shinyWidgets::pickerInput("variables","Select a recreation type:", choices=c(unique(final_rec$type)), options = list(`actions-box` = TRUE),multiple = T),

      #pickerInput("metroinput","Metro within 5km radius", choices=c("Select yes/no", "yes", "no" ),selected = "Select #yes/no", options = list(`actions-box` = F),multiple = F)),

      shinyWidgets::prettyRadioButtons("rb", "Do you want a metro station within 5km proximity?", choices = c("I don't care", "Yes", "No"))),

      dashboardBody(leafletOutput(outputId = 'map', height = 930))
      )
ui
```

```{r}
# server.r

server <- function(input, output) {
  output$map <- renderLeaflet({

# define pal
pal <- colorFactor(
      palette = c("#dff21b","#dc8f5b","#1b6cf4", "#2bc85a", "#6404a0", "#3cd0dc", "#fb0d39"),
      levels = c("Auditorium","Bar and Lounge", "Cafe", "Mall/Shopping", "Relaxation", "Restaurant", "Tourist Destination"),
     domain = final_rec$type # as.numeric(na.omit(x))
    )

    #Set basemap
    leaflet(final_rec) %>%
           setView("map", lng = 77.59, lat = 12.97, zoom = 13)%>%
      addProviderTiles("CartoDB.Positron", group = "CartoDB") %>%
      addTiles(group = "OSM (default)") %>%
   addCircles( ~long,~lat, radius = 11, color = ~pal(type), opacity = 1) %>%
    addLegend("bottomright", pal = pal, values = ~type, title = legend.title, labFormat = labelFormat(suffix = ""),
      opacity = 1) %>%
      addLayersControl(baseGroups = c("CartoDB", "OSM (default)"),options = layersControlOptions(collapsed = FALSE))

  })

  #Select leisure
  selectedRec <- reactive({

    final_rec[final_rec$type %in% input$variables, ] })

legend.title <- "Recreation Space"
  observe({
    popup <- paste0("Feature Type: ",
                        selectedRec()$type)

    leafletProxy("map", data = selectedRec()) %>%
      clearShapes() %>%
      addCircles( ~long,~lat, color = pal(type)
                  )%>%
addLegend("bottomright",colors = ~pal(selectedRec()$variables), values = ~selectedRec()$variables, title = legend.title, labFormat = labelFormat(suffix = ""), opacity = 1)
  })

# proximity to metro
observeEvent(input$rb, {

    if (input$rb == "I don't care") {
      leafletProxy(mapId = "map", data = selectedRec()) %>% addCircles(data= selectedRec(), ~long, ~lat)
    }

    else if (input$rb == "yes")
      {
      leafletProxy(mapId = "map") %>%
      clearShapes() %>%
     dplyr::filter(selectedRec()$metro_5km %in% input$rb) %>%
      addCircles(~long, ~lat)
    }

    else if (input$rb == "no") {
      leafletProxy(mapId = "map") %>%
      clearShapes() %>%
      dplyr::filter(selectedRec()$metro_5km == "no" ) %>%
      addCircles(~long, ~lat)
    }

  })
}

shinyApp(ui, server)
```

```
# sample data

| FID| type             |  metro_5km | lat        |long        |shape |
| ---|-----             | --------   |--------    | --------   |----  |
| 1  | Restaurant       | yes        |12.97109985 |77.59609985 |Point |
| 2  | Mall             | no         |12.9677     |77.53600311 |Point |
| 3  | Bar and Lounge   | yes        |12.98880005 |77.53820038 |Point |
| 4  | Relaxation       | no         |12.99549961 |77.61419678 |Point |
| 5  | Cafe             | no         |12.99779987 |77.6147995  |Point |
| 6  | Auditorium       | yes        |12.98799992 |77.61920166 |Point |
| 7  | Relaxation       | yes        |12.9382     |77.58480072 |Point |
| 8  | Cafe             | yes        |12.9715004  |77.59760284 |Point |

```
</code>```

Both Bar and Lounge are selected but they are in the same color, I want them in different colors that I have specified in the pallet (basically I want the pallete reactive

And the radio button interaction not working!!

Body:
Problem 1: I want to add unique colors to every factor type (this is also what I am selecting from the dropdown)
for example if a person selects "Mall" the mall points are getting selected but the colors are not changing on a different feature type say "Restaurant"

Problem 2: When I select my recreation type from the dropdown, The data is being subset, I want subset this data further based on "If there is a metrostation within 5km of the leisure spot". I have 3 options of the radio button.
Option 1. I don't care: No further subset is required
Option 2: Yes: Keep only those features selected by the dropdown that have a metro within 5km proximity
Option 3: No: Keep only those features selected by the dropdown that "do not" have a metro within 5km proximity

I am unable to add pallet colors and do the second level of filtering. Please help me, I am new to Shiny and R!

My code and the sample data is attached below

``` {r}
#Gobal.r

library(shiny)
library(leaflet)
library(rgdal)
library(shinyWidgets)
library(sf)
library(dplyr)
#install.packages("shinydashboard")
library(shinydashboard)
leisure <-  st_read("D:/geomatics/umich/Sem1/geoviz/project/shpefiles/All_Leisure_Spaces.shp")

final_rec <- st_transform(leisure, 4326)

```

``` {r}
# ui.r

ui <- dashboardPage(

      dashboardHeader(title = "Leisure space"),

      dashboardSidebar(

      shinyWidgets::pickerInput("variables","Select a recreation type:", choices=c(unique(final_rec$type)), options = list(`actions-box` = TRUE),multiple = T),

      #pickerInput("metroinput","Metro within 5km radius", choices=c("Select yes/no", "yes", "no" ),selected = "Select #yes/no", options = list(`actions-box` = F),multiple = F)),

      shinyWidgets::prettyRadioButtons("rb", "Do you want a metro station within 5km proximity?", choices = c("I don't care", "Yes", "No"))),

      dashboardBody(leafletOutput(outputId = 'map', height = 930))
      )
ui
```

```{r}
# server.r

server <- function(input, output) {
  output$map <- renderLeaflet({

# define pal
pal <- colorFactor(
      palette = c("#dff21b","#dc8f5b","#1b6cf4", "#2bc85a", "#6404a0", "#3cd0dc", "#fb0d39"),
      levels = c("Auditorium","Bar and Lounge", "Cafe", "Mall/Shopping", "Relaxation", "Restaurant", "Tourist Destination"),
     domain = final_rec$type # as.numeric(na.omit(x))
    )

    #Set basemap
    leaflet(final_rec) %>%
           setView("map", lng = 77.59, lat = 12.97, zoom = 13)%>%
      addProviderTiles("CartoDB.Positron", group = "CartoDB") %>%
      addTiles(group = "OSM (default)") %>%
   addCircles( ~long,~lat, radius = 11, color = ~pal(type), opacity = 1) %>%
    addLegend("bottomright", pal = pal, values = ~type, title = legend.title, labFormat = labelFormat(suffix = ""),
      opacity = 1) %>%
      addLayersControl(baseGroups = c("CartoDB", "OSM (default)"),options = layersControlOptions(collapsed = FALSE))

  })

  #Select leisure
  selectedRec <- reactive({

    final_rec[final_rec$type %in% input$variables, ] })

legend.title <- "Recreation Space"
  observe({
    popup <- paste0("<strong>Feature Type: </strong>",
                        selectedRec()$type)

    leafletProxy("map", data = selectedRec()) %>%
      clearShapes() %>%
      addCircles( ~long,~lat, color = pal(type)
                  )%>%
addLegend("bottomright",colors = ~pal(selectedRec()$variables), values = ~selectedRec()$variables, title = legend.title, labFormat = labelFormat(suffix = ""), opacity = 1)
  })

# proximity to metro
observeEvent(input$rb, {

    if (input$rb == "I don't care") {
      leafletProxy(mapId = "map", data = selectedRec()) %>% addCircles(data= selectedRec(), ~long, ~lat)
    }

    else if (input$rb == "yes")
      {
      leafletProxy(mapId = "map") %>%
      clearShapes() %>%
     dplyr::filter(selectedRec()$metro_5km %in% input$rb) %>%
      addCircles(~long, ~lat)
    }

    else if (input$rb == "no") {
      leafletProxy(mapId = "map") %>%
      clearShapes() %>%
      dplyr::filter(selectedRec()$metro_5km == "no" ) %>%
      addCircles(~long, ~lat)
    }

  })
}

shinyApp(ui, server)
```

```
# sample data

| FID| type             |  metro_5km | lat        |long        |shape |
| ---|-----             | --------   |--------    | --------   |----  |
| 1  | Restaurant       | yes        |12.97109985 |77.59609985 |Point |
| 2  | Mall             | no         |12.9677     |77.53600311 |Point |
| 3  | Bar and Lounge   | yes        |12.98880005 |77.53820038 |Point |
| 4  | Relaxation       | no         |12.99549961 |77.61419678 |Point |
| 5  | Cafe             | no         |12.99779987 |77.6147995  |Point |
| 6  | Auditorium       | yes        |12.98799992 |77.61920166 |Point |
| 7  | Relaxation       | yes        |12.9382     |77.58480072 |Point |
| 8  | Cafe             | yes        |12.9715004  |77.59760284 |Point |

```

Both Bar and Lounge are selected but they are in the same color, I want them in different colors that I have specified in the pallet (basically I want the pallete reactive

And the radio button interaction not working!!


问:
How can I display total amount, principal and interest earned for a range of years in python?
I am writing a python program that calculates the compound interest. Right now in my program I ask the user to input the years, day and months and convert it to total years (for example, if user inputs 2 years, 6 months and 73 days, this equals to 2.7 years.) I also understand how compound interest works which is earning interest on interest. In my program, I ask for principal, rate, compounding period and the correct answer returns.
The problem I am having is that I want to be able to display something similar to a table where it displays the total amount, principal and interest earned for a range of years.

I have added what I have so far, I'm still new to python so I appreciate all your help, thank you!

This is what I have so far

```<code>```
def get_time():
    year = float(input("enter year: "))
    month = float(input("enter months: "))
    day = float(input("enter days: "))
    day = day/365
    month = month/12
    year = (month + day) + year
    print(f"total time in years is: %.2f" %year)
    return year

def compound_interest(year):
    p = float(input("enter principal: "))
    r = float(input("enter rate: "))
    n = float(input("enter compounding period: "))
    FV = p * (((1+ ((r/100)/n)) ** (n*year)))
    print ("final amount after" year "years is" FV)
    return FV

    year = get_time()
    print(compound_interest(year))
```
</code>```

Body:
I am writing a python program that calculates the compound interest. Right now in my program I ask the user to input the years, day and months and convert it to total years (for example, if user inputs 2 years, 6 months and 73 days, this equals to 2.7 years.) I also understand how compound interest works which is earning interest on interest. In my program, I ask for principal, rate, compounding period and the correct answer returns.
The problem I am having is that I want to be able to display something similar to a table where it displays the total amount, principal and interest earned for a range of years.

I have added what I have so far, I'm still new to python so I appreciate all your help, thank you!

This is what I have so far

```
def get_time():
    year = float(input("enter year: "))
    month = float(input("enter months: "))
    day = float(input("enter days: "))
    day = day/365
    month = month/12
    year = (month + day) + year
    print(f"total time in years is: %.2f" %year)
    return year

def compound_interest(year):
    p = float(input("enter principal: "))
    r = float(input("enter rate: "))
    n = float(input("enter compounding period: "))
    FV = p * (((1+ ((r/100)/n)) ** (n*year)))
    print ("final amount after" year "years is" FV)
    return FV

    year = get_time()
    print(compound_interest(year))
```


问:
python cv2 - detect with of blob at given positions
I have this image containing a gray blob:

and would need to measure the horizontal width of the gray blob at various positions.

For example:

Ideally, I would define the Y position, and it would start at that height, at Width/2 and go left and right, to find the width of the blob in pixels. The blob is always at the horizontal center of the image. It would also have to ignore the small speckles. I do already have the contour of this blob in a variable in case that helps.

```<code> contours, hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
 if len(contours) != 0:
     c = max(contours, key=cv2.contourArea)
</code>```

Body:
I have this image containing a gray blob:

and would need to measure the horizontal width of the gray blob at various positions.

For example:

Ideally, I would define the Y position, and it would start at that height, at Width/2 and go left and right, to find the width of the blob in pixels. The blob is always at the horizontal center of the image. It would also have to ignore the small speckles. I do already have the contour of this blob in a variable in case that helps.

 contours, hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
 if len(contours) != 0:
     c = max(contours, key=cv2.contourArea)


问:
Django redirect after save form in context_processor
I will if form saved, redirect my users. But it does'nt worked.

Error: dictionary update sequence element #0 has length 0; 2 is required

context_processor

```<code>from .models import StaticPages
from .forms import ContactForm
from django.shortcuts import redirect
from django.urls import reverse
def main(request):
    pages = StaticPages.objects.all()
    if request.method == 'POST':  # If the form has been submitted...
        contactform = ContactForm(request.POST)  # A form bound to the POST data
        if contactform.is_valid():  # All validation rules pass
            contactform.save()
            return redirect(reverse('index'))

    else:
        contactform = ContactForm()  # An unbound form
    context ={
        'pages':pages,
        'contactform':contactform

    }
    return(context)
</code>```

my main urls.py:

```<code>from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
...
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

my core.urls:

```<code>from django.urls import path
from .views import MainDashBoard

urlpatterns = [
    path('', MainDashBoard, name='index'),
]
</code>```

views.py:

```<code>from django.shortcuts import render
from service.models import Service
from product.models import Product
def MainDashBoard(request):
    service = Service.objects.all()
    products = Product.objects.all()
    context ={
        'service':service,
        'products':products
    }
    return render(request, "MainDashBoard.html", context=context)
</code>```

Body:
I will if form saved, redirect my users. But it does'nt worked.

Error: dictionary update sequence element #0 has length 0; 2 is required

context_processor

from .models import StaticPages
from .forms import ContactForm
from django.shortcuts import redirect
from django.urls import reverse
def main(request):
    pages = StaticPages.objects.all()
    if request.method == 'POST':  # If the form has been submitted...
        contactform = ContactForm(request.POST)  # A form bound to the POST data
        if contactform.is_valid():  # All validation rules pass
            contactform.save()
            return redirect(reverse('index'))

    else:
        contactform = ContactForm()  # An unbound form
    context ={
        'pages':pages,
        'contactform':contactform

    }
    return(context)

my main urls.py:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
...
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

my core.urls:

from django.urls import path
from .views import MainDashBoard

urlpatterns = [
    path('', MainDashBoard, name='index'),
]

views.py:

from django.shortcuts import render
from service.models import Service
from product.models import Product
def MainDashBoard(request):
    service = Service.objects.all()
    products = Product.objects.all()
    context ={
        'service':service,
        'products':products
    }
    return render(request, "MainDashBoard.html", context=context)