问:
No podspec found for `React-Core` in `../node_modules/react-native`
I got an error:

```<code> No podspec found for `React-Core` in `../node_modules/react-native`
</code>```

And this is my Podfile:

```<code>    target 'RNNativeOrientationInteractor' do
  # Comment the next line if you don't want to use dynamic frameworks
  # use_frameworks!

  # Your 'node_modules' directory is probably in the root of your project,
  # but if not, adjust the `:path` accordingly
  pod 'React', :path => '../node_modules/react-native'
  pod 'React-Core', :path => '../node_modules/react-native'
  pod 'React-DevSupport', :path => '../node_modules/react-native/React'
  pod 'React-fishhook', :path => '../node_modules/react-native/Libraries/fishhook'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-RCTWebSocket', :path => '../node_modules/react-native/Libraries/WebSocket'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

end
</code>```

答:
According to upgrade tool report, If your ReactNative Version between 0.60.6 - 0.61.1. React-Core.podspec was moved from

```<code>pod 'React-Core', :path => '../node_modules/react-native/React'
</code>```

to

```<code>pod 'React-Core', :path => '../node_modules/react-native'
</code>```

But for previous versions, Change your React-Core path in Podfile to

```<code>pod 'React-Core', :path => '../node_modules/react-native/React'
</code>```

In order to confirm that, Check path ../node_modules/react-native/React/React-Core.podspec is really exists relative to Podfile.

Hope this helps you. Feel free for doubts.

Body:
I got an error:

 No podspec found for `React-Core` in `../node_modules/react-native`

And this is my Podfile:

    target 'RNNativeOrientationInteractor' do
  # Comment the next line if you don't want to use dynamic frameworks
  # use_frameworks!

  # Your 'node_modules' directory is probably in the root of your project,
  # but if not, adjust the `:path` accordingly
  pod 'React', :path => '../node_modules/react-native'
  pod 'React-Core', :path => '../node_modules/react-native'
  pod 'React-DevSupport', :path => '../node_modules/react-native/React'
  pod 'React-fishhook', :path => '../node_modules/react-native/Libraries/fishhook'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-RCTWebSocket', :path => '../node_modules/react-native/Libraries/WebSocket'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

end

Body:
According to upgrade tool report, If your ReactNative Version between 0.60.6 - 0.61.1. React-Core.podspec was moved from

pod 'React-Core', :path => '../node_modules/react-native/React'

to

pod 'React-Core', :path => '../node_modules/react-native'

But for previous versions, Change your React-Core path in Podfile to

pod 'React-Core', :path => '../node_modules/react-native/React'

In order to confirm that, Check path ../node_modules/react-native/React/React-Core.podspec is really exists relative to Podfile.

Hope this helps you. Feel free for doubts.


来源: stackexchange

问:
finer-grained control than with LD_PRELOAD?
I have a dynamically linked ELF executable on Linux, and I want to swap a function in a library it is linked against. With LD_PRELOAD I can, of course, supply a small library with a replacement for the function that I compile myself. However, what if in the replacement I want to call the original library function? For example, the function may be srand(), and I want to hijack it with my own seed choice but otherwise let srand() do whatever it normally does.

If I were linking to make said executable, I would use the wrap option of the linker but here I only have the compiled binary.

One trivial solution I see is to cut and paste the source code for the original library function into the replacement - but I want to handle the more general case when the source is unavailable. Or, I could hex edit the needed extra code into the binary but that is specific to the binary and also time consuming. Is something more elegant possible than either of these? Such as some magic with the loader?

(Apologies if I were not using the terminology precisely...)

答:
The canonical answer is to use dlsym(RTLD_NEXT, ...).

From the man page:

```<code>RTLD_NEXT
          Find the next occurrence of the desired symbol in the search
          order after the current object.  This allows one to provide a
          wrapper around a function in another shared object, so that,
          for example, the definition of a function in a preloaded
          shared object (see LD_PRELOAD in ld.so(8)) can find and invoke
          the "real" function provided in another shared object (or for
          that matter, the "next" definition of the function in cases
          where there are multiple layers of preloading).
</code>```

See also this article.

ContentLicense: CC BY-SA 4.0

Body:
The canonical answer is to use dlsym(RTLD_NEXT, ...).

From the man page:

RTLD_NEXT
          Find the next occurrence of the desired symbol in the search
          order after the current object.  This allows one to provide a
          wrapper around a function in another shared object, so that,
          for example, the definition of a function in a preloaded
          shared object (see LD_PRELOAD in ld.so(8)) can find and invoke
          the "real" function provided in another shared object (or for
          that matter, the "next" definition of the function in cases
          where there are multiple layers of preloading).

See also this article.


问:
Python Selenium Webdriver Table Values to Excel
I am working on a project scraping a table off a web site. I will not be able to give full code as this is a company specific site with a login, hence my choice of Selenium. I have located the table in the HTML code:

```<code>class Table:
    def __init__(self, driver):
        self.driver = driver
    def get_row_info(self):
        table_id = self.driver.find_element(By.ID, 'dgTickets')
        rows = table_id.find_elements(By.TAG_NAME, "tr")
        col = []
        i = 0
        for i in rows[0]:
            i+=1
            name = i.text()
            col.append((name, []))
        for j in range(1,len(rows)):
            T = rows[j]
            i = 0
            for t in T.iterchildren():
                data = t.text_content()
                if i>0:
                    try:
                        data = int(data)
                    except:
                        pass
                col[i][1].append(data)
                i+=1
        Dict = {title:column for (title, column) in col}

</code>```

This returns me an error that it is not an iterable value.

I think what I am trying to do here is relatively self explanatory. Primarily, I am trying to return the web table  and eventually get it into a pandas dataframe for parsing. Using various methods, I can get the columns to print out their texts, but there seems to be a problem with passing that to a specified column in a table. Here is one way that I have found to return the column:

```<code>        for row in rows:
            col0 = row.find_elements(By.TAG_NAME, "td")[0]
</code>```

I'm honestly a little lost at this point. Any suggestions for me?

答:
You can use pandas.read_html() to get all tables on page as list of DataFrames. It works very fast.

```<code>import selenium.webdriver
import pandas as pd

url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'

driver = selenium.webdriver.Firefox()
driver.get(url)

# --- get table ---

all_tables = pd.read_html(driver.page_source, attrs={'id': 'constituents'})
df = all_tables[0]

# --- show it ---

print(df)
</code>```

If you want to do it manually - but for this example it takes much longer.

```<code>import selenium.webdriver
import pandas as pd

url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'

driver = selenium.webdriver.Firefox()
driver.get(url)

# --- get table ---

headers = []
columns = dict()

table_id = driver.find_element_by_id('constituents')
all_rows = table_id.find_elements_by_tag_name("tr")

# --- headers ---

row = all_rows[0]
all_items = row.find_elements_by_tag_name("th")
for item in all_items:
    name = item.text
    columns[name] = []
    headers.append(name)

print(headers)

# --- data ---

for row in all_rows[1:]:
    all_items = row.find_elements_by_tag_name("td")
    for name, item in zip(headers, all_items):
        value = item.text
        columns[name].append(value)

df = pd.DataFrame(columns)

# --- show it ---

print(df)
</code>```

Body:
I am working on a project scraping a table off a web site. I will not be able to give full code as this is a company specific site with a login, hence my choice of Selenium. I have located the table in the HTML code:

class Table:
    def __init__(self, driver):
        self.driver = driver
    def get_row_info(self):
        table_id = self.driver.find_element(By.ID, 'dgTickets')
        rows = table_id.find_elements(By.TAG_NAME, "tr")
        col = []
        i = 0
        for i in rows[0]:
            i+=1
            name = i.text()
            col.append((name, []))
        for j in range(1,len(rows)):
            T = rows[j]
            i = 0
            for t in T.iterchildren():
                data = t.text_content()
                if i>0:
                    try:
                        data = int(data)
                    except:
                        pass
                col[i][1].append(data)
                i+=1
        Dict = {title:column for (title, column) in col}

This returns me an error that it is not an iterable value.

I think what I am trying to do here is relatively self explanatory. Primarily, I am trying to return the web table  and eventually get it into a pandas dataframe for parsing. Using various methods, I can get the columns to print out their texts, but there seems to be a problem with passing that to a specified column in a table. Here is one way that I have found to return the column:

        for row in rows:
            col0 = row.find_elements(By.TAG_NAME, "td")[0]

I'm honestly a little lost at this point. Any suggestions for me?

Body:
You can use pandas.read_html() to get all tables on page as list of DataFrames. It works very fast.

import selenium.webdriver
import pandas as pd

url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'

driver = selenium.webdriver.Firefox()
driver.get(url)

# --- get table ---

