问:
Using next/dynamic to Avoid Window Error But Still Getting Window Error
Would really appreciate some help with this, have been trying to figure it out for a while.

I'm getting the below error. After some research, I figured out that you need to use "next/dynamic" with { ssr: false } to load modules dependent on window (since it's only avail in browser and not on server).

I added the below import to my app, but still getting the same error. Is there something wrong with the below and/or is there other configuration needed to make the dynamic loads function properly?

const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });

```<code>Server Error
ReferenceError: window is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
Object.<anonymous>
...
</code>```

UPDATE

So, it looks like I had to dynamic import the component where I was trying to use the component made with this import ... which seems redundant / i feel like I'm still doing something wrong.

So, now it's working, but I'm -

using const Chart = dynamic(() => import("react-apexcharts"), { ssr: false }); to build a component in ../barChart2.js

i'm again dynamic importing the component in barChart2.js when trying to use it (e.g., with const BarChart2 = dynamic(() => import('page-sections/charts/barChart2'), { ssr: false });

Is this actually how you are supposed to do it? Or is there a better way?

Didn't want to submit this as an answer, as I don't believe this is really the "correct" way even though it technically works.

Body:
Would really appreciate some help with this, have been trying to figure it out for a while.

I'm getting the below error. After some research, I figured out that you need to use "next/dynamic" with { ssr: false } to load modules dependent on window (since it's only avail in browser and not on server).

I added the below import to my app, but still getting the same error. Is there something wrong with the below and/or is there other configuration needed to make the dynamic loads function properly?

const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });

Server Error
ReferenceError: window is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
Object.<anonymous>
...

UPDATE

So, it looks like I had to dynamic import the component where I was trying to use the component made with this import ... which seems redundant / i feel like I'm still doing something wrong.

So, now it's working, but I'm -

using const Chart = dynamic(() => import("react-apexcharts"), { ssr: false }); to build a component in ../barChart2.js

i'm again dynamic importing the component in barChart2.js when trying to use it (e.g., with const BarChart2 = dynamic(() => import('page-sections/charts/barChart2'), { ssr: false });

Is this actually how you are supposed to do it? Or is there a better way?

Didn't want to submit this as an answer, as I don't believe this is really the "correct" way even though it technically works.


来源: stackexchange

问:
Photon, Two master clients
I've made a room with Photon and that's all good.
I'm the master client.
When I check the 'Photo View' on both players it shows them both as the master client.

As you can see in these images:

Test ^

Master ^

As you can see in these two images both of the players are the master controller. Why is this happening?

ContentLicense: CC BY-SA 4.0

Title: Photon, Two master clients


问:
Docker compose can't find entry point, but docker run can?
I'm getting this error when trying to use my compose up:

```<code>Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "./Nssams": stat ./Nssams: no such file or directory: unknown
</code>```

This is my compose file

```<code>version: '3.5'

services:

  eventlogger:
    container_name: nssams-eventlogger_
    image: nssams-eventlogger
    environment:
      - MQTT_HOST=mqtt
    depends_on:
      - mqtt
    command: python run.py

  mqtt:
      container_name: nssams-mqtt_
      image: eclipse-mosquitto:1.6.15
      ports:
        - 1883:1883

  ebcmos:
    image: nssams-ebcmos
    container_name: ebcmos
    networks:
      - default
    volumes:
      - ./capture/ebcmos:/app/capture:wo
      - ./logs/ebcmos:/app/
      - /dev/ttyUSB0:/dev/ttyUSB0
      - ./xmp/ebcmos:/app/xmp/ebcmos
    environment:
      - CAMERA_NAME=ebcmos
    privileged: true
    depends_on:
      - mqtt
      - eventlogger

networks:
    default:
        driver: bridge
        name: nssams_bridge

</code>```

Here is my Dockerfile:

```<code>FROM ubuntu:18.04 AS builder

# Install dependencies for building mqtt client from source.
RUN apt-get update && apt-get -y install build-essential git gcc make cmake cmake-gui cmake-curses-gui doxygen

# removed a bunch of irrelevant installs for stack overflow

RUN mkdir -p /app/build \
    && cd build \
    && cmake .. \
    && cmake --build .

# Production Image
FROM debian:latest AS prod
LABEL maintainer=redacted

WORKDIR /app

# Copy NSSAMS executable to prod image.
COPY --from=builder /app/build/Nssams .

CMD [ "./Nssams" ]
</code>```

but if I run the below command:

```<code>docker run -it --privileged --volume {volume} {image_name} bash
</code>```

I can exec it, and see my Nssams executable in /app. I then just go ./Nssams in a shell, and the application starts up.

Why can't docker compose do the same?

Body:
I'm getting this error when trying to use my compose up:

Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "./Nssams": stat ./Nssams: no such file or directory: unknown

This is my compose file

version: '3.5'

services:

  eventlogger:
    container_name: nssams-eventlogger_
    image: nssams-eventlogger
    environment:
      - MQTT_HOST=mqtt
    depends_on:
      - mqtt
    command: python run.py

  mqtt:
      container_name: nssams-mqtt_
      image: eclipse-mosquitto:1.6.15
      ports:
        - 1883:1883

  ebcmos:
    image: nssams-ebcmos
    container_name: ebcmos
    networks:
      - default
    volumes:
      - ./capture/ebcmos:/app/capture:wo
      - ./logs/ebcmos:/app/
      - /dev/ttyUSB0:/dev/ttyUSB0
      - ./xmp/ebcmos:/app/xmp/ebcmos
    environment:
      - CAMERA_NAME=ebcmos
    privileged: true
    depends_on:
      - mqtt
      - eventlogger

networks:
    default:
        driver: bridge
        name: nssams_bridge

Here is my Dockerfile:

FROM ubuntu:18.04 AS builder

# Install dependencies for building mqtt client from source.
RUN apt-get update && apt-get -y install build-essential git gcc make cmake cmake-gui cmake-curses-gui doxygen

# removed a bunch of irrelevant installs for stack overflow

RUN mkdir -p /app/build \
    && cd build \
    && cmake .. \
    && cmake --build .

# Production Image
FROM debian:latest AS prod
LABEL maintainer=redacted

WORKDIR /app

# Copy NSSAMS executable to prod image.
COPY --from=builder /app/build/Nssams .

CMD [ "./Nssams" ]

but if I run the below command:

docker run -it --privileged --volume {volume} {image_name} bash

I can exec it, and see my Nssams executable in /app. I then just go ./Nssams in a shell, and the application starts up.

Why can't docker compose do the same?


问:
how did I use select feature by radius Tool and get radius

How do I obtain the value in the top right corner of the screen when using the "Select feature by radius" function in QGIS, or set it manually, using pyqgis?

I tried to use iface.actionSelectRadius, but I couldn't find any relevant methods.


问:
OAuth on iPhone XR 2020, iOS 14.7.1 unexpected behavior in username entry
When connecting to Google to integrate Nest into another system (in this case Flair Systems) on an iPhone XR 2020 running iOS 14.7.1, the following happens:

I click the link in the Flair App to connect to Google Nest

I am directed to a standard Google OAuth portal

I enter a username with a Google Nest account associated with it

I click the Next button

The gray placeholder text "Email or phone" reappears, overlaid on top of the email address I just entered. The part of the email address that extends beyond "Email or phone" remains visible

The expectation is that I would instead be asked for a password, or informed that the user account does not exist. Image of faulty login state

There is little we can do to attempt to repair or circumvent this from our side. We have seen this in other users on iOS devices as well.


问:
Visualizing heroku postgresql DB backup
So heroku decided to delete hobby app databases as of Nov 28 and it wiped me out. I have a backup saved as '55e8c25e-2de7-4497-be94-6651363ca9e7', but have no idea how to access the data to hand-jam it into an excel spreadsheet to use in the interim. I used to use pgadmin, but it requires a direct link to a live database which heroku has since deleted. Is there a way for me to load this backup into a tool that would let me access the data?

Heroku has a message to open a ticket for situations like mine, but they don't let you open a ticket for hobby apps (go figure).

Title: Visualizing heroku postgresql DB backup


问:
Run shell script when usb is connected
I would like to understand how does a script on a usb stick can lunch itself. I would like to make a script that is on my usb stick and when the usb is connected it lunch a code like this:

```<code>#!/usr/bin/env bash

if zenity --question --text="Do you wish to make a backup of your documents/?"; then
    now=$(date)
    cp /my/document/path/* /my/usb/stick/now
fi
</code>```

The problem is that I don't understand how this .sh file that is on my usb drive know that the usb as been connected and have to lunch itself.

I hope I've explained well enough,

Thanks for your time.

Vincent

Title: Run shell script when usb is connected

Body:
I would like to understand how does a script on a usb stick can lunch itself. I would like to make a script that is on my usb stick and when the usb is connected it lunch a code like this:

#!/usr/bin/env bash

