问:
macos command line params not working at the end
On linux systems when you type a command in a shell like rm * -rf, the order of the * and the -rf doesn't matter. My shell interpret it the same way. Now, on my Mac when I type rm -rf * everything works fine, but if I do rm * -rf an error shows up rm: -rf: No such file or directory

I tried that on a macOS and a linux both with fish and bash shells. Same problems.

Does anyone have any idea why the command interpreter on macOS thinks that -rf at the end of the command is not interpreted as parameters of the command ?

答:
Order of the arguments in any shell has historically been relevant in unix.

rm incidentally even has an option -- to stop parsing options (to be able to remove files that start with "-" e.g.)

See rm(1) and getopt(3) man pages

if the shell doesn't respect order of the arguments it is given just what would the result be of this sequence:

```<code>$ touch a b
$ mv a b
</code>```

what file would remain ?

Body:
Order of the arguments in any shell has historically been relevant in unix.

rm incidentally even has an option -- to stop parsing options (to be able to remove files that start with "-" e.g.)

See rm(1) and getopt(3) man pages

if the shell doesn't respect order of the arguments it is given just what would the result be of this sequence:

$ touch a b
$ mv a b

what file would remain ?


来源: stackexchange

问:
Writing to Kafka from .net core service using Confluent.Kafka
I have a .net core service that fetches data from a MEMSQL server and returns to the client. However, the queries that are generated at the service needs to be logged to Kafka cluster.

I tried installing Confluent.Kafka package and do the logging, it works fine when running locally. But in the container, the service cannot log and generate the following errors:

```<code> warning NU1701: Package 'librdkafka.redist 0.9.5' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
The type initializer for 'Confluent.Kafka.Impl.LibRdKafka' threw an exception.
</code>```

The container is running on a LINUX machine. Basically, I need to figure out a version of Confluent.Kafka that works with .netcore 2.0 and one that does not depend on .NETFramework v4.6.

答: Updating to the latest Confluent Package 0.11.3 fixed the issue. Now the service is able to access Kafka cluster from the docker container. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have a .net core service that fetches data from a MEMSQL server and returns to the client. However, the queries that are generated at the service needs to be logged to Kafka cluster.

I tried installing Confluent.Kafka package and do the logging, it works fine when running locally. But in the container, the service cannot log and generate the following errors:

 warning NU1701: Package 'librdkafka.redist 0.9.5' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
The type initializer for 'Confluent.Kafka.Impl.LibRdKafka' threw an exception.

The container is running on a LINUX machine. Basically, I need to figure out a version of Confluent.Kafka that works with .netcore 2.0 and one that does not depend on .NETFramework v4.6.


问:
Attempting to map dates to index in ElasticSearch
I am using ElasticSearch and attempting to create an index with a class that has a dynamic type property in it.  This property may have strings or dates in it.  When indexing, I have been using the code below:

```<code>dynamic instance = MyObject.GetDynamicJson();
var indexResponse = client.Index((object) instance, i=>i
                .Index("myIndex")
                .Type("MyObject")
            );
</code>```