all_tables = pd.read_html(driver.page_source, attrs={'id': 'constituents'})
df = all_tables[0]

# --- show it ---

print(df)

If you want to do it manually - but for this example it takes much longer.

import selenium.webdriver
import pandas as pd

url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'

driver = selenium.webdriver.Firefox()
driver.get(url)

# --- get table ---

headers = []
columns = dict()

table_id = driver.find_element_by_id('constituents')
all_rows = table_id.find_elements_by_tag_name("tr")

# --- headers ---

row = all_rows[0]
all_items = row.find_elements_by_tag_name("th")
for item in all_items:
    name = item.text
    columns[name] = []
    headers.append(name)

print(headers)

# --- data ---

for row in all_rows[1:]:
    all_items = row.find_elements_by_tag_name("td")
    for name, item in zip(headers, all_items):
        value = item.text
        columns[name].append(value)

df = pd.DataFrame(columns)

# --- show it ---

print(df)


问:
Couldn't retrieve remote JWK set : login.microsoftonline.com
I have used Azure AD in my spring boot application. The issue is when I am trying to validate the token Using AADAuthenticationFilter class, I am getting this error in my company network(internet), but when I am using my own internet things are working fine. Now I think, here proxy need to be used. I tried proxy at eclipse level, set properties in the application properties file, but nothing working out.

Here is the stack trace of the error..

```<code>com.nimbusds.jose.RemoteKeySourceException: Couldn't retrieve remote JWK set: login.microsoftonline.com
    at com.nimbusds.jose.jwk.source.RemoteJWKSet.updateJWKSetFromURL(RemoteJWKSet.java:141)
    at com.nimbusds.jose.jwk.source.RemoteJWKSet.get(RemoteJWKSet.java:219)
    at com.nimbusds.jose.proc.JWSVerificationKeySelector.selectJWSKeys(JWSVerificationKeySelector.java:130)
    at com.nimbusds.jwt.proc.DefaultJWTProcessor.process(DefaultJWTProcessor.java:323)
    at com.nimbusds.jwt.proc.DefaultJWTProcessor.process(DefaultJWTProcessor.java:284)
    at com.nimbusds.jwt.proc.DefaultJWTProcessor.process(DefaultJWTProcessor.java:275)
    at com.microsoft.azure.spring.autoconfigure.aad.UserPrincipalManager.buildUserPrincipal(UserPrincipalManager.java:86)
    at com.microsoft.azure.spring.autoconfigure.aad.AADAuthenticationFilter.doFilterInternal(AADAuthenticationFilter.java:78)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:813)
Caused by: java.net.UnknownHostException: login.microsoftonline.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:666)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
    at com.nimbusds.jose.util.DefaultResourceRetriever.retrieveResource(DefaultResourceRetriever.java:166)
    at com.nimbusds.jose.jwk.source.RemoteJWKSet.updateJWKSetFromURL(RemoteJWKSet.java:139)
    ... 70 more
</code>```

While doing research, I found out that there is a class DefaultResourceRetriever in the com.nimbusds.jose package, but how to set proxy in that ?
Link for the class is https://bitbucket.org/connect2id/nimbus-jose-jwt/commits/7f4dbc0

答:
You can just use the setProxy() method in the DefaultResourceRetriever class and put the proxy object in it. You can refer to the sample below:

```<code>Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
</code>```

We can find its constructor Proxy(Proxy.Type type, SocketAddress sa) shown in this page.

Then put the proxy object to setProxy(proxy) method, you can refer to this tutorial about the setProxy() method.

Here provide a link about the relationship between AADAuthenticationFilter and DefaultResourceRetriever which may help you.

Body:
I have used Azure AD in my spring boot application. The issue is when I am trying to validate the token Using AADAuthenticationFilter class, I am getting this error in my company network(internet), but when I am using my own internet things are working fine. Now I think, here proxy need to be used. I tried proxy at eclipse level, set properties in the application properties file, but nothing working out.

Here is the stack trace of the error..

com.nimbusds.jose.RemoteKeySourceException: Couldn't retrieve remote JWK set: login.microsoftonline.com
    at com.nimbusds.jose.jwk.source.RemoteJWKSet.updateJWKSetFromURL(RemoteJWKSet.java:141)
    at com.nimbusds.jose.jwk.source.RemoteJWKSet.get(RemoteJWKSet.java:219)
    at com.nimbusds.jose.proc.JWSVerificationKeySelector.selectJWSKeys(JWSVerificationKeySelector.java:130)
    at com.nimbusds.jwt.proc.DefaultJWTProcessor.process(DefaultJWTProcessor.java:323)
    at com.nimbusds.jwt.proc.DefaultJWTProcessor.process(DefaultJWTProcessor.java:284)
    at com.nimbusds.jwt.proc.DefaultJWTProcessor.process(DefaultJWTProcessor.java:275)
    at com.microsoft.azure.spring.autoconfigure.aad.UserPrincipalManager.buildUserPrincipal(UserPrincipalManager.java:86)
    at com.microsoft.azure.spring.autoconfigure.aad.AADAuthenticationFilter.doFilterInternal(AADAuthenticationFilter.java:78)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:813)
Caused by: java.net.UnknownHostException: login.microsoftonline.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:666)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
    at com.nimbusds.jose.util.DefaultResourceRetriever.retrieveResource(DefaultResourceRetriever.java:166)
    at com.nimbusds.jose.jwk.source.RemoteJWKSet.updateJWKSetFromURL(RemoteJWKSet.java:139)
    ... 70 more

While doing research, I found out that there is a class DefaultResourceRetriever in the com.nimbusds.jose package, but how to set proxy in that ?
Link for the class is https://bitbucket.org/connect2id/nimbus-jose-jwt/commits/7f4dbc0

Body:
You can just use the setProxy() method in the DefaultResourceRetriever class and put the proxy object in it. You can refer to the sample below:

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));

We can find its constructor Proxy(Proxy.Type type, SocketAddress sa) shown in this page.

Then put the proxy object to setProxy(proxy) method, you can refer to this tutorial about the setProxy() method.

Here provide a link about the relationship between AADAuthenticationFilter and DefaultResourceRetriever which may help you.


问:
Unable to Open .txt File
```<code>std::ifstream infile;
infile.open("example.txt");

if (!infile.is_open()) {
   std::cout << "can't open" << std::endl;
}
</code>```

I read this: unable to open file stream c++ and have tried using the full path infile.open("~/projects/example.txt");

The text file is in the same folder where the .cpp / .hpp files reside.

What else could be the problem?

答: try "realpath ~/projects/example.txt", which will show you the real path of your file, and then use this real path in your cpp</p>

Title: Unable to Open .txt File

Body:
std::ifstream infile;
infile.open("example.txt");

if (!infile.is_open()) {
   std::cout << "can't open" << std::endl;
}

I read this: unable to open file stream c++ and have tried using the full path infile.open("~/projects/example.txt");

The text file is in the same folder where the .cpp / .hpp files reside.

What else could be the problem?


问:
Interest not updating
It is meant to calculate interest and then put that into a table with years, interest, and new balance. For some reason the interest is not being calculated correctly and is not updating.</p>

```<code>import java.util.Scanner;
import java.text.*;

public class Interest
{

    public static void main(String[] args)
    {

        printIntro();
        Scanner input = new Scanner(System.in);
        System.out.print("Enter initial balance: ");
        int balanceAmount = input.nextInt();
        System.out.print("Enter interest rate: ");
        double interestRate = input.nextDouble();
        System.out.print("Enter the number of years: ");
        int years = input.nextInt();
        printTable(years, balanceAmount, interestRate);

    }

    public static double calcInterest(double balanceAmount, double interestRate, double years)
    {
        double interest = balanceAmount * Math.pow((1 + interestRate/100),years);
        return interest;
    }

    public static void printRow(int rowNum, double balanceAmount, double interestRate)
    {
        System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
        //balanceAmount = (balanceAmount + interestRate);
    }

    public static void printTable(int numRows, double balanceAmount, double interestRate)
    {
        System.out.println("Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance");
         System.out.println("----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------");

         for (int i = 1; i <= numRows; i++)
            {
                printRow(i, balanceAmount, interestRate);
                balanceAmount = (balanceAmount + interestRate);
            }
    }

    public static void printIntro()
    {
        System.out.println("This program will calculate the interest "
                + "earned on a deposit over a certain amount of years.");
    }
}
</code>```

答:
You should call your business logic to calculate interest as per your business requirement. That totaly depend on your business requirement.

Though for program specific it seems that You need to call your calcInterest  method in printTable method, before you call your printRow method as below:

