text:
Q: R - From Factor to Numeric or Integer error I have a dataframe in R that I loaded from a CSV file.  One of the variables is called "Amount" and is meant to contain positive and negative numbers.
When I looked at the dataframe, this variable's datatype is listed as a factor, and I need it in a numeric format (Not sure which kind though - integer - numeric, umm...?).  So, I tried to convert it to one of those two formats but saw some interesting behavior.
Initial dataframe:
str(df)

Amount        : Factor w/ 11837 levels "","-1","-10",..: 2 2 1664 4 6290 6290 6290 6290 6290 6290 ...

As I mentioned above, I saw something weird when I tried to convert it to either numeric or integer.  To show this, I put together this comparison:
df2 <- data.frame(df$Amount, as.numeric(df$Amount), as.integer(df$Amount))

str(df2)
'data.frame':   2620276 obs. of  3 variables:
 $ df.Amount            : Factor w/ 11837 levels "","-1","-10",..: 2 2 1664 4 6290 6290 6290 6290 6290 6290 ...
 $ as.numeric.df.Amount.: num  2 2 1664 4 6290 ...
 $ as.integer.df.Amount.: int  2 2 1664 4 6290 6290 6290 6290 6290 6290 ...

> head(df2, 20)
         df.Amount        as.numeric.df.Amount.       as.integer.df.Amount.
1               -1                           2                           2
2               -1                           2                           2
3             -201                        1664                        1664
4             -100                           4                           4
5                1                        6290                        6290
6                1                        6290                        6290
7                1                        6290                        6290
8                1                        6290                        6290
9                1                        6290                        6290
10               1                        6290                        6290
11               1                        6290                        6290
12               1                        6290                        6290
13               1                        6290                        6290
14               1                        6290                        6290
15               1                        6290                        6290
16               1                        6290                        6290
17               1                        6290                        6290
18               2                        7520                        7520
19               2                        7520                        7520
20               2                        7520                        7520

The as.numeric and as.integer functions are taking the Amount variable and doing something to it, but I don't know that that is.  My goal is to get the Amount variable into some sort of a number data type so I can perform sum/mean/etc on it.
What I am I doing incorrectly that's causing the weird numbers, and what can I do to fix it?

A: The root of the problem is likely some funky value in your imported csv.  If it came from excel, this is not uncommon.  It can be a percent symbol, a "comment" character from excel or any of a long list of things.  I would look at the csv in your editor of choice and see what you can see.
Aside from that, you have a few options.
read.csv takes an optional argument stringsAsFactors which you can set to FALSE
A factor is stored as integer levels which map to values.  When you convert directly with as.numeric you wind up with those integer levels rather than the initial values:
> x<-10:20
> as.numeric(factor(x))
 [1]  1  2  3  4  5  6  7  8  9 10 11
>

otherwise look at ?factor:

In particular, as.numeric applied to a factor is meaningless, and may happen by implicit coercion. To transform a factor f to approximately its
      original numeric values, as.numeric(levels(f))[f] is recommended
      and slightly more efficient than as.numeric(as.character(f)).

However, I suspect this will error because the input has something in it besides a number.

A: @Justin is correct. Here's a walk-through on how to find the offending values:
# A sample data set with a weird value ("4%") in it
d <- read.table(text="A B\n1 2\n3 4%\n", header=TRUE)
str(d)
#'data.frame':   2 obs. of  2 variables:
# $ A: int  1 3
# $ B: Factor w/ 2 levels "2","4%": 1 2

as.numeric(d$B) # WRONG, returns 1 2 (the internal factor codes)

# This correctly converts to numeric
x <- as.numeric(levels(d$B))[d$B] # 2 NA

# ...and this finds the offending value(s):
d$B[is.na(x)]  # 4%

# and this finds the offending row numbers:
which(is.na(x)) # row 2

Note that if your data set has missing values encoded as something other than an empty cell or the string "NA", you have to specify that to read.table:
# Here "N/A" is used instead of "NA"...
read.table(text="A B\n1 2\n3 N/A\n", header=TRUE, na.strings="N/A")

A: I'm new here but I have been using this forum for my queries. I was having similar problem but the below worked for me. I am porting data from txt file to data frame
data <- read.delim(paste(folderpath,"data.txt",sep=""),header=TRUE,sep="\\",as.is=6)

Note that I used as.is on the column 6 which had numeric data as well as some garbage characters in some rows. Using as.is ports the data as characters in column 6. then the following changed the characters in column 6 to numeric values. all garbage values were converted to NA which could be removed later.
data[,6] <- as.numeric(data[,6])

Hope this helps

A: Just convert the factor values to character first, and then convert to numeric. This should solve your problem.
as.numeric(as.character(df$Amount))


text:
Q: Why does dask head() check only first partition by default? dask version 1.1.4
I was caught off-guard by the fact that dask.dataframe.head() does not behave similarly to pandas.
Filtered dask.dataframe seems to keep rows in original partitions. If all rows of a partition are filtered out then partition is left empty but still kept in resulting dask.dataframe. If len(first partition) < n then head(n) doesn't look beyond and misses rows.
import dask
import dask.dataframe as dd

dd = dask.datasets.timeseries()

# Original partitions lengths
print(dd.map_partitions(len).compute())

# Since len(first partition) > 5, head() works fine
print(dd.head())

# Now we filter data
dd_filter = dd[dd['id'] <= 870]

# Observe the empty partitions and those with len < 5
print(dd_filter.map_partitions(len).compute())

# Note the difference between the following two outputs:
print(dd_filter.head())
print(dd_filter.compute().head())

The two outputs are not identical.
The UserWarning when head(n) returns less than n rows does suggest to increase npartitions which solves the problem:
.../dask/dataframe/core.py:4494: UserWarning: Insufficient elements for `head`. 5 elements requested, only 0 elements available. Try passing larger `npartitions` to `head`.
  warnings.warn(msg.format(n, len(r)))

But I would rather not have to keep this in mind every time I use dask. Also, it seems performance suffers significantly if npartitions is set to -1 always even if most partitions are empty.
My question is what is the reasoning behind this particular design? Is it possible to match pandas behaviour by simply traversing through the partitions until n rows are collected or partitions are exhausted?

A:
My question is what is the reasoning behind this particular design? Is it possible to match pandas behaviour by simply traversing through the partitions until n rows are collected or partitions are exhausted?

In some cases, yes, what you suggest would be very feasible, but not in all.  For example, consider the case where your dataframe is the result of a sorting operation.  We can compute the first partition, realize that it isn't enough, but unfortunately at this point we've tossed out all of the previous data.
Should we recompute the full sorted dataset?  That's expensive
Should we compute a few partitions just in case?  That may or may not fit in memory.
At the end of the day the only thing we can do is warn and tell the user what's happening so that they can make a well informed decision on their own.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing Font style of textbox for just one line in C# Trying to change Font Style to Underline for 1 line,and printing next line in Regular Style is not working for me. I am trying something like this:-
    textBox1.Font = new Font(textBox1.Font, FontStyle.Underline);
    textBox1.Text+="This line should be underlined";
    textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
    textBox1.Text+=Environment.NewLine;
    textBox1.Text+="This line should be normal";

But everything is coming only as it is done in the last line affecting FontStyle,in this case Regular. If I remove 3rd line,everything comes underline.

A: A normal TextBox usually just supports one style. Its value is just a string, not a string with formatting information.
Instead, use a RichTextBox (WinForms)/RichTextBox (WPF).


text:
Q: Why this simple SELECT is taking 6 seconds when user has many comments? I have this select to show users some notifications when someone comments in one post.
I noticed that users that has posts with many comments it can take 6 seconds +.
select 'comments' prefix, c.foto, c.data as data, c.user,
       concat(k.user, ' comments your post') as logs
from comments c

inner join posts p on c.foto = p.id
inner join cadastro k on c.user = k.id

where p.user = 1 and c.user <> 1 and c.delete = 0
order by c.data desc
limit 5