if zenity --question --text="Do you wish to make a backup of your documents/?"; then
    now=$(date)
    cp /my/document/path/* /my/usb/stick/now
fi

The problem is that I don't understand how this .sh file that is on my usb drive know that the usb as been connected and have to lunch itself.

I hope I've explained well enough,

Thanks for your time.

Vincent


问:
How to provide a DER server certificate file to Akka HTTP
I am trying to provide a server certificate file to my Akka HTTP application using the following code.

```<code>import java.io.{BufferedInputStream, IOException}
import java.security.{KeyStore, SecureRandom}
import java.security.cert.Certificate
import java.security.cert.CertificateFactory
import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLSocketFactory, TrustManagerFactory}
import scala.util.Try

trait TLSSupport extends Logging {

  // Add support for self-signed (local) SSL certificates
  // Based on http://developer.android.com/training/articles/security-ssl.html#UnknownCa

  def https(implicit configuration: Configuration): Either[Throwable, HttpsConnectionContext] = { // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    val cf = CertificateFactory.getInstance("X.509")
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    configuration.config.get("certificate").map {

      x =>
        Try {
          log.info(s"Retrieving resource ${x}")
          import java.io.FileInputStream
          val is = new FileInputStream(x)
          log.info(s"Creating stream for resource ${x}")

          val fis = new BufferedInputStream(is)
          log.info(s"Generating Certificate ${x}")
          val ca: Certificate = cf.generateCertificate(fis)

          log.info(s"Loading keystore Certificate ${x}")

          val keyStoreType = KeyStore.getDefaultType
          val keyStore = KeyStore.getInstance(keyStoreType)
          keyStore.load(null, null)
          log.info(s"Adding certificate entry to  keystore ")

          keyStore.setCertificateEntry("ca", ca)
          // Create a TrustManager that trusts the CAs in our KeyStore
          val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm
          val tmf = TrustManagerFactory.getInstance(tmfAlgorithm)
          tmf.init(keyStore)
          // Create an SSLContext that uses our TrustManager
          val sslContext = SSLContext.getInstance("TLS")
          sslContext.init(null, tmf.getTrustManagers, null)
          val https = ConnectionContext.httpsServer(sslContext)
          https

        }.toEither}.getOrElse(Left(throw new RuntimeException(s"Error loading TLS configuration")))
    }
}
</code>```
```<code>object Main extends App with Logging with TLSSupport {

    def main: Future[Http.ServerBinding] = https.map {
      case x: HttpsConnectionContext => log.info("Listening on secure port 8080."); Http().newServerAt("0.0.0.0", 8443).enableHttps(x).bind(routes)
      case _ => log.warn(new RuntimeException("Error loading tls configuration").toString); Http().newServerAt("0.0.0.0", 8080).bind(routes)
    } .getOrElse( {log.warn(new RuntimeException("Error loading tls configuration").toString); Http().newServerAt("0.0.0.0", 8080).bind(routes)} )

  }

  val server = new Application
  server.main

}

</code>```

No errors are thrown, but when it try to connect to the application locally, I get the followign error in openssl:

```<code>▶ curl --tlsv1.1 -vvv https://localhost:8443/api/umls/search\?searchString\=blood
*   Trying 127.0.0.1:8443...
* Connected to localhost (127.0.0.1) port 8443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/ssl/cert.pem
*  CApath: none
* (304) (OUT), TLS handshake, Client hello (1):
* (304) (IN), TLS handshake, Server hello (2):
* (304) (OUT), TLS handshake, Client hello (1):
* (304) (IN), TLS handshake, Server hello (2):
* (304) (IN), TLS handshake, Unknown (8):
* error:1404B410:SSL routines:ST_CONNECT:sslv3 alert handshake failure
* Closing connection 0
curl: (35) error:1404B410:SSL routines:ST_CONNECT:sslv3 alert handshake failure
</code>```

Doesnt seem to be an issue with ssl versioning etc as i have tested on multiple systems. Frankly I always get very confused with encryption even after reading the documentation cant find something that fits this particular case where I need to provide a preexisting server certificate.

Body:
I am trying to provide a server certificate file to my Akka HTTP application using the following code.

import java.io.{BufferedInputStream, IOException}
import java.security.{KeyStore, SecureRandom}
import java.security.cert.Certificate
import java.security.cert.CertificateFactory
import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLSocketFactory, TrustManagerFactory}
import scala.util.Try

trait TLSSupport extends Logging {

  // Add support for self-signed (local) SSL certificates
  // Based on http://developer.android.com/training/articles/security-ssl.html#UnknownCa

  def https(implicit configuration: Configuration): Either[Throwable, HttpsConnectionContext] = { // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    val cf = CertificateFactory.getInstance("X.509")
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    configuration.config.get("certificate").map {

      x =>
        Try {
          log.info(s"Retrieving resource ${x}")
          import java.io.FileInputStream
          val is = new FileInputStream(x)
          log.info(s"Creating stream for resource ${x}")

          val fis = new BufferedInputStream(is)
          log.info(s"Generating Certificate ${x}")
          val ca: Certificate = cf.generateCertificate(fis)

          log.info(s"Loading keystore Certificate ${x}")

          val keyStoreType = KeyStore.getDefaultType
          val keyStore = KeyStore.getInstance(keyStoreType)
          keyStore.load(null, null)
          log.info(s"Adding certificate entry to  keystore ")

          keyStore.setCertificateEntry("ca", ca)
          // Create a TrustManager that trusts the CAs in our KeyStore
          val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm
          val tmf = TrustManagerFactory.getInstance(tmfAlgorithm)
          tmf.init(keyStore)
          // Create an SSLContext that uses our TrustManager
          val sslContext = SSLContext.getInstance("TLS")
          sslContext.init(null, tmf.getTrustManagers, null)
          val https = ConnectionContext.httpsServer(sslContext)
          https

        }.toEither}.getOrElse(Left(throw new RuntimeException(s"Error loading TLS configuration")))
    }
}

object Main extends App with Logging with TLSSupport {

    def main: Future[Http.ServerBinding] = https.map {
      case x: HttpsConnectionContext => log.info("Listening on secure port 8080."); Http().newServerAt("0.0.0.0", 8443).enableHttps(x).bind(routes)
      case _ => log.warn(new RuntimeException("Error loading tls configuration").toString); Http().newServerAt("0.0.0.0", 8080).bind(routes)
    } .getOrElse( {log.warn(new RuntimeException("Error loading tls configuration").toString); Http().newServerAt("0.0.0.0", 8080).bind(routes)} )

  }

  val server = new Application
  server.main

}

No errors are thrown, but when it try to connect to the application locally, I get the followign error in openssl:

▶ curl --tlsv1.1 -vvv https://localhost:8443/api/umls/search\?searchString\=blood
*   Trying 127.0.0.1:8443...
* Connected to localhost (127.0.0.1) port 8443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/ssl/cert.pem
*  CApath: none
* (304) (OUT), TLS handshake, Client hello (1):
* (304) (IN), TLS handshake, Server hello (2):
* (304) (OUT), TLS handshake, Client hello (1):
* (304) (IN), TLS handshake, Server hello (2):
* (304) (IN), TLS handshake, Unknown (8):
* error:1404B410:SSL routines:ST_CONNECT:sslv3 alert handshake failure
* Closing connection 0
curl: (35) error:1404B410:SSL routines:ST_CONNECT:sslv3 alert handshake failure

Doesnt seem to be an issue with ssl versioning etc as i have tested on multiple systems. Frankly I always get very confused with encryption even after reading the documentation cant find something that fits this particular case where I need to provide a preexisting server certificate.


问:
Tricky Offset date within dataframe rows using Pandas
I would like to add a new consecutive date row at the end of a new category based on a column. Ex. based on the Area column.

Data

```<code>   Date         Start       End         Area    ID  Stat
   1/1/2022     2/1/2022    3/1/2022    NY      222 Y
   2/1/2022     3/1/2022    4/1/2022    NY      111 Y
   1/1/2022     2/1/2022    3/1/2022    CA      333 Y
   2/1/2022     3/1/2022    4/1/2022    CA      100 Y

</code>```

Desired

```<code> Date          Start        End         Area    ID  Stat
 1/1/2022      2/1/2022     3/1/2022    NY      222 Y
 2/1/2022      3/1/2022     4/1/2022    NY      111 Y
 3/1/2022      4/1/2022     5/1/2022    NY
 1/1/2022      2/1/2022     3/1/2022    CA      333 Y
 2/1/2022      3/1/2022     4/1/2022    CA      100 Y
 3/1/2022      4/1/2022     5/1/2022    CA
</code>```

Doing

SO member helped w this code, this works partial for me, as the dates are not offset:

```<code># Convert the cols to datetime
c = ['Start', 'End']
df[c] = df[c].apply(pd.to_datetime, dayfirst=True)

# drop the duplicates rows by Area while keeping only the last row
rows = df[[*c, 'Area']].drop_duplicates('Area', keep='last')

# Add a dateoffset of 1 day
rows[c] += pd.DateOffset(days=1)

# Concat the rows and sort index to maintain order
pd.concat([df, rows]).sort_index(ignore_index=True)
</code>```

Any suggestion is appreciated. I am currently researching this.

Body:
I would like to add a new consecutive date row at the end of a new category based on a column. Ex. based on the Area column.

Data

   Date         Start       End         Area    ID  Stat
   1/1/2022     2/1/2022    3/1/2022    NY      222 Y
   2/1/2022     3/1/2022    4/1/2022    NY      111 Y
   1/1/2022     2/1/2022    3/1/2022    CA      333 Y
   2/1/2022     3/1/2022    4/1/2022    CA      100 Y

Desired

 Date          Start        End         Area    ID  Stat
 1/1/2022      2/1/2022     3/1/2022    NY      222 Y
 2/1/2022      3/1/2022     4/1/2022    NY      111 Y
 3/1/2022      4/1/2022     5/1/2022    NY
 1/1/2022      2/1/2022     3/1/2022    CA      333 Y
 2/1/2022      3/1/2022     4/1/2022    CA      100 Y
 3/1/2022      4/1/2022     5/1/2022    CA

Doing

SO member helped w this code, this works partial for me, as the dates are not offset:

# Convert the cols to datetime
c = ['Start', 'End']
df[c] = df[c].apply(pd.to_datetime, dayfirst=True)

# drop the duplicates rows by Area while keeping only the last row
rows = df[[*c, 'Area']].drop_duplicates('Area', keep='last')

# Add a dateoffset of 1 day
rows[c] += pd.DateOffset(days=1)

# Concat the rows and sort index to maintain order
pd.concat([df, rows]).sort_index(ignore_index=True)

Any suggestion is appreciated. I am currently researching this.


问:
Can I restore my wallet access using just its pubkeys, ckeys, mkey and salt?
I recently managed to restore an old COLX wallet by importing a mobile backup file into colx-qt core %appdata folder.

After resyncing the blockchain I changed the rpcpassword and the wallet's encryption password, tested both of these and everything was in good order.

For testing purposes, I had decided to dump another encrypted backup file (wallet.dat) into the %appdata folder without removing the restored one first, resynced the blockchain, tried the passwords and noted they were now both incorrect.

I've removed both backups,resynced the blockchain anew, set rpcpassword and wallet unlock password to those associated with the first backup, imported said backup again but noticed that both passwords were now incorrect therefore losing my access to that mobile backup while at it.

Since I happen to have an older wallet.json file containing multiple addresses, several pubkeys and ckeys as well as the mkey (in the format {nID=1; encrypted_key:"the encrypted key"; nDerivationIterations:"62116 or some similar number"; version:""; etc etc}), could I use this information to restore my access to the wallet?

If YES, how exactly must I go about doing it?

Thank you in advance for your assistance!

I haven't tried anything else so far because I am trying to understand how this happened, what caused the change and how will I need to fix it before I'd just go ahead adding even more muddy details to the issue.


问:
Is it possible to export the file history timeline in visual studio code?
I would like to export the file-save history of one or more files as a text file, possibly csv.

For example: I'd like to ideally select a file or group of files in the file explorer, or select a time-range in a file's the timeline panel, then export that as a summary in csv form, ie:

```<code>file name, time-stamp
file name, time-stamp etc
</code>```

Can't find functionality for this. Perhaps an extension exists?

Body:
I would like to export the file-save history of one or more files as a text file, possibly csv.

For example: I'd like to ideally select a file or group of files in the file explorer, or select a time-range in a file's the timeline panel, then export that as a summary in csv form, ie:

file name, time-stamp
file name, time-stamp etc

Can't find functionality for this. Perhaps an extension exists?


问:
Lost connection to device: Why doesn't my Flutter project connect to the android emulator?
I cannot solve this error. The app seems to build just fine but, for some reason, can't seem to connect to the emulator. It always ends with "Lost connection to device" while installing. I also tried it on a physical device, still won't work. I have tried numerous possible solution, but none of them worked.

```<code>√  Built build\app\outputs\flutter-apk\app-debug.apk.
W/FlutterActivityAndFragmentDelegate( 5693): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
D/FlutterLocationService( 5693): Creating service.
D/FlutterLocationService( 5693): Binding to location service.
Lost connection to device.
Exited (1)
</code>```

What I've checked:

Memory enough

No connection problem

flutter doctor -v shows no issues

Wipe Data of emulator and tried again

Some further information on what I'm using:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
</code>```

build.gradle/android:

```<code> dependencies {
    classpath 'com.android.tools.build:gradle:7.0.2'

    classpath 'com.google.gms:google-services:4.3.8'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

}
</code>```

build.gradle/app:

```<code>defaultConfig {
    configurations.all {
        resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    }
    applicationId "com.praveeshramroop.athena"
    minSdkVersion 23
    targetSdkVersion 31
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true

}
</code>```

Body:
I cannot solve this error. The app seems to build just fine but, for some reason, can't seem to connect to the emulator. It always ends with "Lost connection to device" while installing. I also tried it on a physical device, still won't work. I have tried numerous possible solution, but none of them worked.

√  Built build\app\outputs\flutter-apk\app-debug.apk.
W/FlutterActivityAndFragmentDelegate( 5693): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
D/FlutterLocationService( 5693): Creating service.
D/FlutterLocationService( 5693): Binding to location service.
Lost connection to device.
Exited (1)

What I've checked:

Memory enough

No connection problem

flutter doctor -v shows no issues

Wipe Data of emulator and tried again

Some further information on what I'm using:

distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip

build.gradle/android:

 dependencies {
    classpath 'com.android.tools.build:gradle:7.0.2'

    classpath 'com.google.gms:google-services:4.3.8'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

}

build.gradle/app:

defaultConfig {
    configurations.all {
        resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    }
    applicationId "com.praveeshramroop.athena"
    minSdkVersion 23
    targetSdkVersion 31
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true

}


问:
Docker can not install yarn packages
I am trying to transform my NodeJs app into a Docker container, but during the "yarn" command, the container is having errors while installing the dependencies. I already removed unnecessary dependencies and cleaned node cache, but it still having this error.

There's the error:

```<code> => ERROR [4/5] RUN yarn                                                                       21.3s
------
 > [4/5] RUN yarn:
#0 0.772 yarn install v1.22.19
#0 0.887 [1/4] Resolving packages...
#0 1.074 [2/4] Fetching packages...
#0 6.223 error An unexpected error occurred: "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz: getaddrinfo EAI_AGAIN registry.yarnpkg.com".
#0 6.223 info If you think this is a bug, please open a bug report with the information provided in "/usr/app/yarn-error.log".
#0 6.223 info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
------
failed to solve: executor failed running [/bin/sh -c yarn]: exit code: 1
</code>```

I tried removing unnecessary dependencies and cleaning the node cache, also deleted the node_modules folder and re-installed the project in my machine, and it worked just fine, while Docker was having this errors.

Dockerfile

```<code>FROM node:16-alpine

WORKDIR /usr/app
COPY package.json yarn.lock ./

RUN yarn

COPY . .

EXPOSE 3000
CMD ["yarn", "start"]
</code>```

docker-compose.yml

```<code>version: '1'

services:
  app:
    container_name: nodejs-backend
    build: .
    ports:
      - "3000:3000"
    command: yarn start
</code>```

.dockerignore

```<code>node_modules
</code>```

I am also starting the container with this command: docker-compose up

Title: Docker can not install yarn packages

Body:
I am trying to transform my NodeJs app into a Docker container, but during the "yarn" command, the container is having errors while installing the dependencies. I already removed unnecessary dependencies and cleaned node cache, but it still having this error.

There's the error:

 => ERROR [4/5] RUN yarn                                                                       21.3s
------
 > [4/5] RUN yarn:
#0 0.772 yarn install v1.22.19
#0 0.887 [1/4] Resolving packages...
#0 1.074 [2/4] Fetching packages...
#0 6.223 error An unexpected error occurred: "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz: getaddrinfo EAI_AGAIN registry.yarnpkg.com".
#0 6.223 info If you think this is a bug, please open a bug report with the information provided in "/usr/app/yarn-error.log".
#0 6.223 info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
------
failed to solve: executor failed running [/bin/sh -c yarn]: exit code: 1

I tried removing unnecessary dependencies and cleaning the node cache, also deleted the node_modules folder and re-installed the project in my machine, and it worked just fine, while Docker was having this errors.

Dockerfile

FROM node:16-alpine

WORKDIR /usr/app
COPY package.json yarn.lock ./

RUN yarn

COPY . .

EXPOSE 3000
CMD ["yarn", "start"]

docker-compose.yml

version: '1'

services:
  app:
    container_name: nodejs-backend
    build: .
    ports:
      - "3000:3000"
    command: yarn start

.dockerignore

node_modules

I am also starting the container with this command: docker-compose up


问:
Image in border top
how can I make a card that contains an SVG image on the top edge?

like this

card

border top image

I tried to separate the image from the card, but I couldn't

Title: Image in border top


问:
Why can't I debug asyncio.get_running_loop() on pycharm?
I'm trying to test a jupyter notebook-safe wrapper for a library I maintain.

As part of that, I'm trying to simulate the jupyter environment by creating a new event loop in the test.

# test.py
...
    def test_with_existing_event_loop(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        jupyter_safe_run_coroutine(some_async_coroutine())
```
<pre class="lang-py prettyprint-override"><code>def jupyter_safe_run_coroutine(async_coro):
    try:
        loop = asyncio.get_running_loop()
        loop.create_task(async_coro)
    except RuntimeError:
        asyncio.run(async_coro)
</code>```

The problem is that even while there's a new loop set in the test, when I debug (pycharm) and step through the jupyter_safe_run_coroutine code, get_running_loop() always throws a RuntimeError.

When I try to step into it, it just doesn't, and skips to the except clause instead.

Any idea why?

Body:
I'm trying to test a jupyter notebook-safe wrapper for a library I maintain.

As part of that, I'm trying to simulate the jupyter environment by creating a new event loop in the test.

# test.py
...
    def test_with_existing_event_loop(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        jupyter_safe_run_coroutine(some_async_coroutine())

def jupyter_safe_run_coroutine(async_coro):
    try:
        loop = asyncio.get_running_loop()
        loop.create_task(async_coro)
    except RuntimeError:
        asyncio.run(async_coro)

The problem is that even while there's a new loop set in the test, when I debug (pycharm) and step through the jupyter_safe_run_coroutine code, get_running_loop() always throws a RuntimeError.

When I try to step into it, it just doesn't, and skips to the except clause instead.

Any idea why?


问:
A CategoriesProvider was used after being disposed. Once you have called dispose() Flutter
I am getting a serious issue that I failed solve so need help.

I was working on a app and there is a provider called CategoryProvider which I used on main screen and there are some forms and a timer so for those things I had to use disposed method (on different screen) and some stateful widgets.

I used MaterialApp inside MultiProvider.


问:
how to use current row data in a condition inside a window function on a partition with range between unbounded preceding and current row
I need to use the current row values in a condition used in a window function on a partition with range. See my example query I am looking for.

```<code>select
count(case when orderdate  >=
(**current_row.orderdate** -30) then 1 end)
over (partition by customerid order by orderdate range between unbounded preceding and current row)
from xyz
</code>```

Not getting correct syntax.

Please see below example output required. This is just an example, the 30 days and the logic is just a sample.

Body:
I need to use the current row values in a condition used in a window function on a partition with range. See my example query I am looking for.

select
count(case when orderdate  >=
(**current_row.orderdate** -30) then 1 end)
over (partition by customerid order by orderdate range between unbounded preceding and current row)
from xyz

Not getting correct syntax.

Please see below example output required. This is just an example, the 30 days and the logic is just a sample.


问:
Can iOS Swift play two separate audio files out of two separate pairs of AirPods?
I've been trying to play two different audio files out of two different pairs of AirPods simultaneously from a Swift app. After some trial and error, I've come to the following roadblock:

There can only be one AVAudioSession

The only way for an AVAudioSession have AVAudioPlayers playing out of different output devices is by setting its category to multiRoute

The only way for an AVAudioSession to detect "A2DP" devices for output (such as AirPods) is to set the category option allowBluetoothA2DP

The multiRoute category does not allow for the allowBluetoothA2DP option

Therefore, I feel I am stuck. Is there something I'm missing?

I tried detecting my bluetooth AirPods with a multiRoute AVAudioSession, with no success. I tried adding the allowBluetoothA2DP option to the multiRoute category, and the app crashed.


问:
Practical applications of multiple callbacks?
relatively new to Node.js and I've found that there's a lot of support for multiple callback functions. I'd love some help in understanding the applications of having such a structure (why isn't one enough?) Thanks!

Might it have something to do with making async requests in our callback functions?

i.e. I'm taking handling a get request, and must first make a get request of my own before ultimately returning the request to the client.


问:
MembershipUser.ChangePassword Rollback when exception
I have implemented the changepassword control and am trying to update password in codebehind. It works! But, when testing negative scenario like giving a password less than the required length, the ChangePassword method throws ArgumentException which is ok but at the same time it updates password in the database.
How can I rollback properly? What are the events fired before throwing the exceptions?

```<code>Try

                Dim password As String = ChangePwd.NewPassword

                'update passwordformat
                sp.UpdatePasswordFormat(username, "1")
                stepsDone += 1

                Dim mu As MembershipUser = Membership.Providers("VLSqlMembershipProvider").GetUser(username, False)

                'Dim resetPassword As String = mu.ResetPassword()
                ' returns false if the current password is invalid)
                If (mu.ChangePassword(mu.ResetPassword(), password)) Then
                    stepsDone += 1

                    'update account to issecurelyupgraded = 1
                    sp.UpdateUserSecurelyUpgradedFlag(username)
                    stepsDone += 1
                    'Else
                    'sp.UpdatePasswordFormat(username, "0")
                End If

            Catch argsex As ArgumentException
                sp.UpdatePasswordFormat(username, "0")
            Catch ex As Exception
                If stepsDone = 1 Then
                    'roll back updatepasswordformat
                    sp.UpdatePasswordFormat(username, "0")
                ElseIf stepsDone = 2 Then
                    'roll back first 2 steps
                End If
            End Try
</code>```

Some Context

I am migrating from clear to hashed passwordformat and have a custom hash implementation.

```<code><membership defaultProvider="VLSqlMembershipProvider" hashAlgorithmType="customhash">
</code>```

This is why I am first updating password format from 0 to 1, then updating password and in the end setting my dirty flag to false.

Body:
I have implemented the changepassword control and am trying to update password in codebehind. It works! But, when testing negative scenario like giving a password less than the required length, the ChangePassword method throws ArgumentException which is ok but at the same time it updates password in the database.
How can I rollback properly? What are the events fired before throwing the exceptions?

Try

                Dim password As String = ChangePwd.NewPassword

                'update passwordformat
                sp.UpdatePasswordFormat(username, "1")
                stepsDone += 1

                Dim mu As MembershipUser = Membership.Providers("VLSqlMembershipProvider").GetUser(username, False)

                'Dim resetPassword As String = mu.ResetPassword()
                ' returns false if the current password is invalid)
                If (mu.ChangePassword(mu.ResetPassword(), password)) Then
                    stepsDone += 1

                    'update account to issecurelyupgraded = 1
                    sp.UpdateUserSecurelyUpgradedFlag(username)
                    stepsDone += 1
                    'Else
                    'sp.UpdatePasswordFormat(username, "0")
                End If

            Catch argsex As ArgumentException
                sp.UpdatePasswordFormat(username, "0")
            Catch ex As Exception
                If stepsDone = 1 Then
                    'roll back updatepasswordformat
                    sp.UpdatePasswordFormat(username, "0")
                ElseIf stepsDone = 2 Then
                    'roll back first 2 steps
                End If
            End Try

Some Context

I am migrating from clear to hashed passwordformat and have a custom hash implementation.

<membership defaultProvider="VLSqlMembershipProvider" hashAlgorithmType="customhash">

This is why I am first updating password format from 0 to 1, then updating password and in the end setting my dirty flag to false.


问:
How do I get the following program to print Last name, first name middle name?
I have the following program that reads in from the user name the person first name, middle name, and last name. Then it prints out First name middle name last name, However I need it to print last name, first name middle name like the following example:

what I need:

User inputs: Jeff Dunlop Aarons

Then printed will be: Aarons, Jeff Dunlop

I know I need to start at the right end of the name and search backwards until a space is found, print it out, insert a commoa, and then go back to the start of the array and print the rest of the name but I can't seem to figure out how to do this.

```<code>
                include PCMAC.INC
                .model small
                .586
                .stack 100h
                .data
chars           db 80 dup(?)
AskName         db "Please Enter your full name, First Middle Last, then press enter: $"

numChars        dw ?

                .code

main            proc
                _Begin
                _PutStr AskName     ;;print the msg to user for what to do
                _Putch 13, 10

                mov numChars, 0     ;;set number of characters to 0
                mov bx, offset chars
                mov cx, 80
;;THIS PORTION OF THE CODE WILL GET THE NAME AND STORE IT IN BX
while_1:        _GetCh              ;; get the given characer
                cmp al, 13       ;; compare the user's input to enter???
                je end_while1
                mov byte ptr [bx], al
                inc bx
                inc al
                dec cx
                jmp while_1
end_while1:

;; THIS PORTION IS TO PRINT THE NAME BACK OUT
                mov cx, 80
                lea bx, chars
                xor si, si
for_1:
                mov dl, [bx + si]
                _Putch
                inc si
                dec cx
                jnz for_1

end_for1:
                _Exit 0
main            endp
                end main
</code>```

Body:
I have the following program that reads in from the user name the person first name, middle name, and last name. Then it prints out First name middle name last name, However I need it to print last name, first name middle name like the following example:

what I need:

User inputs: Jeff Dunlop Aarons

Then printed will be: Aarons, Jeff Dunlop

I know I need to start at the right end of the name and search backwards until a space is found, print it out, insert a commoa, and then go back to the start of the array and print the rest of the name but I can't seem to figure out how to do this.

                include PCMAC.INC
                .model small
                .586
                .stack 100h
                .data
chars           db 80 dup(?)
AskName         db "Please Enter your full name, First Middle Last, then press enter: $"

numChars        dw ?

                .code

main            proc
                _Begin
                _PutStr AskName     ;;print the msg to user for what to do
                _Putch 13, 10

                mov numChars, 0     ;;set number of characters to 0
                mov bx, offset chars
                mov cx, 80
;;THIS PORTION OF THE CODE WILL GET THE NAME AND STORE IT IN BX
while_1:        _GetCh              ;; get the given characer
                cmp al, 13       ;; compare the user's input to enter???
                je end_while1
                mov byte ptr [bx], al
                inc bx
                inc al
                dec cx
                jmp while_1
end_while1:

;; THIS PORTION IS TO PRINT THE NAME BACK OUT
                mov cx, 80
                lea bx, chars
                xor si, si
for_1:
                mov dl, [bx + si]
                _Putch
                inc si
                dec cx
                jnz for_1

end_for1:
                _Exit 0
main            endp
                end main


问:
Skip execution of pre middleware mongoose
I'm trying to implement password forgot functionality. I've a function that generate and save a jwt token to this.passwordResetToken.

But when I uses await user.save() then another userSchema.pre('save') middleware get's activated and this middleware is used to convert password into cryptography hash.

I want to stop execution of pre('save') middleware when user make a post reqyest to forgot password route.

```<code>// Forgot password function
exports.forgotPassword = async (req, res, next) => {
    const user = await User.findOne({email: req.body.email})

    if(!user){
        return next(new AppError('User not found', 404))
    }

    try {
        const resetToken = await user.createPasswordResetToken()
        await user.save()
        res.status(200).json({
            resetToken : resetToken
        })
    } catch (err){
        return next(err)
    }
}

// Pre middleware to convert password into hash.
userSchema.pre('save', async function(next){
    // if(!this.isModified('password')) return next();

    this.password = await bcrypt.hash(this.password, 12)
    this.passwordConfirm = undefined;
    next()
})

// Output Error
data and salt arguments required
</code>```

Body:
I'm trying to implement password forgot functionality. I've a function that generate and save a jwt token to this.passwordResetToken.

But when I uses await user.save() then another userSchema.pre('save') middleware get's activated and this middleware is used to convert password into cryptography hash.

I want to stop execution of pre('save') middleware when user make a post reqyest to forgot password route.

// Forgot password function
exports.forgotPassword = async (req, res, next) => {
    const user = await User.findOne({email: req.body.email})

    if(!user){
        return next(new AppError('User not found', 404))
    }

    try {
        const resetToken = await user.createPasswordResetToken()
        await user.save()
        res.status(200).json({
            resetToken : resetToken
        })
    } catch (err){
        return next(err)
    }
}

// Pre middleware to convert password into hash.
userSchema.pre('save', async function(next){
    // if(!this.isModified('password')) return next();

    this.password = await bcrypt.hash(this.password, 12)
    this.passwordConfirm = undefined;
    next()
})

// Output Error
data and salt arguments required


问:
Combine periodically and zoneschedule in flutter local notification,
I am trying to use a local notification flutter and try to combine periodicallyshow and zonescheduled,

Can anyone give a link or example reference?
Thank you

PERIODICALLYSHOW CODE

```<code> void scheduleNotification(String title, String body) async {
    AndroidNotificationDetails androidNotificationDetails =
        const AndroidNotificationDetails(
      'channelIs',
      'channelName',
      importance: Importance.max,
      priority: Priority.high,
    );
    NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
    );

    await _flutterLocalNotificationsPlugin.periodicallyShow(
      0,
      title,
      body,
      RepeatInterval.daily,//NOTE - repeat daily datetime(now) when press
      notificationDetails,
    );
  }
</code>```

ZONESCHEDULLED

```<code>static Future scheduleNotification({
    int id = 0,
    String? title,
    String? body,
    String? payload,
    required DateTime scheduledDate,
  }) async =>
      _notification.zonedSchedule(
        id,
        title,
        body,
        _scheduleDaily(const Time(07, 30)),//NOTE - SCHEDULE SPECIFIC TIME
        await _notificationDetails(),
        payload: payload,
        androidAllowWhileIdle: true,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime,
        matchDateTimeComponents: DateTimeComponents.time,
      );
  static tz.TZDateTime _scheduleDaily(Time time) {
    final now = tz.TZDateTime.now(tz.local);
    final scheduledDate = tz.TZDateTime(
      tz.local,
      now.year,
      now.month,
      now.day,
      time.hour,
      time.minute,
      time.second,
    );

    return scheduledDate.isBefore(now)
        ? scheduledDate.add(const Duration(days: 1))
        : scheduledDate;
  }
</code>```

When I run the function, it will run the notification repeatedly at the specific at 10:00 that I have determined

Body:
I am trying to use a local notification flutter and try to combine periodicallyshow and zonescheduled,

Can anyone give a link or example reference?
Thank you

PERIODICALLYSHOW CODE

 void scheduleNotification(String title, String body) async {
    AndroidNotificationDetails androidNotificationDetails =
        const AndroidNotificationDetails(
      'channelIs',
      'channelName',
      importance: Importance.max,
      priority: Priority.high,
    );
    NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
    );

    await _flutterLocalNotificationsPlugin.periodicallyShow(
      0,
      title,
      body,
      RepeatInterval.daily,//NOTE - repeat daily datetime(now) when press
      notificationDetails,
    );
  }

ZONESCHEDULLED

static Future scheduleNotification({
    int id = 0,
    String? title,
    String? body,
    String? payload,
    required DateTime scheduledDate,
  }) async =>
      _notification.zonedSchedule(
        id,
        title,
        body,
        _scheduleDaily(const Time(07, 30)),//NOTE - SCHEDULE SPECIFIC TIME
        await _notificationDetails(),
        payload: payload,
        androidAllowWhileIdle: true,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime,
        matchDateTimeComponents: DateTimeComponents.time,
      );
  static tz.TZDateTime _scheduleDaily(Time time) {
    final now = tz.TZDateTime.now(tz.local);
    final scheduledDate = tz.TZDateTime(
      tz.local,
      now.year,
      now.month,
      now.day,
      time.hour,
      time.minute,
      time.second,
    );

    return scheduledDate.isBefore(now)
        ? scheduledDate.add(const Duration(days: 1))
        : scheduledDate;
  }

When I run the function, it will run the notification repeatedly at the specific at 10:00 that I have determined


问:
Problem with in-app purchases in apple watch Swift
I have been trying in vain for several days to make a test purchase of a subscription from the watch, but nothing works out for me, all the methods that I found have been tried, and these are: apphud, rebooting devices, logging out with Apple ID, another Apple ID, test / not test apple id, sandbox is logged in, the appstore is also logged in, the card is linked, but, unfortunately, every time I try to buy, I get an error message: "Unable to Purchase App. Sign in with your Apple ID from the Apple Watch app on your iPhone".

Moreover, when I do all the same from the phone, everything works fine, and the purchase is made.
There is an option to try revenuecat, but honestly, I don't think it will be different from apphud. There is also an assumption that it is simply IMPOSSIBLE to make a test purchase from the watch.
Here is a piece of my code from in app manager (recipes are coming):

```<code>func startProducts() {
    let bundle = appBundleID

    let products = Set([
        bundle + ".1m",
        bundle + ".1y"
    ])

    request = SKProductsRequest(productIdentifiers: Set(products))

    request?.delegate = self
    request?.start()
}

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    guard firstRequestFinish else {
        return
    }
    firstRequestFinish = false
    defer {
        finishProducts()
    }
    if response.invalidProductIdentifiers.count > 0 {
        print("Invalid Products IDs: \(response.invalidProductIdentifiers)")
    }
    self.allProducts = response.products
    let subscriptions = (response.products.compactMap { item in
        return IAProduct(id: item.productIdentifier,
                         title: item.localizedTitle,
                         price: item.price,
                         localePrice: item.localizedPrice,
                         locale: item.priceLocale)
    }.sorted { item1, item2 in
        return item1.price.doubleValue < item2.price.doubleValue
    })
    self.availableSubscriptions = subscriptions
    if subscriptions.count > 0 {
        print("Available products IDs: \(subscriptions.map({ item in return item.id }))")
    }
    self.monthProduct = subscriptions.first { item in
        return item.id.contains(".1m")
    }
    self.yearProduct = subscriptions.first { item in
        return item.id.contains(".1y")
    }

    delegate?.inappWasLoaded()
}
</code>```

I would be glad for any advice! Many thanks to everyone who will take part in the discussion of this issue.

Body:
I have been trying in vain for several days to make a test purchase of a subscription from the watch, but nothing works out for me, all the methods that I found have been tried, and these are: apphud, rebooting devices, logging out with Apple ID, another Apple ID, test / not test apple id, sandbox is logged in, the appstore is also logged in, the card is linked, but, unfortunately, every time I try to buy, I get an error message: "Unable to Purchase App. Sign in with your Apple ID from the Apple Watch app on your iPhone".

Moreover, when I do all the same from the phone, everything works fine, and the purchase is made.
There is an option to try revenuecat, but honestly, I don't think it will be different from apphud. There is also an assumption that it is simply IMPOSSIBLE to make a test purchase from the watch.
Here is a piece of my code from in app manager (recipes are coming):

func startProducts() {
    let bundle = appBundleID

    let products = Set([
        bundle + ".1m",
        bundle + ".1y"
    ])

    request = SKProductsRequest(productIdentifiers: Set(products))

    request?.delegate = self
    request?.start()
}

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    guard firstRequestFinish else {
        return
    }
    firstRequestFinish = false
    defer {
        finishProducts()
    }
    if response.invalidProductIdentifiers.count > 0 {
        print("Invalid Products IDs: \(response.invalidProductIdentifiers)")
    }
    self.allProducts = response.products
    let subscriptions = (response.products.compactMap { item in
        return IAProduct(id: item.productIdentifier,
                         title: item.localizedTitle,
                         price: item.price,
                         localePrice: item.localizedPrice,
                         locale: item.priceLocale)
    }.sorted { item1, item2 in
        return item1.price.doubleValue < item2.price.doubleValue
    })
    self.availableSubscriptions = subscriptions
    if subscriptions.count > 0 {
        print("Available products IDs: \(subscriptions.map({ item in return item.id }))")
    }
    self.monthProduct = subscriptions.first { item in
        return item.id.contains(".1m")
    }
    self.yearProduct = subscriptions.first { item in
        return item.id.contains(".1y")
    }

    delegate?.inappWasLoaded()
}

I would be glad for any advice! Many thanks to everyone who will take part in the discussion of this issue.


问:
How do I make a dynamic list of pages in a folder?
I'm still somewhat new to web development, so I'm sorry if this is a stupid question. I have a site that has several hundred pages that I want to be alphabetically sorted automatically when a user goes to another page. For example, I would want the list to be shown on root/example/index.html displaying all pages named "index.html" in root/example/things/thingsubfolder or root/example/things/ , whichever is easiest to do. I'm not sure if this is a JS question or a PHP question or a SQL question or a XML question or something else, as I'm not all that familiar with any of those, except for JS.

I don't really care if this would have to use a table or an actual list or anything else, I just don't want to be stuck doing this by hand.

I haven't actually tried to run anything, as I don't really know where I should start after a few days of searching Google to no avail.


问:
pdftotext achieve tabular output with php shell_exec()
I'm trying to use pdftotext to extract purchase order data from emailed pdfs. Using the below I have successfully extracted non tabular text but it would be much more useful as a table. I have tried using the -table additional option but wherever I put it I then get a blank output instead. Where should I put it within shell_exec command to make it work?

So this works, to get non tabular output;

```<code>$file_in = "/var/www/vhosts/path.pdf";
$content = shell_exec("/var/www/vhosts/bin/pdftotext ".$file_in." -");
echo $content;
</code>```

However, this gives blank output where I was hoping for tabular:

```<code>$file_in = "/var/www/vhosts/path.pdf";
$content = shell_exec("-table /var/www/vhosts/bin/pdftotext ".$file_in." -");
echo $content;
</code>```

Edit, a little further clarification Original format looks like this in the pdf

```<code>Code Quantity
A123 1
B123 23
A987 16
</code>```

The non tabular text results come out like this:

```<code>Code Quantity

A123
B123
A987

1
23
16
</code>```

Body:
I'm trying to use pdftotext to extract purchase order data from emailed pdfs. Using the below I have successfully extracted non tabular text but it would be much more useful as a table. I have tried using the -table additional option but wherever I put it I then get a blank output instead. Where should I put it within shell_exec command to make it work?

So this works, to get non tabular output;

$file_in = "/var/www/vhosts/path.pdf";
$content = shell_exec("/var/www/vhosts/bin/pdftotext ".$file_in." -");
echo $content;

However, this gives blank output where I was hoping for tabular:

$file_in = "/var/www/vhosts/path.pdf";
$content = shell_exec("-table /var/www/vhosts/bin/pdftotext ".$file_in." -");
echo $content;

Edit, a little further clarification Original format looks like this in the pdf

Code Quantity
A123 1
B123 23
A987 16

The non tabular text results come out like this:

Code Quantity

A123
B123
A987

1
23
16


问:
Woocommerce - How to order my account download by custom field
I've added a custom column to my download page. As shown here.

```<code>// Callback For Account Downloads Last Updated
add_action( 'woocommerce_account_downloads_column_download-updated', function( $data ) {
    $current_post_id    = $data['product_id'];
    $product_changelog  = get_post_meta( $current_post_id, 'product_changelog', true );
    if ( $product_changelog )
    {
        foreach($product_changelog as $key => $value){

            $timestamp = strtotime( $value['log_items']['1']['log_date'] );
            $new_date = date( 'F j, Y', $timestamp );
        }
        echo $timestamp;
    }
} );
</code>```

I am able to see this column on the download page just fine. But I would love to change the order of downloads to show the last updated product first. I know I have to hook
woocommerce_customer_get_downloadable_products but seem the downloads array does not include the custom column data that I added.

Is there any way of achieving this?Thanks.

Body:
I've added a custom column to my download page. As shown here.

// Callback For Account Downloads Last Updated
add_action( 'woocommerce_account_downloads_column_download-updated', function( $data ) {
    $current_post_id    = $data['product_id'];
    $product_changelog  = get_post_meta( $current_post_id, 'product_changelog', true );
    if ( $product_changelog )
    {
        foreach($product_changelog as $key => $value){

            $timestamp = strtotime( $value['log_items']['1']['log_date'] );
            $new_date = date( 'F j, Y', $timestamp );
        }
        echo $timestamp;
    }
} );

I am able to see this column on the download page just fine. But I would love to change the order of downloads to show the last updated product first. I know I have to hook
woocommerce_customer_get_downloadable_products but seem the downloads array does not include the custom column data that I added.

Is there any way of achieving this?Thanks.


问:
Return an Array from SQL Query Result
I don't think it matters, but I'm using PostgresSQL and have this query:

SELECT
  f.superhero_id,
    COUNT(*) AS superhero_follow_count
FROM
  follows AS f
WHERE
  f.active = TRUE
GROUP BY
  superhero_id
ORDER BY
  superhero_id ASC
```

<p>Which gives me results in PostgreSQL like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>superhero_id</th>
<th>superhero_follow_count</th>
</tr>
</thead>
<tbody>
<tr>
<td>298</td>
<td>1</td>
</tr>
<tr>
<td>301</td>
<td>1</td>
</tr>
<tr>
<td>302</td>
<td>1</td>
</tr>
<tr>
<td>490</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>And with the results, I want to return an object like this:</p>
```const heroFollows = {
  298: 1
  301: 1
  302: 1
  490: 2
}
```
<p>I know how to code it if I do a loop, but I think there's a more efficient way to do it, that I just don't know how to code, yet. This method:</p>
```user.heroAllUsersFollowedIds = allUsersHeroFollowsRes.rows.map(
        (c) => c.superhero_id
    );
```

... just returns an array of the superhero_id values, without the counts. Is it possible to build an object like I've described above in just a line or two of code from the query results?

Title: Return an Array from SQL Query Result

Body:
I don't think it matters, but I'm using PostgresSQL and have this query:

SELECT
  f.superhero_id,
    COUNT(*) AS superhero_follow_count
FROM
  follows AS f
WHERE
  f.active = TRUE
GROUP BY
  superhero_id
ORDER BY
  superhero_id ASC

Which gives me results in PostgreSQL like this:

superhero_id
superhero_follow_count

298
1

301
1

302
1

490
2

And with the results, I want to return an object like this:

const heroFollows = {
  298: 1
  301: 1
  302: 1
  490: 2
}

I know how to code it if I do a loop, but I think there's a more efficient way to do it, that I just don't know how to code, yet. This method:

user.heroAllUsersFollowedIds = allUsersHeroFollowsRes.rows.map(
        (c) => c.superhero_id
    );

... just returns an array of the superhero_id values, without the counts. Is it possible to build an object like I've described above in just a line or two of code from the query results?


问:
Kotlin equivalent of scala.io.Source.fromFile()
Is there Kotlin equivalent of scala.io.Source.fromFile()? I want to read a file located in a folder outside the module folder but still under the root project. I used to use Source.fromFile("<path-to-the-file-from-root-project>") in Scala.


问:
How to format date with knex when developing for multiple databases
I want to be able to format the date in the select query to a particular format.
I know that this can be done with .raw as shown in this mssql snippet:

```<code>await knex.raw(
    `SELECT DATE_FORMAT(my_table.date, "%Y-%m-%d") as date FROM my_table...`)
</code>```

I, however, want to be able to do this in a db-agnostic way, so that the db provider could easily be switched between postgres/mssql/sqlite.

After some googling, I found a snippet where a type/constructor can be passed to select, but this is still unable to format the date to my desired format:

```<code> await knex('my_table')
    .select<{ date: Date }[]>('date');
</code>```

Is it possible to apply a function to a column during select in knex or otherwise apply the date format (for example, 'YY-mm-dd') in a db-agnostic way?

Body:
I want to be able to format the date in the select query to a particular format.
I know that this can be done with .raw as shown in this mssql snippet:

await knex.raw(
    `SELECT DATE_FORMAT(my_table.date, "%Y-%m-%d") as date FROM my_table...`)

I, however, want to be able to do this in a db-agnostic way, so that the db provider could easily be switched between postgres/mssql/sqlite.

After some googling, I found a snippet where a type/constructor can be passed to select, but this is still unable to format the date to my desired format:

 await knex('my_table')
    .select<{ date: Date }[]>('date');

Is it possible to apply a function to a column during select in knex or otherwise apply the date format (for example, 'YY-mm-dd') in a db-agnostic way?


问:
Connect life time of C++ objects to Java object
I have a C++ library with objects and am using this in conjunction with Java over JNI. Ideally, I'd like to tie the life cycle of the C++ objects to their Java equivalents and make it controllable from Java. Important to note is that the application is multi-threaded, so the C++ objects are accessed from multiple threads, and that those objects aren't modified after their initial construction. My current implementation looks something like this:

```<code>struct Tree {
  int age = 0;
  std::string type;
}

typedef Tree* TreeHandle;

/*
 * Class:     com_example_Tree
 * Method:    initialize
 * Signature: ([Lcom/example/Tree;)I
 */