```<code>public static void printTable( final int numRows, double balanceAmount, final double interestRate ) {
        System.out.println( "Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance" );
        System.out.println( "----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------" );

        for ( int i = 1; i <= numRows; i++ ) {
            double interest = calcInterest( balanceAmount, interestRate, 1 );
            printRow( i, balanceAmount, interest );
            balanceAmount = ( balanceAmount + interest );
        }
    }
</code>```

Also your formula to calculate interest is wrong. it should be

```<code> double interest = balanceAmount * Math.pow( ( 1 + interestRate / 100 ), years )-balanceAmount;
</code>```

It will give out put as below:

This program will calculate the interest earned on a deposit over a certain amount of years.

This program will calculate the interest earned on a deposit over a certain amount of years.

Enter initial balance: 100
Enter interest rate: 10
Enter the number of years: 3
Year    Balance             Interest                New Balance
----    -------             --------                -----------
1   100.0                   10.000000000000014      110.00000000000001
2   110.00000000000001      23.100000000000037      133.10000000000005
3   133.10000000000005      44.05610000000007       177.15610000000012

Title: Interest not updating

Body:
It is meant to calculate interest and then put that into a table with years, interest, and new balance. For some reason the interest is not being calculated correctly and is not updating.

import java.util.Scanner;
import java.text.*;

public class Interest
{

    public static void main(String[] args)
    {

        printIntro();
        Scanner input = new Scanner(System.in);
        System.out.print("Enter initial balance: ");
        int balanceAmount = input.nextInt();
        System.out.print("Enter interest rate: ");
        double interestRate = input.nextDouble();
        System.out.print("Enter the number of years: ");
        int years = input.nextInt();
        printTable(years, balanceAmount, interestRate);

    }

    public static double calcInterest(double balanceAmount, double interestRate, double years)
    {
        double interest = balanceAmount * Math.pow((1 + interestRate/100),years);
        return interest;
    }

    public static void printRow(int rowNum, double balanceAmount, double interestRate)
    {
        System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
        //balanceAmount = (balanceAmount + interestRate);
    }

    public static void printTable(int numRows, double balanceAmount, double interestRate)
    {
        System.out.println("Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance");
         System.out.println("----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------");

         for (int i = 1; i <= numRows; i++)
            {
                printRow(i, balanceAmount, interestRate);
                balanceAmount = (balanceAmount + interestRate);
            }
    }

    public static void printIntro()
    {
        System.out.println("This program will calculate the interest "
                + "earned on a deposit over a certain amount of years.");
    }
}

Body:
You should call your business logic to calculate interest as per your business requirement. That totaly depend on your business requirement.

Though for program specific it seems that You need to call your calcInterest  method in printTable method, before you call your printRow method as below:

public static void printTable( final int numRows, double balanceAmount, final double interestRate ) {
        System.out.println( "Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance" );
        System.out.println( "----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------" );

        for ( int i = 1; i <= numRows; i++ ) {
            double interest = calcInterest( balanceAmount, interestRate, 1 );
            printRow( i, balanceAmount, interest );
            balanceAmount = ( balanceAmount + interest );
        }
    }

Also your formula to calculate interest is wrong. it should be

 double interest = balanceAmount * Math.pow( ( 1 + interestRate / 100 ), years )-balanceAmount;

It will give out put as below:

This program will calculate the interest earned on a deposit over a certain amount of years.

This program will calculate the interest earned on a deposit over a certain amount of years.

Enter initial balance: 100
Enter interest rate: 10
Enter the number of years: 3
Year    Balance             Interest                New Balance
----    -------             --------                -----------
1   100.0                   10.000000000000014      110.00000000000001
2   110.00000000000001      23.100000000000037      133.10000000000005
3   133.10000000000005      44.05610000000007       177.15610000000012


问:
jquery infinite random image fader
sadly i am totally new to jquery-writing and after googling for 12 hours to find a solution for my needs im giving up and ask straight away.

i am trying to write a short script, that fades in a random picture, delays a bit and then fades out. after that, the function should be invoked to infinity.

for now i mostly had the problem to accomplish the callback in such a manner, that its not regressing heavily but calling over and over. most scripts ive found let my firebug go crazy. also, i did not yet quite understood, how i can queue up the random image selector, a bit of attr (so its not always showing up at the exact same spot, but alternating a bit - but that has low priority), fadein, delay, fadeout and then doing it all over.

if someone could help me there, i'd be very, very grateful.
alex.

答:
Very easy to do in jQuery:

jQuery

```<code>$('document').ready(function() {

    var nextImage = function() {
         $('#slideshow > img:random')
          .fadeIn(function() {
               $(this).delay(3000).fadeOut(nextImage);
           })
    };

    nextImage();
});
</code>```

Using the help of the :random jQuery filter selector -- it's worth noting I've added this in because you said "random" -- but in fact you probably want the "next" image because on occasions it will select the same image as last time, or won't give even time to all images. In which case you can use http://jsfiddle.net/garreh/7BLnT/

Fiddle: http://jsfiddle.net/garreh/JbrXd/

ContentLicense: CC BY-SA 3.0

Title: jquery infinite random image fader

Body:
Very easy to do in jQuery:

jQuery

$('document').ready(function() {

    var nextImage = function() {
         $('#slideshow > img:random')
          .fadeIn(function() {
               $(this).delay(3000).fadeOut(nextImage);
           })
    };

    nextImage();
});

Using the help of the :random jQuery filter selector -- it's worth noting I've added this in because you said "random" -- but in fact you probably want the "next" image because on occasions it will select the same image as last time, or won't give even time to all images. In which case you can use http://jsfiddle.net/garreh/7BLnT/

Fiddle: http://jsfiddle.net/garreh/JbrXd/


问:
Flutter: Send JSON body for Http GET request
I need to make a GET request to an API from my Flutter app which requires request body as JSON (raw).

I tested the API with JSON request body in Postman and it seems to be working fine.

Now on my Flutter application I am trying to do the same thing:

```<code>_fetchDoctorAvailability() async {
    var params = {
      "doctor_id": "DOC000506",
      "date_range": "25/03/2019-25/03/2019" ,
      "clinic_id":"LAD000404"
    };

    Uri uri = Uri.parse("http://theapiiamcalling:8000");
    uri.replace(queryParameters: params);

    var response = await http.get(uri, headers: {
      "Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
      HttpHeaders.contentTypeHeader: "application/json",
      "callMethod" : "DOCTOR_AVAILABILITY"
    });

    print('---- status code: ${response.statusCode}');
    var jsonData = json.decode(response.body);

    print('---- slot: ${jsonData}');
}
</code>```

However the API gives me an error saying

{message: Missing input json., status: false}

How do I send a raw (or rather JSON) request body for Http GET request in Flutter?

答:
GET

GET requests are not intended for sending data to the server (but see this). That's why the http.dart get method doesn't have a body parameter. However, when you want to specify what you are getting from the server, sometimes you need to include query parameters, which is a form of data. The query parameters are key-value pairs, so you can include them as a map like this:

```<code>final queryParameters = {
  'name': 'Bob',
  'age': '87',
};
final uri = Uri.http('www.example.com', '/path', queryParameters);
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.get(uri, headers: headers);
</code>```

POST

Unlike GET requests, POST requests are intended for sending data in the body. You can do it like this:

```<code>final body = {
  'name': 'Bob',
  'age': '87',
};
final jsonString = json.encode(body);
final uri = Uri.http('www.example.com', '/path');
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.post(uri, headers: headers, body: jsonString);
</code>```

Note that the parameters were a Map on the Dart side. Then they were converted to a JSON string by the json.encode() function from the dart:convert library. That string is the POST body.

So if the server is asking you to pass it data in a GET request body, check again. While it is possible to design a server in this way, it isn't standard.

Body:
I need to make a GET request to an API from my Flutter app which requires request body as JSON (raw).

I tested the API with JSON request body in Postman and it seems to be working fine.

Now on my Flutter application I am trying to do the same thing:

_fetchDoctorAvailability() async {
    var params = {
      "doctor_id": "DOC000506",
      "date_range": "25/03/2019-25/03/2019" ,
      "clinic_id":"LAD000404"
    };

    Uri uri = Uri.parse("http://theapiiamcalling:8000");
    uri.replace(queryParameters: params);

    var response = await http.get(uri, headers: {
      "Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
      HttpHeaders.contentTypeHeader: "application/json",
      "callMethod" : "DOCTOR_AVAILABILITY"
    });

    print('---- status code: ${response.statusCode}');
    var jsonData = json.decode(response.body);

    print('---- slot: ${jsonData}');
}

However the API gives me an error saying

{message: Missing input json., status: false}

How do I send a raw (or rather JSON) request body for Http GET request in Flutter?

Body:
GET

GET requests are not intended for sending data to the server (but see this). That's why the http.dart get method doesn't have a body parameter. However, when you want to specify what you are getting from the server, sometimes you need to include query parameters, which is a form of data. The query parameters are key-value pairs, so you can include them as a map like this:

