问:
How do I return JSON from an Azure Function
I am playing with Azure Functions. However, I feel like I'm stumped on something pretty simple. I'm trying to figure out how to return some basic JSON. I'm not sure how to create some JSON and get it back to my request.

Once upon a time,  I would create an object, populate its properties, and serialize it. So, I started down this path:

```<code>#r "Newtonsoft.Json"

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Running Function");
    try {
      log.Info($"Function ran");

      var myJSON = GetJson();

      // I want myJSON to look like:
      // {
      //   firstName:'John',
      //   lastName: 'Doe',
      //   orders: [
      //     { id:1, description:'...' },
      //     ...
      //   ]
      // }
      return ?;
    } catch (Exception ex) {
        // TODO: Return/log exception
        return null;
    }
}

public static ? GetJson()
{
  var person = new Person();
  person.FirstName = "John";
  person.LastName = "Doe";

  person.Orders = new List<Order>();
  person.Orders.Add(new Order() { Id=1, Description="..." });

  ?
}

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int Id { get; set; }
  public string Description { get; set; }
}
</code>```

However, I'm totally stuck on the serialization and return process now.I guess I'm used to returning JSON in ASP.NET MVC where everything is an Action

答:
The easiest way is perhaps to

```<code>public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/jsontestapi")] HttpRequest req,
    ILogger log)
{
    return new JsonResult(resultObject);
}
</code>```

Will set the content-type to application/json and return the json in the response body.

Body:
I am playing with Azure Functions. However, I feel like I'm stumped on something pretty simple. I'm trying to figure out how to return some basic JSON. I'm not sure how to create some JSON and get it back to my request.

Once upon a time,  I would create an object, populate its properties, and serialize it. So, I started down this path:

#r "Newtonsoft.Json"

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Running Function");
    try {
      log.Info($"Function ran");

      var myJSON = GetJson();

      // I want myJSON to look like:
      // {
      //   firstName:'John',
      //   lastName: 'Doe',
      //   orders: [
      //     { id:1, description:'...' },
      //     ...
      //   ]
      // }
      return ?;
    } catch (Exception ex) {
        // TODO: Return/log exception
        return null;
    }
}

public static ? GetJson()
{
  var person = new Person();
  person.FirstName = "John";
  person.LastName = "Doe";

  person.Orders = new List<Order>();
  person.Orders.Add(new Order() { Id=1, Description="..." });

  ?
}

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int Id { get; set; }
  public string Description { get; set; }
}

However, I'm totally stuck on the serialization and return process now.I guess I'm used to returning JSON in ASP.NET MVC where everything is an Action

Body:
The easiest way is perhaps to

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/jsontestapi")] HttpRequest req,
    ILogger log)
{
    return new JsonResult(resultObject);
}

Will set the content-type to application/json and return the json in the response body.


来源: stackexchange

问:
Time measuring overhead in Java
When measuring elapsed time on a low level, I have the choice of using any of these:

```<code>System.currentTimeMillis();
System.nanoTime();
</code>```

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...

