问:
Read all Parquet files saved in a folder via Spark
I have a folder containing Parquet files. Something like this:

```<code>scala> val df = sc.parallelize(List(1,2,3,4)).toDF()
df: org.apache.spark.sql.DataFrame = [value: int]

scala> df.write.parquet("/tmp/test/df/1.parquet")

scala> val df = sc.parallelize(List(5,6,7,8)).toDF()
df: org.apache.spark.sql.DataFrame = [value: int]

scala> df.write.parquet("/tmp/test/df/2.parquet")
</code>```

After saving dataframes when I go to read all parquet files in df folder, it gives me error.

```<code>scala> val read = spark.read.parquet("/tmp/test/df")
org.apache.spark.sql.AnalysisException: Unable to infer schema for Parquet. It must be specified manually.;
  at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:189)
  at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:189)
  at scala.Option.getOrElse(Option.scala:121)
  at org.apache.spark.sql.execution.datasources.DataSource.org$apache$spark$sql$execution$datasources$DataSource$$getOrInferFileFormatSchema(DataSource.scala:188)
  at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:387)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:441)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:425)
  ... 48 elided
</code>```

I know I can read Parquet files by giving full path, but it would be better if there is a way to read all parquet files in a folder.

答:
You can write data into folder not as separate Spark "files" (in fact folders) 1.parquet, 2.parquet etc.
If don't set file name but only path, Spark will put files into the folder as real files (not folders), and automatically name that files.

```<code>df1.write.partitionBy("countryCode").format("parquet").mode("overwrite").save("/tmp/data1/")
df2.write.partitionBy("countryCode").format("parquet").mode("append").save("/tmp/data1/")
df3.write.partitionBy("countryCode").format("parquet").mode("append").save("/tmp/data1/")
</code>```

Further we can read data from all files in data folder:

```<code>val df = spark.read.format("parquet").load("/tmp/data1/")
</code>```

Body:
I have a folder containing Parquet files. Something like this:

scala> val df = sc.parallelize(List(1,2,3,4)).toDF()
df: org.apache.spark.sql.DataFrame = [value: int]

scala> df.write.parquet("/tmp/test/df/1.parquet")

scala> val df = sc.parallelize(List(5,6,7,8)).toDF()
df: org.apache.spark.sql.DataFrame = [value: int]

scala> df.write.parquet("/tmp/test/df/2.parquet")

After saving dataframes when I go to read all parquet files in df folder, it gives me error.

scala> val read = spark.read.parquet("/tmp/test/df")
org.apache.spark.sql.AnalysisException: Unable to infer schema for Parquet. It must be specified manually.;
  at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:189)
  at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:189)
  at scala.Option.getOrElse(Option.scala:121)
  at org.apache.spark.sql.execution.datasources.DataSource.org$apache$spark$sql$execution$datasources$DataSource$$getOrInferFileFormatSchema(DataSource.scala:188)
  at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:387)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:441)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:425)
  ... 48 elided

I know I can read Parquet files by giving full path, but it would be better if there is a way to read all parquet files in a folder.

Body:
You can write data into folder not as separate Spark "files" (in fact folders) 1.parquet, 2.parquet etc.
If don't set file name but only path, Spark will put files into the folder as real files (not folders), and automatically name that files.

df1.write.partitionBy("countryCode").format("parquet").mode("overwrite").save("/tmp/data1/")
df2.write.partitionBy("countryCode").format("parquet").mode("append").save("/tmp/data1/")
df3.write.partitionBy("countryCode").format("parquet").mode("append").save("/tmp/data1/")

Further we can read data from all files in data folder:

val df = spark.read.format("parquet").load("/tmp/data1/")


来源: stackexchange

问:
Find encryption algorithm from a file
If I have a file claimed to be "encrypted using AES algorighm", can I verify that their claim is true?</p>

答: Good encryption schemes are actually designed to hide away all the details of encryption from the encrypted data so if they used a proper application to do the encryption, you should not be able to verify the algorithm used.</p>

ContentLicense: CC BY-SA 3.0

Title: Find encryption algorithm from a file


问:
python mockito argument captor
I have been using python mockito https://code.google.com/p/mockito-python/ for testing my code.

So far python mockito seems to provide only 2 matchers: contains() and any() https://code.google.com/p/mockito-python/wiki/Matchers

I am wondering how can I write some code so that I can capture the entire argument.

So for example if my code is

```<code>deleteSqlStatement = "DELETE from %s WHERE lower(z_id)=lower('%s') and y_id=%s" \
                         % (self.SOME_TABLE, zId, yId)
cursor.execute(deleteSqlStatement)
</code>```

Currently, all I can do in verification is

```<code>verify(self.cursor_mock, times=1).execute(contains("DELETE"))
</code>```

It would be great if I can capture the entire argument passed to execute as a String.

Suggestions?

答:
I also had the issue of trying to verify complex arguments. Mockito is currently missing a convinient way of fetching the call args from the mock like unittest.mock do with call_args.

I ended up using (IMHO) the second best thing which is mockito.matchers.arg_that(predicate) where one can verify arguments by a custom method.

https://mockito-python.readthedocs.io/en/latest/the-matchers.html#mockito.matchers.arg_that

So in your example we can rewrite the verify step as:

```<code>verify(self.cursor_mock, times=1).execute(arg_that(lambda sql: verify_sql(sql))
</code>```

And then the custom verify method that can verify whatever you like:

```<code>def verify_sql(the_sql):
    if the_sql.startswith('SELECT'):
        return True
    else:
        return False
</code>```