final queryParameters = {
  'name': 'Bob',
  'age': '87',
};
final uri = Uri.http('www.example.com', '/path', queryParameters);
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.get(uri, headers: headers);

POST

Unlike GET requests, POST requests are intended for sending data in the body. You can do it like this:

final body = {
  'name': 'Bob',
  'age': '87',
};
final jsonString = json.encode(body);
final uri = Uri.http('www.example.com', '/path');
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.post(uri, headers: headers, body: jsonString);

Note that the parameters were a Map on the Dart side. Then they were converted to a JSON string by the json.encode() function from the dart:convert library. That string is the POST body.

So if the server is asking you to pass it data in a GET request body, check again. While it is possible to design a server in this way, it isn't standard.


问:
Accessing value from key with JavaScript
I'm new to JavaScript. This is giving me undefined.

What am I doing wrong? How do I log the values inside the objects?

let spaceship = {
  passengers: null
};

(spaceship.passengers = [{ name: "Mike" }, { ability: "teleportation" }]),
  [{ name: "David" }, { ability: "cook" }];

let firstPassenger = spaceship.passengers[0];
console.log(firstPassenger.ability);```

答:
I guess what you want to do, do you want to set the value of the object?

I have provided the following example, you can try to compare the two and confirm whether this is what you want

Regarding your json string, I suggest that you redesign it as in my example. This is because all the attributes of an object are best placed in an object. This will make the scope clearer.

let spaceship = {
  passengers: null
};

spaceship.passengers = [{
  name: "Mike",
  ability: "teleportation"
}, {
  name: "David",
  ability: "cook"
}];

const passengers = spaceship.passengers;

passengers.forEach(obj =>
  console.log(`name: ${obj.name}, ability: ${obj.ability}`)
);```


答:
You are not calling calcInterest.

You need to call that under the printRow method before the

```<code>System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
</code>```

line

Title: Interest not updating

Body:
You are not calling calcInterest.

You need to call that under the printRow method before the

System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));

line


问:
ExtJS: grid 100% height
I have a structure of this type (Ext 3.3.1):

```<code>var page = new Ext.Viewport({
    layout: 'border',
    anchor:'100% 100%',
    renderTo: Ext.getBody(),
    items: [{
        region: 'north',
        height:'auto',
        items: [toolbar]
    },{
        region: 'center',
        layout:'fit',
        items: [gridCourses,gridExams]
    }]
});
</code>```

In the toolbar, I have two buttons, COURSES and EXAMS. I use these buttons to show/hide one of the two grid, so that only one is visible at a time. The code of the buttons I uses is something like this:

```<code>{
    text: 'Courses',
    iconCls: 'show-courses',
    handler: function(){
        gridCourses.store.reload();
        gridCourses.show();
        gridExams.hide();
    }
},{
    text: 'Exams',
    iconCls: 'show-exams',
    handler: function(){
        gridExams.store.reload();
        gridCourses.hide();
        gridExams.show();
    }
}
</code>```

The question is: how can I have the the displayed grid to fill the whole screen (especially in height?). I think I have to put something in the handler of the buttons or a listener to my grids, but I do not know what to put. Any hints?

答:
The 'fit' layout is only for placing a single panel. Use the 'card' layout instead for switching between two or more panels which are to share the same space:

```<code>{
    region: 'center',
    layout: 'card',
    // 0 here means the zeroth element of the items array.
    activeItem: 0,
    items: [
        gridCourses,
        gridExams
    ]
}
</code>```

Your button handlers then become:

```<code>{
    text: 'Courses',
    iconCls: 'show-courses',
    handler: function() {
        gridCourses.getStore().reload();
        gridCourses.ownerCt.getLayout().setActiveItem(gridCourses);
    }
},
{
    text: 'Exams',
    iconCls: 'show-exams',
    handler: function() {
        gridExams.getStore().reload();
        gridExams.ownerCt.getLayout().setActiveItem(gridExams);
    }
}
</code>```

Also, assuming the toolbar variable in your example is containing a real Ext.Toolbar instance, your layout in general could be improved with a different viewport definition:

```<code>new Ext.Viewport({
    layout: 'fit',
    items: {
        xtype: 'panel',
        layout: 'card',
        activeItem: 0,
        tbar: [
            {
                text: 'Courses',
                iconCls: 'show-courses',
                handler: function() {
                    gridCourses.getStore().reload();
                    gridCourses.ownerCt.getLayout().setActiveItem(gridCourses);
                }
            },
            {
                text: 'Exams',
                iconCls: 'show-exams',
                handler: function() {
                    gridExams.getStore().reload();
                    gridExams.ownerCt.getLayout().setActiveItem(gridExams);
                }
            }
        ],
        items: [
            gridCourses,
            gridExams
        ]
    }
});
</code>```

That said, if you still need a border layout on your viewport for other reasons then the card panel, toolbar and all, can be parked in the center region as shown at the top of the answer.

Title: ExtJS: grid 100% height

Body:
I have a structure of this type (Ext 3.3.1):

var page = new Ext.Viewport({
    layout: 'border',
    anchor:'100% 100%',
    renderTo: Ext.getBody(),
    items: [{
        region: 'north',
        height:'auto',
        items: [toolbar]
    },{
        region: 'center',
        layout:'fit',
        items: [gridCourses,gridExams]
    }]
});

In the toolbar, I have two buttons, COURSES and EXAMS. I use these buttons to show/hide one of the two grid, so that only one is visible at a time. The code of the buttons I uses is something like this:

{
    text: 'Courses',
    iconCls: 'show-courses',
    handler: function(){
        gridCourses.store.reload();
        gridCourses.show();
        gridExams.hide();
    }
},{
    text: 'Exams',
    iconCls: 'show-exams',
    handler: function(){
        gridExams.store.reload();
        gridCourses.hide();
        gridExams.show();
    }
}

The question is: how can I have the the displayed grid to fill the whole screen (especially in height?). I think I have to put something in the handler of the buttons or a listener to my grids, but I do not know what to put. Any hints?

Body:
The 'fit' layout is only for placing a single panel. Use the 'card' layout instead for switching between two or more panels which are to share the same space:

{
    region: 'center',
    layout: 'card',
    // 0 here means the zeroth element of the items array.
    activeItem: 0,
    items: [
        gridCourses,
        gridExams
    ]
}

Your button handlers then become:

{
    text: 'Courses',
    iconCls: 'show-courses',
    handler: function() {
        gridCourses.getStore().reload();
        gridCourses.ownerCt.getLayout().setActiveItem(gridCourses);
    }
},
{
    text: 'Exams',
    iconCls: 'show-exams',
    handler: function() {
        gridExams.getStore().reload();
        gridExams.ownerCt.getLayout().setActiveItem(gridExams);
    }
}

Also, assuming the toolbar variable in your example is containing a real Ext.Toolbar instance, your layout in general could be improved with a different viewport definition:

new Ext.Viewport({
    layout: 'fit',
    items: {
        xtype: 'panel',
        layout: 'card',
        activeItem: 0,
        tbar: [
            {
                text: 'Courses',
                iconCls: 'show-courses',
                handler: function() {
                    gridCourses.getStore().reload();
                    gridCourses.ownerCt.getLayout().setActiveItem(gridCourses);
                }
            },
            {
                text: 'Exams',
                iconCls: 'show-exams',
                handler: function() {
                    gridExams.getStore().reload();
                    gridExams.ownerCt.getLayout().setActiveItem(gridExams);
                }
            }
        ],
        items: [
            gridCourses,
            gridExams
        ]
    }
});

That said, if you still need a border layout on your viewport for other reasons then the card panel, toolbar and all, can be parked in the center region as shown at the top of the answer.


问:
Django matplotlib: fname must be a PathLike or file handle
I am trying to display a plot with matplotlib and django following this and this questions, however it seems not working, I tried both solutions and only while using IO i get an empty canvas, but when I try to plot a 'real' plot I get the error in the title.

This is my view:

```<code>import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as
FigureCanvas
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt
import io

def mplimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    x = np.arange(-2, 1.5, .01)
    y = np.sin(np.exp(2 * x))
    plt.plot(x, y)
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(fig)
    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
</code>```

and here the link in urls.py:

```<code>    import mpl.views
    url(r'mplimage.png', mpl.views.mplimage)
</code>```

答:
```<code>from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np
import django
def showimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    x = np.arange(-2,1.5,.01)
    y = np.sin(np.exp(2*x))
    ax.plot(x, y)
    response = HttpResponse(content_type='image/jpg')
    canvas.print_jpg(response)
    return response
</code>```

Body:
I am trying to display a plot with matplotlib and django following this and this questions, however it seems not working, I tried both solutions and only while using IO i get an empty canvas, but when I try to plot a 'real' plot I get the error in the title.

