问:
Unable to run a storm-starter topology from the Storm tutorial
When following the guide in the storm-starter repo, I'm unable to actually run any topology- like the ExclamationTopology.

mvn clean install -DskipTests=true ran successfully, executed from the top level Storm repo, as did mvn package at the storm-examples level.

When I try to run storm jar target/storm-starter-2.0.0-SNAPSHOT.jar org.apache.storm.starter.ExclamationTopology, I get the error:

```<code>Error: A JNI error has occurred, please check your installation and try  again
Exception in thread "main" java.lang.NoClassDefFoundError:   org/apache/storm/topology/IRichSpout
</code>```

I'm running OS X, Java version:

```<code>java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
</code>```

Maven version 3.3.9.

Does anyone have any ideas on why I'm getting this error and what I should change in my setup?

Full error output:

```<code>Running:

  /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java -client -Ddaemon.name= -Dstorm.options= -Dstorm.home=/Users/zachary/apache-storm-0.10.0 -Dstorm.log.dir=/Users/zachary/apache-storm-0.10.0/logs -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dstorm.conf.file= -cp /Users/zachary/apache-storm-0.10.0/lib/asm-4.0.jar:/Users/zachary/apache-storm-0.10.0/lib/clojure-1.6.0.jar:/Users/zachary/apache-storm-0.10.0/lib/disruptor-2.10.4.jar:/Users/zachary/apache-storm-0.10.0/lib/hadoop-auth-2.4.0.jar:/Users/zachary/apache-storm-0.10.0/lib/kryo-2.21.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-api-2.1.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-core-2.1.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-over-slf4j-1.6.6.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-slf4j-impl-2.1.jar:/Users/zachary/apache-storm-0.10.0/lib/minlog-1.2.jar:/Users/zachary/apache-storm-0.10.0/lib/reflectasm-1.07-shaded.jar:/Users/zachary/apache-storm-0.10.0/lib/servlet-api-2.5.jar:/Users/zachary/apache-storm-0.10.0/lib/slf4j-api-1.7.7.jar:/Users/zachary/apache-storm-0.10.0/lib/storm-core-0.10.0.jar:target/storm-starter-2.0.0-SNAPSHOT.jar:/Users/zachary/apache-storm-0.10.0/conf:/Users/zachary/apache-storm-0.10.0/bin -Dstorm.jar=target/storm-starter-2.0.0-SNAPSHOT.jar org.apache.storm.starter.ExclamationTopology
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/storm/topology/IRichSpout
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at   sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.apache.storm.topology.IRichSpout
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
</code>```

Edit:

After following the suggestions in the answers below of removing the scope line from the pom.xml, this error was gone, but replaced by:

Exception in thread "main" java.lang.ExceptionInInitializerError

```<code>Caused by: java.lang.RuntimeException: java.io.IOException: Found multiple defaults.yaml resources. You're probably bundling the Storm jars with your topology jar. [jar:file:/Users/zachary/apache-storm-0.10.0/lib/storm-core-0.10.0.jar!/defaults.yaml, jar:file:/Users/zachary/storm/examples/storm-starter/target/storm-starter-2.0.0-SNAPSHOT.jar!/defaults.yaml]
</code>```

Final Edit:

For any future googler, I ended up not getting the storm-starterexamples running via the commandline on a LocalCluster. I instead set up a new project with Maven, adding storm-core as a dependency, following [this] (https://github.com/mbonaci/mbo-storm/wiki/Storm-setup-in-Eclipse-with-Maven,-Git-and-GitHub) general guide. Then, in Eclipse, I was able to import the right packages from storm to do the examples, like ExclamationTopology. I rewrote that class using the same imports (changed to import backtype.storm.Config, etc). Then, running the file as is just works.

This quick Maven guide helps too.

答:
I too faced the same issue (Initially NoClassDefFoundError later multiple defaults.yaml)

For me following config change in intellij solved the problem.

Run ---> Edit configurations ---> Tick - Include dependencies with "provided" scope.

So basically when you are running in cluster mode, storm-core's scope should be "provided" in pom.xml. And above configuration will ensure that dependencies will be provided from cluster at run-time.

Body:
When following the guide in the storm-starter repo, I'm unable to actually run any topology- like the ExclamationTopology.

mvn clean install -DskipTests=true ran successfully, executed from the top level Storm repo, as did mvn package at the storm-examples level.

When I try to run storm jar target/storm-starter-2.0.0-SNAPSHOT.jar org.apache.storm.starter.ExclamationTopology, I get the error:

Error: A JNI error has occurred, please check your installation and try  again
Exception in thread "main" java.lang.NoClassDefFoundError:   org/apache/storm/topology/IRichSpout

I'm running OS X, Java version:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

Maven version 3.3.9.

Does anyone have any ideas on why I'm getting this error and what I should change in my setup?

Full error output:

Running:

  /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java -client -Ddaemon.name= -Dstorm.options= -Dstorm.home=/Users/zachary/apache-storm-0.10.0 -Dstorm.log.dir=/Users/zachary/apache-storm-0.10.0/logs -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dstorm.conf.file= -cp /Users/zachary/apache-storm-0.10.0/lib/asm-4.0.jar:/Users/zachary/apache-storm-0.10.0/lib/clojure-1.6.0.jar:/Users/zachary/apache-storm-0.10.0/lib/disruptor-2.10.4.jar:/Users/zachary/apache-storm-0.10.0/lib/hadoop-auth-2.4.0.jar:/Users/zachary/apache-storm-0.10.0/lib/kryo-2.21.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-api-2.1.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-core-2.1.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-over-slf4j-1.6.6.jar:/Users/zachary/apache-storm-0.10.0/lib/log4j-slf4j-impl-2.1.jar:/Users/zachary/apache-storm-0.10.0/lib/minlog-1.2.jar:/Users/zachary/apache-storm-0.10.0/lib/reflectasm-1.07-shaded.jar:/Users/zachary/apache-storm-0.10.0/lib/servlet-api-2.5.jar:/Users/zachary/apache-storm-0.10.0/lib/slf4j-api-1.7.7.jar:/Users/zachary/apache-storm-0.10.0/lib/storm-core-0.10.0.jar:target/storm-starter-2.0.0-SNAPSHOT.jar:/Users/zachary/apache-storm-0.10.0/conf:/Users/zachary/apache-storm-0.10.0/bin -Dstorm.jar=target/storm-starter-2.0.0-SNAPSHOT.jar org.apache.storm.starter.ExclamationTopology
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/storm/topology/IRichSpout
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at   sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.apache.storm.topology.IRichSpout
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more

Edit:

After following the suggestions in the answers below of removing the scope line from the pom.xml, this error was gone, but replaced by:

Exception in thread "main" java.lang.ExceptionInInitializerError

Caused by: java.lang.RuntimeException: java.io.IOException: Found multiple defaults.yaml resources. You're probably bundling the Storm jars with your topology jar. [jar:file:/Users/zachary/apache-storm-0.10.0/lib/storm-core-0.10.0.jar!/defaults.yaml, jar:file:/Users/zachary/storm/examples/storm-starter/target/storm-starter-2.0.0-SNAPSHOT.jar!/defaults.yaml]

Final Edit:

For any future googler, I ended up not getting the storm-starterexamples running via the commandline on a LocalCluster. I instead set up a new project with Maven, adding storm-core as a dependency, following [this] (https://github.com/mbonaci/mbo-storm/wiki/Storm-setup-in-Eclipse-with-Maven,-Git-and-GitHub) general guide. Then, in Eclipse, I was able to import the right packages from storm to do the examples, like ExclamationTopology. I rewrote that class using the same imports (changed to import backtype.storm.Config, etc). Then, running the file as is just works.

This quick Maven guide helps too.


来源: stackexchange

问:
Validating double field in struts 2
I have a field "length" in one of my struts 2 form. The data-type of "length" is "double". I have applied the "double" validation in XML file. But when I key-in alphabets in the "length" text field, it shows the error message as

```<code>Invalid field value for field "length"
</code>```

I don't want this message to be shown like this. This message is generated by struts 2 itself and not entered by me. I guess, this message comes as the conversion of data fails. I also applied the "conversion" validator, but the above error message is still showing up. Please suggest the solution.

Thanks in advance.

答:
You're in luck. This text is customizable.

The text is defined in xwork-messages.properties in the xwork jar. You can override it by adding the following to your global i18n resource bundle:

```<code>xwork.default.invalid.fieldvalue=Invalid field value for field "{0}".
</code>```

As you guessed, this error message occurs for all type conversion failures. The XWorkConverter class has some useful javadoc about this:

Any error that occurs during type conversion may or may not wish to be reported. For example, reporting that the input "abc" could not be converted to a number might be important. On the other hand, reporting that an empty string, "", cannot be converted to a number might not be important - especially in a web environment where it is hard to distinguish between a user not entering a value vs. entering a blank value.

By default, all conversion errors are reported using the generic i18n key xwork.default.invalid.fieldvalue, which you can override (the default text is Invalid field value for field "xxx", where xxx is the field name) in your global i18n resource bundle.

However, sometimes you may wish to override this message on a per-field basis. You can do this by adding an i18n key associated with just your action (Action.properties) using the pattern invalid.fieldvalue.xxx, where xxx is the field name.

It is important to know that none of these errors are actually reported directly. Rather, they are added to a map called conversionErrors in the ActionContext. There are several ways this map can then be accessed and the errors can be reported accordingly.

ContentLicense: CC BY-SA 3.0

Title: Validating double field in struts 2

Body:
I have a field "length" in one of my struts 2 form. The data-type of "length" is "double". I have applied the "double" validation in XML file. But when I key-in alphabets in the "length" text field, it shows the error message as

Invalid field value for field "length"

I don't want this message to be shown like this. This message is generated by struts 2 itself and not entered by me. I guess, this message comes as the conversion of data fails. I also applied the "conversion" validator, but the above error message is still showing up. Please suggest the solution.

Thanks in advance.

Body:
You're in luck. This text is customizable.

The text is defined in xwork-messages.properties in the xwork jar. You can override it by adding the following to your global i18n resource bundle:

xwork.default.invalid.fieldvalue=Invalid field value for field "{0}".

As you guessed, this error message occurs for all type conversion failures. The XWorkConverter class has some useful javadoc about this:

Any error that occurs during type conversion may or may not wish to be reported. For example, reporting that the input "abc" could not be converted to a number might be important. On the other hand, reporting that an empty string, "", cannot be converted to a number might not be important - especially in a web environment where it is hard to distinguish between a user not entering a value vs. entering a blank value.

By default, all conversion errors are reported using the generic i18n key xwork.default.invalid.fieldvalue, which you can override (the default text is Invalid field value for field "xxx", where xxx is the field name) in your global i18n resource bundle.

However, sometimes you may wish to override this message on a per-field basis. You can do this by adding an i18n key associated with just your action (Action.properties) using the pattern invalid.fieldvalue.xxx, where xxx is the field name.

It is important to know that none of these errors are actually reported directly. Rather, they are added to a map called conversionErrors in the ActionContext. There are several ways this map can then be accessed and the errors can be reported accordingly.


问:
How to implement POST and upload files in ASP C# using API?
I am trying to implement a post HTTP call through ASP C# using an API I have been given. API is not made by me but it works fine in Postman.

Here is a screenshot that worked perfectly in Postman:

and

Now, I just need to convert it to ASP C# which I spent days Googling but failed to find the answer I needed, or I am just bad in finding the right keyword. Here is what I tried, but it's a code from the company that happens to work on his page but not on mine (he's gone BTW).

```<code>public static objWebService PostSomething(string xml, Object md)
    {
        objWebService _webService = new objWebService();
        _webService.result = false;
        DataSet ds = new DataSet();

        XmlDocument xdoc = new XmlDocument(); //seems not used
        string responseString = string.Empty;

        string endpoint = "http://xxxxxxxxxxxxx"; // my post api.

        try
        {

            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            wrWebRequest.Headers["Authorization"] = "Basic xxxxxxxxxxxxx";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
            byte[] newLine = Encoding.UTF8.GetBytes("\r\n");
            byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            byte[] boundaryBytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

            wrWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            wrWebRequest.Method = "POST";
            wrWebRequest.KeepAlive = true;

            Stream requestStream = wrWebRequest.GetRequestStream();

            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"proposal.xml\"\r\nContent-Type: application/xml;\r\n\r\n{1}", "xml", req));
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Write(formItemBytes, 0, formItemBytes.Length);

            if (Utilities.IsFileExist(md.file1_path))
            {
                requestStream.Write(newLine, 0, newLine.Length);
                int bytesRead = 0;
                byte[] buffer = new byte[2048];
                byte[] formFileBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg;\r\n\r\n", "files", md.file1_name));
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                requestStream.Write(formFileBytes, 0, formFileBytes.Length);

                using (FileStream fileStream = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(md.file1_path), FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    fileStream.Close();
                }
            }

            requestStream.Write(newLine, 0, newLine.Length);
            requestStream.Write(trailer, 0, trailer.Length);
            requestStream.Close();

            HttpWebResponse wrWebResponse = wrWebRequest.GetResponse() as HttpWebResponse;

            using (Stream s = wrWebResponse.GetResponseStream())
            {
                ds.ReadXml(s);
            }

            if (ds.Tables["returnObj"] != null)
            {
                _webService.result = true;
                _webService.output = ds;
            }
            else
            {
                _webService.result = false;
            }
        }
        catch (WebException wExp)
        {
            _webService.result = false;
        }
        catch (Exception exp)
        {
            _webService.result = false;
        }
        return _webService;
    }
</code>```

This is a copy paste code I took from my ex coworker and I trim wherever I feel it's safe to trim. Forgive me if its still messy.

Whenever this portion of the code runs, I get these exceptions.

```<code>Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.ArgumentException' in System.Web.dll
</code>```

Can anyone show me how it should be done or link me to an answer if it's been asked before and solved?

答:
Convert your file to byte[]
and, then convert byte[] to HttpContent

```<code>HttpContent bytesContent = new ByteArrayContent(bArr);
</code>```

And, then pass

```<code>using (var formDataImage = new MultipartFormDataContent())
{
  formDataImage.Add(bytesContent, "image", "image");
  using (var httpImage = new HttpClient())
  {
     ServicePointManager.Expect100Continue = true;
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
     httpImage.DefaultRequestHeaders.Add("Authorization", oAuthHeaderImage);
     var httpRespImage = httpImage.PostAsync(baseUrlImage, formDataImage);
     var respBodyImage = httpRespImage.Result;
     if (respBodyImage.StatusCode.ToString().ToLower() != "created")
     {
         string rspImage = httpRespImage.Exception.InnerException.ToString();
     }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement a post HTTP call through ASP C# using an API I have been given. API is not made by me but it works fine in Postman.

Here is a screenshot that worked perfectly in Postman:

and

Now, I just need to convert it to ASP C# which I spent days Googling but failed to find the answer I needed, or I am just bad in finding the right keyword. Here is what I tried, but it's a code from the company that happens to work on his page but not on mine (he's gone BTW).

public static objWebService PostSomething(string xml, Object md)
    {
        objWebService _webService = new objWebService();
        _webService.result = false;
        DataSet ds = new DataSet();

        XmlDocument xdoc = new XmlDocument(); //seems not used
        string responseString = string.Empty;

        string endpoint = "http://xxxxxxxxxxxxx"; // my post api.

        try
        {

            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            wrWebRequest.Headers["Authorization"] = "Basic xxxxxxxxxxxxx";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
            byte[] newLine = Encoding.UTF8.GetBytes("\r\n");
            byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            byte[] boundaryBytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

            wrWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            wrWebRequest.Method = "POST";
            wrWebRequest.KeepAlive = true;

            Stream requestStream = wrWebRequest.GetRequestStream();

            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"proposal.xml\"\r\nContent-Type: application/xml;\r\n\r\n{1}", "xml", req));
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Write(formItemBytes, 0, formItemBytes.Length);

            if (Utilities.IsFileExist(md.file1_path))
            {
                requestStream.Write(newLine, 0, newLine.Length);
                int bytesRead = 0;
                byte[] buffer = new byte[2048];
                byte[] formFileBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg;\r\n\r\n", "files", md.file1_name));
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                requestStream.Write(formFileBytes, 0, formFileBytes.Length);

                using (FileStream fileStream = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(md.file1_path), FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    fileStream.Close();
                }
            }

            requestStream.Write(newLine, 0, newLine.Length);
            requestStream.Write(trailer, 0, trailer.Length);
            requestStream.Close();

            HttpWebResponse wrWebResponse = wrWebRequest.GetResponse() as HttpWebResponse;

            using (Stream s = wrWebResponse.GetResponseStream())
            {
                ds.ReadXml(s);
            }

            if (ds.Tables["returnObj"] != null)
            {
                _webService.result = true;
                _webService.output = ds;
            }
            else
            {
                _webService.result = false;
            }
        }
        catch (WebException wExp)
        {
            _webService.result = false;
        }
        catch (Exception exp)
        {
            _webService.result = false;
        }
        return _webService;
    }

This is a copy paste code I took from my ex coworker and I trim wherever I feel it's safe to trim. Forgive me if its still messy.

Whenever this portion of the code runs, I get these exceptions.

Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.ArgumentException' in System.Web.dll

Can anyone show me how it should be done or link me to an answer if it's been asked before and solved?

Body:
Convert your file to byte[]
and, then convert byte[] to HttpContent

HttpContent bytesContent = new ByteArrayContent(bArr);

And, then pass

using (var formDataImage = new MultipartFormDataContent())
{
  formDataImage.Add(bytesContent, "image", "image");
  using (var httpImage = new HttpClient())
  {
     ServicePointManager.Expect100Continue = true;
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
     httpImage.DefaultRequestHeaders.Add("Authorization", oAuthHeaderImage);
     var httpRespImage = httpImage.PostAsync(baseUrlImage, formDataImage);
     var respBodyImage = httpRespImage.Result;
     if (respBodyImage.StatusCode.ToString().ToLower() != "created")
     {
         string rspImage = httpRespImage.Exception.InnerException.ToString();
     }
  }
}


问:
Can somebody explain me how to make my JSON inside of : let parameters: [String: AnyObject]?
I need to send this JSON with HTTP post request, but I Want to convert him to a String, I have problem with the " "
if somebody can do it for me or explain it for me it will help me,
thank you!</p>

```<code>{
  "inputs": [
    {
      "data": {
        "image": {
          "url": "https://someImage.jpg"
        }
      }
    }
  ]
}
</code>```

答:
To make it dynamic use following approach: </p>

```<code>let url = [
    "url": "https://someImage.jpg"
]

let data = [
    "image":url
]

let inputs = [
    "data": [data]
]
</code>```

Body:
I need to send this JSON with HTTP post request, but I Want to convert him to a String, I have problem with the " "
if somebody can do it for me or explain it for me it will help me,
thank you!

{
  "inputs": [
    {
      "data": {
        "image": {
          "url": "https://someImage.jpg"
        }
      }
    }
  ]
}

Body:
To make it dynamic use following approach:

let url = [
    "url": "https://someImage.jpg"
]

let data = [
    "image":url
]

let inputs = [
    "data": [data]
]


问:
Change child element cursor
I am using @material-ui/core: "4.0.1"

Using a TextField component and trying to change the cursor to 'not-allowed'.

Simple code as below

```<code><TextField style={{cursor:'not-allowed'}}
        id="standard-name"
        label="Name"
        margin="normal"
        disabled={true}
      />
</code>```

But since the TextField it self have other component inside, disabled cursor icon only appear in top part of the ui (not on top of actual text area) as below

Can see two divs and one input control under TextField

Tried using glamor to overwrite the class as below but no luck

```<code>const styles = glamor.css({
  cursor:'not-allowed'
})

function MyStyledDiv({ ...rest}) {
  return (
    <div
      className={`${styles} ${'MuiInputBase-input'}`}
      {...rest}
    />
  )
}

function App() {
  return (
    <div className="App">
      <p>Testing</p>
      <MyStyledDiv>
      <TextField style={{cursor:'not-allowed'}}
        id="standard-name"
        label="Name"
        margin="normal"
        disabled={true}
      />
      </MyStyledDiv>
    </div>
  );
}
</code>```

Is there anyway I can achieve this

答:
Try adding the styling to the inputProps prop:

```<code><TextField
   id="standard-name"
   label="Name"
   margin="normal"
   disabled={true}
   inputProps={{style: {cursor:'not-allowed'}}}
/>
</code>```

Title: Change child element cursor

Body:
I am using @material-ui/core: "4.0.1"

Using a TextField component and trying to change the cursor to 'not-allowed'.

Simple code as below

<TextField style={{cursor:'not-allowed'}}
        id="standard-name"
        label="Name"
        margin="normal"
        disabled={true}
      />

But since the TextField it self have other component inside, disabled cursor icon only appear in top part of the ui (not on top of actual text area) as below

Can see two divs and one input control under TextField

Tried using glamor to overwrite the class as below but no luck

const styles = glamor.css({
  cursor:'not-allowed'
})

function MyStyledDiv({ ...rest}) {
  return (
    <div
      className={`${styles} ${'MuiInputBase-input'}`}
      {...rest}
    />
  )
}

function App() {
  return (

Testing

      <MyStyledDiv>
      <TextField style={{cursor:'not-allowed'}}
        id="standard-name"
        label="Name"
        margin="normal"
        disabled={true}
      />
      </MyStyledDiv>

  );
}

Is there anyway I can achieve this

Body:
Try adding the styling to the inputProps prop:

<TextField
   id="standard-name"
   label="Name"
   margin="normal"
   disabled={true}
   inputProps={{style: {cursor:'not-allowed'}}}
/>


问:
How to Export/Import Data from the local database?
I am working on an iOS and Android app which uses a local database for saving the data. Now my client wants to add the export & import data option in the app. So that the user can export data from one device and import it on any other device to use his account as it is. How can I do that? Any references or help.

Thanks In Advance!!!

答:
You can try to export all the data from the database to a .csv file and read from iOS or viceversa.

You can find an example of how to export data in Android here


问:
Reverse JQuery Range Slider Handlers
I am working on a Range Slider, where i wanted to reverse the ranges in the slider on button click. I have almost done the basic, but i am confused with the calculation of the slider handles being working after swapping the values in text box.

I have posted the code in fiddle.

* JQuery Click Handler for reversing values*

```<code>$("#reversePassFailVal").click(function(e){
    e.preventDefault();
    sliderElement.slider({
    slide: function(event, ui) {
      $("#minValue").val(9-ui.values[0]);
      $("#maxValue").val(5-ui.values[1]);
    }

  })
    $("#minValue").val(sliderElement.slider('values', 1));
  $("#maxValue").val(sliderElement.slider('values', 0));
});
</code>```

HTML

```<code><form id="form1">
    Caution Range:
    <span id="cautionVal"/>
    <br/>
    <div id="slider"/>
    <br/>
    <label for="txtPassRange">Pass Range</label>
    <input type="text" id="minValue"/>
    <br/>
    <label for="txtFailRange">Fail Range</label>
    <input type="text" id="maxValue" />
    <br/>
    <a href="#" class="btn btn-default" id="reversePassFailVal">Inverse</a>
</form>
</code>```

You can find the code in this
FIDDLE

答:
You'd need to destroy the slider on each change of range.

I don't know if this is the optimum solution, but here I'm building a  slider on load of the page and then destroying it on button click and creating a  fresh slider which we'd use till the page is reloaded.

The code needs optimizations and I'm open to it. Please suggest them in the comments below.

HTML: (Notice #Slider1)

```<code><form id="form1">
  Caution Range: <span id="cautionVal"></span>
  <br /><br />
  <div id="slider"><br /></div>
  <div id="slider1"></div><br />
  <label for="txtPassRange">Pass Range</label>
  <input type="text" id="minValue" />
  <br /><br />
  <label for="txtFailRange">Fail Range</label>
  <input type="text" id="maxValue" />
  <br /><br />
  <a href="#" class="btn btn-default" id="reversePassFailVal">Inverse</a>
</form>
</code>```

JS:

```<code>$(document).ready(function() {
  var cautionValue = $("#cautionVal");
  var flag = 0;
  var sliderElement = $("#slider");
  var sliderElement1 = $("#slider1");
  $("#slider").slider({
    range: true,
    steps: 0.01,
    values: [5, 9],
    min: 0,
    max: 24,
    slide: function(event, ui) {
      cautionValue.html(ui.values[0] + '-' + ui.values[1] + 'km/lo');
      $("#minValue").val(ui.values[0]);
      $("#maxValue").val(ui.values[1]);
    },

  });
  cautionValue.html(sliderElement.slider('values', 0) + '-' + sliderElement.slider('values', 1) + 'km/lo');
  $("#minValue").val(sliderElement.slider('values', 0));
  $("#maxValue").val(sliderElement.slider('values', 1));

  // Inverse Click Handler
  $("#reversePassFailVal").click(function(e) {
    e.preventDefault();
    if ($('#slider').length) {
      sliderElement.slider("destroy");
      sliderElement.remove();
    } else {
      sliderElement1.slider("destroy");
    }
    var maxVal = $("#maxValue").val();
    var minVal = $("#minValue").val();
    var minRange = 0;
    var maxRange = 24;
    if (flag === 0) {
      maxVal = maxVal * -1;
      minVal = minVal * -1;
      minRange = -24;
      maxRange = 0;
    }
    sliderElement1.slider({
      range: true,
      steps: 0.01,
      values: [maxVal, minVal],
      min: minRange,
      max: maxRange,
      slide: function(event, ui) {
        if (flag === 0) {
          cautionValue.html(Math.abs(ui.values[0]) + '-' + Math.abs(ui.values[1]) + 'km/lo');
          $("#minValue").val(Math.abs(ui.values[1]));
          $("#maxValue").val(Math.abs(ui.values[0]));
        } else {
          cautionValue.html(Math.abs(ui.values[1]) + '-' + Math.abs(ui.values[0]) + 'km/lo');
          $("#minValue").val(Math.abs(ui.values[0]));
          $("#maxValue").val(Math.abs(ui.values[1]));
        }
        console.log(Math.abs(ui.values[0]) + '-' + Math.abs(ui.values[1]) + 'km/lo');
      },

    });
    var val0 = Math.abs(sliderElement1.slider('values', 0));
    var val1 = Math.abs(sliderElement1.slider('values', 1));
    cautionValue.html(val0 + '-' + val1 + 'km/lo');
    $("#minValue").val(val0);
    $("#maxValue").val(val1);
    if (flag === 0) {
      flag = 1;
    } else {
      flag = 0;
    }

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

See it in action here: JsFiddle

Title: Reverse JQuery Range Slider Handlers

Body:
I am working on a Range Slider, where i wanted to reverse the ranges in the slider on button click. I have almost done the basic, but i am confused with the calculation of the slider handles being working after swapping the values in text box.

I have posted the code in fiddle.

* JQuery Click Handler for reversing values*

$("#reversePassFailVal").click(function(e){
    e.preventDefault();
    sliderElement.slider({
    slide: function(event, ui) {
      $("#minValue").val(9-ui.values[0]);
      $("#maxValue").val(5-ui.values[1]);
    }

  })
    $("#minValue").val(sliderElement.slider('values', 1));
  $("#maxValue").val(sliderElement.slider('values', 0));
});

HTML

<form id="form1">
    Caution Range:

    Pass Range
    <input type="text" id="minValue"/>

    Fail Range
    <input type="text" id="maxValue" />

    Inverse
</form>

You can find the code in this
FIDDLE

Body:
You'd need to destroy the slider on each change of range.

I don't know if this is the optimum solution, but here I'm building a  slider on load of the page and then destroying it on button click and creating a  fresh slider which we'd use till the page is reloaded.

The code needs optimizations and I'm open to it. Please suggest them in the comments below.

HTML: (Notice #Slider1)

<form id="form1">
  Caution Range: <span id="cautionVal"></span>
  <br /><br />
  <div id="slider"><br /></div>
  <div id="slider1"></div><br />
  <label for="txtPassRange">Pass Range</label>
  <input type="text" id="minValue" />
  <br /><br />
  <label for="txtFailRange">Fail Range</label>
  <input type="text" id="maxValue" />
  <br /><br />
  <a href="#" class="btn btn-default" id="reversePassFailVal">Inverse</a>
</form>

JS:

$(document).ready(function() {
  var cautionValue = $("#cautionVal");
  var flag = 0;
  var sliderElement = $("#slider");
  var sliderElement1 = $("#slider1");
  $("#slider").slider({
    range: true,
    steps: 0.01,
    values: [5, 9],
    min: 0,
    max: 24,
    slide: function(event, ui) {
      cautionValue.html(ui.values[0] + '-' + ui.values[1] + 'km/lo');
      $("#minValue").val(ui.values[0]);
      $("#maxValue").val(ui.values[1]);
    },

  });
  cautionValue.html(sliderElement.slider('values', 0) + '-' + sliderElement.slider('values', 1) + 'km/lo');
  $("#minValue").val(sliderElement.slider('values', 0));
  $("#maxValue").val(sliderElement.slider('values', 1));

  // Inverse Click Handler
  $("#reversePassFailVal").click(function(e) {
    e.preventDefault();
    if ($('#slider').length) {
      sliderElement.slider("destroy");
      sliderElement.remove();
    } else {
      sliderElement1.slider("destroy");
    }
    var maxVal = $("#maxValue").val();
    var minVal = $("#minValue").val();
    var minRange = 0;
    var maxRange = 24;
    if (flag === 0) {
      maxVal = maxVal * -1;
      minVal = minVal * -1;
      minRange = -24;
      maxRange = 0;
    }
    sliderElement1.slider({
      range: true,
      steps: 0.01,
      values: [maxVal, minVal],
      min: minRange,
      max: maxRange,
      slide: function(event, ui) {
        if (flag === 0) {
          cautionValue.html(Math.abs(ui.values[0]) + '-' + Math.abs(ui.values[1]) + 'km/lo');
          $("#minValue").val(Math.abs(ui.values[1]));
          $("#maxValue").val(Math.abs(ui.values[0]));
        } else {
          cautionValue.html(Math.abs(ui.values[1]) + '-' + Math.abs(ui.values[0]) + 'km/lo');
          $("#minValue").val(Math.abs(ui.values[0]));
          $("#maxValue").val(Math.abs(ui.values[1]));
        }
        console.log(Math.abs(ui.values[0]) + '-' + Math.abs(ui.values[1]) + 'km/lo');
      },

    });
    var val0 = Math.abs(sliderElement1.slider('values', 0));
    var val1 = Math.abs(sliderElement1.slider('values', 1));
    cautionValue.html(val0 + '-' + val1 + 'km/lo');
    $("#minValue").val(val0);
    $("#maxValue").val(val1);
    if (flag === 0) {
      flag = 1;
    } else {
      flag = 0;
    }

  });
});

See it in action here: JsFiddle


问:
react native back ImageBackground centering
I have an image where i try to center some text on it.

For that i use ImageBackground to have child elements of the image.

However the image is being scaled down on small devices, and full size if possible

When i center my text, it gets centered after the whole image ratio ( on a big screen where you can see the whole image, its centered - on small screens its offset because some of the image is cropped to fit.

```<code><ImageBackground style={{ width: wp('50%'),
                 height: hp('50%'),
                 resizeMode: 'cover',
                 justifyContent: 'center',
                 alignItems: 'center' }}
                 source={require('../assets/images/12.jpg')}>

    // if the full image is showing - it's centered, otherwise not!
    <Text style={{ color: "red" }}>Centered text</Text>

</ImageBackground>
</code>```

答:
you need to add an extra view to wrap the ImageBackground and add style property
justifyContent and alignItems to center and I think this will erase your problem.</p>

```<code><View style={{ flex:1 , justifyContent: 'center', alignItems: 'center' }}>
    <ImageBackground

        style={{ width: wp('50%'), height: hp('50%'), resizeMode: 'cover', justifyContent: 'center', alignItems: 'center' }}
        source={require('../assets/images/12.jpg')}>

        // if the full image is showing - it's centered, otherwise not!
        <Text style={{ color: "red" }}>Centered text</Text>

    </ImageBackground>
</View>
</code>```

Body:
I have an image where i try to center some text on it.

For that i use ImageBackground to have child elements of the image.

However the image is being scaled down on small devices, and full size if possible

When i center my text, it gets centered after the whole image ratio ( on a big screen where you can see the whole image, its centered - on small screens its offset because some of the image is cropped to fit.

<ImageBackground style={{ width: wp('50%'),
                 height: hp('50%'),
                 resizeMode: 'cover',
                 justifyContent: 'center',
                 alignItems: 'center' }}
                 source={require('../assets/images/12.jpg')}>

    // if the full image is showing - it's centered, otherwise not!
    <Text style={{ color: "red" }}>Centered text</Text>

</ImageBackground>

Body:
you need to add an extra view to wrap the ImageBackground and add style property
justifyContent and alignItems to center and I think this will erase your problem.

<View style={{ flex:1 , justifyContent: 'center', alignItems: 'center' }}>
    <ImageBackground

        style={{ width: wp('50%'), height: hp('50%'), resizeMode: 'cover', justifyContent: 'center', alignItems: 'center' }}
        source={require('../assets/images/12.jpg')}>

        // if the full image is showing - it's centered, otherwise not!
        <Text style={{ color: "red" }}>Centered text</Text>

    </ImageBackground>
</View>


问:
Running a Python function for a specific duration
Total sleep time should be 60 secs and each check should be in 5 secs interval.
How should I use count variable to trace the count of the total execution

```<code>
def test(a):
    count=0
    while True:
        if a < 10:
            print("ok")
            return True
        count = count+1
        time.sleep(5)

        if(count == 12):
            return False

print(test(a=40))
</code>```

the while loop should stop executing after 60 secs and return false, the each check interval is 5 secs. I am confused that where should I increment the count, before time.sleep(5) or after time.sleep(5). what will be the solution to see that the time.sleep is been executed for 12 times and it has been 60 secs of waiting and return false

答:
You can use time.time()

```<code>import time
max_time = 60

start_time = time.time()  # remember when we started

    def test(a):
    count=0
    while (time.time() - start_time) < max_time:
        if a < 10:
            print("ok")

print(test(a=40))
</code>```

Body:
Total sleep time should be 60 secs and each check should be in 5 secs interval.
How should I use count variable to trace the count of the total execution

def test(a):
    count=0
    while True:
        if a < 10:
            print("ok")
            return True
        count = count+1
        time.sleep(5)

        if(count == 12):
            return False

print(test(a=40))

the while loop should stop executing after 60 secs and return false, the each check interval is 5 secs. I am confused that where should I increment the count, before time.sleep(5) or after time.sleep(5). what will be the solution to see that the time.sleep is been executed for 12 times and it has been 60 secs of waiting and return false

Body:
You can use time.time()

import time
max_time = 60

start_time = time.time()  # remember when we started

    def test(a):
    count=0
    while (time.time() - start_time) < max_time:
        if a < 10:
            print("ok")

print(test(a=40))


问:
Use transaction in node-oracledb
I need to execute 3 different update statements in a transaction. I am using node-oracle package. Is there an example which shows how transactions are to be done?</p>

答:
Initially You can set autoCommit false and once your tasks are completed you can commit it.

by using connection function connection.commit(function(error))

Example :

```<code>var oracledb = require('oracledb');
oracledb.autoCommit = false;
</code>```

and when connection.execute() is successfully executed you can commit it as below

```<code>conn.execute(
    "INSERT INTO test VALUES (:id, :nm)",
    [2, 'Alison'],  // Bind values
    function(err, result) {
      if (err) {
        return cb(err, conn);
      } else {
        console.log("Rows inserted: " + result.rowsAffected);  // 1
        conn.commit((error)=> {
           console.log('Error : ', error);
        });
      }
    });
</code>```

Title: Use transaction in node-oracledb

Body:
Initially You can set autoCommit false and once your tasks are completed you can commit it.

by using connection function connection.commit(function(error))

Example :

var oracledb = require('oracledb');
oracledb.autoCommit = false;

and when connection.execute() is successfully executed you can commit it as below

conn.execute(
    "INSERT INTO test VALUES (:id, :nm)",
    [2, 'Alison'],  // Bind values
    function(err, result) {
      if (err) {
        return cb(err, conn);
      } else {
        console.log("Rows inserted: " + result.rowsAffected);  // 1
        conn.commit((error)=> {
           console.log('Error : ', error);
        });
      }
    });


问:
reuse a calculated field in the same query
I have this query.

```<code>SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

```<code>SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

答:
You can right it as</p>

```<code>SELECT
nome ,
total,
 residuo AS residuo_TMP,
 (1500-total) AS residuo
 FROM
 (SELECT
carte.nome,
SUM(amount) AS total,
(1500- SUM(amount)) AS residuo
 FROM
movimenti_carta
JOIN carte
  ON movimenti_carta.banca = carte.id
 WHERE DATA BETWEEN '2019-05-01'
AND '2019-05-31'
GROUP BY banca ) aa
</code>```

Body:
I have this query.

SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

Body:
You can right it as

SELECT
nome ,
total,
 residuo AS residuo_TMP,
 (1500-total) AS residuo
 FROM
 (SELECT
carte.nome,
SUM(amount) AS total,
(1500- SUM(amount)) AS residuo
 FROM
movimenti_carta
JOIN carte
  ON movimenti_carta.banca = carte.id
 WHERE DATA BETWEEN '2019-05-01'
AND '2019-05-31'
GROUP BY banca ) aa


答:
You could use a join  with subquery for badge 1 and badge 2 </p>

```<code>select t1.badge, min_dat, nax_date
from  (
  select  badge, min_(data_ora) min_data
  from my_table
  where lettore  = 1
  group by badge
) t1
INNER JOIN  (
 select  badge, max_(data_ora) max_data
  from my_table
  where lettore  = 2
  group by badge
) t2  ON t1.badge = t2.badge
</code>```

Title: Select Max and Min datetime for distinct user

Body:
I have a record as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   2         2017-04-01 12:30:00       1       2
   3         2017-04-01 13:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   10        2017-04-03 12:30:00       3       2
   11        2017-04-03 13:30:00       3       1
   12        2017-04-03 18:30:00       3       2

I want to get the first access time and the last daily logout time (for each day) for each individual user (badge).

How I can do this?

The record I wish to as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   12        2017-04-03 18:30:00       3       2

Is it possible to do that? Thanks.

NOTE: ID are auto-incremented and LETTORE 1 is entry and LETTORE 2 is exit.

Body:
You could use a join  with subquery for badge 1 and badge 2

select t1.badge, min_dat, nax_date
from  (
  select  badge, min_(data_ora) min_data
  from my_table
  where lettore  = 1
  group by badge
) t1
INNER JOIN  (
 select  badge, max_(data_ora) max_data
  from my_table
  where lettore  = 2
  group by badge
) t2  ON t1.badge = t2.badge


问:
Is it possible to fetch the parent object heading to the child object in doors module?
I want to write a dxl code which checks the object's parent heading(object level 3) and writes in a separate column for all the child objects.
Can anyone please help me with dxl command?</p>

答:
The simplest approach would be to create layout DXL column with the following approach

```<code>Object oParent = parent(obj)
if (!null oParent) {
    if (!null oParent."Object Heading""") {
        display oParent."Object Heading"""
    }
}
</code>```

You might want to augment the code with some conditions, like if/and level(obj) == 3 (i.e. only show something if the level of the CURRENT object is 3) or if/and (!null obj."Object Heading""") (i.e. don't show the parent's heading if the CURRENT object owns a heading).

Body:
The simplest approach would be to create layout DXL column with the following approach

Object oParent = parent(obj)
if (!null oParent) {
    if (!null oParent."Object Heading""") {
        display oParent."Object Heading"""
    }
}

You might want to augment the code with some conditions, like if/and level(obj) == 3 (i.e. only show something if the level of the CURRENT object is 3) or if/and (!null obj."Object Heading""") (i.e. don't show the parent's heading if the CURRENT object owns a heading).


答:
try below using correlated subquery and union all</p>

```<code>select * from tablename a
where DATA_ORA in (select min(DATA_ORA) from tablename b where a.badge=b.badge)
union
select * from tablename a
where DATA_ORA in (select max(DATA_ORA) from tablename b where a.badge=b.badge)
</code>```

Body:
try below using correlated subquery and union all

select * from tablename a
where DATA_ORA in (select min(DATA_ORA) from tablename b where a.badge=b.badge)
union
select * from tablename a
where DATA_ORA in (select max(DATA_ORA) from tablename b where a.badge=b.badge)


问:
./startup.sh: command not found error
I downloaded tomcat9 zip file and extracted all files. now I am running

```<code>/bin$ sudo ./startup.sh
</code>```

i am getting this error

```<code>sudo: ./startup.sh: command not found
</code>```

all files are there then why this error ?

答:
go to the bin folder.run bellow two commands

```<code>chmod 777 startup.sh
chmod 777 catalina.sh
</code>```

to start tomcat

```<code>sudo startup.sh
</code>```

Title: ./startup.sh: command not found error

Body:
I downloaded tomcat9 zip file and extracted all files. now I am running

/bin$ sudo ./startup.sh

i am getting this error

sudo: ./startup.sh: command not found

all files are there then why this error ?

Body:
go to the bin folder.run bellow two commands

chmod 777 startup.sh
chmod 777 catalina.sh

to start tomcat

sudo startup.sh


问:
Is the Time Complexity of assigning n values to an array of size n O(n)?
I am trying Index mapping in Hashing to search an element in an array. A linear search would take O(n) to search an element in an array of size n. In hashing what we're doing is basically reducing the time complexity to O(1) by creating a 2d matrix of zeros (say hash[1000][2]) and reassigning hash[a[i]][0] to 1 if a[i] is positive and hash[-a[i]][1] if a[i] is negative. Here a[i] is the array from which we are supposed to search an element.

```<code>    for(i=0 ;i<n    ;i++)
    {
        if(a[i]>=0)
            has[a[i]][0]=1;
        else
            has[-a[i]][1]=1;
    }
</code>```

How much time does the above code take to execute?
Even by hashing, aren't we having a time complexity of O(n) just like linear search? Isn't what has consumed to assign n 1's in a 2d array of zeros equal to the time taken to search an element in a linear fashion?

答:
A typical thing to do here would be to maintain an array sorted by hash key, and then use a binary search to locate elements, giving worst-case time complexity of O(log n).

You can maintain the sort order by using the same binary search for inserting new elements as you use for finding existing elements.

That last point is important: as noted in comments, sorting before each search degrades search time to the point where brute-force linear search is faster for small datasets. But that overhead can be eliminated; the array never needs to be sorted if you maintain sort order when inserting new elements.

Body:
I am trying Index mapping in Hashing to search an element in an array. A linear search would take O(n) to search an element in an array of size n. In hashing what we're doing is basically reducing the time complexity to O(1) by creating a 2d matrix of zeros (say hash[1000][2]) and reassigning hash[a[i]][0] to 1 if a[i] is positive and hash[-a[i]][1] if a[i] is negative. Here a[i] is the array from which we are supposed to search an element.

    for(i=0 ;i<n    ;i++)
    {
        if(a[i]>=0)
            has[a[i]][0]=1;
        else
            has[-a[i]][1]=1;
    }

How much time does the above code take to execute?
Even by hashing, aren't we having a time complexity of O(n) just like linear search? Isn't what has consumed to assign n 1's in a 2d array of zeros equal to the time taken to search an element in a linear fashion?


答:
The best way to do that is creating a way to read data and write data to a .csv file. In reading you can easily write your data like a text file and separate every entry with ','. and reading data from it is also easy , you can read file line by line and use java string tools to process the string file and fetch data from it.

Beside it can be edited or generated by Microsoft excel. So the client could easily work with it.

Title: How to Export/Import Data from the local database?

Body:
I am working on an iOS and Android app which uses a local database for saving the data. Now my client wants to add the export & import data option in the app. So that the user can export data from one device and import it on any other device to use his account as it is. How can I do that? Any references or help.

Thanks In Advance!!!


问:
XmlSerializer serializing an empty list of ints in an attribute
Consider an element like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLSchema1" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Foo">
    <xs:complexType>
      <xs:attribute name="MyList">
        <xs:simpleType>
          <xs:list itemType="xs:int" />
        </xs:simpleType>
      </xs:attribute>
    </xs:complexType>
  </xs:element>
</xs:schema>
</code>```

E.g.:

```<code><Foo MyList='1 2 3' />
</code>```

This corresponds to this C# class:

```<code>[Serializable]
public class Foo
{
  [XmlAttribute]
  public int[] MyList { get; set; }
}
</code>```

And that’s (basically) what xsd.exe /classes generates.

Serializing and Deserializing works great, except deserializing an empty list:

```<code>var ser = new XmlSerializer(typeof(Foo));
ser.Deserialize(new StringReader("<Foo MyList='' />"));
</code>```

AFAIK, this is perfectly legal XML, but the XmlSerializer will throw an InvalidOperationException:

```<code>System.InvalidOperationException: There is an error in XML document (1, 6). ---> System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderFoo.Read2_Foo(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderFoo.Read3_Foo()
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   at Blah.Program.Main(String[] args) in Program.cs:line 17
</code>```

(This exception is from .NET 4.7.2; .NET Core 2.2 throws the same exception with almost identical stack trace.) The exception makes sense, as "" is not an integer.

There is this similar question, but it’s about enums, and I don’t know how to use the answer there for ints.

How can I get deserializing of an empty list working without implementing IXmlSerializable (what involves a lot of additional coding)?

答:
I'm not sure there is any magic you can do with the serializer attributes to make this work, and as it's an attribute, you can't add a complex type to help hide away the problem. You could use a proxy property which handles the input as a string to work around the problem, which while it is not beautiful, avoids the need for a full blown IXmlSerializable implementation.

```<code>[Serializable]
public class Foo
{
    [XmlIgnore]
    public int[] MyList { get; set; }

    [XmlAttribute(AttributeName = "MyList")]
    public string MyListProxy
    {
        get
        {
            if (MyList == null) return String.Empty;
            return String.Join(" ", MyList);
        }
        set
        {
            MyList = String.IsNullOrWhiteSpace(value) ? new int[0] : value
                .Split(' ')
                .Select(a => int.Parse(a))
                .ToArray();
        }
    }
}
</code>```

Body:
Consider an element like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLSchema1" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Foo">
    <xs:complexType>
      <xs:attribute name="MyList">
        <xs:simpleType>
          <xs:list itemType="xs:int" />
        </xs:simpleType>
      </xs:attribute>
    </xs:complexType>
  </xs:element>
</xs:schema>

E.g.:

<Foo MyList='1 2 3' />

This corresponds to this C# class:

[Serializable]
public class Foo
{
  [XmlAttribute]
  public int[] MyList { get; set; }
}

And that’s (basically) what xsd.exe /classes generates.

Serializing and Deserializing works great, except deserializing an empty list:

var ser = new XmlSerializer(typeof(Foo));
ser.Deserialize(new StringReader("<Foo MyList='' />"));

AFAIK, this is perfectly legal XML, but the XmlSerializer will throw an InvalidOperationException:

System.InvalidOperationException: There is an error in XML document (1, 6). ---> System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderFoo.Read2_Foo(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderFoo.Read3_Foo()
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   at Blah.Program.Main(String[] args) in Program.cs:line 17

(This exception is from .NET 4.7.2; .NET Core 2.2 throws the same exception with almost identical stack trace.) The exception makes sense, as "" is not an integer.

There is this similar question, but it’s about enums, and I don’t know how to use the answer there for ints.

How can I get deserializing of an empty list working without implementing IXmlSerializable (what involves a lot of additional coding)?

Body:
I'm not sure there is any magic you can do with the serializer attributes to make this work, and as it's an attribute, you can't add a complex type to help hide away the problem. You could use a proxy property which handles the input as a string to work around the problem, which while it is not beautiful, avoids the need for a full blown IXmlSerializable implementation.

[Serializable]
public class Foo
{
    [XmlIgnore]
    public int[] MyList { get; set; }

    [XmlAttribute(AttributeName = "MyList")]
    public string MyListProxy
    {
        get
        {
            if (MyList == null) return String.Empty;
            return String.Join(" ", MyList);
        }
        set
        {
            MyList = String.IsNullOrWhiteSpace(value) ? new int[0] : value
                .Split(' ')
                .Select(a => int.Parse(a))
                .ToArray();
        }
    }
}


问:
access DOM and change element font and colour

I want to access some character from string and change the style of them
for example "hello"
i want to change "h" character's color and font
how can i do this
i try this

```<code>var txt=document.getElementById('d1').getElementsByTagName('p')[0]
            txt.innerHTML="H"
            txt.style.color="red"
</code>```

答:
document.getElementById('di') selects a single element from the dom.

You don't need .getElementsByTagName('p')[0] after that.

The solution depends on the dom. If you have an element like
H, then the following is correct

```<code>var txt = document.getElementById('d1');
txt.innerHTML="H";
txt.style.color="red";
</code>```

Body:
I want to access some character from string and change the style of them
for example "hello"
i want to change "h" character's color and font
how can i do this
i try this

var txt=document.getElementById('d1').getElementsByTagName('p')[0]
            txt.innerHTML="H"
            txt.style.color="red"

Body:
document.getElementById('di') selects a single element from the dom.

You don't need .getElementsByTagName('p')[0] after that.

The solution depends on the dom. If you have an element like
<span id='d1'>H</span>, then the following is correct

var txt = document.getElementById('d1');
txt.innerHTML="H";
txt.style.color="red";


问:
XCode 4 (Assembla) SVN Repository "Unable to load revisions"
I've been trying unsuccessfully to connect to an https assembla svn repository with the new xcode 4 IDE for an iPhone project I'm working on.

I was able to connect just fine with the last version of xcode (3?), and with other svn apps. I'm using the same repo address and credentials, so I'm baffled as to why this doesn't work.

I also tried loading in a working copy of the repo, and it cannot connect either.

The one error message that comes up is "Unable to load revisions"

Any tips?

答:
There are a lot of links, but no solution posted directly here, so I'll do it.

The reason Xcode4 does this is that it tries to log you into the SVN server with your mac credentials. When that fails, it basically just hangs and fails. The best solution I've seen so far is this:

open a terminal

If you don't have the project out do this:

>svn checkout SERVER_PATH FOLDER_PATH_TO_PUT_THE_PROJECT

It will then ask you for password for the mac username, you just write anything or nothing and press enter.

it will then fail and ask you for a username. Enter the correct one and then the password when it asks.

The project will be checked out, but you can just close the terminal window and delete the folder again if you want. Xcode4 will now connect without a hitch. :)


问:
Compare multiple Lists only one time each in python
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
```

<p>This prints :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2
```

<p>And i would like this result :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2
```

Thanks you for your help !

答:
You should do it more clearly,

Just 2 loops for and just 3 lines :

```<code>for i in resultList:
    for j in resultList[resultList.index(i):]:
            print(str(i[0]) + '-' + str(j[0]) + ' : ' + str((np.isin(i[1], j[1]) == True).sum()))
</code>```

Result :

```<code>Student1-Student1 : 2
Student1-Student2 : 0
Student1-Student3 : 1
Student1-Student4 : 1
Student2-Student2 : 2
Student2-Student3 : 0
Student2-Student4 : 0
Student3-Student3 : 2
Student3-Student4 : 0
Student4-Student4 : 2
</code>```

Your welcome :)

Body:
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))

This prints :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2

And i would like this result :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2

Thanks you for your help !

Body:
You should do it more clearly,

Just 2 loops for and just 3 lines :

for i in resultList:
    for j in resultList[resultList.index(i):]:
            print(str(i[0]) + '-' + str(j[0]) + ' : ' + str((np.isin(i[1], j[1]) == True).sum()))

Result :

Student1-Student1 : 2
Student1-Student2 : 0
Student1-Student3 : 1
Student1-Student4 : 1
Student2-Student2 : 2
Student2-Student3 : 0
Student2-Student4 : 0
Student3-Student3 : 2
Student3-Student4 : 0
Student4-Student4 : 2

Your welcome :)


问:
How to know which params is missing in a query?
I'm setting up a Booking router in NodeJS, and I have many params in.
Now when I forgot params I return an error like :

500: Need more information

I wonder if it's possible to know which params are missing when I return the error code.

This is for a new API made in NodeJS

Here are the params that I want to retrieve from the front ( made in ReactJS )

```<code>let body = {
        agentDutyCode: "STRING",
        RatePlanCode: params.rateCode,
        RoomCode: params.roomCode,
        AmountAfterTax: params.amountTax,
        Start: params.fromDate,
        End: params.toDate,
        CardCode: params.cardCode,
        CardNumber: params.cardNumber,
        ExpireDate: params.expireDate,
        SeriesCode: params.cvv,
        CardHolderName: params.nameCard,
        ChainCode: params.chainCode,
        HotelCode: params.hotelCode,
        RoomQuantities: params.roomQuantities,
        GuestQuantitie: params.numberGuest,
        GuestPerRoom: params.guestPerRoom,
        LastName: params.lastName,
        FirstName: params.firstName,
        PhoneNumber: params.phoneNumber,
        email: params.email,
        FVL_SUBUNIT_7: params.walletAddress
    }
</code>```

And this is my promise :

 cdsJson.bookResource(req.body)
        .then((response) => {
            if (response !== null) {
                res.response = {
                    ...response
                }
            } if (response.hotel.length === 0) {
                res.respStatus = 500
                res.response = {
                    sendMsg: "Need more informations"
                }
                next('route')
            }
            return response
        })
```

If the request succeeds I got a reservation ID otherwise I got :

Error 500: Need more information

答:
try it for a for ... in loop like this:

```<code>cdsJson.bookResource(req.body)
.then((response) => {
    if (response !== null) {
        res.response = {
            ...response
        }
    } if (response.hotel.length === 0) {
        res.respStatus = 500

        let errorStr = "Need more informations"

        for(var key in req.body) { // Get all parameters that are not set
            if(objects[key] == undefined)
                errorStr += "\nParameter ["+key+"] is missing!"
        }

        res.response = {
            sendMsg: errorStr
        }
        next('route')
    }
    return response
})
</code>```

Body:
I'm setting up a Booking router in NodeJS, and I have many params in.
Now when I forgot params I return an error like :

500: Need more information

I wonder if it's possible to know which params are missing when I return the error code.

This is for a new API made in NodeJS

Here are the params that I want to retrieve from the front ( made in ReactJS )

let body = {
        agentDutyCode: "STRING",
        RatePlanCode: params.rateCode,
        RoomCode: params.roomCode,
        AmountAfterTax: params.amountTax,
        Start: params.fromDate,
        End: params.toDate,
        CardCode: params.cardCode,
        CardNumber: params.cardNumber,
        ExpireDate: params.expireDate,
        SeriesCode: params.cvv,
        CardHolderName: params.nameCard,
        ChainCode: params.chainCode,
        HotelCode: params.hotelCode,
        RoomQuantities: params.roomQuantities,
        GuestQuantitie: params.numberGuest,
        GuestPerRoom: params.guestPerRoom,
        LastName: params.lastName,
        FirstName: params.firstName,
        PhoneNumber: params.phoneNumber,
        email: params.email,
        FVL_SUBUNIT_7: params.walletAddress
    }

And this is my promise :

 cdsJson.bookResource(req.body)
        .then((response) => {
            if (response !== null) {
                res.response = {
                    ...response
                }
            } if (response.hotel.length === 0) {
                res.respStatus = 500
                res.response = {
                    sendMsg: "Need more informations"
                }
                next('route')
            }
            return response
        })

If the request succeeds I got a reservation ID otherwise I got :

Error 500: Need more information

Body:
try it for a for ... in loop like this:

cdsJson.bookResource(req.body)
.then((response) => {
    if (response !== null) {
        res.response = {
            ...response
        }
    } if (response.hotel.length === 0) {
        res.respStatus = 500

        let errorStr = "Need more informations"

        for(var key in req.body) { // Get all parameters that are not set
            if(objects[key] == undefined)
                errorStr += "\nParameter ["+key+"] is missing!"
        }

        res.response = {
            sendMsg: errorStr
        }
        next('route')
    }
    return response
})


问:
In ASP.net, what kind of IF statement could I use to hide a div if the image inside it matches the current page URL?
This is within Sitefinity if that matters, and I am really new at ASP.NET and C#.

I have an image-based navigation element at the bottom of a page that links to different articles using the same template.   There are 5 articles, and I would like the link to the active page/article to be hidden so there is a grid of 4 image links.

Here's a screenshot:

https://i.imgur.com/PG2Sfpo.png

Here is the code behind it:

```<code>@{
    string navTitle = string.Empty;
    string url = string.Empty;

    if (Model.CurrentSiteMapNode != null && Model.CurrentSiteMapNode.ParentNode != null)
    {
        if (Model.CurrentSiteMapNode.Title == "Home")
        {
            navTitle = Model.CurrentSiteMapNode.ParentNode.Title;
        }
        else
        {
            navTitle = Model.CurrentSiteMapNode.Title;
        }
        url = Model.CurrentSiteMapNode.ParentNode.Url;
    }
}
 <div class="foundation-stories-container">
    @foreach (var node in Model.Nodes)
    {
        @RenderRootLevelNode(node);
    }
</div>

@*Here is specified the rendering for the root level*@
@helper RenderRootLevelNode(NodeViewModel node)
{
string[] thisPage = (node.Url).Split('/');
string thisImage = thisPage[4] + ".jpg";
 <a href="@node.Url" target="@node.LinkTarget">
     <div class="foundation-story-block">
         <div class="hovereffect">
             <img src="[OUR WEBSITE URL]/stories/@thisImage" class="img-fluid">
             <div class="overlay">
                 <h2>@node.Title</h2>
             </div>
         </div>
     </div>
 </a>
}
</code>```

So we're already getting the page URL and image file name

```<code>string[] thisPage = (node.Url).Split('/');
string thisImage = thisPage[4] + ".jpg";
</code>```

Is this as easy as doing the following?

```<code>if (thisImage = thisPage)
{
   foundation-story-block.AddClassToHtmlControl("hide")
}

</code>```

Seems easy enough, but I don't know where to start.

I'm better at Javascript, so I do have a JS solution in place for this already, but I'd really like to find a cleaner way to do it.

```<code><script type="text/javascript">

$(document).ready(function() {

    var active = window.location.pathname.split("/").pop()

    var name = active;
    name = name.replace(/-/g, ' ');

    jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >=
    0;
    };
});

$("h2:Contains('" + name + "')").closest(".foundation-story-block").addClass("hide");

});

</script>
</code>```

This exists on the main template page.

Gets the last part of the URL

Sets that as a variable called "name"

Changes the dash to a space if there is one (most of the pages are associated with names so it's like /first-last)

Then it goes and looks at the  which is where the title of the page lives, and if it equals the "name" variable, the ".hide" class is added to the block.

Thanks for any help anyone can provide.

答:
It is possible, yes. Here is how:</p>

```<code>...
@{
  var hiddenClass = thisImage == thisPage ? "hide" : string.Empty;
}
<div class="foundation-story-block @hiddenClass">
    <div class="hovereffect">
        <img src="[OUR WEBSITE URL]/stories/@thisImage" class="img-fluid">
        <div class="overlay">
              <h2>@node.Title</h2>
         </div>
    </div>
</div>
</code>```

Body:
This is within Sitefinity if that matters, and I am really new at ASP.NET and C#.

I have an image-based navigation element at the bottom of a page that links to different articles using the same template.   There are 5 articles, and I would like the link to the active page/article to be hidden so there is a grid of 4 image links.

Here's a screenshot:

https://i.imgur.com/PG2Sfpo.png

Here is the code behind it:

@{
    string navTitle = string.Empty;
    string url = string.Empty;

    if (Model.CurrentSiteMapNode != null && Model.CurrentSiteMapNode.ParentNode != null)
    {
        if (Model.CurrentSiteMapNode.Title == "Home")
        {
            navTitle = Model.CurrentSiteMapNode.ParentNode.Title;
        }
        else
        {
            navTitle = Model.CurrentSiteMapNode.Title;
        }
        url = Model.CurrentSiteMapNode.ParentNode.Url;
    }
}

    @foreach (var node in Model.Nodes)
    {
        @RenderRootLevelNode(node);
    }

@*Here is specified the rendering for the root level*@
@helper RenderRootLevelNode(NodeViewModel node)
{
string[] thisPage = (node.Url).Split('/');
string thisImage = thisPage[4] + ".jpg";

@node.Title

}

So we're already getting the page URL and image file name

string[] thisPage = (node.Url).Split('/');
string thisImage = thisPage[4] + ".jpg";

Is this as easy as doing the following?

if (thisImage = thisPage)
{
   foundation-story-block.AddClassToHtmlControl("hide")
}

Seems easy enough, but I don't know where to start.

I'm better at Javascript, so I do have a JS solution in place for this already, but I'd really like to find a cleaner way to do it.

This exists on the main template page.

Gets the last part of the URL

Sets that as a variable called "name"

Changes the dash to a space if there is one (most of the pages are associated with names so it's like /first-last)

Then it goes and looks at the  which is where the title of the page lives, and if it equals the "name" variable, the ".hide" class is added to the block.

Thanks for any help anyone can provide.

Body:
It is possible, yes. Here is how:

...
@{
  var hiddenClass = thisImage == thisPage ? "hide" : string.Empty;
}
<div class="foundation-story-block @hiddenClass">
    <div class="hovereffect">
        <img src="[OUR WEBSITE URL]/stories/@thisImage" class="img-fluid">
        <div class="overlay">
              <h2>@node.Title</h2>
         </div>
    </div>
</div>


问:
Why does compiling this code result in a syntax error?
I wrote the following code but i am getting the error as i mentioned can any one tell</p>

```<code>protected void btnGenerate_Click(object sender, EventArgs e)
{
    DataRow[] dRow;
    DataTable dt = new DataTable();
    foreach (GridViewRow grRow in grdACH.Rows)
    {
        CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
        if (chkItem.Checked)
        {
            chkItm = true;
            chkcnt++;
            strBankTypeID = ((Label)grRow.FindControl("lblBankType")).Text.ToString();
            strBnkArray.Append(strBankTypeID);
            strBnkArray.Append(",");
        }
    }
    oEmpDeposits.getEmpDepositDetails(out local_ds, strFedTaxId, PayperiodNumber, PayrollYear, strPayFreqType);

for (int i = 0; i < local_ds.Tables[0].Rows.Count; i++)
    {
        string strTrim = strBnkArray.ToString().TrimEnd(',');
        strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        if (strTrim.Contains("BankAccountTypeID=',"))
        {
            strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        }

        dRow = local_ds.Tables[0].Select(strTrim);
    }
}
</code>```

答:
WHy don't you use ArrayList instead of String array. So that it will be easy to manipulate

Sample

```<code>if (chkItem.Checked)
{
  chkItm = true;
  chkcnt++;
  strBankTypeID += ((Label)grRow.FindControl("lblBankType")).Text.ToString();
  ArrayList lstArray=new ArrayList();
  lstArray.Add(strBankTypeID);
}
</code>```

Later

```<code> oEmpDeposits.getEmpDepositDetails(out local_ds, strFedTaxId, PayperiodNumber, PayrollYear, strPayFreqType);

    for (int i = 0; i < lstArray.Count; i++)
    {
        //string strTrim = strBnkArray.ToString().TrimEnd(',');
        strBankAccntType = "BankAccountTypeID='" + lstArray[i].ToString() + "'";
        dRow = local_ds.Tables[0].Select(strBankAccntType);
    }
</code>```

Body:
I wrote the following code but i am getting the error as i mentioned can any one tell

protected void btnGenerate_Click(object sender, EventArgs e)
{
    DataRow[] dRow;
    DataTable dt = new DataTable();
    foreach (GridViewRow grRow in grdACH.Rows)
    {
        CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
        if (chkItem.Checked)
        {
            chkItm = true;
            chkcnt++;
            strBankTypeID = ((Label)grRow.FindControl("lblBankType")).Text.ToString();
            strBnkArray.Append(strBankTypeID);
            strBnkArray.Append(",");
        }
    }
    oEmpDeposits.getEmpDepositDetails(out local_ds, strFedTaxId, PayperiodNumber, PayrollYear, strPayFreqType);

for (int i = 0; i < local_ds.Tables[0].Rows.Count; i++)
    {
        string strTrim = strBnkArray.ToString().TrimEnd(',');
        strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        if (strTrim.Contains("BankAccountTypeID=',"))
        {
            strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        }

        dRow = local_ds.Tables[0].Select(strTrim);
    }
}

Body:
WHy don't you use ArrayList instead of String array. So that it will be easy to manipulate

Sample

if (chkItem.Checked)
{
  chkItm = true;
  chkcnt++;
  strBankTypeID += ((Label)grRow.FindControl("lblBankType")).Text.ToString();
  ArrayList lstArray=new ArrayList();
  lstArray.Add(strBankTypeID);
}

Later

 oEmpDeposits.getEmpDepositDetails(out local_ds, strFedTaxId, PayperiodNumber, PayrollYear, strPayFreqType);

    for (int i = 0; i < lstArray.Count; i++)
    {
        //string strTrim = strBnkArray.ToString().TrimEnd(',');
        strBankAccntType = "BankAccountTypeID='" + lstArray[i].ToString() + "'";
        dRow = local_ds.Tables[0].Select(strBankAccntType);
    }


问:
How to deserialize JSON to IList<KeyValuePair<string, object>> with whitespaces in key?
I have a big problem with deserializing my JSON to an object. It should be deserialized to IList<KeyValuePair<string, object>> the problem is that the keys have white spaces.

```<code>"spec": {
         "SOMETHING WITH SPACES" : "10"
         etc.
         ...
}
</code>```

public class SomeObject
{
...
public IList<KeyValuePair<string, object>> spec{ get; set; }
...
}
```

<p>Deserializing code:</p>

<pre class="lang-cs prettyprint-override"><code>var sr = new ServiceStack.Text.JsonSerializer<SomeObject>();
var esResult = sr.DeserializeFromString(responseJson);
</code>```

responseJson is a GET from ElasticSearch.

What I get to my field it is null.
If I have key without whitespaces it's deserializing normally and I'm getting my IList<KeyValuePair<string, object>>

答:
I guess your JSON serialiazer makes some trouble. I'd recommend to use Newtonsoft.Json (in NuGet)
I've tried following code, and it works fine:

```<code>        var o1 = new SomeObject() { spec = new List<KeyValuePair<string, object>>() };
        o1.spec.Add(new KeyValuePair<string, object>("test with spaces", 10));

        var r1 = Newtonsoft.Json.JsonConvert.SerializeObject(o1);
        Console.WriteLine(r1);
        var o2 = Newtonsoft.Json.JsonConvert.DeserializeObject<SomeObject>(r1);
        var r2 = Newtonsoft.Json.JsonConvert.SerializeObject(o2);
        Console.WriteLine(r2);
</code>```

The outcome is

```<code>{"spec":[{"Key":"test with spaces","Value":10}]}
{"spec":[{"Key":"test with spaces","Value":10}]}
</code>```

No null values, all works fine.

EDIT: I actually see no reason, why spaces should be any problem at all. They are just part of the string.

Body:
I have a big problem with deserializing my JSON to an object. It should be deserialized to IList<KeyValuePair<string, object>> the problem is that the keys have white spaces.

"spec": {
         "SOMETHING WITH SPACES" : "10"
         etc.
         ...
}

public class SomeObject
{
...
public IList<KeyValuePair<string, object>> spec{ get; set; }
...
}

Deserializing code:

var sr = new ServiceStack.Text.JsonSerializer<SomeObject>();
var esResult = sr.DeserializeFromString(responseJson);

responseJson is a GET from ElasticSearch.

What I get to my field it is null.
If I have key without whitespaces it's deserializing normally and I'm getting my IList<KeyValuePair<string, object>>

Body:
I guess your JSON serialiazer makes some trouble. I'd recommend to use Newtonsoft.Json (in NuGet)
I've tried following code, and it works fine:

        var o1 = new SomeObject() { spec = new List<KeyValuePair<string, object>>() };
        o1.spec.Add(new KeyValuePair<string, object>("test with spaces", 10));

        var r1 = Newtonsoft.Json.JsonConvert.SerializeObject(o1);
        Console.WriteLine(r1);
        var o2 = Newtonsoft.Json.JsonConvert.DeserializeObject<SomeObject>(r1);
        var r2 = Newtonsoft.Json.JsonConvert.SerializeObject(o2);
        Console.WriteLine(r2);

The outcome is

{"spec":[{"Key":"test with spaces","Value":10}]}
{"spec":[{"Key":"test with spaces","Value":10}]}

No null values, all works fine.

EDIT: I actually see no reason, why spaces should be any problem at all. They are just part of the string.


问:
Send PerformanceCounter to ApplicationInsights
I'm trying to send some PerformanceCounters manually to ApplicationInsights.

I've tried posting directly to https://dc.services.visualstudio.com/v2/track with this body:

```<code>{
    "iKey": "xxxxxxx",
    "time": "2019-05-23T10:22:52.9586379Z",
    "name": "MetricData",
    "tags": {
        "ai.cloud.role": "My Test Role"
    },
    "data": {
        "baseType": "MetricData",
        "baseData": {
            "metrics": [
                {
                    "name": "performanceCounters/processCpuPercentage",
                    "value": 0.5,
                    "count": 1
                }
            ]
        }
    }
}

</code>```

This call ends up in customMetrics and I really want it to end up in performanceCounters so that I can use all the existing dashboards.

I've looked through github repos but can't find the place where is actually write ther perfconter to json.

Any ideas?

Thanks!

答:
Update: a quick test with following data via postman, and it works ok.

the data:

```<code>{
  "name": "Microsoft.ApplicationInsights.foo.PerformanceCounter",
  "time": "2019-05-28T08:22:20.6464765-07:00",
  "iKey": "xxxxx",
  "tags": { "ai.internal.sdkVersion": "1.2.0.5639" },
  "data": {
    "baseType": "PerformanceCounterData",
    "baseData": {
      "ver": 2,
      "categoryName": "Process",
      "counterName": "% Processor Time",
      "instanceName": "TestPerfCounters.vshost",
      "value": 20.0318031311035
    }
  }
}
</code>```

in postman:

in azure portal -> app insights -> logs, I can find the data in performanceCounters table.

As per the last section of this doc, please try to change "baseType" to "PerformanceCounterData".

Screenshot from the doc:

I did not have time to test it. But if any issues, please let me know.

Body:
I'm trying to send some PerformanceCounters manually to ApplicationInsights.

I've tried posting directly to https://dc.services.visualstudio.com/v2/track with this body:

{
    "iKey": "xxxxxxx",
    "time": "2019-05-23T10:22:52.9586379Z",
    "name": "MetricData",
    "tags": {
        "ai.cloud.role": "My Test Role"
    },
    "data": {
        "baseType": "MetricData",
        "baseData": {
            "metrics": [
                {
                    "name": "performanceCounters/processCpuPercentage",
                    "value": 0.5,
                    "count": 1
                }
            ]
        }
    }
}

This call ends up in customMetrics and I really want it to end up in performanceCounters so that I can use all the existing dashboards.

I've looked through github repos but can't find the place where is actually write ther perfconter to json.

Any ideas?

Thanks!

Body:
Update: a quick test with following data via postman, and it works ok.

the data:

{
  "name": "Microsoft.ApplicationInsights.foo.PerformanceCounter",
  "time": "2019-05-28T08:22:20.6464765-07:00",
  "iKey": "xxxxx",
  "tags": { "ai.internal.sdkVersion": "1.2.0.5639" },
  "data": {
    "baseType": "PerformanceCounterData",
    "baseData": {
      "ver": 2,
      "categoryName": "Process",
      "counterName": "% Processor Time",
      "instanceName": "TestPerfCounters.vshost",
      "value": 20.0318031311035
    }
  }
}

in postman:

in azure portal -> app insights -> logs, I can find the data in performanceCounters table.

As per the last section of this doc, please try to change "baseType" to "PerformanceCounterData".

Screenshot from the doc:

I did not have time to test it. But if any issues, please let me know.


问:
Overloads of std::isnan and std::isinf for integral types
Cppreference mentions the overloads of std::isnan and std::isinf (and maybe others) for integral types. This makes the following call unambiguous:

```<code>std::isnan(1);
</code>```

However, I cannot find any such overloads mentioned in the C++ Standard. I checked C++11 and the current draft, and there are only overloads for float, double, and long double.

As for compiler behavior, GCC and Clang both compile the code, but MSVC does not. Who is right? Where did the integral overload on cppreference come from?

答:
There is a paragraph at the end of the standard page for cmath:

For each set of overloaded functions within <cmath>, with the exception of abs, there shall be additional overloads sufficient to ensure:

2. Otherwise, if any argument of arithmetic type corresponding to a double parameter has type double or an integer type, then all arguments of arithmetic type corresponding to double parameters are effectively cast to double.

The integral overloads are mandatory, otherwise you would get ambiguous calls between the three floating point overloads, but how such overloads are implemented is unspecified.

Notice that other functions in the <cmath> header have correct overloads for integral types, e.g.,

```<code>std::atan(1)
</code>```

calls the templated version double atan<int,void>(int).

Body:
Cppreference mentions the overloads of std::isnan and std::isinf (and maybe others) for integral types. This makes the following call unambiguous:

std::isnan(1);

However, I cannot find any such overloads mentioned in the C++ Standard. I checked C++11 and the current draft, and there are only overloads for float, double, and long double.

As for compiler behavior, GCC and Clang both compile the code, but MSVC does not. Who is right? Where did the integral overload on cppreference come from?

Body:
There is a paragraph at the end of the standard page for cmath:

For each set of overloaded functions within <cmath>, with the exception of abs, there shall be additional overloads sufficient to ensure:

2. Otherwise, if any argument of arithmetic type corresponding to a double parameter has type double or an integer type, then all arguments of arithmetic type corresponding to double parameters are effectively cast to double.

The integral overloads are mandatory, otherwise you would get ambiguous calls between the three floating point overloads, but how such overloads are implemented is unspecified.

Notice that other functions in the <cmath> header have correct overloads for integral types, e.g.,

std::atan(1)

calls the templated version double atan<int,void>(int).


问:
Getting data from file stream in c
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

```<code>char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);
</code>```

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

答:
In general, You just have to pick a size and go with it.  Base the choice on max expected line length or record length or something like that specific to the input type.   Just make sure to check return codes and handle the case when the line is longer than you expect.

There are a few tricks you could play to get an exact size, however I can't remember ever having to use these in practice:

Do a ftell, read char by char, counting until you get to a newline, then allocate enough memory, fseek to rewind, and read the whole line.

Do a fseek to the end of the file to find the size, then rewind and read the whole thing at once into a single buffer.

Title: Getting data from file stream in c

Body:
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?


问:
Referencing keywords from another robot file
I have a resource.robot file where i want to keep my keywords here.

resource.robot

```<code>*** Settings ***
Library         Process

*** Keywords ***
Start Server
        ${result}=  Run Process  python  script.py
</code>```

Another robot file where i want to reference the keyword "Start Server" to run the process as shown below.

test.robot

```<code>*** Settings ***
Library           SeleniumLibrary
Resource          resource.robot

*** Test cases ***
Run Server
    resource.Start Server  #Keyword from resource.robot file
</code>```

But my error is that i cannot find the keyword 'Start Server' when i run test.robot. Been trying out the different post available here but still cannot resolve this problem.

Would appreciate if anyone have any idea about this situation.

答:
Managed to find out what's the issue.

I added in Test Cases section for my resource.robot file thinking that it will not affect the resource.robot file.

After pouring through the documentation, i realized that the test cases section is the issue.

Removing the test cases section for my resource.robot file solved the problem.

The higher-level structure of resource files is the same as that of
  test case files otherwise, but, of course, they cannot contain Test
  Case tables. Additionally, the Setting table in resource files can
  contain only import settings (Library, Resource, Variables) and
  Documentation. The Variable table and Keyword table are used exactly
  the same way as in test case files.

Referenced to: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#creating-user-keywords

Body:
I have a resource.robot file where i want to keep my keywords here.

resource.robot

*** Settings ***
Library         Process

*** Keywords ***
Start Server
        ${result}=  Run Process  python  script.py

Another robot file where i want to reference the keyword "Start Server" to run the process as shown below.

test.robot

*** Settings ***
Library           SeleniumLibrary
Resource          resource.robot

*** Test cases ***
Run Server
    resource.Start Server  #Keyword from resource.robot file

But my error is that i cannot find the keyword 'Start Server' when i run test.robot. Been trying out the different post available here but still cannot resolve this problem.

Would appreciate if anyone have any idea about this situation.