I'd like to show users notifications, someone comments your post, to do so, I used inned join on posts (to know if the comment is from user '1') and inner join cadastro (to get user nick name - user who comments user 1 post).
checking on where if user is 1, c.user <> 1 (not show his own comments notifications) and c.delete (comment not deleted).
my tables:
`posts` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user` int(11) UNSIGNED NOT NULL,
  `foto` varchar(400),
  `data` datetime NOT NULL,
  `delete` tinyint(1) NOT NULL DEFAULT '0',
  FOREIGN KEY (`user`) REFERENCES cadastro (`id`),
  PRIMARY KEY (`id`)
)

`comments` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `foto` int(11) UNSIGNED NOT NULL,
  `user` int(11) UNSIGNED NOT NULL,
  `texto` varchar(3000) NOT NULL,
  `data` datetime NOT NULL,
  `delete` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `foto_delete` (foto, `delete`),
  FOREIGN KEY (`foto`) REFERENCES posts (`id`) ON DELETE CASCADE
)

any ideas why it is taking so long when an user has about 200.000 comments? (if user has 1000, it is fast).

A: Without indexes, to run your Query the engine usually scans all rows looking for the required values in the ON, WHERE, as well the ORDER BY clause.
A simple thing you can do is to create the indexes:
CREATE INDEX cadastro_id ON cadastro(id);
CREATE INDEX posts_id ON posts(id);

CREATE INDEX posts_user ON posts(user);

CREATE INDEX comments_foto ON comments(foto);
CREATE INDEX comments_user ON comments(user);
CREATE INDEX comments_delete ON comments(delete);

CREATE INDEX comments_data ON comments(data);

Measure the current time it takes, then apply these Indexes and measure again, and tell here.
See also:
https://dev.mysql.com/doc/refman/5.7/en/create-index.html
https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html


text:
Q: Can I place "non-static blocks" of code in class definitions? Is there non-static block in C++?
If no, how to emulate it elegantly?
I want to replace something like :-
class C{
    public: void ini(){/* some code */}
};
class D{
    std::vector<C*> regis; //will ini(); later
    public: C field1;
    public: C field2;
    public: C field3;             //whenever I add a new field, I have to ... #1
    public: D(){
        regis.push_back(&field1);
        regis.push_back(&field2);
        regis.push_back(&field3); //#1 ... also add a line here
    }
    public: void ini(){
        for(auto ele:regis){
            ele->ini();
        }
    }
};

with :-
class D{
    std::vector<C*> regis;
    public: C field1;{regis.push_back(&field1);}//less error-prone (because it is on-site)
    public: C field2;{regis.push_back(&field2);}
    public: C field3;{regis.push_back(&field3);}
    public: D(){    }  //<-- empty
    public: void ini(){
        for(auto ele:regis){
            ele->ini();
        }
    }
};

I found many questions related to static-block in C++, but didn't found any one about non-static-block.
To make it easy to answer, here is a full code.
It can be done using X-MACRO (wiki link), but I am trying to avoid it.
Edit
In real case, fieldX can has any types that derived from a certain C.
I consider another bad workaround :-
class D{
    std::vector<C*> regis;
    char f(C& c){   regis.push_back(&c); return 42;}
    public: C field1; char dummyWaste1=f(field1);
    public: C field2; char dummyWaste2=f(field2);
    public: C field3; char dummyWaste3=f(field3);

Edit2 (bounty reason)
skypjack's answer is very useful, but I am curious to find out more alternatives.
The final objective is to emulate general non-static block that has more variety.
In other words, it would be nice if new solution can solve this :-
class D{
    int field1=5;
    { do something very custom; /* may access field1 which must = 5 */}
    //^ have to be executed after "field1=5;" but before "field2=7"
    int field2=7;
    int field3=8;
    { do something very custom ; /* e.g. "field1=field2+field3" */}
    //^ have to be executed after "field3=8;"
};

without wasting 1 char (or more - for alignment) for each block.

A:
how to emulate it elegantly?

You can initialize regis directly:
std::vector<C*> regis = { &field1, &field2, &field3 };

That is, define your class as:
class D{
public:
    C field1;
    C field2;
    C field3;

    void ini(){
        for(auto ele:regis){
            ele->ini();
        }
    }

private:
    std::vector<C*> regis = { &field1, &field2, &field3 };
};

Otherwise, if you can add a constructor to C, revert the logic and have it adding itself to the vector:
#include<vector>

struct C {
    C(std::vector<C*> &vec) {
        vec.push_back(this);
        // ...
    }

    void ini() {}
};

class D{
    std::vector<C*> regis{};

public:
    C field1 = regis;
    C field2 = regis;
    C field3 = regis;

    void ini(){
        for(auto ele:regis){
            ele->ini();
        }
    }
};

int main() { D d{}; d.ini(); }

------ EDIT ------
As requested in the comments:

C is a holy class for me. Is it possible to not hack C?

Here is a possible alternative that doesn't require you to modify C:
#include<vector>

struct C {
    void ini() {}
};

struct Wrapper {
    Wrapper(std::vector<C*> &vec) {
        vec.push_back(*this);
        // ...
    }

    operator C *() { return &c; }

private:
    C c;
};

class D{
    std::vector<C*> regis{};

public:
    Wrapper field1{regis};
    Wrapper field2{regis};
    Wrapper field3{regis};

    void ini(){
        for(auto ele:regis){
            ele->ini();
        }
    }
};

int main() { D d{}; d.ini(); }

A: Maybe you are looking for a dummy fields initialized by lambda capturing this pointer invoked immediately after declaration:
#include <iostream>

struct C { };

class D{
    int field1=5;
    int dummy1{[&]{ std::cout << field1 << std::endl; return 0;}()};
    int field2=7;
    int field3=8;
    int dummy2{[&]{ std::cout << (field1 + field2 + field3) << std::endl; return 0;}()};
};

int main() {
    D d;
}

Output:
5
20

[live demo]

A: I'd turn it around and initialise the vector with the "real" objects of type C, let the members field0 .. field2 be of type "reference to C", i.e. C&, and initialise them with the respective elements of the vector. The advantage of this "turn around" is that the various C-elements are placed one after each other in the vector, which is the most compact way and without padding, while still providing "named" data members (i.e. field0..field2) for accessing the elements without exposing the vector member itself.
The custom "static" code can then be done with a comma expression, which lets you place almost arbitrary code. For code that is not allowed in comma expressions, e.g. the declaration of variables, one could still call member functions or use lambda-expressions. So we do not need any dummy members for "static" code executed between the various fields.
The only place where we needed a dummy member is for code to be executed after the last field_x; so the overhead is a single char-value, and the "static" code here is again solved with a comma expression.
See the following code, which demonstrates the approach. Note that you actually do not have to touch class C; member functions/data C::setX,C::print, and int x have been introduced for demonstration purpose only:
class C{
public:
    void ini(){/* some code */}

    // the following methods and data members are actually not necessary; they have been introduced just for demonstration purpose:
    void setX(int _x) { x = _x;  };
    void print() { cout << x << endl; }
    int x;
};

class D{
protected:
    std::vector<C> regis = std::vector<C>(3); //will ini(); later
public:
    C &field0 = (regis[0].setX(5),printAllRegis("at field0:"),regis[0]);
    C &field1 = (regis[1].setX(7),printAllRegis("at field1:"),regis[1]);
    C &field2 = (regis[2].setX(regis[0].x + regis[1].x),printAllRegis("at field2:"),regis[2]);
    char dummy = (cout << "after field2: ", field2.print(), '0');
    D(){ }

    void ini(){
        for(auto ele:regis){ ele.ini(); }
    }

    void printAllRegis(string header) {
        int i=0;
        cout << header << endl;
        for(auto ele:regis){ cout << "  field" << i++ << ":"; ele.print(); }
    }
};

int main() {

    D d;
    /* Output:
     at field0:
       field0:5
       field1:0
       field2:0
     at field1:
       field0:5
       field1:7
       field2:0
     at field2:
       field0:5
       field1:7
       field2:12
     after field2: 12
     */

    return 0;
}

A: Looking at this question, it reminds me to my own "Object with properties" concept. I consider it rather as pragmatical than elegant but I dare to present it:
To establish the dependency between Field and Object, I introduced a back-reference to Object in Field. At the cost of an additional member, this has certain conveniencies.
class Field – the base class required to store fields:
class Object; // forward reference

// super class of all object fields
class Field {
  // variables:
  private:
    // parent object
    Object &_obj;
  // methods:
  protected:
    // constructor.
    Field(Object &obj);
    // destructor.
    ~Field();
    // disabled:
    Field(const Field&) = delete;
    Field operator=(const Field&) = delete;
}

The corresponding class Object – the field container:
#include <vector>

// super class of objects which may contain fields
class Object {
  // friends:
  friend class Field;
  // variables:
  private:
    // table of all registered fields
    std::vector<Field*> _pFields;
  // methods:
  protected:
    // constructor.
    Object() = default;
    // destructor.
    virtual ~Object() = default;
    // disabled:
    Object(const Object&) = delete;
    Object& operator=(const Object&) = delete;
};

The implementation of class Field has to "know" both classes:
#include <algorithm>

// implementation of class Field

Field::Field(Object &obj): _obj(obj)
{
  _obj._pFields.push_back(this);
}

Field::~Field()
{
  _obj.erase(
    std::find(
      _obj._pField.begin(), _obj._pField.end(), this));
}

The template for field instances:
// a class template for derived fields
template <typename VALUE>
class FieldT: public Field {
  // variables:
  private:
    // the value
    VALUE _value;
  // methods:
  public:
    // constructor.
    FieldT(Object &obj, const VALUE &value):
      Field(obj), _value(value)
    { }
    // copy constructor.
    FieldT(Object &obj, const FieldT &field):
      Field(obj), _value(field._value)
    { }
    // disabled:
    FieldT(const FieldT&) = delete;
    FieldT& operator=(const FieldT&) = delete;
};

The advantages and disadvantages as considered by me:
Pros:

*

*The object would never register non-fields.

*You may never forget to construct fields explicitly because the C++ compiler will remind you in this case. (Fields are not default constructable.)

*You may decide in a copy constructor of a derived Object whether to copy the field or initialize it with a constant (or alternative) value instead.
Cons:

*

*It requires explicitly written code in every derived Object which might be considered as tedious. (I, personally, like explicit code to a certain amount to make maintenance easier.)

*It is not foolproof.
E.g. fields created with new are "begging" for memory leaks. (Although... I never considered to simply delete the operator new(). I've to check out this soon.)
So, how could this look in real-life:
// storage of a 2d vector
struct Vec2f {
  float x, y;
  Vec2f(float x, float y): x(x), y(y) { }
};

// storage of a 2d circle
class Circle: public Object {
  // fields:
  public:
    // center
    FieldT<Vec2f> center;
    // radius
    FieldT<float> radius;
 // methods:
 public:
   // constructor.
   explicit Circle(float x, float y, float r):
     Object(),
     center(*this, Vec2f(x, y)),
     radius(*this, r)
   { }
   // copy constructor.
   Circle(const Circle &circle):
     Object(),
     center(*this, center),
     radius(*this, radius)
  { }
};

Note:
You may wonder why the fields are public – this is intentional. In my real-life incarnation, these fields have a lot more i.e. getter and setter as well as (optional) signal slots to install guardians and modification notifier. My intention was to free me from the tedious writing of access methods in the objects.
In real-life this concept has even more potential:

*

*It's sufficient for generic I/O classes which may write and read XML files or other formats.

*It can be obtained in a second concept of generic GUI classes to simplify the creation of user interfaces in a generic way.
Worth of the costs for administrational extra data:
Some extra bytes seems often enough worth to me if they promise a lot of safed development time. Of course, there are counter examples where I consider every single bit e.g. the vertex data when loading geometry for visual simulation. (For the vertex data example, I never considered a property concept to access every single vertex. Instead, I used the properties to access arrays of vertices as once.)
Concerning the additional requirement of additional construction details:

class D{
      int field1=5;
      { do something very custom; }
      //^ have to be executed after "field1=5;" but before "field2=7"
      int field2=7;
      int field3=8;
      { do something very custom ; }//have to be executed after "field3=8;"
  };

I would choose a simple solution which has nothing to do with the above concept:
class D {
  int field1 = 5;
  struct InitBefore {
    InitBefore() {
      // do something very custom;
    }
  } initBefore;
  int field2 = 7;
  int field3 = 8;
  struct InitAfter {
    InitAfter() {
      // do something very custom;
    }
  } initAfter;
  // the rest...
};

Unfortunately, this doesn't fulfill the extra requirement:

without wasting 1 char for each block.

(The reason can be found in SO: sizeof empty structure is 0 in C and 1 in C++ why?.)
May be, it could be solved exploiting the sequence operator and static methods applied to the constructor of the appropriate member. This even seems so ugly to me that I don't dare to sketch code for this.
May be, it could be solved to make an embedded, private derived class of the respective field where the "very custom code" can be added in the constructor. Due to the fact that fields actually have data the empty struct/class problem should be prevented.
Actually, I never cared about the non-zero structs/classes because I needed this trick itself only in rare cases (where only a few resp. instances are expected).
As there are (at the time of writing) still 7 days until the bounty is over I will keep this in mind...

A: something like this?
class D
{
public:
    D()
    {
        objects.emplace("field1", std::make_unique<C>());
        //{ do something very custom; }
        //^ have to be executed after "field1=5;" but before "field2=7"
        objects.emplace("field2", std::make_unique<C>());
        objects.emplace("field3", std::make_unique<C>());
        //{ do something very custom; }//have to be executed after "field3=8;"

        // if you want you can store the pointers in the vector. but since you store everything in the map you maybe wanna drop the vector
        for (const auto& o : objects)
        {
            regis.emplace_back(o.second.get());
        }
    }

private:
    void ini()
    {
        for (auto ele : regis){
            ele->ini();
        }

        /* or use the map to iterate
        for (const auto& o : objects)
        {
            o.second->ini();
        }
        */

        // to acces a specific field:
        //objects["field1"]->any_obj_from_c;
    }
    std::vector<C*> regis; //will ini(); later
    std::map<std::string, std::unique_ptr<C>> objects;
};

A: This may be an overkill here, but alternative still: instead of maintaining D.h and D.cpp write small app, that will generate D.h and D.cpp on base of D.txt, and maintain D.txt. So when you will need to add a new field to D (or some other change), you just add a line to D.txt and run generator.

A: I think it might be smarter to create this the other way around. Instead of artificially enhancing your structure with an additional vector of pointers for iteration purposes, enhance a vector with named fields.
A strong indicator for why you would want to do this is that the layout and naming scheme of your fields already sounds exactly like an array. Think about it, your names are just covering up that you most likely access consecutive fields with indices.
class C {
public:
    int value; // For code example
    void ini() { value = 42; };
};

class D {
    std::array<C, 4 /*or w/e you need*/ > storage;
public:
    // Reference initializers are compulsory, so less chance of forgetting & bugs
    int field_index = 0;
    C& field1 = storage.at(field_index++);
    C& field2 = storage.at(field_index++);
    void ini(){
        for(auto& ele: storage) {
            ele.ini();
        }
    }
    // We can even do some templating due to std::array
    template<size_t I> C& field() {
        return std::get<I>(storage);
    }
};

Now you can add additional stored Cs by increasing the size count of the array, and name any field by simply adding an additional member line. Of course you could also store the array as a member instead of inheriting from it in case you need the member overloads or want a flat hierarchy.
Additional plus: Since all access indices are constant expression, any good compiler might inline the actual access, no matter if done by index or by field.
int main() {
     D d; d.ini();
     int s = d.field1.value + d.field2.value;
     // alternatively d.field<0>().value + d.field<1>().value;
     printf("%i", s); // Compiler can deduce to printf("%i", 84);
}

For example the above will compile to basically little more than printf("%i", 84) with both clang and gcc. You can check this with your own compiler or see the link to https://godbolt.org/g/50VjyY.

Edit: I realized that maybe initialization semantics are the initial reasoning for listing multiple consecutive fields. But any initialization you would normally do on the fields directly can arguably also be done in the array initializer. Assume some constructor
// Replace this (from your structure)
D::D(/*some arguments*/) : field1(args), field2(otherargs) {}

// with this
D::D(/*same arguments*/) : storage{C{args}, C{otherargs}} {}

Edit 2: Although it might not accurately answer the fundamental problem of how to nicely express the above data representation, it should be noted that there is indeed a way to execute arbitrary code in the way you might have originally intended it to but you have to very careful.
class D{
    std::vector<C*> regis;
public:
    C field1 = (regis.push_back(&field1), C{});
    C field2 = (regis.push_back(&field2), C{});
    C field3 = (regis.push_back(&field3), C{});
    D(){    }  //<-- empty
    void ini(){
        for(auto ele:regis){
            ele->ini();
        }
    }
};

Here you need to acknowledge than any initialization in the initializer list of any other constructor you might add later will remove the push_back of the respective pointer! This will likely introduce an hard to find bug and cause obscure side effect. For this reason I would never advise for using the comma operator , in default member initializers.
By using the standard correctly, you can theoretically use values of previous members

12.6.2.5
Initialization shall proceed in the following order:
...
[...] nonstatic data members shall be initialized in the order they were declared in the class definition.

Note that this will also apply to the other initialization with array as well and is not exclusive to your original approach.


text:
Q: Editable cell of WPF Datagrid goes disabled on removing old value and putting blank and then tab out I have problem with WPF datagrid.
One column of my datagrid is editable means I have put its property to IsReadOnly="False".
But, if I make it blank by pressing back space key and tabout and again click on editable field but, then it is not editable. How can I fix this?

A: I tried and and solved this problem with the following approach:
I took "PreviewKeyDown" event in the grid and in this event I wrote the following code:
if (e.Key == Key.Tab)
                    {
                        myGrid.CancelEdit();
                    }

Actually, On editing mode cell expect some value, but if user keeps it blank then Cell Edit mode remains open. So, other cell was not opening in the edit mode.


text:
Q: Javascript : How to retrieve initial value after permutation Starting with a 6-digits value (i.e "123456") and a [0->9] table, this script (but many other exist...) procuces the 123456th permutation of the table :
  let tabl10 = [0,1,2,3,4,5,6,7,8,9],
      permut = permutation( 123456 , tabl10 )

  console.log(permut) // 0,4,1,6,5,9,2,3,7,8

  function permutation(n,a) {
      let f, k = [], l = a.length;
      a = a.slice();
      while (l--) {
         f = factorial(l);
         k.push(Math.floor(n / f));
         n %= f;
      }
      return k.map(function (i) {
         return a.splice(i, 1)[0];
      });
   }

   function factorial(n) {
       let r = 1;
       while (n) {
           r *= n;
           n--;
       }
       return r;
   }

My question is : is it possible to retrieve "123456" from the "0,4,1,6,5,9,2,3,7,8" permutation ?
We have 10! (3.6288 million) of possibles permutations and trying all of them one by one till we find the 123456th is painfull: it is possible to explore all permutations and retrieve the nth with a 7-digits table [0,1,2,3,4,5,6]: 7!=5040, but a 8-digits (40320) or higher definively freezes browsers. How to achieve this ?

A: In a Lehmer code for a permutation perm, the i-th number is the number of the elements on the right of i that are less than perm[i]. So, given a permutation, you can compute its LC first, and then convert the LC from the factorial system to an int, which gives you the index of the permutation.
Complete code:

// int => LC
function int2lc(n, len) {
    let lc = []
    for (let i = 1; i <= len; i++) {
        lc[len - i] = (n % i)
        n = (n / i) | 0
    }
    return lc
}

// LC => int
function lc2int(lc, len) {
    let n = 0, f = 1
    for (let i = 1; i <= len; i++) {
        n += lc[len - i] * f
        f *= i
    }
    return n
}

// LC => permutation
function lc2perm(a, lc) {
    let perm = [], copy = [...a]
    for (let i = 0; i < lc.length; i++) {
        perm[i] = copy[lc[i]]
        copy.splice(lc[i], 1)
    }
    return perm
}

// permutation => LC
function perm2lc(perm) {
    let lc = []
    for (let i = 0; i < perm.length; i++) {
        let c = 0
        for (let k = i + 1; k < perm.length; k++)
            c += perm[k] < perm[i]
        lc[i] = c
    }
    return lc
}

//

A = [0,1,2,3,4,5,6,7,8,9]

// index to perm

N = 123456
lc = int2lc(N, A.length)
console.log('LEHMER', ...lc)
perm = lc2perm(A, lc)
console.log('PERMUT', ...perm)

// perm to index

lc2 = perm2lc(perm)
console.log('LEHMER', ...lc2)
M = lc2int(lc2, A.length)
console.log('INDEX ', M)


text:
Q: How to show $\int_{\sum_{i = 1}^n \gamma_i} f = \sum_{i = 1}^n \int_{\gamma_i} f$
Let $G \subset \mathbb C$ be an open set, $f: G \to \mathbb C$ a continuous function and $\gamma: [\alpha, \beta] \to G$ a contour. Define the contour integral of $f$ along $\gamma$ to be
  \begin{align*}
\int_\gamma f = \sum_{k = 1}^n \int_{t_{k-1}}^{t_k} f(\gamma(t)) \gamma'(t)dt,
\end{align*}
  where $\alpha = t_0 < t_1 < \ldots < t_n = \beta$ is the partition of $[\alpha, \beta]$, associated to $\gamma = \sum_{i = 1}^n \gamma_i$.

I tried to prove the (simple) fact that, if we have a smooth contour then

\begin{align*}
\int_{\sum_{i = 1}^n \gamma_i} f = \sum_{i = 1}^n \int_{\gamma_i} f.
\end{align*}

I suppose it is straight forward, just with the definition, and I reached the following point:
\begin{align*}
\int_{\sum_{i = 1}^n \gamma_i} f &= \int_\alpha^\beta f\left(\sum_{i = 1}^n \gamma_i(t)\right) \left(\sum_{i = 1}^n \gamma_i(t)\right)' dt
= \sum_{i = 1}^n \int_\alpha^\beta f\left(\sum_{i = 1}^n \gamma_i(t)\right) \gamma_i'(t) dt.
\end{align*}
The problem is, that I need $f(\gamma_i)$ instead of $f\left(\sum_{i = 1}^n \gamma_i(t)\right)$ on the right hand side. How can I achieve that?


text:
Q: What is the minimum reputation amount required to view questions without replies tagged as "duplicate""? When not logged in, attempting to visit a question that is marked as duplicate of another and doesn't have any replies, redirects to the original question (i.e. the question displayed in the "possible duplicates" banner.)
Example: When not logged in, visiting this question Malicious site using "stackoverflow.com" as subdomain redirects to A site (or scraper) is copying content from Stack Exchange. What should I do?. When I am logged in using this account (477 reputation) this redirect doesn't happen.
What is the minimum reputation amount required to view duplicate questions without redirecting?

A: The minimum reputation is 1. You just need to have an account and be logged in for the redirect not to be applied; it only applies to anonymous (logged-out) users:

Starting with the next build, anonymous users will be redirected when they visit duplicate questions with no answers.
As with migration and merge redirects you can disable with ?noredirect=1.


text:
Q: How can I automatically insert images for each row of Google Sheets document to a Slides template (mail merge) using Apps Script? I want that Apps Script to automatically generate a new set of slides using data from a Sheets document which has rows of the different information I want inserted into a Slides template replacing the placeholder tags. I want it to do it instantly for each row inside the table with one action, so if there are 10 rows, 10 sets of Slides documents will be generated.
The text replacement works, however I'm not sure how to replace, for example, a placeholder tag with "{{image}}"
The Image is a generated Qr code in column (N) with an sheet addon (QR Code  for Classroom Attendance)and for each row separate. For example 10 rows with different qr codes. This addon writes the generate QR code in the column N. As I said for each I have a different Qr code.
function mailMergeSlidesFromSheets() {
  // Load data from the spreadsheet
  var dataRange = SpreadsheetApp.getActive().getDataRange();
  var sheetContents = dataRange.getValues();

  // Save the header in a variable called header
  var header = sheetContents.shift();

  // Create an array to save the data to be written back to the sheet.
  // We'll use this array to save links to Google Slides.
  var updatedContents = [];

  // Add the header to the array that will be written back
  // to the sheet.
  updatedContents.push(header);

  // For each row, see if the 4th column is empty.
  // If it is empty, it means that a slide deck hasn't been
  // created yet.
  sheetContents.forEach(function(row) {
    if(row[14] === "") {
      // Create a Google Slides presentation using
      // information from the row.
      var slides = createSlidesFromRow(row);
      var slidesId = slides.getId();

      // Create the Google Slides' URL using its Id.
      var slidesUrl = `https://docs.google.com/presentation/d/${slidesId}/edit`;

      // Add this URL to the 4th column of the row and add this row
      // to the updatedContents array to be written back to the sheet.
      row[14] = slidesUrl;
      updatedContents.push(row);
    }
  });

  // Write the updated data back to the Google Sheets spreadsheet.
  dataRange.setValues(updatedContents);

}