JNIEXPORT jlong JNICALL Java_com_example_Tree_initialize
        (JNIEnv * env, jclass cls, jobject j_tree) {
    auto tree_ptr = new Tree();
    return (jlong) tree_ptr;
}

/*
 * Class:     com_example_Tree
 * Method:    dispose
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_example_Tree_dispose
        (JNIEnv * env, jclass cls, jlong j_tree_handle) {
    auto tree_ptr = reinterpret_cast<TreeHandle*>(j_tree_handle);
    delete tree_ptr;
}
</code>```

My Java part then looks like this:

```<code>class Tree implements AutoClosable {
    static {
        System.load("/path/to/tree.so");
    }

    private long handle;

    public Tree() {
        this.handle = initialize();
    }

    @Override
    protected void finalize() {
        if (this.handle != 0) {
            this.close();
        }
    }

    @override
    public synchronized void close() {
        dispose(this.handle);
        this.handle = 0;
    }

    private static native long initialize();
    private static native void dispose();
}
</code>```

However, the result is that I have some global objects floating around in memory that are only accessible via a C-style pointer. Is there a more modern way of achieving the same, i.e., using smart pointers or directly designing the C++ objects as members of the Java class?

Body:
I have a C++ library with objects and am using this in conjunction with Java over JNI. Ideally, I'd like to tie the life cycle of the C++ objects to their Java equivalents and make it controllable from Java. Important to note is that the application is multi-threaded, so the C++ objects are accessed from multiple threads, and that those objects aren't modified after their initial construction. My current implementation looks something like this:

struct Tree {
  int age = 0;
  std::string type;
}

typedef Tree* TreeHandle;

/*
 * Class:     com_example_Tree
 * Method:    initialize
 * Signature: ([Lcom/example/Tree;)I
 */
