问:
How to build an efficient named array?
I want to have a type that both has named members and also is iterable, so one should be able to refer to the members by index, by label or from a for-each loop. One way to realise this would be to use std::unordered_map<std::string,T> with some helper data for the indices. Clearly this would be horribly inefficient as for each member access you need to hash a std::string.

My current attempt looks like this:

```<code>// named-array.h
#pragma once

#include <array>
#include <cstddef>

#define NamedArray_KeyDecl(Name, ...) enum class Name : std::size_t { __VA_ARGS__, NUM }

namespace util {
  template <typename K, typename T>
  struct NamedArray {
    static constexpr std::size_t cast(K k) {
      return static_cast<std::size_t>(k);
    }

    std::array<T,cast(K::NUM)> array;
    NamedArray(std::array<T,cast(K::NUM)> a) : array(a) {
    }
    constexpr T& operator[](K k) {
      return array[cast(k)];
    }
    constexpr T const& operator[](K k) const {
      return array[cast(k)];
    }
  };
}
</code>```

Which can be used like so:

```<code>  struct Gadget {
    int i;
    Gadget(int i) : i(i) {}
    void operator()() const {
      std::cout << "Gadget(" << i << ")\n";
    }
  };

  NamedArray_KeyDecl(Test1, a,b,c,d);

  util::NamedArray<Test1,Gadget> gadgets {{0,1,2,3}};
  // for each works:
  for (auto const& gadget: gadgets.array) {
    gadget();
  }
  // named access works:
  gadgets[Test1::b]();
  // access by index works:
  gadgets.array[1]();
</code>```

Exposing the array member could be avoided by forwarding all interface functions of std::array.

However, an obvious drawback is that

gadgets[Test1::b] is not as pretty as something along the lines of gadgets.member().b and

there is an exposed #define in a c++ header file (which is extremely smelly)

Is there a way to have a named array with the same performance as an std::array?

答:
Minimalistic example of how it could be done:</p>

```<code>#include <array>
#include <type_traits>

template<class Tag, class...Tags>
struct position {
};

template<class Tag, class...Tags>
struct position<Tag, Tag, Tags...> {
    constexpr static unsigned value = 0;
};

template<class Tag, class First, class...Tags>
struct position<Tag, First, Tags...> {
    constexpr static unsigned value = 1 + position<Tag, Tags...>::value;
};

template<class T, class...Tags>
class NamedArray {
public:

    template<class U>
    constexpr T& operator[](U tag) {
        return array_[position<U, Tags...>::value];
    }

    constexpr T& operator[](unsigned val) {
        return array_[val];
    }

    template<class U>
    constexpr T& member(U u = U{}) {
        return (*this)[u];
    }
private:
    std::array<T, sizeof...(Tags)> array_;
};

struct tag1{};
struct tag2{};

int main() {

    NamedArray<int, tag1, tag2> a;
    a[tag1{}];
    a[tag2{}];

    a.member(tag1{});
    a.member<tag1>();

}
</code>```

Title: How to build an efficient named array?

Body:
I want to have a type that both has named members and also is iterable, so one should be able to refer to the members by index, by label or from a for-each loop. One way to realise this would be to use std::unordered_map<std::string,T> with some helper data for the indices. Clearly this would be horribly inefficient as for each member access you need to hash a std::string.

My current attempt looks like this:

// named-array.h
#pragma once

#include <array>
#include <cstddef>

#define NamedArray_KeyDecl(Name, ...) enum class Name : std::size_t { __VA_ARGS__, NUM }

namespace util {
  template <typename K, typename T>
  struct NamedArray {
    static constexpr std::size_t cast(K k) {
      return static_cast<std::size_t>(k);
    }

    std::array<T,cast(K::NUM)> array;
    NamedArray(std::array<T,cast(K::NUM)> a) : array(a) {
    }
    constexpr T& operator[](K k) {
      return array[cast(k)];
    }
    constexpr T const& operator[](K k) const {
      return array[cast(k)];
    }
  };
}

Which can be used like so:

  struct Gadget {
    int i;
    Gadget(int i) : i(i) {}
    void operator()() const {
      std::cout << "Gadget(" << i << ")\n";
    }
  };

  NamedArray_KeyDecl(Test1, a,b,c,d);

  util::NamedArray<Test1,Gadget> gadgets {{0,1,2,3}};
  // for each works:
  for (auto const& gadget: gadgets.array) {
    gadget();
  }
  // named access works:
  gadgets[Test1::b]();
  // access by index works:
  gadgets.array[1]();

Exposing the array member could be avoided by forwarding all interface functions of std::array.

However, an obvious drawback is that

gadgets[Test1::b] is not as pretty as something along the lines of gadgets.member().b and

there is an exposed #define in a c++ header file (which is extremely smelly)

Is there a way to have a named array with the same performance as an std::array?

Body:
Minimalistic example of how it could be done:

#include <array>
#include <type_traits>

template<class Tag, class...Tags>
struct position {
};

template<class Tag, class...Tags>
struct position<Tag, Tag, Tags...> {
    constexpr static unsigned value = 0;
};

template<class Tag, class First, class...Tags>
struct position<Tag, First, Tags...> {
    constexpr static unsigned value = 1 + position<Tag, Tags...>::value;
};

template<class T, class...Tags>
class NamedArray {
public:

    template<class U>
    constexpr T& operator[](U tag) {
        return array_[position<U, Tags...>::value];
    }

    constexpr T& operator[](unsigned val) {
        return array_[val];
    }

    template<class U>
    constexpr T& member(U u = U{}) {
        return (*this)[u];
    }
private:
    std::array<T, sizeof...(Tags)> array_;
};

struct tag1{};
struct tag2{};

int main() {

    NamedArray<int, tag1, tag2> a;
    a[tag1{}];
    a[tag2{}];

    a.member(tag1{});
    a.member<tag1>();

}


来源: stackexchange

问:
Slice vs type alias as the method receiver
I have a struct Foo with a method print:

type Foo struct {
    Bar string
}
func (f Foo) print() {
    fmt.Println(f.Bar)
}
```

<p>If I want to print for a slice of <code>Foo</code>, the canonical way perhaps is to write a <code>for</code> loop, and have a function to encapsulate it:</p>

<pre class="lang-golang prettyprint-override"><code>func printFoos(fs []Foo) {
    for _, f := range fs {
        f.print()
    }
}
printFoos([]Foo{})
</code>```

Coming from an OOP background, I find this approach a bit unappealing.

What I would like to do is to associate printFoos with []Foo:

// Invalid Go code
func (fs []Foo) print() {
    for _, f := range fs {
        f.print()
    }
}
```

<p>The above doesn't work because in Go, an unnamed type can't be used as the method receiver, as discussed in this Google Group thread.</p>

<p>To circumvent it, it is possible to write:</p>

<pre class="lang-golang prettyprint-override"><code>type Foos []Foo
func (fs Foos) print() {
    for _, f := range fs {
        f.print()
    }
}
</code>```

To use it, I have to explicitly declare the type as Foos, so still I can't use print on []Foo

fs := []Foo{}
fs.print() // error
var fss Foos = fs
fss.print()
```

What I'm confused about is, in the above code, fss and fs are clearly of the same type, as I can assign fs to fss without error. However, we can't simply use fs.print() and let Go be smart about the conversion.

Why is this the case?

The full code can be found on playground.

答:
What I'm confused about is, in the above code, fss and fs are clearly of the same type, as I can assign fs to fss without error.

You jump to the wrong conclusion. Having the same type is not a must have requirement for assignability.

fss has type Foos, and fs has type []Foo, an unnamed slice type. It's true that they have the same underlying type, that's why you can assign fs to fss, covered in this assignability rule:

A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:

...

x's type V and T have identical underlying types and at least one of V or T is not a defined type.

Methods are bound to concrete types. So the Foos.print() method is not available for a value of a different type, including []Foo.

But you don't need to create a variable just to call that method, you may simply use a type conversion:

```<code>Foos(fs).print()
</code>```

This conversion does not change the memory layout, just the type, so it's safe and efficient. We used it only to gain access to a method of a type with identical underlying type.

ContentLicense: CC BY-SA 4.0

Body:
I have a struct Foo with a method print:

type Foo struct {
    Bar string
}
func (f Foo) print() {
    fmt.Println(f.Bar)
}

If I want to print for a slice of Foo, the canonical way perhaps is to write a for loop, and have a function to encapsulate it:

func printFoos(fs []Foo) {
    for _, f := range fs {
        f.print()
    }
}
printFoos([]Foo{})

Coming from an OOP background, I find this approach a bit unappealing.

What I would like to do is to associate printFoos with []Foo:

// Invalid Go code
func (fs []Foo) print() {
    for _, f := range fs {
        f.print()
    }
}

The above doesn't work because in Go, an unnamed type can't be used as the method receiver, as discussed in this Google Group thread.

To circumvent it, it is possible to write:

type Foos []Foo
func (fs Foos) print() {
    for _, f := range fs {
        f.print()
    }
}

To use it, I have to explicitly declare the type as Foos, so still I can't use print on []Foo

fs := []Foo{}
fs.print() // error
var fss Foos = fs
fss.print()

What I'm confused about is, in the above code, fss and fs are clearly of the same type, as I can assign fs to fss without error. However, we can't simply use fs.print() and let Go be smart about the conversion.

Why is this the case?

The full code can be found on playground.

Body:
What I'm confused about is, in the above code, fss and fs are clearly of the same type, as I can assign fs to fss without error.

You jump to the wrong conclusion. Having the same type is not a must have requirement for assignability.

fss has type Foos, and fs has type []Foo, an unnamed slice type. It's true that they have the same underlying type, that's why you can assign fs to fss, covered in this assignability rule:

A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:

...

x's type V and T have identical underlying types and at least one of V or T is not a defined type.

Methods are bound to concrete types. So the Foos.print() method is not available for a value of a different type, including []Foo.

But you don't need to create a variable just to call that method, you may simply use a type conversion:

Foos(fs).print()

This conversion does not change the memory layout, just the type, so it's safe and efficient. We used it only to gain access to a method of a type with identical underlying type.


问:
Don't cover a method in transaction that is running inside a transactional method
I've asked this question somewhere ,

Suppose i have a method A which is running in transaction by using @transactional ,
if there is a method B  which is being called from that transactional method , by default this will also be running in the same transaction.

So , the question is what to do that B is not covered by the transaction,
how to avoid the transaction for B.

答:
You have to use the following pattern to get what you want: Execute A and if B needs the result of A you can send it to be in a nontransactional context.

```<code>void myFunction() {
        Object result = myTransactionalClass.A();
        B(result);
}
</code>```

Be ware that since you are asking this question (you do not want B() to be transactional), the code mentioned is most definitely gonna work.

Body:
You have to use the following pattern to get what you want: Execute A and if B needs the result of A you can send it to be in a nontransactional context.

void myFunction() {
        Object result = myTransactionalClass.A();
        B(result);
}

Be ware that since you are asking this question (you do not want B() to be transactional), the code mentioned is most definitely gonna work.


问:
Errors using FMXLinux on CentOS_7 1908
```<code>[DCC Error] E2597 C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\ld-linux.exe: error: cannot find -lrtlhelper_PIC
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\ld-linux.exe: error: cannot find -lrtlhelper
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\ld-linux.exe: error: cannot find -lpcre_PIC
</code>```

<p>When compiling, I have this error. Has anyone seen this and know how to fix it? </p>

答:
in terminal run the following commands:

```<code>sudo yum install qt4-devel
sudo yum install gcc-c++.x86_64
</code>```

or

```<code>sudo yum glibc-static
sudo yum install glibc-devel
sudo yum install zlib-devel
</code>```

or if not enough

```<code>sudo yum install compat-libstdc++-33
sudo yum install compat-gcc-44-c++
</code>```

Then update the local file cache for Linux SDK in Delphi->Options/Deployment/SDK Manager

Stefanos

Title: Errors using FMXLinux on CentOS_7 1908

Body:
[DCC Error] E2597 C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\ld-linux.exe: error: cannot find -lrtlhelper_PIC
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\ld-linux.exe: error: cannot find -lrtlhelper
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\ld-linux.exe: error: cannot find -lpcre_PIC

When compiling, I have this error. Has anyone seen this and know how to fix it?

Body:
in terminal run the following commands:

sudo yum install qt4-devel
sudo yum install gcc-c++.x86_64

or

sudo yum glibc-static
sudo yum install glibc-devel
sudo yum install zlib-devel

or if not enough

sudo yum install compat-libstdc++-33
sudo yum install compat-gcc-44-c++

Then update the local file cache for Linux SDK in Delphi->Options/Deployment/SDK Manager

Stefanos


问:
Search in nested Postgresql JSONB column
How to search in nested jsonb column in Rails.

```<code>Model: Shop
jsonb column: shop_data