Here's the code for GetDynamicJson().
MyObject has only Name and Value as properties.  (apologies, I've had issues in the past with Elastic choking on json without all the quotes, which I have escaped with \ characters):

```<code>String json = "{ \"Name\":\" + Name + "\",\"DateValue\":\"";
try {
     var date = DateTime.parse(Value);
     json += DateTime.ToString("yyyy/MM/dd HH:mm:ss Z") + "\", \"Value\":\"\"}";
} catch {   //If the DateTime parse fails, DateValue is empty and I'll have text in Value
     json += "\",\"Value\":\"" + Value + "\"}";
}
return json;
</code>```

   For some reason it doesn't seem to like the string in DateValue and I definitely don't know why it's leaving out that property entirely in the error:

For whatever reason, ElasticSearch is completely dumping the DateValue property, doesn't seem to see the DateValue property at all.

I'm getting the error:

{"name":"CreatedDate","value":"2017-11-07T13:37:11.4340238-06:00"}
[indices:data/write/bulk[s][p]]"}],"type":"class_cast_exception","reason":"org.elasticsearch.index.mapper.TextFieldMapper cannot be cast to org.elasticsearch.index.mapper.DateFieldMapper"},"status":500

Later note:  I have changed the index creator method to update the mapping.  I added a third field to the Object, so now it has properties:  Name, Value, DateValue:

```<code>public static void CreateRecordsIndex(ElasticClient client)
    {
        client.CreateIndex("myIndex", i => i
            .Settings(s => s
                .NumberOfShards(2)
                .NumberOfReplicas(0)
            )
            .Mappings(x => x
                .Map<MyObject>(m => m.AutoMap())));
    }
</code>```

Now, it is successfully mapping and creating a property each time, but it still seems to drop the property I am sending it in the json.  It just sets them all to the default datetime:  "dateValue": "0001-01-01T00:00:00".  This is strange, because when making the dynamic instance I send to Elastic, I use only the MyObject.GetDynamicJson() method to build it.  I no longer get the mapping error, but Elastic still seems oblivious to "dateValue":"some date here" in the object when it is set.

答:
OK, I got rid of the dynamic object type (ultimately I wasn't actually getting data from the json method, I had a typo and Elastic was getting the original object directly - it's a wonder it was still handling it).  So I let Elastic do the parse using its mapping.  In order to do that, I first updated MyObject to include multiple properties, one for each type the incoming property could be (I am only handling text and dates in this case).  For the DateValue property of MyObject, I have this:

```<code>public DateTime DateValue {
        get
        {
            try
            {
                return DateTime.Parse(Value);
            } catch
            {
                return new DateTime();
            }
        }
        set
        {
            try {
                DateValue = value;
            } catch
            {
                DateValue = new DateTime();
            }
        }
    }
</code>```

Now, if Value is a date, my DateValue field will be set.  Otherwise it'll have the default date (a very early date "0001-01-01T00:00:00").  This way, I can later search both for text against that dynamic field, or if a date is set, I can do date and date range queries against it (technically they end up in two different fields, but coming from the same injested data).

Key to this is having the index mapping setup, as you can see in this method from the question:

```<code>public static void CreateRecordsIndex(ElasticClient client)
{
    client.CreateIndex("myIndex", i => i
        .Settings(s => s
            .NumberOfShards(2)
            .NumberOfReplicas(0)
        )
        .Mappings(x => x
            .Map<MyObject>(m => m.AutoMap())));
}
</code>```

In order to recreate the index with the updated MyObject, I did this:

```<code>if (client.IndexExists("myIndex").Exists)
        {
            client.DeleteIndex("myIndex");
            CreateRecordsIndex(client);  //Goes to the method above
        }
</code>```

Body:
I am using ElasticSearch and attempting to create an index with a class that has a dynamic type property in it.  This property may have strings or dates in it.  When indexing, I have been using the code below:

dynamic instance = MyObject.GetDynamicJson();
var indexResponse = client.Index((object) instance, i=>i
                .Index("myIndex")
                .Type("MyObject")
            );

Here's the code for GetDynamicJson().
MyObject has only Name and Value as properties.  (apologies, I've had issues in the past with Elastic choking on json without all the quotes, which I have escaped with \ characters):

String json = "{ \"Name\":\" + Name + "\",\"DateValue\":\"";
try {
     var date = DateTime.parse(Value);
     json += DateTime.ToString("yyyy/MM/dd HH:mm:ss Z") + "\", \"Value\":\"\"}";
} catch {   //If the DateTime parse fails, DateValue is empty and I'll have text in Value
     json += "\",\"Value\":\"" + Value + "\"}";
}
return json;

   For some reason it doesn't seem to like the string in DateValue and I definitely don't know why it's leaving out that property entirely in the error:

For whatever reason, ElasticSearch is completely dumping the DateValue property, doesn't seem to see the DateValue property at all.

I'm getting the error:

{"name":"CreatedDate","value":"2017-11-07T13:37:11.4340238-06:00"}
[indices:data/write/bulk[s][p]]"}],"type":"class_cast_exception","reason":"org.elasticsearch.index.mapper.TextFieldMapper cannot be cast to org.elasticsearch.index.mapper.DateFieldMapper"},"status":500

Later note:  I have changed the index creator method to update the mapping.  I added a third field to the Object, so now it has properties:  Name, Value, DateValue:

public static void CreateRecordsIndex(ElasticClient client)
    {
        client.CreateIndex("myIndex", i => i
            .Settings(s => s
                .NumberOfShards(2)
                .NumberOfReplicas(0)
            )
            .Mappings(x => x
                .Map<MyObject>(m => m.AutoMap())));
    }

Now, it is successfully mapping and creating a property each time, but it still seems to drop the property I am sending it in the json.  It just sets them all to the default datetime:  "dateValue": "0001-01-01T00:00:00".  This is strange, because when making the dynamic instance I send to Elastic, I use only the MyObject.GetDynamicJson() method to build it.  I no longer get the mapping error, but Elastic still seems oblivious to "dateValue":"some date here" in the object when it is set.

Body:
OK, I got rid of the dynamic object type (ultimately I wasn't actually getting data from the json method, I had a typo and Elastic was getting the original object directly - it's a wonder it was still handling it).  So I let Elastic do the parse using its mapping.  In order to do that, I first updated MyObject to include multiple properties, one for each type the incoming property could be (I am only handling text and dates in this case).  For the DateValue property of MyObject, I have this:

public DateTime DateValue {
        get
        {
            try
            {
                return DateTime.Parse(Value);
            } catch
            {
                return new DateTime();
            }
        }
        set
        {
            try {
                DateValue = value;
            } catch
            {
                DateValue = new DateTime();
            }
        }
    }

Now, if Value is a date, my DateValue field will be set.  Otherwise it'll have the default date (a very early date "0001-01-01T00:00:00").  This way, I can later search both for text against that dynamic field, or if a date is set, I can do date and date range queries against it (technically they end up in two different fields, but coming from the same injested data).

Key to this is having the index mapping setup, as you can see in this method from the question:

public static void CreateRecordsIndex(ElasticClient client)
{
    client.CreateIndex("myIndex", i => i
        .Settings(s => s
            .NumberOfShards(2)
            .NumberOfReplicas(0)
        )
        .Mappings(x => x
            .Map<MyObject>(m => m.AutoMap())));
}

In order to recreate the index with the updated MyObject, I did this:

if (client.IndexExists("myIndex").Exists)
        {
            client.DeleteIndex("myIndex");
            CreateRecordsIndex(client);  //Goes to the method above
        }


问:
euler question about strings and ints
i am currently programming in euler (mathematics)
the problem is i need to split the first 10 numbers and the latst 2

: 012345678912 =

0123456789      12

i can do this by using the substring method
but i need to calculate further with the first 10 numbers
so what i can do is cast the string back to an int
but i have no idea how to do it ..
can anyone help me ?

thanks in advance

答:
An easier way is to get the last 2 digits using the modulo operator:

```<code>012345678912 % 100 = 12
</code>```

And then getting the rest by doing integer division by 100:

```<code>012345678912 // 100 = 123456789
</code>```

The exact syntax needed varies depending on the language.

ContentLicense: CC BY-SA 2.5

Title: euler question about strings and ints

Body:
An easier way is to get the last 2 digits using the modulo operator:

012345678912 % 100 = 12

And then getting the rest by doing integer division by 100:

012345678912 // 100 = 123456789

The exact syntax needed varies depending on the language.


问:
How much load can Parse Server on Compute Engine instance handle
The server will run singly on one instance of compute engine. What could limit it's serving capacity and how much load can a single instance (4 vCPUs and 15GB Memory) handle.

Note : I've already looked at Kubernetes and even load-balancing multiple instances but accessing the database from multiple clients is a little too complicated for me right now. So please keep in mind if you're going to suggest containerisation, that I'm a beginner.

Any and all advice is welcome. Thanks!

答:
The serving capacity of the server depends on a number of factors, which includes the requests you receive from the clients, the additional applications running in it etc. For a 4 core CPU, as per this help center article, you will get a peak performance of 8Gb/s, which is good for a single instance. Since you are using a single parse server alone on the VM, it should work very well with the above-mentioned configuration.

A container is a tool for a developer. It contains all the dependencies and library which required to run/test a particular application in a container. The applications running in the container are easily portable.

There is this help center article which might give a precise idea of containers and its usage. While the Kubernetes Engine will help you to deploy/manage these containerized application.


问:
Mapping a script over all lines of stdin
Is there a more idiomatic way of doing the following:

cat some_lines.txt | while read x; do ./process_line.sh $x; done

ie. applying a script to each line of stdin?

I could include the while read x; boilerplate in the script itself, but that doesn't really feel right either.

答:
If you're running an external process and have GNU xargs, consider:

```<code>xargs -n1 -d $'\n' ./process_line.sh <some_lines.txt
</code>```

If you don't like the while read loop's verbosity, and are running a shell function (where a fork() isn't natively needed, and thus where using an external tool like xargs or GNU parallel has a substantial performance cost), you can avoid it by wrapping the loop in a function:

```<code>for_each_line() {
  local line
  while IFS= read -r line; do
    "$@" "$line" </dev/null
  done
}
</code>```

...can be run as:

```<code>process_line() {
  echo "Processing line: $1"
}
for_each_line process_line <some_lines.txt
</code>```

Body:
If you're running an external process and have GNU xargs, consider:

xargs -n1 -d $'\n' ./process_line.sh <some_lines.txt

If you don't like the while read loop's verbosity, and are running a shell function (where a fork() isn't natively needed, and thus where using an external tool like xargs or GNU parallel has a substantial performance cost), you can avoid it by wrapping the loop in a function:

for_each_line() {
  local line
  while IFS= read -r line; do
    "$@" "$line" </dev/null
  done
}

...can be run as:

process_line() {
  echo "Processing line: $1"
}
for_each_line process_line <some_lines.txt


问:
No Twitter authorization prompt when using rtweet package
When using rtweet, I am not prompted to sign into twitter at any point.  As a result I receive a : Error: is.request(signed_req) is not TRUE error. Any suggestions on how to overcome this issue?

I have been following the getting started examples on cran with no success.  Thanks in advance.

答:
Could you post some of the code you tried? According to http://rtweet.info/:

The first time you make an API request—e.g., search_tweets(), stream_tweets(), get_followers()—a browser window will open

You may need to reinstall from the github.


问:
push_back keeps rewriting all entries in the vector to the item pushed_back?
I am currently trying to make a light copy of a vector. A light copy meaning that the content of the copy, is a vector of pointer of the original vector.  I am for some reasons having problems doing so... Each time I push_back a new entry into the copy vector, I seem to overwrite all the entries in the vector, to the element I just push_back, why is this happening:

MWE:

```<code>// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <experimental/filesystem>
#include <vector>
#include <algorithm>

struct abstract_data_structure
{
    int x;
    int y;
    std::vector<int> points;
    std::string name;

    abstract_data_structure(int x, int y , std::vector<int> points, std::string name)
    {
        this->x= x;
        this->y = y;
        this->points = points;
        this->name = name;
    }
};

int main()
{
     std::vector<abstract_data_structure> storage;
     std::vector<abstract_data_structure*> copy_of_storage;

     std::srand(std::time(0));
     for (int i = 0; i< 5 ; i++)
     {
        int x = std::rand();
        int y = std::rand();
        std::vector<int> vecOfRandomNums(10);
        std::generate(vecOfRandomNums.begin(), vecOfRandomNums.end(), []() {
           return rand() % 100;
        });
        std::string name = "something"+std::to_string(i);
        abstract_data_structure something(x,y,vecOfRandomNums,name);
        storage.push_back(something);

     }

    std::cout << storage.size() << std::endl;
    std::cout << "Make the copy" << std::endl;

    for (auto element : storage)
    {
        std::cout << "in storage" << std::endl;
        std::cout << element.name << std::endl;
        copy_of_storage.push_back(&(element));
        std::cout << "in copy storage" << std::endl;

        for (auto copy_element: copy_of_storage)
        {
            std::cout << copy_element->name << std::endl;
        }
    }

}
</code>```

https://wandbox.org/permlink/Xn96xbIshd6RXTRa

which outputs this:

```<code>5
Make the copy
in storage
something0
in copy storage
something0
in storage
something1
in copy storage
something1
something1
in storage
something2
in copy storage
something2
something2
something2
in storage
something3
in copy storage
something3
something3
something3
something3
in storage
something4
in copy storage
something4
something4
something4
something4
something4
0
</code>```

As one might see are all the entries in the copy vector, modified to point to last element inserted? why?

答:
```<code>//***1***
for (auto element : storage)
{
    std::cout << "in storage" << std::endl;
    std::cout << element.name << std::endl;
    //***2***
    copy_of_storage.push_back(&(element));
    std::cout << "in copy storage" << std::endl;

    for (auto copy_element: copy_of_storage)
    {
        std::cout << copy_element->name << std::endl;
    }
}
</code>```

At ***1***, you're making a local copy of each variable.

At ***2***, you're taking the address of that local copy and saving it in the vector.

When you leave scope, the object has been destructed and no longer exists. So when you later try to read it, you get Undefined Behavior, which means you cannot guarantee the behavior that will take place.

What seems to be happening is that each time, you're taking the address of the local variable, and each iteration of the for-loop, that location of the variable is the same, so each address in the final copy vector is the same, and because the most recent copy is whichever entry in the storage vector you were most recently working with, that's the version that gets read by the pointer.

If you change ***1*** to for(auto & element : storage), your issue should be fixed.

Body:
I am currently trying to make a light copy of a vector. A light copy meaning that the content of the copy, is a vector of pointer of the original vector.  I am for some reasons having problems doing so... Each time I push_back a new entry into the copy vector, I seem to overwrite all the entries in the vector, to the element I just push_back, why is this happening:

MWE:

// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <experimental/filesystem>
#include <vector>
#include <algorithm>

struct abstract_data_structure
{
    int x;
    int y;
    std::vector<int> points;
    std::string name;

    abstract_data_structure(int x, int y , std::vector<int> points, std::string name)
    {
        this->x= x;
        this->y = y;
        this->points = points;
        this->name = name;
    }
};

int main()
{
     std::vector<abstract_data_structure> storage;
     std::vector<abstract_data_structure*> copy_of_storage;

     std::srand(std::time(0));
     for (int i = 0; i< 5 ; i++)
     {
        int x = std::rand();
        int y = std::rand();
        std::vector<int> vecOfRandomNums(10);
        std::generate(vecOfRandomNums.begin(), vecOfRandomNums.end(), []() {
           return rand() % 100;
        });
        std::string name = "something"+std::to_string(i);
        abstract_data_structure something(x,y,vecOfRandomNums,name);
        storage.push_back(something);

     }

    std::cout << storage.size() << std::endl;
    std::cout << "Make the copy" << std::endl;

    for (auto element : storage)
    {
        std::cout << "in storage" << std::endl;
        std::cout << element.name << std::endl;
        copy_of_storage.push_back(&(element));
        std::cout << "in copy storage" << std::endl;

        for (auto copy_element: copy_of_storage)
        {
            std::cout << copy_element->name << std::endl;
        }
    }

}

https://wandbox.org/permlink/Xn96xbIshd6RXTRa

which outputs this:

5
Make the copy
in storage
something0
in copy storage
something0
in storage
something1
in copy storage
something1
something1
in storage
something2
in copy storage
something2
something2
something2
in storage
something3
in copy storage
something3
something3
something3
something3
in storage
something4
in copy storage
something4
something4
something4
something4
something4
0

As one might see are all the entries in the copy vector, modified to point to last element inserted? why?

Body:
//***1***
for (auto element : storage)
{
    std::cout << "in storage" << std::endl;
    std::cout << element.name << std::endl;
    //***2***
    copy_of_storage.push_back(&(element));
    std::cout << "in copy storage" << std::endl;

    for (auto copy_element: copy_of_storage)
    {
        std::cout << copy_element->name << std::endl;
    }
}

At ***1***, you're making a local copy of each variable.

At ***2***, you're taking the address of that local copy and saving it in the vector.

When you leave scope, the object has been destructed and no longer exists. So when you later try to read it, you get Undefined Behavior, which means you cannot guarantee the behavior that will take place.

What seems to be happening is that each time, you're taking the address of the local variable, and each iteration of the for-loop, that location of the variable is the same, so each address in the final copy vector is the same, and because the most recent copy is whichever entry in the storage vector you were most recently working with, that's the version that gets read by the pointer.

If you change ***1*** to for(auto & element : storage), your issue should be fixed.


问:
C++ - constant variable, is it a correct term?
At the end of the artile here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/

It mentions the following sentence:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

Is "constant variables" a correct term to use? Aren't constants different from variables?

Thanks.

答:
So many people are confused. In K&R C, a string literal can be changed. Hence, literals being constants meaning immutable is wrong. In ISO C and C++ variables of type T const for some T can also be changed, using a cast. So again, constant doesn't mean immutable. As @foo pointed out above, constants often do not have the properties of a variable because of optimisation, and in fact the semantics often specify it. Also do not forget in C and C++ there are constant expressions sometimes known as compile-time constants, used for array bounds, for example, a kind of constant which would never be confused with a variable, agree?

So here's a definition: a constant is a binding of a name to a value. With this definition, 1 is a constant because it is a literal name, and the binding is implicit. And here

```<code>enum {x};
void f();
</code>```

there are two constants, namely x and f: these are bindings of symbol names (in this case both identifiers, in C++ operator+ is also a name but not an identifier).

Now, I will show you another constant which will surprise you!

```<code>int y = 1;
</code>```

Yes indeed, y is a constant too! It is a binding of the name y to an address.
[If on the stack, an offset from the frame base instead]

So actually pretty much everything in your abstract syntax is a constant if you think about it hard enough :)

Body:
So many people are confused. In K&R C, a string literal can be changed. Hence, literals being constants meaning immutable is wrong. In ISO C and C++ variables of type T const for some T can also be changed, using a cast. So again, constant doesn't mean immutable. As @foo pointed out above, constants often do not have the properties of a variable because of optimisation, and in fact the semantics often specify it. Also do not forget in C and C++ there are constant expressions sometimes known as compile-time constants, used for array bounds, for example, a kind of constant which would never be confused with a variable, agree?

So here's a definition: a constant is a binding of a name to a value. With this definition, 1 is a constant because it is a literal name, and the binding is implicit. And here

enum {x};
void f();

there are two constants, namely x and f: these are bindings of symbol names (in this case both identifiers, in C++ operator+ is also a name but not an identifier).

Now, I will show you another constant which will surprise you!

int y = 1;

Yes indeed, y is a constant too! It is a binding of the name y to an address.
[If on the stack, an offset from the frame base instead]

So actually pretty much everything in your abstract syntax is a constant if you think about it hard enough :)


问:
How to order the list of entries using npm contentful integration with metalsmith?
Am trying to order the list of entries using contentful metalsmith example shown at https://github.com/contentful-labs/contentful-metalsmith-example/blob/master/build.js

```<code>Metalsmith(__dirname)
.source('src')
.destination('build')
.use(contentful({
space_id: 'w7sdyslol3fu',
access_token:
'baa905fc9cbfab17b1bc0b556a7e17a3e783a2068c9fd6ccf74ba09331357182',
common: {
  featured_author: {
    limit: 1,
    filter: {
      'sys.id[in]': '5JQ715oDQW68k8EiEuKOk8'
    }
  }
 },
}))
</code>```

I want the list of entries or post to be ordered based on their update or createdAt fields value.

Please help me out.
Thanks.

答:
You can order the entries by adding the order property to the query.

https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/order/query-entries/console/js

This can be done in the global configuration or as described in the docs in the source file configuration.

https://github.com/contentful/contentful-metalsmith/blob/master/docs/source-file-settings.md#order-optional

Hope that helps. :)

Body:
Am trying to order the list of entries using contentful metalsmith example shown at https://github.com/contentful-labs/contentful-metalsmith-example/blob/master/build.js

Metalsmith(__dirname)
.source('src')
.destination('build')
.use(contentful({
space_id: 'w7sdyslol3fu',
access_token:
'baa905fc9cbfab17b1bc0b556a7e17a3e783a2068c9fd6ccf74ba09331357182',
common: {
  featured_author: {
    limit: 1,
    filter: {
      'sys.id[in]': '5JQ715oDQW68k8EiEuKOk8'
    }
  }
 },
}))

I want the list of entries or post to be ordered based on their update or createdAt fields value.

Please help me out.
Thanks.


问:
Add cast to same type
I've got an outer class DoublyLinkedList<T> and two inner classes DoublyLinkedNode<T> as well as DoublyLinkedListIterator<T>. They are arranged as follows:

```<code>public class DoublyLinkedList<T> extends Collection<T> {

    private DoublyLinkedNode<T> head;
    private DoublyLinkedNode<T> tail;

    public class DoublyLinkedNode<T> {

        private DoublyLinkedNode<T> prev;
        private DoublyLinkedNode<T> next;
        T element;

    }

    public class DoublyLinkedListIterator<T> implements ListIterator<T> {

        private DoublyLinkedNode<T> current = head;

    }

}
</code>```

Now since I heard / read on multiple pages in stackoverflow and other sources that an Iterator should be implemented in the corresponding iterable class like DoublyLinkedList<T>, I thought it would be easier since you have access to the outer classes fields. Now I want to initialize an instance of DoublyLinkedListIterator<T>, but Eclipse says at this point:

```<code>private DoublyLinkedNode<T> current = head;
</code>```

inside the DoublyLinkedListIterator<T> that:

Type mismatch: cannot convert from DoublyLinkedList.DoublyLinkedNode< T > to DoublyLinkedList.DoublyLinkedNode< T >

And the only way to resolve this is by casting it with the same type again:

```<code>private DoublyLinkedNode<T> current = (DoublyLinkedNode<T>) head;
</code>```

Why is that so?

答:
You've declared inner classes DoublyLinkedNode and DoublyLinkdListIterator.
 Inner classes have in scope all generic type parameters of the enclosing class, so T is already available to them.  When you declare them again, you are hiding the T on the enclosing class.  They are different Ts.

Remove the re-declarations of T that are hiding the outer T (and your class should implement Collection, which is an interface), and let your inner classes use the outer T:

```<code>public class DoublyLinkedList<T> implements Collection<T> {

    private DoublyLinkedNode head;
    private DoublyLinkedNode tail;

    public class DoublyLinkedNode {
        private DoublyLinkedNode prev;
        private DoublyLinkedNode next;
        T element;
    }

    public class DoublyLinkedListIterator implements ListIterator<T> {
        private DoublyLinkedNode current = head;
    }
}
</code>```

Title: Add cast to same type

Body:
I've got an outer class DoublyLinkedList<T> and two inner classes DoublyLinkedNode<T> as well as DoublyLinkedListIterator<T>. They are arranged as follows:

public class DoublyLinkedList<T> extends Collection<T> {

    private DoublyLinkedNode<T> head;
    private DoublyLinkedNode<T> tail;

    public class DoublyLinkedNode<T> {

        private DoublyLinkedNode<T> prev;
        private DoublyLinkedNode<T> next;
        T element;

    }

    public class DoublyLinkedListIterator<T> implements ListIterator<T> {

        private DoublyLinkedNode<T> current = head;

    }

}

Now since I heard / read on multiple pages in stackoverflow and other sources that an Iterator should be implemented in the corresponding iterable class like DoublyLinkedList<T>, I thought it would be easier since you have access to the outer classes fields. Now I want to initialize an instance of DoublyLinkedListIterator<T>, but Eclipse says at this point:

private DoublyLinkedNode<T> current = head;

inside the DoublyLinkedListIterator<T> that:

Type mismatch: cannot convert from DoublyLinkedList.DoublyLinkedNode< T > to DoublyLinkedList.DoublyLinkedNode< T >

And the only way to resolve this is by casting it with the same type again:

private DoublyLinkedNode<T> current = (DoublyLinkedNode<T>) head;

Why is that so?

Body:
You've declared inner classes DoublyLinkedNode and DoublyLinkdListIterator.
 Inner classes have in scope all generic type parameters of the enclosing class, so T is already available to them.  When you declare them again, you are hiding the T on the enclosing class.  They are different Ts.

Remove the re-declarations of T that are hiding the outer T (and your class should implement Collection, which is an interface), and let your inner classes use the outer T:

public class DoublyLinkedList<T> implements Collection<T> {

    private DoublyLinkedNode head;
    private DoublyLinkedNode tail;

    public class DoublyLinkedNode {
        private DoublyLinkedNode prev;
        private DoublyLinkedNode next;
        T element;
    }

    public class DoublyLinkedListIterator implements ListIterator<T> {
        private DoublyLinkedNode current = head;
    }
}


问:
Does this C code leak memory?
So here is my code:

```<code>typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}

int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}
</code>```

I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.
Oh, and I know that if I define another vector let's say w, such that
w = fct(v)
it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.

答: Sure it does. vector t is allocated twice, and freed once. The whole architecture looks problematic.</p>

Title: Does this C code leak memory?

Body:
So here is my code:

typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}