答:
System.currentTimeMillis() is usually really fast (afaik 5-6 cpu cycles but i don't know where i have read this any more), but it's resolution varies on different plattforms.

So if you need high precision go for nanoTime(), if you are worried about overhead go for currentTimeMillis().

ContentLicense: CC BY-SA 3.0

Title: Time measuring overhead in Java

Body:
When measuring elapsed time on a low level, I have the choice of using any of these:

System.currentTimeMillis();
System.nanoTime();

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...


问:
Is it possible to force data immutability in a python function?
Say I define a list object and only want it to be read-only in a function I define. In C++, you'd do this with a const reference. Is there any way to do this with a python function? Does this make sense with respect to writing "pythonic" code or am I just trying to apply a C++ paradigm incorrectly?</p>

答:
Using a tuple is the most common way to do this, as explained in the other answers.  Assuming you are starting with a list instance, other possible strategies include:

if the role of the list in the function is just to be looped over, pass an iterator rather than the list itself - iterator = iter(my_list).  Note that the you can only loop over the iterator once; if you need to loop more than once you could pass a generator that repeatedly yields iter(my_list).

pass copy of the list instead of the list itself: new_list = my_list.copy() or new_list = my_list[:].  This may not be a good strategy for very large lists, due to memory consumption.

Whichever method you choose - even tuples - be aware that these approaches all assume that the elements in the collection are themselves immutable, for example integers and strings.  If the elements are mutable then they can be mutated (but not replaced):

```<code>>>> t = ([1], [1,2])
>>> t[0] = 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t[0][0] = 6
>>> t
([6], [1, 2])

>>> L = [[1], [1, 2]]
>>> for x in iter(L):
...     x[0] += 1
...
>>> L
[[2], [2, 2]]

>>> L = [[1], [1, 2]]
>>> copy = L.copy()
>>> for x in copy:
...     x[0] += 1
...
>>> L
[[2], [2, 2]]
>>>

>>> copy[0] = 42
>>> copy
[42, [2, 2]]
>>> L
[[2], [2, 2]]
</code>```

You can workaround this by using copy.deepcopy, but again at a cost in memory.

ContentLicense: CC BY-SA 4.0

Body:
Using a tuple is the most common way to do this, as explained in the other answers.  Assuming you are starting with a list instance, other possible strategies include:

if the role of the list in the function is just to be looped over, pass an iterator rather than the list itself - iterator = iter(my_list).  Note that the you can only loop over the iterator once; if you need to loop more than once you could pass a generator that repeatedly yields iter(my_list).

pass copy of the list instead of the list itself: new_list = my_list.copy() or new_list = my_list[:].  This may not be a good strategy for very large lists, due to memory consumption.

Whichever method you choose - even tuples - be aware that these approaches all assume that the elements in the collection are themselves immutable, for example integers and strings.  If the elements are mutable then they can be mutated (but not replaced):

>>> t = ([1], [1,2])
>>> t[0] = 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t[0][0] = 6
>>> t
([6], [1, 2])

>>> L = [[1], [1, 2]]
>>> for x in iter(L):
...     x[0] += 1
...
>>> L
[[2], [2, 2]]

>>> L = [[1], [1, 2]]
>>> copy = L.copy()
>>> for x in copy:
...     x[0] += 1
...
>>> L
[[2], [2, 2]]
>>>

>>> copy[0] = 42
>>> copy
[42, [2, 2]]
>>> L
[[2], [2, 2]]

You can workaround this by using copy.deepcopy, but again at a cost in memory.


问:
How to able to select and input at the same time in the same line?
I have done the code which able to select only

```<code><div class="form-group">
                        <label for="editAppointmentContact" class="col-sm-2 control-label">Customer Name</label>
                        <div class="col-sm-10">
                            <select class="form-control select2contact" id="editAppointmentContact" ></select>
                        </div>
                    </div>
</code>```

and the other line to input

```<code><div class="form-group">
                        <label for="editAppointmentContact" class="col-sm-2 control-label">Customer Name</label>
                        <div class="col-sm-10">
                            <input class="form-control"  id="editAppointmentContact" type="text" >
                        </div>
                    </div>
</code>```

How can I make these two select and input at the same time in the same line?

答:
Like you use bootstrap, you can use form-inline. Look the docs :

https://getbootstrap.com/docs/4.0/components/forms/#inline-forms

Try to adapt this layout to your case.

(And I give you an advice, you shouldn't use 2 times the same id in html for different element, as you did with select and text input)

Hope it will helps,
Best regards !

Body:
I have done the code which able to select only

                        Customer Name

                            <select class="form-control select2contact" id="editAppointmentContact" ></select>

and the other line to input

                        Customer Name

                            <input class="form-control"  id="editAppointmentContact" type="text" >

How can I make these two select and input at the same time in the same line?


问:
How To Find Time Difference using Chrono library in Rust
I have a Rust program where I want to do some simple benchmarking with start time and end time!

use chrono::{NaiveTime, Utc};

fn main() {
    let start_time: NaiveTime = Utc::now().time();
    let end_time: NaiveTime = Utc::now().time();
    println!("Total time taken to run is {}", end_time - start_time);
}
```

<p>The code above prints as:</p>

<pre class="lang-none prettyprint-override"><code>Total time taken to run is PT520.532696S
</code>```

I guess it is 520 seconds if I'm not wrong, but how can I convert that into minutes? Is there a better way?

答:
A simple look to the doc give the answer:

use chrono::Utc;

fn main() {
    let start_time = Utc::now().time();
    let end_time = Utc::now().time();
    let diff = end_time - start_time;
    println!("Total time taken to run is {}", diff.num_minutes());
}
```

but be aware that it's not a good way to mesure time in a monotonic way, this code could show -5 minutes if user change the system date somehow. Also call time() remove the information of the date, and this is strange when you use chrono because generally you don't want to ignore the date so just remove time() call.

Body:
I have a Rust program where I want to do some simple benchmarking with start time and end time!

use chrono::{NaiveTime, Utc};

fn main() {
    let start_time: NaiveTime = Utc::now().time();
    let end_time: NaiveTime = Utc::now().time();
    println!("Total time taken to run is {}", end_time - start_time);
}

The code above prints as:

Total time taken to run is PT520.532696S

I guess it is 520 seconds if I'm not wrong, but how can I convert that into minutes? Is there a better way?

Body:
A simple look to the doc give the answer:

use chrono::Utc;

fn main() {
    let start_time = Utc::now().time();
    let end_time = Utc::now().time();
    let diff = end_time - start_time;
    println!("Total time taken to run is {}", diff.num_minutes());
}

but be aware that it's not a good way to mesure time in a monotonic way, this code could show -5 minutes if user change the system date somehow. Also call time() remove the information of the date, and this is strange when you use chrono because generally you don't want to ignore the date so just remove time() call.


问:
Decrement with setInterval in for loop
Using this construction of code, how to decrement as a stopwatch the inserted  number of the the user with an interval of 1 second. I have created this script but i don't get the necessary result. Which is the issue of the code?

  var seconds = prompt();
    setInterval(function () {
        for (var i = seconds; i>0; i--){
            console.log(i)
        }
    },1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="result"></p></code>```

答:
You could take a function which checks the value and exits the timer interval.

It works in two parts, first set an interval and then clear the interval.

Inside of the callback show the value and decrement it. Then check if the value is smaller than zero and clear the interval in this case.

You do not need a for loop inside of the callback, because you want to display only one value.

var seconds = +prompt(),
    interval = setInterval(function () {
        document.getElementById('result').innerHTML = seconds;
        if (--seconds < 0) clearInterval(interval);
    }, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="result"></p></code>```

Title: Decrement with setInterval in for loop

Body:
You could take a function which checks the value and exits the timer interval.

It works in two parts, first set an interval and then clear the interval.

Inside of the callback show the value and decrement it. Then check if the value is smaller than zero and clear the interval in this case.

You do not need a for loop inside of the callback, because you want to display only one value.

var seconds = +prompt(),
    interval = setInterval(function () {
        document.getElementById('result').innerHTML = seconds;
        if (--seconds < 0) clearInterval(interval);
    }, 1000);

<p id="result"></p>


问:
How to load Image data from s3 bucket to sagemaker notebook?
I just started to use aws sagemaker. I tried to import images from my s3 bucket to sagemaker notebook. But I can't import images to the notebook. my image location is s3://my_bucket/train how can I import the train folder from the given path to my sagemaker notebook. I've gone through some of  the solution in here and the solutions are for CSV file. All the images in my S3 bucket are in .jpeg format.

答:
you could use s3fs to easily access your bucket as well as an image file in it.

from PIL import Image
import s3fs

fs = s3fs.S3FileSystem()

# To List 5 files in your accessible bucket
fs.ls('s3://bucket-name/data/')[:5]

# open it directly
with fs.open(f's3://bucket-name/data/image.png') as f:
    display(Image.open(f))
```


问:
Saving data from arrays into csv file
I made a program to save two arrays into csv file using pandas data frame in python so that I could record all the data.

I tried the code listed below.

```<code> U_8=[]
 start=[]
 U_8.append(d)
 start.append(str(time.time()))
 x=pd.DataFrame({'1st':U_8,  'Time Stamp':start})
 export_csv = x.to_csv (r'/home/pi/Frames/q8.csv', index = None,
 header=True)
</code>```

Every time the program is closed and run again , it overwrites the previous values stored in the csv file. I expected it to save the new values along with the previous ones. How could I store the past and present value in this csv file.

答:
In order to append to a csv instead of writing, pass mode='a' to df.to_csv. The default mode is 'w' which overwrites any existing csv with the same filename. Plain appending, however, appends the column headers as well which will appear as values in your csv. To mitigate that, pass header=False in your subsequent runs: df.to_csv(data, mode='a', header=False).

Another way is to read your original DataFrame and use pd.concat to join it with your new results. The workflow will then be as such:

Read the original csv into a DataFrame.

Create a DataFrame with new results.

Concatenate the two DataFrames.

Write the resulting DataFrame to csv.

Assigning the return value of .to_csv to a variable is not necessary. As in df.to_csv(data) will still export to csv.

Title: Saving data from arrays into csv file

Body:
I made a program to save two arrays into csv file using pandas data frame in python so that I could record all the data.

I tried the code listed below.

 U_8=[]
 start=[]
 U_8.append(d)
 start.append(str(time.time()))
 x=pd.DataFrame({'1st':U_8,  'Time Stamp':start})
 export_csv = x.to_csv (r'/home/pi/Frames/q8.csv', index = None,
 header=True)

Every time the program is closed and run again , it overwrites the previous values stored in the csv file. I expected it to save the new values along with the previous ones. How could I store the past and present value in this csv file.


问:
Performance impacts of having class level url annotations
Iam curious about internal working of Spring request mapping . Does having a requestmapping annotation at class level speed up resolving controllers for a request ?

How @RequestMapping internally works in Spring Boot? - read this answer and similar ones.Are controllers and urls mapped during initial startup and stored in a registry ?Because I  Found these log traces while starting a spring boot application .

LogTrace :
s.w.s.m.m.a.RequestMappingHandlerMapping :  Mapped "{[/employeedetails/{name}/{id} || /employeedetails],methods=[GET],produces=[application/json]}" onto public java.util.HashMap com.example.controller.EmployeeController.getEmployees(java.util.Optional,java.lang.String) throws java.lang.InterruptedException
2019-06-01 13:32:48.289  INFO 60719 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)

Are controllers+methods  and urls are mapped initially during startup or they are iterated everytime for a request? I wanted to know whether having a class level request annotation makes any difference during request mapping to controller.

答:
Are controllers+methods and urls are mapped initially during startup
  or they are iterated everytime for a request?

With default HandlerMapping implementation, Url mappings of Spring controllers are done at startup.  That would make no sense to do that at each request invocation since the url mapping cannot change once the container was started.

Beyond this question, consider Controllers as beans and these are set/initialized by Spring a single time : at container startup.
So consider the class level annotation for @RequestMapping simply as a shortcut to be dry.

Here is a code that should interest you : AbstractUrlHandlerMapping.getHandlerInternal() used under the hood by the default implementation of HandlerMapping :

```<code>@Override
@Nullable
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
    Object handler = lookupHandler(lookupPath, request);
    if (handler == null) {
        // We need to care for the default handler directly, since we need to
        // expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.
        Object rawHandler = null;
        if ("/".equals(lookupPath)) {
            rawHandler = getRootHandler();
        }
        if (rawHandler == null) {
            rawHandler = getDefaultHandler();
        }
        if (rawHandler != null) {
            // Bean name or resolved handler?
            if (rawHandler instanceof String) {
                String handlerName = (String) rawHandler;
                rawHandler = obtainApplicationContext().getBean(handlerName);
            }
            validateHandler(rawHandler, request);
            handler = buildPathExposingHandler(rawHandler, lookupPath, lookupPath, null);
        }
    }
    if (handler != null && logger.isDebugEnabled()) {
        logger.debug("Mapping [" + lookupPath + "] to " + handler);
    }
    else if (handler == null && logger.isTraceEnabled()) {
        logger.trace("No handler mapping found for [" + lookupPath + "]");
    }
    return handler;
}
</code>```

The interesting part is that the handler is created a single time in the whole life of the bean :

```<code>if (handler == null) {
  // init handler...
}
return handler;
</code>```

Note that the HandlerMapping interface that defines getHandler() specifies that you could create your own logic for the mapping resolution :

Interface to be implemented by objects that define a mapping between
  requests and handler objects. This class can be implemented by
  application developers, although this is not necessary, as
  BeanNameUrlHandlerMapping and RequestMappingHandlerMapping are
  included in the framework. The former is the default if no
  HandlerMapping bean is registered in the application context.
  HandlerMapping implementations can support mapped interceptors but do
  not have to.

So not caching url mappings is fairly possible by creating your own implementation of handler mapping , but that is of course not the behavior of the default implementation for fair reasons.

Body:
Are controllers+methods and urls are mapped initially during startup
  or they are iterated everytime for a request?

With default HandlerMapping implementation, Url mappings of Spring controllers are done at startup.  That would make no sense to do that at each request invocation since the url mapping cannot change once the container was started.

Beyond this question, consider Controllers as beans and these are set/initialized by Spring a single time : at container startup.
So consider the class level annotation for @RequestMapping simply as a shortcut to be dry.

Here is a code that should interest you : AbstractUrlHandlerMapping.getHandlerInternal() used under the hood by the default implementation of HandlerMapping :

@Override
@Nullable
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
    Object handler = lookupHandler(lookupPath, request);
    if (handler == null) {
        // We need to care for the default handler directly, since we need to
        // expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.
        Object rawHandler = null;
        if ("/".equals(lookupPath)) {
            rawHandler = getRootHandler();
        }
        if (rawHandler == null) {
            rawHandler = getDefaultHandler();
        }
        if (rawHandler != null) {
            // Bean name or resolved handler?
            if (rawHandler instanceof String) {
                String handlerName = (String) rawHandler;
                rawHandler = obtainApplicationContext().getBean(handlerName);
            }
            validateHandler(rawHandler, request);
            handler = buildPathExposingHandler(rawHandler, lookupPath, lookupPath, null);
        }
    }
    if (handler != null && logger.isDebugEnabled()) {
        logger.debug("Mapping [" + lookupPath + "] to " + handler);
    }
    else if (handler == null && logger.isTraceEnabled()) {
        logger.trace("No handler mapping found for [" + lookupPath + "]");
    }
    return handler;
}

The interesting part is that the handler is created a single time in the whole life of the bean :

if (handler == null) {
  // init handler...
}
return handler;

Note that the HandlerMapping interface that defines getHandler() specifies that you could create your own logic for the mapping resolution :

Interface to be implemented by objects that define a mapping between
  requests and handler objects. This class can be implemented by
  application developers, although this is not necessary, as
  BeanNameUrlHandlerMapping and RequestMappingHandlerMapping are
  included in the framework. The former is the default if no
  HandlerMapping bean is registered in the application context.
  HandlerMapping implementations can support mapped interceptors but do
  not have to.

So not caching url mappings is fairly possible by creating your own implementation of handler mapping , but that is of course not the behavior of the default implementation for fair reasons.


问:
How can I save a value from MySQL database into a .txt file when a download button is clicked?
I am just getting started with MySQL and PHP, I created a table "Joke" in my database and I showed the data in my PHP server side with this code:

```<code>$result = mysqli_query($link, 'SELECT joketext FROM joke');

while ($row = mysqli_fetch_array($result))
{
  $jokes[] = $row['joketext'];
}

include 'jokes.html.php';
</code>```

And HTML code:

```<code><p>Here are all the jokes in the database:</p>
    <?php foreach ($jokes as $joke): ?>
      <blockquote><p>
        <?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); ?>
      </p></blockquote>
    <?php endforeach; ?>
</code>```

That's worked for me, but now I want to add a button "download" beside each joke to download it in .txt file.

答:
You can implode() the $jokes array:

```<code>$all_jokes = implode("\n", $jokes);
file_put_contents("all_jokes.txt", $all_jokes);
</code>```

and in your html page:

```<code><a href="all_jokes.txt">Download all</a>
</code>```

references here:

https://www.w3schools.com/php/func_filesystem_file_put_contents.asp
https://php.net/manual/en/function.implode.php

Body:
I am just getting started with MySQL and PHP, I created a table "Joke" in my database and I showed the data in my PHP server side with this code:

$result = mysqli_query($link, 'SELECT joketext FROM joke');

while ($row = mysqli_fetch_array($result))
{
  $jokes[] = $row['joketext'];
}

include 'jokes.html.php';

And HTML code:

Here are all the jokes in the database:

    <?php foreach ($jokes as $joke): ?>

        <?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); ?>

    <?php endforeach; ?>