shop_data: {
  common_data: {
    "image_url" => "https://sample.com/img.jpg"
    "token" => "AOsa2123ASDasdaasasda"
    "uid" => ""
    "expires_at" => ""
  }
}
</code>```

Wanna make a scopes that will checks for records where:

```<code>1. shop_data->common_data->expires_at IS NOT NULL
2. shop_data->common_data->image_url IS NULL
</code>```

答:
 1. scope :expired, -> { where("shop_data -> 'common_data' ->> 'expires_at' IS NOT NULL") }
 2. scope :null_image, -> { where("shop_data -> 'common_data' ->> 'image_url' IS NULL") }
```

source JSON functions in postgres

Hope it helps

Body:
How to search in nested jsonb column in Rails.

Model: Shop
jsonb column: shop_data

shop_data: {
  common_data: {
    "image_url" => "https://sample.com/img.jpg"
    "token" => "AOsa2123ASDasdaasasda"
    "uid" => ""
    "expires_at" => ""
  }
}

Wanna make a scopes that will checks for records where:

1. shop_data->common_data->expires_at IS NOT NULL
2. shop_data->common_data->image_url IS NULL

Body:
 1. scope :expired, -> { where("shop_data -> 'common_data' ->> 'expires_at' IS NOT NULL") }
 2. scope :null_image, -> { where("shop_data -> 'common_data' ->> 'image_url' IS NULL") }

source JSON functions in postgres

Hope it helps


问:
Elasticsearch multi fields multi words match
I'm looking to implement an auto-complete like feature on my app with elasticsearch.

Let's say my input is "ronan f", I want elastic to return all elements where "ronan" or "f" is contained in last name or first name. I expect elasticsearch to sort the result by rank, so the element which is the closest to what I search should be on top.

I tried multiple requests but none of them results as expected.

For example :

```<code>{
  "query": {
    "bool": {
        "must_not": [
            {
                "match": {
                    "email": "*@guest.booking.com"
                }
            }
        ],
        "should": [
            {
                "match": {
                    "lastname": "ronan"
                }
            },
            {
                "match": {
                    "firstname": "ronan"
                }
            },
            {
                "match": {
                    "lastname": "f"
                }
            },
            {
                "match": {
                    "firstname": "f"
                }
            }
        ],
        "minimum_should_match" : 1
    }
  },
  "sort": [
    "_score"
  ],
  "from": 0,
  "size": 30
}
</code>```

With this request the ranks seams a bit odds, for example :

```<code>"_index": "clients",
"_type": "client",
"_id": "4369",
"_score": 20.680058,
"_source": {
   "firstname": "F",
   "lastname": "F"
 }
</code>```

is on top of :

```<code>"_index": "clients",
"_type": "client",
"_id": "212360",
_score": 9.230003,
"_source": {
   "firstname": "Ronan",
   "lastname": "Fily"
}
</code>```

For me the second result should have a better rank than the first.

Can someone show me how can I achieve the result I want ?

For info, I can't use Completion Suggester functionality of elasticsearch because I can't access the configuration of the database (so no indexes).

答:
Ok as you can reindex your data i join a "start with" anylyzer. It will work caseless & on text field (i thinck first name and last name can have multi words on it).

Delete / create a new index using mappings.

define your analyzer (PUT my_index)
{
  "settings": {:

```<code>"filter": {
        "name_ngrams": {
            "max_gram": "20",
            "type": "edgeNGram",
            "min_gram": "1",
            "side": "front"
        }
    },
    "analyzer": {
        "partial_name": {
            "type": "custom",
            "filter": [
                "lowercase"
                ,
                "name_ngrams"
                ,
                "standard"
                ,
                "asciifolding"
            ],
            "tokenizer": "standard"
        },
        "full_name": {
            "type": "custom",
            "filter": [
                "standard"
                ,
                "lowercase"
                ,
                "asciifolding"
            ],
            "tokenizer": "standard"
        }
    }
</code>```

post _mappings using this for your fields:

```<code>"lastname": {
        "type": "text",
        "analyzer": "partial_name",
        "search_analyzer": "full_name"

},

    "firstname": {
        "type": "text",
        "analyzer": "partial_name",
        "search_analyzer": "full_name"
}
</code>```

if this is not clear and elasticsearch documentation couldnot help you dont hesite to ask us.

Body:
I'm looking to implement an auto-complete like feature on my app with elasticsearch.

Let's say my input is "ronan f", I want elastic to return all elements where "ronan" or "f" is contained in last name or first name. I expect elasticsearch to sort the result by rank, so the element which is the closest to what I search should be on top.

I tried multiple requests but none of them results as expected.

For example :

{
  "query": {
    "bool": {
        "must_not": [
            {
                "match": {
                    "email": "*@guest.booking.com"
                }
            }
        ],
        "should": [
            {
                "match": {
                    "lastname": "ronan"
                }
            },
            {
                "match": {
                    "firstname": "ronan"
                }
            },
            {
                "match": {
                    "lastname": "f"
                }
            },
            {
                "match": {
                    "firstname": "f"
                }
            }
        ],
        "minimum_should_match" : 1
    }
  },
  "sort": [
    "_score"
  ],
  "from": 0,
  "size": 30
}

With this request the ranks seams a bit odds, for example :

"_index": "clients",
"_type": "client",
"_id": "4369",
"_score": 20.680058,
"_source": {
   "firstname": "F",
   "lastname": "F"
 }

is on top of :

"_index": "clients",
"_type": "client",
"_id": "212360",
_score": 9.230003,
"_source": {
   "firstname": "Ronan",
   "lastname": "Fily"
}

For me the second result should have a better rank than the first.

Can someone show me how can I achieve the result I want ?

For info, I can't use Completion Suggester functionality of elasticsearch because I can't access the configuration of the database (so no indexes).

Body:
Ok as you can reindex your data i join a "start with" anylyzer. It will work caseless & on text field (i thinck first name and last name can have multi words on it).

Delete / create a new index using mappings.

define your analyzer (PUT my_index)
{
  "settings": {:

"filter": {
        "name_ngrams": {
            "max_gram": "20",
            "type": "edgeNGram",
            "min_gram": "1",
            "side": "front"
        }
    },
    "analyzer": {
        "partial_name": {
            "type": "custom",
            "filter": [
                "lowercase"
                ,
                "name_ngrams"
                ,
                "standard"
                ,
                "asciifolding"
            ],
            "tokenizer": "standard"
        },
        "full_name": {
            "type": "custom",
            "filter": [
                "standard"
                ,
                "lowercase"
                ,
                "asciifolding"
            ],
            "tokenizer": "standard"
        }
    }

post _mappings using this for your fields:

"lastname": {
        "type": "text",
        "analyzer": "partial_name",
        "search_analyzer": "full_name"

},

    "firstname": {
        "type": "text",
        "analyzer": "partial_name",
        "search_analyzer": "full_name"
}

if this is not clear and elasticsearch documentation couldnot help you dont hesite to ask us.


问:
undefined and null
```<code>undefined === null => false
undefined == null => true
</code>```

I have thought about the reason of undefined == null and found out only one case:

```<code>if(document.getElementById() == null) ....
</code>```

Is there any other reason to make (undefined === null) == false ?

Is there any other examples of use === - operation in javascript?

答: Type coercion (using the == operator) can lead to undesired or unexpected results. After following all the talks I could find of Douglas Crockford on the net (mostly Yahoo video) I got used to using === all te time. Given my default usage of the strict equal operator I would be more interested in type coercion javascript use cases ;~) nowadays.

ContentLicense: CC BY-SA 3.0

Title: undefined and null

Body:
undefined === null => false
undefined == null => true

I have thought about the reason of undefined == null and found out only one case:

if(document.getElementById() == null) ....

Is there any other reason to make (undefined === null) == false ?

Is there any other examples of use === - operation in javascript?


问:
Efficiently removing shared elements from grouped data
I have the following data.table:

```<code>dt
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE   07   03   84
# 3:         3        2      FALSE   10 <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA>   10
# 6:         6        3      FALSE   22   03 <NA>
# 7:         7        3       TRUE <NA>   13   03
</code>```

unique_ids are grouped by common phone numbers (ph1, ph2, ph3) which are common across rows (e.g. in the first group "07", "03" are common across the group and in the third group, "03" is shared, but not in the same column, as per group 2).

Each group has 1 primary_id.

Within each group I want to remove the common phone number element(s) in the non primary_id's and retain it for the primary id, so they are no longer linked.

I can achieve this easily in a for loop, however, it's across millions of groups and it's extremely slow.

Looking for a quicker method.

Data:

```<code>library(data.table)

dt <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
    1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
    FALSE, TRUE), ph1 = c("07", "07", "10", NA, NA, "22", NA), ph2 = c("03",
    "03", NA, "10", NA, "03", "13"), ph3 = c(NA, "84", NA, NA, "10",
    NA, "03")), class = "data.frame", row.names = c(NA, -7L))
)
</code>```

Desired output is:

```<code>output <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
FALSE, TRUE), ph1 = c("07", NA, NA, NA, NA, "22", NA), ph2 = c("03",
NA, NA, "10", NA, NA, "13"), ph3 = c(NA, "84", NA, NA, NA, NA,
"03")), class = "data.frame", row.names = c(NA, -7L)))

output
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE <NA> <NA>   84
# 3:         3        2      FALSE <NA> <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA> <NA>
# 6:         6        3      FALSE   22 <NA> <NA>
# 7:         7        3       TRUE <NA>   13   03
</code>```

If still unclear, it may be easier to visualize it like this:

答:
Here's another data.table approach that uses table() and ifelse() to achieve the goal. Maybe this is faster since it doesn't create any additional matrices or reshape the data.

```<code>cleaner <- function(DT){

  repeats <- DT[ , table(c(ph1, ph2, ph3))]

  return(
    DT[ , .(ifelse(primary_id | (!primary_id & repeats[ph1] %in% 1), ph1, NA_character_),
            ifelse(primary_id | (!primary_id & repeats[ph2] %in% 1), ph2, NA_character_),
            ifelse(primary_id | (!primary_id & repeats[ph3] %in% 1), ph3, NA_character_))]
    )
}

cols <- c("primary_id", "ph1", "ph2", "ph3")
dt[ , cols[2:4] := cleaner(.SD), by = group_id, .SDcols = cols]
</code>```

Output:

```<code>> dt
   unique_id group_id primary_id  ph1  ph2  ph3
1:         1        1       TRUE   07   03 <NA>
2:         2        1      FALSE <NA> <NA>   84
3:         3        2      FALSE <NA> <NA> <NA>
4:         4        2       TRUE <NA>   10 <NA>
5:         5        2      FALSE <NA> <NA> <NA>
6:         6        3      FALSE   22 <NA> <NA>
7:         7        3       TRUE <NA>   13   03
</code>```

Body:
I have the following data.table:

dt
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE   07   03   84
# 3:         3        2      FALSE   10 <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA>   10
# 6:         6        3      FALSE   22   03 <NA>
# 7:         7        3       TRUE <NA>   13   03

unique_ids are grouped by common phone numbers (ph1, ph2, ph3) which are common across rows (e.g. in the first group "07", "03" are common across the group and in the third group, "03" is shared, but not in the same column, as per group 2).

Each group has 1 primary_id.

Within each group I want to remove the common phone number element(s) in the non primary_id's and retain it for the primary id, so they are no longer linked.

I can achieve this easily in a for loop, however, it's across millions of groups and it's extremely slow.

Looking for a quicker method.

Data:

library(data.table)

dt <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
    1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
    FALSE, TRUE), ph1 = c("07", "07", "10", NA, NA, "22", NA), ph2 = c("03",
    "03", NA, "10", NA, "03", "13"), ph3 = c(NA, "84", NA, NA, "10",
    NA, "03")), class = "data.frame", row.names = c(NA, -7L))
)