int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}

I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.
Oh, and I know that if I define another vector let's say w, such that
w = fct(v)
it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.


问:
UICollectionView not rendering all rows
I'm trying to create a simple app, where one can enter a number of columns and a number of rows for an UICollectionView. The collection view then calculates the size of possible squares that fit into it and draws them.
I want to allow a maximum of 32 in width and 64 in height. Scrolling is disabled as the whole grid should be shown at once.

For example, 4x8 looks like this

and 8x4 will look like this

So as one can see that works fine. The problems comes with a higher amount of columns and/or rows. Up to 30x8 everything is fine but starting with 31 only 6 of the 8 rows are drawn.

So I don't understand why. Following is the code I use to calculate everything:

Number of section and number of rows:

```<code>func numberOfSections(in collectionView: UICollectionView) -> Int
{
    let num = Int(heightInput.text!)
    if(num != nil)
    {
        if(num! > 64)
        {
            return 64
        }
        return num!
    }
    return 8
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    let num = Int(widthInput.text!)
    if(num != nil)
    {
        if(num! > 32)
        {
            return 32
        }
        return num!
    }
    return 4
}
</code>```

Cell for item at indexPath

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let size = calculateCellSize()
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    var origin = cell.frame.origin
    origin.x = 1+CGFloat(indexPath.row) + size.width*CGFloat(indexPath.row)
    origin.y = 1+CGFloat(indexPath.section) + size.height*CGFloat(indexPath.section)
    cell.frame = CGRect(origin: origin, size: size)
    NSLog("Cell X:%@, Cell Y:%@",origin.x.description,origin.y.description)
    return cell
}
</code>```

The calculate size method

```<code>func calculateCellSize() -> CGSize
{
    //First check if we have valid values
    let col = Int(widthInput.text!)
    let row = Int(heightInput.text!)
    if(col == nil || row == nil)
    {
        return CGSize(width: 48.0, height: 48.0)
    }
    //If there are more or equal amount of columns than rows
    let columns = CGFloat(col!)
    let rows = CGFloat(row!)
    if(columns >= rows)
    {
        //Take the grid width
        let gridWidth = drawCollection.bounds.size.width
        //Calculate the width of the "pixels" that fit the width of the grid
        var pixelWidth = gridWidth/columns
        //Remember to substract the inset from the width
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelWidth -= (drawLayout?.sectionInset.left)! + 1/columns
        return CGSize(width: pixelWidth, height: pixelWidth)
    }
    else
    {
        //Rows are more than columns
        //Take the grid height as reference here
        let gridHeight = drawCollection.bounds.size.height
        //Calculate the height of the "pixels" that fit the height of the grid
        var pixelHeight = gridHeight/rows
        //Remember to substract the inset from the height
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelHeight -= (drawLayout?.sectionInset.top)! + 1/rows
        return CGSize(width: pixelHeight, height: pixelHeight)
    }
    return CGSize(width: 48.0, height: 48.0)
}
</code>```

For debugging reasons I put a counter into the cellforItemAtIndexPath method and in fact I can see that the last two rows are not called. The counter ends at 185 but in theory it should have been called 248 times and in fact the difference will show it is 2*32 - 1(for the uneven 31) so the last missing rows....

Several things came to my mind what the reason is but nothing of it seems to be:

the cells are not drawn at the right location (aka outside the grid) -> At least not correct as the method is only called 185 times.

The cells are calculated to be outside the grid therefore not tried to be rendered by the UICollectionView -> Still possible as I couldn't figure how to proof that.

There is a (if so hopefully configurable) maximum amount of elements the UICollectionView can draw and 31x8 already exceeds that number -> Still possible couldn't find anything about that.

So summary:

Is it possible to display all elements in the grid (32x64 max) and if so, what is wrong in my implementation?

Thank you all for your time and answers!

答:
You need to develop your own UICollectionViewLayout. With this approach you can achieve any result human being can imagine.

```<code>import UIKit

