问:
Eclipse - Can not reach market place
I am trying to install glassfish on my Eclipse but I have an issue each time I try to access it :

Resource not found: http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155
http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155

I can reach web page from inside eclipse web browser and I can reach the market place with my browser I guess it is coming from eclipse but I don't know how to solve it.

I tried to change the Network Connections settings from Native to Manual but no luck so far.

If anyone as an idea ?

Here is the stack trace :

```<code>eclipse.buildId=4.15.0.I20200305-0155
java.version=1.8.0_231
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=fr_FR
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product

org.eclipse.epp.mpc.core
Error
Tue Jun 02 10:54:16 CEST 2020
Failed to stream using org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport@27a4a153 - falling back to org.eclipse.epp.internal.mpc.core.util.TransportFactory$$Lambda$811/602501626@46a0adaa: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.

org.eclipse.core.runtime.CoreException: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:119)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    ... 11 more
Contains: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
</code>```

I have the same issue from Help->Marketplace and from the welcome menu.

Thx

UPDATE : I manage to make it work again by deleting all the . folder (.me2, .plguings ...)

答:
Hi Everyone,

This is not a JDK issue, and not required to install a new eclipse.

The root cause is the internet not connecting inside the eclipse.

Here are the steps for modifying the network inside eclipse:

In eclipse - GoTo --> Preferences --> Network Connections

Inside "Network Connections" -->  select ActiveProvider = manual

Click on "Apply & Close".

Restart eclipse.

you will get access to Marketplace.

eclipse Preferences screenshot for reference :
https://i.stack.imgur.com/Flljz.png

Title: Eclipse - Can not reach market place

Body:
I am trying to install glassfish on my Eclipse but I have an issue each time I try to access it :

Resource not found: http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155
http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155

I can reach web page from inside eclipse web browser and I can reach the market place with my browser I guess it is coming from eclipse but I don't know how to solve it.

I tried to change the Network Connections settings from Native to Manual but no luck so far.

If anyone as an idea ?

Here is the stack trace :

eclipse.buildId=4.15.0.I20200305-0155
java.version=1.8.0_231
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=fr_FR
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product

org.eclipse.epp.mpc.core
Error
Tue Jun 02 10:54:16 CEST 2020
Failed to stream using org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport@27a4a153 - falling back to org.eclipse.epp.internal.mpc.core.util.TransportFactory$$Lambda$811/602501626@46a0adaa: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.

org.eclipse.core.runtime.CoreException: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:119)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    ... 11 more
Contains: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)

I have the same issue from Help->Marketplace and from the welcome menu.

Thx

UPDATE : I manage to make it work again by deleting all the . folder (.me2, .plguings ...)


来源: stackexchange

问:
SSRS printing rogue lines
I have created an SSRS report which includes a company logo embedded in the report header.  When the report is printed, two lines show up in the printout that are not in the design of the report.  It's like it is printing the textbox borders, but I have the borders set to none.  Has anyone seen this, and do you know how to make them go away?

Picture 1:  Design View of the report

Picture 2:  Preview of the report (looks normal)

Picture 3:  Print Layout of the report (how it looks printed to paper or to PDF) - notice the two lines show up

答:
You probably do actually have the borders set up to be displayed.

Open the border settings for the areas of your table on both sides of the border as well as the the border settings for the picture itself.

When you have a table with different borders settings specified for adjacent items, it is a bit of a crapshoot as to which shows up.

If that is not the case, I would try loading the image in another part of the report to see if the lines follow it.  Depending on what happens there, you will know where the problem originates.

ContentLicense: CC BY-SA 4.0

Title: SSRS printing rogue lines


问:
Joining Class DataFrame Tables by using Index in Python
I get tables as the attached images. It says class 'pandas.core.frame.DataFrame' when I checked its type. I get the tables by running for loop. I would like to keep merging/joining the tables by using index as below. Thank you for your help in advance! I attached my codes just in case.

```<code># Loop credentials
for credential in config.api_credentials:
    # Parameters
    security_key = ''
    system_id = credential[0]
    name = credential[1]
    api_id = credential[2]
    api_pass = credential[3]
    solar_id = credential[4]
    solar_tables = {}
    auth_url = "https://example.com/customer/authenticate?login=" + \
        api_id + "&password=" + api_pass + "&json=1"

    res = requests.post(auth_url)
    data = res.json()

    if data.get('securitykey') == None:
        print("There is no securitykey")
    else:
        security_key = data.get('securitykey')

    get_historical_data_url = "https://example.com/location/getHistoricalData?security_key=" + \
        security_key + "&json=1&startTime=2013-02-14T23:59&period=months"
    res2 = requests.get(get_historical_data_url)
    res2_text = res2.text
    production_data = json.loads(res2_text)
    production_data2 = production_data.get(system_id).get('data')

    # Transpose columns and rows
    production_data3 = pd.DataFrame(production_data2).transpose()

    # Drop useless columns and only keep solar production data
    solar_data = production_data3.loc[:, [solar_id]]

    # Extract and replace production values to absolute values
    solar_data[solar_id] = solar_data[solar_id].str.get(
        'kWh').astype(float).abs()

    # Change Label to system id + name
    solar_data.rename(columns={solar_id: system_id+"_"+name}, inplace=True)

    # Change index from datetime to date only
    solar_data.index = solar_data.index.str.split().str[0]

    print(type(solar_data))
    print(solar_data)
</code>```

答:
```<code>solar_data_list = []
# Loop credentials
for credential in config.api_credentials:
    # ...
    # at the end of the loop
    # ensure that the solar_data.index is really a DateTimeIndex and not a string
    solar_data_list += [solar_data]

result = pd.concat(solar_data_list, axis=1)
</code>```

Consider to have a look into how to deal with time series and how to merge, join, and concatenate in pandas.

Body:
I get tables as the attached images. It says class 'pandas.core.frame.DataFrame' when I checked its type. I get the tables by running for loop. I would like to keep merging/joining the tables by using index as below. Thank you for your help in advance! I attached my codes just in case.

# Loop credentials
for credential in config.api_credentials:
    # Parameters
    security_key = ''
    system_id = credential[0]
    name = credential[1]
    api_id = credential[2]
    api_pass = credential[3]
    solar_id = credential[4]
    solar_tables = {}
    auth_url = "https://example.com/customer/authenticate?login=" + \
        api_id + "&password=" + api_pass + "&json=1"

    res = requests.post(auth_url)
    data = res.json()

    if data.get('securitykey') == None:
        print("There is no securitykey")
    else:
        security_key = data.get('securitykey')

    get_historical_data_url = "https://example.com/location/getHistoricalData?security_key=" + \
        security_key + "&json=1&startTime=2013-02-14T23:59&period=months"
    res2 = requests.get(get_historical_data_url)
    res2_text = res2.text
    production_data = json.loads(res2_text)
    production_data2 = production_data.get(system_id).get('data')

    # Transpose columns and rows
    production_data3 = pd.DataFrame(production_data2).transpose()

    # Drop useless columns and only keep solar production data
    solar_data = production_data3.loc[:, [solar_id]]

    # Extract and replace production values to absolute values
    solar_data[solar_id] = solar_data[solar_id].str.get(
        'kWh').astype(float).abs()

    # Change Label to system id + name
    solar_data.rename(columns={solar_id: system_id+"_"+name}, inplace=True)

    # Change index from datetime to date only
    solar_data.index = solar_data.index.str.split().str[0]

    print(type(solar_data))
    print(solar_data)

Body:
solar_data_list = []
# Loop credentials
for credential in config.api_credentials:
    # ...
    # at the end of the loop
    # ensure that the solar_data.index is really a DateTimeIndex and not a string
    solar_data_list += [solar_data]

result = pd.concat(solar_data_list, axis=1)

Consider to have a look into how to deal with time series and how to merge, join, and concatenate in pandas.


问:
Passing an object's Type in a call to a Generic
I've seen several other similar posts, but they don't seem to fit with my scenario.

I'm trying to create a set of deep Cloning methods to a set of objects that inherit from a base class.  I've created some sample classes that illustrate what I'm trying to do.

I've been reading through all the similar posts here and the MS documentation, but nothing seems to work.  Any suggestions on how to approach this would be appreciated.

The offending line of code in this is below.  Using typeof(c) is invalid and I cannot find any suitable way of replacing that with something that does work.

```<code>SubEvents = (IList<IFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()
</code>```

I cannot figure a way to pass the object's type to the Clone method.