function createSlidesFromRow(row) {
 // Create a copy of the Slides template
 var deck = createCopyOfSlidesTemplate();

 // Rename the deck using the firstname and lastname of the student
 deck.setName(row[4] + " " + row[9] + row[3]);

 // Replace template variables using the student's information.
    deck.replaceAllText("{{id}}", row[0]);
    deck.replaceAllText("{{tag}}", row[3]);
    deck.replaceAllText("{{besetzung}}", row[4]);
    deck.replaceAllText("{{beginn}}", row[5]);
    deck.replaceAllText("{{ende}}", row[6]);
    deck.replaceAllText("{{halle}}", row[7]);
    deck.replaceAllText("{{stand}}", row[8]);
    deck.replaceAllText("{{firma}}", row[2]);
    deck.replaceAllText("{{veranstaltung}}", row[9]);
    deck.insertImage("{{image}}", row[13]);

 return deck;
}

function createCopyOfSlidesTemplate() {
 //
 var TEMPLATE_ID = "19PKvWoDtbeVHcqm4DnWUxRx1OBO817uG3cL5Ox-dQoo";

 // Create a copy of the file using DriveApp
 var copy = DriveApp.getFileById(TEMPLATE_ID).makeCopy();

 // Load the copy using the SlidesApp.
 var slides = SlidesApp.openById(copy.getId());

 return slides;
}