Another example (can't get enough Mockito examples)

In my case I had to verify that proper input, including a timestamp, were sent to a mocked boto3 client:

```<code>verify(boto3_client_mock).put_object_tagging(Bucket="foo-bucket",
                                         Key="foo-prefix",
                                         Tagging=[{'Key':'tag1', 'Value': 'value1'},
                                                  {'Key': 'timestamp', 'Value': '1581670796'}])
</code>```

The thing that made it tricky were the timestamp, so regular matching didn't fly.

But it became rather straightforward using arg_that:

```<code>verify(boto3_client_mock).put_object_tagging(Bucket=ANY,
                                             Key=ANY,
                                             Tagging=arg_that(lambda tag_list: verify_tagset(tag_list)))

def verify_tagset(tagset):
    for tag in tagset['TagSet']:
        # Some verification in here
        if yadda:
            return True
    return False
</code>```

Title: python mockito argument captor

Body:
I have been using python mockito https://code.google.com/p/mockito-python/ for testing my code.

So far python mockito seems to provide only 2 matchers: contains() and any() https://code.google.com/p/mockito-python/wiki/Matchers

I am wondering how can I write some code so that I can capture the entire argument.

So for example if my code is

deleteSqlStatement = "DELETE from %s WHERE lower(z_id)=lower('%s') and y_id=%s" \
                         % (self.SOME_TABLE, zId, yId)
cursor.execute(deleteSqlStatement)

Currently, all I can do in verification is

verify(self.cursor_mock, times=1).execute(contains("DELETE"))

It would be great if I can capture the entire argument passed to execute as a String.

Suggestions?

Body:
I also had the issue of trying to verify complex arguments. Mockito is currently missing a convinient way of fetching the call args from the mock like unittest.mock do with call_args.

I ended up using (IMHO) the second best thing which is mockito.matchers.arg_that(predicate) where one can verify arguments by a custom method.

https://mockito-python.readthedocs.io/en/latest/the-matchers.html#mockito.matchers.arg_that

So in your example we can rewrite the verify step as:

verify(self.cursor_mock, times=1).execute(arg_that(lambda sql: verify_sql(sql))

And then the custom verify method that can verify whatever you like:

def verify_sql(the_sql):
    if the_sql.startswith('SELECT'):
        return True
    else:
        return False

Another example (can't get enough Mockito examples)

In my case I had to verify that proper input, including a timestamp, were sent to a mocked boto3 client:

verify(boto3_client_mock).put_object_tagging(Bucket="foo-bucket",
                                         Key="foo-prefix",
                                         Tagging=[{'Key':'tag1', 'Value': 'value1'},
                                                  {'Key': 'timestamp', 'Value': '1581670796'}])

The thing that made it tricky were the timestamp, so regular matching didn't fly.

But it became rather straightforward using arg_that:

verify(boto3_client_mock).put_object_tagging(Bucket=ANY,
                                             Key=ANY,
                                             Tagging=arg_that(lambda tag_list: verify_tagset(tag_list)))

def verify_tagset(tagset):
    for tag in tagset['TagSet']:
        # Some verification in here
        if yadda:
            return True
    return False

ContentLicense: CC BY-SA 4.0


问:
How to import local json file data to my JavaScript variable?
I have data inside employees.json how can I get this data and assign it to the variable inside main.js?</p>

答:
You can simply require that file.

```<code>const data = require("./data.json");
</code>```

Here's a working example for you: https://codesandbox.io/s/festive-rgb-75z4o/ in React. Lmk if you have any doubts.

Body:
You can simply require that file.

const data = require("./data.json");

Here's a working example for you: https://codesandbox.io/s/festive-rgb-75z4o/ in React. Lmk if you have any doubts.


问:
iOS 13, Custom Image, title and subtitle in the presented UIActivityViewController
I would like to know if there is any way to customise the image, title and subtitle of presented UIActivityViewController in iOS 13?

答:
I have found a solution using UIActivityItemSource

UIActivityItemSource have this protocol activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata?which we can use to set image title and subtitle for our UIActivityViewController

This is an example:

```<code> public func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
    let metadata = LPLinkMetadata()

    metadata.title = "My title" // Preview Title

    // Set image

        metadata.imageProvider = NSItemProvider(object: image)
        metadata.iconProvider = NSItemProvider(object: image)
        metadata.url = urlImage

   // Set URL for sharing
        metadata.originalURL = myUrl // Add this if you want to have a url in your share message.

    return metadata
}
</code>```

And this is the result: I have my custom image and title.

Body:
I have found a solution using UIActivityItemSource

UIActivityItemSource have this protocol activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata?which we can use to set image title and subtitle for our UIActivityViewController

This is an example:

 public func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
    let metadata = LPLinkMetadata()

    metadata.title = "My title" // Preview Title

    // Set image

        metadata.imageProvider = NSItemProvider(object: image)
        metadata.iconProvider = NSItemProvider(object: image)
        metadata.url = urlImage

   // Set URL for sharing
        metadata.originalURL = myUrl // Add this if you want to have a url in your share message.

    return metadata
}

And this is the result: I have my custom image and title.


问:
How to mount same volume on to all pods in a kubernetes namespace
We have a namespace in kubernetes where I would like some secrets (files like jks,properties,ts,etc.) to be made available to all the containers in all the pods (we have one JVM per container & one container per pod kind of Deployment).

I have created secrets using kustomization and plan to use it as a volume for spec of each Deployment & then volumeMount it for the container of this Deployment. I would like to have this volume to be mounted on each of the containers deployed in our namespace.

I want to know if kustomize (or anything else) can help me to mount this volume on all the deployments in this namespace?

I have tried the following patchesStrategicMerge

```<code>---
apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: myNamespace
spec:
  template:
    spec:
      imagePullSecrets:
        - name: pull-secret
      containers:
        - volumeMounts:
          - name: secret-files
            mountPath: "/secrets"
            readOnly: true
      volumes:
      - name: secret-files
        secret:
          secretName: mySecrets
          items:
          - key: key1
            path: ...somePath
          - key: key2
            path: ...somePath
</code>```

It requires name in metadata section which does not help me as all my Deployments have different names.

答:
PodPresent (https://kubernetes.io/docs/tasks/inject-data-application/podpreset/) is one way to do this but for this all pods in your namespace should match the label you specify in PodPresent spec.

Another way (which is most popular) is to use Dynamic Admission Control (https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/) and write a Mutating webhook in your cluster which will edit your pod spec and add all the secrets you want to mount. Using this you can also make other changes in your pod spec like mounting volumes, adding label and many more.

Body:
We have a namespace in kubernetes where I would like some secrets (files like jks,properties,ts,etc.) to be made available to all the containers in all the pods (we have one JVM per container & one container per pod kind of Deployment).

I have created secrets using kustomization and plan to use it as a volume for spec of each Deployment & then volumeMount it for the container of this Deployment. I would like to have this volume to be mounted on each of the containers deployed in our namespace.

I want to know if kustomize (or anything else) can help me to mount this volume on all the deployments in this namespace?

I have tried the following patchesStrategicMerge

---
apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: myNamespace
spec:
  template:
    spec:
      imagePullSecrets:
        - name: pull-secret
      containers:
        - volumeMounts:
          - name: secret-files
            mountPath: "/secrets"
            readOnly: true
      volumes:
      - name: secret-files
        secret:
          secretName: mySecrets
          items:
          - key: key1
            path: ...somePath
          - key: key2
            path: ...somePath

It requires name in metadata section which does not help me as all my Deployments have different names.


问:
push view after 2 seconds in swiftui
how to push a view after x seconds in swiftUI without any interaction?</p>

```<code> NavigationView{
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
                    NavigationLink(destination: pageViewUi()) {
                        EmptyView()
                    }
                }
            }
}
</code>```

答:
You can handle it it this way :

struct ContentView: View {
    @State var show = false
    var body: some View {
        NavigationView{
            NavigationLink(destination: Text("OK"), isActive: $show, label: {
                EmptyView()
            })
                .onAppear {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                        self.show.toggle()
                    }
            }
        }
    }
}

```

Title: push view after 2 seconds in swiftui

Body:
how to push a view after x seconds in swiftUI without any interaction?

 NavigationView{
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
                    NavigationLink(destination: pageViewUi()) {
                        EmptyView()
                    }
                }
            }
}


问:
C#: Filter things like `-beta1` and ` hotfix` from a string version number
I'm processing some old version strings which are usually in the form 1.2.3, but sometimes they have stuff tagged on the end such as -beta1 or hotfix (space at start of that).

I want to filter to just the version number, eg. 1.2.3, with only digits (0-9) and periods (.) remaining, so that I can pass it to Version.TryParse() with a high chance that it will parse.

I've looked at several examples online, but they all seem to focus on numbers like 12.34 and don't work when there are additional period-number parts like 12.34.56.

Performance is not critical, maintainability is. Which would be the most appropriate approach?

答:
You can try matching with a help of regular expressions:

```<code>using System.Text.RegularExpressions;

...

string source = "some text with 1.2.34.4893-beta1 version" ;

if (Version.TryParse(Regex.Match(source, @"[0-9]+(?:\.[0-9]+)+").Value, out var version)) {
  // version  extracted
}
else {
  // source doesn't have a match
}
</code>```

Body:
You can try matching with a help of regular expressions:

using System.Text.RegularExpressions;

...

string source = "some text with 1.2.34.4893-beta1 version" ;

if (Version.TryParse(Regex.Match(source, @"[0-9]+(?:\.[0-9]+)+").Value, out var version)) {
  // version  extracted
}
else {
  // source doesn't have a match
}


问:
Ionic Android build error after updating cordova-plugin-x-socialsharing plugin
I have an Ionic 3 application, where I just updated the cordova-plugin-x-socialsharing plugin.

Ionic info:

```<code>    $ ionic info

    Ionic:

       ionic (Ionic CLI)  : 4.5.0 (C:\Users\peter\AppData\Roaming\npm\node_modules\ionic)
       Ionic Framework    : ionic-angular 3.6.1
       @ionic/app-scripts : 3.2.2

    Cordova:

       cordova (Cordova CLI) : 7.0.1
       Cordova Platforms     : android 6.2.3, ios 4.3.1, windows 5.0.0
       Cordova Plugins       : no whitelisted plugins (16 plugins total)

    System:

       Android SDK Tools : 26.1.1 (C:\Users\peter\AppData\Local\Android\sdk)
       NodeJS            : v10.15.0 (C:\Program Files\nodejs\node.exe)
       npm               : 6.4.1
       OS                : Windows 10
</code>```

I now get the following build error:

```<code>    * Where:
    Build file 'D:\dev\myapp\platforms\android\build.gradle' line: 252

    * What went wrong:
    A problem occurred evaluating root project 'android'.
    > Could not get unknown property 'ANDROID_SUPPORT_V4_VERSION' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
</code>```

At the line in build.grade, I have the following:

Also, in my package.json, I notice I now have the following:

```<code>"cordova-plugin-x-socialsharing": {
            "ANDROID_SUPPORT_V4_VERSION": "24.1.1+"
        },
</code>```

I have got my port to Ionic 4 planned, where I will probably re-add all my platforms but until then, how can I fix this problem?

答:
The suggestion here is to downgrade to the version 5.4.0. As of writing this, the current version of the plugin is 5.6.3 though. So it's not really a fix for me, it's a temporary workaround. But I tried it, and it seems to work.

5.4.0 is the last version that has the version hardcoded in plugin.xml:

<framework src="com.android.support:support-v4:24.1.1+" />
```

<p>Later versions use a variable, which doesn't seem to get resolved when Cordova creates the build.gradle file for Android:</p>

<pre class="lang-xml prettyprint-override"><code><framework src="com.android.support:support-v4:$ANDROID_SUPPORT_V4_VERSION" />
<preference name="ANDROID_SUPPORT_V4_VERSION" default="24.1.1+"/>
</code>```

see diff: 5.4.0...5.4.4

Body:
I have an Ionic 3 application, where I just updated the cordova-plugin-x-socialsharing plugin.

Ionic info:

    $ ionic info

    Ionic:

       ionic (Ionic CLI)  : 4.5.0 (C:\Users\peter\AppData\Roaming\npm\node_modules\ionic)
       Ionic Framework    : ionic-angular 3.6.1
       @ionic/app-scripts : 3.2.2

    Cordova:

       cordova (Cordova CLI) : 7.0.1
       Cordova Platforms     : android 6.2.3, ios 4.3.1, windows 5.0.0
       Cordova Plugins       : no whitelisted plugins (16 plugins total)

    System:

       Android SDK Tools : 26.1.1 (C:\Users\peter\AppData\Local\Android\sdk)
       NodeJS            : v10.15.0 (C:\Program Files\nodejs\node.exe)
       npm               : 6.4.1
       OS                : Windows 10

I now get the following build error:

    * Where:
    Build file 'D:\dev\myapp\platforms\android\build.gradle' line: 252

    * What went wrong:
    A problem occurred evaluating root project 'android'.
    > Could not get unknown property 'ANDROID_SUPPORT_V4_VERSION' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

At the line in build.grade, I have the following:

Also, in my package.json, I notice I now have the following:

"cordova-plugin-x-socialsharing": {
            "ANDROID_SUPPORT_V4_VERSION": "24.1.1+"
        },

I have got my port to Ionic 4 planned, where I will probably re-add all my platforms but until then, how can I fix this problem?

Body:
The suggestion here is to downgrade to the version 5.4.0. As of writing this, the current version of the plugin is 5.6.3 though. So it's not really a fix for me, it's a temporary workaround. But I tried it, and it seems to work.

5.4.0 is the last version that has the version hardcoded in plugin.xml:

<framework src="com.android.support:support-v4:24.1.1+" />

Later versions use a variable, which doesn't seem to get resolved when Cordova creates the build.gradle file for Android:

<framework src="com.android.support:support-v4:$ANDROID_SUPPORT_V4_VERSION" />
<preference name="ANDROID_SUPPORT_V4_VERSION" default="24.1.1+"/>

see diff: 5.4.0...5.4.4


问:
How can you change how a matplotlib figure/axes is stretched when resizing the parent window in PyQt5?
I have a program with an emedded figure that also shows a colorbar with custom tick labels. However, the automatic resizing of the figure cuts off part of the tick labels. This wouldn't be too bad if I could simply manually resize the window a bit so that everything is shown again. But, when you resize the window, the figure stretches in such a way that there is a large empty space created on the left side while the tick labels on the right can still not be completely seen unless you stretch the window unnecessarily wide. How can I change this behaviour?
Below is an example. As you can see I already tried a few things but none of them worked.</p>

```<code>import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas
import matplotlib.ticker as mticker

from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout
from PyQt5.QtCore import QSize

class MathTextSciFormatter(mticker.Formatter):
    def __init__(self, fmt="%1.1e"):
        self.fmt = fmt

    def __call__(self, x, pos=None):
        s = self.fmt % x
        decimal_point = '.'
        positive_sign = '+'
        tup = s.split('e')
        significand = tup[0].rstrip(decimal_point)
        sign = tup[1][0].replace(positive_sign, '')
        exponent = tup[1][1:].lstrip('0')
        if exponent:
            exponent = '10^{%s%s}' % (sign, exponent)
        if significand and exponent:
            s = r'%s{\times}%s' % (significand, exponent)
        else:
            s = r'%s%s' % (significand, exponent)
        return "${}$ W/m${{}}^2$".format(s)

class Test(QDialog):
    def __init__(self):
        super().__init__()
        self.lay = QGridLayout(self)
        self.fig, self.ax = plt.subplots()
        # self.ax.set_anchor('SW')
        # self.ax.set_position([0, 0, 0, 0])
        # self.fig.tight_layout()
        # self.ax.margins(0, 0)
        self.canvas = FigureCanvas(self.fig)
        self.lay.addWidget(self.canvas)
        self.resize(QSize(380, 290))
        self.setMaximumHeight(290)
        self.image = np.reshape(np.random.randint(0, 1000, 10000), (100, 100))
        self.image_artist = self.ax.imshow(self.image)
        self.colorbar = self.fig.colorbar(self.image_artist)
        self.colorbar.ax.yaxis.set_major_formatter(
            MathTextSciFormatter()
        )

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = Test()
    test.show()
    sys.exit(app.exec_())
</code>```

答:
As pointed out by ImportanceOfBeingErnest in a comment, making use of constrained_layout does the trick.

```<code>import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas
import matplotlib.ticker as mticker

from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout
from PyQt5.QtCore import QSize

class MathTextSciFormatter(mticker.Formatter):
    def __init__(self, fmt="%1.1e"):
        self.fmt = fmt

    def __call__(self, x, pos=None):
        s = self.fmt % x
        decimal_point = '.'
        positive_sign = '+'
        tup = s.split('e')
        significand = tup[0].rstrip(decimal_point)
        sign = tup[1][0].replace(positive_sign, '')
        exponent = tup[1][1:].lstrip('0')
        if exponent:
            exponent = '10^{%s%s}' % (sign, exponent)
        if significand and exponent:
            s = r'%s{\times}%s' % (significand, exponent)
        else:
            s = r'%s%s' % (significand, exponent)
        return "${}$ W/m${{}}^2$".format(s)

class Test(QDialog):
    def __init__(self):
        super().__init__()
        self.lay = QGridLayout(self)
        self.fig, self.ax = plt.subplots(constrained_layout=True)
        # self.ax.set_anchor('SW')
        # self.ax.set_position([0, 0, 0, 0])
        # self.fig.tight_layout()
        # self.ax.margins(0, 0)
        self.canvas = FigureCanvas(self.fig)
        self.lay.addWidget(self.canvas)
        self.resize(QSize(380, 290))
        self.setMaximumHeight(290)
        self.image = np.reshape(np.random.randint(0, 1000, 10000), (100, 100))
        self.image_artist = self.ax.imshow(self.image)
        self.colorbar = self.fig.colorbar(self.image_artist)
        self.colorbar.ax.yaxis.set_major_formatter(
            MathTextSciFormatter()
        )

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = Test()
    test.show()
    sys.exit(app.exec_())
</code>```

Body:
I have a program with an emedded figure that also shows a colorbar with custom tick labels. However, the automatic resizing of the figure cuts off part of the tick labels. This wouldn't be too bad if I could simply manually resize the window a bit so that everything is shown again. But, when you resize the window, the figure stretches in such a way that there is a large empty space created on the left side while the tick labels on the right can still not be completely seen unless you stretch the window unnecessarily wide. How can I change this behaviour?
Below is an example. As you can see I already tried a few things but none of them worked.

import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas
import matplotlib.ticker as mticker

from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout
from PyQt5.QtCore import QSize

class MathTextSciFormatter(mticker.Formatter):
    def __init__(self, fmt="%1.1e"):
        self.fmt = fmt

    def __call__(self, x, pos=None):
        s = self.fmt % x
        decimal_point = '.'
        positive_sign = '+'
        tup = s.split('e')
        significand = tup[0].rstrip(decimal_point)
        sign = tup[1][0].replace(positive_sign, '')
        exponent = tup[1][1:].lstrip('0')
        if exponent:
            exponent = '10^{%s%s}' % (sign, exponent)
        if significand and exponent:
            s = r'%s{\times}%s' % (significand, exponent)
        else:
            s = r'%s%s' % (significand, exponent)
        return "${}$ W/m${{}}^2$".format(s)

class Test(QDialog):
    def __init__(self):
        super().__init__()
        self.lay = QGridLayout(self)
        self.fig, self.ax = plt.subplots()
        # self.ax.set_anchor('SW')
        # self.ax.set_position([0, 0, 0, 0])
        # self.fig.tight_layout()
        # self.ax.margins(0, 0)
        self.canvas = FigureCanvas(self.fig)
        self.lay.addWidget(self.canvas)
        self.resize(QSize(380, 290))
        self.setMaximumHeight(290)
        self.image = np.reshape(np.random.randint(0, 1000, 10000), (100, 100))
        self.image_artist = self.ax.imshow(self.image)
        self.colorbar = self.fig.colorbar(self.image_artist)
        self.colorbar.ax.yaxis.set_major_formatter(
            MathTextSciFormatter()
        )

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = Test()
    test.show()
    sys.exit(app.exec_())

Body:
As pointed out by ImportanceOfBeingErnest in a comment, making use of constrained_layout does the trick.

import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas
import matplotlib.ticker as mticker

from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout
from PyQt5.QtCore import QSize

class MathTextSciFormatter(mticker.Formatter):
    def __init__(self, fmt="%1.1e"):
        self.fmt = fmt

    def __call__(self, x, pos=None):
        s = self.fmt % x
        decimal_point = '.'
        positive_sign = '+'
        tup = s.split('e')
        significand = tup[0].rstrip(decimal_point)
        sign = tup[1][0].replace(positive_sign, '')
        exponent = tup[1][1:].lstrip('0')
        if exponent:
            exponent = '10^{%s%s}' % (sign, exponent)
        if significand and exponent:
            s = r'%s{\times}%s' % (significand, exponent)
        else:
            s = r'%s%s' % (significand, exponent)
        return "${}$ W/m${{}}^2$".format(s)

class Test(QDialog):
    def __init__(self):
        super().__init__()
        self.lay = QGridLayout(self)
        self.fig, self.ax = plt.subplots(constrained_layout=True)
        # self.ax.set_anchor('SW')
        # self.ax.set_position([0, 0, 0, 0])
        # self.fig.tight_layout()
        # self.ax.margins(0, 0)
        self.canvas = FigureCanvas(self.fig)
        self.lay.addWidget(self.canvas)
        self.resize(QSize(380, 290))
        self.setMaximumHeight(290)
        self.image = np.reshape(np.random.randint(0, 1000, 10000), (100, 100))
        self.image_artist = self.ax.imshow(self.image)
        self.colorbar = self.fig.colorbar(self.image_artist)
        self.colorbar.ax.yaxis.set_major_formatter(
            MathTextSciFormatter()
        )

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = Test()
    test.show()
    sys.exit(app.exec_())


问:
Several types with OR with one generic position method
I have two types of data: String and extend from SpecificRecordBase and the several methods  with the same business logic to process this data, except using java methods from another library which I cant change.

```<code>  def createResultStreamSpecificRecordBase[T <: SpecificRecordBase](topic: String, source: DataStream[KafkaSourceType])(
      implicit tag: ClassTag[T]): DataStream[T] = {
      // contain calling java method with T <: SpecificRecordBase
      serialize(source, topic)
      // the same logic
  }

  def createResultStreamString(topic: String, source: DataStream[KafkaSourceType]): DataStream[String] = {
      // dont contain calling java method with T <: SpecificRecordBase
      // the same logic
  }

  def processSpecificRecordBase[T <: SpecificRecordBase](...)(implicit tag: ClassTag[T]): Unit = {
      val stream = createStreamSpecificRecordBase(topic, source)
      // the other the same process actions
  }

  def processString(...): Unit = {
      val stream = createResultStreamString(topic, source)
      // the other the same process actions
  }
</code>```

I want to remove the duplicated code in process methods and write single. Could you write please how to do it? Is it possible to use something like OR in generic types?

```<code>  def process[T <: SpecificRecordBase ?OR? String](...)(implicit tag: ClassTag[T]): Unit = {
      val stream = createStream(topic, source)

      this match {
          case SpecificRecordBaseRunner() => createStreamSpecificRecordBase(topic, source)
          case StringRunner()             => createStreamString(topic, source)
      }
      // the other process actions
  }
</code>```

答:
Unfortunately right now there is no OR type operator as you described. The good news that, Union Types feature is a part of upcoming Dotty:
https://dotty.epfl.ch/docs/reference/new-types/union-types.html

Right now such problems solved usually with next approaches:

Sum types

You can declare sealed trait which will box all possible instances.
Please, see next code example for more details:

```<code>// This is your base of sum type
sealed trait TopicResult

//Declared instances which you need to handle
case class RecordResult[T <: SpecificRecordBase](tag: ClassTag[T]) extends TopicResult
case object StringResult extends TopicResult

//Helper methods goes here for convenience
object TopicResult {
    def record[T <: SpecificRecordBase](implicit tag: ClassTag[T]): TopicResult = RecordResult(tag)
    def string: TopicResult = StringResult
  }

def process(result: TopicResult /*other arguments*/): Unit = {
  // This pattern matching should be safe, because you know all instances in advance.
  result match {
    case RecordResult(tag) => createStreamSpecificRecordBase(topic, source)
    case StringResult => createStreamString(topic, source)
  }
  /// other operations
}
</code>```

Ad-hoc polymorphous

Also known as Type Class pattern. You can extract behavior based on it's type. This is quite popular approach, you may see in libraries like cats, circe etc.
Please, see code example below for more details:

```<code>// Type dependent logic interface
trait CreateTopic[T] {
 def createTopic(topic: String, source: String): String // put desired result type here
}

object CreateTopic {
  implicit def recordCreateTopic[T <: SpecificRecordBase](implicit tag: ClassTag[T]): CreateTopic[T] = {
    (topic: String, source: String) => ??? // create topic for record base
  }

  implicit val stringCreateTopic: CreateTopic[String] = {
    (topic: String, source: String) => ??? // create topic for record base
  }
}

import CreateTopic._
// implementation will be substituted by compiler based on it's type, from implicit context
def process[T](/*other arguments*/)(implicit create: CreateTopic[T]): Unit = {
  create.createTopic(topic, source)
  /// other operations
}
</code>```

Excuse me, I'm not an Kafka expert, so please correct me if you will find some parts, which does not make sens from Kafka point of view.

Hope this helps!

Body:
I have two types of data: String and extend from SpecificRecordBase and the several methods  with the same business logic to process this data, except using java methods from another library which I cant change.

  def createResultStreamSpecificRecordBase[T <: SpecificRecordBase](topic: String, source: DataStream[KafkaSourceType])(
      implicit tag: ClassTag[T]): DataStream[T] = {
      // contain calling java method with T <: SpecificRecordBase
      serialize(source, topic)
      // the same logic
  }

  def createResultStreamString(topic: String, source: DataStream[KafkaSourceType]): DataStream[String] = {
      // dont contain calling java method with T <: SpecificRecordBase
      // the same logic
  }

  def processSpecificRecordBase[T <: SpecificRecordBase](...)(implicit tag: ClassTag[T]): Unit = {
      val stream = createStreamSpecificRecordBase(topic, source)
      // the other the same process actions
  }

  def processString(...): Unit = {
      val stream = createResultStreamString(topic, source)
      // the other the same process actions
  }

I want to remove the duplicated code in process methods and write single. Could you write please how to do it? Is it possible to use something like OR in generic types?

  def process[T <: SpecificRecordBase ?OR? String](...)(implicit tag: ClassTag[T]): Unit = {
      val stream = createStream(topic, source)

      this match {
          case SpecificRecordBaseRunner() => createStreamSpecificRecordBase(topic, source)
          case StringRunner()             => createStreamString(topic, source)
      }
      // the other process actions
  }

Body:
Unfortunately right now there is no OR type operator as you described. The good news that, Union Types feature is a part of upcoming Dotty:
https://dotty.epfl.ch/docs/reference/new-types/union-types.html

Right now such problems solved usually with next approaches:

Sum types

You can declare sealed trait which will box all possible instances.
Please, see next code example for more details:

// This is your base of sum type
sealed trait TopicResult

//Declared instances which you need to handle
case class RecordResult[T <: SpecificRecordBase](tag: ClassTag[T]) extends TopicResult
case object StringResult extends TopicResult

//Helper methods goes here for convenience
object TopicResult {
    def record[T <: SpecificRecordBase](implicit tag: ClassTag[T]): TopicResult = RecordResult(tag)
    def string: TopicResult = StringResult
  }

def process(result: TopicResult /*other arguments*/): Unit = {
  // This pattern matching should be safe, because you know all instances in advance.
  result match {
    case RecordResult(tag) => createStreamSpecificRecordBase(topic, source)
    case StringResult => createStreamString(topic, source)
  }
  /// other operations
}

Ad-hoc polymorphous

Also known as Type Class pattern. You can extract behavior based on it's type. This is quite popular approach, you may see in libraries like cats, circe etc.
Please, see code example below for more details:

// Type dependent logic interface
trait CreateTopic[T] {
 def createTopic(topic: String, source: String): String // put desired result type here
}

object CreateTopic {
  implicit def recordCreateTopic[T <: SpecificRecordBase](implicit tag: ClassTag[T]): CreateTopic[T] = {
    (topic: String, source: String) => ??? // create topic for record base
  }

  implicit val stringCreateTopic: CreateTopic[String] = {
    (topic: String, source: String) => ??? // create topic for record base
  }
}

import CreateTopic._
// implementation will be substituted by compiler based on it's type, from implicit context
def process[T](/*other arguments*/)(implicit create: CreateTopic[T]): Unit = {
  create.createTopic(topic, source)
  /// other operations
}

Excuse me, I'm not an Kafka expert, so please correct me if you will find some parts, which does not make sens from Kafka point of view.

Hope this helps!


问:
Change table columns order using drag drop Angular 8
I am creating an application with:
Angular CLI: 8.3.23
Node: 10.15.0
typescript: 3.5.3 and I need to make the table columns re-order able using drag drop. Something like this https://sindu12jun.github.io/table-dragger but I have tried multiple things like it but nothing is working.
I tried to use some jquery plugins as well but that doesn't work either. I used this https://akottr.github.io/dragtable/ jQuery plugin but no luck.
This can be done using <mat-table> but due to some other requirements I don't want to use material table.

If anyone have any idea, please let me know. Thanks

答:
I was able to do it finally, check the link:
Angular material table column dragger</p>


问:
How to execute psycopg query inside for loop python 3
**psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block
** error occured after excution</p>

```<code>import pandas as pd
conn = ...
cur = conn.cursor()
fb_csv_file = "File_path"
table = pd.read_csv(fb_csv_file, encoding = 'latin1')
try:
    for index,row in table.iterrows():
        sql =  'DELETE FROM public."tbl_Name"  WHERE "col_1" =\'' +str(row['col_1']) + '\' \
                    AND "col_2"=\'' + str(row['col_2'])+'\';'
        cur.execute(sql)
        conn.commit()
except Exception as e :
    print("Error  : ",e)
</code>```

答:
This may be useful.

This is what Postgres does when a query produces an error and you try to run another query without first rolling back the transaction. (You might think of it as a safety feature, to keep you from corrupting your data.)

Source: https://stackoverflow.com/a/2979389/8074624

Body:
**psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block
** error occured after excution

import pandas as pd
conn = ...
cur = conn.cursor()
fb_csv_file = "File_path"
table = pd.read_csv(fb_csv_file, encoding = 'latin1')
try:
    for index,row in table.iterrows():
        sql =  'DELETE FROM public."tbl_Name"  WHERE "col_1" =\'' +str(row['col_1']) + '\' \
                    AND "col_2"=\'' + str(row['col_2'])+'\';'
        cur.execute(sql)
        conn.commit()
except Exception as e :
    print("Error  : ",e)


问:
How can I pass more than one enum to a method that receives only one?
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

```<code>RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline
</code>```

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

答:
If it is a Flags enum you need to to a bitwise OR:

```<code>var combine = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhiteSpace | RegexOptions.Multiline;
myFunction(combine);
</code>```

If this is not such an enum, you are out of luck.

Body:
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

Body:
If it is a Flags enum you need to to a bitwise OR:

var combine = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhiteSpace | RegexOptions.Multiline;
myFunction(combine);

If this is not such an enum, you are out of luck.


答:
Use the below code to import json data in main js file. So your main.js file looks like:

```<code>const employees = require('./employees.json');
</code>```

Now you can use employees variable that contains json data.

Title: How to import local json file data to my JavaScript variable?

Body: I have data inside employees.json how can I get this data and assign it to the variable inside main.js?

Body:
Use the below code to import json data in main js file. So your main.js file looks like:

const employees = require('./employees.json');

Now you can use employees variable that contains json data.


问:
Is there a way to avoid code duplication in multiple similar functions?
I am writing a family of functions which are to be embedded in a small micro-controller operating at very near real time, so every clock cycle counts.  The functions are almost identical.

The only way that I can see to do this without duplicating vast chunks of code is to use the really ugly and frowned upon method of declaring the code in an include file which is then intentionally included multiple times.

The following works to demonstrate the concept:

```<code>// func.inc

// The absence of an include guard is intentional, as each time this file gets included
// the output will be different

void FUNC(int x)
{
    /* SNIP - lots and lots of code that is duplicated between
       variant A and B (and more) of the function
    for ( ... 4096 )
    {
        for( lots more nested loops)
        {
    */
    // IMPORTANT - I do not want to call functions here as it is
    // in a tight loop withconsecutive memory accesses of
    // different sizes of strided sparse arrays
#ifdef A
    printf("A %d\n", x);
#endif
#ifdef B
    printf("B %d\n", x);
#endif
    /*
        }
    }
    */
</code>```

```<code>// main.c

#include <stdio.h>

#define FUNC func_A
#define A
#include "func.inc"
#undef A
#undef FUNC

#define FUNC func_B
#define B
#include "func.inc"
#undef B
#undef FUNC

#define FUNC func_AB
#define A
#define B
#include "func.inc"

int main()
{
    func_A(10);
    func_B(20);
    func_AB(30);

    printf("Done\n");

    return 0;
}

</code>```

My problem is that whilst this works, it looks hideous, and might be very confusing to someone else trying to understand it.  Using a pointer to a function is too inefficient to be a viable option in this case.

Is there a solution that anyone can suggest without simply duplicating several slightly different versions of the same function?

答:
It's not really clear what's pseudo code and real code here, but overall you should not use #define + #undef + #include for the purpose of different code generation. (You could do it with "X macros" though as a last resort. Not an ideal solution but better than this.)

The solution to " IMPORTANT - I do not want to call functions here" is to call functions.

Function inlining has been a thing for some 30 years and 20 years ago C got explicit language support for it. And nowadays compilers are much better than programmers to determine what to inline. I'll make an example with explicit inline just to demonstrate that calling functions does not affect performance, if done correctly.

With traditional C, you would do something like this:

```<code>#include <stdio.h>

static inline void SNIP (void)
{
  puts(__func__);
}

static inline void A_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

static inline void B_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

typedef enum { A=1, B=2 } AB_t;

void func(AB_t ab, int val)
{
  SNIP();

  if(ab & A)
    A_stuff(val);
  if(ab & B)
    B_stuff(val);
}

int main()
{
  func(A, 10);
  func(B, 20);
  func(A|B, 30);

  printf("Done\n");
  return 0;
}
</code>```

That's the sane solution. The only functions that are actually called in the generated machine code are func and the printing functions.

Alternatively, you could have done code generation with "X macros" too - these exist solely for the purpose of avoiding code repetition, at the expense of readability. Wouldn't really recommend it here, but I'll include an example for completeness:

```<code>#include <stdio.h>

#define FUNC_LIST \
  X(A,  10)       \
  X(B,  20)       \
  X(AB, 30)       \

static inline void SNIP (void)
{
  puts(__func__);
}

static inline void A_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

static inline void B_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

static inline void AB_stuff (int val)
{
  A_stuff(val);
  B_stuff(val);
}

#define X(opt, val) void func_##opt (int x) { SNIP(); opt##_stuff(x); }
  FUNC_LIST
#undef X

int main()
{
  #define X(opt, val) func_##opt(val),
    FUNC_LIST
  #undef X

  printf("Done\n");
  return 0;
}
</code>```

This is quite unreadable just like the original code, except "X macros" are something of a de facto standard for icky macro tricks to avoid code repetition.

This creates multiple functions just like a C++ template, so it isn't ideal for that reason as well.

Body:
I am writing a family of functions which are to be embedded in a small micro-controller operating at very near real time, so every clock cycle counts.  The functions are almost identical.

The only way that I can see to do this without duplicating vast chunks of code is to use the really ugly and frowned upon method of declaring the code in an include file which is then intentionally included multiple times.

The following works to demonstrate the concept:

// func.inc

// The absence of an include guard is intentional, as each time this file gets included
// the output will be different

void FUNC(int x)
{
    /* SNIP - lots and lots of code that is duplicated between
       variant A and B (and more) of the function
    for ( ... 4096 )
    {
        for( lots more nested loops)
        {
    */
    // IMPORTANT - I do not want to call functions here as it is
    // in a tight loop withconsecutive memory accesses of
    // different sizes of strided sparse arrays
#ifdef A
    printf("A %d\n", x);
#endif
#ifdef B
    printf("B %d\n", x);
#endif
    /*
        }
    }
    */

// main.c

#include <stdio.h>

#define FUNC func_A
#define A
#include "func.inc"
#undef A
#undef FUNC

#define FUNC func_B
#define B
#include "func.inc"
#undef B
#undef FUNC

#define FUNC func_AB
#define A
#define B
#include "func.inc"

int main()
{
    func_A(10);
    func_B(20);
    func_AB(30);

    printf("Done\n");

    return 0;
}

My problem is that whilst this works, it looks hideous, and might be very confusing to someone else trying to understand it.  Using a pointer to a function is too inefficient to be a viable option in this case.

Is there a solution that anyone can suggest without simply duplicating several slightly different versions of the same function?

Body:
It's not really clear what's pseudo code and real code here, but overall you should not use #define + #undef + #include for the purpose of different code generation. (You could do it with "X macros" though as a last resort. Not an ideal solution but better than this.)

The solution to " IMPORTANT - I do not want to call functions here" is to call functions.

Function inlining has been a thing for some 30 years and 20 years ago C got explicit language support for it. And nowadays compilers are much better than programmers to determine what to inline. I'll make an example with explicit inline just to demonstrate that calling functions does not affect performance, if done correctly.

With traditional C, you would do something like this:

#include <stdio.h>

static inline void SNIP (void)
{
  puts(__func__);
}

static inline void A_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

static inline void B_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

typedef enum { A=1, B=2 } AB_t;

void func(AB_t ab, int val)
{
  SNIP();

  if(ab & A)
    A_stuff(val);
  if(ab & B)
    B_stuff(val);
}

int main()
{
  func(A, 10);
  func(B, 20);
  func(A|B, 30);

  printf("Done\n");
  return 0;
}

That's the sane solution. The only functions that are actually called in the generated machine code are func and the printing functions.

Alternatively, you could have done code generation with "X macros" too - these exist solely for the purpose of avoiding code repetition, at the expense of readability. Wouldn't really recommend it here, but I'll include an example for completeness:

#include <stdio.h>

#define FUNC_LIST \
  X(A,  10)       \
  X(B,  20)       \
  X(AB, 30)       \

static inline void SNIP (void)
{
  puts(__func__);
}

static inline void A_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

static inline void B_stuff (int val)
{
  printf("%s %d\n", __func__, val);
}

static inline void AB_stuff (int val)
{
  A_stuff(val);
  B_stuff(val);
}

#define X(opt, val) void func_##opt (int x) { SNIP(); opt##_stuff(x); }
  FUNC_LIST
#undef X

int main()
{
  #define X(opt, val) func_##opt(val),
    FUNC_LIST
  #undef X

  printf("Done\n");
  return 0;
}

This is quite unreadable just like the original code, except "X macros" are something of a de facto standard for icky macro tricks to avoid code repetition.

This creates multiple functions just like a C++ template, so it isn't ideal for that reason as well.


问:
Split SQL Server Column value
I have a SQL Server table which name is AbundanceImpact.

```<code>Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95
</code>```

So I want the all integer values only with SUM.

答:
Try this below logic-

DEMO HERE

```<code>SELECT
SUM(
    CAST(
        RIGHT(
            Column_name,
            LEN(Column_name) - CHARINDEX('~',Column_name,0)
        )
        AS FLOAT
    )
)
FROM AbundanceImpact
</code>```

Title: Split SQL Server Column value

Body:
I have a SQL Server table which name is AbundanceImpact.

Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95

So I want the all integer values only with SUM.

Body:
Try this below logic-

DEMO HERE

SELECT
SUM(
    CAST(
        RIGHT(
            Column_name,
            LEN(Column_name) - CHARINDEX('~',Column_name,0)
        )
        AS FLOAT
    )
)
FROM AbundanceImpact


问:
Grails w/ Spring Security Core only allowing owner to update in GSP
This question has some code to add to the controller closure, which is fine, but what if I want to use the grails default scaffolding views but only have the edit/update buttons appear if the user is a manager, or the domain object is owned by the user? Reading the documentation, I've tried:

```<code><sec:access expression="hasRole('ROLE_MANAGER') || (projectInstance.owner == springSecurityService.currentUser)">
   <span class="button"><g:actionSubmit class="save" action="update" value="${message(code: 'default.button.update.label', default: 'Update')}" /></span>
</sec:access>
</code>```

But the access class doesn't seem to allow ORs:

```<code>Error processing GroovyPageView: Error executing tag <g:form>: Error executing tag <sec:access>: Cannot handle (124) '|'
</code>```

Anyone done something similar?

答:
I've decided that would be stupid. A better approach is to do it in the controller as:

```<code> def edit = {
    def projectInstance = Project.get(params.id)
    def managerOrAdmin = SpringSecurityUtils.ifAnyGranted('ROLE_ADMIN,ROLE_MANAGER')
    def editable = (projectInstance.owner == springSecurityService.currentUser
                   || managerOrAdmin)
    if (!projectInstance) {
        flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'project.label', default: 'Project'), params.id])}"
        redirect(action: "list")
    }
    else {
        return [projectInstance: projectInstance, editable:editable]
    }
}
</code>```

and then in the gsp do

```<code><g:if test="${editable}">
  <span class="button"><g:actionSubmit class="save" action="update" value="${message(code: 'default.button.update.label', default: 'Update')}" /></span>