```<code>public class MyFoo : IFoo
{
    public int Id { get; set; }
    public IList<IFoo> SubEvents { get; set; } = new List<IFoo>();

    public T Clone<T>() where T : IFoo, new()
    {
        var rtn = new T
        {
            Id = Id,
            SubEvents = (IList<IMyFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()
        };
        return rtn;
    }
}

public class Bar: Foo, IBar
{
    public int Fred { get; set; }
    public int Betty { get; set; }

    public IEventQuestTimerChange Clone()
    {
        var rtn = base.Clone<Foo>();
        rtn.Fred = Fred;
        rtn.Betty = Betty;
        return rtn;
    }
}

public class Loader
{
    var IList<IFoo> MyList {get;set;} = new List<IFoo>();
    MyList.Add(new Foo());
    var bar = new Bar();
    bar.SubEvent.Add(new Foo());
    bar.SubEvent.Add(new Bar());
    MyList.Add(bar);

    var cloneList = MyList.Clone();
}
</code>```

答:
If I understand the problem correctly, the reason you want to use a generic type in the clone method is so you can return the derived type, and not the base type.

One way to solve this would be to create a copy-constructor, and a virtual clone method that returns a object of the derived type. That way you should not need any generics to create a deep copy:

```<code>    public class Foo
    {
        public int FooProperty { get; }
        public List<Foo> FooList { get; }
        public Foo()
        {
            // Regular Constructor
            FooList = new List<Foo>();
        }
        protected Foo(Foo other)
        {
            // Copy constructor
            FooProperty = other.FooProperty;
            FooList = other.FooList.Select(item => item.Clone()).ToList();
        }

        public virtual Foo Clone() => new Foo(this);
    }

    public class Bar : Foo
    {
        public int BarProperty { get; }
        public Bar()
        {
            // regular constructor
        }
        protected Bar(Bar other) : base(other)
        {
            // Copy constructor
            BarProperty = other.BarProperty;
        }
        public override Foo Clone() => new Bar(this);
        public virtual Bar CloneBar() => new Bar(this);
    }
</code>```

Example:

```<code>        var root = new Foo();
        root.FooList.Add(new Bar());
        root.FooList.Add(new Foo());
        var clone = root.Clone();
        Console.WriteLine($"Root: {clone.GetType().Name} -> [{clone.FooList[0].GetType().Name}, {clone.FooList[1].GetType().Name}]");
</code>```

Will write: "Root: Foo -> [Bar, Foo]"

Body:
I've seen several other similar posts, but they don't seem to fit with my scenario.

I'm trying to create a set of deep Cloning methods to a set of objects that inherit from a base class.  I've created some sample classes that illustrate what I'm trying to do.

I've been reading through all the similar posts here and the MS documentation, but nothing seems to work.  Any suggestions on how to approach this would be appreciated.

The offending line of code in this is below.  Using typeof(c) is invalid and I cannot find any suitable way of replacing that with something that does work.

SubEvents = (IList<IFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()

I cannot figure a way to pass the object's type to the Clone method.

public class MyFoo : IFoo
{
    public int Id { get; set; }
    public IList<IFoo> SubEvents { get; set; } = new List<IFoo>();

    public T Clone<T>() where T : IFoo, new()
    {
        var rtn = new T
        {
            Id = Id,
            SubEvents = (IList<IMyFoo>) SubEvents.Select(c => c.Clone < typeof(c) > ()).ToList()
        };
        return rtn;
    }
}

public class Bar: Foo, IBar
{
    public int Fred { get; set; }
    public int Betty { get; set; }

    public IEventQuestTimerChange Clone()
    {
        var rtn = base.Clone<Foo>();
        rtn.Fred = Fred;
        rtn.Betty = Betty;
        return rtn;
    }
}

public class Loader
{
    var IList<IFoo> MyList {get;set;} = new List<IFoo>();
    MyList.Add(new Foo());
    var bar = new Bar();
    bar.SubEvent.Add(new Foo());
    bar.SubEvent.Add(new Bar());
    MyList.Add(bar);

    var cloneList = MyList.Clone();
}

Body:
If I understand the problem correctly, the reason you want to use a generic type in the clone method is so you can return the derived type, and not the base type.

One way to solve this would be to create a copy-constructor, and a virtual clone method that returns a object of the derived type. That way you should not need any generics to create a deep copy:

    public class Foo
    {
        public int FooProperty { get; }
        public List<Foo> FooList { get; }
        public Foo()
        {
            // Regular Constructor
            FooList = new List<Foo>();
        }
        protected Foo(Foo other)
        {
            // Copy constructor
            FooProperty = other.FooProperty;
            FooList = other.FooList.Select(item => item.Clone()).ToList();
        }

        public virtual Foo Clone() => new Foo(this);
    }

    public class Bar : Foo
    {
        public int BarProperty { get; }
        public Bar()
        {
            // regular constructor
        }
        protected Bar(Bar other) : base(other)
        {
            // Copy constructor
            BarProperty = other.BarProperty;
        }
        public override Foo Clone() => new Bar(this);
        public virtual Bar CloneBar() => new Bar(this);
    }

Example:

        var root = new Foo();
        root.FooList.Add(new Bar());
        root.FooList.Add(new Foo());
        var clone = root.Clone();
        Console.WriteLine($"Root: {clone.GetType().Name} -> [{clone.FooList[0].GetType().Name}, {clone.FooList[1].GetType().Name}]");

Will write: "Root: Foo -> [Bar, Foo]"


问:
How to run an AppleScript from within a Python script?
How to run an AppleScript from within a Python script?

The questions says it all..
(On a Mac obviously)

答:
I was pretty frustrated at the lack of detail in Apple's own documentation regarding how to do this AND to also pass in arguments. I had to send the desired arg (in this case a zoom id) as a string otherwise the argument didn't come through to the applescript app

Here's my code running from python:

```<code>f = script if os.path.exists(script) else _tempfile()

if not os.path.exists(script):
            open(f,'w').write(script)
args = ["osascript", f, str(zoom_id)]

kwargs = {'stdout':open(os.devnull, 'wb'),'stderr':open(os.devnull, 'wb')}
        #kwargs.update(params)
proc = subprocess.Popen(args,**kwargs)
</code>```

and here is my applescript:

```<code>on run argv
    set zoom_id to 0
    zoom_id = item 1 in argv
    tell application "zoom.us"
       --do stuff
    end tell
end run
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was pretty frustrated at the lack of detail in Apple's own documentation regarding how to do this AND to also pass in arguments. I had to send the desired arg (in this case a zoom id) as a string otherwise the argument didn't come through to the applescript app

Here's my code running from python:

f = script if os.path.exists(script) else _tempfile()

if not os.path.exists(script):
            open(f,'w').write(script)
args = ["osascript", f, str(zoom_id)]

kwargs = {'stdout':open(os.devnull, 'wb'),'stderr':open(os.devnull, 'wb')}
        #kwargs.update(params)
proc = subprocess.Popen(args,**kwargs)

and here is my applescript:

on run argv
    set zoom_id to 0
    zoom_id = item 1 in argv
    tell application "zoom.us"
       --do stuff
    end tell
end run


问:
Visual Studio C++ How to get the Form not freezing while calling a time-consuming function?
I am making a C++/CLI Forms application.

In the main window of my app I have a button. When I click that button I call the Load function. Below there is the C++/CLI code:

```<code>private: System::Void Button1_Click(System::Object^  sender, System::EventArgs^  e) {
     Load();
}
</code>```

The function Load() is a time-consuming function. It uses the cURL library to send several HTTP GET request to a website.

In the Form I also included a ProgressBar and a textLabel showing the current request being sended.

The problem is that when I click the button and call the function the Form just freezes. I can't see the progressBar and Textlabel changing it's value while the function Load() is called, the Form is just freezed. When the function Load() has finished sending request, suddenly the progressBar change It's value to 100%.

I hope I described my problem clearly enough to understand it.

答:
Either break the task into smaller parts (design a finite state machine or use continuations) or use a separate thread.

The first approach takes more getting used to, but it's easier for an experienced programmer to get right.  Threading requires synchronization which is very detail-oriented and causes a lot of hidden sporadic bugs which are extremely difficult to debug.

Body:
I am making a C++/CLI Forms application.

In the main window of my app I have a button. When I click that button I call the Load function. Below there is the C++/CLI code:

private: System::Void Button1_Click(System::Object^  sender, System::EventArgs^  e) {
     Load();
}

The function Load() is a time-consuming function. It uses the cURL library to send several HTTP GET request to a website.

In the Form I also included a ProgressBar and a textLabel showing the current request being sended.

The problem is that when I click the button and call the function the Form just freezes. I can't see the progressBar and Textlabel changing it's value while the function Load() is called, the Form is just freezed. When the function Load() has finished sending request, suddenly the progressBar change It's value to 100%.

I hope I described my problem clearly enough to understand it.


问:
Show notification then after 5 seconds navigation to other page
I want to create a notification. After 5 seconds the notification should vanish then it goes to another page.

```<code>export class AppComponent  {
name = 'Angular 5';
constructor(private router: Router) {
  var notify = new Notification('', {body: 'test'});
  setTimeout(notify.close.bind(notify), 5000);
  this.router.navigate(['/page1']);
  }
}
</code>```

However it navigates to the other page immediately; I can't see the notification.

Stackblize demo

答:
From what I understood, you want to show the notification and on close of it redirect to a different page.

Try this:

```<code> export class AppComponent  {
  name = 'Angular 5';
  constructor(private router: Router) {
      var notify = new Notification('', {body: 'This is a notification'});
      notify.onclose = (
          () => {
          setTimeout(() => {
            this.router.navigate(['/page1']);
          }, 5000);
        }
      );
    }
  }
</code>```

Stackblitz Editor: https://stackblitz.com/edit/routing-example-x8hbhm

Stackblitz App url: https://routing-example-x8hbhm.stackblitz.io

You also might want to check if the notification permission was granted or not.

Example from https://developer.mozilla.org/en-US/docs/Web/API/notification

```<code>if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");
  }

  // Otherwise, we need to ask the user for permission
  else if (Notification.permission !== "denied") {
    Notification.requestPermission().then(function (permission) {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  }
</code>```

Body:
I want to create a notification. After 5 seconds the notification should vanish then it goes to another page.

export class AppComponent  {
name = 'Angular 5';
constructor(private router: Router) {
  var notify = new Notification('', {body: 'test'});
  setTimeout(notify.close.bind(notify), 5000);
  this.router.navigate(['/page1']);
  }
}

However it navigates to the other page immediately; I can't see the notification.

Stackblize demo

Body:
From what I understood, you want to show the notification and on close of it redirect to a different page.

Try this:

 export class AppComponent  {
  name = 'Angular 5';
  constructor(private router: Router) {
      var notify = new Notification('', {body: 'This is a notification'});
      notify.onclose = (
          () => {
          setTimeout(() => {
            this.router.navigate(['/page1']);
          }, 5000);
        }
      );
    }
  }

Stackblitz Editor: https://stackblitz.com/edit/routing-example-x8hbhm

Stackblitz App url: https://routing-example-x8hbhm.stackblitz.io

You also might want to check if the notification permission was granted or not.

Example from https://developer.mozilla.org/en-US/docs/Web/API/notification

if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");
  }

  // Otherwise, we need to ask the user for permission
  else if (Notification.permission !== "denied") {
    Notification.requestPermission().then(function (permission) {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  }


问:
cURL in Laravel and goDaddy API
I am making a domain purchase call via the godaddy API. I have been successful purchasing a domain on their test environment: https://developer.godaddy.com/doc/endpoint/domains

```<code>
                $bodyContent=json_encode($bodyContent);

                $ch = curl_init();
                $timeout=60;

                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyContent);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);

                $result = curl_exec($ch);

                $dn = json_decode($result,true);
                $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                dd($http_status);