This is my view:

import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as
FigureCanvas
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt
import io

def mplimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    x = np.arange(-2, 1.5, .01)
    y = np.sin(np.exp(2 * x))
    plt.plot(x, y)
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(fig)
    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

and here the link in urls.py:

    import mpl.views
    url(r'mplimage.png', mpl.views.mplimage)


问:
How to Change Unity Toggle background image in Code C#
I have unity project and I used five toggle and set 1 image for the background another image to Checkmark.
I want to set that both images by using code(C#).

答:
Thank you for every ones to support me and I find a answer to this question.
answer is:

first we need to declare varibles(for reference to Image) and then set images to variable from unity.

```<code>public Sprite MondayRW;
public Sprite MondayRG;
public Sprite TuesRW;
public Sprite TuesRG;
public Sprite WendRW;
public Sprite WendRG;
public Sprite ThurRW;

//If Phone language is Russian, Set Russian value images to tonggles.
        if(Application.systemLanguage == SystemLanguage.Russian)
        {
            GameObject.Find("BackgroundMon").GetComponent<Image>().sprite = MondayRW;
            GameObject.Find("CheckmarkMon").GetComponent<Image>().sprite = MondayRG;
            GameObject.Find("BackgroundTue").GetComponent<Image>().sprite = TuesRW;
            GameObject.Find("CheckmarkTue").GetComponent<Image>().sprite = TuesRG;
            GameObject.Find("BackgroundWed").GetComponent<Image>().sprite = WendRW;
            GameObject.Find("CheckmarkWed").GetComponent<Image>().sprite = WendRG;
            GameObject.Find("BackgroundThu").GetComponent<Image>().sprite = ThurRW;

        }
</code>```

I find the place to replace my image from GameObject.Find("BackgroundMon") and then I set my image to that place.

Body:
Thank you for every ones to support me and I find a answer to this question.
answer is:

first we need to declare varibles(for reference to Image) and then set images to variable from unity.

public Sprite MondayRW;
public Sprite MondayRG;
public Sprite TuesRW;
public Sprite TuesRG;
public Sprite WendRW;
public Sprite WendRG;
public Sprite ThurRW;

//If Phone language is Russian, Set Russian value images to tonggles.
        if(Application.systemLanguage == SystemLanguage.Russian)
        {
            GameObject.Find("BackgroundMon").GetComponent<Image>().sprite = MondayRW;
            GameObject.Find("CheckmarkMon").GetComponent<Image>().sprite = MondayRG;
            GameObject.Find("BackgroundTue").GetComponent<Image>().sprite = TuesRW;
            GameObject.Find("CheckmarkTue").GetComponent<Image>().sprite = TuesRG;
            GameObject.Find("BackgroundWed").GetComponent<Image>().sprite = WendRW;
            GameObject.Find("CheckmarkWed").GetComponent<Image>().sprite = WendRG;
            GameObject.Find("BackgroundThu").GetComponent<Image>().sprite = ThurRW;

        }

I find the place to replace my image from GameObject.Find("BackgroundMon") and then I set my image to that place.


问:
Exporting to excel with cell column width on ag-grid
How to set column width in the excel for certain columns?

I tried the following but not working.

```<code>  this.gridOptions.excelStyles = this.excelStyles;
  let params = {
    fileName: 'DelegateStatus',
    sheetName: 'Delegate Status',
    columnWidth: 10
  }
  this.gridOptions.api.exportDataAsExcel(params);
</code>```

Thanks

答:
Your approach using columnWidth is correct however,

columnWidth was introduced in version 22.1.0

AG-1486   [Feature Request]   22.1.0  Allow configuring row groups/cells
  when exporting to excel/csv

What is the ag-grid version you are using?

Body:
How to set column width in the excel for certain columns?

I tried the following but not working.

  this.gridOptions.excelStyles = this.excelStyles;
  let params = {
    fileName: 'DelegateStatus',
    sheetName: 'Delegate Status',
    columnWidth: 10
  }
  this.gridOptions.api.exportDataAsExcel(params);

Thanks


问:
Unable to get PHP script name using REGEX
I am having quite the challenge. I have my function where() which tracks where users are visiting on the site, and takes the script filename and provides a description and inserts into database.

The script was working great, until recently, and unaware of the failure of this function after a recent minor update from MySQL 5.6.40 to 5.6.47

I am not sure if that had anything to do with it, but I discovered days later that it was not working anymore.

Our function:

```<code>function where($scriptname = "index", $userid, $update=1){
    if (!is_valid_id($userid))
        die;

    if (preg_match("/details.php/i", $scriptname))
        $where = "Browsing File Details (ID $_GET[id])";
    elseif (preg_match("/files.php/i", $scriptname))
        $where = "Browsing Files";
    elseif (preg_match("/account-info.php/i", $scriptname))
        $where = "Browsing Account Info (ID $_GET[id])";
    elseif (preg_match("/upload.php/i", $scriptname))
        $where = "Uploading File";
    elseif (preg_match("/account.php/i", $scriptname))
        $where = "Browsing User Control Panel";
    elseif (preg_match("/search.php/i", $scriptname))
        $where = "Searching For Files";
    elseif (preg_match("/forums.php/i", $scriptname))
        $where = "Viewing Forums";
    elseif (preg_match("/index.php/i", $scriptname))
        $where = "Browsing Homepage";
    elseif (preg_match("/mailbox.php/i", $scriptname))
        $where = "Viewing Messages";
    elseif (preg_match("/comments.php/i", $scriptname))
        $where = "Viewing Comments";
    elseif (preg_match("/recover.php/i", $scriptname))
        $where = "Recovering Account";
    elseif (preg_match("/bookmarks.php/i", $scriptname))
        $where = "Viewing Bookmarks";
    elseif (preg_match("/getfile.php/i", $scriptname))
        $where = "Downloaded File (ID $_GET[id])";
    elseif (preg_match("/faq.php/i", $scriptname))
        $where = "Reading FAQ Page";
    elseif (preg_match("/friends.php/i", $scriptname))
        $where = "Viewing Friends";
    elseif (preg_match("/admin.php/i", $scriptname))
        $where = "Managing Admin Panel";
    else
        $where = "Unknown Location";

    if ($update) {
        // Worked until a few days ago. No site changes were made prior for quite some time.
        //$query = sprintf("UPDATE users SET page=".sqlesc($where)." WHERE id ='%s'", mysql_real_escape_string($userid));
        // Now using line below, which does insert into row if I use my own variable.
        $query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($where) . " WHERE id=" . $userid;
        $result = SQL_Query_exec($query);
    }
        return $where;
}
</code>```

Now, I have tried the following code to narrow it down to what is causing it. Currently, the function above only inserts

Unknown Location

to the Database, no matter what page is viewed.

I got it down to this:

```<code>$stringtest = "This inserts into database!";
$query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($stringtest) . " WHERE id=" . $userid;
</code>```

This works great, however it is not passing any of the $where conditions.

I've tried varies regular expressions for filename matching to no avail.

Any idea what I'm doing wrong?

Thanks in advance!

答:
For the SQL part use prepared statements, as noted above.

Assuming, the $scriptname holds filename, without extension, and not the absolute path, and based on the code provided I don't see great need for preg_match() there. Just simple switch ... case would do.

Even better, if you want to have a sort of manageable list of locations with descriptions (you reuse them every time anyway), you could had associative array (could be returned by a separate function) like below and do as follows:

$locations = array(
  'index' => 'Browsing Homepage',
  'forums' => 'Browsing Homepage,
  //  and so on for all of your files
);

// And to get the description - assuming case matters, otherwise use strtolower()
$desc = isset($locations[$scriptname]) ? $locations[$scriptname] : 'Unknown Location';
```

Body:
I am having quite the challenge. I have my function where() which tracks where users are visiting on the site, and takes the script filename and provides a description and inserts into database.

The script was working great, until recently, and unaware of the failure of this function after a recent minor update from MySQL 5.6.40 to 5.6.47

I am not sure if that had anything to do with it, but I discovered days later that it was not working anymore.

Our function:

function where($scriptname = "index", $userid, $update=1){
    if (!is_valid_id($userid))
        die;

    if (preg_match("/details.php/i", $scriptname))
        $where = "Browsing File Details (ID $_GET[id])";
    elseif (preg_match("/files.php/i", $scriptname))
        $where = "Browsing Files";
    elseif (preg_match("/account-info.php/i", $scriptname))
        $where = "Browsing Account Info (ID $_GET[id])";
    elseif (preg_match("/upload.php/i", $scriptname))
        $where = "Uploading File";
    elseif (preg_match("/account.php/i", $scriptname))
        $where = "Browsing User Control Panel";
    elseif (preg_match("/search.php/i", $scriptname))
        $where = "Searching For Files";
    elseif (preg_match("/forums.php/i", $scriptname))
        $where = "Viewing Forums";
    elseif (preg_match("/index.php/i", $scriptname))
        $where = "Browsing Homepage";
    elseif (preg_match("/mailbox.php/i", $scriptname))
        $where = "Viewing Messages";
    elseif (preg_match("/comments.php/i", $scriptname))
        $where = "Viewing Comments";
    elseif (preg_match("/recover.php/i", $scriptname))
        $where = "Recovering Account";
    elseif (preg_match("/bookmarks.php/i", $scriptname))
        $where = "Viewing Bookmarks";
    elseif (preg_match("/getfile.php/i", $scriptname))
        $where = "Downloaded File (ID $_GET[id])";
    elseif (preg_match("/faq.php/i", $scriptname))
        $where = "Reading FAQ Page";
    elseif (preg_match("/friends.php/i", $scriptname))
        $where = "Viewing Friends";
    elseif (preg_match("/admin.php/i", $scriptname))
        $where = "Managing Admin Panel";
    else
        $where = "Unknown Location";

    if ($update) {
        // Worked until a few days ago. No site changes were made prior for quite some time.
        //$query = sprintf("UPDATE users SET page=".sqlesc($where)." WHERE id ='%s'", mysql_real_escape_string($userid));
        // Now using line below, which does insert into row if I use my own variable.
        $query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($where) . " WHERE id=" . $userid;
        $result = SQL_Query_exec($query);
    }
        return $where;
}

Now, I have tried the following code to narrow it down to what is causing it. Currently, the function above only inserts

Unknown Location

to the Database, no matter what page is viewed.

I got it down to this:

$stringtest = "This inserts into database!";
$query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($stringtest) . " WHERE id=" . $userid;

This works great, however it is not passing any of the $where conditions.

I've tried varies regular expressions for filename matching to no avail.

Any idea what I'm doing wrong?

Thanks in advance!


问:
How to initialize a LiveData<> object to avoid a NullPointerException when trying to return a single record
I want to pull a single record from my Room database and can do so with a query in my Dao:

```<code>@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
LiveData<Scenario> getScenario(long scenarioId);
</code>```

I only want to be update it in my ViewModel when there is a change:

```<code>final Observer<Scenario> scenarioObserver = new Observer<Scenario>() {
    @Override
    public void onChanged(Scenario scenario) {
        Log.d(TAG, "onChanged: " + scenario.getId());
    }
};
</code>```

When running I get an error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference
</code>```

but I can't initialize it the variable:

```<code>scenario = new LiveData<Scenario>();
</code>```

because I get an error: LiveData is abstract; cannot be abstract.

How do I deal with this situation? How do I initialize the LiveData object?

UPDATE

I get this error from the compiler:

```<code>error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.MutableLiveData<com.behaviorotg.tokensystem1.model.ScenarioBehaviorTokenLog>).
</code>```

On this line:

```<code>@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
MutableLiveData<Scenario> getScenario (long scenarioId);
</code>```

答:
There is an official document for LiveData at here

You can initialize LiveData as follow.

In Java

```<code>    // This code should be in `ViewModel` class.
    // Create a LiveData with a String
    private MutableLiveData<String> currentName;

    public MutableLiveData<String> getCurrentName() {
        if (currentName == null) {
            currentName = new MutableLiveData<String>();
        }
        return currentName;
    }

</code>```

In kotlin

```<code>    // Create a LiveData with a String
    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
</code>```

Body:
I want to pull a single record from my Room database and can do so with a query in my Dao:

@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
LiveData<Scenario> getScenario(long scenarioId);

I only want to be update it in my ViewModel when there is a change:

final Observer<Scenario> scenarioObserver = new Observer<Scenario>() {
    @Override
    public void onChanged(Scenario scenario) {
        Log.d(TAG, "onChanged: " + scenario.getId());
    }
};

When running I get an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference

but I can't initialize it the variable:

scenario = new LiveData<Scenario>();

because I get an error: LiveData is abstract; cannot be abstract.

How do I deal with this situation? How do I initialize the LiveData object?

UPDATE

I get this error from the compiler:

error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.MutableLiveData<com.behaviorotg.tokensystem1.model.ScenarioBehaviorTokenLog>).