</g:if>
</code>```

which makes sense, if we follow the good programming mantra of "views should do as little processing logic as possible in MVC"

Body:
This question has some code to add to the controller closure, which is fine, but what if I want to use the grails default scaffolding views but only have the edit/update buttons appear if the user is a manager, or the domain object is owned by the user? Reading the documentation, I've tried:

<sec:access expression="hasRole('ROLE_MANAGER') || (projectInstance.owner == springSecurityService.currentUser)">
   <g:actionSubmit class="save" action="update" value="${message(code: 'default.button.update.label', default: 'Update')}" />
</sec:access>

But the access class doesn't seem to allow ORs:

Error processing GroovyPageView: Error executing tag <g:form>: Error executing tag <sec:access>: Cannot handle (124) '|'

Anyone done something similar?

Body:
I've decided that would be stupid. A better approach is to do it in the controller as:

 def edit = {
    def projectInstance = Project.get(params.id)
    def managerOrAdmin = SpringSecurityUtils.ifAnyGranted('ROLE_ADMIN,ROLE_MANAGER')
    def editable = (projectInstance.owner == springSecurityService.currentUser
                   || managerOrAdmin)
    if (!projectInstance) {
        flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'project.label', default: 'Project'), params.id])}"
        redirect(action: "list")
    }
    else {
        return [projectInstance: projectInstance, editable:editable]
    }
}

and then in the gsp do

<g:if test="${editable}">
  <span class="button"><g:actionSubmit class="save" action="update" value="${message(code: 'default.button.update.label', default: 'Update')}" /></span>
</g:if>

which makes sense, if we follow the good programming mantra of "views should do as little processing logic as possible in MVC"


问:
ActionController::RoutingError (No route matches “/javascripts/defaults.js
Everything seems to be working fine, the profile get created and the
company address gets saved but I would like to make it so that this
error is not thrown. I imagine that this is a routing issue, but I
honestly am not certain of that. Anyone have any ideas about what is
happening and how to stop it from throwing these errors? Thanks,</p>

答: There is not much detail in your question but maybe this previous post can help you.</p>


问:
Break array of words in chunks based on the maximum number of character
I need to break the array of words into chunks based on maximum number of character:

const maxChar = 50
const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a','comfortable','home','and','happy','disposition,','seemed','to','unite','some','of','the','best','blessings','of','existence;','and','had','lived','nearly','twenty-one','years','in','the','world','with','very','little','to','distress','or','vex','her.']
```