</code>```

The URL endpoint:

```<code>$url = "https://api.ote-godaddy.com/v1/domains/purchase";
</code>```

When i now try and do this on laravel and dd(http_status) i get a 404 error. I can provide more details on the $bodyContent but for now just know the same variable works fine in the godaddy environment. I am new to curl so something must be wrong in the above code snippet

答:
Try to use Guzzle, Laravel provides it out of the box. Your request will be like this (don't forget to paste your Api Keys):

```<code>// Initialise new Client
$client = new \GuzzleHttp\Client();

// Make headers
$headers = ['Authorization' => 'sso-key [API_KEY]:[API_SECRET]']

// Make body (without json_encode)
$body = ['name' => John, 'age' => '21'];

// Make request with your headers and body
$responce = $client->post('https://api.ote-godaddy.com/v1/domains/purchase', [
    'headers' => $headers,
    'form_params' => $body
]);

// Get Api responce content
$result = $responce->getBody()->getContents();
</code>```

Notice! I`m use 'POST' reques, becouse for 'v1/domains/purchase'
  available only POST method

Title: cURL in Laravel and goDaddy API

Body:
I am making a domain purchase call via the godaddy API. I have been successful purchasing a domain on their test environment: https://developer.godaddy.com/doc/endpoint/domains

                $bodyContent=json_encode($bodyContent);

                $ch = curl_init();
                $timeout=60;

                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyContent);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);

                $result = curl_exec($ch);

                $dn = json_decode($result,true);
                $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                dd($http_status);

The URL endpoint:

$url = "https://api.ote-godaddy.com/v1/domains/purchase";

When i now try and do this on laravel and dd(http_status) i get a 404 error. I can provide more details on the $bodyContent but for now just know the same variable works fine in the godaddy environment. I am new to curl so something must be wrong in the above code snippet

Body:
Try to use Guzzle, Laravel provides it out of the box. Your request will be like this (don't forget to paste your Api Keys):

// Initialise new Client
$client = new \GuzzleHttp\Client();

// Make headers
$headers = ['Authorization' => 'sso-key [API_KEY]:[API_SECRET]']

// Make body (without json_encode)
$body = ['name' => John, 'age' => '21'];

// Make request with your headers and body
$responce = $client->post('https://api.ote-godaddy.com/v1/domains/purchase', [
    'headers' => $headers,
    'form_params' => $body
]);

// Get Api responce content
$result = $responce->getBody()->getContents();

Notice! I`m use 'POST' reques, becouse for 'v1/domains/purchase'
  available only POST method


问:
Iterating through a range of dates in Python
I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.

day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
    print strftime("%Y-%m-%d", single_date.timetuple())
```

<h2>Notes</h2>

<ul>
<li>I'm not actually using this to print. That's just for demo purposes. </li>
<li>The <code>start_date</code> and <code>end_date</code> variables are <code>datetime.date</code> objects because I don't need the timestamps. (They're going to be used to generate a report).</li>
</ul>

<h2>Sample Output</h2>

<p>For a start date of <code>2009-05-30</code> and an end date of <code>2009-06-09</code>:</p>

<pre class="lang-py prettyprint-override"><code>2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09
</code>```

答:
```<code>import datetime
from dateutil.rrule import DAILY,rrule

date=datetime.datetime(2019,1,10)

date1=datetime.datetime(2019,2,2)

for i in rrule(DAILY , dtstart=date,until=date1):
     print(i.strftime('%Y%b%d'),sep='\n')
</code>```

OUTPUT:

```<code>2019Jan10
2019Jan11
2019Jan12
2019Jan13
2019Jan14
2019Jan15
2019Jan16
2019Jan17
2019Jan18
2019Jan19
2019Jan20
2019Jan21
2019Jan22
2019Jan23
2019Jan24
2019Jan25
2019Jan26
2019Jan27
2019Jan28
2019Jan29
2019Jan30
2019Jan31
2019Feb01
2019Feb02
</code>```

Body:
I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.

day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
    print strftime("%Y-%m-%d", single_date.timetuple())

Notes

I'm not actually using this to print. That's just for demo purposes.

The start_date and end_date variables are datetime.date objects because I don't need the timestamps. (They're going to be used to generate a report).

Sample Output

For a start date of 2009-05-30 and an end date of 2009-06-09:

2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09

Body:
import datetime
from dateutil.rrule import DAILY,rrule

date=datetime.datetime(2019,1,10)

date1=datetime.datetime(2019,2,2)

for i in rrule(DAILY , dtstart=date,until=date1):
     print(i.strftime('%Y%b%d'),sep='\n')

OUTPUT:

2019Jan10
2019Jan11
2019Jan12
2019Jan13
2019Jan14
2019Jan15
2019Jan16
2019Jan17
2019Jan18
2019Jan19
2019Jan20
2019Jan21
2019Jan22
2019Jan23
2019Jan24
2019Jan25
2019Jan26
2019Jan27
2019Jan28
2019Jan29
2019Jan30
2019Jan31
2019Feb01
2019Feb02


问:
Teambuild not copying XAP fiesl to _PublishedWebsites
I have a TFS build for sivelright and it copies all the files in the web project to _PublishedWebsites, except the xap file. Error is

Web.csproj error MSB3021: Unable to copy file "Some.xap" to "c:\somewhere\Some.xap"  Could not find file "Some.xap".

What it is trying to do, from where it is trying to copy and why it is failing?

答: Make sure your projects are built in the right order in your TFS Build Definition (Build Definition, Process, Required, Project to Build).</p>


问:
Possible to render Material elements within material-table?
I'm working on a data display for my application and have been looking into different available data table components built on top of Material UI. I'm wondering if it would be possible with material-table to render Material UI <Chip> components within one of the table columns. I tried what I thought made the most sense to attempt something like this, but it did not work. My attempt:

```<code>const test = () => {
    return (
      <div>
        <Chip>Test</Chip>
        <Chip>Another Test</Chip>
      </div>
    )
  }