On this line:

@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
MutableLiveData<Scenario> getScenario (long scenarioId);

Body:
There is an official document for LiveData at here

You can initialize LiveData as follow.

In Java

    // This code should be in `ViewModel` class.
    // Create a LiveData with a String
    private MutableLiveData<String> currentName;

    public MutableLiveData<String> getCurrentName() {
        if (currentName == null) {
            currentName = new MutableLiveData<String>();
        }
        return currentName;
    }

In kotlin

    // Create a LiveData with a String
    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }


问:
Xcode and flutter compiler error: reading from wrong directory
I am getting this error and my app will not compile.   The problem is that I had to upgrade macos to be able to compile apps on newer iOS versions, and in doing so I copied my project over from my mojave machine to my catalina one.   The directory users/mojave no longer exists, and it needs to be replaced with users/catalina

I have searched the app for any reference of mojave anywhere, and replaced it all with catalina.   I have rebooted macos, and it still fails, looking for this old directory.

How do I find and change these references?   I am not able to find anything online, possibly because I don't really know how to phrase this question.

答:
So this is another one of those occasions where the error doesn't really indicate what is wrong here.

The problem was that "pods setup" had not been run, so it had not initialised.

The reason for this is that when I ran "pod setup" it does literally nothing.

Researching this issue online, it seems an issue since cocoapods 1.8.0, and the dev team said that they had hotfixed this issue and it would be available from version 1.8.1

Well, this was version 1.8.4 and it is still broken with exactly the same issue.

The fix was to uninstall it completely:

sudo gem uninstall cocoapods

And then install version 1.7.5:

sudo gemo install cocoapods --version 1.7.5

From here, with the older version installed that actually works, "pod setup" runs fine, pods is initialised and the app no longer looks in the incorrect folders.

Hope this helps someone.