function onOpen() {
 // Create a custom menu to make it easy to run the Mail Merge
 // script from the sheet.
 SpreadsheetApp.getUi().createMenu("⚙ Create BWN by Pavlos")
   .addItem("Create Slides","mailMergeSlidesFromSheets")
   .addToUi();
}

 replaces the placeholder tags with the desired text
      // I am not sure how to insert something similar for images and charts in the code here
      // I've tried variations of the below, none of which have worked

        // picture.find("{{image}}").replace(image);
          //  picture.findText("{{image}}").replace(image);
              //  picture.getText("{{image}}").replaceWithImage(image);
                 // picture.getText().findText("{{image}}").replace(image);

A: I believe your goal is as follows.

*

*You want to replace {{Image}} on 1st page of Google Slides with the image.

*The image can be retrieved by the URL like "https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl="&M2.

In this case, how about directly using the values of column "M" as follows? When your script is modified, please modify it as follows.
From:
deck.insertImage("{{image}}", row[13]);

To:
deck.getSlides()[0].getShapes().find(s => s.getText().asString().trim().toUpperCase() == "{{IMAGE}}").replaceWithImage(`https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=${row[12]}`);

Note:

*

*In this modification, it supposes that row[14] === "" is true and the column "M" has the value of https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=${value}. Please be careful about this.

*It seems that there are a lot of rows you want to process. So, if the maximum execution time (6 minutes) is over, please separate the rows for processing. In your this question, you want to replace {{Image}} with the image. So, this answer is for it. Please be careful about this.
Reference:

*

*replaceWithImage(imageUrl)


text:
Q: Why does += reset the value of the variable it's operating on to nil? Taking this piece of code as an example:
class Thing
  attr_accessor :options, :list

  def initialize
    @list    = []
    @options = { published_at_end: 'NOW', published_at_start: 'NOW-2DAYS' }
  end

  def run
    # If you replace this comment with a debugger, the value of list is nil
    list += _some_method(options)
    return list
  end

  private

  def _some_method(options)
    [options[:published_at_start], 1, 2, 3, 4, options[:published_at_end]]
  end
end

If you copy/paste that into irb, then run:

*

*t = Thing.new

*t.run
It will output this error:
NoMethodError: undefined method `+' for nil:NilClass

If you remove the += line (leaving just the return line), it returns []... So from what I can tell, it's just the presence of += that sets list to nil.
I also find it interesting that it's value is nil in the line before the += call (see my comment in the code example).
Alternatively, if you use << with flatten instead, you'll get the expected result:
class Thing
  attr_accessor :options, :list

  def initialize
    @list    = []
    @options = { published_at_end: 'NOW', published_at_start: 'NOW-2DAYS' }
  end

  def run
    list << _some_method(options)
    list.flatten
  end

  private

  def _some_method(options)
    [options[:published_at_start], 1, 2, 3, 4, options[:published_at_end]]
  end
end

If you copy/paste that into irb, then run:

*

*t = Thing.new

*t.run
It will output ['NOW-2DAYS', 1, 2, 3, 4, 'NOW'].

Why does += reset the value of list to nil?
Additionally, how does it set its value to nil prior to += being called?
Semi-related / helpful side note - I'm going to use shovel (<<) with flatten because of performance reasons, but I'm still interested why the variable gets reset to nil.

A: list += [1, 2, 3] is equivalent to:
list = list + [1, 2, 3]

Because this is an assignment, Ruby creates a new local variable list, shadowing your list method. From the documentation:

When using method assignment you must always have a receiver. If you do not have a receiver, Ruby assumes you are assigning to a local variable

More specifically, the local variable list is created when the parser encounters list =. Like uninitialized instance variables and global variables, it has a value of nil. Attempting to evaluate the assignment's right-hand side list + [1, 2, 3] therefore fails, because it is equivalent to:
nil + [1, 2, 3]
# NoMethodError: undefined method `+' for nil:NilClass

So to get the expected result, you have to provide an explicit receiver:
self.list += [1, 2, 3]

Or directly assign to the instance variable:
@list += [1, 2, 3]

Or use a method that modifies the receiver:
list.concat [1, 2, 3]

A: I believe list += _some_method(options) is internally compiling into list = list + _some_method(options). Despite the existence of a list method, Ruby interprets list = :anything as defining a new local variable called list, overriding the interpretation of list within the scope of the method call. When Ruby mistakenly jumps to the 'local variable' conclusion, it has to be told with self.. This is why switching to self.list += _some_method(options) works.
class Thing
    def foo; 'BAR'; end
    def baz; foo = 'ODD'; foo; end
end

Thing.new.foo #=> "BAR"
Thing.new.baz #=> "ODD"

But I agree using list << followed by a flatten(1) is still more efficient.


text:
Q: How to use the ffmpeg library to transpose a video? I'm trying to develop an video recorder and playback app in Android. So, I'm using the ffmpeg library and I've compiled the library to use in the project.
I record a video and when I playback, in some devices don't recognize the orientation matrix, so I want to develop with the ffmpeg library a C method to do this order:
ffmpeg -i f.mp4 -vf "transpose=1" -r 24 -sameq f2.mp4"
I found this documentation but don't help me, because don't use the AVFilter and AVFilterContext classes.
http://dranger.com/ffmpeg/tutorial01.html
http://cekirdek.pardus.org.tr/~ismail/ffmpeg-docs/structAVFilterContext.html
http://ffmpeg.org/doxygen/trunk/api-example_8c-source.html
Now I only have the opening and closing video file
Here my code:
/*open the video file*/
if ((lError = av_open_input_file(&gFormatCtx, gFileName, NULL, 0, NULL)) !=0 ) {
    LOGE(1, "Error open video file: %d", lError);
    return; //open file failed
}
/*retrieve stream information*/
if ((lError = av_find_stream_info(gFormatCtx)) < 0) {
    LOGE(1, "Error find stream information: %d", lError);
    return;
}
/*find the video stream and its decoder*/
gVideoStreamIndex = av_find_best_stream(gFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &lVideoCodec, 0);
if (gVideoStreamIndex == AVERROR_STREAM_NOT_FOUND) {
    LOGE(1, "Error: cannot find a video stream");
    return;
} else {
LOGI(10, "video codec: %s", lVideoCodec->name);
}
if (gVideoStreamIndex == AVERROR_DECODER_NOT_FOUND) {
    LOGE(1, "Error: video stream found, but no decoder is found!");
    return;
}
/*open the codec*/
gVideoCodecCtx = gFormatCtx->streams[gVideoStreamIndex]->codec;
LOGI(10, "open codec: (%d, %d)", gVideoCodecCtx->height, gVideoCodecCtx->width);
#ifdef SELECTIVE_DECODING
gVideoCodecCtx->allow_selective_decoding = 1;
#endif
if (avcodec_open(gVideoCodecCtx, lVideoCodec) < 0) {
LOGE(1, "Error: cannot open the video codec!");
    return;
}
LOGI(10, "get video info ends");

How can I transpose the video using the ffmpeg library?

A: How to Using FFmpeg decode Customer I/O
AVCodec *pCodec;
avcodec_register_all();
// Register all formats and codecs
av_register_all();

//av_init_packet(&packet);
if(avformat_network_init()!=0){
    goto initError; // Couldn't init new work
}
// Open video file

pFormatCtx = avformat_alloc_context();
printf("==========>>%p %lu\n", buff,sizeof(buff));
pFormatCtx->pb=av_malloc(buff_size);//pFormatCtx->pb=av_alloc_put_byte(buff,buff_size,0,NULL,NULL,NULL,NULL);
pFormatCtx->pb=avio_alloc_context(buff,buff_size,0,NULL,NULL,NULL,NULL);

pFormatCtx->iformat=av_find_input_format("h264");
pFormatCtx->flags = AVFMT_FLAG_CUSTOM_IO;
pFormatCtx->iformat->flags=AVFMT_NOFILE;

// Retrieve stream information
 if(avformat_find_stream_info(pFormatCtx,NULL)<0){
        goto initError; // Couldn't find stream information
}
 streamNo=-1;
// Find the first video stream
if ((streamNo =  av_find_best_stream(pFormatCtx,AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, 0)) < 0)
{
    av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file %d\n",streamNo);
    goto initError;
}

While i'm Can't Find Stream from My Buffer  the streamNo allway is -1381258232
my Buffer is void* buff int buff_size


text:
Q: Communication, Classes and ActionListener I am new to java and I was wondering if anyone could help me
I have three panels (myJPanel, myJPanel1, myJPanel2),where myJPanel1 will display the student's name myJPanel2 will display my method. For my assignment I can only make one change in my line of code in myJPanel and there will be many changes in myJPanel2.
I know that for the one line of code I have to change in myJPanel, I have to be able to pass p1 to the class where I will be modifying most of my code. Which I am unsure of how to do. I was given a hint I just need to add two letters to this line of code and it will work and I have tried multiple times and failed.
I figure if I can figure out how to do that, I can get the ActionListener to work in myJPanel2
Here is my code so far (I know there are a lot of comments, but those are just notes to help myself with the code).
myJPanel
import java.awt.*;
import javax.swing.*;

public class myJPanel extends JPanel
{
    public myJPanel()
    {
        super();
        setBackground(Color.gray);

        setLayout(new BorderLayout());

        myJPanel1 p1 = new myJPanel1();
        myJPanel2 p2 = new myJPanel2();
        //change above line(add two letters)
        //Constructor is gateway for passing information into another class
        //When passing in a value, you have access in the constructor

        add(p1,"North");
        add(p2,"Center");

    }
}

myJPanel2
 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 import java.awt.event.ActionEvent;

 public abstract class myJPanel2 extends JPanel implements ActionListener
 {
    //Modify button on myJPanel1 and capture buttons that has been pressed
    //Have to modify myJPanel to access fields and attributes that need access
    //From myJPanel2 makes changes so listen to button events on myJPanel1
    //Get access to button on myJPanel1, set it equal to student

    JButton b2;
    JButton b1;
    student st1;

    public myJPanel2()
    {
        super();
        st1 = new student("Fred","Fonseca",44);
        setBackground(Color.pink);
        b2 = new JButton("whats Up will be shown here" );
        add(b2);

        b1.addActionListener(this);
    }

    public void actionPerformed(ActionListener event)
    {
        Object obj = event.getSource();
        if(obj == b1)
        {
            b2.setText(st1.whatsUp());
        }
    }

}


text:
Q: Integral Measures: Identification Problem
Given a Borel space $\Omega$.
Consider a Borel measure:
$$\mu:\mathcal{B}(\Omega)\to\overline{\mathbb{R}}:\quad\mu\geq0$$
Regard a Borel measure:
$$\rho\geq0:\quad\mu_\rho(A):=\int_A\rho\,\mathrm{d}\mu$$
Denote its Borel support:
$$\sigma_\rho:=\left({\bigcup}_{U\in\mathcal{T}(\Omega):\mu_{\rho}(U)=0}U\right)^\complement$$

Then isometrically:
  $$\mathcal{L}(\sigma_\rho;\mu_\rho)\cong\mathcal{L}(\sigma_\rho;\mu)$$

How can I prove this?
Attempt
Define the map:
$$U_\rho:\mathcal{L}(\sigma_\rho;\mu_\rho)\to\mathcal{L}(\sigma_\rho;\mu):\eta\mapsto\eta\rho$$
It is isometric since:
$$\|U_\rho\eta\|=\int|\omega|\rho\mathrm{d}\mu=\int|\omega|\mathrm{d}\mu_\rho=\|\eta\|$$
So also well-defined:
$$\|\omega\|=0\implies\|U_\rho\omega\|=0$$
But why surjective?