class CollectionLayout: UICollectionViewFlowLayout {

    private var width: Int = 1
    private var height: Int = 1

    func set(width: Int, height: Int) {
        guard width > 0, height > 0 else { return }

        self.height = height
        self.width = width
        calculateItemSize()
    }

    private func calculateItemSize() {
        guard let collectionView = collectionView else { return }
        let size = collectionView.frame.size
        var itemWidth = size.width / CGFloat(width)
        // spacing is needed only if there're more than 2 items in a row
        if width > 1 {
            itemWidth -= minimumInteritemSpacing
        }
        var itemHeight = size.height / CGFloat(height)
        if height > 1 {
            itemHeight -= minimumLineSpacing
        }
        let edgeLength = min(itemWidth, itemHeight)
        itemSize = CGSize(width: edgeLength, height: edgeLength)
    }

    // calculate origin for every item
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = super.layoutAttributesForItem(at: indexPath)

        // calculate item position in the grid
        let col = CGFloat(indexPath.row % width)
        let row = CGFloat(Int(indexPath.row / width))

        // don't forget to take into account 'minimumInteritemSpacing' and 'minimumLineSpacing'
        let x = col * itemSize.width + col * minimumInteritemSpacing
        let y = row * itemSize.height + row * minimumLineSpacing

        // set new origin
        attributes?.frame.origin = CGPoint(x: x, y: y)

        return attributes
    }

    // accumulate all attributes
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }
        var newAttributes = [UICollectionViewLayoutAttributes]()
        for attribute in attributes {
            if let newAttribute = layoutAttributesForItem(at: attribute.indexPath) {
                newAttributes.append(newAttribute)
            }
        }
        return newAttributes
    }
}
</code>```

Set our layout to UICollectionView

Update collection view every time user enters width and height:

```<code>@IBAction func onSetTapped(_ sender: Any) {
    width = Int(widthTextField.text!)
    height = Int(heightTextField.text!)
    if let width = width, let height = height,
       let layout = collectionView.collectionViewLayout as? CollectionLayout {
        layout.set(width: width, height: height)
        collectionView.reloadData()
    }
}
</code>```

Title: UICollectionView not rendering all rows

Body:
I'm trying to create a simple app, where one can enter a number of columns and a number of rows for an UICollectionView. The collection view then calculates the size of possible squares that fit into it and draws them.
I want to allow a maximum of 32 in width and 64 in height. Scrolling is disabled as the whole grid should be shown at once.

For example, 4x8 looks like this

and 8x4 will look like this

So as one can see that works fine. The problems comes with a higher amount of columns and/or rows. Up to 30x8 everything is fine but starting with 31 only 6 of the 8 rows are drawn.

So I don't understand why. Following is the code I use to calculate everything:

Number of section and number of rows:

func numberOfSections(in collectionView: UICollectionView) -> Int
{
    let num = Int(heightInput.text!)
    if(num != nil)
    {
        if(num! > 64)
        {
            return 64
        }
        return num!
    }
    return 8
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    let num = Int(widthInput.text!)
    if(num != nil)
    {
        if(num! > 32)
        {
            return 32
        }
        return num!
    }
    return 4
}

Cell for item at indexPath

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let size = calculateCellSize()
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    var origin = cell.frame.origin
    origin.x = 1+CGFloat(indexPath.row) + size.width*CGFloat(indexPath.row)
    origin.y = 1+CGFloat(indexPath.section) + size.height*CGFloat(indexPath.section)
    cell.frame = CGRect(origin: origin, size: size)
    NSLog("Cell X:%@, Cell Y:%@",origin.x.description,origin.y.description)
    return cell
}

The calculate size method

func calculateCellSize() -> CGSize
{
    //First check if we have valid values
    let col = Int(widthInput.text!)
    let row = Int(heightInput.text!)
    if(col == nil || row == nil)
    {
        return CGSize(width: 48.0, height: 48.0)
    }
    //If there are more or equal amount of columns than rows
    let columns = CGFloat(col!)
    let rows = CGFloat(row!)
    if(columns >= rows)
    {
        //Take the grid width
        let gridWidth = drawCollection.bounds.size.width
        //Calculate the width of the "pixels" that fit the width of the grid
        var pixelWidth = gridWidth/columns
        //Remember to substract the inset from the width
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelWidth -= (drawLayout?.sectionInset.left)! + 1/columns
        return CGSize(width: pixelWidth, height: pixelWidth)
    }
    else
    {
        //Rows are more than columns
        //Take the grid height as reference here
        let gridHeight = drawCollection.bounds.size.height
        //Calculate the height of the "pixels" that fit the height of the grid
        var pixelHeight = gridHeight/rows
        //Remember to substract the inset from the height
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelHeight -= (drawLayout?.sectionInset.top)! + 1/rows
        return CGSize(width: pixelHeight, height: pixelHeight)
    }
    return CGSize(width: 48.0, height: 48.0)
}

For debugging reasons I put a counter into the cellforItemAtIndexPath method and in fact I can see that the last two rows are not called. The counter ends at 185 but in theory it should have been called 248 times and in fact the difference will show it is 2*32 - 1(for the uneven 31) so the last missing rows....

Several things came to my mind what the reason is but nothing of it seems to be:

the cells are not drawn at the right location (aka outside the grid) -> At least not correct as the method is only called 185 times.

The cells are calculated to be outside the grid therefore not tried to be rendered by the UICollectionView -> Still possible as I couldn't figure how to proof that.

There is a (if so hopefully configurable) maximum amount of elements the UICollectionView can draw and 31x8 already exceeds that number -> Still possible couldn't find anything about that.

So summary:

Is it possible to display all elements in the grid (32x64 max) and if so, what is wrong in my implementation?

Thank you all for your time and answers!

Body:
You need to develop your own UICollectionViewLayout. With this approach you can achieve any result human being can imagine.

import UIKit

class CollectionLayout: UICollectionViewFlowLayout {

    private var width: Int = 1
    private var height: Int = 1

    func set(width: Int, height: Int) {
        guard width > 0, height > 0 else { return }

        self.height = height
        self.width = width
        calculateItemSize()
    }

    private func calculateItemSize() {
        guard let collectionView = collectionView else { return }
        let size = collectionView.frame.size
        var itemWidth = size.width / CGFloat(width)
        // spacing is needed only if there're more than 2 items in a row
        if width > 1 {
            itemWidth -= minimumInteritemSpacing
        }
        var itemHeight = size.height / CGFloat(height)
        if height > 1 {
            itemHeight -= minimumLineSpacing
        }
        let edgeLength = min(itemWidth, itemHeight)
        itemSize = CGSize(width: edgeLength, height: edgeLength)
    }

    // calculate origin for every item
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = super.layoutAttributesForItem(at: indexPath)

        // calculate item position in the grid
        let col = CGFloat(indexPath.row % width)
        let row = CGFloat(Int(indexPath.row / width))

        // don't forget to take into account 'minimumInteritemSpacing' and 'minimumLineSpacing'
        let x = col * itemSize.width + col * minimumInteritemSpacing
        let y = row * itemSize.height + row * minimumLineSpacing

        // set new origin
        attributes?.frame.origin = CGPoint(x: x, y: y)

        return attributes
    }

    // accumulate all attributes
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }
        var newAttributes = [UICollectionViewLayoutAttributes]()
        for attribute in attributes {
            if let newAttribute = layoutAttributesForItem(at: attribute.indexPath) {
                newAttributes.append(newAttribute)
            }
        }
        return newAttributes
    }
}

Set our layout to UICollectionView

Update collection view every time user enters width and height:

@IBAction func onSetTapped(_ sender: Any) {
    width = Int(widthTextField.text!)
    height = Int(heightTextField.text!)
    if let width = width, let height = height,
       let layout = collectionView.collectionViewLayout as? CollectionLayout {
        layout.set(width: width, height: height)
        collectionView.reloadData()
    }
}


答:
Depends on your programming language.

In C#, it would be the following: int.Parse(s.Substring(0, s.Length - 2));

However, I would do it mathematically as Sebastian P. detailed.

Title: euler question about strings and ints

Body:
i am currently programming in euler (mathematics)
the problem is i need to split the first 10 numbers and the latst 2

: 012345678912 =

0123456789      12

i can do this by using the substring method
but i need to calculate further with the first 10 numbers
so what i can do is cast the string back to an int
but i have no idea how to do it ..
can anyone help me ?

thanks in advance


问:
Push variable from loop into array that is indexed
I've looked around for awhile and haven't found any solutions. What I'm trying to do is store the variable that contains my option values into an array with an index for each element that is in the variable so I can call it's index.

Here is my code:

var selectArray = ['Package 1', 'Package 2'];
var selectField = document.getElementById('testS');

 for(i = 0; i < selectArray.length; i++) {
  let arrayList = selectArray[i];
  let arrayOption = document.createElement('option');
  selectField.appendChild(arrayOption);
  arrayOption.value = arrayList; // Value Option in Option
  arrayOption.innerHTML = arrayList; // Text in Option

  let newArray = [];

  newArray.push(arrayOption.value);
    // This doesn't work I want each element in the variable to be indexed in the array. so I can do for example newArray[0] which will return Package 1 from the value.

 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="fromList" id="testS"></select></code>```