That's worked for me, but now I want to add a button "download" beside each joke to download it in .txt file.

Body:
You can implode() the $jokes array:

$all_jokes = implode("\n", $jokes);
file_put_contents("all_jokes.txt", $all_jokes);

and in your html page:

<a href="all_jokes.txt">Download all</a>

references here:

https://www.w3schools.com/php/func_filesystem_file_put_contents.asp
https://php.net/manual/en/function.implode.php


问:
compareTo() vs. equals()
When testing for equality of String's in Java I have always used equals() because to me this seems to be the most natural method for it. After all, its name already says what it is intended to do. However, a colleague of mine recently told me had been taught to use compareTo() == 0 instead of equals(). This feels unnatural (as compareTo() is meant to provide an ordering and not compare for equality) and even somewhat dangerous (because compareTo() == 0 does not necessarily imply equality in all cases, even though I know it does for String's) to me.

He did not know why he was taught to use compareTo() instead of equals() for String's, and I could also not find any reason why. Is this really a matter of personal taste, or is there any real reason for either method?

答: I believe equals and equalsIgnoreCase methods of String return true and false which is useful if you wanted to compare the values of the string object, But in case of implementing compareTo and compareToIgnoreCase methods returns positive, negative and zero value which will be useful in case of sorting.

Title: compareTo() vs. equals()


问:
Laravel 5.5 make a search of multiple entities
I have a Laravel 5.5 project. The idea of the project consist on make a search page for finding information about the second world war. I have data of soldiers, historic documents and fights.

The idea of the search page is to enter one word or a set of words (like in Google) and filter the soldiers, documents and fights names in one query.

I have been investigating but all what I have found is about making search from one entity, and I need a search for three entities.

I have seen the official documentation of Laravel https://laravel.com/docs/5.5/scout, but seems that works for one entity.

My database is relational MySQL. Is there any way to solve this problem?

答:
You can do it with my package if you ready to add Elasticsearch to your project
https://github.com/matchish/laravel-scout-elasticsearch#search-amongst-multiple-models</p>


问:
Converting CSV to JSON in bash
Trying to convert a CSV file into a JSON

Here is two sample lines :

```<code>-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata
</code>```

I would like to get something like :

```<code>"occurrences": [
                 {
                "position": [-21.3214077, 55.4851413],
                "taxo": {
                    "espece": "Ruizia cordata"
                 },
                 ...
             }]
</code>```

Here is my script :

```<code>    echo '"occurences": [ '

cat se.csv | while read -r line
  do
      IFS=';' read -r -a array <<< $line;
      echo -n -e '{ "position": [' ${array[0]}
      echo -n -e ',' ${array[1]} ']'
      echo -e ', "taxo": {"espece":"' ${array[2]} '"'
done
echo "]";
</code>```

I get really strange results :

```<code>   "occurences": [
 ""position": [ -21.3214077, 55.4851413 ], "taxo": {"espece":" Ruizia cordata
 ""position": [ -21.3213078, 55.4849803 ], "taxo": {"espece":" Cossinia pinnata
</code>```

What is wrong with my code ?

答:
If you want to go crazy, you can write a parser using jq. Here's my implementation which can be thought of as the inverse of the @csv filter. Throw this into your .jq file.

```<code>def do_if(pred; update):
    if pred then update else . end;
def _parse_delimited($_delim; $_quot; $_nl; $_skip):
    [($_delim, $_quot, $_nl, $_skip)|explode[]] as [$delim, $quot, $nl, $skip] |
    [0,1,2,3,4,5] as [$s_start,$s_next_value,$s_read_value,$s_read_quoted,$s_escape,$s_final] |
    def _append($arr; $value):
        $arr + [$value];
    def _do_start($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; [""])]
        elif $c == $delim then
            [$s_next_value, null, [""], .[3]]
        elif $c == $quot then
            [$s_read_quoted, [], [], .[3]]
        else
            [$s_read_value, [$c], [], .[3]]
        end;
    def _do_next_value($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; _append(.[2]; ""))]
        elif $c == $delim then
            [$s_next_value, null, _append(.[2]; ""), .[3]]
        elif $c == $quot then
            [$s_read_quoted, [], .[2], .[3]]
        else
            [$s_read_value, [$c], .[2], .[3]]
        end;
    def _do_read_value($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif $c == $delim then
            [$s_next_value, null, _append(.[2]; .[1]|implode), .[3]]
        else
            [$s_read_value, _append(.[1]; $c), .[2], .[3]]
        end;
    def _do_read_quoted($c):
        if $c == $quot then
            [$s_escape, .[1], .[2], .[3]]
        else
            [$s_read_quoted, _append(.[1]; $c), .[2], .[3]]
        end;
    def _do_escape($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif $c == $delim then
            [$s_next_value, null, _append(.[2]; .[1]|implode), .[3]]
        else
            [$s_read_quoted, _append(.[1]; $c), .[2], .[3]]
        end;
    def _do_final($c):
        .;
    def _do_finalize:
        if .[0] == $s_start then
            [$s_final, null, null, .[3]]
        elif .[0] == $s_next_value then
            [$s_final, null, null, _append(.[3]; [""])]
        elif .[0] == $s_read_value then
            [$s_final, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif .[0] == $s_read_quoted then
            [$s_final, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif .[0] == $s_escape then
            [$s_final, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        else # .[0] == $s_final
            .
        end;
    reduce explode[] as $c (
        [$s_start,null,null,[]];
        do_if($c != $skip;
            if .[0] == $s_start then
                _do_start($c)
            elif .[0] == $s_next_value then
                _do_next_value($c)
            elif .[0] == $s_read_value then
                _do_read_value($c)
            elif .[0] == $s_read_quoted then
                _do_read_quoted($c)
            elif .[0] == $s_escape then
                _do_escape($c)
            else # .[0] == $s_final
                _do_final($c)
            end
        )
    )
    | _do_finalize[3][];
def parse_delimited($delim; $quot; $nl; $skip):
    _parse_delimited($delim; $quot; $nl; $skip);
def parse_delimited($delim; $quot; $nl):
    parse_delimited($delim; $quot; $nl; "\r");
def parse_delimited($delim; $quot):
    parse_delimited($delim; $quot; "\n");
def parse_delimited($delim):
    parse_delimited($delim; "\"");
def parse_csv:
    parse_delimited(",");
</code>```

For your data, you would want to change the delimiter to semicolons.

```<code>$ cat se.csv
-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata
$ jq -R 'parse_delimited(";")' se.csv
[
  "-21.3214077",
  "55.4851413",
  "Ruizia cordata"
]
[
  "-21.3213078",
  "55.4849803",
  "Cossinia pinnata"
]
</code>```

This will work fine for most inputs to parse a line at a time, but if your data has literal newlines, you will want to read the entire file as a string.

```<code>$ cat input.csv
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
$ jq -Rs 'parse_csv' input.csv
[
  "Year",
  "Make",
  "Model",
  "Description",
  "Price"
]
[
  "1997",
  "Ford",
  "E350",
  "ac, abs, moon",
  "3000.00"
]
[
  "1999",
  "Chevy",
  "Venture \"Extended Edition\"",
  "",
  "4900.00"
]
[
  "1999",
  "Chevy",
  "Venture \"Extended Edition, Very Large\"",
  "",
  "5000.00"
]
[
  "1996",
  "Jeep",
  "Grand Cherokee",
  "MUST SELL!\nair, moon roof, loaded",
  "4799.00"
]
</code>```