</code>```

And then trying to render it:

```<code><MaterialTable
   columns={[
      { title: 'Project Types', field: 'types' }
   ]}
   data={[
      { types: test },
   ]}
/>
</code>```

Is there anything I can do to render these Chips within my Material Table?

答:
Something like this?
Check out MaterialTable's custom column rendering section

```<code><MaterialTable
  columns={[
    {
      title: 'Project Types',
      field: 'types',
      render: rowData => (
        <div>
          {rowData.types.map(type => (
            <Chip key={type} label={type}/>
          ))}
        </div>
      ),
    },
  ]}
/>;
</code>```

Body:
I'm working on a data display for my application and have been looking into different available data table components built on top of Material UI. I'm wondering if it would be possible with material-table to render Material UI <Chip> components within one of the table columns. I tried what I thought made the most sense to attempt something like this, but it did not work. My attempt:

const test = () => {
    return (

        <Chip>Test</Chip>
        <Chip>Another Test</Chip>

    )
  }

And then trying to render it:

<MaterialTable
   columns={[
      { title: 'Project Types', field: 'types' }
   ]}
   data={[
      { types: test },
   ]}
/>

Is there anything I can do to render these Chips within my Material Table?

Body:
Something like this?
Check out MaterialTable's custom column rendering section

<MaterialTable
  columns={[
    {
      title: 'Project Types',
      field: 'types',
      render: rowData => (
        <div>
          {rowData.types.map(type => (
            <Chip key={type} label={type}/>
          ))}
        </div>
      ),
    },
  ]}
/>;


问:
PPTXGENJS Is there a way to insert an HTML formatted text inside a slide?
Is it possible to insert HTML formatted texts inside a slide?

I need to insert a set of HTML formatted texts that was entered in a WYSIWYG input from TinyMCE in a powerpoint slide generated by PPTXGENJS.

If this is possible, I am looking for examples on how to do it. Articles or samples will be greatly appreciated.

答:
This solutions worked for me.

You need to create a table in html.

```<code><table id="table-id">
</table>
</code>```

Then you can append WYSIWYG (tinyMCE) content to this table.

```<code>$('#table-id').html('<tbody><tr><td>' + tinymce.activeEditor.getContent() + '</td></tr></tbody>');
</code>```

Then use tableToSlides method.

```<code>pptx.tableToSlides('table-id');
</code>```

Body:
This solutions worked for me.

You need to create a table in html.

<table id="table-id">
</table>

Then you can append WYSIWYG (tinyMCE) content to this table.

$('#table-id').html('<tbody><tr><td>' + tinymce.activeEditor.getContent() + '</td></tr></tbody>');

Then use tableToSlides method.

pptx.tableToSlides('table-id');


问:
How to solve size mismatch error in pytorch?
I am trying to create a logistic model by using CIFAR10 data in PyTorch. After running the model for evaluation I run into an error :

RuntimeError: size mismatch, m1: [750 x 4096], m2: [1024 x 10] at C:\w\1\s\tmp_conda_3.7_100118\conda\conda-bld\pytorch_1579082551706\work\aten\src\TH/generic/THTensorMath.cpp:136

It seems like input_size is creating a problem, I dont know I am new to this. Please let me know what changes should I make in order to overcome this error.

These are the hyperparameters:

```<code>batch_size = 100
learning_rate = 0.001

# Other constants
input_size = 4*4*64
num_classes = 10
</code>```

This is the cell that downloads and splits the dataset into train, validation and test.

```<code>transform = torchvision.transforms.Compose(
    [torchvision.transforms.ToTensor(),
     torchvision.transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])

testset = torchvision.datasets.CIFAR10(root='D:\PyTorch\cifar-10-python', train=False,download=False, transform=transform)
trainvalset = torchvision.datasets.CIFAR10(root='D:\PyTorch\cifar-10-python', train=True,download=False, transform=transform)
trainset, valset = torch.utils.data.random_split(trainvalset, [45000, 5000]) # 10% for validation

train_loader = torch.utils.data.DataLoader(trainset, batch_size=50, shuffle=True)
test_loader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=False)
val_loader = torch.utils.data.DataLoader(valset, batch_size=1000, shuffle=False)
</code>```

This is the architecture of my model.

```<code>class CifarModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(input_size,  num_classes)
    def forward(self, xb):
        xb = xb.view(-1, 64*8*8)
        #xb = xb.reshape(-1, 784)
        print(xb.shape)
        out = self.linear(xb)
        return out

    def training_step(self, batch):
        images, labels = batch
        out = self(images)                  # Generate predictions
        loss = F.cross_entropy(out, labels) # Calculate loss
        return loss

    def validation_step(self, batch):
        images, labels = batch
        out = self(images)                    # Generate predictions
        loss = F.cross_entropy(out, labels)   # Calculate loss
        acc = accuracy(out, labels)           # Calculate accuracy
        return {'val_loss': loss.detach(), 'val_acc': acc.detach()}

    def validation_epoch_end(self, outputs):
        batch_losses = [x['val_loss'] for x in outputs]
        epoch_loss = torch.stack(batch_losses).mean()   # Combine losses
        batch_accs = [x['val_acc'] for x in outputs]
        epoch_acc = torch.stack(batch_accs).mean()      # Combine accuracies
        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}

    def epoch_end(self, epoch, result):
        print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc']))

model = CifarModel()
</code>```

```<code>def accuracy(outputs, labels):
    _, preds = torch.max(outputs, dim=1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))
def evaluate(model, val_loader):
    outputs = [model.validation_step(batch) for batch in val_loader]
    return model.validation_epoch_end(outputs)

def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
    history = []
    optimizer = opt_func(model.parameters(), lr)
    for epoch in range(epochs):
        # Training Phase
        for batch in train_loader:
            loss = model.training_step(batch)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
        # Validation phase
        result = evaluate(model, val_loader)
        model.epoch_end(epoch, result)
        history.append(result)
    return history