Reason I'm trying to push the option values from my loop variable into the array is because I want to select each of there index and append to them another array that contains data.

答:
You just need to change where you are declaring the newArray. let creates block level scope, so if you delcare it within a loop, it is scoped to just that one iteration of the loop. You don't want the variable re-declared upon each iteration of the loop because that wipes out the earlier value.

var selectArray = ['Package 1', 'Package 2'];
var selectField = document.getElementById('testS');

// You need to declare variables in the scope that you will want to use them
let newArray = [];

 for(i = 0; i < selectArray.length; i++) {
  let arrayList = selectArray[i];
  let arrayOption = document.createElement('option');
  selectField.appendChild(arrayOption);
  arrayOption.value = arrayList; // Value Option in Option
  arrayOption.innerHTML = arrayList; // Text in Option

  newArray.push(arrayOption.value);
 }

console.log(newArray);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="fromList" id="testS"></select></code>```

Now, the next question is why do you really need to even do this? The option elements in the select can always be gotten on-demand as an array with this:

```<code>var options = Array.prototype.slice.call(document.querySelectorAll("#testS > option"));
</code>```

Body:
I've looked around for awhile and haven't found any solutions. What I'm trying to do is store the variable that contains my option values into an array with an index for each element that is in the variable so I can call it's index.

Here is my code:

var selectArray = ['Package 1', 'Package 2'];
var selectField = document.getElementById('testS');

 for(i = 0; i < selectArray.length; i++) {
  let arrayList = selectArray[i];
  let arrayOption = document.createElement('option');
  selectField.appendChild(arrayOption);
  arrayOption.value = arrayList; // Value Option in Option
  arrayOption.innerHTML = arrayList; // Text in Option

  let newArray = [];

  newArray.push(arrayOption.value);
    // This doesn't work I want each element in the variable to be indexed in the array. so I can do for example newArray[0] which will return Package 1 from the value.

 }

<select name="fromList" id="testS"></select>

Reason I'm trying to push the option values from my loop variable into the array is because I want to select each of there index and append to them another array that contains data.

Body:
You just need to change where you are declaring the newArray. let creates block level scope, so if you delcare it within a loop, it is scoped to just that one iteration of the loop. You don't want the variable re-declared upon each iteration of the loop because that wipes out the earlier value.

var selectArray = ['Package 1', 'Package 2'];
var selectField = document.getElementById('testS');

// You need to declare variables in the scope that you will want to use them
let newArray = [];

 for(i = 0; i < selectArray.length; i++) {
  let arrayList = selectArray[i];
  let arrayOption = document.createElement('option');
  selectField.appendChild(arrayOption);
  arrayOption.value = arrayList; // Value Option in Option
  arrayOption.innerHTML = arrayList; // Text in Option

  newArray.push(arrayOption.value);
 }

console.log(newArray);

<select name="fromList" id="testS"></select>

Now, the next question is why do you really need to even do this? The option elements in the select can always be gotten on-demand as an array with this:

var options = Array.prototype.slice.call(document.querySelectorAll("#testS > option"));


问:
RestHighLevelClient with BulkProcessor Elastic Search issue
Earlier I was using TransportClient in my app.
Recently moving towards AWS manages Elastic Search services.
Learned that AWS managed ES Cluster would not support TransportClient.

So migrating the code where it was using BulkProcessort to insert documents to ES.
When I refactor the code as a part of ES documentation I added this line.

```<code>BulkProcessor bulkProcessor = BulkProcessor.builder(client::bulkAsync, listener).build();
</code>```

and I get an error at client::bulkAsync saying Client is not a functional interface.

Need help understanding what am I doing wrong.

Document Link For reference,

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-document-bulk.html#java-rest-high-document-bulk-processor

答:
What is the type of your client object?
It must be a RestHighLevelClient instance.

Here is a working code: https://github.com/dadoonet/legacy-search/blob/02-bulk/src/main/java/fr/pilato/demo/legacysearch/dao/ElasticsearchDao.java

Body:
Earlier I was using TransportClient in my app.
Recently moving towards AWS manages Elastic Search services.
Learned that AWS managed ES Cluster would not support TransportClient.

So migrating the code where it was using BulkProcessort to insert documents to ES.
When I refactor the code as a part of ES documentation I added this line.

BulkProcessor bulkProcessor = BulkProcessor.builder(client::bulkAsync, listener).build();

and I get an error at client::bulkAsync saying Client is not a functional interface.

Need help understanding what am I doing wrong.

Document Link For reference,

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-document-bulk.html#java-rest-high-document-bulk-processor


问:
PLSQL ORACLE: Errors with triggers
I am trying to make a  trigger for a table PET that has a field Invitation and it turns Yes or No based on the value of a field called Phone from a table PEOPLE. If the phone value isn't null and some of the other fields in the PET table have valid values and aren't null, the value in Invitation field should turn to Yes.

I am able to do that but the problem is later on when I try to update my table and set one of the fields to null, it doesn't update the value of invitation field to No. So now I am working on making a trigger for the PET table itself that checks to see if the required fields are not null so that the value of invitation can be changed.

However, the problem is that the user has to enter data into the PET table before going towards the PEOPLE table. So my trigger isn't able to fetch any value when I am inserting data inside my table PET.

Here is what I did for the trigger:

```<code>create or replace trigger Phone_check
    before insert or update on PETS
    for each row
DECLARE
    SELECT phone INTO v_phone
    FROM PEOPLE
        INNER JOIN Family ON PEOPLE.ID=FAMILY.ID
        INNER JOIN PETS ON FAMILY.ID=PETS.ID
    WHERE PETS.ID=:NEW.ID;
    IF :NEW.NAME IS NOT NULL
    AND :NEW.AGE IS NOT NULL
    AND v_phone IS NOT NULL THEN
        :NEW.INVITATION:='Yes';
    ELSIF :NEW.NAME IS NULL
    OR :NEW.AGE IS NULL
    AND v_phone IS NULL THEN
       :NEW.INVITATION:='No';
    END IF;
END;
</code>```

I get what the problem with this trigger is:  there are no values in the people or family table yet. But the PET table is supposed to be the first table. How should I fix this? Is there a way to activate this trigger only after required values already exist inside other tables? I'm really confused.

答:
"when in the end I change a value in one of the required fields in the PET tables and set it to null, The invitation still stays set to YES."

The condition in your trigger that drives changing the invitation to No is this:

```<code>ELSIF :NEW.NAME IS NULL
OR :NEW.AGE IS NULL
AND v_phone IS NULL THEN
</code>```

So if PEOPLE.PHONE is not null the trigger won't go down that branch. It seems like what you want is:

```<code>ELSIF :NEW.NAME IS NULL
OR :NEW.AGE IS NULL
OR v_phone IS NULL THEN
</code>```

The trigger will then act if you set PET.NAME or PET.AGE to null.

The business logic here is really confused. The conditions are based on the presence of records in three tables: this is a poor use case for a trigger. A better implementation would be to have a stored procedure to insert the  records into all three tables and which manages the business rules such as setting the invitation flag.

Obviously this is a bit vague, but a proper solution will require more details about your scenario. What is you application? How are records are inserted? What is the Unit of Work (transaction)?

Title: PLSQL ORACLE: Errors with triggers

Body:
I am trying to make a  trigger for a table PET that has a field Invitation and it turns Yes or No based on the value of a field called Phone from a table PEOPLE. If the phone value isn't null and some of the other fields in the PET table have valid values and aren't null, the value in Invitation field should turn to Yes.

I am able to do that but the problem is later on when I try to update my table and set one of the fields to null, it doesn't update the value of invitation field to No. So now I am working on making a trigger for the PET table itself that checks to see if the required fields are not null so that the value of invitation can be changed.

However, the problem is that the user has to enter data into the PET table before going towards the PEOPLE table. So my trigger isn't able to fetch any value when I am inserting data inside my table PET.

Here is what I did for the trigger:

create or replace trigger Phone_check
    before insert or update on PETS
    for each row
DECLARE
    SELECT phone INTO v_phone
    FROM PEOPLE
        INNER JOIN Family ON PEOPLE.ID=FAMILY.ID
        INNER JOIN PETS ON FAMILY.ID=PETS.ID
    WHERE PETS.ID=:NEW.ID;
    IF :NEW.NAME IS NOT NULL
    AND :NEW.AGE IS NOT NULL
    AND v_phone IS NOT NULL THEN
        :NEW.INVITATION:='Yes';
    ELSIF :NEW.NAME IS NULL
    OR :NEW.AGE IS NULL
    AND v_phone IS NULL THEN
       :NEW.INVITATION:='No';
    END IF;
END;

I get what the problem with this trigger is:  there are no values in the people or family table yet. But the PET table is supposed to be the first table. How should I fix this? Is there a way to activate this trigger only after required values already exist inside other tables? I'm really confused.

Body:
"when in the end I change a value in one of the required fields in the PET tables and set it to null, The invitation still stays set to YES."

The condition in your trigger that drives changing the invitation to No is this:

ELSIF :NEW.NAME IS NULL
OR :NEW.AGE IS NULL
AND v_phone IS NULL THEN

So if PEOPLE.PHONE is not null the trigger won't go down that branch. It seems like what you want is:

ELSIF :NEW.NAME IS NULL
OR :NEW.AGE IS NULL
OR v_phone IS NULL THEN

The trigger will then act if you set PET.NAME or PET.AGE to null.

The business logic here is really confused. The conditions are based on the presence of records in three tables: this is a poor use case for a trigger. A better implementation would be to have a stored procedure to insert the  records into all three tables and which manages the business rules such as setting the invitation flag.

Obviously this is a bit vague, but a proper solution will require more details about your scenario. What is you application? How are records are inserted? What is the Unit of Work (transaction)?


问:
IIS/ASP.NET - Infinite redirects in deployed code
I am getting an infinite redirect loop only when I deploy my code to a Production environment.  I am attempting to force SSL on the page by using a simple code redirect.  I am running into the issue with a stripped-down old school web form (I'm stuck on .NET 3.5 for this project).  All code is below.
Any ideas on why I would get an infinite redirect look in Production and not Test?

Notes on test vs production:

Test is IIS 10 on Windows 10.

Production is IIS 6 on Windows Server 2003 R2.

Test uses a self-signed SSL cert.

Production uses a fully trusted SSL cert.

Identical web.configs

ASPX Markup:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SecurePage.aspx.cs" Inherits="wwwroot.SecurePage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            This page is secure!
        </div>
    </form>
</body>
</html>
</code>```