问:
How do I express that S must have a property "dirty" of type boolean?
I tried to ask this earlier generically (Why can't I assign a U to a Partial<T> when T extends U?) and I think I now understand why S extends {dirty: boolean} is incorrect (S could be {dirty: false}, but most of the suggestions were to rewrite the function in some way. So, how do I rewrite this function so that it has proper type checking and doesn't require a cast?

import {ActionCreatorWithPreparedPayload} from '@reduxjs/toolkit';
import {assert, pick} from '@helpmedo/util';
import {State, ThunkAction} from '@helpmedo/state';

export const createAsyncUpdateAction = <Arg, S extends {dirty: boolean}, P>(
  updateAction: ActionCreatorWithPreparedPayload<[Arg, Partial<S>], P>,
  selector: (state: State, arg: Arg) => S,
) => (
  arg: Arg,
  update: Partial<S>,
  asyncUpdate: () => Promise<unknown>,
): ThunkAction<unknown> => async (dispatch, getState) => {
  const state = selector(getState(), arg);
  assert(!state.dirty, 'Attempt to modify dirty state');
  const save = pick(state, Object.keys(update));
  dispatch(updateAction(arg, {...update, dirty: true}));
  try {
    const result = await asyncUpdate();
    dispatch(updateAction(arg, {dirty: false} /* as Partial<S> */));
    return result;
  } catch (err) {
    dispatch(updateAction(arg, {...save, dirty: false}));
    throw err;
  }
};
```

The existing error is Argument of type '{ dirty: false; }' is not assignable to parameter of type 'Partial<S>'.ts(2345) on the line with the commented out cast.

答: you are doing S extends { dirty: boolean } correctly. just replace Partial<S> with S should fix as SquattingSlavInTracksuit explained.

Body:
I tried to ask this earlier generically (Why can't I assign a U to a Partial<T> when T extends U?) and I think I now understand why S extends {dirty: boolean} is incorrect (S could be {dirty: false}, but most of the suggestions were to rewrite the function in some way. So, how do I rewrite this function so that it has proper type checking and doesn't require a cast?

import {ActionCreatorWithPreparedPayload} from '@reduxjs/toolkit';
import {assert, pick} from '@helpmedo/util';
import {State, ThunkAction} from '@helpmedo/state';

export const createAsyncUpdateAction = <Arg, S extends {dirty: boolean}, P>(
  updateAction: ActionCreatorWithPreparedPayload<[Arg, Partial<S>], P>,
  selector: (state: State, arg: Arg) => S,
) => (
  arg: Arg,
  update: Partial<S>,
  asyncUpdate: () => Promise<unknown>,
): ThunkAction<unknown> => async (dispatch, getState) => {
  const state = selector(getState(), arg);
  assert(!state.dirty, 'Attempt to modify dirty state');
  const save = pick(state, Object.keys(update));
  dispatch(updateAction(arg, {...update, dirty: true}));
  try {
    const result = await asyncUpdate();
    dispatch(updateAction(arg, {dirty: false} /* as Partial<S> */));
    return result;
  } catch (err) {
    dispatch(updateAction(arg, {...save, dirty: false}));
    throw err;
  }
};

The existing error is Argument of type '{ dirty: false; }' is not assignable to parameter of type 'Partial<S>'.ts(2345) on the line with the commented out cast.


问:
Pass parameters to ajax function that can be used in php?
I have the following ajax/jquery snippet, and my goal is to send a request that has a 'type' parameter. I already have a username and password, which I can echo back no problems. However, if I attempt to add a
type:'login' to the data of the request, I can never access 'type' from the php.

```<code>$(document).ready(function(){
     $("#button").click(function(){
          $.ajax({
               url: 'login.php',
               type: 'POST',
               content-type: 'application/x-www-form-urlencoded',
               data: {type:'login',username:user,password:pass},//this is my issue, why can't I pass type?
               success: function(response){
                    //determine if login was successful
               }
     });
});
</code>```

The login.php simply checks if POST is set and checks for parameter POST["type"], but it does not get passed?

PHP

```<code><?php

if (!isset($_POST))
{
    $msg = "NO POST MESSAGE SET, POLITELY **** OFF";
    echo json_encode($msg);
    exit(0);
}
$request = $_POST;
$response = "unsupported request type, politely **** OFF";
switch ($request["type"])
{
    case "login":
        $response = "login, yeah we can do that";
    break;
}
echo json_encode($response);
exit(0);

?>
</code>```

答: Since you are using content-type: 'application/x-www-form-urlencoded', you need to use jQuery's $.param to serialize the value. Check here: https://api.jquery.com/jQuery.param/

Body:
I have the following ajax/jquery snippet, and my goal is to send a request that has a 'type' parameter. I already have a username and password, which I can echo back no problems. However, if I attempt to add a
type:'login' to the data of the request, I can never access 'type' from the php.

$(document).ready(function(){
     $("#button").click(function(){
          $.ajax({
               url: 'login.php',
               type: 'POST',
               content-type: 'application/x-www-form-urlencoded',
               data: {type:'login',username:user,password:pass},//this is my issue, why can't I pass type?
               success: function(response){
                    //determine if login was successful
               }
     });
});

The login.php simply checks if POST is set and checks for parameter POST["type"], but it does not get passed?

PHP

<?php

if (!isset($_POST))
{
    $msg = "NO POST MESSAGE SET, POLITELY **** OFF";
    echo json_encode($msg);
    exit(0);
}
$request = $_POST;
$response = "unsupported request type, politely **** OFF";
switch ($request["type"])
{
    case "login":
        $response = "login, yeah we can do that";
    break;
}
echo json_encode($response);
exit(0);

?>


问:
Do methods take up space in the class instance on javascript?
 Similar questions for other languages.

Consider a simple class:

```<code>class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}
</code>```

For each instance of this class, in javascript, will be consumed memory for a reference for bar method?

If I add other methods in Foo class, the instance of it will be heavier on memory?

If I need to create a lot of Foo objects, should I write:

```<code>function Foo(value) {
  this.a = value;
}

function bar(fooInstance) {
  console.log(fooInstance.a);
}
</code>```

The questions above only illustrate the same question:

Do methods take up space in the class instance?

答:
Your code:

```<code>class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}
</code>```

Is equivalent to:

function Foo(value) {
  this.a = value;
}

Foo.prototype.bar = function () {
  console.log(this.a);
}

let foo1 = new Foo('foo1');
let foo2 = new Foo('foo2');

foo1.bar();
foo2.bar();

// true only if foo1.bar and foo2.bar reference the same object
console.log(foo1.bar === foo2.bar);```

So there is only one bar method on the constructor's public prototype. It's "inherited" by instances of Foo via their private [[Prototype]] property that points to Foo.prototype.

Body:
 Similar questions for other languages.

Consider a simple class:

class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}

For each instance of this class, in javascript, will be consumed memory for a reference for bar method?

If I add other methods in Foo class, the instance of it will be heavier on memory?

If I need to create a lot of Foo objects, should I write:

function Foo(value) {
  this.a = value;
}

function bar(fooInstance) {
  console.log(fooInstance.a);
}

The questions above only illustrate the same question:

Do methods take up space in the class instance?

Body:
Your code:

class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}

Is equivalent to:

function Foo(value) {
  this.a = value;
}

Foo.prototype.bar = function () {
  console.log(this.a);
}

let foo1 = new Foo('foo1');
let foo2 = new Foo('foo2');

foo1.bar();
foo2.bar();

// true only if foo1.bar and foo2.bar reference the same object
console.log(foo1.bar === foo2.bar);

So there is only one bar method on the constructor's public prototype. It's "inherited" by instances of Foo via their private [[Prototype]] property that points to Foo.prototype.