evaluate(model, val_loader)
</code>```

答:
Here you are specifying that the number of output classes should be 10:

```<code>num_classes = 10
</code>```

Your forward function does not reflect this:

```<code>xb = xb.view(-1, 64*8*8) # you get 750x4096
out = self.linear(xb) # here an input of
# input_size to linear layer = 4*4*64 # 1024
# num_classes = 10
</code>```

Modify it like this:

```<code>xb = xb.view(-1, 64*4*4) # you get 750x1024
out = self.linear(xb) # M1 750x1024 M2 1024x10:
# input_size = 4*4*64 # 1024
# num_classes = 10
</code>```

Body:
I am trying to create a logistic model by using CIFAR10 data in PyTorch. After running the model for evaluation I run into an error :

RuntimeError: size mismatch, m1: [750 x 4096], m2: [1024 x 10] at C:\w\1\s\tmp_conda_3.7_100118\conda\conda-bld\pytorch_1579082551706\work\aten\src\TH/generic/THTensorMath.cpp:136

It seems like input_size is creating a problem, I dont know I am new to this. Please let me know what changes should I make in order to overcome this error.

These are the hyperparameters:

batch_size = 100
learning_rate = 0.001

# Other constants
input_size = 4*4*64
num_classes = 10

This is the cell that downloads and splits the dataset into train, validation and test.

transform = torchvision.transforms.Compose(
    [torchvision.transforms.ToTensor(),
     torchvision.transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])

testset = torchvision.datasets.CIFAR10(root='D:\PyTorch\cifar-10-python', train=False,download=False, transform=transform)
trainvalset = torchvision.datasets.CIFAR10(root='D:\PyTorch\cifar-10-python', train=True,download=False, transform=transform)
trainset, valset = torch.utils.data.random_split(trainvalset, [45000, 5000]) # 10% for validation

train_loader = torch.utils.data.DataLoader(trainset, batch_size=50, shuffle=True)
test_loader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=False)
val_loader = torch.utils.data.DataLoader(valset, batch_size=1000, shuffle=False)

This is the architecture of my model.

class CifarModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(input_size,  num_classes)
    def forward(self, xb):
        xb = xb.view(-1, 64*8*8)
        #xb = xb.reshape(-1, 784)
        print(xb.shape)
        out = self.linear(xb)
        return out

    def training_step(self, batch):
        images, labels = batch
        out = self(images)                  # Generate predictions
        loss = F.cross_entropy(out, labels) # Calculate loss
        return loss

    def validation_step(self, batch):
        images, labels = batch
        out = self(images)                    # Generate predictions
        loss = F.cross_entropy(out, labels)   # Calculate loss
        acc = accuracy(out, labels)           # Calculate accuracy
        return {'val_loss': loss.detach(), 'val_acc': acc.detach()}

    def validation_epoch_end(self, outputs):
        batch_losses = [x['val_loss'] for x in outputs]
        epoch_loss = torch.stack(batch_losses).mean()   # Combine losses
        batch_accs = [x['val_acc'] for x in outputs]
        epoch_acc = torch.stack(batch_accs).mean()      # Combine accuracies
        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}

    def epoch_end(self, epoch, result):
        print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc']))

model = CifarModel()

def accuracy(outputs, labels):
    _, preds = torch.max(outputs, dim=1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))
def evaluate(model, val_loader):
    outputs = [model.validation_step(batch) for batch in val_loader]
    return model.validation_epoch_end(outputs)

def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
    history = []
    optimizer = opt_func(model.parameters(), lr)
    for epoch in range(epochs):
        # Training Phase
        for batch in train_loader:
            loss = model.training_step(batch)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
        # Validation phase
        result = evaluate(model, val_loader)
        model.epoch_end(epoch, result)
        history.append(result)
    return history
evaluate(model, val_loader)

Body:
Here you are specifying that the number of output classes should be 10:

num_classes = 10

Your forward function does not reflect this:

xb = xb.view(-1, 64*8*8) # you get 750x4096
out = self.linear(xb) # here an input of
# input_size to linear layer = 4*4*64 # 1024
# num_classes = 10

Modify it like this:

xb = xb.view(-1, 64*4*4) # you get 750x1024
out = self.linear(xb) # M1 750x1024 M2 1024x10:
# input_size = 4*4*64 # 1024
# num_classes = 10


问:
Volume mount in docker for postgres data
I am trying to insert data into postgres using docker.

I have a folder in my code named data which has insert commands and has one file named init.sql.

I want to insert the data from init.sql present in folder data to tables present in docker.

version: '3.1'

services:
  postgres:
    image: postgres:11.6-alpine
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tables:/docker-entrypoint-initdb.d/
      - ./data:/var/lib/postgresql/data
volumes:
  data: {}
```

I am trying this but I get the error:

initdb: directory "/var/lib/postgresql/data" exists but is not empty

I think I am not using the correct use case, I am new to docker compose.

But is there any way, my use case can get satisfied?

答:
This is caused by an improper usage of the volumes syntax for your named volume.

In order to mount a named volume you have to just use its name like this:

    volumes:
      - data:/var/lib/postgresql/data
```

<p>If your syntax begins with a <code>.</code> then it will be a bind mount from your host.</p>

<pre class="lang-yaml prettyprint-override"><code>    volumes:
      - ./data:/var/lib/postgresql/data
</code>```

The above code is mounting the host folder data relative to where you your docker-compose.yml is located.

This docker-compose.yml should do what you expect.

version: '3.1'

services:
  postgres:
    image: postgres:11.6-alpine
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tables:/docker-entrypoint-initdb.d/
      - data:/var/lib/postgresql/data
volumes:
  data:
```

<hr>

<p>If for some reason your volume has been created already, with an empty or no database, your first step should be running:</p>

<pre class="lang-sh prettyprint-override"><code>docker-compose down --volumes
</code>```

From the documentation:

-v, --volumes           Remove named volumes declared in the `volumes`
                        section of the Compose file and anonymous volumes
                        attached to containers.

```

From: https://docs.docker.com/compose/reference/down/

Body:
I am trying to insert data into postgres using docker.

I have a folder in my code named data which has insert commands and has one file named init.sql.

I want to insert the data from init.sql present in folder data to tables present in docker.

version: '3.1'

services:
  postgres:
    image: postgres:11.6-alpine
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tables:/docker-entrypoint-initdb.d/
      - ./data:/var/lib/postgresql/data
volumes:
  data: {}

I am trying this but I get the error:

initdb: directory "/var/lib/postgresql/data" exists but is not empty

I think I am not using the correct use case, I am new to docker compose.

But is there any way, my use case can get satisfied?

Body:
This is caused by an improper usage of the volumes syntax for your named volume.

In order to mount a named volume you have to just use its name like this:

    volumes:
      - data:/var/lib/postgresql/data

If your syntax begins with a . then it will be a bind mount from your host.

    volumes:
      - ./data:/var/lib/postgresql/data

The above code is mounting the host folder data relative to where you your docker-compose.yml is located.

This docker-compose.yml should do what you expect.

version: '3.1'

services:
  postgres:
    image: postgres:11.6-alpine
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tables:/docker-entrypoint-initdb.d/
      - data:/var/lib/postgresql/data
volumes:
  data:

If for some reason your volume has been created already, with an empty or no database, your first step should be running:

docker-compose down --volumes

From the documentation:

-v, --volumes           Remove named volumes declared in the `volumes`
                        section of the Compose file and anonymous volumes
                        attached to containers.

From: https://docs.docker.com/compose/reference/down/


问:
how do I pass information from one class to another
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

```<code>File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }
</code>```

This code is in my customer class how do I get this information in my append class??

答:
In addition to DeadPassive's answer of associating the additional information with the Customer object:

The saving of the Customer data does not belong in the Customer Class.  The logic of persisting the data belongs in a seperate layer than the code that deals with manipulating the problem domain. A controller or service class seems like a more appropriate place to put the persistance logic.

Body:
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }

This code is in my customer class how do I get this information in my append class??


问:
Defined Array Variable working fine but child element not working in vuejs
Facing an Weird Issue in Vuejs.. I am using firestore to get data using props as id for the singlepost...
Now array formed is fine.. as you can see in the screenshot... there is no error in the console, i am seeing data... but its not working for its child key element.. attaching another screenshot of code.i guess if {{temple}} is working then {{temple.templename}} should work fine also

```<code><div class="appCapsule">
{{temple}}
         <div class="section mt-2">
            <div class="card text-center">
                <div class="card-header">
                    {{temple.templename}}
                </div>
                <div class="card-body">
                    <img v-bind:src="'https://awesong.in/jain/storage/temples/' + temple.fileToUpload1" style="width:100%">

                    <p class="card-text">Temple Type : {{temple.templetype}}</p>
                    <p class="card-text">Near By City : {{temple.nearbycity}}</p>
                    <p class="card-text">Built in : {{temple.built}}</p>
                    <p class="card-text">Address : {{temple.address}}</p>
                    <p class="card-text">Location : {{temple.location}}</p>
                    <p class="card-text">District : {{temple.district}}</p>
                    <p class="card-text">State : {{temple.state}}</p>
                    <p class="card-text">Phone : {{temple.phone}}</p>
                    <p class="card-text">Email : {{temple.email}}</p>
                    <p class="card-text">Website : {{temple.website}}</p>
                    <p class="card-text">Views : {{temple.clicks}}</p>

                </div>

            </div>
        </div>

    </div>
</code>```

Image attached for reference

答:
Temple is an array of JSON objects. You could use temple[0].property, or you could loop over it:

```<code><div v-for="t in temple" :key="JSON.stringify(t)">
     {{t.templename}} // etc