Desired output is:

output <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
FALSE, TRUE), ph1 = c("07", NA, NA, NA, NA, "22", NA), ph2 = c("03",
NA, NA, "10", NA, NA, "13"), ph3 = c(NA, "84", NA, NA, NA, NA,
"03")), class = "data.frame", row.names = c(NA, -7L)))

output
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE <NA> <NA>   84
# 3:         3        2      FALSE <NA> <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA> <NA>
# 6:         6        3      FALSE   22 <NA> <NA>
# 7:         7        3       TRUE <NA>   13   03

If still unclear, it may be easier to visualize it like this:

Body:
Here's another data.table approach that uses table() and ifelse() to achieve the goal. Maybe this is faster since it doesn't create any additional matrices or reshape the data.

cleaner <- function(DT){

  repeats <- DT[ , table(c(ph1, ph2, ph3))]

  return(
    DT[ , .(ifelse(primary_id | (!primary_id & repeats[ph1] %in% 1), ph1, NA_character_),
            ifelse(primary_id | (!primary_id & repeats[ph2] %in% 1), ph2, NA_character_),
            ifelse(primary_id | (!primary_id & repeats[ph3] %in% 1), ph3, NA_character_))]
    )
}

cols <- c("primary_id", "ph1", "ph2", "ph3")
dt[ , cols[2:4] := cleaner(.SD), by = group_id, .SDcols = cols]

Output:

> dt
   unique_id group_id primary_id  ph1  ph2  ph3
1:         1        1       TRUE   07   03 <NA>
2:         2        1      FALSE <NA> <NA>   84
3:         3        2      FALSE <NA> <NA> <NA>
4:         4        2       TRUE <NA>   10 <NA>
5:         5        2      FALSE <NA> <NA> <NA>
6:         6        3      FALSE   22 <NA> <NA>
7:         7        3       TRUE <NA>   13   03


问:
Logical exception vs technical exception
There is a restriction on the database level in the user table for the unique field - email. That is, if we try to save the user with an existing email address, then an SQLServerException will occur. In this case, we can catch this technical exception, create and then throw our own technical exception.

But we can also make a request to the database and check if the user exists and then throw our own a logical exception.

The question is which of the options is more preferable?

答:
The best practice is to check the database and not use the constraint of your database.

The database constraints must be seen as a second shield to ensure data integrity. But it musn't drive your business logic. Only your software drives your business logic.


问:
In linked list ,when i write (temp->next=newnode) then when i apply temp=temp->next does not work but temp=newnode works?
Below is my code:

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

int main() {
    struct node {
        int data;
        struct node *next;
    };
    int choice;
    struct node *head, *newnode, *temp;
    head = 0;
    while (choice) {
        newnode = (struct node *)malloc(sizeof(struct node));
        printf("enter items ");
        scanf("%d", &newnode->data);
        newnode->next = 0;
        if (head == 0) {
            head = temp = newnode;
        } else
            temp->next = newnode;  /** **this is the problem** **/
            temp = newnode;      /** temp=newnode works but temp=temp->next doesn't**/
        printf("do you want to continue");
        scanf("%d", &choice);
    }
    temp = head;
    while (temp != 0) {
        printf("list is %d \n", temp->data);
        temp = temp->next;
    }
}
</code>```

答:
The problem is here:

```<code>    if(head==0)
    {
        head=temp=newnode;
    }
    else
        temp->next=newnode;  /** **this is the problem** **/
        temp=newnode;      /** temp=newnode works but temp=temp->next doesn't**/
</code>```

Indentation does not determine structure. You must enclose multiple instructions in a block to group them in the else clause. As coded, temp=newnode; is executed unconditionally after the test, which is not a problem, but redundant with head=temp=newnode.

Note also that choice is uninitialized when tested the first time.

Here is a corrected version:

#include <stdio.h>
#include <stdlib.h>

int main() {
    struct node {
        int data;
        struct node *next;
    };
    int choice;
    struct node *head, *tail, *newnode, *temp;
    head = tail = NULL;
    for (;;) {
        newnode = (struct node *)malloc(sizeof(struct node));
        if (newnode == NULL)
            break;
        printf("enter item: ");
        if (scanf("%d", &newnode->data) != 1) {
            free(nownode);
            break;
        }
        newnode->next = NULL;
        if (head == NULL) {
            head = newnode;
        } else {
            tail->next = newnode;
        }
        tail = newnode;
        printf("do you want to continue? [0/1] ");
        if (scanf("%d", &choice) != 1 || choice == 0)
            break;
    }
    for (temp = head; temp != NULL; temp = temp->next) {
        printf("list is %d \n", temp->data);
    }
    return NULL;
}
```

Body:
Below is my code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    struct node {
        int data;
        struct node *next;
    };
    int choice;
    struct node *head, *newnode, *temp;
    head = 0;
    while (choice) {
        newnode = (struct node *)malloc(sizeof(struct node));
        printf("enter items ");
        scanf("%d", &newnode->data);
        newnode->next = 0;
        if (head == 0) {
            head = temp = newnode;
        } else
            temp->next = newnode;  /** **this is the problem** **/
            temp = newnode;      /** temp=newnode works but temp=temp->next doesn't**/
        printf("do you want to continue");
        scanf("%d", &choice);
    }
    temp = head;
    while (temp != 0) {
        printf("list is %d \n", temp->data);
        temp = temp->next;
    }
}

Body:
The problem is here:

    if(head==0)
    {
        head=temp=newnode;
    }
    else
        temp->next=newnode;  /** **this is the problem** **/
        temp=newnode;      /** temp=newnode works but temp=temp->next doesn't**/

Indentation does not determine structure. You must enclose multiple instructions in a block to group them in the else clause. As coded, temp=newnode; is executed unconditionally after the test, which is not a problem, but redundant with head=temp=newnode.

Note also that choice is uninitialized when tested the first time.

Here is a corrected version:

#include <stdio.h>
#include <stdlib.h>

int main() {
    struct node {
        int data;
        struct node *next;
    };
    int choice;
    struct node *head, *tail, *newnode, *temp;
    head = tail = NULL;
    for (;;) {
        newnode = (struct node *)malloc(sizeof(struct node));
        if (newnode == NULL)
            break;
        printf("enter item: ");
        if (scanf("%d", &newnode->data) != 1) {
            free(nownode);
            break;
        }
        newnode->next = NULL;
        if (head == NULL) {
            head = newnode;
        } else {
            tail->next = newnode;
        }
        tail = newnode;
        printf("do you want to continue? [0/1] ");
        if (scanf("%d", &choice) != 1 || choice == 0)
            break;
    }
    for (temp = head; temp != NULL; temp = temp->next) {
        printf("list is %d \n", temp->data);
    }
    return NULL;
}


问:
URL parameter in react Class Component
I'm trying to pass parameter to component using URL.I'm using react component not functionnel component so I can't use hooks? How can I read url parameter in class component ?
I'm trying to pass parameter to a component so it can depending on parameter fetch data from database and update it or just create a new record!
Thanks</p>

答:
You can use the withRouter HOC decorator. This decorates a component (either class-based or functional) and injects match, location, and history props.

```<code>import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
</code>```

The match prop is the one that allows you to access the URL params

```<code>this.props.match.params
</code>```

Title: URL parameter in react Class Component

Body:
You can use the withRouter HOC decorator. This decorates a component (either class-based or functional) and injects match, location, and history props.

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

The match prop is the one that allows you to access the URL params