问:
How to get wiki pageid?
I am currently using PHP to make a chatbot that can do research on wiki,and send the introduction automaitcally, here is the wiki api json(https://zh.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=search_title)

```<code>{"batchcomplete":"","query":{"redirects":[{"from":"search_title","to":"search_title"}],"pages":{"541":{"pageid":541,"ns":0,"title":"search_title","extract":"ablablablablablablablablablablabla。"}}}}
</code>```

I want to get the extract part by

$data=$jsondata['query']['pages']["541"]['extract'];

but it seems like I need to have to know pageid is '541' first, is there method that I can know padeid in first??

答:
You should look for a way to iterate over array values without knowing the keys. I'm not a PHP developer but I think a foreach will do:

```<code>foreach ($jsondata['query']['pages'] as $pageid => $pagedata) {
    extract = $pagedata['extract']
    ...
}
</code>```

There is also a formatversion=2 parameter for the query that, among other things, will make

action=query's "pages" be an array, instead of an object with page ids
  as keys that can be difficult to iterate.

Title: How to get wiki pageid?

Body:
I am currently using PHP to make a chatbot that can do research on wiki,and send the introduction automaitcally, here is the wiki api json(https://zh.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=search_title)

{"batchcomplete":"","query":{"redirects":[{"from":"search_title","to":"search_title"}],"pages":{"541":{"pageid":541,"ns":0,"title":"search_title","extract":"ablablablablablablablablablablabla。"}}}}

I want to get the extract part by

$data=$jsondata['query']['pages']["541"]['extract'];

but it seems like I need to have to know pageid is '541' first, is there method that I can know padeid in first??

Body:
You should look for a way to iterate over array values without knowing the keys. I'm not a PHP developer but I think a foreach will do:

foreach ($jsondata['query']['pages'] as $pageid => $pagedata) {
    extract = $pagedata['extract']
    ...
}

There is also a formatversion=2 parameter for the query that, among other things, will make

action=query's "pages" be an array, instead of an object with page ids
  as keys that can be difficult to iterate.


问:
c++ raspberry pi 4 - Get keyboard keys input without enter/validation?
I've been searching for a while, and I don't achieve to find any way to get the input keys of my keyboard, to use them in my program...

Context : I'm starting on robotics, and C++, and I'd simply like to command a motor.
The idea is that "if I press the up arrow, the motor turns, if I press the down arrow, the motor stops" and that's it, no need to validate something or anything like that...

I am with raspbian, through VNC (controlling from my real computer), and the actual code is executed in the terminal.

I'll see later on to make that more complex.

I went through 20 or more pages and didn't find anything helpful... Isn't there an easy way to do something that seems so basically useful?

Some spoke about conio library, but apparently it's outdated, curses/ncurses took its place,but I didn't achieve to find/have anything working...
http://www.cplusplus.com/forum/general/74211/

Create a function to check for key press in unix using ncurses

Capture characters from standard input without waiting for enter to be pressed

This is apparently C code, and not C++, moreover, I don't really understand that...
How to detect key presses in a Linux C GUI program without prompting the user?

This, maybe? But it makes no sense to me (beginner in C++)
How can I get the keyboard state in Linux?

here they speak of "allegro", but apparently, it don't work on the PI 45 yet... and no idea how to install that anyway
http://www.cplusplus.com/forum/general/47357/

Does someone knows a simple little code that I can copy-past to do that, or any way? I'm quite shocked to not have something similar to windows C++ programming where it seems so simple

I mean something like "Keyboard.GetKeyStates(Key)"

I'll continue my research anyway, but please, help !

EDIT :

Apparently, the library SDL (SDL2) can help me do this...
I tried to implement it, it doesn't give any result...

Here is the code I got up to now (I deleted a good part that is useless in here), basically, it's a copy-past from internet SDL official web page :

#include <iostream>
#include <wiringPi.h>   //Raspberry pi GPIO Library
#include <cstdio>
#include <csignal>
#include <ctime>
#include <chrono>   //library for counting time
#include <thread>   //for "this thread sleep"
#include <SDL2/SDL.h>   //for getting the keyboard buttons events

bool RUNNING = true;    // global flag used to exit from the main loop

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  GPIO Pins definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
int SPser = 13, SPclk = 19, SPrclk = 26; //Define the output pins used
int Optocoupler = 17; //define the input pins used

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  SDL definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/

    //void PrintKeyInfo( SDL_KeyboardEvent *key );
    //void PrintModifiers( SDLMod mod );

//SOME CODE

// Callback handler if CTRL-C signal is detected
void my_handler(int s) {
    std::cout << "Detected CTRL-C signal no. " << s << '\n';
    RUNNING = false;
}

//###################################################################################
int main(int argc, char *args[]) {
    // Initialize wiringPi and allow the use of BCM pin numbering
    wiringPiSetupGpio();

    //Initialize SDL
    if (SDL_Init(SDL_INIT_EVENTS) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }
    else
    {
        SDL_Log("SDL initialized");
    }
    SDL_Event event;

    // Register a callback function to be called if the user presses CTRL-C
    std::signal(SIGINT, my_handler);

    while(RUNNING)
    {

    while( SDL_PollEvent( &event ) )
    {
    std::cout << "SDL While \n" << '\n';
        //When the user presses a key
        switch( event.type )
        {
        case SDL_KEYDOWN:
        std::cout << "Key press detected \n" << '\n';
            //printf( "Key press detected\n" );
        break;

        case SDL_KEYUP:
        std::cout << "Key release detected \n" << '\n';
            //printf( "Key release detected\n" );
        break;

        default:
        break;
        }
    }
//std::cout << "Works??" << '\n';

    /*for( i = 0; i <= 15; i++ )
    {
        //std::cout << "data input i =" << i << '\n';
        if (i==0){
        //std::cout << "if array " << i << '\n';
        DataArr[i]=1;
        DataArr[15]=0;
        }
        else{
            j=i-1;
            DataArr[j]=0;
            DataArr[i]=1;
            //std::cout << "in else i" << i << " and j " << j << '\n';
        }
    SendData(DataArr);
    }*/
    }
    std::cout << "Program ended ...\n";
}

```

As I followed "dumbly" the tutorial, this should work, but the while loop is never entered as the "std::cout << "SDL While \n" << '\n';" is never shown...

But, as it achieve to compile, I guess the SDL library was installed correctly and things work...

When executing the code, it writes "SDL initialized", then, nothing... pressing keys do nothing

I'm still not sure how to check if the library is installed correctly, but when I type in de command prompt "sudo apt-get install libsdl2-dev", it shows a few lines and says "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"

答:
If you are on linux, you should use termios to stop the buffering

#include <termios.h>

void set_no_buffer()
{
     struct termios term;
     tcgetattr(0, &term);
     term.c_lflag &= ~ICANON;
     tcsetattr(0, TCSANOW, &term);
}
```

and then getchar() to get a character without entering

Body:
I've been searching for a while, and I don't achieve to find any way to get the input keys of my keyboard, to use them in my program...

Context : I'm starting on robotics, and C++, and I'd simply like to command a motor.
The idea is that "if I press the up arrow, the motor turns, if I press the down arrow, the motor stops" and that's it, no need to validate something or anything like that...

I am with raspbian, through VNC (controlling from my real computer), and the actual code is executed in the terminal.

I'll see later on to make that more complex.

I went through 20 or more pages and didn't find anything helpful... Isn't there an easy way to do something that seems so basically useful?

Some spoke about conio library, but apparently it's outdated, curses/ncurses took its place,but I didn't achieve to find/have anything working...
http://www.cplusplus.com/forum/general/74211/

Create a function to check for key press in unix using ncurses

Capture characters from standard input without waiting for enter to be pressed

This is apparently C code, and not C++, moreover, I don't really understand that...
How to detect key presses in a Linux C GUI program without prompting the user?

This, maybe? But it makes no sense to me (beginner in C++)
How can I get the keyboard state in Linux?

here they speak of "allegro", but apparently, it don't work on the PI 45 yet... and no idea how to install that anyway
http://www.cplusplus.com/forum/general/47357/

Does someone knows a simple little code that I can copy-past to do that, or any way? I'm quite shocked to not have something similar to windows C++ programming where it seems so simple

I mean something like "Keyboard.GetKeyStates(Key)"

I'll continue my research anyway, but please, help !

EDIT :

Apparently, the library SDL (SDL2) can help me do this...
I tried to implement it, it doesn't give any result...

Here is the code I got up to now (I deleted a good part that is useless in here), basically, it's a copy-past from internet SDL official web page :

#include <iostream>
#include <wiringPi.h>   //Raspberry pi GPIO Library
#include <cstdio>
#include <csignal>
#include <ctime>
#include <chrono>   //library for counting time
#include <thread>   //for "this thread sleep"
#include <SDL2/SDL.h>   //for getting the keyboard buttons events

bool RUNNING = true;    // global flag used to exit from the main loop

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  GPIO Pins definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
int SPser = 13, SPclk = 19, SPrclk = 26; //Define the output pins used
int Optocoupler = 17; //define the input pins used

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  SDL definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/

    //void PrintKeyInfo( SDL_KeyboardEvent *key );
    //void PrintModifiers( SDLMod mod );

//SOME CODE

// Callback handler if CTRL-C signal is detected
void my_handler(int s) {
    std::cout << "Detected CTRL-C signal no. " << s << '\n';
    RUNNING = false;
}

//###################################################################################
int main(int argc, char *args[]) {
    // Initialize wiringPi and allow the use of BCM pin numbering
    wiringPiSetupGpio();

    //Initialize SDL
    if (SDL_Init(SDL_INIT_EVENTS) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }
    else
    {
        SDL_Log("SDL initialized");
    }
    SDL_Event event;

    // Register a callback function to be called if the user presses CTRL-C
    std::signal(SIGINT, my_handler);

    while(RUNNING)
    {

    while( SDL_PollEvent( &event ) )
    {
    std::cout << "SDL While \n" << '\n';
        //When the user presses a key
        switch( event.type )
        {
        case SDL_KEYDOWN:
        std::cout << "Key press detected \n" << '\n';
            //printf( "Key press detected\n" );
        break;

        case SDL_KEYUP:
        std::cout << "Key release detected \n" << '\n';
            //printf( "Key release detected\n" );
        break;

        default:
        break;
        }
    }
//std::cout << "Works??" << '\n';

    /*for( i = 0; i <= 15; i++ )
    {
        //std::cout << "data input i =" << i << '\n';
        if (i==0){
        //std::cout << "if array " << i << '\n';
        DataArr[i]=1;
        DataArr[15]=0;
        }
        else{
            j=i-1;
            DataArr[j]=0;
            DataArr[i]=1;
            //std::cout << "in else i" << i << " and j " << j << '\n';
        }
    SendData(DataArr);
    }*/
    }
    std::cout << "Program ended ...\n";
}

As I followed "dumbly" the tutorial, this should work, but the while loop is never entered as the "std::cout << "SDL While \n" << '\n';" is never shown...

But, as it achieve to compile, I guess the SDL library was installed correctly and things work...

When executing the code, it writes "SDL initialized", then, nothing... pressing keys do nothing

I'm still not sure how to check if the library is installed correctly, but when I type in de command prompt "sudo apt-get install libsdl2-dev", it shows a few lines and says "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"

Body:
If you are on linux, you should use termios to stop the buffering

#include <termios.h>

void set_no_buffer()
{
     struct termios term;
     tcgetattr(0, &term);
     term.c_lflag &= ~ICANON;
     tcsetattr(0, TCSANOW, &term);
}

and then getchar() to get a character without entering


问:
Error While running the SSIS Package through Control-M
I have 1 SSIS package with simple Data flow task to read the data from CSV file and load it into the SQL server.
We have 3 servers :
1 unix server for control-M (RedHat Server7.6)
1 windows server for SQL database and SSIS
1 Window server for storing the files.

When we run the package from Control-M then it is not able to read the files from file server, but when we run the package from SQL Agent in SSIS then it is executing successfully.

I have already given the permission of file server folder to the account that we are using in Control-M connection profile. PFB Error for reference.

Data Flow Task:Error: Cannot open the datafile "Location".

Data Flow Task:Error: Flat File Source failed the pre-execute phase
  and returned error code 0xC020200E.

答: In order to run SSIS packages in Control-M an Agent must exist on the server that contains the SSIS package.  D</p>