</div>
</code>```

Body:
Facing an Weird Issue in Vuejs.. I am using firestore to get data using props as id for the singlepost...
Now array formed is fine.. as you can see in the screenshot... there is no error in the console, i am seeing data... but its not working for its child key element.. attaching another screenshot of code.i guess if {{temple}} is working then {{temple.templename}} should work fine also

{{temple}}

                    {{temple.templename}}

Temple Type : {{temple.templetype}}

Near By City : {{temple.nearbycity}}

Built in : {{temple.built}}

Address : {{temple.address}}

Location : {{temple.location}}

District : {{temple.district}}

State : {{temple.state}}

Phone : {{temple.phone}}

Email : {{temple.email}}

Website : {{temple.website}}

Views : {{temple.clicks}}

Image attached for reference

Body:
Temple is an array of JSON objects. You could use temple[0].property, or you could loop over it:

<div v-for="t in temple" :key="JSON.stringify(t)">
     {{t.templename}} // etc
</div>


问:
Creating an JS array from PHP
I'm developing a Google Geochart and I'd like it to be dynamic. This is the static code to make the array to store the two values are as follows. The Country is the unique identifier for the map and the colour value is what the colour of the map will be. (Irrelevant but context)

```<code>  arrayData = [['Country','Color Value'],
  ['China',3],
  ['Russia',2.6],
  ['France',2.5],
  ['Spain',2.4],
  ['Portugal',1.1]
</code>```

I'd like to be able to make this array from a for loop taken from php echo values. Something like this pseudo code;

```<code>for (i in range table.length)

 arrayData = [['Country','Color Value'],

 [<?php echo $statements["Country"]; ?>], [<?php echo $statements["Color_Value"]; ?>],
</code>```

So similar to a php table as it gets all the values, I would like to do the same but for a JavaScript array. Any advice would be kind!

EDIT: The static code is an example, I want to take values from the database, the first value being country and the second value being colour value. BOTH from the database. I suppose in turn making the geochart dynamic

答:
You need to prepare array in php first and than just echo json_encode($arr):</p>

```<code><?php

$data = [];
foreach ($something as $statements) {
   $data[] = [$statements["Country"], $statements["Color_Value"]];
}
$arrayData = json_encode($data);
?>
arrayData = <?= $arrayData ?>;
</code>```

Title: Creating an JS array from PHP

Body:
I'm developing a Google Geochart and I'd like it to be dynamic. This is the static code to make the array to store the two values are as follows. The Country is the unique identifier for the map and the colour value is what the colour of the map will be. (Irrelevant but context)

  arrayData = [['Country','Color Value'],
  ['China',3],
  ['Russia',2.6],
  ['France',2.5],
  ['Spain',2.4],
  ['Portugal',1.1]

I'd like to be able to make this array from a for loop taken from php echo values. Something like this pseudo code;

for (i in range table.length)

 arrayData = [['Country','Color Value'],

 [<?php echo $statements["Country"]; ?>], [<?php echo $statements["Color_Value"]; ?>],

So similar to a php table as it gets all the values, I would like to do the same but for a JavaScript array. Any advice would be kind!

EDIT: The static code is an example, I want to take values from the database, the first value being country and the second value being colour value. BOTH from the database. I suppose in turn making the geochart dynamic

Body:
You need to prepare array in php first and than just echo json_encode($arr):

<?php

$data = [];
foreach ($something as $statements) {
   $data[] = [$statements["Country"], $statements["Color_Value"]];
}
$arrayData = json_encode($data);
?>
arrayData = <?= $arrayData ?>;


问:
How can I put a callable object into the map in C++?
I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?</p>

```<code>std::map<std::string, std::function<std::string()>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"] = [](std::string data) { return std::string("MD5 : ") + data; };
    FUNCS["CRC32"] = [](std::string data) { return std::string("CRC32 : ") + data; };
    FUNCS["RSA"] = [](std::string data, std::string key) { return std::string("RSA : ") + data + key; };

    std::cout << FUNCS["MD5"]("hello") << std::endl;
    std::cout << FUNCS["CRC32"]("hello") << std::endl;
    std::cout << FUNCS["RSA"]("hello","world") << std::endl;
}
</code>```

答:
You can put callable objects in a map or other containers just like you do with any other data: they must be of the same type.

It seems that the type your lambdas can be converted to are std::function<std::string(std::string)> for MD5 and CRC32, and it is std::function<std::string(std::string, std::string)> for RSA. Neither matches the type you defined in the map, which is std::function<std::string()>.

The difference between RSA and others is a real problem in your design. For instance, how are you supposed to write a function like the following:

```<code>std::string format_data(std::string algo, std::string data)
{
    return FUNCS[algo](data, ¿¿¿ maybe also "some key" ???);
}
</code>```

Body:
I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?

std::map<std::string, std::function<std::string()>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"] = [](std::string data) { return std::string("MD5 : ") + data; };
    FUNCS["CRC32"] = [](std::string data) { return std::string("CRC32 : ") + data; };
    FUNCS["RSA"] = [](std::string data, std::string key) { return std::string("RSA : ") + data + key; };

    std::cout << FUNCS["MD5"]("hello") << std::endl;
    std::cout << FUNCS["CRC32"]("hello") << std::endl;
    std::cout << FUNCS["RSA"]("hello","world") << std::endl;
}

Body:
You can put callable objects in a map or other containers just like you do with any other data: they must be of the same type.

It seems that the type your lambdas can be converted to are std::function<std::string(std::string)> for MD5 and CRC32, and it is std::function<std::string(std::string, std::string)> for RSA. Neither matches the type you defined in the map, which is std::function<std::string()>.

The difference between RSA and others is a real problem in your design. For instance, how are you supposed to write a function like the following:

std::string format_data(std::string algo, std::string data)
{
    return FUNCS[algo](data, ¿¿¿ maybe also "some key" ???);
}


问:
TypeError: props.routes.map is not a function
I'm new to react-redux. I am trying to pull data from Asp.Net Core Web Api to my react project.

I get an error when mapping the data I receive with redux in react.

I see the data coming in redux DevTools. State is filling up.

```<code>import React, { useEffect } from "react";
import * as actions from "../redux/actions/routeActions";
import { connect } from "react-redux";
import PropTypes from 'prop-types'

function Data({ ...props }) {
  useEffect(() => {
    props.fetchRoutes();
  });

    function renderData() {
        return props.routes.map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (
                <tr key={id}>
                    <td>{id}</td>
                    <td>{departureLocation}</td>
                    <td>{arrivalLocation}</td>
                    <td>{distance}</td>
                </tr>
            )
        })
    }
    return(
        < div >
            <table className="table">
                <thead>
                    <tr>
                        <th />
                        <th>departureLocation</th>
                        <th>arrivalLocation</th>
                        <th>Distance</th>
                    </tr>
                </thead>
                <tbody>
                    {renderData()}
                </tbody>
            </table>
        </div >
    );
}

Data.propTypes = {
    routes: PropTypes.array.isRequired
}

const mapStateToProps = (state) => ({
  routes: state.routes,
});

const mapDispatchToProps = {
  fetchRoutes: actions.fetchAll,
};

export default connect(mapStateToProps, mapActionToProps)(Data);
</code>```

And i get this error.

```<code>TypeError: props.routes.map is not a function.
</code>```

I couldn't find where I made a mistake.

答:
In addition to other answers you can also make your renderData to handle routes more safe like this :

    function renderData() {
        return (props.routes || []).map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (

                    {id}
                    {departureLocation}
                    {arrivalLocation}
                    {distance}

            )
        })
    }
```

Body:
I'm new to react-redux. I am trying to pull data from Asp.Net Core Web Api to my react project.

I get an error when mapping the data I receive with redux in react.

I see the data coming in redux DevTools. State is filling up.

import React, { useEffect } from "react";
import * as actions from "../redux/actions/routeActions";
import { connect } from "react-redux";
import PropTypes from 'prop-types'

function Data({ ...props }) {
  useEffect(() => {
    props.fetchRoutes();
  });

    function renderData() {
        return props.routes.map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (

                    {id}
                    {departureLocation}
                    {arrivalLocation}
                    {distance}

            )
        })
    }
    return(

                        departureLocation
                        arrivalLocation
                        Distance

                    {renderData()}

    );
}

Data.propTypes = {
    routes: PropTypes.array.isRequired
}

const mapStateToProps = (state) => ({
  routes: state.routes,
});

const mapDispatchToProps = {
  fetchRoutes: actions.fetchAll,
};

export default connect(mapStateToProps, mapActionToProps)(Data);

And i get this error.

TypeError: props.routes.map is not a function.

I couldn't find where I made a mistake.