JNIEXPORT jlong JNICALL Java_com_example_Tree_initialize
        (JNIEnv * env, jclass cls, jobject j_tree) {
    auto tree_ptr = new Tree();
    return (jlong) tree_ptr;
}

/*
 * Class:     com_example_Tree
 * Method:    dispose
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_example_Tree_dispose
        (JNIEnv * env, jclass cls, jlong j_tree_handle) {
    auto tree_ptr = reinterpret_cast<TreeHandle*>(j_tree_handle);
    delete tree_ptr;
}

My Java part then looks like this:

class Tree implements AutoClosable {
    static {
        System.load("/path/to/tree.so");
    }

    private long handle;

    public Tree() {
        this.handle = initialize();
    }

    @Override
    protected void finalize() {
        if (this.handle != 0) {
            this.close();
        }
    }

    @override
    public synchronized void close() {
        dispose(this.handle);
        this.handle = 0;
    }

    private static native long initialize();
    private static native void dispose();
}

However, the result is that I have some global objects floating around in memory that are only accessible via a C-style pointer. Is there a more modern way of achieving the same, i.e., using smart pointers or directly designing the C++ objects as members of the Java class?


问:
questions about llvm plugin:expression expand,
expression expand

does llvm have some interface to solve the expression expand problem?
for example:

b = a + 1

c = b + 1

d = b * c

after expression expand, we can know that:

c = a + 1 + 1

d = (a + 1 + 1) * (a + 1)

i think Reverse Polish notation is useful for this, but i didn't find related description in llvm.

Any help would be appreciated~


问:
How can I change the port for Webmin access?
I'm managing a Rails website that relies on MySQL tables. I used to be able to access the tables with Webmin by going to xxx.xxx.xxx.xxx:10000 . At some point, I lost the ability to access it this way.

I'm not great with SSH, but I was able to SSH into my website as a general user. Then, I switched to Root user. Then, I ran this command to restart my Webmin:

```<code>svcadm restart webmin
</code>```

It seemed to accept the command, but I'm not really sure how to check. Anyway, I started getting a new error message when I tried to access Webmin through my browser:

```<code>ERR_SSL_VERSION_OR_CIPHER_MISMATCH
</code>```

The website uses a connection with Cloudflare. My guess was that this could be the problem since Cloudflare doesn’t support port 10000. I tried deactivating Cloudflare, but it didn't resolve the problem.

Still, I figured I might need to use SSH to change the port for Webmin access just in case. I found a source that suggested how to do it, and it starts with SSH. I went in through SSH and I switched to Root user. Then, I ran this command:

```<code>/etc/webmin/miniserv.conf
</code>```

And it tells me

```<code>bash /etc/webmin/miniserv.conf Permission denied
</code>```

How can I get past this step? Am I headed the wrong direction to get access back to Webmin? Thank you!

Body:
I'm managing a Rails website that relies on MySQL tables. I used to be able to access the tables with Webmin by going to xxx.xxx.xxx.xxx:10000 . At some point, I lost the ability to access it this way.

I'm not great with SSH, but I was able to SSH into my website as a general user. Then, I switched to Root user. Then, I ran this command to restart my Webmin:

svcadm restart webmin

It seemed to accept the command, but I'm not really sure how to check. Anyway, I started getting a new error message when I tried to access Webmin through my browser:

ERR_SSL_VERSION_OR_CIPHER_MISMATCH

The website uses a connection with Cloudflare. My guess was that this could be the problem since Cloudflare doesn’t support port 10000. I tried deactivating Cloudflare, but it didn't resolve the problem.

Still, I figured I might need to use SSH to change the port for Webmin access just in case. I found a source that suggested how to do it, and it starts with SSH. I went in through SSH and I switched to Root user. Then, I ran this command:

/etc/webmin/miniserv.conf

And it tells me

bash /etc/webmin/miniserv.conf Permission denied

How can I get past this step? Am I headed the wrong direction to get access back to Webmin? Thank you!


问:
How to resolve django filter button not working?
I am trying to implement Django Filtering but I cant seem to make it work. Only an 'Option' button appears the 'filter' button does not. It still does not work. What seems to be the problem here?

views.py

```<code>class MKRealtyListView(generics.ListAPIView):
    queryset = Realty.objects.all()
    serializer_class = RealtySerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('type', 'location')

    #@permission_classes([IsAuthenticated])
    @api_view(['GET', 'POST'])
    def listings(request, format=None):
        if request.method == 'GET':
            realty = Realty.objects.all()
            serializer = RealtySerializer(realty, many=True)
            return Response(serializer.data)
</code>```

settings.py

```<code>INSTALLED_APPS = [
    'rest_framework',
    'mkrealty',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework.authtoken',
    'django_filters'
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend',]
}
</code>```

urls.py

```<code>
urlpatterns = [
    path('admin/', admin.site.urls),
    path('listings/', views.MKRealtyListView.listings),
    path('listings/<int:id>', views.listing_detail),
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),  # <-- And here
]
</code>```

Body:
I am trying to implement Django Filtering but I cant seem to make it work. Only an 'Option' button appears the 'filter' button does not. It still does not work. What seems to be the problem here?

views.py

class MKRealtyListView(generics.ListAPIView):
    queryset = Realty.objects.all()
    serializer_class = RealtySerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('type', 'location')

    #@permission_classes([IsAuthenticated])
    @api_view(['GET', 'POST'])
    def listings(request, format=None):
        if request.method == 'GET':
            realty = Realty.objects.all()
            serializer = RealtySerializer(realty, many=True)
            return Response(serializer.data)

settings.py

INSTALLED_APPS = [
    'rest_framework',
    'mkrealty',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework.authtoken',
    'django_filters'
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend',]
}

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('listings/', views.MKRealtyListView.listings),
    path('listings/<int:id>', views.listing_detail),
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),  # <-- And here
]


问:
the connection was reset but the script is running
I have a problem when the process from PHP to SQL server to run the trigger appears like this. Even if viewed from within the database the query is running. Can anyone help me find the answer?

I hope there is an answer that can help my problem


问:
Flutter transak API
I'm try to transak application using flutter.

But I don't know much about the structure of the flutter, so I can't use the http communication provided by transak

I want to use the code using this OKHTTP as an http library supported by the flutter

```<code>OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"apiKey\":\"YOUR_API_KEY\"}");
Request request = new Request.Builder()
  .url("https://api-stg.transak.com/partners/api/v2/refresh-token")
  .post(body)
  .addHeader("accept", "application/json")
  .addHeader("api-secret", "YOUR_API_SECRET")
  .addHeader("content-type", "application/json")
  .build();

Response response = client.newCall(request).execute();
</code>```

I tried to use the 'Future' method, but I couldn't find a method like 'MediaType' or 'RequestBody'

Title: Flutter transak API

Body:
I'm try to transak application using flutter.

But I don't know much about the structure of the flutter, so I can't use the http communication provided by transak

I want to use the code using this OKHTTP as an http library supported by the flutter

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"apiKey\":\"YOUR_API_KEY\"}");
Request request = new Request.Builder()
  .url("https://api-stg.transak.com/partners/api/v2/refresh-token")
  .post(body)
  .addHeader("accept", "application/json")
  .addHeader("api-secret", "YOUR_API_SECRET")
  .addHeader("content-type", "application/json")
  .build();

Response response = client.newCall(request).execute();

I tried to use the 'Future' method, but I couldn't find a method like 'MediaType' or 'RequestBody'


问:
Rotate or shift a neon vector by a byte?
I want to do the below but avoid the double load

```<code>isSlash  = vld1q_u8(ptr)   == '\\'
isSlash2 = vld1q_u8(ptr+1) == '\\'
backToBackSlash = isSlash & isSlash2
</code>```

My first instinct was to use a shift but I didn't see a way to shift all 128bits? Next instinct was to use a tbl shuffle but that uses a register which I'll have to do a memory load which means I should just use what I did above instead? Is there another efficient way I may have overlooked? Yes I am processing text and trying to do a backslash escape

Body:
I want to do the below but avoid the double load

isSlash  = vld1q_u8(ptr)   == '\\'
isSlash2 = vld1q_u8(ptr+1) == '\\'
backToBackSlash = isSlash & isSlash2

My first instinct was to use a shift but I didn't see a way to shift all 128bits? Next instinct was to use a tbl shuffle but that uses a register which I'll have to do a memory load which means I should just use what I did above instead? Is there another efficient way I may have overlooked? Yes I am processing text and trying to do a backslash escape


问:
Macro to search in Excel Part number column A from different groups different values and add not found value at end
I have values in PART Number field(Example-Column A 1-50), i have values in different groups, Ex-Engine A - 48 to 52, Engine B- 40 to 60, When macro run, user need to select Engine A or B or C etc. If Engine A selected 48 to 52 to be searched in Column A one by one and add not found value at end. Please help in macro

I dont know VBA, Please help me in creating Macro


问:
How to animate an image so it appears to move between specific coordinates?
I'm trying to take an image and have it appear to move from a given starting coordinate (more or less the display's upper right corner, coded as (DISPLAY_WIDTH, 0-image_height)) to a given ending coordinate (let's say (250,200)).

I can animate images in the game loop, drawing ("blitting"?) them at different coordinates every event loop, until they get particular x or y coordinates (and stop moving) with code like

```<code>if image_y < 200:
    image_x -= some_distance
    image_y += some_other_distance
</code>```

or

```<code>if image_x < 250:
    image_x -= some_distance
    image_y += some_other_distance
</code>```

but I can't direct the image to stop at a particular coordinate pair. I can play with values for some_distance and some_other_distance, but that's just trial and error.

Ultimately, my goal is to have images of playing cards appear to move from a deck to particular spots on a "table."

Body:
I'm trying to take an image and have it appear to move from a given starting coordinate (more or less the display's upper right corner, coded as (DISPLAY_WIDTH, 0-image_height)) to a given ending coordinate (let's say (250,200)).

I can animate images in the game loop, drawing ("blitting"?) them at different coordinates every event loop, until they get particular x or y coordinates (and stop moving) with code like

if image_y < 200:
    image_x -= some_distance
    image_y += some_other_distance

or

if image_x < 250:
    image_x -= some_distance
    image_y += some_other_distance

but I can't direct the image to stop at a particular coordinate pair. I can play with values for some_distance and some_other_distance, but that's just trial and error.

Ultimately, my goal is to have images of playing cards appear to move from a deck to particular spots on a "table."


问:
jq insert new key in json and parameterized value
I am trying to insert new key/value in json using jq.
I am able to successfully insert the key but my value comes from a variable but I am not able to set it properly.

Here is my Code:

```<code>SHORT_NAME=`jq -r '.properties.cluster_name' filepath` //Output is "abc-test-00"
//Insert new key into json
jq '.properties += { "short_name": "$SHORT_NAME" }' filepath
    // It inserts short_name under properties but it shows "short_name" = "SHORT_NAME" instead of actual value
    ("abc-test-00")
</code>```

JSON:

```<code>{
  "properties":
  {
     "cluster_name": "abc-test-00",
     "short_name": "$SHORT_NAME"
  }
}
</code>```

What I am missing ?

Body:
I am trying to insert new key/value in json using jq.
I am able to successfully insert the key but my value comes from a variable but I am not able to set it properly.

Here is my Code:

SHORT_NAME=`jq -r '.properties.cluster_name' filepath` //Output is "abc-test-00"
//Insert new key into json
jq '.properties += { "short_name": "$SHORT_NAME" }' filepath
    // It inserts short_name under properties but it shows "short_name" = "SHORT_NAME" instead of actual value
    ("abc-test-00")

JSON:

{
  "properties":
  {
     "cluster_name": "abc-test-00",
     "short_name": "$SHORT_NAME"
  }
}

What I am missing ?


问:
need help fixing a _csv.Error iterable expected, not nonetype. error in my data collection loop
i have a data collection loop that gathers information from a sensor and writes it to a csv, ive had previous issues with the writing component and am at my wits end as im new to coding. the error is in the

```<code>csv_writer.writerow(combined_rows)
</code>```

line and i for the life of me cant think of a way to solve this issue
the exact error code it produces is as follows

```<code>Traceback (most recent call last):
File "c:\\Users", line 24, in \<module\>
csv_writer.writerow(combined_rows)
\_csv.Error: iterable expected, not NoneType
</code>```

the full code is as shown below

```<code>    import csv
    import os
    import time
    from gdx import gdx
    gdx = gdx.gdx()
    gdx.open(connection='usb')
    gdx.select_sensors()
    os.chdir(r"C:\Users")
    column_headers = ["DO Concentration (mg/L)","DO Saturation (%)","Temperature (C)","Pressure      (kPa)","DO Salinity (mg/L)"]
    with open('sensor_data.csv', 'a', newline='') as my_data_file:
        csv_writer = csv.writer(my_data_file)
        while True:
            gdx.start(period=100)
            column_headers = gdx.enabled_sensor_info()
            column_headers.insert(0, "Timestamp")
            csv_writer.writerow(column_headers)

            for i in range(0,100000):
                measurements = gdx.read()
                localtime = time.localtime()
                result = time.strftime("%I:%M:%S %p", localtime)
                print(result)
                combined_rows = measurements.insert(0, result)
                csv_writer.writerow(combined_rows)
                print(combined_rows)
                my_data_file.flush()
                time.sleep(59.9)
</code>```

the error writes the column headers to the csv file then encounters the error and outputs the error code shown above,
any help is greatly appreciated.

Body:
i have a data collection loop that gathers information from a sensor and writes it to a csv, ive had previous issues with the writing component and am at my wits end as im new to coding. the error is in the

csv_writer.writerow(combined_rows)

line and i for the life of me cant think of a way to solve this issue
the exact error code it produces is as follows

Traceback (most recent call last):
File "c:\\Users", line 24, in \<module\>
csv_writer.writerow(combined_rows)
\_csv.Error: iterable expected, not NoneType

the full code is as shown below

    import csv
    import os
    import time
    from gdx import gdx
    gdx = gdx.gdx()
    gdx.open(connection='usb')
    gdx.select_sensors()
    os.chdir(r"C:\Users")
    column_headers = ["DO Concentration (mg/L)","DO Saturation (%)","Temperature (C)","Pressure      (kPa)","DO Salinity (mg/L)"]
    with open('sensor_data.csv', 'a', newline='') as my_data_file:
        csv_writer = csv.writer(my_data_file)
        while True:
            gdx.start(period=100)
            column_headers = gdx.enabled_sensor_info()
            column_headers.insert(0, "Timestamp")
            csv_writer.writerow(column_headers)

            for i in range(0,100000):
                measurements = gdx.read()
                localtime = time.localtime()
                result = time.strftime("%I:%M:%S %p", localtime)
                print(result)
                combined_rows = measurements.insert(0, result)
                csv_writer.writerow(combined_rows)
                print(combined_rows)
                my_data_file.flush()
                time.sleep(59.9)

the error writes the column headers to the csv file then encounters the error and outputs the error code shown above,
any help is greatly appreciated.


问:
Unable to run kafka producer for twitter data
I am trying to run kafka to stream twitter data using some specific keywords. In my case I used "Dollar8". But I am getting error as shown below.  I am using macOS.

```<code>import tweepy
from kafka import KafkaProducer
import logging
from tweepy import OAuthHandler
from tweepy import Stream

consumer_key = "XXXXXXX"
consumer_secret = "XXXXX"
access_token = "00000-XXXXXX"
access_token_secret = "XXXXXX"
# Accessing Kafka  server at localhost:9092
producer = KafkaProducer(bootstrap_servers='localhost:9092')
# our cluster name is "top"
topic_name = "top"
class twitterauth():
# Setting up twitter
    def authenticateTwitterApp(self):
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        return auth
class twitterstream():
# Streaming data
    def __init__(self):
        self.twitterAuth = twitterauth()
    def stream_tweets(self):
        while True:
            listener_data = ListenerTS('consumer_key', 'consumer_secret', 'access_token','access_token_secret')
            auth = self.twitterAuth.authenticateTwitterApp()
            #stream = Stream(auth, listener)
            listener_data.filter(track=["dollar8"], stall_warnings=True, languages= ["en"])
class ListenerTS(tweepy.Stream):
    def on_data(self, raw_data):
            producer.send(topic_name, str.encode(raw_data))
            return True
if __name__ == "__main__":
    TS = twitterstream()
    TS.stream_tweets()
</code>```

After trying multiple solutions like upgrading/ downgrading tweepy, rewriting code with different approch I keep on getting same error is

```<code>Traceback (most recent call last):
  File "/Users/dishant/Documents/603_data/manisha/projectfiles/producer_a.py", line 96, in <module>
    TS.stream_tweets()
  File "/Users/dishant/Documents/603_data/manisha/projectfiles/producer_a.py", line 86, in stream_tweets
    listener_data = ListenerTS('consumer_key', 'consumer_secret', 'access_token','access_token_secret')
TypeError: Stream.__init__() takes 3 positional arguments but 5 were given
</code>```

Body:
I am trying to run kafka to stream twitter data using some specific keywords. In my case I used "Dollar8". But I am getting error as shown below.  I am using macOS.

import tweepy
from kafka import KafkaProducer
import logging
from tweepy import OAuthHandler
from tweepy import Stream

consumer_key = "XXXXXXX"
consumer_secret = "XXXXX"
access_token = "00000-XXXXXX"
access_token_secret = "XXXXXX"
# Accessing Kafka  server at localhost:9092
producer = KafkaProducer(bootstrap_servers='localhost:9092')
# our cluster name is "top"
topic_name = "top"
class twitterauth():
# Setting up twitter
    def authenticateTwitterApp(self):
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        return auth
class twitterstream():
# Streaming data
    def __init__(self):
        self.twitterAuth = twitterauth()
    def stream_tweets(self):
        while True:
            listener_data = ListenerTS('consumer_key', 'consumer_secret', 'access_token','access_token_secret')
            auth = self.twitterAuth.authenticateTwitterApp()
            #stream = Stream(auth, listener)
            listener_data.filter(track=["dollar8"], stall_warnings=True, languages= ["en"])
class ListenerTS(tweepy.Stream):
    def on_data(self, raw_data):
            producer.send(topic_name, str.encode(raw_data))
            return True
if __name__ == "__main__":
    TS = twitterstream()
    TS.stream_tweets()

After trying multiple solutions like upgrading/ downgrading tweepy, rewriting code with different approch I keep on getting same error is

Traceback (most recent call last):
  File "/Users/dishant/Documents/603_data/manisha/projectfiles/producer_a.py", line 96, in <module>
    TS.stream_tweets()
  File "/Users/dishant/Documents/603_data/manisha/projectfiles/producer_a.py", line 86, in stream_tweets
    listener_data = ListenerTS('consumer_key', 'consumer_secret', 'access_token','access_token_secret')
TypeError: Stream.__init__() takes 3 positional arguments but 5 were given


问:
How can I read live-updating data (excel or database) in Python?
I need to visualize the live-updating data in the diagrams. The data is updating every 5 seconds, and I don't know how to import it at this frequency,

I usually use pandas, but I don't think it is able to read online data. As the data is big, it takes time to import all the data each time.

Thanks in advance.


问:
Can i execute an APK file without writing it on FileSystem?
Is there another way beyond that?

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(apk)), "application/vnd.android.package-archive");
</code>```

I'm looking for something like:

```<code>byte[] apkByteArray = downloadApk();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkByteArray, "application/vnd.android.package-archive");
</code>```

My point is to avoid:

Creation/Deletion code

Handle internal/external storage issues

Force uses-permission

Handle File System checked exceptions

ContentLicense: CC BY-SA 3.0

Body:
Is there another way beyond that?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(apk)), "application/vnd.android.package-archive");

I'm looking for something like:

byte[] apkByteArray = downloadApk();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkByteArray, "application/vnd.android.package-archive");

My point is to avoid:

Creation/Deletion code

Handle internal/external storage issues

Force uses-permission

Handle File System checked exceptions