this.props.match.params


问:
Check if the time difference is less than 1 second in moment
In my javascript project, I want to check if the time difference is less than 1 second. I use moment to get this difference. This is the function I have written to achieve it.

```<code>const withinOneSecond = (time) => {
  const currentTime = moment();
  return time + 1000 < currentTime;
};
</code>```

But this doesn't work as expected. How can I check if the given time is within a second to the current time?

答:
You just need to use the duration.asHours() method (see the docs).</p>

```<code>const withinOneSecond = (time) => {
  const currentTime = moment();
  return moment.duration(currentTime.diff(time)).asSeconds() > 1;
};
</code>```

Body:
In my javascript project, I want to check if the time difference is less than 1 second. I use moment to get this difference. This is the function I have written to achieve it.

const withinOneSecond = (time) => {
  const currentTime = moment();
  return time + 1000 < currentTime;
};

But this doesn't work as expected. How can I check if the given time is within a second to the current time?

Body:
You just need to use the duration.asHours() method (see the docs).

const withinOneSecond = (time) => {
  const currentTime = moment();
  return moment.duration(currentTime.diff(time)).asSeconds() > 1;
};


问:
python opens text file with a space between every character
Whenever I try to open a .csv file with the python command
fread = open('input.csv', 'r')
it always opens the file with spaces between every single character.  I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly.  Does anyone know why a text file would load like this in python?

Thanks.

Update

Ok, I got it with the help of Jarret Hardie's post

this is the code that I used to convert the file to ascii

```<code>fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')
mytext = mytext.encode('ascii', 'ignore')
fwrite = open('input-ascii.csv', 'wb')
fwrite.write(mytext)
</code>```

Thanks!

答: The file is encoded in some unicode encoding, but you are reading it as ascii.  Try to convert the file to ascii before using it in python.</p>

ContentLicense: CC BY-SA 2.5

Body:
Whenever I try to open a .csv file with the python command
fread = open('input.csv', 'r')
it always opens the file with spaces between every single character.  I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly.  Does anyone know why a text file would load like this in python?

Thanks.

Update

Ok, I got it with the help of Jarret Hardie's post

this is the code that I used to convert the file to ascii

fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')
mytext = mytext.encode('ascii', 'ignore')
fwrite = open('input-ascii.csv', 'wb')
fwrite.write(mytext)

Thanks!

LastEditorDisplayName: ΤΖΩΤΖΙΟΥ

OwnerDisplayName: recursive


问:
How to pass everything possible to i, j and by in nested functions?
I'm working on a package which uses data.table inside. In this package, I have a function count_by which calculates the number of distinct ID's for a specific variable in a data.table by groups. With some help (R data.table: How to pass "everything possible" to by in a function?) I got this to work as expected:

library(data.table)
#> Warning: package 'data.table' was built under R version 3.6.2

# create example data
sample_dt <- data.table(
    id = sort(rep(LETTERS[1:3], 3)),
    year = rep(2018L:2020L),
    x = runif(9)
)
sample_dt[id == "B" & year < 2020, x := NA_real_]

# define inner function
count_by <- function(DT, id_var, val_var, by = NULL) {
    id_var <- as.character(substitute(id_var))
    val_var <- as.character(substitute(val_var))

    eval(substitute(
        DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
    ))
}

# test inner function -> works as expected
(reference <- count_by(sample_dt, id_var = id, val_var = x, by = year))
#>    year distinct_ids
#> 1: 2018            2
#> 2: 2019            2
#> 3: 2020            3