Body:
In addition to other answers you can also make your renderData to handle routes more safe like this :

    function renderData() {
        return (props.routes || []).map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (
                <tr key={id}>
                    <td>{id}</td>
                    <td>{departureLocation}</td>
                    <td>{arrivalLocation}</td>
                    <td>{distance}</td>
                </tr>
            )
        })
    }


问:
put value of different keys to a single array
I have the following array of objects:

```<code>[
  {
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
]
</code>```

I would like to pass the value of all the months to a single array respecting the order of the months as follows:

```<code>[
  {
    "name": "product1",
    "data": [3, 2, 0, 1, 3, 0, 0, 0, 5, 0, 0, 0],
  },
  {
    "name": "product2",
    "data": [4, 0, 0, 1, 1, 0, 0, 0, 5, 0, 0, 0],
  }
]
</code>```

so how can i do this?

答:
Use a map to iterate over array of objects. Separate name from rest of the entries and return an object with name and the rest(using Object.values()).

var arr = [ { name: "product1", Jan: 3, Feb: 2, Mar: 0, Apr: 1, May: 3, Jun: 0, Jul: 0, Aug: 0, Sep: 5, Oct: 0, Nov: 0, Dec: 0 }, { name: "product2", Jan: 4, Feb: 0, Mar: 0, Apr: 1, May: 1, Jun: 0, Jul: 0, Aug: 0, Sep: 5, Oct: 0, Nov: 0, Dec: 0 } ];
var result = arr.map(item => {
  let { name, ...rest } = item;
  return { name, data: Object.values(rest) };
});
console.log(result);```

Body:
I have the following array of objects:

[
  {
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
]

I would like to pass the value of all the months to a single array respecting the order of the months as follows:

[
  {
    "name": "product1",
    "data": [3, 2, 0, 1, 3, 0, 0, 0, 5, 0, 0, 0],
  },
  {
    "name": "product2",
    "data": [4, 0, 0, 1, 1, 0, 0, 0, 5, 0, 0, 0],
  }
]

so how can i do this?


问:
Jupyter | The kernel appears to have died. It will restart automatically |
I have been running a particular python script for some time. All of the script had been running perfectly fine (including in Jupyter) for many months before this. Now, somehow, the jupyter in my system has started showing the following error message at one particular line of the code (the last line of the below mentioned code). All parts of the code run fine, except for the last line of the code (where I call a user defined function to do pair counts). The user defined function (correlation.polepy) can be found from https://github.com/OMGitsHongyu/N-body-analysis

This is the error message that I am getting:

Kernel Restarting
The kernel appears to have died. It will restart automatically.
```
<p>And, here is the skeleton of my Python Code:</p>
<pre class="lang-py prettyprint-override"><code>from __future__ import division
import numpy as np
import correlation
from scipy.spatial import cKDTree

File1 = np.loadtxt('/Users/Research/fname1.txt')
File2 = np.loadtxt('/Users/Research/fname2.txt')

masscut = 1.1*np.power(10,13)
mark1 = (np.where(File1[:,0]>masscut))[0]
mark2 = (np.where(File2[:,0]>masscut))[0]

Data1 = File1[mark1,1:8]
Data2 = File2[mark2,1:8]

Xi_masscut = correlation.polepy(p1=Data1, p2=Data2, rlim=150, nbins=150, nhocells=100, blen=1024, dis_f=100)
</code>```

Similar problem happens (last line of the code) when I try to use IPython. When I try to use Python (implement in terminal), I get an error message (at the last line) which says "Segmentation fault: 11". I am using Python 2.7.13 :: Anaconda 2.5.0 (x86_64).

I have tried the following methods already in search for a solution:

1.> I checked some of the previous links on stackoverflow where this problem has been asked: The kernel appears to have died. It will restart automatically

I tried the solution given in the link above; sadly it doesn't seem to work for my case. This is the solution that was mention in the link given above:

conda update mkl
```