A: The assertion is wrong:
Given the interval $[-1,1]$.
Consider the Borel measure:
$$\mu:\mathcal{B}([-1,1])\to\overline{\mathbb{R}}:\quad\mu:=\lambda+\delta$$
Regard the Borel measure:
$$\rho:=1-1_{\{0\}}:\quad\mu_\rho(A):=\int_{[-1,1]}\rho\,\mathrm{d}\mu=\lambda$$
It has Borel support:
$$\sigma_\rho=\sigma(\lambda)=[-1,1]$$
But it is not surjective:
$$\vartheta:=1_{\{0\}}:\quad\vartheta\notin\mathcal{R}U_\rho$$
Concluding counterexample.


text:
Q: ScrollTop is not working in Chrome and Firefox I try to scroll the div of a chat down with JavaScript to the newest message when the user opens the chat, sends or receives a message. For this I tried to use ScrollTop like recommended in many google search results. I made the div element as a global object because I want to use the line with ScrollTop several times in the script. The chatdiv is set to 'overflow-y: scroll;'.
I verified with an alert output in the browser console that the window.onload function is working.
<script type="text/javascript">
var element_label = document.getElementById("chatdiv");

window.onload = function WindowLoad(event) {
    element_label.scrollTop = element_label.scrollHeight;
}
</script>

My next try was to get the newest message object and use ScrollIntoView on it. This also did not work.
<script type="text/javascript">
var element_label = document.getElementById("chatdiv");
var last_mess = document.getElementById("chatdiv").lastChild;

window.onload = function WindowLoad(event) {
    last_mess.scrollIntoView();
}
</script>

Am I missing a significant point or is it no longer possible to scroll a div with JavaScript?
Thanks in advance!


text:
Q: What does it mean const type& method What does it mean when const is a part of the method type
const std::string& getName();

and when const is at the end of the method
const std::string& getName() const;

Thanks a lot.

A: It means that the definition of that function cannot modify the structure/class it is part of (i.e. it cannot mutate instance variables).
struct MyStruct
{
    int i ;
    void go1 ()
    {
        i = 5 ;
    }
    void go2 () const
    {
        i = 5 ; // error: 'this' is const
    }
} ;


text:
Q: Why no default clone() in Cloneable in Java 8 Cloneable in Java is inherently broken. Specifically, my biggest problem with the interface is it expects a method behavior that doesn't define the method itself. So if traversing through a Cloneable list you must use reflection to access its defined behavior. However, in Java 8, we now have default methods and now I ask why there isn't a default clone() method in Cloneable.
I understand why interfaces cannot default Object methods, however, this was an explicit design decision and so exceptions can be made.
I sort of envision deprecating Object.clone() and changing its interior code to something like:
if(this instanceof Cloneable) {
    return ((Cloneable) this).clone();
}
else {
    throw new CloneNotSupportedException();
}

And moving on whatever magic makes clone() do its thing as a default method in Cloneable. This doesn't really fix that clone() can still easily be implemented incorrectly, but that's another discussion in of itself.
As far as I can still this change would be completely backwards compatible:

*

*Classes that currently override clone() but didn't implement Cloneable (WHY?!) would still be technically okay (even if functionally impossible, but this is no different then it was before).

*Classes that currently override clone(), but did implement Cloneable would still function the same on its implementation.

*Classes that don't currently override clone(), but did implement Cloneable (WHY?!) would now follow a specification, even if it's not completely functionally correct.

*Those that used reflection and referred to Object.clone() would still functionally work.

*super.clone() would still be functionally the same even if it's referencing Object.clone().

Not to mention this would solve a huge problem that Cloneable is. While tedious and still easy to implement incorrectly, it would solve a huge object oriented problem with the interface.
The only problem I can see with this is those that implement Cloneable aren't obligated to override clone(), but this is no different than it was before.
Has this been discussed internally, but never came to fruition? If so, why? If it's for the reason that interfaces cannot default Object methods, wouldn't it make sense to make an exception in this case since all objects inheriting Cloneable are expecting clone() anyway?

A: Your question is somewhat broad and more of a discussion, but I can shed some light on this matter.
In Effective Java™, Joshua Bloch gives quite the rundown on the situation. He opens with a bit of history behind Cloneable

The Cloneable interface was intended as a mixin interface for objects to
  advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks a clone method, and Object's clone method is protected. You cannot, without resorting to reflection, invoke the clone method on an object merely because it implements Cloneable.

and continues with the reasoning

[Cloneable] determines the behavior of Object's protected clone implementation: if a class implements Cloneable, Object's clone method returns a field-by-field copy of the object... This is a highly atypical use of interfaces and not one to be emulated. Normally, implementing an interface says something about what a class can do for its clients. In the case of Cloneable, it modifies the behavior of a protected method on a superclass.

and

If implementing the Cloneable interface is to have any effect on a class, the
  class and all of its superclasses must obey a fairly complex, unenforceable, and
  thinly documented protocol. The resulting mechanism is extralinguistic: it creates an object without calling a constructor.

There are a lot of details that go into this, but to note just one problem:

The clone architecture is incompatible with normal use of final fields referring to mutable objects.

I think this is enough to reason against having a default method in the interface do the cloning. It would be extremely complicated to implement it correctly.

A: My experience is probably far from being mainstream, but I use clone() and support the current design of Cloneable. Probably it would be better to have it as annotation instead, but Cloneable appeared long before the annotations. My opinion is that Cloneable is a low-level thing and nobody should do something like obj instanceof Cloneable. If you are using Cloneable in some business-logic, it's much better to declare your own interface or abstract class which exposes clone() to public and implement it in all of your business-logic objects. Sometimes you will probably want not to expose clone() actually, but create your own method which uses clone() internally.
For example, consider that you have an hierarchy of named objects where name cannot be changed after construction, but you want to allow cloning them with new name. You can create some abstract class like this:
public abstract class NamedObject implements Cloneable {
    private String name;

    protected NamedObject(String name) {
        this.name = name;
    }

    public final String getName() {
        return name;
    }

    public NamedObject clone(String newName) {
        try {
            NamedObject clone = (NamedObject)super.clone();
            clone.name = newName;
            return clone;
        }
        catch(CloneNotSupportedException ex) {
            throw new AssertionError();
        }
    }
}

Here even though you implement Cloneable, you want to use clone(), but don't want to expose it publicly. Instead you provide another method which allows to clone with another name. So having public clone() in Cloneable would unnecessarily pollute the public interface of your classes.
Another case where I use Cloneable is the implementation of Spliterator.trySplit(). See the implementation of simple spliterator which returns given number of constant objects. It has four specializations (for Objects, ints, longs and doubles), but thanks to clone() I can implement trySplit() only once in the superclass. Again, I don't want to expose clone(), I just want to use it by myself.
So to conclude, not having clone() method in Cloneable interface is actually more flexible as it allows me to decide whether I want to have it public or not.


text:
Q: Perl script to add newline to end of textfile I have tried to make a perl script add a newline to the end of a text file and then write in the following:
/bin/false
The file looks like this:

/bin/sh
  /bin/dash
  /bin/bash
  /bin/rbash
  /usr/bin/tmux
  /usr/bin/screen

I have tried running the following script:

perl -pi -e 's///usr//bin//screen///usr//bin//screen"\n"//bin//false/g' /etc/shells

But without any luck. It does not accept the newline and just returns an error for the syntax. Can you help!?

A: This:
s///usr//bin//screen///usr//bin//screen"\n"//bin//false/g

Indeed has  syntax errors. Starting from  the fact that you  used double
bars on  the path, where you  should have escaped them  (\/), and also
the strange newline string in the middle of it. You could also use other
delimiters rather than forward slash, to avoid having to escape all.
s!/usr/bin/screen\n!/usr/bin/screen\n/bin/false!

Also, don't forget  to close your last  line. And you can  also use \K
(see perldoc perlre for details) to  simplify your regex, with a final
result of:
s!/usr/bin/screen\n\K!/bin/false\n!

But anyway, this  seems to be overkill. You can  use your shell features
to echo a line and redirect to a file, by appending with >>:
echo /bin/false >> /etc/shells


text:
Q: Page source not keeping up with updates made to the page by Selenium I'm using the following code to scrape a web page:
import scrapy
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException

class JornaleconomicoSpider(scrapy.Spider):
    name = 'jornaleconomico'
    allowed_domains = ['jornaleconomico.pt']
    start_urls = ['https://jornaleconomico.pt/categoria/economia']

    def parse(self, response):
        options = Options()
        driver_path = '###' #Your Chrome Webdriver Path
        browser_path = '###' #Your Google Chrome Path
        options.binary_location = browser_path
        options.add_experimental_option("detach", True)

        self.driver = webdriver.Chrome(options=options, executable_path=driver_path)
        self.driver.get(response.url)

        ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
        wait = WebDriverWait(self.driver, 120, ignored_exceptions=ignored_exceptions)

        self.new_src = None
        self.new_response = None

        i=0

        while i<10:
            # click next link
            try:
                element = wait.until(EC.element_to_be_clickable((By.XPATH, '*//div[@class="je-btn je-btn-more"]')))
                self.driver.execute_script("arguments[0].click();", element)
                self.new_src = self.driver.page_source
                self.new_response = response.replace(body=self.new_src)
                i += 1
            except TimeoutException:
                self.logger.info('No more pages to load.')
                self.driver.quit()
                break

        # grab the data
        headlines = self.new_response.xpath('*//h1[@class="je-post-title"]/a/text()').extract()

        for headline in headlines:
            yield {
            'text': headline
        }

The code above is supposed to click 10 times on Ver mais artigos (See More Articles) and get the text from all the headlines, but it's getting only the first original nine headlines. I checked the page source code on Chrome Selenium (using the options.add_experimental_option("detach", True) line to freeze the Selenium window), and I figured out that the page source is the same as the original page, before the clicks. For me, this shouldn't be happening, since in that same Selenium window I can correctly inspect all articles, not just the first nine, and even using WebDriveWait is not preventing this from happening. How to solve this?

A: You don't actually need to use Selenium for this very-easy-to-fetch website. Here is what I would do if I need data from there.

Testing with postman

POST https://domain.pt/wp-admin/admin-ajax.php
content-type: application/x-www-form-urlencoded; charset=UTF-8
pragma: no-cache
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36
x-requested-with: XMLHttpRequest

action=je_pagination&nonce=f2e925cd72&je_offset=9&je_term=economia

First 9 records of the blog are printed with the link and pagination can be done using above postman sample, just change the 'je_offset' to [9,18,27,etc] and updating the 'nonce'.
Every time you load the page, you need to get new 'nonce' from html.
This is what the website shows on every page, try using re.search to get 'ajax_nonce' value.
<script type='text/javascript' id='je-main-js-extra'>
/* <![CDATA[ */
var ajax_object = {"ajax_url":"https:\/\/domain.pt\/wp-admin\/admin-ajax.php","ajax_nonce":"f2e925cd72"};
/* ]]> */
</script>

Try load the page using requests.get and paginate using requests.post - this should make your job super easy and much faster than selenium.

A: Here is the (almost) complete solution:
from json import loads, dumps
from requests import get, post
from lxml.html import fromstring
from re import search, sub, findall

headerz = {
    "accept": "application/json, text/javascript, */*; q=0.01",
    "accept-language": "en-US,en;q=0.9",
    "sec-ch-ua": "'Chromium';v='106', 'Google Chrome';v='106', 'Not;A=Brand';v='99'",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "'Linux'",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest"
}