CODE-BEHIND:

```<code>namespace wwwroot
{
    public partial class SecurePage : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.Url.ToString().ToLower().StartsWith("https://"))
                Response.Redirect(Request.Url.ToString().ToLower().Replace("http://", "https://"));
        }
    }
}
</code>```

答:
If you have a load balancer (e.g. IIS ARR), I would suspect that your application may be receiving http from it. Your code is similar to a check Request.IsSecureConnection which will always be false in such a case, thereby causing the infinite loop. Essentially client -> load balancer is https, then from load balancer -> web farm it's http

...there IS INDEED a load balancer in the equation. I had tried Request.IsSecureConnection at first and got the infinite redirect...I can hit static resources with the https scheme without issue, CSS files, JS files, Images, etc.

Your load balancer will typically (hopefully) have a header that indicates such. You should handle it at the IIS level with a rewrite rule - before it hits the ASP.net pipeline (which is why/how static resources are "unaffected"). You'll have to remove code that checks for it too (don't check and redirect at the ASP.Net level).

Here's a sample I use for a specific provider (obviously you'll have to check with your provider):

```<code><rule name="Redirect to HTTPS" stopProcessing="true">
    <match url=".*" />

    <conditions>
      <add input="{HTTP_CLUSTER_HTTPS}" pattern="^on$" negate="true" />
      <add input="{HTTP_CLUSTER_HTTPS}" pattern=".+" negate="true" />

    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{SCRIPT_NAME}/{REQUEST_URI}" redirectType="SeeOther" />
</rule>
</code>```

Hth...

Body:
I am getting an infinite redirect loop only when I deploy my code to a Production environment.  I am attempting to force SSL on the page by using a simple code redirect.  I am running into the issue with a stripped-down old school web form (I'm stuck on .NET 3.5 for this project).  All code is below.
Any ideas on why I would get an infinite redirect look in Production and not Test?

Notes on test vs production:

Test is IIS 10 on Windows 10.

Production is IIS 6 on Windows Server 2003 R2.

Test uses a self-signed SSL cert.

Production uses a fully trusted SSL cert.

Identical web.configs

ASPX Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SecurePage.aspx.cs" Inherits="wwwroot.SecurePage" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

            This page is secure!

    </form>

CODE-BEHIND:

namespace wwwroot
{
    public partial class SecurePage : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.Url.ToString().ToLower().StartsWith("https://"))
                Response.Redirect(Request.Url.ToString().ToLower().Replace("http://", "https://"));
        }
    }
}

Body:
If you have a load balancer (e.g. IIS ARR), I would suspect that your application may be receiving http from it. Your code is similar to a check Request.IsSecureConnection which will always be false in such a case, thereby causing the infinite loop. Essentially client -> load balancer is https, then from load balancer -> web farm it's http

...there IS INDEED a load balancer in the equation. I had tried Request.IsSecureConnection at first and got the infinite redirect...I can hit static resources with the https scheme without issue, CSS files, JS files, Images, etc.

Your load balancer will typically (hopefully) have a header that indicates such. You should handle it at the IIS level with a rewrite rule - before it hits the ASP.net pipeline (which is why/how static resources are "unaffected"). You'll have to remove code that checks for it too (don't check and redirect at the ASP.Net level).

Here's a sample I use for a specific provider (obviously you'll have to check with your provider):

<rule name="Redirect to HTTPS" stopProcessing="true">
    <match url=".*" />

    <conditions>
      <add input="{HTTP_CLUSTER_HTTPS}" pattern="^on$" negate="true" />
      <add input="{HTTP_CLUSTER_HTTPS}" pattern=".+" negate="true" />

    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{SCRIPT_NAME}/{REQUEST_URI}" redirectType="SeeOther" />
</rule>

Hth...


问:
Permission issue with simple appveyor script
So I have this very simple script which just tries to create a text file and then read it.

```<code>version: 1.0.{build}-{branch}

shallow_clone: true

environment:
matrix:
    - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
    TOOLSET: msvc-14.1
    ARCH: x86_64
    - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
    TOOLSET: msvc-14.1
    ARCH: x86

install:
- if %ARCH% == x86 ( set TRIPLET=x86-windows ) else ( set TRIPLET=x64-windows )
- if %ARCH% == x86 ( set AM=32 ) else ( set AM=64 )
- git clone -b master --depth 1 https://github.com/boostorg/boost.git boost-root
- cd boost-root

build: off

test_script:
- set PATH=%ADDPATH%%PATH%
- |-
    set VCPKG=%APPVEYOR_BUILD_FOLDER%\..\vcpkg\installed\%TRIPLET%
    set "CHUNK=^<include^>%VCPKG%\include ^<search^>%VCPKG%\lib"
    echo using zlib : : %CHUNK% ; > config.jam
    echo using libjpeg : : %CHUNK% ; >> config.jam
    echo using libpng : : ^<name^>libpng16 %CHUNK% ; >> config.jam
    echo using libtiff : : %CHUNK% ; >> config.jam
    more config.jam
</code>```

When I run it I get the following error:

```<code>Cannot access file C:\projects\gil\boost-root\config.jam
Command exited with code 1
</code>```

Is there something obviously wrong that I'm missing?

答: I think set "CHUNK=^<include^>%VCPKG%\include ^<search^>%VCPKG%\lib" breaks something in environment variables. Try moving first " after =, like set CHUNK="^<include^>%VCPKG%\include ^<search^>%VCPKG%\lib".

Body:
So I have this very simple script which just tries to create a text file and then read it.

version: 1.0.{build}-{branch}

shallow_clone: true

environment:
matrix:
    - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
    TOOLSET: msvc-14.1
    ARCH: x86_64
    - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
    TOOLSET: msvc-14.1
    ARCH: x86

install:
- if %ARCH% == x86 ( set TRIPLET=x86-windows ) else ( set TRIPLET=x64-windows )
- if %ARCH% == x86 ( set AM=32 ) else ( set AM=64 )
- git clone -b master --depth 1 https://github.com/boostorg/boost.git boost-root
- cd boost-root

build: off

test_script:
- set PATH=%ADDPATH%%PATH%
- |-
    set VCPKG=%APPVEYOR_BUILD_FOLDER%\..\vcpkg\installed\%TRIPLET%
    set "CHUNK=^<include^>%VCPKG%\include ^<search^>%VCPKG%\lib"
    echo using zlib : : %CHUNK% ; > config.jam
    echo using libjpeg : : %CHUNK% ; >> config.jam
    echo using libpng : : ^<name^>libpng16 %CHUNK% ; >> config.jam
    echo using libtiff : : %CHUNK% ; >> config.jam
    more config.jam

When I run it I get the following error:

Cannot access file C:\projects\gil\boost-root\config.jam
Command exited with code 1

Is there something obviously wrong that I'm missing?


问:
There is any limit on how many critical section i can create?
i have a Class that can be accessed on multiple thread.

To make sure i don't have simultaneous access i will use a CCriticalSection

I was wondering if i can just create a CCriticalSectionfor any copy of the object (i think i can have about 100-1000 this object in the program) or it will be best to create a static member CCriticalSection and use this for all the object?

答: If your scope was only to "signal" why not use InterlockedExchange and Interlock... family functions?</p>


问:
Unable to set BackgroundColor with MvxBind
I am trying to change the RecyclerView's item color.  The code below only shows the RelativeLayout which is the root layout of the item layout.

I have the following code:

(Item) Layout:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/item_listitem"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal"
    android:paddingTop="2dp"
    android:paddingBottom="2dp"
    android:paddingStart="@dimen/margin_left_shoppinglistitems"
    android:paddingEnd="@dimen/margin_medium"
    local:MvxBind="BackgroundColor NativeColor(Background)">

  ...

</RelativeLayout>
```

<p>ViewModel:</p>

<pre class="lang-cs prettyprint-override"><code>public class ListItem : TableData, IListItem
{
    ...
    public MvxColor Background { get { return new MvxColor(255,189,69,128); } }
    ...
}
</code>```

I have added MvvmCross.Plugin.Color to both Droid and Core project. I have no idea why this is not working?  I can see Background property being accessed but the color is not being set to the set test value (in the future I want the color to be based on another boolean property). Any ideas?

答:
Checks that you have the plugin color installed and it´s initialized. I use binding in this way:
local:MvxBind="BackgroundColor Background, Converter=NativeColor"</p>

Body:
I am trying to change the RecyclerView's item color.  The code below only shows the RelativeLayout which is the root layout of the item layout.

I have the following code:

(Item) Layout:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/item_listitem"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal"
    android:paddingTop="2dp"
    android:paddingBottom="2dp"
    android:paddingStart="@dimen/margin_left_shoppinglistitems"
    android:paddingEnd="@dimen/margin_medium"
    local:MvxBind="BackgroundColor NativeColor(Background)">

  ...

</RelativeLayout>

ViewModel:

public class ListItem : TableData, IListItem
{
    ...
    public MvxColor Background { get { return new MvxColor(255,189,69,128); } }
    ...
}

I have added MvvmCross.Plugin.Color to both Droid and Core project. I have no idea why this is not working?  I can see Background property being accessed but the color is not being set to the set test value (in the future I want the color to be based on another boolean property). Any ideas?


问:
What is the run time of shift/unshift in a ruby array
Does anyone know how efficient shift and unshift are in a ruby array?

Deleting from the beginning of an array and having to move every element in memory can become very inefficient. I assume ruby does this some other way.

Any info on the following would be helpful:

- Algorithmic runtime

- Implementation

- General efficiency

- Would shift/unshift be acceptable to use for a queue (in something like C++ this would not)

Thank you!

答:
In older versions of Ruby (before ~2012), unshift was an O(n) operation. However, an optimization was added in this commit and released in Ruby 2.0.0 that makes the unshift amortized O(1), meaning that it is guaranteed, on average, to be O(1), but an individual operation may be O(n). This is the same running time as shift.

This CS Stack Exchange post has a good explanation of how this works and how you end up with an O(1) amortized running time (it's about C++'s vector::push_back, but it works the same way).

ContentLicense: CC BY-SA 4.0


问:
Using global variables in chef ruby
Is it possible to define some variable as global in a chef recipe.Like I am declaring & changing a var in a chef resource and later i want to use this changed value in the recipe code.

```<code>version=""
ruby 'extract_module' do
    #cwd ::File.dirname(C:\\chef\\cache)
    code <<-EOH
        require 'win32/registry'
        Win32::Registry::HKEY_LOCAL_MACHINE.open(
        'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall') do |reg|
            reg.each_key do |key|
                k = reg.open(key)
                app = k["DisplayName"] rescue nil

                if app == "Qlik Sense 3.2"
                    version = k["DisplayVersion"] rescue nil
                    puts version
                end
            end
        end
    EOH
end

puts "#{version}"
</code>```

This variable is not printing outside the ruby resource. Can we do something like python, declare with global keyword & modify the value. Any similar here?

答: The ruby resource doesn't run in the same process, it runs ruby -E as a subprocess. What you want is a ruby_block resource, which is unrelated.

Title: Using global variables in chef ruby

Body:
Is it possible to define some variable as global in a chef recipe.Like I am declaring & changing a var in a chef resource and later i want to use this changed value in the recipe code.

version=""
ruby 'extract_module' do
    #cwd ::File.dirname(C:\\chef\\cache)
    code <<-EOH
        require 'win32/registry'
        Win32::Registry::HKEY_LOCAL_MACHINE.open(
        'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall') do |reg|
            reg.each_key do |key|
                k = reg.open(key)
                app = k["DisplayName"] rescue nil

                if app == "Qlik Sense 3.2"
                    version = k["DisplayVersion"] rescue nil
                    puts version
                end
            end
        end
    EOH
end

puts "#{version}"

This variable is not printing outside the ruby resource. Can we do something like python, declare with global keyword & modify the value. Any similar here?


问:
Converting c++ to c#
1) My program runs fine in c++, im just trying to convert it to c#, Need help converting the ifstream part
c++ code:

```<code>ifstream data;
data.open("data.txt");
if (data.fail()) {
    cout << "Error opening file\n";
    exit(1);
}
</code>```

So far this is what i got from research is to use filestream and streamreader
c# code: Just want to make sure its equivalent.

```<code>        if(!File.Exists(data))
        {
            Console.Write("{0} does not exist.", data);
            return 0;
        }
        FileStream fsIn = new FileStream(data, FileMode.Open,
         FileAccess.Read, FileShare.Read);
        using (StreamReader sr = new StreamReader(fsIn))
</code>```

2) Next part where im stuck on, is on the function where its suppose to get the data from the .txt file and store into an array (the data.txt file is added from solution of the project so no url to the file was required)(using visual studio)
c++ code:

void read_file(ifstream& fsIn, float h_temp[], int array_size, int& valid_entries_high, int& valid_entries_low, float l_temp[])
{

```<code>while (!data.eof()) // eof = end of file
{
    data >> h_temp[valid_entries_high];
    valid_entries_high++;

    data >> l_temp[valid_entries_low];
    valid_entries_low++;

    if (valid_entries_high + valid_entries_low == array_size) {
        cout << "Array's full,\n";
        break;
    }
}
    if (valid_entries_high == valid_entries_low)
    {
        cout << "file is valid" << endl;
    }
    else
    {
        exit(1);
    }
    //check make sure theyre the same length
</code>```

}

This is where im stuck on with my c#:
 public static void read_file(FileStream fsIn, float[] h_temp, int array_size, ref int valid_entries_high, ref int valid_entries_low, float[] l_temp)
        {

```<code>        while (!fsIn.EndofStream()) // eof = end of file
        {
            fsIn >> h_temp[valid_entries_high];
            valid_entries_high++;

            fsIn >> l_temp[valid_entries_low];
            valid_entries_low++;

            if (valid_entries_high + valid_entries_low == array_size)
            {
                Console.WriteLine("Array's full,\n");
                break;
            }
        }
        if (valid_entries_high == valid_entries_low)
        {
            Console.WriteLine("file is valid");
        }
        else
        {
            Environment.Exit(1);
        }

    }
</code>```

converting that input << sign into c# and also why .EndofStream wont work? Im using sysmtem.io like the tutorial said but it says Filestream does not contain a definition for 'endofstream'. Also is ifstream& the same as FileStream ref?
Any advice will be greatly apperciated!

答:
If you wanted to do it manually the simplest way is the way it's done in the .NET framework:

```<code>String line;
List<String> lines = new List<String>();

using (StreamReader sr = new StreamReader(path, encoding))
    while ((line = sr.ReadLine()) != null)
        lines.Add(line);
</code>```

If you wanted an array:

```<code>string[] linesArray = lines.ToArray();
</code>```

Title: Converting c++ to c#

Body:
1) My program runs fine in c++, im just trying to convert it to c#, Need help converting the ifstream part
c++ code:

ifstream data;
data.open("data.txt");
if (data.fail()) {
    cout << "Error opening file\n";
    exit(1);
}

So far this is what i got from research is to use filestream and streamreader
c# code: Just want to make sure its equivalent.

        if(!File.Exists(data))
        {
            Console.Write("{0} does not exist.", data);
            return 0;
        }
        FileStream fsIn = new FileStream(data, FileMode.Open,
         FileAccess.Read, FileShare.Read);
        using (StreamReader sr = new StreamReader(fsIn))

2) Next part where im stuck on, is on the function where its suppose to get the data from the .txt file and store into an array (the data.txt file is added from solution of the project so no url to the file was required)(using visual studio)
c++ code:

void read_file(ifstream& fsIn, float h_temp[], int array_size, int& valid_entries_high, int& valid_entries_low, float l_temp[])
{

while (!data.eof()) // eof = end of file
{
    data >> h_temp[valid_entries_high];
    valid_entries_high++;

    data >> l_temp[valid_entries_low];
    valid_entries_low++;

    if (valid_entries_high + valid_entries_low == array_size) {
        cout << "Array's full,\n";
        break;
    }
}
    if (valid_entries_high == valid_entries_low)
    {
        cout << "file is valid" << endl;
    }
    else
    {
        exit(1);
    }
    //check make sure theyre the same length

}

This is where im stuck on with my c#:
 public static void read_file(FileStream fsIn, float[] h_temp, int array_size, ref int valid_entries_high, ref int valid_entries_low, float[] l_temp)
        {

        while (!fsIn.EndofStream()) // eof = end of file
        {
            fsIn >> h_temp[valid_entries_high];
            valid_entries_high++;

            fsIn >> l_temp[valid_entries_low];
            valid_entries_low++;

            if (valid_entries_high + valid_entries_low == array_size)
            {
                Console.WriteLine("Array's full,\n");
                break;
            }
        }
        if (valid_entries_high == valid_entries_low)
        {
            Console.WriteLine("file is valid");
        }
        else
        {
            Environment.Exit(1);
        }

    }

converting that input << sign into c# and also why .EndofStream wont work? Im using sysmtem.io like the tutorial said but it says Filestream does not contain a definition for 'endofstream'. Also is ifstream& the same as FileStream ref?
Any advice will be greatly apperciated!

Body:
If you wanted to do it manually the simplest way is the way it's done in the .NET framework:

String line;
List<String> lines = new List<String>();

using (StreamReader sr = new StreamReader(path, encoding))
    while ((line = sr.ReadLine()) != null)
        lines.Add(line);

If you wanted an array:

string[] linesArray = lines.ToArray();


问:
Can't target two different dropdowns properly by jQuery
I have two seperate dropdowns, whose hover states can't be target by css based on the html markup. I tried to solve this by jQuery and I am halfway done. One problem still exists all the time and I am trying to solve this by days now.

If I hover the link of the second dropdown and moves the mouse really fast to the link of the first dropdown and then move the mouse immediately into the container of the displayed first dropdown, this dropdown menu disappears. It seems that my script removes the adding css classes in this case. This situation only appears with fast mouse movement but it drives me crazy. I am unable to figure out why this happens. I include a jsfiddle demo, where you can see the problem by yourself.

jQuery