2.> Just to check if the system is running out of memory, I closed all applications which are heavy on memory. My system has 16 GB physical memory and even when there is over 9 GB of free memory, this problem happens (again, this problem had not been happening before, even when I had been using 14 GB in other tasks and had less than 2 GB of memory. It's very surprising that I could run task with given inputs before and I am not able to replicate calculation with the same exact inputs now.)

3.> I saw another link:
https://alpine.atlassian.net/wiki/plugins/servlet/mobile?contentId=134545485#content/view/134545485

This one appears to tackle similar problems and it speaks about there not being enough memory for the docker container. I had doubts about how to implement the suggestions mentioned in there.

How do I solve this problem?

答: I tried conda install tensorflow which solved my problem.

Body:
I have been running a particular python script for some time. All of the script had been running perfectly fine (including in Jupyter) for many months before this. Now, somehow, the jupyter in my system has started showing the following error message at one particular line of the code (the last line of the below mentioned code). All parts of the code run fine, except for the last line of the code (where I call a user defined function to do pair counts). The user defined function (correlation.polepy) can be found from https://github.com/OMGitsHongyu/N-body-analysis

This is the error message that I am getting:

Kernel Restarting
The kernel appears to have died. It will restart automatically.

And, here is the skeleton of my Python Code:

from __future__ import division
import numpy as np
import correlation
from scipy.spatial import cKDTree

File1 = np.loadtxt('/Users/Research/fname1.txt')
File2 = np.loadtxt('/Users/Research/fname2.txt')

masscut = 1.1*np.power(10,13)
mark1 = (np.where(File1[:,0]>masscut))[0]
mark2 = (np.where(File2[:,0]>masscut))[0]

Data1 = File1[mark1,1:8]
Data2 = File2[mark2,1:8]

Xi_masscut = correlation.polepy(p1=Data1, p2=Data2, rlim=150, nbins=150, nhocells=100, blen=1024, dis_f=100)

Similar problem happens (last line of the code) when I try to use IPython. When I try to use Python (implement in terminal), I get an error message (at the last line) which says "Segmentation fault: 11". I am using Python 2.7.13 :: Anaconda 2.5.0 (x86_64).

I have tried the following methods already in search for a solution:

1.> I checked some of the previous links on stackoverflow where this problem has been asked: The kernel appears to have died. It will restart automatically

I tried the solution given in the link above; sadly it doesn't seem to work for my case. This is the solution that was mention in the link given above:

conda update mkl

2.> Just to check if the system is running out of memory, I closed all applications which are heavy on memory. My system has 16 GB physical memory and even when there is over 9 GB of free memory, this problem happens (again, this problem had not been happening before, even when I had been using 14 GB in other tasks and had less than 2 GB of memory. It's very surprising that I could run task with given inputs before and I am not able to replicate calculation with the same exact inputs now.)

3.> I saw another link:
https://alpine.atlassian.net/wiki/plugins/servlet/mobile?contentId=134545485#content/view/134545485

This one appears to tackle similar problems and it speaks about there not being enough memory for the docker container. I had doubts about how to implement the suggestions mentioned in there.

How do I solve this problem?


问:
How to create a python 3 class to start MATLAB and keep it running?
I'm using matlab 2017b and python 3 on windows 10. I want to create a class that can start the matlab and keep it open. However, matlab closes right after I finished the python script. Here is the code:

import matlab.engine
class Test:
    def __init__(self):
        self.eng = matlab.engine.start_matlab("-desktop")

if __name__ == "__main__":
    Test()
```

I can open the matlab in python console with the "start_matlab" command, but with this class I will keep failing to keep it open.
Anyone know how I could make this work?

答:
That's expected. From the documentation:

If you exit Python with an engine still running, then Python
  automatically stops the engine and its MATLAB process.

It sounds to me like you just want to start MATLAB from Python, as opposed to actually using the MATLAB engine.

To do so, you can use Python's subprocess standard library, e.g.:

```<code>import subprocess

class Test:
    def __init__(self):
        subprocess.run(r"C:\Program Files\MATLAB\R2020a\bin\matlab.exe")

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

Now the script will launch MATLAB, and MATLAB will remain open on termination of the script.
Obviously replace the path shown with the location of the MATLAB executable on your machine.

Body:
I'm using matlab 2017b and python 3 on windows 10. I want to create a class that can start the matlab and keep it open. However, matlab closes right after I finished the python script. Here is the code:

import matlab.engine
class Test:
    def __init__(self):
        self.eng = matlab.engine.start_matlab("-desktop")

if __name__ == "__main__":
    Test()

I can open the matlab in python console with the "start_matlab" command, but with this class I will keep failing to keep it open.
Anyone know how I could make this work?

Body:
That's expected. From the documentation:

If you exit Python with an engine still running, then Python
  automatically stops the engine and its MATLAB process.

It sounds to me like you just want to start MATLAB from Python, as opposed to actually using the MATLAB engine.

To do so, you can use Python's subprocess standard library, e.g.:

import subprocess

class Test:
    def __init__(self):
        subprocess.run(r"C:\Program Files\MATLAB\R2020a\bin\matlab.exe")

if __name__ == "__main__":
    Test()

Now the script will launch MATLAB, and MATLAB will remain open on termination of the script.
Obviously replace the path shown with the location of the MATLAB executable on your machine.


问:
Git untracked file in new feature branch
I was working on a feature branch locally, and added a new folder with a file in it. I then committed these new files along with my other changes and pushed to a remote server.

I am now working on a different feature branch from master; however the folder/file I added from the previous feature branch is showing in 'git status' as untracked and when I try to commit locally from my new feature branch, the folder stages itself for commit. I have tried to remove the folder using git clean -fd, but it then reappears when I am committing!

How do I deal with this untracked folder?

答:
If the file is committed when running git commit, it somehow got staged before.

To remove it from the staging area, run :

```<code>git reset folder/file
</code>```

You should not see it anymore in your next

```<code>git commit
</code>```

If it is not tracked and still present on your disk, and you know you want to delete it, just remove it with a regular rm.

Body:
If the file is committed when running git commit, it somehow got staged before.

To remove it from the staging area, run :

git reset folder/file

You should not see it anymore in your next

git commit

If it is not tracked and still present on your disk, and you know you want to delete it, just remove it with a regular rm.


问:
Error installing library of Scrapy in PyCharm
I can install other packages, but can't install Scrapy. I get the following errors:

```<code>warning: build_py: byte-compiling is disabled, skipping.

running build_ext
building 'lxml.etree' extension
error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).
</code>```

However, C++ is installed, which I installed numerous of times. I have x86 and 64 bit installations (not sure if it's 10.0) but I have 2013-2017 versions installed.

答:
In my case, I found that pywin32 was not installed...
So I did</p>

Body:
I can install other packages, but can't install Scrapy. I get the following errors:

warning: build_py: byte-compiling is disabled, skipping.

running build_ext
building 'lxml.etree' extension
error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).

However, C++ is installed, which I installed numerous of times. I have x86 and 64 bit installations (not sure if it's 10.0) but I have 2013-2017 versions installed.


问:
Problem with file dependencies and templates on a C++ program

Possible Duplicates:

  Templated function being reported as “undefined reference” during compilation

  Why can templates only be implemented in the header file?

Hi,
I'm having a problem with dependencies in a c++ program that only originates when I use templates. Apparently the compiler is not able to instantiate the template for a concrete type and I don't know why.

Suppose I have this library (the real program where I find this is much bigger, but I think this seems to reproduce my original problem):

```<code>//temp.cpp file
#include "temp.hpp"

template <typename a>
void printVector(std::vector<a> xs) {
  for_each(xs.begin(), xs.end(), [](a x) {std::cout << x << " ";});
}

void printDoubVector(std::vector<double> xs) {
  for_each(xs.begin(), xs.end(), [](double x) {std::cout << x << " ";});
}
</code>```

with this header file:

```<code>#include <vector>
#include <algorithm>
#include <iostream>

template <typename a> void printVector(std::vector<a> xs);
void printDoubVector(std::vector<double> xs);
</code>```

And this main file:

```<code>#include "temp.hpp"

int main(){
  std::vector<double> foo(10,1);
  printVector(foo);
  std::cout << std::endl;
}
</code>```

When I compile them with this makefile:

```<code>CC=g++-4.5
FLAGS = -std=gnu++0x -Wall

all: test

test: temp.o main.o
    $(CC) $(FLAGS) $^ -o $@

%.o: %.cpp
    $(CC) $(FLAGS) -c $^ -o $@
</code>```

I got a undefined reference to 'void printVector<double>(std::vector<double, std::allocator<double> >)' error.

Of course, if I do printDoubVector(foo); instead of printVector(foo);, it compiles normally. If everything's in the same file, it also compiles normally. I also tried to do printVector<double>(foo); with no result. Apparently the compiler knows I want a printVector<double>, he just can't find it. :(

I don't understand this problem. I was using templates in different files before without any problems at compilation. :( Yet, it feels like something very basic that I should know at this level. :/

答:
The reason is described in detail here.

In short, you need to provide the full definition in the header-file, otherwise the compiler cannot instantiate the template.

Body:
Possible Duplicates:

  Templated function being reported as “undefined reference” during compilation

  Why can templates only be implemented in the header file?

Hi,
I'm having a problem with dependencies in a c++ program that only originates when I use templates. Apparently the compiler is not able to instantiate the template for a concrete type and I don't know why.

Suppose I have this library (the real program where I find this is much bigger, but I think this seems to reproduce my original problem):

//temp.cpp file
#include "temp.hpp"

template <typename a>
void printVector(std::vector xs) {
  for_each(xs.begin(), xs.end(), [](a x) {std::cout << x << " ";});
}

void printDoubVector(std::vector<double> xs) {
  for_each(xs.begin(), xs.end(), [](double x) {std::cout << x << " ";});
}

with this header file:

#include <vector>
#include <algorithm>
#include <iostream>

template <typename a> void printVector(std::vector xs);
void printDoubVector(std::vector<double> xs);

And this main file:

#include "temp.hpp"

int main(){
  std::vector<double> foo(10,1);
  printVector(foo);
  std::cout << std::endl;
}

When I compile them with this makefile:

CC=g++-4.5
FLAGS = -std=gnu++0x -Wall

all: test

test: temp.o main.o
    $(CC) $(FLAGS) $^ -o $@

%.o: %.cpp
    $(CC) $(FLAGS) -c $^ -o $@

I got a undefined reference to 'void printVector<double>(std::vector<double, std::allocator<double> >)' error.

Of course, if I do printDoubVector(foo); instead of printVector(foo);, it compiles normally. If everything's in the same file, it also compiles normally. I also tried to do printVector<double>(foo); with no result. Apparently the compiler knows I want a printVector<double>, he just can't find it. :(

I don't understand this problem. I was using templates in different files before without any problems at compilation. :( Yet, it feels like something very basic that I should know at this level. :/


问:
Create a PowerShell Collections.Generic.IEnumerable[string] error
I can't create an IEnumerable on PowerShell.

My goal is another issue/type, but help me solve this "simple" one.

```<code>C:\Users\Me> $var = New-Object Collections.Generic.IEnumerable[string]
New-Object : A constructor was not found. Cannot find an appropriate constructor for type Collections.Generic.IEnumerable[string].
At line:1 char:8
+ $var = New-Object Collections.Generic.IEnumerable[string]
+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
</code>```

Can anyone clarify where or what I'm doing wrong?

The final object have a property with Collections.Generic.IEnumerable[...] so that is why using this type.

答:
IEnumerable[TypeParameter] is an interface, an abstract type that cannot be instantiated.

If you want an instance of a generic collection that implements IEnumerable[string], create a List[string]:

```<code>$var = New-Object System.Collections.Generic.List[string]
</code>```

If you use PowerShell 5.0 and newer versions' ::new() method, you can skip the System namespace prefix:

```<code>$var = [Collections.Generic.List[string]]::new()
# these will resolve to the same type
$var = [System.Collections.Generic.List[string]]::new()
</code>```

Body:
I can't create an IEnumerable on PowerShell.

My goal is another issue/type, but help me solve this "simple" one.

C:\Users\Me> $var = New-Object Collections.Generic.IEnumerable[string]
New-Object : A constructor was not found. Cannot find an appropriate constructor for type Collections.Generic.IEnumerable[string].
At line:1 char:8
+ $var = New-Object Collections.Generic.IEnumerable[string]
+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

Can anyone clarify where or what I'm doing wrong?

The final object have a property with Collections.Generic.IEnumerable[...] so that is why using this type.

Body:
IEnumerable[TypeParameter] is an interface, an abstract type that cannot be instantiated.

If you want an instance of a generic collection that implements IEnumerable[string], create a List[string]:

$var = New-Object System.Collections.Generic.List[string]

If you use PowerShell 5.0 and newer versions' ::new() method, you can skip the System namespace prefix:

$var = [Collections.Generic.List[string]]::new()
# these will resolve to the same type
$var = [System.Collections.Generic.List[string]]::new()