url = "https://jornaleconomico.pt/categoria/economia"
pag_href = "https://jornaleconomico.pt/wp-admin/admin-ajax.php"
page_count = 0

r = get(url)
html = fromstring(r.content.decode())

rawnonce = html.xpath("//script[@id='je-main-js-extra']/text()")

# print first 9 records
for p in html.xpath("//div[contains(@class,'je-posts-container')]//h1[contains(@class,'je-post-title')]/a"):
    ptitle = p.xpath("./text()")
    if isinstance(ptitle, list):
        post_title = ptitle[0]
        post_href = p.xpath("./@href")[0]
        print (post_href)

# pagination
while True:
    page_count += 9
    pag_params = {
        "action":"je_pagination",
        "nonce": "",
        "je_offset": page_count,
        "je_term": "economia"
    }
    r = post(pag_href, headers=headerz, data=pag_params)
    jdata = r.json()
    if (jdata and 'data' in jdata):
        jdata = jdata['data']['posts']
        html = fromstring(jdata)
        for p in html.xpath("//h1[contains(@class,'je-post-title')]/a"):
            ptitle = p.xpath("./text()")
            if isinstance(ptitle, list):
                post_title = ptitle[0]
                post_href = p.xpath("./@href")[0]
                print (post_href)
    else:
        break

The output looks like:
https://jornaleconomico.pt/noticias/ministro-das-financas-diz-que-o-governo-esta-a-acompanhar-de-forma-atenta-inflacao-dos-produtos-alimentares-989146
https://jornaleconomico.pt/noticias/bancos-amortizam-antecipadamente-pagamento-dos-ltro-ao-bce-no-valor-de-16-mil-milhoes-989098
https://jornaleconomico.pt/noticias/je-podcast-ouca-aqui-as-noticias-mais-importantes-desta-terca-feira-51-988633
https://jornaleconomico.pt/noticias/prestacao-da-casa-sobe-quase-200-euros-para-creditos-de-150-mil-euros-a-6-meses-989134
https://jornaleconomico.pt/noticias/portugal-2020-atinge-85-de-execucao-e-116-de-compromisso-ate-dezembro-989132
https://jornaleconomico.pt/noticias/crescimento-do-pib-de-67-da-mais-confianca-para-desempenho-de-2023-diz-fernando-medina-989124
https://jornaleconomico.pt/noticias/apesar-dos-reforcos-salario-minimo-portugues-continua-a-meio-da-tabela-na-europa-988979
https://jornaleconomico.pt/noticias/atividade-turistica-dormidas-aumentaram-863-face-a-2021-988958
https://jornaleconomico.pt/noticias/producao-industrial-cresceu-25-em-dezembro-988947
https://jornaleconomico.pt/noticias/pib-cresce-36-na-ue-e-35-na-zona-euro-988921
https://jornaleconomico.pt/noticias/fundo-soberano-da-noruega-regista-maiores-perdas-desde-2008-988905
https://jornaleconomico.pt/noticias/economia-do-reino-unido-e-a-unica-do-g7-com-perspectivas-de-crescimento-negativo-988900
https://jornaleconomico.pt/noticias/economia-portuguesa-cresceu-67-em-2022-988868
https://jornaleconomico.pt/noticias/revista-de-imprensa-nacional-as-noticias-que-estao-a-marcar-esta-terca-feira-48-988814
https://jornaleconomico.pt/noticias/economia-chinesa-com-fortes-perspetivas-de-crescimento-988855
https://jornaleconomico.pt/noticias/fmi-reve-em-alta-as-previsoes-globais-de-crescimento-global-para-2023-e-agradece-a-china-988823
https://jornaleconomico.pt/noticias/alemanha-vendas-a-retalho-registam-a-maior-queda-desde-abril-de-2021-988817
https://jornaleconomico.pt/noticias/je-bom-dia-ine-divulga-dados-sobre-a-inflacao-e-a-economia-988416
https://jornaleconomico.pt/noticias/economia-francesa-cresce-26-em-2022-988767
https://jornaleconomico.pt/noticias/topo-da-agenda-o-que-nao-pode-perder-nos-mercados-e-na-economia-esta-terca-feira-31-988687
https://jornaleconomico.pt/noticias/auditoria-da-igf-ao-sifide-deteta-319-milhoes-de-euros-em-credito-fiscal-indevido-988699
https://jornaleconomico.pt/noticias/ministerio-das-infraestruturas-esta-a-acompanhar-subida-de-precos-das-operadoras-988697
https://jornaleconomico.pt/noticias/economistas-preveem-crescimento-do-pib-entre-66-e-68-em-2022-988681
https://jornaleconomico.pt/noticias/queda-do-pib-em-cadeia-na-alemanha-faz-soar-alarmes-de-recessao-na-zona-euro-de-novo-988583
https://jornaleconomico.pt/noticias/je-podcast-ouca-aqui-as-noticias-mais-importantes-desta-segunda-feira-49-988067
https://jornaleconomico.pt/noticias/jmj-investimentos-da-igreja-do-governo-e-dos-municipios-somam-pelo-menos-155-milhoes-de-euros-988637
https://jornaleconomico.pt/noticias/da-energia-europeia-a-economia-chinesa-veja-as-escolhas-da-semana-no-mercados-em-acao-988544
https://jornaleconomico.pt/noticias/riscos-de-uma-nova-moeda-comum-para-brasil-e-argentina-ouca-o-podcast-atlantic-connection-988395
https://jornaleconomico.pt/noticias/sindicatos-reunem-se-hoje-com-governo-para-tentar-evitar-greve-na-cp-e-ip-988622
https://jornaleconomico.pt/noticias/fundo-europeu-para-os-media-e-informacao-abre-novos-concursos-988564
https://jornaleconomico.pt/noticias/pt2020-portugal-entre-paises-que-mais-executam-fundos-europeus-988590
https://jornaleconomico.pt/noticias/maiores-bancos-espanhois-preparam-se-para-contestar-taxa-sobre-lucros-caidos-do-ceu-988545


text:
Q: Function that stores one for ever number that is not zero in a vector How can I write a function that changes any value not zero to 1?
My current approach:
> numbersGreaterZeroAreOne(c(0.001, 0, 1, 2, 3, 4))
[1] 1 0 1 1 1 1

and my implementation:
numbersGreaterZeroAreOne <- function(x) {
    x <- x/x
    x[is.na(x)] <- 0
    return(x)
}

However, I think my function works, but I don't quite like it, it seems unnatural to use devision through zero and NaN values.