<p>The desire result is to count the char of each word and break the array when the count of char reach maxChar.</p>

```const resultArr = [['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a'],['comfortable','home','and',..]....]
```

The problem is that I am using 2 for loops and want to know if there is a better way to reach the same result

答:
You can use the array.reduce function to loop over and create your new array.

I am assuming that if the new word would take the length over the limit it is just moved to the next array (not split partway through the word)

const maxChar = 50
const arrOfWords = ['Emma', 'Woodhouse,', 'handsome,', 'clever,', 'and', 'rich,', 'with', 'a', 'comfortable', 'home', 'and', 'happy', 'disposition,', 'seemed', 'to', 'unite', 'some', 'of', 'the', 'best', 'blessings', 'of', 'existence;', 'and', 'had', 'lived', 'nearly', 'twenty-one', 'years', 'in', 'the', 'world', 'with', 'very', 'little', 'to', 'distress', 'or', 'vex', 'her.']

let lengthSoFar = 0

const results = arrOfWords.reduce((accumulator, word) => {
  const lastAddedResult = accumulator.pop() || []

  if (lengthSoFar + word.length < maxChar) {
    lengthSoFar += word.length
    lastAddedResult.push(word)
    accumulator.push(lastAddedResult)
  } else {
    lengthSoFar = word.length
    accumulator.push(lastAddedResult)
    accumulator.push([word])
  }
  return accumulator
}, [])