```<code>jQuery(document).ready(function($) {
    var $body = $('body'),
        $tg_header = $('#main-header'),
        $tg_top_menu = $('ul.nav'),
        /*$tg_submenu_link = $('.tg-submenu__link'),*/
        $tg_submenu_link_tg = $('.tg-submenu__link--tg'),
        $tg_submenu_link_abteilungen = $('.tg-submenu__link--abteilungen'),
        $tg_submenu = $('.tg-submenu'),
        $tg_submenu_tg = $('.tg-submenu__tg'),
        $tg_submenu_abteilungen = $('.tg-submenu__abteilungen'),
        et_menu_hover_triggered = false;

                /* General Hiding Function for first mega menu */
        function tg_hide_tg() {
            setTimeout( function () {
                if ($tg_top_menu.find('.tg-submenu__link--tg:hover').length == 0 && $('.tg-submenu__tg:hover').length == 0) {
                    $body.removeClass('tg-submenu__tg--active')
                };
                }, 50);
        }

                /* General Hiding Function for second mega menu */
        function tg_hide_abteilungen() {
            setTimeout( function () {
                if ($tg_top_menu.find('.tg-submenu__link--abteilungen:hover').length == 0 && $('.tg-submenu__abteilungen:hover').length == 0) {
                    $body.removeClass('tg-submenu__abteilungen--active')
                };
                }, 50);
        }

                /* Mouse Hover Mega Link 1 and Leave Link */
        $tg_submenu_link_tg.mouseenter(function() {
            $body.addClass('tg-submenu__tg--active');
        }).mouseleave(function() {
            tg_hide_tg();
        });

                /* Mouse Leave Mega Menu Container 1 */
        $tg_submenu_tg.mouseleave(function () {
            setTimeout(function () {
                if ($('.tg-submenu__link--tg:hover').length == 0 && $('.tg-submenu__tg:hover').length == 0 ) {
                    $body.removeClass('tg-submenu__tg--active');
                };
            },50)
        });

                /* Mouse Hover Mega Link 2 and Leave Link */
        $tg_submenu_link_abteilungen.mouseenter(function() {
            $body.addClass('tg-submenu__abteilungen--active');
        }).mouseleave(function() {
            tg_hide_abteilungen();
        })

        /* Mouse Leave Mega Menu Container 2 */
        $tg_submenu_abteilungen.mouseleave(function () {
            setTimeout(function () {
                if ($('.tg-submenu__link--abteilungen:hover').length == 0 && $('.tg-submenu__abteilungen:hover').length == 0 ) {
                    $body.removeClass('tg-submenu__abteilungen--active');
                };
            },50)
        });
    });
</code>```

HTML-Markup

```<code><body>
<header id="main-header">
  <div class="container">
    <div id="et-top-navigation">
          <div class="tg-mainMenu__left">
              <nav id="top-menu-nav">
                  <ul id="top-menu" class="nav">
            <li id="menu-item-154" class="tg-submenu__link tg-submenu__link--tg menu-item"><a href="#">MEGA LINK 1</a></li>
            <li id="menu-item-156" class="tg-submenu__link tg-submenu__link--abteilungen menu-item"><a href="#">MEGA LINK 2</a></li>
            <li id="menu-item-166" class="menu-item menu-item"><a href="#">Normal Link 3</a></li>
          </ul>
         </nav>
            </div><!-- TG-mainMenu__left-->
            <div class="tg-mainMenu__right">
              <nav id="top-menu-nav">
                    <ul id="top-menu" class="nav">
            <li id="menu-item-154" class="menu-item menu-item"><a href="#">Normal Link 4</a></li>
            <li id="menu-item-154" class="menu-item menu-item"><a href="#">Normal Link 5</a></li>
            <li id="menu-item-154" class="menu-item menu-item"><a href="#">Normal Link 6</a></li>
          </ul>
        </nav>
            </div> <!-- tg-mainMenu__right -->
        </div> <!-- #et-top-navigation -->
    <!-- TG Mega 1 -->
    <div class="tg-submenu tg-submenu__tg">
      <div class="container tg-submenu__content">
        <h1>
         MEGA MENU 1
        </h1>
      </div>
    </div>
    <!-- Abteilungen Mega -->
    <div class="tg-submenu tg-submenu__abteilungen">
        <div class="container tg-submenu__content">
          <h1>
            MEGA MENU 2
          </h1>
        </div>
    </div>
  </div> <!-- .container -->
</header>
</body>
</code>```

My fiddle: https://jsfiddle.net/hfammzce/

答:
I dont know why this is happening. But you can use jQuery .show() and .hide() instead of using add/remove class and opacity.

Here is the updated fiddle: https://jsfiddle.net/1dzyszdq/

```<code>    /* General Hiding Function for first mega menu */
    function tg_hide_tg() {
        setTimeout( function () {
            if ($tg_top_menu.find('.tg-submenu__link--tg:hover').length == 0 && $('.tg-submenu__tg:hover').length == 0) {
                $(".tg-submenu__tg").hide();
            };
            }, 50);
    }

    /* Mouse Hover Mega Link 1 and Leave Link */
    $tg_submenu_link_tg.mouseenter(function() {
        $('.tg-submenu__tg').show();
    }).mouseleave(function() {
        tg_hide_tg();
    });
</code>```

Body:
I have two seperate dropdowns, whose hover states can't be target by css based on the html markup. I tried to solve this by jQuery and I am halfway done. One problem still exists all the time and I am trying to solve this by days now.

If I hover the link of the second dropdown and moves the mouse really fast to the link of the first dropdown and then move the mouse immediately into the container of the displayed first dropdown, this dropdown menu disappears. It seems that my script removes the adding css classes in this case. This situation only appears with fast mouse movement but it drives me crazy. I am unable to figure out why this happens. I include a jsfiddle demo, where you can see the problem by yourself.

jQuery

jQuery(document).ready(function($) {
    var $body = $('body'),
        $tg_header = $('#main-header'),
        $tg_top_menu = $('ul.nav'),
        /*$tg_submenu_link = $('.tg-submenu__link'),*/
        $tg_submenu_link_tg = $('.tg-submenu__link--tg'),
        $tg_submenu_link_abteilungen = $('.tg-submenu__link--abteilungen'),
        $tg_submenu = $('.tg-submenu'),
        $tg_submenu_tg = $('.tg-submenu__tg'),
        $tg_submenu_abteilungen = $('.tg-submenu__abteilungen'),
        et_menu_hover_triggered = false;

                /* General Hiding Function for first mega menu */
        function tg_hide_tg() {
            setTimeout( function () {
                if ($tg_top_menu.find('.tg-submenu__link--tg:hover').length == 0 && $('.tg-submenu__tg:hover').length == 0) {
                    $body.removeClass('tg-submenu__tg--active')
                };
                }, 50);
        }

                /* General Hiding Function for second mega menu */
        function tg_hide_abteilungen() {
            setTimeout( function () {
                if ($tg_top_menu.find('.tg-submenu__link--abteilungen:hover').length == 0 && $('.tg-submenu__abteilungen:hover').length == 0) {
                    $body.removeClass('tg-submenu__abteilungen--active')
                };
                }, 50);
        }

                /* Mouse Hover Mega Link 1 and Leave Link */
        $tg_submenu_link_tg.mouseenter(function() {
            $body.addClass('tg-submenu__tg--active');
        }).mouseleave(function() {
            tg_hide_tg();
        });

                /* Mouse Leave Mega Menu Container 1 */
        $tg_submenu_tg.mouseleave(function () {
            setTimeout(function () {
                if ($('.tg-submenu__link--tg:hover').length == 0 && $('.tg-submenu__tg:hover').length == 0 ) {
                    $body.removeClass('tg-submenu__tg--active');
                };
            },50)
        });

                /* Mouse Hover Mega Link 2 and Leave Link */
        $tg_submenu_link_abteilungen.mouseenter(function() {
            $body.addClass('tg-submenu__abteilungen--active');
        }).mouseleave(function() {
            tg_hide_abteilungen();
        })

        /* Mouse Leave Mega Menu Container 2 */
        $tg_submenu_abteilungen.mouseleave(function () {
            setTimeout(function () {
                if ($('.tg-submenu__link--abteilungen:hover').length == 0 && $('.tg-submenu__abteilungen:hover').length == 0 ) {
                    $body.removeClass('tg-submenu__abteilungen--active');
                };
            },50)
        });
    });

HTML-Markup

MEGA LINK 1

MEGA LINK 2

Normal Link 3

Normal Link 4

Normal Link 5

Normal Link 6

         MEGA MENU 1

            MEGA MENU 2

My fiddle: https://jsfiddle.net/hfammzce/

Body:
I dont know why this is happening. But you can use jQuery .show() and .hide() instead of using add/remove class and opacity.

Here is the updated fiddle: https://jsfiddle.net/1dzyszdq/

    /* General Hiding Function for first mega menu */
    function tg_hide_tg() {
        setTimeout( function () {
            if ($tg_top_menu.find('.tg-submenu__link--tg:hover').length == 0 && $('.tg-submenu__tg:hover').length == 0) {
                $(".tg-submenu__tg").hide();
            };
            }, 50);
    }

    /* Mouse Hover Mega Link 1 and Leave Link */
    $tg_submenu_link_tg.mouseenter(function() {
        $('.tg-submenu__tg').show();
    }).mouseleave(function() {
        tg_hide_tg();
    });


问:
Multithreading in c++
I want to run one function with different parameters on different threads:

```<code>int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}
</code>```

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

答:
You create a thread in Windows by calling CreateThread. There's an example here.

Yes, you can dynamically create threads.

Now, when your "thread function" is getting called (which means the thread started) you use the passed parameter which you've feeded when calling CreateThread.

At the "thread-function" it's "LPVOID lpParam". You should cast it to your type. If it's two objects you need to pass to the thread then create your own custom struct/class with the appropriate memebers, and pass an instance of it when calling CreateThread so you can use it later. Very straight-forward.

Title: Multithreading in c++

Body:
I want to run one function with different parameters on different threads:

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?


答:
```<code>v.t=malloc(2*sizeof(int));
</code>```

Here you assign allocated memory to v.t.

```<code>v=fct(v);
</code>```

Then here you overwrite all fields of v with what was returned from fct.  This discards the old value of v.t, causing a memory leak.

The call to free at the end of main is freeing the memory that was allocated inside of fct.

You can fix this leak by saving v.t and calling free on the saved pointer:

```<code>vector v;
int *vt_sav;
v.x=2;
v.t=malloc(2*sizeof(int));
vt_sav = v.t;
v.t[0]=1; v.t[1]=5;
v=fct(v);
free(vt_sav);
</code>```

Title: Does this C code leak memory?

Body:
So here is my code:

typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}

int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}

I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.
Oh, and I know that if I define another vector let's say w, such that
w = fct(v)
it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.

Body:
v.t=malloc(2*sizeof(int));

Here you assign allocated memory to v.t.

v=fct(v);

Then here you overwrite all fields of v with what was returned from fct.  This discards the old value of v.t, causing a memory leak.

The call to free at the end of main is freeing the memory that was allocated inside of fct.

You can fix this leak by saving v.t and calling free on the saved pointer:

vector v;
int *vt_sav;
v.x=2;
v.t=malloc(2*sizeof(int));
vt_sav = v.t;
v.t[0]=1; v.t[1]=5;
v=fct(v);
free(vt_sav);