A: You can use vector assignment [<- and the logical operator !=
> x <- c(0.001, 0, 1, 2, 3, 4)
> f <- function(x) { x[x != 0] <- 1; x }
> f(x)
# [1] 1 0 1 1 1 1

Or you could do a little trickery
> g <- function(x) { as.logical(x)+0 }
> g(x)
# [1] 1 0 1 1 1 1

The latter seems to be quite a bit faster
> library(microbenchmark)
> microbenchmark(f(x), g(x))
# Unit: nanoseconds
#  expr  min     lq median     uq   max neval
#  f(x) 2320 2642.5 2757.5 2864.0 24662   100
#  g(x)  955 1080.0 1408.0 1487.5 12219   100


text:
Q: How do I have a nested formik form or form field that generates a list without creating additional fields? For example, if I want to create a user signup form that also has a field to add pets, which generates a bullet point list of pets that you can delete from, how would I do that with formik? Is there a correct approach for the example image below where I can add and delete pets in that way without having a form field for each pet and upon clicking submit it submits a name field along with an array of pet names?

A: you can do it with FieldArray of Formik


text:
Q: How to represent uncertainty on the support of a (uniform) distribution? I want to represent a situation where a Bayesian agent believes that a certain quantity is uniformly distributed over an interval $[\underline{X},\overline{X}]$ but is uncertain on the value of $\underline{X}$ and $\overline{X}$. In other words, $\underline{X},\overline{X}$ are random variables and she might receive informative signals about them. In this sense, the agents' uncertainty is double layered, pertaining not only the value of the quantity, but also the distribution it follows.
My problem is how to represent such a situation, in the sense that I consider adopting a Bayesian Hierarchical Model where $\underline{X}\sim\mathcal{N}(\underline{x},1)$, $\overline{X}\sim\mathcal{N}(\overline{x},1)$, but I don't know how to introduce dependency between $\underline{X}$ and $\overline{X}$ so that
$$\mathbb{P}(\underline{X}<\overline{X})=1$$
which is the condition ensuring that $\underline{X}$ and $\overline{X}$ almost surely define an interval.
I thought that random set theory (https://link.springer.com/book/10.1007/1-84628-150-4) might help here, but, in that field I am even less experienced than in Bayesian statistics.
Any help or reference would be much appreciated.


text:
Q: Why does my accordion list keep closing? I've created a side menu that contains accordion list. When I load the page, the accordion list has one section open because it's coded to be active on page load. However if I attempt to open another section... it opens the section but then closes straight away. Can someone tell me where I'm going wrong?
List code:
<ion-content class="has-header" id="accordian"scroll="false" ng-controller="MainCtrl">

Group 1

{{ card.title }}

Group 2

{{ card.title }}

Group 3

{{ card.title }}

JS:
$(document).ready(function(){
  $("#accordian h3").click(function(){
    //slide up all the link lists
    $("#accordian ul ul").slideUp();
    //slide down the link list below the h3 clicked - only if its closed
    if(!$(this).next().is(":visible"))
    {
      $(this).next().slideDown();
    }
  })
})

A: You must wait until the execution of the slideUp function is completed (by default the duration is 400ms) before you test if the next element is visible or not.
$(document).ready(function(){
  $("#accordian h3").click(function(){
    //slide up all the link lists
    $("#accordian ul ul").slideUp();
    //slide down the link list below the h3 clicked - only if its closed
      var $elemH3 = $(this);
      setTimeout(function() {
          if(!$elemH3.next().is(":visible"))
          {
              $elemH3.next().slideDown();
          }
      }, 401);

  })
})

You can use some CSS to do this easily see this example : http://jsfiddle.net/nx2LkoLd/
You hide all sections but not the active one :
css code
li.active ul {
    display:block;
}
li ul {
    display: none;
}

The js and html code still the same.
Hope it's clear and will help you resolve your problem.

A: Default position of accordion is collapsed... put this on the begining of your $(document).ready to expand it.
$('#accordian').collapse({toggle: true});

EDIT:
In your case:
$(document).ready(function(){
    $('#accordian').collapse({toggle: true});

});

Or... if you want your accordion expands independent of the ready event you can put this line anywhere in your js file (except inside another function):
$(function () { $('#accordian').collapse({toggle: true}); });

Both will work, but I'm not sure if your own functions are working, so be careful. I'm sorry, no time to test. ;)


text:
Q: Unable to query postgress sql from python I am trying to extract the data from Postgress DB, I am using the below code to get the data and it's working for those query which returns results within a second but not working when execution time > 4 sec
connection = psycopg2.connect('connection string')
cursor = connection.cursor()
postgreSQL_select_Query = """ SLECT * FROM TABLEA """
cursor.execute(postgreSQL_select_Query)

It is throwing the below error for big query

('Error while fetching data from PostgreSQL', OperationalError('TEIID30504 nz_security_src: TEIID11009 java.sql.SQLException: javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener@14b492f7[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection@49b199 connection handles=0 lastUse=1581690750049 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool@7ad42622 pool internal context=SemaphoreArrayListManagedConnectionPool@62c5cfd8[pool=source] xaResource=LocalXAResourceImpl@7528aaf6[connectionListener=14b492f7 connectionManager=6b1b6361 warned=false currentXid=null productName=Netezza NPS productVersion=Release 7.2.0.5-P2 [Build 45588] jndiName=java:/source] txSync=null]\nDETAIL:  org.teiid.jdbc.TeiidSQLException: TEIID30504 nz_security_src: TEIID11009 java.sql.SQLException: javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener@14b492f7[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection@49b199 connection handles=0 lastUse=1581690750049 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool@7ad42622 pool internal context=SemaphoreArrayListManagedConnectionPool@62c5cfd8[pool=source] xaResource=LocalXAResourceImpl@7528aaf6[connectionListener=14b492f7 connectionManager=6b1b6361 warned=false currentXid=null productName=Netezza NPS productVersion=Release 7.2.0.5-P2 [Build 45588] jndiName=java:/source] txSync=null]\n',))


text:
Q: How do I alert XML file in jQuery This is a login api in which I am trying to send an xml document but it is showing an error. After removing <? this, it is not showing error but I need to send with it. Can anyone help me to send the whole xml with any other type or method?
<script>
    $(document).ready(function(){

        var xmldata='<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelopexmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><login xmlns="urn:partner.soap.sforce.com"><username>ddd@c.in</username><password>Year#2018@2018</password></login></soapenv:Body></soapenv:Envelope>';
        alert(xmldata);
        $.ajax({
            url: 'url',
            type: 'POST',
            headers: {
               'Content-Type': "text/xml",
               'SOAPAction': "",
            } ,
            dataType: 'xml',
            contentType: "text/xml",
            data: {xml:xmldata},
            success: function (data, textStatus, xhr) {
                console.log(data);
            },
            error: function (data, errorThrown) {
               console.log(data);
            }
        });
    });
</script>

Also I am getting a cross domain error in this code. How can I send the SOAP data?

A: Use:

$(document).ready(function(){
var xmldata='<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelopexmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><login xmlns="urn:partner.soap.sforce.com"><username>ddd@c.in</username><password>Year#2018@2018</password></login></soapenv:Body></soapenv:Envelope>';
alert(xmldata);
$.ajax({
    url: 'url',
    type: 'POST',
    headers: {
       'Content-Type': "text/xml",
       'SOAPAction': "",
    } ,
    dataType: 'xml',
    contentType: "text/xml",
    data: {xml:xmldata},
    success: function (data, textStatus, xhr) {
        console.log(data);
    },
    error: function (data, errorThrown) {
       console.log(data);
    }
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Add the jQuery library (which you can google or see the snippet) before the script runs.
I think your problem about not getting the whole XML content will be solved.

A: Try the following.
In Internet Explorer:
xmlObject.xml

Other browsers:
(new XMLSerializer()).serializeToString(xmlObject)


text:
Q: Multiple hops SSH tunnel I need to open an ssh tunnel through to an oracle database port...after much fluffing around I cant seem to get it to work.
Here is the scenario...
My Machine --> host1 --> host2 --> oracle_instance(host3)...
So i need to be able to go through host1 which knows about host2...then from host2 to the oracle_instance on host3.
This is in order to connect up my sql developer.
Therefore I should be able telnet to the local port on my machine which will in effect be forwarding traffic from the oracle_instance port...
Any help much appreciated...

A: Add a stanza to ~/.ssh/config:
Host oracletunnel
    ProxyCommand ssh host1user@host1 nc host2 22

Then use ssh host2user@oracletunnel -L <port>:host3:<port>.


text:
Q: All Stack Exchange emails come from Stack Overflow When I get an email about an inbox notification on any Stack Exchange site it comes from
"Stack Overflow <do-not-reply@stackoverflow.email>"
And I think they should at least change the name displayed on the front of the email if not the email address itself to stackexchange.email.
Also, I think they should remove the link at the top of all SE notifications which links to Stack Overflow and change it to link to Stack Exchange instead.


text:
Q: Landscaping a page I am trying to landscape a specific page of my document and used pdflscape package and landscape environment to do so. The page does turn into landscape mode, however, the texts are not (as shown in the figure).

What does make the page to be like that?
Here I add the main.tex file and try.sty file of my document.
\documentclass[oneside,12pt,a4paper,fleqn]{book}
\usepackage{try}

\begin{document}
\frontmatter
\mainmatter
   \input{CompleteGraph.tex}
\backmatter
\end{document}

This is the try.sty file.
% LaTeX cod for chapter header
%--------------------------------------------------------
\makeatletter
\def\@makechapterhead#1{
  %\vspace*{20\p@}   %  \vspace*{15\p@}
  {\parindent \z@
      \centering
    \normalfont
    \ifnum \c@secnumdepth >\m@ne
      \if@mainmatter
      \normalsize
           \bfseries \@chapapp\space \thechapter
       \par\nobreak
              \vskip 1.4\baselineskip
      \fi
    \fi
    \interlinepenalty\@M
    \normalsize
         \bfseries #1\par\nobreak
       \vskip 1.4\baselineskip %
  }}
\def\@schapter#1{\if@twocolumn
                   \@topnewpage[\@makeschapterhead{#1}]%
                 \else
                   \@makeschapterhead{#1}
                   \@afterheading
                 \fi}
\def\@makeschapterhead#1{
  %\vspace*{20\p@} % \vspace*{20\p@} %
  {\parindent \z@
    \centering
    \normalfont
    \interlinepenalty\@M
    \normalsize
    \bfseries  #1\par\nobreak
         \vskip 1.4\baselineskip
  }}
\makeatother
\renewcommand{\chaptername}{CHAPTER}
%------------------------------------------------------------
% Commands for layout
   %\setlength{\topmargin}{-1.2cm}
   %\setlength{\oddsidemargin}{1.7cm}   %\setlength{\oddsidemargin}{1.46cm}
\setlength{\textwidth}{14.5cm}
   \setlength{\textheight}{24.5cm} %  \setlength{\textheight}{24.5cm}
   %\setlength{\headheight}{2mm}
    %\setlength{\headsep}{10.175mm}
%-------------------------------------------------------------
% Command for 1.5 spacing
   %\renewcommand{\baselinestretch}{1.5}
\usepackage{doublespace}
\setstretch{1.5}
%-------------------------------------------------------------
% Command for  indentation
   \setlength\parindent{.5in}
   \usepackage{indentfirst} %1st line indented after section...
%-------------------------------------------------------------
% Command for space between paragraph
  \makeatletter
    %\setlength{\parskip}{1.5\baselineskip \@plus 3ex
                %  \@minus 2.0ex}
    \setlength{\parskip}{2\baselineskip \@plus .01ex
                  \@minus .01ex}
   \makeatother
%-------------------------------------------------------------
% Commands for no hyphenation and right justified
    \hyphenpenalty=10000 \sloppy
    \raggedbottom
%-------------------------------------------------------------
% Command to get rid of default running head
   \pagestyle{myheadings}
%-------------------------------------------------------------
% Command for  page number
%  \makeatletter
%    \renewcommand{\ps@plain}{%
%    \renewcommand{\@oddhead}{\hfill\textrm{\thepage}}
%    \renewcommand{\@evenhead}{\@oddhead}
%    \renewcommand{\@evenfoot}{}
%    \renewcommand{\@oddfoot}{}  }
%   \makeatother
%-----------------------------------------------------------------

 %For section font
 % \usepackage{sectsty}
  %  \chapterfont{\centering\normalsize\uppercase}
  %  \sectionfont{\normalsize\uppercase}
   % \subsectionfont{\normalsize}
   % \subsubsectionfont{\itshape\normalsize}
%---------------------------------------------------------
%--------------------------------------------------------------
% Commands for REFERENCES name
\renewcommand{\bibname}{REFERENCES}
%--------------------------------------------------------------
% Commands to change vertical space in section and subsection
\makeatletter
\renewcommand{\section}{\@startsection
  {section}%      % the name
  {1}             % the level
  {0cm}           % the indent
  {1.0cm}         % the beforeskip
  {0.01cm}    %{0.5cm}    % the afterskip
  {\normalfont\normalsize\bfseries} } % the style
\renewcommand{\subsection}{\@startsection
  {subsection}%   % the name
  {2}             % the leve2
  {0cm}           % the indent
  {1.0cm}         % the beforeskip
  {0.01cm} %{0.5cm}        % the afterskip
  {\normalfont\normalsize\bfseries} } % the style
\makeatother
%--------------------------------------------------------------
% Commands to change horizontal space in section and subsection
% for times romans
   \renewcommand{\thesection} % space between sect. etc.
     {\thechapter.\arabic{section}\hspace{.12in}}
    \renewcommand{\thesubsection}
       {\thesection\hspace{-.3cm}.\arabic{subsection} \hspace{-.135cm}}
%--------------------------------------------------------------
% Commands for  TocLoFT
  \usepackage{tocloft}
    %\cftsetrmarg{2.75cm} %
     \cftsetrmarg{1.5cm} %
       \cftsetpnumwidth{1.25cm}
       %\cftsetpnumwidth{1.25cm}
    \renewcommand{\cftdot}{} % get rid of dots
%Table of Contents
\renewcommand{\contentsname}{}    % off tocname
\renewcommand{\cftchapfont}{\bfseries}
\renewcommand{\cftchappagefont}{\normalfont\bfseries}
\renewcommand{\cftchappresnum}{\hspace{0.3cm}CHAPTER }
%\setlength{\cftchapindent}{.8cm}      % chapter indent
\setlength{\cftsecindent}{2.3cm}      % section indent
\setlength{\cftsubsecindent}{3.25cm}  % subsection indent
\setlength{\cftchapnumwidth}{3.25cm}  % chp number width
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  \renewcommand{\cftchapafterpnum}{\rule{1.75ex}{0ex}}
%   \renewcommand{\cftsecafterpnum}{\rule{1.75ex}{0ex}}
%   \renewcommand{\cftsubsecafterpnum}{\rule{1.75ex}{0ex}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \renewcommand{\cftchapafterpnum}{\rule{0.75ex}{0ex}}
   \renewcommand{\cftsecafterpnum}{\rule{0.75ex}{0ex}}
   \renewcommand{\cftsubsecafterpnum}{\rule{0.75ex}{0ex}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   \renewcommand{\cftchappagefont}{\normalfont}
%-------------------------------------------------------------
%List of Table
\setlength{\cfttabnumwidth}{2.5cm}  %\setlength{\cfttabnumwidth}{2.5cm}
\renewcommand{\listtablename}{} % off lotname
%\setlength{\cfttabindent}{-.015cm}      % table indent %%%%%%%%%%%%%%%%%%
\setlength{\cfttabindent}{-.1cm}      % table indent %%%%%%%%%%%%%%%%%%
\renewcommand{\cfttabpresnum}{Table }
\renewcommand{\cfttabafterpnum}{\rule{2ex}{0ex}}
\cftsetrmarg{3cm}
%------------------------------------------------------------
 %List of Figure
\setlength{\cftfignumwidth}{2.5cm}
\renewcommand{\listfigurename}{} % off lofname
\setlength{\cftfigindent}{-.1cm}      % figure indent %%%%%%%%%%%%%%%%%%
\renewcommand{\cftfigpresnum}{Figure }
\renewcommand{\cftfigafterpnum}{\rule{2ex}{0ex}}
%-------------------------------------------------------------
%-------------------------------------------------------------
% Command for bold caption
\makeatletter
  \long\def\@makecaption#1#2{\vskip 10\p@   % caption parameter
       \setbox\@tempboxa\hbox{{ #1\,\,\,\,\,} #2} %%%%%
       \ifdim \wd\@tempboxa >\hsize         % caption parameter
           {#1\,\,\,\,\,}  #2\par  % caption parameter
       \else                                   % caption parameter
           \hbox to\hsize{\hfil\box\@tempboxa\hfil}  % caption parameter
   \fi}                                            % caption parameter
\makeatother
\renewcommand{\thefigure}{\arabic{chapter}.\arabic{figure}}
\renewcommand{\thetable}{\arabic{chapter}.\arabic{table}}
%--------------------------------------------------------------
\usepackage{paralist} %refine list item
%--------------------------------------------------------------
\usepackage{latexsym,amsmath,amssymb} % math symbols
%--------------------------------------------------------------
\usepackage{graphicx} % .eps graphic
%--------------------------------------------------------------
\usepackage{pdflscape} % for landscape
%--------------------------------------------------------------
\usepackage{times}
%--------------------------------------------------------------
% Theorem-Like-Environment
\usepackage{theorem}
{\theorembodyfont{\upshape}
\newtheorem{lemma}{Lemma}[chapter]
\newtheorem{theorem}{\rule{0ex}{5ex}Theorem}[chapter]
\newtheorem{corollary}{Corollary}[chapter]
\newtheorem{proposition}{Proposition}[chapter]
\newtheorem{definition}{\rule{0ex}{5ex}Definition}[chapter]
\newtheorem{example}{Example}[chapter] }
%--------------------------------------------------------
\newenvironment{proof}{\begin{paragraph}
          {Proof}\vspace{-1cm}}{\end{paragraph}}
\newenvironment{solution}{\begin{paragraph}
          {Solution}\vspace{-1cm}}{\end{paragraph}}

and the CompleteGraph.tex file is just simple as follows.
\begin{landscape}
$COM\rightarrow$ a set of combinations of $\textrm{C}^{n}_{m}$\\

$(x_0\textrm{ }x_1\textrm{ }\cdots\textrm{ }x_m)\in COM$ such $x_i=0,1,2,...,n-1$ for $i=0,1,2,...,m$\\

$\delta_j\rightarrow$ difference between two consecutive $x_i$\\

$\Delta(\delta_1\textrm{ }\delta_2\textrm{ }\cdots\textrm{ }\delta_{m-1})\rightarrow$ collection/sequence of differences $\delta_j$ for $j=1,2,...,m-1$
\end{landscape}


text:
Q: Unity: Fit size of parent to size of childs I have an empty in a Canvas that has multiple objects as children. More children are added to the parent as the game progresses. I want the parent to fit the size to its children.
I already read a lot about this topic, but every time I came across the ContentSizeFitter, which unfortunately does not work for me, because it needs a layout group, which I do not have, because the children do not have an order and are wildly placed.
I am using Unity 2018.3.4f1 Personal.
Not sized parent:

Sized parent (Red: New, Green: Old):

Structure:
Canvas
 |- Empty
     |- Child 1
     |- Child 2
     |- Child X

A: I have written a small piece of code that does its job, or does it the way I want and it is enough for me:
using UnityEngine;

public class SizeFitter : MonoBehaviour {
    public void CheckForChanges() {
        RectTransform children = transform.GetComponentInChildren<RectTransform>();

        float min_x, max_x, min_y, max_y;
        min_x = max_x = transform.localPosition.x;
        min_y = max_y = transform.localPosition.y;

        foreach (RectTransform child in children) {
            Vector2 scale = child.sizeDelta;
            float temp_min_x, temp_max_x, temp_min_y, temp_max_y;

            temp_min_x = child.localPosition.x - (scale.x / 2);
            temp_max_x = child.localPosition.x + (scale.x / 2);
            temp_min_y = child.localPosition.y - (scale.y / 2);
            temp_max_y = child.localPosition.y + (scale.y / 2);

            if (temp_min_x < min_x)
                min_x = temp_min_x;
            if (temp_max_x > max_x)
                max_x = temp_max_x;

            if (temp_min_y < min_y)
                min_y = temp_min_y;
            if (temp_max_y > max_y)
                max_y = temp_max_y;
        }

        GetComponent<RectTransform>().sizeDelta = new Vector2(max_x - min_x, max_y - min_y);
    }
}

A: I think you can find the leftiest border and the rightiest border and then add the difference of that value as sizeDelta of the parent RectTransform.
That should fix the size (repeat with top and bottom for Y).
For the position you can get the Top Left corner with leftiest border and top border in a Vector2, then you set that vector as anchoredPosition to the parent RectTransform.
Note that the pivot of the parent must be on Top Left corner for this to work.
This code only approached something, but it is not good enough.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FitParentToChildren : MonoBehaviour
{
    #region INTERNAL

    public RectTransform parent;
    public RectTransform[] children;

    public float minX = 100000;
    public float maxX = -100000;
    public float minY = 100000;
    public float maxY = -100000;

    #endregion

    #region INITIALIZATION

    void Awake()
    {
        parent = GetComponent<RectTransform>();
        children = GetComponentsInChildren<RectTransform>();
    }

    void Start()
    {
        SetMinMaxValues();
        FitToChildren();
    }

    #endregion

    #region BEHAVIOURS

    private void FitToChildren()
    {
        parent.sizeDelta = GetNewRect();
        parent.anchoredPosition = GetTopLeftCornerPositon();
    }

    private void SetMinMaxValues()
    {
        for (int i = 1; i < children.Length; i++)
        {
            float tempMinX = children[i].anchoredPosition.x - children[i].sizeDelta.x / 2;
            if (tempMinX < minX) minX = tempMinX;

            float tempMaxX = children[i].anchoredPosition.x + children[i].sizeDelta.x / 2;
            if (tempMaxX > maxX) maxX = tempMaxX;

            float tempMinY = children[i].anchoredPosition.y - children[i].sizeDelta.y / 2;
            if (tempMinY < minY) minY = tempMinY;

            float tempMaxY = children[i].anchoredPosition.y + children[i].sizeDelta.y / 2;
            if (tempMaxY > maxY) maxY = tempMaxY;
        }
    }

    private Vector2 GetNewRect()
    {
        return new Vector2 (maxX - minX, maxY - minY);
    }

    private Vector2 GetTopLeftCornerPositon()
    {
        return new Vector2 (minX, maxY);
    }

    #endregion
}

GIF HERE

A: Something like this should work.  It loops through all the children of the object of your choice, then finds the renderer bounds of those objects and updates the min and max as it goes.  At the end of the Start() function, the variables min and max hold the coordinates to the corners of the box that defines the bounds.
public class NewBehaviourScript : MonoBehaviour
{
    void Start ()
    {
        Vector2 min = new Vector2 (0, 0);
        Vector2 max = new Vector2 (0, 0);

        GetParentBounds (gameObject, out min, out max);
        Debug.Log (min);
        Debug.Log (max);

    }

    void GetParentBounds (GameObject GO, out Vector2 pMin, out Vector2 pMax)
    {
        Transform[] ts = GO.GetComponentsInChildren<Transform> ();

        Vector2 parentMin = new Vector2 (float.MaxValue, float.MaxValue);
        Vector2 parentMax = new Vector2 (float.MinValue, float.MinValue);

        foreach (Transform t in ts) {
            Renderer rend = t.GetComponent<Renderer> ();
            if (rend != null) {
                Vector2 min = rend.bounds.min;
                Vector2 max = rend.bounds.max;
                Debug.Log (string.Format ("[{0}, {1}], [{2}, {3}]", min.x, min.y, max.x, max.y));
                parentMin.x = Mathf.Min (parentMin.x, min.x);
                parentMin.y = Mathf.Min (parentMin.y, min.y);
                parentMax.x = Mathf.Max (parentMax.x, max.x);
                parentMax.y = Mathf.Max (parentMax.y, max.y);
            }
        }

        pMin = parentMin;
        pMax = parentMax;
    }
}

A: Bounds bound = new Bounds();
for (int i = 0; i < children.Length; ++i)
{
    RectTransform child = children[i];
    if (child != null && child.gameObject.activeSelf)
    {
        Vector2 pos = child.localPosition;
        Vector2 min = pos - child.sizeDelta * child.pivot;
        Vector2 max = min + child.sizeDelta;
        Bounds temp = new Bounds();
        temp.SetMinMax(min, max);
        bound.Encapsulate(temp);
    }
}


text:
Q: C# COM Interop Library I am currently porting a legacy VBA application to a .Net application. During this process the users of the existing VBA application need to have some features added. So instead of coding them in VBA & then later in C#, I've wrote the new functionality in C# and I want to expose this to the existing VBA application through COM, as well as also keeping it in the currently .Net application version.
The solution contain several projects, 1 project for the UI, 1 project for Business Logic, 1 project for the data access layer.
The new features are just a some new forms to modify data. So ideally they will click on a form command button in access which lunch these C# forms via COM interop.
How should I go about exposing this forms through COM Interop.
What I was hoping to do was just add another project, MyProject.COM, which will contain my Interface ICOMManager, for exposing methods to access to launch the required forms. My COMManager class will just instantiate the required forms in my .net application and show them.
This project MyProject.COM will have references to the UI layer & Business Logic Layers.
When I want to register this project using REGASM how will I include references to these other projects?
Thanks for any help or advice on how about doing this.

A: Ah ok so i see this is alot easier than i thought.
Once i looked at the reg file produced by regasm i could see that the tlb (Type Library) is just a pointer to where it can find the libraries to execute the .Net component.
So once i register the tlb and make sure its pointed to the install directory where the rest of the project files are located it works.


text:
Q: efficient way to compare multiple int values to 0 I'm trying to compare three lengths to 0 and was wondering if there was a more efficient/cleaner way than repeating "!= 0".
public static boolean isTriangle(int lengthA, int lengthB, int lengthC) {
    if (lengthA != 0 && lengthB != 0 && lengthC != 0) { //is there a shorter/cleaner way to write this?
        //do a thing
    }
    return false;
}

A: You can use the IntStream and allMatch
if(IntStream.of(lengthA,lengthB,lengthC).allMatch(i->i!=0)) {
     // do a thing
  }

or by using noneMatch also
IntStream.of(lengthA,lengthB,lengthC).noneMatch(i->i==0)

The other way around you do this is by having a util method
public static boolean isNotZero(int val) {
       return val!=0;
     }

Now simplify the if condition
if (isNotZero(lengthA) && isNotZero(lengthB) && isNotZero(lengthC)) {

A: Best answer (IMHO): "Don't even try to second-guess the optimizing compiler."  Just specify the source-code in the way that most accurately specifies (to your fellow humans, nothing more ...) what you want the computer to do.  Don't presume that the actual sequence of machine instructions that is actually given to the hardware actually corresponds to this.  "It's magic.  Really."

A: You're asking three things; you're asking for code that is

*

*shorter

*more efficient

*cleaner

I have an alternative for you:
if ((lengthA & lengthB & lengthC) != 0)

It's correct - it does the same as your old code (it uses bitwise-and)

*

*it is shorter.

*it's potentially more efficient but only a good microbenchmark can confirm. Even if it is, that shouldn't guide you. Because of point 3, you should only consider it if it shows up as a bottleneck in your app using a performance analyzer tool, which is very, very unlikely.

*however it's not cleaner. And with that I mean that it will make your code harder to read and understand, and anyone maintaining your code will now have to think about bit manipulation.

Most likely the same will go for any proposed alternative.
What you were doing in your original code is good enough; it's what people understand, and it's most likely the cleanest code you can write for the purpose.

A: For Java language, your code is good. There's no better way to do this in Java.