console.log(...results)```

Body:
I need to break the array of words into chunks based on maximum number of character:

const maxChar = 50
const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a','comfortable','home','and','happy','disposition,','seemed','to','unite','some','of','the','best','blessings','of','existence;','and','had','lived','nearly','twenty-one','years','in','the','world','with','very','little','to','distress','or','vex','her.']

The desire result is to count the char of each word and break the array when the count of char reach maxChar.

const resultArr = [['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a'],['comfortable','home','and',..]....]

The problem is that I am using 2 for loops and want to know if there is a better way to reach the same result


问:
Android get R.raw from variable
i have some sounds in a raw folder on my app.
And sometimes i need to play a sound, but i don't know exactly which is.

Example :

```<code>String actualSound = "hit"

playSound(mediaPlayer, R.Raw.actualSound));
</code>```

I want to play the R.raw.hit but i don't know how to do that.

答:
Quick answer:</p>

```<code>public class WebsiteActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_website);

        Resources res = getResources();
        int sound = res.getIdentifier(music, "raw", getPackageName());

        //Play music
        mediaPlayer = MediaPlayer.create(getApplicationContext(), sound);
        mediaPlayer.start();
    }

    @Override
    protected void onPause() {
        super.onPause();

        mediaPlayer.stop();
        mediaPlayer.reset();
    }
}
</code>```

Title: Android get R.raw from variable

Body:
i have some sounds in a raw folder on my app.
And sometimes i need to play a sound, but i don't know exactly which is.

Example :

String actualSound = "hit"

playSound(mediaPlayer, R.Raw.actualSound));

I want to play the R.raw.hit but i don't know how to do that.

Body:
Quick answer:

public class WebsiteActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_website);

        Resources res = getResources();
        int sound = res.getIdentifier(music, "raw", getPackageName());

        //Play music
        mediaPlayer = MediaPlayer.create(getApplicationContext(), sound);
        mediaPlayer.start();
    }

    @Override
    protected void onPause() {
        super.onPause();

        mediaPlayer.stop();
        mediaPlayer.reset();
    }
}


问:
Lazy loading of beans referenced in apache camel route
There is a bean declared in a Spring boot configuration class with lazy annotation, which is referenced in camel route.
The lazy annotation stops the eager loading, but since it is reference in camel route its gets initialized.
Example ::
ChoiceDefinition org.apache.camel.model.ProcessorDefinition.bean(Object bean, String method)

Is there any way of lazy loading of beans referenced in the camel route ?

答:
No, because Camel needs to "build" and start the route, it also needs to initialize the Bean. You would have to lazy load the route.

You could try to disable autostart on the route and check if the bean is no more initialized when the route does not start.

If this is the case, you could use the Controlbus component to start your routes only when needed (and therefore initialize your beans only when needed).


问:
Combining parsers in Haskell
I'm given the following parsers

```<code>newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