identical(count_by(sample_dt, "id", x, year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", year)     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", "year")   , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", c("year")), reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, "year")       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, c("year"))    , reference)
#> [1] TRUE
```

<p><sup>Created on 2020-02-20 by the reprex package (v0.3.0)</sup></p>

<p>Now I would like to use the function <code>count_by()</code> within another function (minimal example below):</p>

<pre class="lang-r prettyprint-override"><code># define wrapper function
wrapper <- function(data, id_var, val_var, by = NULL) {
    data <- as.data.table(data)
    count_by(data, id_var, val_var, by)
}

# test wrapper function
wrapper(sample_dt, id_var = id, val_var = x, by = year)
#> Error in .(distinct_ids = uniqueN(get("id_var"))): could not find function "."
</code>```

Created on 2020-02-20 by the reprex package (v0.3.0)

Debugging count_by() lead to the observation that if count_by() is called from wrapper(), substitute(DT[...]) also substitutes DT to data:

Browse[2]> substitute(
+         DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
+     )
data[!is.na(get("val_var")), .(distinct_ids = uniqueN(get("id_var"))),
    by = by]
```

Since data is not available in the function environment of count_by() it gets evaluated to utils::data which then leads to the error. This makes the problem clear, but I cannot think of a solution.

I need to substitute the whole DT[...] expression in order for by to work properly (see R data.table: How to pass "everything possible" to by in a function? or pass variables and names to data.table function). But I can't substitute the whole expression in order for DT not beeing substituted.

What is the solution to this dilemma?

答:
Getting NSE out of the picture works for this particular example and simplifies things a lot. But then you should pass the arguments as string:</p>

```<code>count_by <- function(DT, id_var, val_var, by = NULL) {
    DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
}

wrapper <- function(data, id_var, val_var, by = NULL) {
    count_by(data, id_var, val_var, by)
}

wrapper(sample_dt, id_var = "id", val_var = "x", by = "year")

#    year distinct_ids
# 1: 2018            2
# 2: 2019            2
# 3: 2020            3
</code>```

Body:
I'm working on a package which uses data.table inside. In this package, I have a function count_by which calculates the number of distinct ID's for a specific variable in a data.table by groups. With some help (R data.table: How to pass "everything possible" to by in a function?) I got this to work as expected:

library(data.table)
#> Warning: package 'data.table' was built under R version 3.6.2

# create example data
sample_dt <- data.table(
    id = sort(rep(LETTERS[1:3], 3)),
    year = rep(2018L:2020L),
    x = runif(9)
)
sample_dt[id == "B" & year < 2020, x := NA_real_]

# define inner function
count_by <- function(DT, id_var, val_var, by = NULL) {
    id_var <- as.character(substitute(id_var))
    val_var <- as.character(substitute(val_var))

    eval(substitute(
        DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
    ))
}

# test inner function -> works as expected
(reference <- count_by(sample_dt, id_var = id, val_var = x, by = year))
#>    year distinct_ids
#> 1: 2018            2
#> 2: 2019            2
#> 3: 2020            3

identical(count_by(sample_dt, "id", x, year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", year)     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", "year")   , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", c("year")), reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, "year")       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, c("year"))    , reference)
#> [1] TRUE

Created on 2020-02-20 by the reprex package (v0.3.0)

Now I would like to use the function count_by() within another function (minimal example below):

# define wrapper function
wrapper <- function(data, id_var, val_var, by = NULL) {
    data <- as.data.table(data)
    count_by(data, id_var, val_var, by)
}

# test wrapper function
wrapper(sample_dt, id_var = id, val_var = x, by = year)
#> Error in .(distinct_ids = uniqueN(get("id_var"))): could not find function "."

Created on 2020-02-20 by the reprex package (v0.3.0)

Debugging count_by() lead to the observation that if count_by() is called from wrapper(), substitute(DT[...]) also substitutes DT to data:

Browse[2]> substitute(
+         DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
+     )
data[!is.na(get("val_var")), .(distinct_ids = uniqueN(get("id_var"))),
    by = by]

Since data is not available in the function environment of count_by() it gets evaluated to utils::data which then leads to the error. This makes the problem clear, but I cannot think of a solution.

I need to substitute the whole DT[...] expression in order for by to work properly (see R data.table: How to pass "everything possible" to by in a function? or pass variables and names to data.table function). But I can't substitute the whole expression in order for DT not beeing substituted.

What is the solution to this dilemma?

Body:
Getting NSE out of the picture works for this particular example and simplifies things a lot. But then you should pass the arguments as string:

count_by <- function(DT, id_var, val_var, by = NULL) {
    DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
}

wrapper <- function(data, id_var, val_var, by = NULL) {
    count_by(data, id_var, val_var, by)
}

wrapper(sample_dt, id_var = "id", val_var = "x", by = "year")

#    year distinct_ids
# 1: 2018            2
# 2: 2019            2
# 3: 2020            3


问:
why take the first hidden state for sequence classification (DistilBertForSequenceClassification) by HuggingFace
In the last few layers of sequence classification by HuggingFace, they took the first hidden state of the sequence length of the transformer output to be used for classification.

```<code>hidden_state = distilbert_output[0]  # (bs, seq_len, dim) <-- transformer output
pooled_output = hidden_state[:, 0]  # (bs, dim)           <-- first hidden state
pooled_output = self.pre_classifier(pooled_output)  # (bs, dim)
pooled_output = nn.ReLU()(pooled_output)  # (bs, dim)
pooled_output = self.dropout(pooled_output)  # (bs, dim)
logits = self.classifier(pooled_output)  # (bs, dim)
</code>```

Is there any benefit to taking the first hidden state over the last, average, or even the use of a Flatten layer instead?

答:
Yes, this is directly related to the way that BERT is trained. Specifically, I encourage you to have a look at the original BERT paper, in which the authors introduce the meaning of the [CLS] token:

[CLS] is a special symbol added in front of every input example [...].

Specifically, it is used for classification purposes, and therefore the first and simplest choice for any fine-tuning for classification tasks. What your relevant code fragment is doing, is basically just extracting this [CLS] token.

Unfortunately, the DistilBERT documentation of Huggingface's library does not explicitly refer to this, but you rather have to check out their BERT documentation, where they also highlight some issues with the [CLS] token, analogous to your concerns:

Alongside MLM, BERT was trained using a next sentence prediction (NSP)
objective using the [CLS] token as a sequence approximate. The user
may use this token (the first token in a sequence built with special
tokens) to get a sequence prediction rather than a token prediction.
However, averaging over the sequence may yield better results than
using the [CLS] token.

Body:
In the last few layers of sequence classification by HuggingFace, they took the first hidden state of the sequence length of the transformer output to be used for classification.

hidden_state = distilbert_output[0]  # (bs, seq_len, dim) <-- transformer output
pooled_output = hidden_state[:, 0]  # (bs, dim)           <-- first hidden state
pooled_output = self.pre_classifier(pooled_output)  # (bs, dim)
pooled_output = nn.ReLU()(pooled_output)  # (bs, dim)
pooled_output = self.dropout(pooled_output)  # (bs, dim)
logits = self.classifier(pooled_output)  # (bs, dim)

Is there any benefit to taking the first hidden state over the last, average, or even the use of a Flatten layer instead?


问:
SSMS Uncomment Selected shortcut no longer working
I make frequent use of SSMS's shortcut keys CTRL + K, C, to comment a block of code, and CTRL + K, U to uncomment.

Today, I went to do this, and noticed thatCTRL + K, U no longer works. Instead, it shifts focus to the availabile databases dialog in the top left of the screen, which apparently has the shortcut of CTRL + U.

I have checked the settings and CTRL + K, U is still mapped to uncomment selected code, but this is flat out not working.

Is this a bug, or something that I can fix?

SSMS v17.8.1

答: Seems to be an issue with ApexSQL refactor addin. I disabled it and the keyboard shortcut is working again.</p>


问:
Display all product in sale report
in sale report you can choose only products and quantity bought per costumers and export it as an excel file
what i need is a way to show all products even if the quantity is 0

Is that possible ?
Thanks.

答:
you can using the advanced filters in the search bar
chose quantity on hand equal 0 or greater than 0</p>

Title: Display all product in sale report


问:
How to convert String to Type of Integer?
I've got an converting Problem in Java.
How can I check if the content of my string matches the data class Integer in Java?
As an example: I have a String "Integer", how can I compare if the content of my String matches the Java Type Integer (I don't want an integer data typ, I really want the class).

```<code>String value = "Integer";
Integer int_val = 123456;
</code>```

I would try something like:

```<code>value.parseToInteger;
</code>```

because I want to do something like that:

```<code>if(int_val.typeOf(value))
{
...
}
</code>```

I want to check if it's class Integer because I want to compare my Integer like the example above. But I don't know how to convert the value of my String to a Java Class Type.

答:
```<code>String type = "Integer";
Object int_val = 123456;
if (int_val instanceof Integer) { }
if (int_val != null && int_val.getClass().getSimpleName().equals(type)) { }
</code>```

One should avoid starting with too general/abstract solutions;
as nice as it is to consider things on a more general/abstract level.

Body:
I've got an converting Problem in Java.
How can I check if the content of my string matches the data class Integer in Java?
As an example: I have a String "Integer", how can I compare if the content of my String matches the Java Type Integer (I don't want an integer data typ, I really want the class).

String value = "Integer";
Integer int_val = 123456;

I would try something like:

value.parseToInteger;

because I want to do something like that:

if(int_val.typeOf(value))
{
...
}

I want to check if it's class Integer because I want to compare my Integer like the example above. But I don't know how to convert the value of my String to a Java Class Type.

Body:
String type = "Integer";
Object int_val = 123456;
if (int_val instanceof Integer) { }
if (int_val != null && int_val.getClass().getSimpleName().equals(type)) { }

One should avoid starting with too general/abstract solutions;
as nice as it is to consider things on a more general/abstract level.


问:
wcf architecture - how to design my service contract in a flexible way
I have some entities like: Customers, Orders, Invoices.

For each one of them I grouped their CRUD operations and few other in interfaces like: ISvcCustomerMgmt, ISvcOrderMgmt, ISvcInvoicesMgmt, ISvcPaymentsMgmt.

Now I need to create few WCF service contracts independent to each other which will consist of implementing one or more of this interfaces.

one for internal use
ISvcInternal:    ISvcCustomerMgmt,
ISvcOrderMgmt,    ISvcInvoicesMgmt
//,maybe more in the future

one for external use (3rd parties) ISvcExternal:
ISvcCustomerMgmt //,maybe more in the future

So, my real services look like this: 1) SvcInternal: ISvcInternal, 2) SvcExternal: ISvcExternal.

When I see SvcInternal implementation, it gets bigger with a lot of operations.

Is this method flexible enough? Do you recommend another approach of splitting them up somehow? Feel free to share your thoughts.

Thank you.

答:
if i have to implement this i would say i will put all the code and Operations in a Worker Manager or Fascade Layer... that will consist of all operations... (Real coding logic).

my service will be only a thin client that will only pass request to Fascade layer....
This allows me to reuse a great amount of code... and it also allows me to expose same method in more then one services without ReImplementation....
One point though why don't you use differentiate b/w you internal and external services with different bindings... e.g. even if you are going to use WSHttpBinding or BasicHttpBinding for both services create different endpoints and binding for them....

in terms of Code Hirerachy my idea would be of using folder hirerachy and namespaces to differentiate b/w this... e.g. Namespace.Interfaces.Internal and vice versa...

hope that helps.


问:
How was the assumption made on half will have i < j?
I have been reading "Cracking the Coding Interview 6th Edition".. On Chapter 0 - Big O, I have problem understanding an assumption made to a problem on Example 3.

```<code>void printUnorderedPairs(int[] array){
  for(int i = 0; i < array.length; i++){
    for(int j = i + 1; j < array.length; j++){
      ...
    }
  }
}
</code>```

Under What It Means section, it assumed that:

There are N^2 total pairs. Roughly half of those will have i < j and the remaining half will have i > j. This code goes through roughly n^2/2 pairs so it does O(N^2) work.

My question is, how was the assumption made on Roughly half of those will have i < j and the remaining half will have i > j done? Can someone explain it to me please?

Thanks!

答:
There are several ways you can try to think about this assumption, I quite like the "geometric" suggestion from @IanMercer in the comments.   Here is another:

What is an unordered pair

An unordered pair is a pair of integers (i,j) where i and j is in the domain (1, N). (They can take any value from 1 to N).

How many pairs are there?

 i can be of any value from 1 to N, and j can be of any value from 1 to N.  Any combination of i forms a valid pair. So there are are N*N pairs.

Among all the pairs, how many pairs are there that i < j

Note that for any pair (a,b) where a is smaller than b, there exists a counterpart (b,a) (same values but flipped).  So there is an equal amount of pairs where i<j as there are pairs 'i>j'.

So what is this confusing roughly part? It is because of all those N*N pairs there are some where neither i<j nor j>i, and those are precisely the N pairs where i==j.

The N*N pairs are thus divided into three parts (those where i < j), (those where j> i) and (those where i==j). Since first two are much larger O(N**2)/2 vs. the last group which has only N elements, we can state that roughly half have the property that i<j.

Body:
I have been reading "Cracking the Coding Interview 6th Edition".. On Chapter 0 - Big O, I have problem understanding an assumption made to a problem on Example 3.

void printUnorderedPairs(int[] array){
  for(int i = 0; i < array.length; i++){
    for(int j = i + 1; j < array.length; j++){
      ...
    }
  }
}

Under What It Means section, it assumed that:

There are N^2 total pairs. Roughly half of those will have i < j and the remaining half will have i > j. This code goes through roughly n^2/2 pairs so it does O(N^2) work.

My question is, how was the assumption made on Roughly half of those will have i < j and the remaining half will have i > j done? Can someone explain it to me please?

Thanks!


问:
Set Specific Font Weight for UILabel in Swift
When people have asked how to set a bold font, most people suggest:

```<code>let boldFont = UIFont.boldSystemFont(ofSize: ___)
</code>```

But take a look at all the font weights that the standard system font offers:

So my question is how do you set a light, semibold, or heavy font weight? The only way that I know how is:

```<code>sectionLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];
</code>```

However, I'm still asking because this isn't strongly typed. Most other class attributes are set by selecting from a fixed set of options and don't require passing a string that I could mistype. I guess I could set my own global enum... But any better ideas?

答:
The very old thread, but someone may be interested in how to do it in Swift.

UIFont.Weight defines all of the options:

ultraLight

thin

light

regular

medium

semibold

bold

heavy

black

you can use simply like that, e.g.:

```<code>label.font = UIFont.systemFont(ofSize: size, weight: .bold)
</code>```

or if you want to keep the previous size:

```<code>label.font = UIFont.systemFont(ofSize: label.font!.pointSize, weight: .bold)
</code>```

Body:
When people have asked how to set a bold font, most people suggest:

let boldFont = UIFont.boldSystemFont(ofSize: ___)

But take a look at all the font weights that the standard system font offers:

So my question is how do you set a light, semibold, or heavy font weight? The only way that I know how is:

sectionLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];

However, I'm still asking because this isn't strongly typed. Most other class attributes are set by selecting from a fixed set of options and don't require passing a string that I could mistype. I guess I could set my own global enum... But any better ideas?

Body:
The very old thread, but someone may be interested in how to do it in Swift.

UIFont.Weight defines all of the options:

ultraLight

thin

light

regular

medium

semibold

bold

heavy

black

you can use simply like that, e.g.:

label.font = UIFont.systemFont(ofSize: size, weight: .bold)

or if you want to keep the previous size:

label.font = UIFont.systemFont(ofSize: label.font!.pointSize, weight: .bold)


问:
Is it Possible to style Table horizontal scrollbar?
Is it possible to style horizontal scroll bar in Table, it's so ugly ?

```<code>import { Row, Col, Modal, Table } from 'reactstrap';
<Table bordered responsive>
...
</Table>
</code>```

答:
This link should be helpful. https://css-tricks.com/almanac/properties/s/scrollbar/
jsfiddle for the example: https://jsfiddle.net/prak_mtl/ta3spmgu/5/</p>

```<code>tableWrapperClassName::-webkit-scrollbar {
  width: 1em;
}

tableWrapperClassName::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