Title: Converting CSV to JSON in bash

Body:
Trying to convert a CSV file into a JSON

Here is two sample lines :

-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata

I would like to get something like :

"occurrences": [
                 {
                "position": [-21.3214077, 55.4851413],
                "taxo": {
                    "espece": "Ruizia cordata"
                 },
                 ...
             }]

Here is my script :

    echo '"occurences": [ '

cat se.csv | while read -r line
  do
      IFS=';' read -r -a array <<< $line;
      echo -n -e '{ "position": [' ${array[0]}
      echo -n -e ',' ${array[1]} ']'
      echo -e ', "taxo": {"espece":"' ${array[2]} '"'
done
echo "]";

I get really strange results :

   "occurences": [
 ""position": [ -21.3214077, 55.4851413 ], "taxo": {"espece":" Ruizia cordata
 ""position": [ -21.3213078, 55.4849803 ], "taxo": {"espece":" Cossinia pinnata

What is wrong with my code ?

Body:
If you want to go crazy, you can write a parser using jq. Here's my implementation which can be thought of as the inverse of the @csv filter. Throw this into your .jq file.

def do_if(pred; update):
    if pred then update else . end;
def _parse_delimited($_delim; $_quot; $_nl; $_skip):
    [($_delim, $_quot, $_nl, $_skip)|explode[]] as [$delim, $quot, $nl, $skip] |
    [0,1,2,3,4,5] as [$s_start,$s_next_value,$s_read_value,$s_read_quoted,$s_escape,$s_final] |
    def _append($arr; $value):
        $arr + [$value];
    def _do_start($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; [""])]
        elif $c == $delim then
            [$s_next_value, null, [""], .[3]]
        elif $c == $quot then
            [$s_read_quoted, [], [], .[3]]
        else
            [$s_read_value, [$c], [], .[3]]
        end;
    def _do_next_value($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; _append(.[2]; ""))]
        elif $c == $delim then
            [$s_next_value, null, _append(.[2]; ""), .[3]]
        elif $c == $quot then
            [$s_read_quoted, [], .[2], .[3]]
        else
            [$s_read_value, [$c], .[2], .[3]]
        end;
    def _do_read_value($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif $c == $delim then
            [$s_next_value, null, _append(.[2]; .[1]|implode), .[3]]
        else
            [$s_read_value, _append(.[1]; $c), .[2], .[3]]
        end;
    def _do_read_quoted($c):
        if $c == $quot then
            [$s_escape, .[1], .[2], .[3]]
        else
            [$s_read_quoted, _append(.[1]; $c), .[2], .[3]]
        end;
    def _do_escape($c):
        if $c == $nl then
            [$s_start, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif $c == $delim then
            [$s_next_value, null, _append(.[2]; .[1]|implode), .[3]]
        else
            [$s_read_quoted, _append(.[1]; $c), .[2], .[3]]
        end;
    def _do_final($c):
        .;
    def _do_finalize:
        if .[0] == $s_start then
            [$s_final, null, null, .[3]]
        elif .[0] == $s_next_value then
            [$s_final, null, null, _append(.[3]; [""])]
        elif .[0] == $s_read_value then
            [$s_final, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif .[0] == $s_read_quoted then
            [$s_final, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        elif .[0] == $s_escape then
            [$s_final, null, null, _append(.[3]; _append(.[2]; .[1]|implode))]
        else # .[0] == $s_final
            .
        end;
    reduce explode[] as $c (
        [$s_start,null,null,[]];
        do_if($c != $skip;
            if .[0] == $s_start then
                _do_start($c)
            elif .[0] == $s_next_value then
                _do_next_value($c)
            elif .[0] == $s_read_value then
                _do_read_value($c)
            elif .[0] == $s_read_quoted then
                _do_read_quoted($c)
            elif .[0] == $s_escape then
                _do_escape($c)
            else # .[0] == $s_final
                _do_final($c)
            end
        )
    )
    | _do_finalize[3][];
def parse_delimited($delim; $quot; $nl; $skip):
    _parse_delimited($delim; $quot; $nl; $skip);
def parse_delimited($delim; $quot; $nl):
    parse_delimited($delim; $quot; $nl; "\r");
def parse_delimited($delim; $quot):
    parse_delimited($delim; $quot; "\n");
def parse_delimited($delim):
    parse_delimited($delim; "\"");
def parse_csv:
    parse_delimited(",");

For your data, you would want to change the delimiter to semicolons.

$ cat se.csv
-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata
$ jq -R 'parse_delimited(";")' se.csv
[
  "-21.3214077",
  "55.4851413",
  "Ruizia cordata"
]
[
  "-21.3213078",
  "55.4849803",
  "Cossinia pinnata"
]

This will work fine for most inputs to parse a line at a time, but if your data has literal newlines, you will want to read the entire file as a string.

$ cat input.csv
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
$ jq -Rs 'parse_csv' input.csv
[
  "Year",
  "Make",
  "Model",
  "Description",
  "Price"
]
[
  "1997",
  "Ford",
  "E350",
  "ac, abs, moon",
  "3000.00"
]
[
  "1999",
  "Chevy",
  "Venture \"Extended Edition\"",
  "",
  "4900.00"
]
[
  "1999",
  "Chevy",
  "Venture \"Extended Edition, Very Large\"",
  "",
  "5000.00"
]
[
  "1996",
  "Jeep",
  "Grand Cherokee",
  "MUST SELL!\nair, moon roof, loaded",
  "4799.00"
]


问:
how to overcome error in images array in javascript
I am trying to insert images (at present there are 7 images)into an array using a for loop and preview(display) those images in a scroll bar. the particular image from the scroll bar on click should appear in the given div.(the should be expanded to the size of the div)
this is for a certificate generator

this js code I triedenter image description here so far

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" src='index.css'>
</head>
<body>
  <div id="expandedImage" style="width:800px; height:500px;float:left;
border: 1px solid black">
  </div>
  <!-- <div id="con"></div> -->
  <div id="main" style="width:150px; height: 500px; overflow-y:
scroll;float:right">
  </div>
  <script src="index.js"></script>
</body
</html></code>```

I expect the output to be the image I click on, but the actual output is the 7th image of my array

答:
The reason why this was a problem is because JS has something called "hoarding". Basically if you write this:

```<code>if (true) {
    var x = 4;
}
</code>```

It becomes this:

```<code>var x;
if (true) {
    x = 4;
}
</code>```

To fix this you can use let insead of var

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  let img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" src='index.css'>
</head>
<body>
  <div id="expandedImage" style="width:800px; height:500px;float:left;
border: 1px solid black">
  </div>
  <!-- <div id="con"></div> -->
  <div id="main" style="width:150px; height: 500px; overflow-y:
scroll;float:right">
  </div>
  <script src="index.js"></script>
</body
</html></code>```

Body:
I am trying to insert images (at present there are 7 images)into an array using a for loop and preview(display) those images in a scroll bar. the particular image from the scroll bar on click should appear in the given div.(the should be expanded to the size of the div)
this is for a certificate generator

this js code I triedenter image description here so far

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" src='index.css'>

</body

I expect the output to be the image I click on, but the actual output is the 7th image of my array

Body:
The reason why this was a problem is because JS has something called "hoarding". Basically if you write this:

if (true) {
    var x = 4;
}

It becomes this:

var x;
if (true) {
    x = 4;
}

To fix this you can use let insead of var

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  let img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" src='index.css'>
</head>
<body>
  <div id="expandedImage" style="width:800px; height:500px;float:left;
border: 1px solid black">
  </div>
  <!-- <div id="con"></div> -->
  <div id="main" style="width:150px; height: 500px; overflow-y:
scroll;float:right">
  </div>
  <script src="index.js"></script>
</body
</html>


问:
Node.js how to use socket.io in express route
In one of my node.js script i am trying to use socket.io in express route. I found many similar questions and tried to implement the solution as suggested but nothing worked out. May be because of my lack of understanding of express routes. I followed below links,

How use socket.io in express routes with node.js

Use socket.io in expressjs routes instead of in main server.js file

This is my app.js

```<code>const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

const PORT = 3000;
server.listen(PORT);
console.log('Server is running');
var api = require('./routes/api');

//app.use('/api', api);
app.use('/api', (req, res) => {
res.sendFile(__dirname + '/api.html');
});

app.get('/', (req, res) => {
   res.send("this is home location");
});
</code>```

And route file api.js in ./routes folder

```<code>var express = require('express');
var router = express.Router();
var fs = require("fs");
var bodyParser = require('body-parser');

const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

console.log("inside api route");

router.get('/', function(req, res, next) {
console.log("api route called");

const connections = [];
var jsonobj = [{name:"john",score:345},{name:"paul",score:678}]

io.sockets.on('connection',(socket) => {
    connections.push(socket);
    console.log(' %s sockets is connected', connections.length); // this is not printing

    socket.on('disconnect', () => {
       connections.splice(connections.indexOf(socket), 1);
    });

    socket.emit('server message', jsonobj);

 });
    //res.send(jsonobj)
});

module.exports = router;
</code>```

Socket.emit is not showing data on html page i am rendering on route use. My html code is,

//api.html

```<code><!DOCTYPE html>
<html lang="en">

<body>
   <div class="container">
      <h1 class="jumbotron">
         Node js Socket io with  socket route example
      </h1>
      <div class="results">results</div>
   </div>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
   <script>
    jQuery(document).ready(function() {
       var socket = io.connect();
       var jsondata = "";

       socket.on('server message', function(data){
         console.log('got data from server',data)
         jsondata = JSON.stringify(data);
         //console.log('jsondata',jsondata)
         $('.results').html(jsondata);
       });
    });
 </script>
</body>
</html>
</code>```

Please suggest what i am supposed to get route socket data in html page.
Thanks

答:
At first glance, it looks like you are delcaring the URL prefix twice. Once in app.js and again in api.js.

Try localhost:port/api/api

If this is the case, change

router.get('/api', function(req, res, next){

to

router.get('/', function(req, res, next){

This will allow you to hit localhost:port/api and access your endpoint.

Body:
In one of my node.js script i am trying to use socket.io in express route. I found many similar questions and tried to implement the solution as suggested but nothing worked out. May be because of my lack of understanding of express routes. I followed below links,

How use socket.io in express routes with node.js

Use socket.io in expressjs routes instead of in main server.js file

This is my app.js

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

const PORT = 3000;
server.listen(PORT);
console.log('Server is running');
var api = require('./routes/api');

//app.use('/api', api);
app.use('/api', (req, res) => {
res.sendFile(__dirname + '/api.html');
});

app.get('/', (req, res) => {
   res.send("this is home location");
});

And route file api.js in ./routes folder

var express = require('express');
var router = express.Router();
var fs = require("fs");
var bodyParser = require('body-parser');

const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

console.log("inside api route");

router.get('/', function(req, res, next) {
console.log("api route called");

const connections = [];
var jsonobj = [{name:"john",score:345},{name:"paul",score:678}]

io.sockets.on('connection',(socket) => {
    connections.push(socket);
    console.log(' %s sockets is connected', connections.length); // this is not printing

    socket.on('disconnect', () => {
       connections.splice(connections.indexOf(socket), 1);
    });

    socket.emit('server message', jsonobj);

 });
    //res.send(jsonobj)
});

module.exports = router;

Socket.emit is not showing data on html page i am rendering on route use. My html code is,

//api.html

<!DOCTYPE html>

         Node js Socket io with  socket route example

results

Please suggest what i am supposed to get route socket data in html page.
Thanks


问:
Opensmile installation on ubuntu
when giving the command:

```<code>./configure CXXFLAGS=‘‘-O2 -mfpmath=sse -march=native’’ CFLAGS=‘‘-O2  -mfpmath=sse -march=native’’
</code>```

it shows me the following error:

configure: error: unrecognized option: `-mfpmath=sse'
Try `./configure --help' for more information
```

I used sse2 but yet it is not working. On opensmile installation guide it is written that this option is not supported by all compilers.

答:
The shell supports "..." and '...' (plain ASCII quotes) to quote words that contain spaces.

Your command uses fancy directional Unicode quotation marks, but not the usual “...” double quote ones, but the ‘...’ single quote version, twice: ‘‘...’’.

The shell doesn't understand those quotes, which is why configure thinks you're trying to set CXXFLAGS=‘‘-O2 and -mfpmath=sse is parsed as a separate option.

Fix:

```<code>./configure CXXFLAGS='-O2 -mfpmath=sse -march=native' CFLAGS='-O2  -mfpmath=sse -march=native'
</code>```

Title: Opensmile installation on ubuntu

Body:
when giving the command:

./configure CXXFLAGS=‘‘-O2 -mfpmath=sse -march=native’’ CFLAGS=‘‘-O2  -mfpmath=sse -march=native’’

it shows me the following error:

configure: error: unrecognized option: `-mfpmath=sse'
Try `./configure --help' for more information

I used sse2 but yet it is not working. On opensmile installation guide it is written that this option is not supported by all compilers.

Body:
The shell supports "..." and '...' (plain ASCII quotes) to quote words that contain spaces.

Your command uses fancy directional Unicode quotation marks, but not the usual “...” double quote ones, but the ‘...’ single quote version, twice: ‘‘...’’.

The shell doesn't understand those quotes, which is why configure thinks you're trying to set CXXFLAGS=‘‘-O2 and -mfpmath=sse is parsed as a separate option.

Fix:

./configure CXXFLAGS='-O2 -mfpmath=sse -march=native' CFLAGS='-O2  -mfpmath=sse -march=native'


问:
Change iFrame src on ajax complete
using jQuery's $.ajax() I want to retrieve some information from the server, and then, based on that info, change the src attribute of an iframe.

Something like:

```<code>$.ajax(
                {
                    url: "someUrl.aspx/getInfo",
                    dataType: "json",
                    data: "{'data':{'data1':'data1'}}",
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    complete: function(data, stat) {
                        if (stat == "success" )
                        {
                           var src = JSON.parse(jsondata.responseText).d.src
                           $('#myframe').attr("src",src);
                        }

                    }
                }
                );
</code>```

The page I am trying to load is returning a PDF file, so the goal is to show the user the dialog to choose between downloading or opening that file. On IE7 and 8 the browser is showing the info bar with this message : "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for options."

Changing the iframe's src attribute OUTSIDE the ajax call works fine and the dialog to choose between opening or saving the PDF is shown.

Any workarounds to avoid the info bar showing?
Thanks in advance.

答: An alternate approach that avoids both an iframe and the info bar is to simply not open the PDF automatically. In the call AJAX callback, create a regular link to the PDF file so the user can click on it directly. This should prevent IE from flagging the download.</p>

Title: Change iFrame src on ajax complete

Body:
using jQuery's $.ajax() I want to retrieve some information from the server, and then, based on that info, change the src attribute of an iframe.

Something like:

$.ajax(
                {
                    url: "someUrl.aspx/getInfo",
                    dataType: "json",
                    data: "{'data':{'data1':'data1'}}",
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    complete: function(data, stat) {
                        if (stat == "success" )
                        {
                           var src = JSON.parse(jsondata.responseText).d.src
                           $('#myframe').attr("src",src);
                        }

                    }
                }
                );

The page I am trying to load is returning a PDF file, so the goal is to show the user the dialog to choose between downloading or opening that file. On IE7 and 8 the browser is showing the info bar with this message : "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for options."

Changing the iframe's src attribute OUTSIDE the ajax call works fine and the dialog to choose between opening or saving the PDF is shown.

Any workarounds to avoid the info bar showing?
Thanks in advance.


问:
how to declare an empty numeric (number) value in javaScript
I need to create an object with some non-defined values.
I know how to declare an empty string- in example that would be a object.name. But what would be an empty numeric value. What do I need to put instead of word 'number' in object.age property to tell the javaScript it can be any number?</p>
```<code>let object = {
name : ''
age : number
}
</code>```

答:
You could take NaN, not a number as value, this values has a number type and not a usefull value.

```<code>let object = {
    name : '',
    age : NaN
};
</code>```

If you not like to use NaN, you might use null or just undefined, but the first one is an object and the second is undefined as type.

And for checking if value equals to these defines:

```<code>NaN: isNaN(object.age)
null: object.age===null
undefined: typeof object.age==="undefined"
</code>```

Body:
I need to create an object with some non-defined values.
I know how to declare an empty string- in example that would be a object.name. But what would be an empty numeric value. What do I need to put instead of word 'number' in object.age property to tell the javaScript it can be any number?

let object = {
name : ''
age : number
}

Body:
You could take NaN, not a number as value, this values has a number type and not a usefull value.

let object = {
    name : '',
    age : NaN
};

If you not like to use NaN, you might use null or just undefined, but the first one is an object and the second is undefined as type.

And for checking if value equals to these defines:

NaN: isNaN(object.age)
null: object.age===null
undefined: typeof object.age==="undefined"


问:
Image edge detection Keras model loss not improving
I have a video of droplets. I have taken the first frame and manually marked the edges. I split up the image into smaller images. I then tried to train a keras model of the small unmarked images against the small marked images.

I've tried using "dense" layers. The model trains, but the loss does not improve. When I try using the model, it just gives me a black image output.

Marked split images

Input image (frame 1)

Model summary

```<code>#################### IMPORT AND SPLIT

from cam_img_split import cam_img_split
import cv2

img_tr_in=cv2.imread('frame 1.png')
img_tr_out=cv2.imread('frame 1 so far.png')
seg_shape=[32,32]

tr_in=cam_img_split(img_tr_in,seg_shape)
tr_out=cam_img_split(img_tr_out,seg_shape)

pl=[4,20] #images selected for training

##################### NEURAL NETWORK

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import adam

b_sha=np.prod(tr_in.shape[2:5]) #batch shape

model = Sequential()
model.add(Dense(b_sha, activation='relu'))
model.add(Dense(3072, activation='softmax'))
model.add(Dense(3072, activation='softmax'))
model.add(Dense(3072, activation='softmax'))
model.add(Dense(np.prod(tr_out.shape[2:5]), activation='softmax'))
model.compile(optimizer=adam(lr=0.1), loss='mean_squared_error', metrics=['accuracy'])

tr_in_sel=tr_in[0:pl[0],0:pl[1],:,:,:]
tr_out_sel=tr_out[0:pl[0],0:pl[1],:,:,:]

tr_in_sel_flat=tr_in_sel.reshape([np.prod(pl),b_sha])   #Flattening
tr_out_sel_flat=tr_in_sel.reshape([np.prod(pl),b_sha])

tr_in_sel_flat_norm=tr_in_sel_flat/255
tr_out_sel_flat_norm=tr_out_sel_flat/255

model.fit(tr_in_sel_flat_norm, tr_out_sel_flat_norm, epochs=10, batch_size=pl[0])
</code>```

I expected an output matching the images with the marked edges. Instead I got a black image output.

答:
I solved this problem by using 7x7 sections of the image to classify the central pixel of that section as either oil or water (1 or 0). I then used the binary_crossentropy loss function to train the model.

By having a 7x7 section moving one pixel at a time across the main image, I can have a lot more training data than just segmenting the main image.

I previously tried to get a 7x7 image from another 7x7 image, which made the problem more difficult.

```<code>#IMPORT AND SPLIT

from cam_img_split import cam_img_split
from cam_pad import cam_pad
from cam_img_bow import cam_img_bow
import cv2
import numpy as np

img_tr_in=cv2.imread('frame 1.png',0)[0:767,0:767]/255
img_tr_out=cv2.imread('frame 1 so far bnw 2.png',0)[0:767,0:767]/255
img_tr_out=(cam_img_bow(img_tr_out,0.5)).astype(np.uint8)

seg_shape=[15,15] #needs to be odd and equal to each other

pl_max=img_tr_in.shape[0:2]
pl=np.array([0.15*pl_max[0],pl_max[1]]).astype(np.uint32)

pad_in=int(np.floor(seg_shape[0]/2))

img_tr_in_pad=cam_pad(img_tr_in,pad_in)

tr_in=np.zeros([pl[0],pl[1],seg_shape[0],seg_shape[1]])

for n1 in range(0,pl[0]):
        for n2 in range(0,pl[1]):
                tr_in[n1,n2]=img_tr_in_pad[n1:n1+seg_shape[0],n2:n2+seg_shape[1]]

##################### NEURAL NETWORK

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense,Dropout,Conv2D, MaxPooling2D, Flatten
from keras.optimizers import adam
from keras.utils import to_categorical
import matplotlib.pyplot as plt

pad=4

input_shape=(seg_shape[0]+2*pad,seg_shape[1]+2*pad,1)
output_shape=(1,1,1)

model = Sequential()
model.add(Conv2D(32, (3, 3),input_shape=input_shape, activation='relu'))
model.add(Conv2D(64,(3, 3), activation='relu'))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(units=2, activation='softmax'))

model.compile(optimizer=adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])

##################### FITTING THE MODEL

tr_in_flat=tr_in.reshape([pl[0]*pl[1],seg_shape[0],seg_shape[1],1])
tr_out_flat=img_tr_out.reshape([pl_max[0]*pl_max[1]])

tr_in_flat_pad=np.zeros(tr_in_flat.shape+np.array([0,2*pad,2*pad,0]))

for n3 in range(0,tr_in_flat.shape[0]):
        tr_in_flat_pad[n3,:,:,0]=cam_pad(tr_in_flat[n3,:,:,0], pad)

model.fit(tr_in_flat_pad, to_categorical(tr_out_flat[0:pl[0]*pl[1]]), epochs=5, batch_size=int(16*pl[0]),shuffle=True)

##################### PLOTTING PREDICTIONS

tr_in_full=np.zeros([pl_max[0],pl_max[1],seg_shape[0]+2*pad,seg_shape[1]+2*pad])

for n1 in range(0,pl_max[0]):
        for n2 in range(0,pl_max[1]):
                tr_in_full[n1,n2]=cam_pad(img_tr_in_pad[n1:n1+seg_shape[0],n2:n2+seg_shape[1]],pad)

tr_in_full_flat=tr_in_full.reshape([pl_max[0]*pl_max[1],seg_shape[0]+2*pad,seg_shape[1]+2*pad,1])

pred = model.predict(tr_in_full_flat)

pred_img=np.zeros(pred.shape[0])

for n1 in range(0,pred.shape[0]):
        pred_img[n1]=round(pred[n1,0])

pred_img_out=(pred_img.reshape([pl_max[0],pl_max[1]]))

plt.subplot(1,2,1)
plt.imshow(pred_img_out)

plt.subplot(1,2,2)
plt.imshow(img_tr_in)

plt.show()
</code>```

Body:
I have a video of droplets. I have taken the first frame and manually marked the edges. I split up the image into smaller images. I then tried to train a keras model of the small unmarked images against the small marked images.

I've tried using "dense" layers. The model trains, but the loss does not improve. When I try using the model, it just gives me a black image output.

Marked split images

Input image (frame 1)

Model summary

#################### IMPORT AND SPLIT

from cam_img_split import cam_img_split
import cv2

img_tr_in=cv2.imread('frame 1.png')
img_tr_out=cv2.imread('frame 1 so far.png')
seg_shape=[32,32]

tr_in=cam_img_split(img_tr_in,seg_shape)
tr_out=cam_img_split(img_tr_out,seg_shape)

pl=[4,20] #images selected for training

##################### NEURAL NETWORK

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import adam

b_sha=np.prod(tr_in.shape[2:5]) #batch shape

model = Sequential()
model.add(Dense(b_sha, activation='relu'))
model.add(Dense(3072, activation='softmax'))
model.add(Dense(3072, activation='softmax'))
model.add(Dense(3072, activation='softmax'))
model.add(Dense(np.prod(tr_out.shape[2:5]), activation='softmax'))
model.compile(optimizer=adam(lr=0.1), loss='mean_squared_error', metrics=['accuracy'])

tr_in_sel=tr_in[0:pl[0],0:pl[1],:,:,:]
tr_out_sel=tr_out[0:pl[0],0:pl[1],:,:,:]

tr_in_sel_flat=tr_in_sel.reshape([np.prod(pl),b_sha])   #Flattening
tr_out_sel_flat=tr_in_sel.reshape([np.prod(pl),b_sha])

tr_in_sel_flat_norm=tr_in_sel_flat/255
tr_out_sel_flat_norm=tr_out_sel_flat/255

model.fit(tr_in_sel_flat_norm, tr_out_sel_flat_norm, epochs=10, batch_size=pl[0])

I expected an output matching the images with the marked edges. Instead I got a black image output.

Body:
I solved this problem by using 7x7 sections of the image to classify the central pixel of that section as either oil or water (1 or 0). I then used the binary_crossentropy loss function to train the model.

By having a 7x7 section moving one pixel at a time across the main image, I can have a lot more training data than just segmenting the main image.

I previously tried to get a 7x7 image from another 7x7 image, which made the problem more difficult.

#IMPORT AND SPLIT

from cam_img_split import cam_img_split
from cam_pad import cam_pad
from cam_img_bow import cam_img_bow
import cv2
import numpy as np

img_tr_in=cv2.imread('frame 1.png',0)[0:767,0:767]/255
img_tr_out=cv2.imread('frame 1 so far bnw 2.png',0)[0:767,0:767]/255
img_tr_out=(cam_img_bow(img_tr_out,0.5)).astype(np.uint8)

seg_shape=[15,15] #needs to be odd and equal to each other

pl_max=img_tr_in.shape[0:2]
pl=np.array([0.15*pl_max[0],pl_max[1]]).astype(np.uint32)

pad_in=int(np.floor(seg_shape[0]/2))

img_tr_in_pad=cam_pad(img_tr_in,pad_in)

tr_in=np.zeros([pl[0],pl[1],seg_shape[0],seg_shape[1]])

for n1 in range(0,pl[0]):
        for n2 in range(0,pl[1]):
                tr_in[n1,n2]=img_tr_in_pad[n1:n1+seg_shape[0],n2:n2+seg_shape[1]]

##################### NEURAL NETWORK

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense,Dropout,Conv2D, MaxPooling2D, Flatten
from keras.optimizers import adam
from keras.utils import to_categorical
import matplotlib.pyplot as plt

pad=4

input_shape=(seg_shape[0]+2*pad,seg_shape[1]+2*pad,1)
output_shape=(1,1,1)

model = Sequential()
model.add(Conv2D(32, (3, 3),input_shape=input_shape, activation='relu'))
model.add(Conv2D(64,(3, 3), activation='relu'))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(units=2, activation='softmax'))

model.compile(optimizer=adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])

##################### FITTING THE MODEL

tr_in_flat=tr_in.reshape([pl[0]*pl[1],seg_shape[0],seg_shape[1],1])
tr_out_flat=img_tr_out.reshape([pl_max[0]*pl_max[1]])

tr_in_flat_pad=np.zeros(tr_in_flat.shape+np.array([0,2*pad,2*pad,0]))

for n3 in range(0,tr_in_flat.shape[0]):
        tr_in_flat_pad[n3,:,:,0]=cam_pad(tr_in_flat[n3,:,:,0], pad)

model.fit(tr_in_flat_pad, to_categorical(tr_out_flat[0:pl[0]*pl[1]]), epochs=5, batch_size=int(16*pl[0]),shuffle=True)

##################### PLOTTING PREDICTIONS

tr_in_full=np.zeros([pl_max[0],pl_max[1],seg_shape[0]+2*pad,seg_shape[1]+2*pad])

for n1 in range(0,pl_max[0]):
        for n2 in range(0,pl_max[1]):
                tr_in_full[n1,n2]=cam_pad(img_tr_in_pad[n1:n1+seg_shape[0],n2:n2+seg_shape[1]],pad)

tr_in_full_flat=tr_in_full.reshape([pl_max[0]*pl_max[1],seg_shape[0]+2*pad,seg_shape[1]+2*pad,1])

pred = model.predict(tr_in_full_flat)

pred_img=np.zeros(pred.shape[0])

for n1 in range(0,pred.shape[0]):
        pred_img[n1]=round(pred[n1,0])

pred_img_out=(pred_img.reshape([pl_max[0],pl_max[1]]))

plt.subplot(1,2,1)
plt.imshow(pred_img_out)

plt.subplot(1,2,2)
plt.imshow(img_tr_in)

plt.show()


问:
How to erase the dotting watermark from the image?
I want to automate the task of entering the faxed documents into the system with OCR. I tried using tesseract, but I found that the part that does not contain the watermark is recognized well, but the part that is watermarked is almost impossible to recognize.

I would like to remove the watermark using image processing. Unusually, the watermark of this image consists of 1x1 black pixels.

Is there a way to get rid of this watermark?

Example document (masked sensitive personal info):

Watermark (composed of 1x1 pixels):

Edit: Another answer marked as duplicate is simply a greyed-out watermark, but the image I want to process is a binary image, so the color of the image and watermark is black. So it can not be processed in the same way and it seems to have to be processed in a different way.

答:
Since the OCR was not working properly when the text data was deleted, I processed the text so that it was not deleted, instead of leaving a few watermarks. I ended up using two nested for loop.

result:

code:

```<code>img = cv2.imread('masked.png')
img_bw = 255*(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) > 5).astype('uint8')
img_copy = np.copy(img_bw)

for x in range(1, 2146):
    for y in range(1, 1727):
        if img_bw[x][y] == 0 and \
                img_bw[x-1][y] == img_bw[x+1][y] == img_bw[x][y-1] == img_bw[x][y+1] == \
                img_bw[x-1][y-1] == img_bw[x-1][y+1] == img_bw[x+1][y-1] == img_bw[x+1][y+1] == 255:
            img_copy[x][y] = 255
</code>```

Body:
Since the OCR was not working properly when the text data was deleted, I processed the text so that it was not deleted, instead of leaving a few watermarks. I ended up using two nested for loop.

result:

code:

img = cv2.imread('masked.png')
img_bw = 255*(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) > 5).astype('uint8')
img_copy = np.copy(img_bw)

for x in range(1, 2146):
    for y in range(1, 1727):
        if img_bw[x][y] == 0 and \
                img_bw[x-1][y] == img_bw[x+1][y] == img_bw[x][y-1] == img_bw[x][y+1] == \
                img_bw[x-1][y-1] == img_bw[x-1][y+1] == img_bw[x+1][y-1] == img_bw[x+1][y+1] == 255:
            img_copy[x][y] = 255


问:
uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library
I don't understand this error message

```<code>  C:\Program Files (x86)\Jenkins\workspace\__temp-mobile-prev\platforms\android\AndroidManifest.xml:67:5 Error:
        uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library C:\Program Files (x86)\Jenkins\workspace\__temp-mobile-prev\platforms\android\build\intermediates\exploded-aar\com.paypal.sdk\paypal-android-sdk\2.14.2\AndroidManifest.xml
        Suggestion: use tools:overrideLibrary="com.paypal.android.sdk.payments" to force usage
</code>```

Because line 67 of AndroidManifest.xml looks like:

```<code><uses-sdk android:minSdkVersion="18" android:targetSdkVersion="22" />
</code>```

Where does 15 come from?

I use ionic to build my app. But I don't think that this is the problem.

答:
The easier way to do this is to:

-Go to Build.gradle(Module:app).

-Change minSDKVersion 15 to minSDKVersion 16.

-Sync your project.

Body:
I don't understand this error message

  C:\Program Files (x86)\Jenkins\workspace\__temp-mobile-prev\platforms\android\AndroidManifest.xml:67:5 Error:
        uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library C:\Program Files (x86)\Jenkins\workspace\__temp-mobile-prev\platforms\android\build\intermediates\exploded-aar\com.paypal.sdk\paypal-android-sdk\2.14.2\AndroidManifest.xml
        Suggestion: use tools:overrideLibrary="com.paypal.android.sdk.payments" to force usage

Because line 67 of AndroidManifest.xml looks like:

<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="22" />

Where does 15 come from?

I use ionic to build my app. But I don't think that this is the problem.


问:
How to remove duplicate words from a string comparing to other string in SQL
I need to check string2 if there are words that I already have in string1 and remove those.

```<code>declare @Text1 nvarchar(500) = 'apple, orange, pear'
declare @Text2 nvarchar(500) = 'banana, apple'
</code>```

The output should be 'banana'

Edit: I just realized I made the question not properly.
So, this is right:

```<code>DECLARE @Tab TABLE (Ingredients nvarchar(500))

insert @Tab select 'apple, orange, pear'

insert @Tab select 'banana, apple'

insert @Tab select 'pear, mango'

declare @Ingredients nvarchar(4000) = ''

select @Ingredients = @Ingredients + value + ',' from @Tab cross apply STRING_SPLIT(Ingredients, ',')

SELECT @Ingredients
</code>```

current result:
apple,orange,pear,banana,apple,pear,mango,

expected result:
apple,orange,pear,banana,mango,

答:
So if that is the case I would like to suggest you to create a function:

```<code>    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    CREATE FUNCTION GetUniqueValues
    (
        @LIST AS NVARCHAR(MAX)
    )
    RETURNS NVARCHAR(MAX)
    AS
    BEGIN

        DECLARE @POS INT
        DECLARE @LEN INT
        DECLARE @VALUE NVARCHAR(MAX)

        SET @POS = 0
        SET @LEN = 0

        DECLARE @RESULT NVARCHAR(MAX) = ''

        WHILE CHARINDEX(',', @LIST, @POS + 1) > 0
        BEGIN

            SET @LEN = CHARINDEX(',', @LIST, @POS + 1) - @POS
            SET @VALUE = RTRIM(LTRIM(SUBSTRING(@LIST, @POS, @LEN)))

            IF (CHARINDEX(@VALUE, @RESULT) = 0)
                BEGIN
                    IF (LEN(RTRIM(LTRIM(@RESULT))) = 0)
                        BEGIN
                            SET @RESULT = @VALUE
                        END
                    ELSE
                        BEGIN
                            SET @RESULT = @RESULT + ', ' + @VALUE
                        END
                END
            SET @POS = CHARINDEX(',', @LIST, @POS + @LEN) +1
        END

        RETURN @RESULT

    END
    GO
</code>```

You can use this function like this based on you example:

```<code>SELECT dbo.GetUniqueValues(@Ingredients)
</code>```

Expected result

apple, orange, pear, banana, mango

Body:
I need to check string2 if there are words that I already have in string1 and remove those.

declare @Text1 nvarchar(500) = 'apple, orange, pear'
declare @Text2 nvarchar(500) = 'banana, apple'

The output should be 'banana'

Edit: I just realized I made the question not properly.
So, this is right:

DECLARE @Tab TABLE (Ingredients nvarchar(500))

insert @Tab select 'apple, orange, pear'

insert @Tab select 'banana, apple'

insert @Tab select 'pear, mango'

declare @Ingredients nvarchar(4000) = ''

select @Ingredients = @Ingredients + value + ',' from @Tab cross apply STRING_SPLIT(Ingredients, ',')

SELECT @Ingredients

current result:
apple,orange,pear,banana,apple,pear,mango,

expected result:
apple,orange,pear,banana,mango,

Body:
So if that is the case I would like to suggest you to create a function:

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    CREATE FUNCTION GetUniqueValues
    (
        @LIST AS NVARCHAR(MAX)
    )
    RETURNS NVARCHAR(MAX)
    AS
    BEGIN

        DECLARE @POS INT
        DECLARE @LEN INT
        DECLARE @VALUE NVARCHAR(MAX)

        SET @POS = 0
        SET @LEN = 0

        DECLARE @RESULT NVARCHAR(MAX) = ''

        WHILE CHARINDEX(',', @LIST, @POS + 1) > 0
        BEGIN

            SET @LEN = CHARINDEX(',', @LIST, @POS + 1) - @POS
            SET @VALUE = RTRIM(LTRIM(SUBSTRING(@LIST, @POS, @LEN)))

            IF (CHARINDEX(@VALUE, @RESULT) = 0)
                BEGIN
                    IF (LEN(RTRIM(LTRIM(@RESULT))) = 0)
                        BEGIN
                            SET @RESULT = @VALUE
                        END
                    ELSE
                        BEGIN
                            SET @RESULT = @RESULT + ', ' + @VALUE
                        END
                END
            SET @POS = CHARINDEX(',', @LIST, @POS + @LEN) +1
        END

        RETURN @RESULT

    END
    GO

You can use this function like this based on you example:

SELECT dbo.GetUniqueValues(@Ingredients)

Expected result

apple, orange, pear, banana, mango


问:
How can I achieve this type result using Python Tkinter?
I am trying to make transparent GUI using Tkinter in python, Please help me how can I make this type GUI
Transparent GUI

```<code>import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()
</code>```

答:
You need to use wm_attributes:</p>

```<code>import tkinter as tk

root = tk.Tk()
# load image
root.image = tk.PhotoImage(file='image.gif')
# disable window movement
root.overrideredirect(True)
# setup start window position
root.geometry("+800+200")
# initialise wm attributes
root.wm_attributes()
# setup transparency
root.wm_attributes("-alpha", 0.5)
# setup label
label = tk.Label(root, image=root.image, bg='white')
label.pack()
label.mainloop()
</code>```

Body:
I am trying to make transparent GUI using Tkinter in python, Please help me how can I make this type GUI
Transparent GUI

import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()

Body:
You need to use wm_attributes:

import tkinter as tk

root = tk.Tk()
# load image
root.image = tk.PhotoImage(file='image.gif')
# disable window movement
root.overrideredirect(True)
# setup start window position
root.geometry("+800+200")
# initialise wm attributes
root.wm_attributes()
# setup transparency
root.wm_attributes("-alpha", 0.5)
# setup label
label = tk.Label(root, image=root.image, bg='white')
label.pack()
label.mainloop()


问:
With CSS, how to style a generic, global style?
Update: this question is about global style.  So solution such as #some-id .score is NOT a solution.

At first, I was styling as

```<code>.score { font-size: 32px; color: #777 }
</code>```

And the "score" is something that can happen any where, something of a global style.  But since other style actually might have:

```<code>#summary-panel { font-size: 13px }
</code>```

The one with id will override the one just having classes (the first CSS rule in this post).  (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use

```<code>.score { font-size: 32px !important; color: #777 !important }
</code>```

because the !important can act as the "second level" which override everything ordinary, and act as a global style.

Is this a good way or better way?  One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also

```<code>#summary-panel { font-size: 12px !important }
</code>```

so in this case, the !important will be overridden because the one having an id will always win over just classes.  So is there a better way?

答:
this question is about global style.
  So solution  such as #some-id .score
  is NOT a solution

[...]

.score is NOT a solution So is there a better way?

there is no answer, all the comments you got in the first answer are valid and polite,  but I would tell you as a user, that you should not use !important unless in an emergency to override external code that is outwith your control, !important is for user styles

CSS is a mindset, a suggestion, your request (with a please ;) to the browsers how you would like your styles displayed - at the minute you seem to be struggling between the mindsets

The logical programmer side wants a "global" style, and I believe most programming languages have "globals" ? CSS is not a programming language it's a markup language.

Anyway, the recent last 3-4 years CSS'ers have been encouraged to "class everything"  YUI and Blueprint and other frameworks would have us do so.. but that means you should not use ID's because as you rightly point out they override.. they are the ultimate in the CSS Specificity Wars.. BUT as an efficient CSS coder you need to use ID's  - that is best practice isn't it? - so if you do need to mix them then you should group your ID selectors and if necessary group the class selectors as was suggested to you

there really is no answer here (except there no such thing as global styling unless you pass it down via ID's and inheritance, it's a coding preference rather than a right/wrong answer

Body:
Update: this question is about global style.  So solution such as #some-id .score is NOT a solution.

At first, I was styling as

.score { font-size: 32px; color: #777 }

And the "score" is something that can happen any where, something of a global style.  But since other style actually might have:

#summary-panel { font-size: 13px }

The one with id will override the one just having classes (the first CSS rule in this post).  (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use

.score { font-size: 32px !important; color: #777 !important }

because the !important can act as the "second level" which override everything ordinary, and act as a global style.

Is this a good way or better way?  One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also

#summary-panel { font-size: 12px !important }

so in this case, the !important will be overridden because the one having an id will always win over just classes.  So is there a better way?


问:
Databinding with C# and Mysql shows wrong data
I have just created my first WPF-application and connected it to MySql-database.
I am able to retrieve data from DB, but it presents it totally wrong

I have searched through internet and different threads and now I have tried different things for a couple of hours.

My XAML-file

```<code>   <Window x:Class="AppGetMySQL.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:AppGetMySQL"
    mc:Ignorable="d"
    Title="Get All Records" Height="450" WindowStartupLocation="CenterScreen" Width="800" AllowsTransparency="False" WindowStyle="ThreeDBorderWindow">
<Window.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FFF1F7FF" Offset="0"/>
        <GradientStop Color="White" Offset="1"/>
    </LinearGradientBrush>
</Window.Background>
<Grid Margin="0,-52,0,0">
    <Button Content="Connect" HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Width="112" Height="41" Click="Button_Click"/>
    <ListView HorizontalAlignment="Left" Margin="126,170,0,0" VerticalAlignment="Top" Name="ListAllUsers" Width="527" Height="291" FontSize="16" FontFamily="Calibri">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" />
                <GridViewColumn Header="Name" Width="300px"/>
                <GridViewColumn Header="City" Width="300px" />
            </GridView>
        </ListView.View>
    </ListView>

</Grid>
</Window>
</code>```

My .cs-file

```<code>int x = 0;

string connectionString = "SERVER=db5.freemysqlhosting.net;" + "DATABASE=db5233941;" + "UID=db5233941;" + "PASSWORD=*******;";
        string query = "select * from AllUsers";//I know I should not use *, but this is just test.
        MySqlConnection con = new MySqlConnection(connectionString);
        MySqlDataAdapter ada = new MySqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        ada.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow dr = dt.Rows[i];
            List<String> stringList = new List<string>();
            stringList.Add(dr["Id"].ToString());
            stringList.Add(dr["Name"].ToString());
            stringList.Add(dr["City"].ToString());
            ListAllUsers.ItemsSource = stringList;
        }
</code>```

I hope to print something like:

| id | Name | City |

| id | Name | City |

| id | Name | City |

But instead it prints

| id | id | id |

| Name | Name | Name |

| City | City | City |

Picture:

What am I doing wrong?

Edit:
Actually when I add this in the loop:

```<code>            Console.WriteLine("Id: " + dr["Id"].ToString());
            Console.WriteLine("Name: " + dr["Name"].ToString());
            Console.WriteLine("City: " + dr["City"].ToString());
</code>```

It prints everything correct. All five rows I have in my table.

答:
I think you are missing the binding somehow. Compare to this tutorial page, that might help. ListView with a GridView Exerpt:</p>

```<code>        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
                <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
            </GridView>
        </ListView.View>
</code>```

Body:
I have just created my first WPF-application and connected it to MySql-database.
I am able to retrieve data from DB, but it presents it totally wrong

I have searched through internet and different threads and now I have tried different things for a couple of hours.

My XAML-file

   <Window x:Class="AppGetMySQL.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:AppGetMySQL"
    mc:Ignorable="d"
    Title="Get All Records" Height="450" WindowStartupLocation="CenterScreen" Width="800" AllowsTransparency="False" WindowStyle="ThreeDBorderWindow">
<Window.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FFF1F7FF" Offset="0"/>
        <GradientStop Color="White" Offset="1"/>
    </LinearGradientBrush>
</Window.Background>
<Grid Margin="0,-52,0,0">
    <Button Content="Connect" HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Width="112" Height="41" Click="Button_Click"/>
    <ListView HorizontalAlignment="Left" Margin="126,170,0,0" VerticalAlignment="Top" Name="ListAllUsers" Width="527" Height="291" FontSize="16" FontFamily="Calibri">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" />
                <GridViewColumn Header="Name" Width="300px"/>
                <GridViewColumn Header="City" Width="300px" />
            </GridView>
        </ListView.View>
    </ListView>

</Grid>
</Window>

My .cs-file

int x = 0;

string connectionString = "SERVER=db5.freemysqlhosting.net;" + "DATABASE=db5233941;" + "UID=db5233941;" + "PASSWORD=*******;";
        string query = "select * from AllUsers";//I know I should not use *, but this is just test.
        MySqlConnection con = new MySqlConnection(connectionString);
        MySqlDataAdapter ada = new MySqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        ada.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow dr = dt.Rows[i];
            List<String> stringList = new List<string>();
            stringList.Add(dr["Id"].ToString());
            stringList.Add(dr["Name"].ToString());
            stringList.Add(dr["City"].ToString());
            ListAllUsers.ItemsSource = stringList;
        }

I hope to print something like:

| id | Name | City |

| id | Name | City |

| id | Name | City |

But instead it prints

| id | id | id |

| Name | Name | Name |

| City | City | City |

Picture:

What am I doing wrong?

Edit:
Actually when I add this in the loop:

            Console.WriteLine("Id: " + dr["Id"].ToString());
            Console.WriteLine("Name: " + dr["Name"].ToString());
            Console.WriteLine("City: " + dr["City"].ToString());

It prints everything correct. All five rows I have in my table.

Body:
I think you are missing the binding somehow. Compare to this tutorial page, that might help. ListView with a GridView Exerpt:

        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
                <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
            </GridView>
        </ListView.View>


问:
Decrement with setInterval in for loop
Using this construction of code, how to decrement as a stopwatch the inserted  number of the the user with an interval of 1 second. I have created this script but i don't get the necessary result. Which is the issue of the code?

  var seconds = prompt();
    setInterval(function () {
        for (var i = seconds; i>0; i--){
            console.log(i)
        }
    },1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="result"></p></code>```

答:
set value : document.getElementById("result").innerHTML = seconds;

and then end by  clearInterval(stopWatch);

```<code><script>
    var seconds = prompt();

    var stopWatch = setInterval(function() {
    if(seconds <=0){
        clearInterval(stopWatch);
        return;
    }
    document.getElementById("result").innerHTML = seconds;
    seconds--;
}, 1000);
</code>```

```<code> <p id="result"></p>
</code>```

Title: Decrement with setInterval in for loop

Body:
set value : document.getElementById("result").innerHTML = seconds;

and then end by  clearInterval(stopWatch);

<script>
    var seconds = prompt();

    var stopWatch = setInterval(function() {
    if(seconds <=0){
        clearInterval(stopWatch);
        return;
    }
    document.getElementById("result").innerHTML = seconds;
    seconds--;
}, 1000);

 <p id="result"></p>