instance Functor Parser where
   fmap f p = Parser $ \s -> (\(a,c) -> (f a, c)) <$> parse p s

instance Applicative Parser where
   pure a = Parser $ \s -> Just (a,s)
   f <*> a = Parser $ \s ->
     case parse f s of
       Just (g,s') -> parse (fmap g a) s'
       Nothing -> Nothing

instance Alternative Parser where
   empty = Parser $ \s -> Nothing
   l <|> r = Parser $ \s -> parse l s <|> parse r s

 ensure :: (a -> Bool) -> Parser a -> Parser a
 ensure p parser = Parser $ \s ->
    case parse parser s of
      Nothing -> Nothing
      Just (a,s') -> if p a then Just (a,s') else Nothing

 lookahead :: Parser (Maybe Char)
 lookahead = Parser f
   where f [] = Just (Nothing,[])
         f (c:s) = Just (Just c,c:s)

 satisfy :: (Char -> Bool) -> Parser Char
 satisfy p = Parser f
   where f [] = Nothing
         f (x:xs) = if p x then Just (x,xs) else Nothing

 eof :: Parser ()
 eof = Parser $ \s -> if null s then Just ((),[]) else Nothing

 eof' :: Parser ()
 eof' = ???
</code>```

I need to write a new parser eof' that does exactly what eof does but is built only using the given parsers and the
 Functor/Applicative/Alternative instances above. I'm stuck on this as I don't have experience in combining parsers. Can anyone help me out ?

答:
To understand it easier, we can write it in an equational pseudocode, while we substitute and simplify the definitions, using Monad Comprehensions for clarity and succinctness.

Monad Comprehensions are just like List Comprehensions, only working for any MonadPlus type, not just []; while corresponding closely to do notation, e.g. [ (f a, s') | (a, s') <- parse p s ]  ===  do { (a, s') <- parse p s ; return (f a, s') }.

This gets us:

```<code>newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

instance Functor Parser where
   parse (<b>fmap f p</b>)  s  =  [ (f a, s') | (a, s') <- parse p s ]

instance Applicative Parser where
   parse (<b>pure a</b>)    s  =  pure (a, s)
   parse (<b>pf <*> pa</b>) s  =  [ (g a, s'') | (g, s')  <- parse pf s
                                        , (a, s'') <- parse pa s' ]

instance Alternative Parser where
   parse <b>empty</b> s      =  empty
   parse (<b>l <|> r</b>) s  =  parse l s <|> parse r s

ensure :: (a -> Bool) -> Parser a -> Parser a
parse (<b>ensure pred p</b>) s  =  [ (a, s') | (a, s') <- parse p s, pred a ]

lookahead :: Parser (Maybe Char)
parse <b>lookahead</b> []       =  pure (Nothing, [])
parse <b>lookahead</b> s@(c:_)  =  pure (Just c,  s )

satisfy :: (Char -> Bool) -> Parser Char
parse (<b>satisfy p</b>) []      =  mzero
parse (<b>satisfy p</b>) (x:xs)  =  [ (x, xs) | p x ]

eof :: Parser ()
parse <b>eof</b> s  =  [ ((), []) | null s ]

eof' :: Parser ()
eof'  =  ???</code>```

By the way thanks to the use of Monad Comprehensions and the more abstract pure, empty and mzero instead of their concrete representations in terms of the Maybe type, this same (pseudo-)code will work with a different type, like [] in place of Maybe, viz. newtype Parser a = Parser { parse :: String -> [(a,String)] }.

So we have

```<code>ensure    :: (a -> Bool) -> Parser a           -> Parser a
lookahead ::                Parser (Maybe Char)
</code>```

(satisfy is no good for us here .... why?)

Using that, we can have

```<code>ensure  .......  ......                        :: Parser (Maybe Char)
</code>```

(... what does ensure id (pure False) do? ...)

but we'll have a useless Nothing result in case the input string was in fact empty, whereas the eof parser given to use produces the () as its result in such case (and otherwise it produces nothing).

No fear, we also have

```<code>fmap :: (  a      ->   b )                     -> Parser a        ->  Parser b
</code>```

which can transform the Nothing into () for us. We'll need a function that will always do this for us,

```<code>alwaysUnit nothing  =  ()
</code>```

which we can use now to arrive at the solution:

```<code>eof'  =  fmap ..... (..... ..... ......)
</code>```

Title: Combining parsers in Haskell

Body:
I'm given the following parsers

newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

instance Functor Parser where
   fmap f p = Parser $ \s -> (\(a,c) -> (f a, c)) <$> parse p s

instance Applicative Parser where
   pure a = Parser $ \s -> Just (a,s)
   f <*> a = Parser $ \s ->
     case parse f s of
       Just (g,s') -> parse (fmap g a) s'
       Nothing -> Nothing

instance Alternative Parser where
   empty = Parser $ \s -> Nothing
   l <|> r = Parser $ \s -> parse l s <|> parse r s

 ensure :: (a -> Bool) -> Parser a -> Parser a
 ensure p parser = Parser $ \s ->
    case parse parser s of
      Nothing -> Nothing
      Just (a,s') -> if p a then Just (a,s') else Nothing

 lookahead :: Parser (Maybe Char)
 lookahead = Parser f
   where f [] = Just (Nothing,[])
         f (c:s) = Just (Just c,c:s)

 satisfy :: (Char -> Bool) -> Parser Char
 satisfy p = Parser f
   where f [] = Nothing
         f (x:xs) = if p x then Just (x,xs) else Nothing

 eof :: Parser ()
 eof = Parser $ \s -> if null s then Just ((),[]) else Nothing

 eof' :: Parser ()
 eof' = ???

I need to write a new parser eof' that does exactly what eof does but is built only using the given parsers and the
 Functor/Applicative/Alternative instances above. I'm stuck on this as I don't have experience in combining parsers. Can anyone help me out ?

Body:
To understand it easier, we can write it in an equational pseudocode, while we substitute and simplify the definitions, using Monad Comprehensions for clarity and succinctness.

Monad Comprehensions are just like List Comprehensions, only working for any MonadPlus type, not just []; while corresponding closely to do notation, e.g. [ (f a, s') | (a, s') <- parse p s ]  ===  do { (a, s') <- parse p s ; return (f a, s') }.

This gets us:

newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

instance Functor Parser where
   parse (fmap f p)  s  =  [ (f a, s') | (a, s') <- parse p s ]

instance Applicative Parser where
   parse (pure a)    s  =  pure (a, s)
   parse (pf <*> pa) s  =  [ (g a, s'') | (g, s')  <- parse pf s
                                        , (a, s'') <- parse pa s' ]

instance Alternative Parser where
   parse empty s      =  empty
   parse (l <|> r) s  =  parse l s <|> parse r s

ensure :: (a -> Bool) -> Parser a -> Parser a
parse (ensure pred p) s  =  [ (a, s') | (a, s') <- parse p s, pred a ]

lookahead :: Parser (Maybe Char)
parse lookahead []       =  pure (Nothing, [])
parse lookahead s@(c:_)  =  pure (Just c,  s )

satisfy :: (Char -> Bool) -> Parser Char
parse (satisfy p) []      =  mzero
parse (satisfy p) (x:xs)  =  [ (x, xs) | p x ]

eof :: Parser ()
parse eof s  =  [ ((), []) | null s ]

eof' :: Parser ()
eof'  =  ???

By the way thanks to the use of Monad Comprehensions and the more abstract pure, empty and mzero instead of their concrete representations in terms of the Maybe type, this same (pseudo-)code will work with a different type, like [] in place of Maybe, viz. newtype Parser a = Parser { parse :: String -> [(a,String)] }.

So we have

ensure    :: (a -> Bool) -> Parser a           -> Parser a
lookahead ::                Parser (Maybe Char)

(satisfy is no good for us here .... why?)

Using that, we can have

ensure  .......  ......                        :: Parser (Maybe Char)

(... what does ensure id (pure False) do? ...)

but we'll have a useless Nothing result in case the input string was in fact empty, whereas the eof parser given to use produces the () as its result in such case (and otherwise it produces nothing).

No fear, we also have

fmap :: (  a      ->   b )                     -> Parser a        ->  Parser b

which can transform the Nothing into () for us. We'll need a function that will always do this for us,

alwaysUnit nothing  =  ()

which we can use now to arrive at the solution:

eof'  =  fmap ..... (..... ..... ......)


问:
A basic question regarding or operator in python
I get confused why the message always pops up like 'Welcome xxx' no matter what a user types.

```<code>username = input('Please enter your username: ')

if username == 'admin' or 'Admin' or 'ADMIN':
    print(f'Welcome {username}')
</code>```

Sorry I know it seems a silly question but hopefully it helps beginners like me understand or operator in python better.

Thank you for your help.

答:
You want to go for:</p>

```<code>if username == 'admin' or username == 'Admin' or username =='ADMIN':
</code>```

Body:
I get confused why the message always pops up like 'Welcome xxx' no matter what a user types.

username = input('Please enter your username: ')

if username == 'admin' or 'Admin' or 'ADMIN':
    print(f'Welcome {username}')

Sorry I know it seems a silly question but hopefully it helps beginners like me understand or operator in python better.

Thank you for your help.

Body:
You want to go for:

if username == 'admin' or username == 'Admin' or username =='ADMIN':


问:
Java code for getting count in the sorted ArrayList for particular range
Need to find the count of the elements in the sorted ArrayList from the given range(x,y). And the count should have count of range elements also if it is in ArrayList.

So for, I have done this by traversing the whole list and getting the count.

Pseudo-code:

```<code>count = 0;
for (i=0; i<length(list); i++)
{
if (list[i]>= startrange and list[i]<=endrange)
  {
    count = count+1;
  }
}
</code>```

Current solution is taking more time because input array size is more than 1000000. Help me to optimize the solution.

Example:

Input array looks like this [1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37].

Input range: (12,30)

Output should be like 8

答:
Following Java 8 Stream one-liner will work fine & return the result as expected without using cumbersome for-loop .

```<code>int[] xyz = { 1, 4, 5, 8, 9, 12, 16, 19, 23, 26, 28, 29, 30, 31, 33, 35, 37 };
long elementCountWithinRange = Arrays.stream(xyz).filter(x -> (x > 12 && x <= 31)).count();
    System.out.println(elementCountWithinRange); // will return 8
</code>```

Note : Earlier similar answer given by @Gaurav Dhiman is incorrect as the expression won't compile as count() method returns a long and not an int . Also , even if you resolve that it will give below error :

```<code>The operator >= is undefined for the argument type(s) int[], int
</code>```

To resolve that i have used Arrays.stream() instead of Stream.of() to create a Stream .

Body:
Need to find the count of the elements in the sorted ArrayList from the given range(x,y). And the count should have count of range elements also if it is in ArrayList.

So for, I have done this by traversing the whole list and getting the count.

Pseudo-code:

count = 0;
for (i=0; i<length(list); i++)
{
if (list[i]>= startrange and list[i]<=endrange)
  {
    count = count+1;
  }
}

Current solution is taking more time because input array size is more than 1000000. Help me to optimize the solution.

Example:

Input array looks like this [1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37].

Input range: (12,30)

Output should be like 8

Body:
Following Java 8 Stream one-liner will work fine & return the result as expected without using cumbersome for-loop .

int[] xyz = { 1, 4, 5, 8, 9, 12, 16, 19, 23, 26, 28, 29, 30, 31, 33, 35, 37 };
long elementCountWithinRange = Arrays.stream(xyz).filter(x -> (x > 12 && x <= 31)).count();
    System.out.println(elementCountWithinRange); // will return 8

Note : Earlier similar answer given by @Gaurav Dhiman is incorrect as the expression won't compile as count() method returns a long and not an int . Also , even if you resolve that it will give below error :

The operator >= is undefined for the argument type(s) int[], int

To resolve that i have used Arrays.stream() instead of Stream.of() to create a Stream .


问:
C/C++: goto into the for loop
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

```<code>function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}
</code>```

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

答:
If I understand correctly, you're trying to do something on the order of:

The first time foo is called, it needs to request some data from somewhere else, so it sets up that request and immediately returns;

On each subsequent call to foo, it processes the data from the previous request and sets up a new request;

This continues until foo has processed all the data.

I don't understand why you need the for loop at all in this case; you're only iterating through the loop once per call (if I understand the use case here).  Unless i has been declared static, you lose its value each time through.

Why not define a type to maintain all the state (such as the current value of i) between function calls, and then define an interface around it to set/query whatever parameters you need:

```<code>typedef ... FooState;

void foo(FooState *state, ...)
{
  if (FirstCall(state))
  {
    SetRequest(state, 1);
  }
  else if (!Done(state))
  {
    // process data;
    SetRequest(state, GetRequest(state) + 1);
  }
}
</code>```

Title: C/C++: goto into the for loop

Body:
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

Body:
If I understand correctly, you're trying to do something on the order of:

The first time foo is called, it needs to request some data from somewhere else, so it sets up that request and immediately returns;

On each subsequent call to foo, it processes the data from the previous request and sets up a new request;

This continues until foo has processed all the data.

I don't understand why you need the for loop at all in this case; you're only iterating through the loop once per call (if I understand the use case here).  Unless i has been declared static, you lose its value each time through.

Why not define a type to maintain all the state (such as the current value of i) between function calls, and then define an interface around it to set/query whatever parameters you need:

typedef ... FooState;

void foo(FooState *state, ...)
{
  if (FirstCall(state))
  {
    SetRequest(state, 1);
  }
  else if (!Done(state))
  {
    // process data;
    SetRequest(state, GetRequest(state) + 1);
  }
}


问:
How to use space bar key as a command in C? Without using system calls
If I hit the space bar then it should enter the loop and execute functionality...
The below code is for enter. Please let me know how to do the same with space bar hit

#include <stdio.h>
int main()
{
  char ch;
  //infinite loop
  while(1)
  {
    printf("Enter any character: ");
    ch=fgetc(stdin);
    if(ch==0x0A)
    {
      printf("ENTER KEY is pressed.\n");
      break;
    }
    else
    {
      printf("%c is pressed.\n",ch);
    }
    ch=getchar();
  }
  return 0;
}
```

答:
I think that what @Sreekar Sai is asking for is a way to read the space bar input without having to press the enter.

By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.

This is called the canonical mode (https://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html).

To solve this you need to disable the canonical mode, and run your application.
Here is a link where they have discussed the same and provided the solution:
How to avoid pressing enter with getchar()

Also remove the ch=getchar(); from the while loop, as I don't see the need of it.

There is also the possibility of using the conio.h header file and use the getch() function. I have not personally verified this, but you can give it a try.


问:
dplyr select is claiming that I have extra arguments that are not there

data <- tibble(x = 1:5, y = 6:10)
data %>% select(x)
```

<p>returns</p>

```Error: `...` is not empty.

We detected these problematic arguments:
* `logical`

These dots only exist to allow future extensions and should be empty.
Did you misspecify an argument?
```

<p>I can not figure out what is causing this error.  I've tried reinstalling dplyr, restarting R, restarting the computer.  Any suggestions would be appreciated.  Running slang::last_error() gives</p>

<pre class="lang-r prettyprint-override"><code><error/rlib_error_dots_nonempty>
`...` is not empty.

We detected these problematic arguments:
* `logical`

These dots only exist to allow future extensions and should be empty.
Did you misspecify an argument?
Backtrace:
  9. dplyr::select(., x)
 11. tidyselect::vars_select(tbl_vars(.data), !!!enquos(...))
 12. tidyselect:::eval_select_impl(...)
 20. tidyselect:::vars_select_eval(...)
 21. tidyselect:::walk_data_tree(expr, data_mask, context_mask)
 22. tidyselect:::eval_c(expr, data_mask, context_mask)
 23. tidyselect:::reduce_sels(node, data_mask, context_mask, init = init)
 24. tidyselect:::walk_data_tree(init, data_mask, context_mask)
 25. tidyselect:::as_indices_sel_impl(...)
 26. tidyselect:::as_indices_impl(x, vars, strict = strict)
 27. vctrs::vec_as_subscript(x, logical = "error")
 28. ellipsis::check_dots_empty()
 29. ellipsis:::action_dots(...)
Run `rlang::last_trace()` to see the full context.
</code>```

答:
I had the same thing occur. Pretty much out of the blue. Happened with tidyr::separate, So it probably propagates from dplyr into other packages depending on it. Happened on code that had no issue running previously.

Also managed to solve it by installing the dev version of dplyr, but I find this a very tricky solution. :/

Body:
data <- tibble(x = 1:5, y = 6:10)
data %>% select(x)

returns

Error: `...` is not empty.

We detected these problematic arguments:
* `logical`

These dots only exist to allow future extensions and should be empty.
Did you misspecify an argument?

I can not figure out what is causing this error.  I've tried reinstalling dplyr, restarting R, restarting the computer.  Any suggestions would be appreciated.  Running slang::last_error() gives

<error/rlib_error_dots_nonempty>
`...` is not empty.

We detected these problematic arguments:
* `logical`

These dots only exist to allow future extensions and should be empty.
Did you misspecify an argument?
Backtrace:
  9. dplyr::select(., x)
 11. tidyselect::vars_select(tbl_vars(.data), !!!enquos(...))
 12. tidyselect:::eval_select_impl(...)
 20. tidyselect:::vars_select_eval(...)
 21. tidyselect:::walk_data_tree(expr, data_mask, context_mask)
 22. tidyselect:::eval_c(expr, data_mask, context_mask)
 23. tidyselect:::reduce_sels(node, data_mask, context_mask, init = init)
 24. tidyselect:::walk_data_tree(init, data_mask, context_mask)
 25. tidyselect:::as_indices_sel_impl(...)
 26. tidyselect:::as_indices_impl(x, vars, strict = strict)
 27. vctrs::vec_as_subscript(x, logical = "error")
 28. ellipsis::check_dots_empty()
 29. ellipsis:::action_dots(...)
Run `rlang::last_trace()` to see the full context.


问:
The first key is not being recorded by keypress event
The keypress and keydown events are not recording the first keypress/down character, while the keyup event is working fine, I need in my case to use keypress but it's not recording the first char

const demo = document.querySelector('.demo');
  const input = document.querySelector('.input');

  input.addEventListener('keypress', (e)=>{
    demo.innerHTML = input.value;
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something"></code>```

答:
Document: keypress event

Deprecated

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Use HTMLElement: input event instead:

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('input', (e)=>{
  demo.innerHTML = input.value;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something"></code>```

If you want to detect which key is pressed then use Document: keyup event:

The keyup event is fired when a key is released.

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('keyup', (e)=>{
  console.log(e.code);
  demo.innerHTML = input.value;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something"></code>```

Body:
The keypress and keydown events are not recording the first keypress/down character, while the keyup event is working fine, I need in my case to use keypress but it's not recording the first char

const demo = document.querySelector('.demo');
  const input = document.querySelector('.input');

  input.addEventListener('keypress', (e)=>{
    demo.innerHTML = input.value;
  });

<input type="text" class="input" placeholder="write something">

Body:
Document: keypress event

Deprecated

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Use HTMLElement: input event instead:

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('input', (e)=>{
  demo.innerHTML = input.value;
});

<h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something">

If you want to detect which key is pressed then use Document: keyup event:

The keyup event is fired when a key is released.

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('keyup', (e)=>{
  console.log(e.code);
  demo.innerHTML = input.value;
});

<h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something">


问:
setValue() or setFormula() with complex formulas/"You do not have permission to call setFormula"
So I keep getting this error message in my spreadsheet when I try to run my code in google script:

You do not have permission to call setFormula.

I tried with both setValue() and setFormula() and the error is the same. I saw somewhere that setFormula() only works with simple formulas (ex. A2*B2/C2).

This is a simple function to concat a hyperlink to the content of the selected cell and forma a hyperlink sintax.

```<code>function HIPERLINK() {
      var ws = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var cell = ws.getActiveCell();
      var auto = cell.getValue();
      var link = '=HIPERLINK("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso='
        +auto+'";"'+auto+'")';
      cell.setFormula(link);
 }
</code>```

If anyone knows a way to do this without the error message, thanks.

答:
I tried this way and it worked for me without issues:

```<code>function setCustomLink(){
  var ss = SpreadsheetApp.getActive().getActiveSheet();
  var cell = ss.getActiveCell();
  var cellValue = cell.getValue();
  cell.setValue("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso=" + cellValue + ";" + cellValue);
}
</code>```

Let me know if you get different result.

Tip:
you can create a button and assign setCustomLink function to it, and when you need reformatting just click the button.

Here is the link how to accomplish this: Clickable images and drawings in Google Sheets.

Body:
So I keep getting this error message in my spreadsheet when I try to run my code in google script:

You do not have permission to call setFormula.

I tried with both setValue() and setFormula() and the error is the same. I saw somewhere that setFormula() only works with simple formulas (ex. A2*B2/C2).

This is a simple function to concat a hyperlink to the content of the selected cell and forma a hyperlink sintax.

function HIPERLINK() {
      var ws = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var cell = ws.getActiveCell();
      var auto = cell.getValue();
      var link = '=HIPERLINK("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso='
        +auto+'";"'+auto+'")';
      cell.setFormula(link);
 }

If anyone knows a way to do this without the error message, thanks.

Body:
I tried this way and it worked for me without issues:

function setCustomLink(){
  var ss = SpreadsheetApp.getActive().getActiveSheet();
  var cell = ss.getActiveCell();
  var cellValue = cell.getValue();
  cell.setValue("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso=" + cellValue + ";" + cellValue);
}

Let me know if you get different result.

Tip:
you can create a button and assign setCustomLink function to it, and when you need reformatting just click the button.

Here is the link how to accomplish this: Clickable images and drawings in Google Sheets.


答:
This is due entirely to the behaviour of keypress itself.

keypress fires before the content of your input has been updated, so when you retrieve the value of the input it is still empty.

Instead, you can use the keyup event which will fire faithfully as you are expecting:

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('keyup', (e)=>{
  demo.innerHTML = input.value;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something"></code>```

Alternatively, you can use your knowledge that keypress fires before the input is updated, and simulate the new value of the input by appending e.key to it:

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('keypress', (e)=>{
  demo.innerHTML = input.value + e.key;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something"></code>```

Title: The first key is not being recorded by keypress event

Body:
This is due entirely to the behaviour of keypress itself.

keypress fires before the content of your input has been updated, so when you retrieve the value of the input it is still empty.

Instead, you can use the keyup event which will fire faithfully as you are expecting:

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('keyup', (e)=>{
  demo.innerHTML = input.value;
});

<h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something">

Alternatively, you can use your knowledge that keypress fires before the input is updated, and simulate the new value of the input by appending e.key to it:

const demo = document.querySelector('.demo');
const input = document.querySelector('.input');

input.addEventListener('keypress', (e)=>{
  demo.innerHTML = input.value + e.key;
});

<h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something">


答:
This happens because the keypress event is fired before the field changes its value, while the keyup event is fired after

So when you detect the first keypress, the value of the input is still empty when you update the demo element


问:
Xcode not supported for iOS 11.3 by Xcode 9.2 needed 9.3
Apparently, with the latest IOS update, my version of Xcode could not build due to the following error.

Could not locate device support files. This iPhone 7 Plus (Model 1661, 1784, 1785, 1786) is running iOS 11.3 (15E216), which may not be supported by this version of Xcode.

Tried to install Xcode 9.3 via this link https://developer.apple.com/download/more/. But as it turns out, my Mac OS version sees the update as an incompatible version. Running on Sierra 10.12.6

答:
Quicker/Smaller Fix

This is probably due to outdated Xcode, if you don't want a big Xcode update due to limited storage/time then you can manually download the required support files instead of the whole update.

Download the files (depend on iOS veersion) from here

And then paste the downloaded files in below directory /Applications/Xcode/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport


问:
How to check if spark dataframe is empty?
Right now, I have to use df.count > 0 to check if the DataFrame is empty or not. But it is kind of inefficient. Is there any better way to do that?

PS: I want to check if it's empty so that I only save the DataFrame if it's not empty

答:
I had the same question, and I tested 3 main solution :

(df != null) && (df.count > 0)

df.head(1).isEmpty() as @hulin003 suggest

df.rdd.isEmpty() as @Justin Pihony suggest

and of course the 3 works, however in term of perfermance, here is what I found, when executing the these methods on the same DF in my machine, in terme of execution time :

it takes ~9366ms

it takes ~5607ms

it takes ~1921ms

therefore I think that the best solution is df.rdd.isEmpty() as @Justin Pihony suggest