tableWrapperClassName::-webkit-scrollbar-thumb {
  background-color: darkgrey;
  outline: 1px solid slategrey;
}
</code>```

Body:
Is it possible to style horizontal scroll bar in Table, it's so ugly ?

import { Row, Col, Modal, Table } from 'reactstrap';

...

Body:
This link should be helpful. https://css-tricks.com/almanac/properties/s/scrollbar/
jsfiddle for the example: https://jsfiddle.net/prak_mtl/ta3spmgu/5/

tableWrapperClassName::-webkit-scrollbar {
  width: 1em;
}

tableWrapperClassName::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

tableWrapperClassName::-webkit-scrollbar-thumb {
  background-color: darkgrey;
  outline: 1px solid slategrey;
}


问:
Apache guacamole multi user connection cache issue
Im using apache guacamole with tomcat 8

I have an issue which if im loggedin in a browser (chrome) tab, and i open another tab it is reconnecting me to the same user i have logged in the first tab,
I do not want this behavior as i need it to be able to work with a lot of users on the same browser with different tabs.

I cant always open incognito \ clean cache.  ( and also 2 pages of incognito of the same webpage also redirect)

My python code which redirect to apache guacamle RDP connection is a simple redirect to html page:

```<code>from flask import Flask, request, render_template, redirect
return render_template('gqm.html')
</code>```

Somone has some recommandtion of a browser \ configuration i can change in tomcat or my python code?
To maybe send forced clear cookie\cache to this specific site connection?

答:
Solved this by not giving a uniq user to a uniq connection, but giving the same user (guacadmin) and blocked the user from seeing home page, using nginx :

```<code>location / {
proxy_pass http://guacamole:8080/guacamole/;
rewrite ^.*api/session/data/postgresql.*/activeConnections.* /no_such_page last;
</code>```

so when i redirect client to a connection using the url token he cannot do logout\home page as it will give him an error.

Body:
Im using apache guacamole with tomcat 8

I have an issue which if im loggedin in a browser (chrome) tab, and i open another tab it is reconnecting me to the same user i have logged in the first tab,
I do not want this behavior as i need it to be able to work with a lot of users on the same browser with different tabs.

I cant always open incognito \ clean cache.  ( and also 2 pages of incognito of the same webpage also redirect)

My python code which redirect to apache guacamle RDP connection is a simple redirect to html page:

from flask import Flask, request, render_template, redirect
return render_template('gqm.html')

Somone has some recommandtion of a browser \ configuration i can change in tomcat or my python code?
To maybe send forced clear cookie\cache to this specific site connection?

Body:
Solved this by not giving a uniq user to a uniq connection, but giving the same user (guacadmin) and blocked the user from seeing home page, using nginx :

location / {
proxy_pass http://guacamole:8080/guacamole/;
rewrite ^.*api/session/data/postgresql.*/activeConnections.* /no_such_page last;

so when i redirect client to a connection using the url token he cannot do logout\home page as it will give him an error.


问:
Is possible, make the framework HUGO to building dynamic websites from a json?
I tested build a website with Middleman and was possible build dynamic pages with info from a json, including the url path with slug originally from Jason, but the middleman get so much time do build website if we compare it with Hugo.

So is possible, make some similar with Hugo?

答:
No, it is not possible, at least not with hugo alone.

You can read JSON from any URL and use it's data in a page (https://gohugo.io/templates/data-templates/#call-the-functions-with-a-url)

But to dynamically create new pages from JSON data is not possible in hugo, as is discussed here:

https://github.com/gohugoio/hugo/issues/140 (I used to have better links, but can't find them right now)

You can do it, by running some other script that generates the pages. As an example see

https://github.com/kidsil/hugo-data-to-pages


问:
Imgur server-to-server request on-behalf of user?
I am currently designing a solution for a client and they which to create albums of images and display them on the website. The crux is that ideally we want to offload the hosting of the images to a third-party service (i.e. imgur). Is it possible with the imgur API to make requests on-behalf of a user without explicit (e.g. redirect with login) user consent?</p>

答: FYI, this is not possible. If anyone is looking for a similar solution, none of the big players allow this type of integration. I ended up using a custom solution.</p>


问:
Apache Camel not printing FTP logs
I have a route in Apache Camel that I am calling from a Spring Boot application. My Camel route picks up a file from one server using FTP and transfers to another server using FTP. My route looks like the below:

```<code>public void configure() throws Exception {
        errorHandler(defaultErrorHandler()
                .maximumRedeliveries(3)
                .redeliveryDelay(1000)
                .loggingLevel(LoggingLevel.DEBUG)
                .retryAttemptedLogLevel(LoggingLevel.DEBUG));

        from("direct:transferFile")
            .doTry()
                .log("Transferring file")
                .process(requestProcessor)
                .log("${exchangeProperty.inputEndpoint}")
                .pollEnrich()
                    .simple("${exchangeProperty.inputEndpoint}").timeout(0).aggregationStrategy(requestAggregator)
                .choice()
                    .when(body().isNotNull())
                        .toD("${exchangeProperty.outputEndpoint}", true)
                        .log("File transferred")
                        .endChoice()
                    .otherwise()
                        .log("Empty body, exiting")
                        .endChoice()
                .endDoTry()
            .doCatch(Exception.class)
                .log("Exception")
            .end();
    }
</code>```

The problem is it is not printing the FTP logs like username, password etc when it is attempting to connect to the FTP servers. Can anyone please let me know how can I enable the FTP logs?

答:
Just enable TRACE level for "org.apache.camel.component.file.remote" package. Here log4j2 example:

```<code>appender.stdout.type = Console
appender.stdout.name = stdout
appender.stdout.layout.type = PatternLayout
appender.stdout.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
rootLogger.level = INFO
rootLogger.appenderRef.stdout.ref = stdout

logger.stdout.name = org.apache.camel.component.file.remote
logger.stdout.level = TRACE
</code>```

Output:

```<code>2020-02-20 12:57:49,355 [ing.Main.main()] DEBUG FtpEndpoint                    - Created FTPClient [connectTimeout: 10000, soTimeout: 300000, dataTimeout: 30000, bufferSize: 32768, receiveDataSocketBufferSize: 0, sendDataSocketBufferSize: 0]: org.apache.commons.net.ftp.FTPClient@2620b111
2020-02-20 12:57:49,400 [ing.Main.main()] DEBUG RemoteFileProducer             - Starting
2020-02-20 12:57:49,401 [ing.Main.main()] TRACE RemoteFileProducer             - Starting producer: RemoteFileProducer[ftp://anonymous@10.192.0.50:21/Public/someFolder/]
2020-02-20 12:57:49,402 [ing.Main.main()] INFO  SpringCamelContext             - Route: timer:foo?period=5s started and consuming from: timer://foo?period=5s
2020-02-20 12:57:49,403 [ing.Main.main()] INFO  SpringCamelContext             - Total 1 routes, of which 1 are started
2020-02-20 12:57:49,404 [ing.Main.main()] INFO  SpringCamelContext             - Apache Camel 2.25.0 (CamelContext: Test) started in 0.358 seconds
2020-02-20 12:57:50,426 [2 - timer://foo] TRACE RemoteFileProducer             - Processing file: Public/someFolder/test.txt for exchange: Exchange[ID-Antons-iMac-local-1582189068946-0-1]
2020-02-20 12:57:50,426 [2 - timer://foo] DEBUG RemoteFileProducer             - Not already connected/logged in. Connecting to: ftp://anonymous@10.192.0.50:21/Public/someFolder/
2020-02-20 12:57:50,426 [2 - timer://foo] TRACE FtpOperations                  - Connecting using FTPClient: org.apache.commons.net.ftp.FTPClient@2620b111
2020-02-20 12:57:50,427 [2 - timer://foo] TRACE FtpOperations                  - Connecting to ftp://anonymous@10.192.0.50:21 using connection timeout: 10000
2020-02-20 12:57:52,461 [2 - timer://foo] TRACE FtpOperations                  - Using SoTimeout=300000
2020-02-20 12:57:52,462 [2 - timer://foo] TRACE FtpOperations                  - Attempting to login user: anonymous using password: ********
2020-02-20 12:57:59,903 [2 - timer://foo] TRACE FtpOperations                  - User anonymous logged in: true
2020-02-20 12:57:59,926 [2 - timer://foo] DEBUG RemoteFileProducer             - Connected and logged in to: ftp://anonymous@10.192.0.50:21/Public/someFolder/
2020-02-20 12:57:59,926 [2 - timer://foo] TRACE FtpOperations                  - buildDirectory(Public/someFolder)
2020-02-20 12:58:00,020 [2 - timer://foo] TRACE FtpOperations                  - changeCurrentDirectory(/)
2020-02-20 12:58:00,020 [2 - timer://foo] TRACE FtpOperations                  - Changing directory: /
2020-02-20 12:58:00,122 [2 - timer://foo] TRACE RemoteFileProducer             - About to write [Public/someFolder/test.txt] to [ftp://anonymous@10.192.0.50:21/Public/someFolder/] from exchange [Exchange[ID-Antons-iMac-local-1582189068946-0-1]]
2020-02-20 12:58:00,122 [2 - timer://foo] DEBUG FtpClientActivityListener      - Uploading to host: ftp://anonymous@10.192.0.50:21 file: Public/someFolder/test.txt starting
2020-02-20 12:58:00,122 [2 - timer://foo] TRACE FtpOperations                  - storeFile(Public/someFolder/test.txt)
2020-02-20 12:58:00,122 [2 - timer://foo] TRACE FtpOperations                  - getCurrentDirectory()
2020-02-20 12:58:00,212 [2 - timer://foo] TRACE FtpOperations                  - Current dir: /
2020-02-20 12:58:00,212 [2 - timer://foo] TRACE FtpOperations                  - changeCurrentDirectory(Public/someFolder)
2020-02-20 12:58:00,212 [2 - timer://foo] TRACE FtpOperations                  - Changing directory: Public
2020-02-20 12:58:00,217 [2 - timer://foo] TRACE FtpOperations                  - Changing directory: someFolder
2020-02-20 12:58:00,310 [2 - timer://foo] TRACE FtpOperations                  - doStoreFile(test.txt)
2020-02-20 12:58:00,311 [2 - timer://foo] DEBUG FtpOperations                  - About to store file: test.txt using stream: java.io.ByteArrayInputStream@7eeeaf66
2020-02-20 12:58:00,311 [2 - timer://foo] TRACE FtpOperations                  - Client storeFile: test.txt
2020-02-20 12:58:00,527 [2 - timer://foo] DEBUG FtpOperations                  - Took 0.216 seconds (216 millis) to store file: test.txt and FTP client returned: true
</code>```

Title: Apache Camel not printing FTP logs

Body:
I have a route in Apache Camel that I am calling from a Spring Boot application. My Camel route picks up a file from one server using FTP and transfers to another server using FTP. My route looks like the below:

public void configure() throws Exception {
        errorHandler(defaultErrorHandler()
                .maximumRedeliveries(3)
                .redeliveryDelay(1000)
                .loggingLevel(LoggingLevel.DEBUG)
                .retryAttemptedLogLevel(LoggingLevel.DEBUG));

        from("direct:transferFile")
            .doTry()
                .log("Transferring file")
                .process(requestProcessor)
                .log("${exchangeProperty.inputEndpoint}")
                .pollEnrich()
                    .simple("${exchangeProperty.inputEndpoint}").timeout(0).aggregationStrategy(requestAggregator)
                .choice()
                    .when(body().isNotNull())
                        .toD("${exchangeProperty.outputEndpoint}", true)
                        .log("File transferred")
                        .endChoice()
                    .otherwise()
                        .log("Empty body, exiting")
                        .endChoice()
                .endDoTry()
            .doCatch(Exception.class)
                .log("Exception")
            .end();
    }

The problem is it is not printing the FTP logs like username, password etc when it is attempting to connect to the FTP servers. Can anyone please let me know how can I enable the FTP logs?

Body:
Just enable TRACE level for "org.apache.camel.component.file.remote" package. Here log4j2 example:

appender.stdout.type = Console
appender.stdout.name = stdout
appender.stdout.layout.type = PatternLayout
appender.stdout.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
rootLogger.level = INFO
rootLogger.appenderRef.stdout.ref = stdout

logger.stdout.name = org.apache.camel.component.file.remote
logger.stdout.level = TRACE

Output:

2020-02-20 12:57:49,355 [ing.Main.main()] DEBUG FtpEndpoint                    - Created FTPClient [connectTimeout: 10000, soTimeout: 300000, dataTimeout: 30000, bufferSize: 32768, receiveDataSocketBufferSize: 0, sendDataSocketBufferSize: 0]: org.apache.commons.net.ftp.FTPClient@2620b111
2020-02-20 12:57:49,400 [ing.Main.main()] DEBUG RemoteFileProducer             - Starting
2020-02-20 12:57:49,401 [ing.Main.main()] TRACE RemoteFileProducer             - Starting producer: RemoteFileProducer[ftp://anonymous@10.192.0.50:21/Public/someFolder/]
2020-02-20 12:57:49,402 [ing.Main.main()] INFO  SpringCamelContext             - Route: timer:foo?period=5s started and consuming from: timer://foo?period=5s
2020-02-20 12:57:49,403 [ing.Main.main()] INFO  SpringCamelContext             - Total 1 routes, of which 1 are started
2020-02-20 12:57:49,404 [ing.Main.main()] INFO  SpringCamelContext             - Apache Camel 2.25.0 (CamelContext: Test) started in 0.358 seconds
2020-02-20 12:57:50,426 [2 - timer://foo] TRACE RemoteFileProducer             - Processing file: Public/someFolder/test.txt for exchange: Exchange[ID-Antons-iMac-local-1582189068946-0-1]
2020-02-20 12:57:50,426 [2 - timer://foo] DEBUG RemoteFileProducer             - Not already connected/logged in. Connecting to: ftp://anonymous@10.192.0.50:21/Public/someFolder/
2020-02-20 12:57:50,426 [2 - timer://foo] TRACE FtpOperations                  - Connecting using FTPClient: org.apache.commons.net.ftp.FTPClient@2620b111
2020-02-20 12:57:50,427 [2 - timer://foo] TRACE FtpOperations                  - Connecting to ftp://anonymous@10.192.0.50:21 using connection timeout: 10000
2020-02-20 12:57:52,461 [2 - timer://foo] TRACE FtpOperations                  - Using SoTimeout=300000
2020-02-20 12:57:52,462 [2 - timer://foo] TRACE FtpOperations                  - Attempting to login user: anonymous using password: ********
2020-02-20 12:57:59,903 [2 - timer://foo] TRACE FtpOperations                  - User anonymous logged in: true
2020-02-20 12:57:59,926 [2 - timer://foo] DEBUG RemoteFileProducer             - Connected and logged in to: ftp://anonymous@10.192.0.50:21/Public/someFolder/
2020-02-20 12:57:59,926 [2 - timer://foo] TRACE FtpOperations                  - buildDirectory(Public/someFolder)
2020-02-20 12:58:00,020 [2 - timer://foo] TRACE FtpOperations                  - changeCurrentDirectory(/)
2020-02-20 12:58:00,020 [2 - timer://foo] TRACE FtpOperations                  - Changing directory: /
2020-02-20 12:58:00,122 [2 - timer://foo] TRACE RemoteFileProducer             - About to write [Public/someFolder/test.txt] to [ftp://anonymous@10.192.0.50:21/Public/someFolder/] from exchange [Exchange[ID-Antons-iMac-local-1582189068946-0-1]]
2020-02-20 12:58:00,122 [2 - timer://foo] DEBUG FtpClientActivityListener      - Uploading to host: ftp://anonymous@10.192.0.50:21 file: Public/someFolder/test.txt starting
2020-02-20 12:58:00,122 [2 - timer://foo] TRACE FtpOperations                  - storeFile(Public/someFolder/test.txt)
2020-02-20 12:58:00,122 [2 - timer://foo] TRACE FtpOperations                  - getCurrentDirectory()
2020-02-20 12:58:00,212 [2 - timer://foo] TRACE FtpOperations                  - Current dir: /
2020-02-20 12:58:00,212 [2 - timer://foo] TRACE FtpOperations                  - changeCurrentDirectory(Public/someFolder)
2020-02-20 12:58:00,212 [2 - timer://foo] TRACE FtpOperations                  - Changing directory: Public
2020-02-20 12:58:00,217 [2 - timer://foo] TRACE FtpOperations                  - Changing directory: someFolder
2020-02-20 12:58:00,310 [2 - timer://foo] TRACE FtpOperations                  - doStoreFile(test.txt)
2020-02-20 12:58:00,311 [2 - timer://foo] DEBUG FtpOperations                  - About to store file: test.txt using stream: java.io.ByteArrayInputStream@7eeeaf66
2020-02-20 12:58:00,311 [2 - timer://foo] TRACE FtpOperations                  - Client storeFile: test.txt
2020-02-20 12:58:00,527 [2 - timer://foo] DEBUG FtpOperations                  - Took 0.216 seconds (216 millis) to store file: test.txt and FTP client returned: true


问:
getopt always return -1 if begin from third arguments
I'm making a simple console that do something based on the command of the second argument. Below is the simplified code. My console however doesn't print any NSLog, and after checking, opt is always -1.

Usage is myconsole firstMethod -t "this is a test string"

```<code>int main(int argc, char *argv[], char *envp[]) {

    NSString *stringArgument = [NSString stringWithFormat:@"%s", argv[1]];

    if([stringArgument caseInsensitiveCompare:@"firstMethod"] == NSOrderedSame) {
        extern char *optarg;
        extern int optind;
        int opt;

        while ((opt = getopt(argc, argv, "t:")) != -1) {
            switch (opt){
                case 't':
                    NSLog(@"Case t");
                break;
                default:
                    NSLog(@"Default");
            }
        }
    }
}
</code>```

Any idea why this failed? Thanks in advance.

答:
The non-option arguments have to go at the end in general. GNU getopt() moves these to the end automatically by default, but your implementation does not have this feature, so getopt() stops processing at the first non-option argument.

If you always have the first argument as non-option (for example, a single command name), you can pass a modified (advanced by one argument) argument vector to getopt() like this:

```<code>while ((opt = getopt(argc-1, argv+1, "t:")) != -1){
</code>```

Then the first argument (which is non-option in your case) should be skipped.

Body:
I'm making a simple console that do something based on the command of the second argument. Below is the simplified code. My console however doesn't print any NSLog, and after checking, opt is always -1.

Usage is myconsole firstMethod -t "this is a test string"

int main(int argc, char *argv[], char *envp[]) {

    NSString *stringArgument = [NSString stringWithFormat:@"%s", argv[1]];

    if([stringArgument caseInsensitiveCompare:@"firstMethod"] == NSOrderedSame) {
        extern char *optarg;
        extern int optind;
        int opt;

        while ((opt = getopt(argc, argv, "t:")) != -1) {
            switch (opt){
                case 't':
                    NSLog(@"Case t");
                break;
                default:
                    NSLog(@"Default");
            }
        }
    }
}

Any idea why this failed? Thanks in advance.

Body:
The non-option arguments have to go at the end in general. GNU getopt() moves these to the end automatically by default, but your implementation does not have this feature, so getopt() stops processing at the first non-option argument.

If you always have the first argument as non-option (for example, a single command name), you can pass a modified (advanced by one argument) argument vector to getopt() like this:

while ((opt = getopt(argc-1, argv+1, "t:")) != -1){

Then the first argument (which is non-option in your case) should be skipped.


问:
Disable mouse scroll middle click event with jQuery
I wrote the below code for disabling the scroll in the mouse while it is clicked.
but my code does not work an when I click with the scroll of my mouse it opens my link.

Here is my code :

$('a').on('mousedown', function(e) {
  if (e.which === 2) {
    console.log('Disabled');
    return false;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
 click here </code>```

答:
You have to use auxclick in order to disable this feature. Replace your 'click' with 'auxclick', and add e.preventDefault(), it will work, tested in chrome and FF

$('a').on('auxclick', function(e) {
  if (e.which === 2) {
    e.preventDefault();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
 click here </code>```

Body:
I wrote the below code for disabling the scroll in the mouse while it is clicked.
but my code does not work an when I click with the scroll of my mouse it opens my link.

Here is my code :

$('a').on('mousedown', function(e) {
  if (e.which === 2) {
    console.log('Disabled');
    return false;
  }
});

 click here

Body:
You have to use auxclick in order to disable this feature. Replace your 'click' with 'auxclick', and add e.preventDefault(), it will work, tested in chrome and FF

$('a').on('auxclick', function(e) {
  if (e.which === 2) {
    e.preventDefault();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<a href="#dontwanttoopen"> click here </a>


问:
How can I change routes in React in response to window message event?
I have a React App which is intended to be embedded into another non-react application.  It resides within an iframe on the main applications page.  The react app uses react-router (5.0.0) and react-router-dom (5.1.0) In the react app, when someone clicks a nav link, i fire off a:

```<code>window.parent.postMessage(window.location.pathname,"*");
</code>```

So that i can make the parent websites url path match that of the iframe.   I have also tied into the onpopstate event of the parent window so that i can capture the back button of the browser when it is clicked and then fire off a:

```<code>iframe.contentWindow.postMessage(new_url, '*');
</code>```

The idea here is that in the React app i will listen for this message and then manually route to the correct location to keep both the parent and the iframe in sync when the back button is clicked.

I have verified that when i use the back button, i do in fact get the message in the iframe, however i am confused on the best way to trigger this re-route.  For now, i put the event listener into the root element like this:

```<code>import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { push } from 'react-router-redux';
import Wizard from '../Wizards';

const Root = (props) => {
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  // Listen to message from child window
  eventer(messageEvent,function(e) {
    console.log(e);
    console.log('props');

    console.log(props);
    //props.store.dispatch(push('/broadcast_wizard/step1'));
    //Router.push('/broadcast_wizard/step1');
    //this.context.history.push('/broadcast_wizard/step1');
    console.log('why?');

  },false);

  return (
    <Provider store={props.store}>
      <Router>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700"/>
        <Switch>
          <Route path="/broadcast_wizard/:step" component={Wizard} />
          <Route path="/:filter?">
            Root page
          </Route>
        </Switch>
      </Router>
    </Provider>
  );
};

export default Root;
</code>```

In the above examples i have included (commented out) all the things that i have tried so far that have failed.  Please help, new to React but many years of JavaScript experience.

答:
Do you have to render the React app in an iframe? Have you explored mounting it on another root element? This might make things easier

Something like:

```<code>ReactDOM.render(
  <App/>,
  document.getElementById('react-root') as HTMLElement
)
</code>```

Body:
I have a React App which is intended to be embedded into another non-react application.  It resides within an iframe on the main applications page.  The react app uses react-router (5.0.0) and react-router-dom (5.1.0) In the react app, when someone clicks a nav link, i fire off a:

window.parent.postMessage(window.location.pathname,"*");

So that i can make the parent websites url path match that of the iframe.   I have also tied into the onpopstate event of the parent window so that i can capture the back button of the browser when it is clicked and then fire off a:

iframe.contentWindow.postMessage(new_url, '*');

The idea here is that in the React app i will listen for this message and then manually route to the correct location to keep both the parent and the iframe in sync when the back button is clicked.

I have verified that when i use the back button, i do in fact get the message in the iframe, however i am confused on the best way to trigger this re-route.  For now, i put the event listener into the root element like this:

import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { push } from 'react-router-redux';
import Wizard from '../Wizards';

const Root = (props) => {
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  // Listen to message from child window
  eventer(messageEvent,function(e) {
    console.log(e);
    console.log('props');

    console.log(props);
    //props.store.dispatch(push('/broadcast_wizard/step1'));
    //Router.push('/broadcast_wizard/step1');
    //this.context.history.push('/broadcast_wizard/step1');
    console.log('why?');

  },false);

  return (
    <Provider store={props.store}>
      <Router>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700"/>
        <Switch>
          <Route path="/broadcast_wizard/:step" component={Wizard} />
          <Route path="/:filter?">
            Root page
          </Route>
        </Switch>
      </Router>
    </Provider>
  );
};

export default Root;

In the above examples i have included (commented out) all the things that i have tried so far that have failed.  Please help, new to React but many years of JavaScript experience.

Body:
Do you have to render the React app in an iframe? Have you explored mounting it on another root element? This might make things easier

Something like:

ReactDOM.render(
  <App/>,
  document.getElementById('react-root') as HTMLElement
)


问:
Assign a unique 4 digit number to a list of ids using python
I have a list of ids that i want to give a 4 digit unique number for each of them .

For example :

```<code>driver id = ['5c73d1238472750067e86c6d','5a0d5513494c09001491c118']
unique id = ['1234' , '5897']
</code>```

Is there a package i can use for this?

答:
You can use the zfill function of the string object like this

```<code>ids = [1, 2, 3, 4]
list(map(lambda x: str(x).zfill(4), ids))
</code>```

And will result in:

```<code>['0001', '0002', '0003', '0004']
</code>```

Body:
I have a list of ids that i want to give a 4 digit unique number for each of them .

For example :

driver id = ['5c73d1238472750067e86c6d','5a0d5513494c09001491c118']
unique id = ['1234' , '5897']

Is there a package i can use for this?

Body:
You can use the zfill function of the string object like this

ids = [1, 2, 3, 4]
list(map(lambda x: str(x).zfill(4), ids))

And will result in:

['0001', '0002', '0003', '0004']


问:
how can I make variadic template function with a function pointer as non type argument?
what I want to achieve is create a temple similar to following:

```<code>template<type R, type T, type S, auto F, class ...Fargs>
R create(T input, Fargs... fargs)
{
  S a = F(input, fargs ...);
  return some_func(a, input.b);
}
</code>```

Then I would like to call it like

```<code>int x = create<int, SomeClass, float, SomeFunc_to_apply>(2, someObj, 8.0f, 3, "whatever", "it", "needs");
</code>```

答:
You can simplify a little:

```<code>template <auto F, typename T, class ...Fargs>
decltype(auto) create(T input, Fargs... fargs)
{
  auto a = F(input, fargs ...);
  return some_func(a, input.b);
}
</code>```

And use it:

```<code>SomeClass someObj;
float SomeFunc_to_apply(SomeClass, float, int, const char*, const char*, const char*);
int x = create<SomeFunc_to_apply>(someObj, 8.0f, 3, "whatever", "it", "needs");
</code>```

Demo

Body:
what I want to achieve is create a temple similar to following:

template<type R, type T, type S, auto F, class ...Fargs>
R create(T input, Fargs... fargs)
{
  S a = F(input, fargs ...);
  return some_func(a, input.b);
}

Then I would like to call it like

int x = create<int, SomeClass, float, SomeFunc_to_apply>(2, someObj, 8.0f, 3, "whatever", "it", "needs");

Body:
You can simplify a little:

template <auto F, typename T, class ...Fargs>
decltype(auto) create(T input, Fargs... fargs)
{
  auto a = F(input, fargs ...);
  return some_func(a, input.b);
}

And use it:

SomeClass someObj;
float SomeFunc_to_apply(SomeClass, float, int, const char*, const char*, const char*);
int x = create<SomeFunc_to_apply>(someObj, 8.0f, 3, "whatever", "it", "needs");

Demo


问:
Why the volume folder is empty after a redis save?

Code

I'm trying to run a redis service defined inside a docker-compose.yml as follows:

```<code>version: '3'
services:
  redis:
    image: "redis:5-alpine"
    volumes:
      - ./redis-vol:/home/data
  app:
    build: .
    ports:
      - 8080:8080
    volumes:
      - .:/home/app/
</code>```

This is the Dockerfile:

```<code>FROM python:2.7-alpine3.8
WORKDIR /home/app
COPY ./requirements.txt .
RUN apk add python2-dev build-base linux-headers pcre-dev && \
    pip install -r requirements.txt
# Source files
COPY ./api.py .
COPY ./conf.ini .
CMD ["uwsgi", "--ini", "conf.ini"]
</code>```

The app consists of this snippet running a uwsgi interface on port 8080

```<code>import uwsgi
import redis
r = redis.Redis('redis')
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    r.append('hello', 'world!')
    r.save()
    return [b"Hello World"]
</code>```

And this is the conf.ini file:

```<code>[uwsgi]
http = :8080
wsgi-file = api.py
master = true
process = 2
enable-threads = true
uid = 1001
gid = 1001
</code>```

The app service is supposed to save a key:value pair through redis every time it receives a request to http://localhost:8080.
Upon a successful request, the docker-compose process returns the following log:

```<code>redis_1_bdf757fbb2bf | 1:M 26 Nov 2018 15:38:20.399 * DB saved on disk
app_1_5f729e6bcd36   | [pid: 17|app: 0|req: 1/1] 172.21.0.1 () {38 vars in 690 bytes} [Mon Nov 26 15:38:20 2018] GET / => generated 11 bytes in 8 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1 switches on core 0)
redis_1_bdf757fbb2bf | 1:M 26 Nov 2018 15:38:20.998 * DB saved on disk
app_1_5f729e6bcd36   | [pid: 17|app: 0|req: 2/2] 172.21.0.1 () {40 vars in 691 bytes} [Mon Nov 26 15:38:20 2018] GET /favicon.ico => generated 11 bytes in 4 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1 switches on core 0)
</code>```

Problem

Despite the DB saved on disk log, the redis_vol folder is empty and the dump.rdb file doesn't seem to be saved anywhere else.

What I am doing wrong? I've also tried to use redis:alpine as image but I have the following error at startup:

```<code>redis_1_bdf757fbb2bf | 1:M 26 Nov 14:57:27.003 # Can't handle RDB format version 9
redis_1_bdf757fbb2bf | 1:M 26 Nov 14:57:27.003 # Fatal error loading the DB: Invalid argument. Exiting.
</code>```

And I've also tried to map the dump.rdb in the redis service as follows:

```<code>  redis:
    image: "redis:5-alpine"
    volumes:
      - ./redis-vol/dump.rdb:/home/data/dump.rdb
</code>```

but the docker creates a folder named dump.rdb/ instead of a readable file.

答:
To be able to mount a single file for your container with docker-compose, use absolute path of the file you want to mount from your filesystem:</p>

```<code>  redis:
    image: "redis:5-alpine"
    volumes:
      - /Users/username/dirname/redis-vol/dump.rdb:/home/data/dump.rdb
</code>```

Body:
Code

I'm trying to run a redis service defined inside a docker-compose.yml as follows:

version: '3'
services:
  redis:
    image: "redis:5-alpine"
    volumes:
      - ./redis-vol:/home/data
  app:
    build: .
    ports:
      - 8080:8080
    volumes:
      - .:/home/app/

This is the Dockerfile:

FROM python:2.7-alpine3.8
WORKDIR /home/app
COPY ./requirements.txt .
RUN apk add python2-dev build-base linux-headers pcre-dev && \
    pip install -r requirements.txt
# Source files
COPY ./api.py .
COPY ./conf.ini .
CMD ["uwsgi", "--ini", "conf.ini"]

The app consists of this snippet running a uwsgi interface on port 8080

import uwsgi
import redis
r = redis.Redis('redis')
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    r.append('hello', 'world!')
    r.save()
    return [b"Hello World"]

And this is the conf.ini file:

[uwsgi]
http = :8080
wsgi-file = api.py
master = true
process = 2
enable-threads = true
uid = 1001
gid = 1001

The app service is supposed to save a key:value pair through redis every time it receives a request to http://localhost:8080.
Upon a successful request, the docker-compose process returns the following log:

redis_1_bdf757fbb2bf | 1:M 26 Nov 2018 15:38:20.399 * DB saved on disk
app_1_5f729e6bcd36   | [pid: 17|app: 0|req: 1/1] 172.21.0.1 () {38 vars in 690 bytes} [Mon Nov 26 15:38:20 2018] GET / => generated 11 bytes in 8 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1 switches on core 0)
redis_1_bdf757fbb2bf | 1:M 26 Nov 2018 15:38:20.998 * DB saved on disk
app_1_5f729e6bcd36   | [pid: 17|app: 0|req: 2/2] 172.21.0.1 () {40 vars in 691 bytes} [Mon Nov 26 15:38:20 2018] GET /favicon.ico => generated 11 bytes in 4 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1 switches on core 0)

Problem

Despite the DB saved on disk log, the redis_vol folder is empty and the dump.rdb file doesn't seem to be saved anywhere else.

What I am doing wrong? I've also tried to use redis:alpine as image but I have the following error at startup:

redis_1_bdf757fbb2bf | 1:M 26 Nov 14:57:27.003 # Can't handle RDB format version 9
redis_1_bdf757fbb2bf | 1:M 26 Nov 14:57:27.003 # Fatal error loading the DB: Invalid argument. Exiting.

And I've also tried to map the dump.rdb in the redis service as follows:

  redis:
    image: "redis:5-alpine"
    volumes:
      - ./redis-vol/dump.rdb:/home/data/dump.rdb

but the docker creates a folder named dump.rdb/ instead of a readable file.

Body:
To be able to mount a single file for your container with docker-compose, use absolute path of the file you want to mount from your filesystem:

  redis:
    image: "redis:5-alpine"
    volumes:
      - /Users/username/dirname/redis-vol/dump.rdb:/home/data/dump.rdb