text:
Q: Changing the order of integration and Fubini's theorem My understanding of Fubini's theorem is that one can conclude $$ \int_{b}^{\infty} \int_{a}^{\infty} f(x,y) \, dx \, dy = \int_{a}^{\infty} \int_{b}^{\infty} f(x,y) \, dy \, dx $$ if at least one of the iterated integrals converges absolutely.
But this Wikipedia article seems to state that there are additional conditions. I'm a bit confused.
EDIT:
Revisiting this question, I now realize that theorem II in that Wikipedia article is not Fubini's theorem.
It's basically a corollary of the following theorem:

Assume that $f(x,y)$ is a continuous function defined for $a \le x <
\infty$ and $b \le y \le c$. If $ \int_{a}^{\infty} f(x,y) \, dx$
  converges uniformly on the closed interval $[b,c]$, then
  $$\int_{b}^{c} \int_{a}^{\infty} f(x,y) \, dx \, dy =
\int_{a}^{\infty} \int_{b}^{c} f(x,y) \, dy \, dx . $$

The above theorem and theorem II in that Wikipedia article can both be found in chapter XIII, section 3 of Serge Lang's textbook Undergraduate Analysis.

A: Fubini's  theorem doesn't apply here because:
$$\int_1^\infty \int_1^\infty \left| \frac{x^2-y^2}{(x^2+y^2)^2}\right|=\infty$$


text:
Q: Installed Postfix and Amavis but SPF Check dosent work I installed Postfix and Amavis and followed the instructions below.
Link:https://help.ubuntu.com/community/PostfixAmavisNewClamAVSpamAssassin
Test Emails via Telnet arrive or are Rejected when I integrate an Eicar. But now when I want to spoof my own domain no SPF check is done.
The spamassassin init.pre file lists the loadplugin Mail::SpamAssassin::Plugin::SPF module. According to the above instructions, Amavis accesses the spamassassin library, so this should work.
How can i activate the spf check?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel mix undefined error I try to minify my sources with laravel mix and here is my webpack.mix.js file
let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.styles([
  'theme/admin/assets/css/bootstrap.css',
  'theme/admin/assets/font-awesome/css/font-awesome.css',
  'theme/admin/assets/css/zabuto_calendar.css',
  'theme/admin/assets/js/gritter/css/jquery.gritter.css',
  'theme/admin/assets/lineicons/style.css',
  'theme/admin/assets/css/style.css',
  'theme/admin/assets/css/style-responsive.css',
  'theme/admin/assets/js/chart-master/Chart.js'
], 'public/css/admin.css');

mix.js([
  'theme/admin/assets/js/jquery.js',
  'theme/admin/assets/js/jquery-1.8.3.min.js',
  'theme/admin/assets/js/bootstrap.min.js',
  'theme/admin/assets/js/jquery.dcjqaccordion.2.7.js',
  'theme/admin/assets/js/jquery.scrollTo.min.js',
  'theme/admin/assets/js/jquery.nicescroll.js',
  'theme/admin/assets/js/jquery.sparkline.js',
  'theme/admin/assets/js/common-scripts.js',
  'theme/admin/assets/js/gritter/js/jquery.gritter.js',
  'theme/admin/assets/js/gritter-conf.js'
], 'public/js/admin.js');

If i only use styles part on npm run watch it return success the problem is in js files and specifically in this part 'theme/admin/assets/js/bootstrap.min.js',

any idea?


text:
Q: The axis argument to unique is not supported for dtype object I am trying to get unique counts column-wise but my array has categorical variables (dtype object)
val, count = np.unique(x, axis=1, return_counts=True)

Though I am getting an error like this:
TypeError: The axis argument to unique is not supported for dtype object

How do I sove this problem?
Sample x:
array([[' Private', ' HS-grad', ' Divorced'],
       [' Private', ' 11th', ' Married-civ-spouse'],
       [' Private', ' Bachelors', ' Married-civ-spouse'],
       [' Private', ' Masters', ' Married-civ-spouse'],
       [' Private', ' 9th', ' Married-spouse-absent'],
       [' Self-emp-not-inc', ' HS-grad', ' Married-civ-spouse'],
       [' Private', ' Masters', ' Never-married'],
       [' Private', ' Bachelors', ' Married-civ-spouse'],
       [' Private', ' Some-college', ' Married-civ-spouse']], dtype=object)

Need the following counts:
for x_T in x.T:
    val, count = np.unique(x_T, return_counts=True)
    print (val,count)

[' Private' ' Self-emp-not-inc'] [8 1]
[' 11th' ' 9th' ' Bachelors' ' HS-grad' ' Masters' ' Some-college'] [1 1 2 2 2 1]
[' Divorced' ' Married-civ-spouse' ' Married-spouse-absent'
 ' Never-married'] [1 6 1 1]

A: You could use Itemfreq eventhough it the output does not look like yours it delivers the desired counts:
import numpy as np
from scipy.stats import itemfreq

x = np. array([[' Private', ' HS-grad', ' Divorced'],
       [' Private', ' 11th', ' Married-civ-spouse'],
       [' Private', ' Bachelors', ' Married-civ-spouse'],
       [' Private', ' Masters', ' Married-civ-spouse'],
       [' Private', ' 9th', ' Married-spouse-absent'],
       [' Self-emp-not-inc', ' HS-grad', ' Married-civ-spouse'],
       [' Private', ' Masters', ' Never-married'],
       [' Private', ' Bachelors', ' Married-civ-spouse'],
       [' Private', ' Some-college', ' Married-civ-spouse']], dtype=object)

itemfreq(x)

Output:
array([[' 11th', 1],
       [' 9th', 1],
       [' Bachelors', 2],
       [' Divorced', 1],
       [' HS-grad', 2],
       [' Married-civ-spouse', 6],
       [' Married-spouse-absent', 1],
       [' Masters', 2],
       [' Never-married', 1],
       [' Private', 8],
       [' Self-emp-not-inc', 1],
       [' Some-college', 1]], dtype=object)

otherwise you could try to specifiy another dtype such as:
val, count = np.unique(x.astype("<U22"), axis=1, return_counts=True)

for this however your array has to be different


text:
Q: Не могу понять, как применить OnColliderStay и OnColliderExit. Unity C# Доброго времени суток.
Делаю игру для диплома по книжке Unity и C# от Бонда. Тема программирования на C# в Unity очень интересна, поэтому выбрал её, как основу.
Игра, по сути, клон Angry Birds.
Есть SphereCollider(ограничивает натяжение, подсвечивает область куда нужно клацать мышью, чтобы появился снаряд) в GameObject Slingshot(сама рогатка). Есть сам снаряд(projectile), который появляется при нажатии на ЛКМ.
И есть LineRenderer, в созданом специально для всего этого дела GameObject ProjectileBorder, имитирующий резинку, которая натянута между двух "рук" рогатки.
Проблема в том, что когда я задаю точки привязки LineRenderer в последовательности ПРука, снаряд, ЛРука, то они прилипают к снаряду и тянутся за ним, когда он уже запущен.
И т.к. снаряды клонируются при каждом нажатии ЛКМ, то в LineRenderer не задаётся точка для нового снаряда, а остаётся на старой. Подумал, что можно решить проблему с помощью Collider.
Такой вопрос - как можно, с помощью OnColliderStay и OnColliderExit сделать следующий код:
Если projPref.projectile == null или не в коллайдере, то
(
    line.positionCount = 2;
    pointFirst = GameObject.FindGameObjectWithTag("RArmBorder").transform.position;
    pointFour = GameObject.FindGameObjectWithTag("LArmBorder").transform.position;
    line.SetPosition(0, pointFirst);
    line.SetPosition(1, pointFour);
)

Если projPref.projectile находится в коллайдере, то
(
    line.positionCount = 3;
    pointSecond = GameObject.FindGameObjectWithTag("ProjBorder").transform.position;
    pointThird = GameObject.FindGameObjectWithTag("ProjBorderS").transform.position;
    line.SetPosition(0, pointFirst);
    line.SetPosition(1, pointSecond);
    line.SetPosition(2, pointFour);
)

И будет ли он работать так, как задумано(сбрасывать старую точку привязки к снаряду и привязывать к только что созданному)? Спасибо.
Если что-то не понятно в той тарабарщине, что я написал - прошу уточнить. Постараюсь дать развёрнутый ответ.
P.S.: Также заметил у себя другую проблему. Если задавать сразу 4 точки привязки для LineRenderer, то "резинка" исчезает по какой-то причине. Так и не нашёл в чём может быть проблема. Вдруг вы поможете?
Прикладываю код который есть сейчас:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RubberLine : MonoBehaviour
{
    private LineRenderer line;
    private Vector3 pointFirst;
    private Vector3 pointSecond;
    private Vector3 pointThird; // Пока не используется.
    private Vector3 pointFour;
    public Slingshot projPref;

    void Awake()
    {
        line = GetComponent<LineRenderer>();
        projPref = GameObject.Find("Slingshot").GetComponent<Slingshot>();
    }

    void Update()
    {
        if (projPref.projectile == null)
        {
            line.positionCount = 2;
            pointFirst = GameObject.FindGameObjectWithTag("RArmBorder").transform.position;
            pointFour = GameObject.FindGameObjectWithTag("LArmBorder").transform.position;
            line.SetPosition(0, pointFirst);
            line.SetPosition(1, pointFour);
        }

        if (projPref.projectile != null)
        {
            line.positionCount = 3;
            pointSecond = GameObject.FindGameObjectWithTag("ProjBorder").transform.position;
            pointThird = GameObject.FindGameObjectWithTag("ProjBorderS").transform.position;
            line.SetPosition(0, pointFirst);
            line.SetPosition(1, pointSecond);
            line.SetPosition(2, pointFour);
        }

    }

}


text:
Q: What phrase/idiom can be used to refer to procrastination? Suppose I'm replying to someone's email and it's long overdue - completely hypothetically :)
Starting with "Sorry for [ ... ] this". At first I thought I'd use "dropping the ball on" but it seems that "dropping the ball" refers more to making a blunder than to simply putting something off for too long.
Any ideas?

A: You've let it slide, you've been dragging your heels, you've been putting it off.

A: Sorry for this belated reply, but the word is 'belated'. ;-)

A: 'Sorry for letting the grass grow under my feet' is probably going to deflect their annoyance by the mild humour involved.

A: use delayed, it is professional and means, well, not on time

A: It depends on the audience.  It may be especially important to get the tone right in this situation, because it's possible that your recipient is upset, and you need to mollify them.
For instance, in a business letter, you might start with something like "I apologise for the long delay", and continue with a respectful tone throughout (without being obsequious).  In a letter to a friend, something more light and humorous could work, but if the friend is really upset, florid apologies might be called for.
It may be worthwhile to try to think of something original here, since using stock phrases may not improve your correspondent's mood.


text:
Q: instance member is not accessible How can I access class functions from inside stack navigator header? Is this possible?
What I'm trying to achieve is to call a function when I press the stack navigator header title.
class Dashboard extends React.Component {
        static navigationOptions = ({ navigation }) => {
            return {
                headerTitle: (
                        <View style={header.addressView}>
                            <Text
                                style={header.titleAddress}
                                onPress={() => {
                                  this._show().bind(this);
                                }}>
                            />
                        </View>
                ),
            };
        };

        _show(){
            this.setState({ visibleModal: 1 })
        }

        constructor(props) {
            super(props);

            this.state = {
                visibleModal: null,
            };
        }

        render() {
            ...........

        }
    }

    export default Dashboard;

A: class Dashboard extends React.Component {
    static navigationOptions = ({ navigation }) => {
        const showParams = navigation.getParam("show",()=>{});
        //Access the params like this.
        return {
            headerTitle: (
                    <View style={header.addressView}>
                        <Text
                            style={header.titleAddress}
                            onPress={showParams}>
                        />
                    </View>
            ),
        };
    };

    _show(){
        this.setState({ visibleModal: 1 })
    }

    //Too add this.

    componentDidMount(){
      this.props.navigation.setParams({show:()=>this._show()});
    }

    constructor(props) {
        super(props);

        this.state = {
            visibleModal: null,
        };
    }

    render() {
        ...........

    }
}

export default Dashboard;

This is how you access the variables or states inside a class and make it available for the static navigationOptions function.
Reference


text:
Q: How to make my program JLabel selection random Here is my code.new with this .thanks in advance
im not sure how to use the random generator...i want to randomize my correct answer...i want to make sure that the next selection will not be the same jlabel ive selected..thank you very much if you could help me...new in programming here...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class NumberFinder extends JFrame implements MouseListener{
FlowLayout f1 = new FlowLayout();
Font aFont = new Font("Arial", Font.BOLD, 100);
Font bFont = new Font("Century", Font.BOLD, 20);

JLabel a = new JLabel("1");
JLabel b = new JLabel("2");
JLabel c = new JLabel("3");
JLabel d = new JLabel("4");
JLabel ed = new JLabel("5");
JLabel f = new JLabel("6");
JLabel g = new JLabel("7");
JLabel h = new JLabel("8");
JLabel i = new JLabel("9");
JLabel j = new JLabel("");
int ran = 0;
int count = 0;

public NumberFinder()
{
    super("Number Finder");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(f1);
    a.setFont(aFont);
    b.setFont(aFont);
    c.setFont(aFont);
    d.setFont(aFont);
    ed.setFont(aFont);
    f.setFont(aFont);
    g.setFont(aFont);
    h.setFont(aFont);
    i.setFont(aFont);
    j.setFont(bFont);
    add(a);
    add(b);
    add(c);
    add(d);
    add(ed);
    add(f);
    add(g);
    add(h);
    add(i);
    add(j);
    a.addMouseListener(this);
    b.addMouseListener(this);
    c.addMouseListener(this);
    d.addMouseListener(this);
    ed.addMouseListener(this);
    f.addMouseListener(this);
    g.addMouseListener(this);
    h.addMouseListener(this);
    i.addMouseListener(this);

}

public void mouseClicked(MouseEvent e){
    if(e.getSource()==a)
    {
    a.getText();
    j.setText("Try Again");
    a.setEnabled(false);
    count ++;
    }
    else if(e.getSource()==b)
    {
    b.getText();
    j.setText("Correct!");
    b.setEnabled(true);
    count ++;
    }
    else if(e.getSource()==c)
    {
        c.getText();
        j.setText("Try Again");
        c.setEnabled(false);
        count++;
    }
    else if(e.getSource()==d)
    {
        d.getText();
        j.setText("Try again");
        d.setEnabled(false);
        count++;
    }
    else if(e.getSource()==ed){
        ed.getText();
        j.setText("Try Again");
        ed.setEnabled(false);
        count++;
    }
    else if(e.getSource()==f){
        f.getText();
        j.setText("Try Again");
        f.setEnabled(false);
        count++;
    }
    else if(e.getSource()==g){
        g.getText();
        j.setText("Try Again");
        f.setEnabled(false);
        count++;
    }
    else if(e.getSource()==h){
        h.getText();
        j.setText("Try Again");
        h.setEnabled(false);
        count++;
    }
    else if(e.getSource()==i){
        i.getText();
        j.setText("Try Again");
        i.setEnabled(false);
        count++;
    }}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}

}

A: Add your labels to some kind of List...
JLabel[] arrayOfLables = {
    new JLabel("1"),
    new JLabel("2"),
    new JLabel("3"),
    new JLabel("4"),
    new JLabel("5"),
    new JLabel("6"),
    new JLabel("7"),
    new JLabel("8"),
    new JLabel("9"),
    new JLabel("")};
List<JLabel> labels = new ArrayList<>(Arrays.asList(arrayOfLables));

Use Collections.shuffle to shuffle the list...
Collections.shuffle(labels);

Add them to you container...
for (JLabel label : labels) {
    add(label);
}


text:
Q: Variable stays as False - Python Beginner I'll preface by saying that I'm new to Python. I appologize if this should be extremely simple...
I'm working on "Maze" world on reeborg.ca trying to fix a bug where if your sprite starts with no walls around it, it could loop in a circle. I tried to create an init cycle called "init_homing" where it tests to see if the condition of being in a space with no walls surrounding the sprite is true. If it does, it will move and then run the "init_homing" function again until it has a wall adjacent to it. Once it has this adjacent wall, it should change the seek_goal value to True, which should break the "init_homing" function and continue on to the primary part of the program..
The issue is, is that even though it gets to the else statements which should change the value of seek_goal to True, the seek_goal value remains as False
Thank you in advanced:
seek_goal = False
def turn_right():
    turn_left()
    turn_left()
    turn_left()
def turn_around():
    turn_left()
    turn_left()
def init_homing():
    if right_is_clear() and front_is_clear():
        turn_around()
        if right_is_clear() and front_is_clear():
            turn_right()
            move()
        else:
            seek_goal = True
    else:
        seek_goal = True

while seek_goal == False:
    init_homing()

while at_goal() == False and seek_goal == True:
    if right_is_clear():
        turn_right()
        move()
    elif front_is_clear():
        move()
    else:
        turn_left()

A: If you assign to a variable inside of a function, it's treated as a local variable. The seek_goal variable inside init_homing has no relation to the global one at the top of your file, despite seeming to have the same name.
To demand that Python use the global variable instead, use the global keyword.
def init_homing():
    global seek_goal
    if right_is_clear() and front_is_clear():
        turn_around()
        if right_is_clear() and front_is_clear():
            turn_right()
            move()
        else:
            seek_goal = True
    else:
        seek_goal = True


text:
Q: Clang and GCC has an inconsistent interpretation to the case where the parameter name appears as an unevaluated operand #include <iostream>
void fun(int a = sizeof(a)){
    std::cout<< a<<std::endl;
}
int main(){
   fun();
}

Consider this case. Clang accepts it while GCC rejects it. According to [dcl.fct.default] p9

A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument.

[basic.def.odr] p2

An expression or conversion is potentially evaluated unless it is an unevaluated operand

sizeof is not a potentially-evaluated expression and a can be found at this point. I wonder which one is correct for this case?

A: GCC is wrong. It assumes that a is not yet in scope in the default argument, although generally the point of declaration is immediately after the declarator before the initializer and none of the exceptions apply here. [basic.scope.pdecl]/1
An older bug report for this is here.
Note however, that the bug report has equivalent code to yours, but claims it should be ill-formed. That is because it was written before CWG 2082 which allowed the use of a parameter in an unevaluated context in the default argument.
Related question regarding this GCC bug here.


text:
Q: Get property that extends interface I am trying to write a generic function in TypeScript that returns the property of an object with the additional constraint that the returned property extends an HasID interface.
I would hope to be able to use it something like this:
let obj = {
  foo: 123,
  bar: {
    id: 123
  }
};

get(obj, 'foo') // Error
get(obj, 'bar') // Everything is fine

This is what I have so far:
interface HasID {
  id: number;
}

interface HasPropertyWithID<K, T extends HasID> {
  K: T
}

function get<
  T extends HasID,
  K extends keyof O,
  O extends HasPropertyWithID<K, T>
>(obj: O, key: K): T {
  return obj[key]
}

But it gives the error 'O[K]' is not assignable to type 'T'. Is there some way to bend TypeScript's type system to support this?

A: Using a mapped type will constrain the value appropriately:
function get<
    K extends keyof O,
    T extends HasID,
    O extends { [P in K]: T }
    >(obj: O, key: K): T {
    return obj[key]
}
// Usage
let obj = {
    foo: 123,
    bar: {
        id: 123,
        ss: ''
    }
};

get(obj, 'foo') // Error
get(obj, 'bar') // Everything is fine


text:
Q: In Object-Oriented Programming, can a class be considered "too specialized"? If a class can only perform one task, could it be considered to be "too specialized"?
My intuition is that classes should be abstractions that are capable of representing themselves in multiple ways.  I'm reviewing some class definitions that are so specific that these objects cannot be used except for a single use case.
Example:
If I wanted to have a class called Dog, I may also want a subclass like Dog::Collie.  If we want an instance of Lassie the dog, Dog::Collie should be abstract enough to describe her.  If we need to specialize a new class Dog::Collie::Lassie, I'd be inclined to refactor Collie to support this - not super specialize a new derivation.
Edit: for clarification, Lassie is not an attribute of Collie or Dog, it's a concrete class definition that has functions like getHelp() and smileForCamera() that are not in Dog or Collie.

A:
If we need to specialize a new class Dog::Collie::Lassie, I'd be inclined to refactor Collie to support this - not super specialize a new derivation.

Why? Apparently, there have been nine different Lassies over the years, and they presumably each had their own birth date, weight, height, medical history, list of film and television appearances, etc. Depending on what your program is meant to do, it might make sense to have Lassie as a subclass because not all Collie instances need to track their media appearances, fan club connections, etc.
I think the point you were trying to make is that if a class represents one specific thing rather than a category of things, it's too specific. My counterargument is that when you create a class you often can't know how many instances of a thing you'll eventually have, and you shouldn't worry about that. If generalizing Collie to include the behaviors needed for Lassie makes you write a lot of code that looks like:
if (dangerPresent) {
    if (name is Lassie) {
        runForHelp
        barkBarkBark
    else {
        runAway
    }
}

then it's probably a lot better to create a Lassie subclass even if you know for certain that it'll only ever represent a single dog.

If a class can only perform one task, could it be considered to be "too specialized"?

Some would argue the opposite, i.e. that according to the Single Responsibility Principle a class should only do one thing. Exactly what counts as a "task" or "responsibility" depends a lot on where the class fits into the design of the system. Your example above helps to clarify that... if the job of the Collie class is to represent any collie, then making it also model characteristics that apply only to some subset of collies (even if that subset has only one member) violates SRP.
I think a class can be too specialized, but mainly because it purports to be more abstract than it really is. Again, see the SRP. If a class's implementation is doing things to support only one or more subsets of the category that it represents, then the class is too specialized and should be refactored.

A: Collie can be regarded a special kind of dog, Lassie cannot be regarded a special kind of Collie.
You seem to have trouble making the distinction between classes on the one hand and individual variations on the other hand. Lassie is a Collie incarnation, an individual or in OO-speak: an instance. You can have an infinite number of instances of Collie and they may all be different in some way, yet they would not be different in "collieness".
It is only for fundamental differences that apply to all instances of a kind of dog that you would consider introducing a new class. Collies have long hair, they all have a pointy snout, they all share the patched coloring and the fluffy tail, so... maybe we should have a sub-class of dog to model this kind of dog. And then you would only do this if you care about these traits, if they make a difference in your problem domain. I am more of a cat man so I would be happy with just Dog (dogs are dogs, I don't care about their furs or sizes, I just want them to keep their distance).
The bottom line is: a class should make your software easier to understand, to write and to maintain. If a new class defeats that purpose, if it only adds complexity period, then you are over-specializing.

A: Classes are not exactly abstractions, they are concretions (potentially of an abstraction). Generally, whatever you can create an instance of typically:

*

*Is concrete.

*May have specific state.

*May have specific behavior.

It might be that you are confusing the class definition and the class instances. Of course class definitions are an abstraction that represents the range of all possible instances (defined as the set of all instances occurring by cover the entire domain of the internal state parameters).
Your Dog::Collie:Lassie example showcases a minor problem. Dog and Collie are class definitions, but Lassie should be a specific class instance. It is a just matter of taxonomy, really. Collie is a Type, but Lassie is a Name. So, unless you really want to represent Lassie as a Type (in which case you may have multiple Lassie instances).
To make this clearer, let me introduce you to my two friends. I have 3 instances of Michael and another 3 instances of Jordan:
Michael morningMichael = new Michael();
Michael afternoonMichael = new Michael();
Michael nightMichael = new Michael();

Jordan morningJordan = new Jordan();
Jordan afternoonJordan = new Jordan();
Jordan nightJordan = new Jordan();

Now, this is my mental model. When I see Michael in the afternoon, it is a different Michael, who happens to bear terrific resemblance to the morning version of Michael. He is a little more tired than morning Michael, his weight is slightly different, and stuff, but he still has two hands, two legs, one head, same hair color, same complexion, etc. There are two obvious problems with this mental model, and one that is not so obvious.

*

*There is gross definition duplication. Michael and Jordan share very similar traits so I will have to code definitions multiple times. I can overcome this by using base definitions and inheriting, but I will reach a point where, after inheriting, there will be virtually nothing more to define.

*There is no resemblance of this mental model to reality, which is what I have been trained in for my entire life, so reality is a model I can perfectly, easily and fluently relate to, and whatever I can translate to or from reality is, practically, easier for me to understand, grasp and develop around. When I see a friend after a day goes by, I don't ever feel like it is a copy of my friend...

*The not so obvious problem is that this is perfectly allowed using available coding tools and definition/prototyping capabilities.

In solving the third problem, at some point, Types must end, and State must come to be. Therefore, I choose to stop my definitions (types, really) at Human and let state manifest, in the form of instances. Then, whenever I read my code, it really takes me less than a few milliseconds to understand that whenever I come across instance micheal, it is really the same Human I came across earlier, when talking about michael. He may have changed internally, but it is the same guy (viz. the same byte-group in memory).
Human michael = new Human();

Human jordan = new Human();

So, like I said earlier, it is a matter of taxonomy, really. It is more like philosophy, but also a lot about what makes you more productive. Object-oriented programming borrows from the real world, because understanding the real world is something we all have a lot of training in, and we can express our ideas much easier in that model.
All that aside, the extent of detail one reaches is always dependent on the case. For example, while birds are, technically, dinosaurs, you will not come across many real-world code-bases with a hierarchy such as Dinosaur::Bird.... So, as usual, more often than not, your very own definitions in your code generally reflect what you are trying to achieve, and this is what you should use to balance your choices.


text:
Q: PXE boot problem using netboot.xyz "mounting tmpfs on /cdrom failed: Invalid argument" I've set up my pfsense server with tftp to support PXE booting. I've configured it to boot the latest (as of posting) version of netboot.xyz. This works to a point, but I've tried loading a few Linux images and they all seem to die with the same error messages. Key output text includes:
...
mount: mounting tmpfs on /cdrom failed: Invalid argument
...
curl: (23) Failed writing body (0 != 16384)
Unable to find a live file system on the network
...

Screenshot:

I'm not sure if this is a tftp issue (I doubt it), a pfsense issue (I doubt it), a netboot.xyz issue (my main guess) or something else.

A: Figured it out! I've been working on machines with fairly small amounts of memory. In the example above, it was a VM with about 1GB of RAM. I increased it to 4GB and the PXE booting started working fine.
So I guess a take-away is that netboot.xyz could add something to their menus to warn you if your machine has a risky-tiny amount of memory.


text:
Q: Spring REST error handling : Cannot have my custom message I read several articles/tutorials... about error handling on server side. I simply want to return an http error code with my custom message. And of course it does not work.
The result I'm always having in my javascript callbacks is this message :
<title>HTTP ERROR</title>
My code :
Javascript :
create : function() {
    $scope.myObject.$save(
    function(response) {
         init();
         $scope.popupCtrl.hideModal();
         $scope.popupCtrl.hideError();
    },
    function(error) {
        // error, where I always get the html page...
        $scope.popupCtrl.manageError(error.message);
    });
}

My Controller :
@RequestMapping(value = "myObject", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public final String createNewCrawlConfiguration(@RequestBody final String receivedString)
{
    String jsonString;
    try
    {
        jsonString = URLDecoder.decode(receivedString, "UTF-8");
        LOGGER.debug("Preparing configuration to be saved. Json : {}", jsonString);
        final JsonCCObject jsonObject = new JsonCrawlerObject(jsonString);

        // check for the json*
        // validate contains an array of missing attributes.

        if (!jsonObject.validate().isEmpty())
        {
            throw new ConfigurationCreationException(HttpStatus.BAD_REQUEST,
                    returnJsonError(new ArrayList<>(jsonObject.validate())));
        }

        // save the object

    }
    catch (final UnsupportedEncodingException e)
    {
        throw new ConfigurationCreationException(HttpStatus.BAD_REQUEST,
                "Unsupported encoding : " + e.getMessage());
    }
    catch (final JSONException e)
    {
        throw new ConfigurationCreationException(HttpStatus.BAD_REQUEST,
                "Json Exception : " + e.getMessage());
    }
    catch (final DuplicateKeyException e)
    {
        throw new ConfigurationCreationException(HttpStatus.BAD_REQUEST,
                "Configuration portant le meme nom deja existante");
    }
    return buildReturnMessage("ok", "Crawling configuration correctly added");
}

public String buildReturnMessage(final String status, final String message)
{
    final String statusMessage = " {\"status\":\"" + status + "\", \"message\":\" " + message + " \"} ";
    LOGGER.debug(statusMessage);
    return statusMessage;
}

/**
 * Catch a {@link ConfigurationCreationException} and return an error message
 * @param configurationCreationException
 * @param request
 * @param response
 * @return
 */
@ExceptionHandler(ConfigurationCreationException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleConfigurationCreationException(
        final ConfigurationCreationException configurationCreationException,
        final WebRequest request, final HttpServletResponse response)
{
    LOGGER.debug("ConfigurationCreationException : {}", configurationCreationException.getErrMessage());
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    return buildReturnMessage(configurationCreationException.getErrCode(),
            configurationCreationException.getErrMessage());
}

Have you got any ideas ?
Thank you !

EDIT
I did a mistake on my question :
The html returned shows error 400.
I haven't any media problem, it's the error I want to return. What I mean is that tomcat is not generating it, I do it myself with a throw new ConfigurationCreationException(HttpStatus.BAD_REQUEST,...).
The issue here is only about retrieving the custom error on the client side :/.

A: I solved this problem, by writing and registering a Exception Handler that responds with an JSON encoded error message, whenever a exception is delivered to the Exception Handler, and the requests accept type header is application/json or application/json; charset=utf-8.
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import org.springframework.web.util.WebUtils;

/**
 * Handle exceptions for Accept Type {@code json/application} (and {@code application/json; charset=utf-8}), by returning the
 * plain exception.
 *
 *

 * This handler "catches" EVERY exception of json requests, therefore it should be the last exception resolver that handle json requests!
 *

 *
 *

 * It is important to register this handler before (lower order) than the normal
 * {@link org.springframework.web.servlet.handler.SimpleMappingExceptionResolver}.
 *

 *

 *
 * A typical configuration will looks like this pay attention to the order:
 *
 {@code
 *
 * <bean id="handlerExceptionResolver" class="org.springframework.web.servlet.handler.HandlerExceptionResolverComposite">
 *      <property name="exceptionResolvers">
 *          <list>
 *
 *              <ref bean="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0" />
 *
 *
 *              <ref bean="org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0" />
 *
 *                   <bean class="JsonPlainExceptionResolver">
 *
 *                       <property name="defaultErrorCode" value="500"/>
 *                       <property name="exceptionToErrorCodeMappings">
 *                           <props>
 *                               <prop key=".DataAccessException">500</prop>
 *                               <prop key=".NoSuchRequestHandlingMethodException">404</prop>
 *                               <prop key=".TypeMismatchException">404</prop>
 *                               <prop key=".MissingServletRequestParameterException">404</prop>
 *                              <prop key=".ResourceNotFoundException">404</prop>
 *                              <prop key=".AccessDeniedException">403</prop>
 *                        </props>
 *                   </property>
 *              </bean>
 *
 *
 *              <ref bean="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0" />
 *          </list>
 *      </property>
 *  </bean>
 * }
 *

 *

 *
 *

 * It is recommended to use this exception resolver together with an
 * {@link ResponseCommittedAwarenessExceptionResolverWrapper}
 *

 *
 * @author Ralph Engelmann
 */
public class JsonPlainExceptionResolver extends AbstractHandlerExceptionResolver {

    /** Logger for this class. */
    private static final Logger LOGGER = Logger.getLogger(JsonPlainExceptionResolver.class);

    /** Accept header attribute for application/json. */
    private static final String APPLICATION_JSON = "application/json";

    /** Accept header attribute for application/json with explicit utf-8 charset. */
    private static final String APPLICATION_JSON_UTF8 = "application/json; charset=utf-8";

    /** The default for the {@link #defaultErrorCode}. */
    private static final int DEFAULT_DEFAULT_ERROR_CODE = 500;

    /** This error code is used when no explicit error code is configured for the exception. */
    private int defaultErrorCode = DEFAULT_DEFAULT_ERROR_CODE;

    /** Key = exception pattern, value exception code. */
    private Properties exceptionToErrorCodeMappings;

    public int getDefaultErrorCode() {
        return this.defaultErrorCode;
    }

    public void setDefaultErrorCode(final int defaultErrorCode) {
        this.defaultErrorCode = defaultErrorCode;
    }

    public Properties getExceptionToErrorCodeMappings() {
        return this.exceptionToErrorCodeMappings;
    }

    /**
     * Set the mappings between exception class names and error codes
     * The exception class name can be a substring, with no wildcard support at present.
     * A value of "ServletException" would match javax.servlet.ServletException
     * and subclasses, for example.

     * @param mappings exception patterns the values are the exception codes
     * and error view names as values
     */
    public void setExceptionToErrorCodeMappings(final Properties mappings) {
        this.exceptionToErrorCodeMappings = mappings;
    }

    /**
     * Check whether this resolver is supposed to apply to the given handler.
     *
     *

     * This implementation do the same checks as the super class, and requires in addition that
     * the request has an JSON accept Type.
     *

     */
    @Override
    protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {

        String acceptType = request.getHeader("Accept");
        return super.shouldApplyTo(request, handler)
                && (acceptType != null)
                && (acceptType.equalsIgnoreCase(APPLICATION_JSON) || acceptType.equalsIgnoreCase(APPLICATION_JSON_UTF8));
    }

    /**
     * Do resolve exception.
     *
     * @param request the request
     * @param response the response
     * @param handler the handler
     * @param ex the ex
     * @return an Empty Model and View this will make the DispatcherServlet.processHandlerException in conjunction with
     * DispatcherServlet.processDispatchResult assume that the request is already handeled.
     *
     * @see
     * org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver#doResolveException(javax.servlet.http
     * .HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    protected ModelAndView doResolveException(final HttpServletRequest request, final HttpServletResponse response,
            final Object handler, final Exception ex) {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Handle exception from request: "+ request, ex);
        }

        String exceptionDetails = JsonPlainExceptionResolver.getExceptionDetailsAndCompleteStackTrace(ex);

        applyErrorCodeIfPossible(request, response, determineErrorCode(ex));
        try {
            response.getOutputStream().write(exceptionDetails.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 not supported???", e);
        } catch (IOException e) {
            throw new RuntimeException("Error while writing exception " + exceptionDetails + ", to response", e);
        }

        WebUtils.clearErrorRequestAttributes(request);

        ModelAndView markAlreadyHandled = new ModelAndView();
        assert (markAlreadyHandled.isEmpty());
        return markAlreadyHandled;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver#buildLogMessage(java.lang.Exception,
     * javax.servlet.http.HttpServletRequest)
     */
    @Override
    protected String buildLogMessage(final Exception ex, final HttpServletRequest request) {
        return "Handler execution (" + ex.getClass() + ") resulted in exception , request: "
                + request);
    }

    /**
     * Determine the view name for the given exception, searching the {@link #setExceptionMappings "exceptionMappings"},
     * using the {@link #setDefaultErrorView "defaultErrorView"} as fallback.
     * @param ex the exception that got thrown during handler execution
     * @return the resolved view name, or null if none found
     */
    protected int determineErrorCode(final Exception ex) {
        // Check for specific exception mappings.
        if (this.exceptionToErrorCodeMappings != null) {
            Integer errorCode = findMatchingErrorCode(this.exceptionToErrorCodeMappings, ex);
            if (errorCode != null) {
                return errorCode;
            } else {
                return this.defaultErrorCode;
            }
        }
        return this.defaultErrorCode;
    }

    /**
     * Find a matching view name in the given exception mappings.
     * @param exceptionMappings mappings between exception class names and error view names
     * @param ex the exception that got thrown during handler execution
     * @return the view name, or null if none found
     * @see #setExceptionMappings
     */
    protected Integer findMatchingErrorCode(final Properties exceptionMappings, final Exception ex) {
        Integer errorCode = null;
        int deepest = Integer.MAX_VALUE;
        for (Enumeration<?> names = exceptionMappings.propertyNames(); names.hasMoreElements();) {
            String exceptionMapping = (String) names.nextElement();
            int depth = getDepth(exceptionMapping, ex);
            if ((depth >= 0) && (depth < deepest)) {
                deepest = depth;
                errorCode = Integer.parseInt(exceptionMappings.getProperty(exceptionMapping));
            }
        }
        return errorCode;
    }

    /**
     * Return the depth to the superclass matching.
     *
0 means ex matches exactly. Returns -1 if there's no match.
     * Otherwise, returns depth. Lowest depth wins.
     *
     * @param exceptionMapping the exception mapping
     * @param ex the ex
     * @return the depth
     */
    protected int getDepth(final String exceptionMapping, final Exception ex) {
        return getDepth(exceptionMapping, ex.getClass(), 0);
    }

    /**
     * Gets the depth.
     *
     * @param exceptionMapping the exception mapping
     * @param exceptionClass the exception class
     * @param depth the depth
     * @return the depth
     */
    private int getDepth(final String exceptionMapping, final Class<?> exceptionClass, final int depth) {
        if (exceptionClass.getName().contains(exceptionMapping)) {
            // Found it!
            return depth;
        }
        // If we've gone as far as we can go and haven't found it...
        if (exceptionClass.equals(Throwable.class)) {
            return -1;
        }
        return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1);
    }

    /**
     * Apply the specified HTTP status code to the given response, if possible (that is,
     * if not executing within an include request).
     * @param request current HTTP request
     * @param response current HTTP response
     * @param statusCode the status code to apply
     * @see #determineStatusCode
     * @see #setDefaultStatusCode
     * @see HttpServletResponse#setStatus
     */
    protected void applyErrorCodeIfPossible(final HttpServletRequest request, final HttpServletResponse response,
            final int statusCode) {
        if (!WebUtils.isIncludeRequest(request)) {
            response.setStatus(statusCode);
            request.setAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE, statusCode);
        }
    }

    /**
     * Gets the exception details and complete stack trace.
     *
     * @param e the e
     * @return the exception details and complete stack trace
     */
    public static String getExceptionDetailsAndCompleteStackTrace(final Throwable e) {
        StringBuilder detailedMessage = new StringBuilder();
        if (e.getLocalizedMessage() != null) {
            detailedMessage.append(e.getLocalizedMessage());
        }

        if (detailedMessage.length() > 0) {
            detailedMessage.append("\n");
        }

        detailedMessage.append(e.getClass().getName());

        /** Save: Commons lang does not support generics in this old version. */
        @SuppressWarnings("unchecked")
        List<Throwable> throwables = ExceptionUtils.getThrowableList(e);
        for (int i = 1; i < throwables.size(); i++) {
            detailedMessage.append("\n cause: ");
            detailedMessage.append(throwables.get(i).getClass().getName());
            if (StringUtils.isNotBlank(throwables.get(i).getLocalizedMessage())) {
                detailedMessage.append(" -- " + throwables.get(i).getLocalizedMessage());
            }
            detailedMessage.append(";");
        }

        detailedMessage.append("\n\n --full Stacktrace--\n");
        detailedMessage.append(ExceptionUtils.getFullStackTrace(e));

        return detailedMessage.toString();
    }

}

A: You probably have the worlderror.org malware installed on your computer that is intercepting the 400-600 status code responses.
Your not even seeing the spring errors because the malware is intercepting it.
Try running a different browser or run a spyware removal software.

A: I have the following and works fine:
Note: Doing the things simple.
In your class that extends WebMvcConfigurerAdapter add the following:
@Bean
public StringHttpMessageConverter stringHttpMessageConverter(){
    StringHttpMessageConverter converter = new StringHttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaType.ALL));
    return converter;
}

@Bean
public ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver(){
    ExceptionHandlerExceptionResolver eher = new ExceptionHandlerExceptionResolver();
    eher.setMessageConverters(Arrays.asList(stringHttpMessageConverter()));
    return eher;
}

@Bean
public ResponseStatusExceptionResolver responseStatusExceptionResolver(){
    return new ResponseStatusExceptionResolver();
}

@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers){
        exceptionResolvers.add(exceptionHandlerExceptionResolver());
        exceptionResolvers.add(responseStatusExceptionResolver());
}

Therefore
@ExceptionHandler(value=MyException.class)
public ResponseEntity<String> errorHandlerHttpHeaderRestrict(MyException me){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>("ERROR FATAL: "+me.getMessage(), httpHeaders, HttpStatus.BAD_REQUEST);//400
}

I suggest you use ResponseEntity instead of
@ResponseStatus(value = HttpStatus.BAD_REQUEST) and @ResponseBody.
It because:

*

*ResponseEntity is more flexible

*With @ResponseStatus you must be totally sure the method only can return that HttpStatus (just one)

A: Here is how I solved this :
I updated my Spring version from 3.2.2 to 4.0.3 (a more recent should work too).
Then, @ControllerAdvice accepts the basePackage parameters :
@ControllerAdvice(basePackages = "me.myself.hi")
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler
{
    /** The associated logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);

    @ExceptionHandler(value = { HttpRestException.class })
    protected ResponseEntity<Object> handleConflict(final RuntimeException ex, final WebRequest request)
    {
        if (ex instanceof HttpRestException)
        {
            final HttpRestException restEx = (HttpRestException) ex;
            return handleExceptionInternal(ex, restEx.getMessage(), new HttpHeaders(), restEx.getHttpStatus(), request);
        }

        return handleExceptionInternal(ex, "Internal server error",
                new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }
}

basePackage specify the package assigned to the handler class. That means each controller defined in this package (or a sub one) will be concerned.
For me, me.myself.hi is a base package name shared by at least 10 projects. So even if a controller is in another project, as long as it is under a package starting with me.myself.hi, the HttpRestException will be catched there.
Remember that the exception must not be handled at the Controller level, but only thrown, the @ControllerAdvice annotated controller will handle this exception and return statuscode + error message.


text:
Q: Why is onAttach called before onCreate? In a Fragment's Lifecycle, the onAttach() method is called before the onCreate() method. I can't wrap my head around this. Why would you attach a Fragment first?

A: This is related to retained fragments. Following Fragment setRetainInstance(boolean retain) documentation:

If set, the fragment lifecycle will be slightly different when an activity is recreated:

*

*onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).

*onCreate(Bundle) will not be called since the fragment is not being re-created.

*onAttach(Activity) and onActivityCreated(Bundle) will still be called.

Take a look at the source code (android.support.v4.app.FragmentManager, v21):
void moveToState(Fragment f,
                 int newState,
                 int transit,
                 int transitionStyle,
                 boolean keepActive) {
    ...
    f.onAttach(mActivity);
    if (!f.mCalled) {
        throw new SuperNotCalledException("Fragment " + f
                + " did not call through to super.onAttach()");
    }
    if (f.mParentFragment == null) {
        mActivity.onAttachFragment(f);
    }

    if (!f.mRetaining) {
        f.performCreate(f.mSavedFragmentState); // <- Here onCreate() will be called
    }
    ...
}

Example
Case 1: not retained fragment or setRetainInstanceState(false)
Application is started. Fragment is added dynamically using FragmentManager or inflated from XML via setContentView().
onAttach() called after Activity super.onCreate() call - Activity is already initialised.
MainActivity﹕ call super.onCreate() before
MainActivity﹕ super.onCreate() returned
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@1be4f2dd
MainFragment﹕ onCreate() getActivity=com.example.MainActivity@1be4f2dd

Configuration changed. Activity recreates fragments from saved state, fragments are added/attached from inside Activity super.onCreate() call:
MainActivity﹕ call super.onCreate() before
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@2443d905
MainFragment﹕ onCreate() getActivity=com.example.MainActivity@2443d905
MainActivity﹕ super.onCreate() returned

Case 2: setRetainsInstanceState(true)
Application is started. Fragment is added dynamically using FragmentManager or inflated from XML via setContentView(). Same as above:
onAttach() called after Activity super.onCreate() call - Activity is already initialised.
MainActivity﹕ call super.onCreate() before
MainActivity﹕ super.onCreate() returned
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@3d54a168
MainFragment﹕ onCreate() getActivity=com.example.MainActivity@3d54a168

Configuration changed.
Fragment onCreate() not called, but onAttach() still called - you need to know, that hosting Activity has changed. But still fragment is already created, so no onCreate() called.
MainActivity﹕ call super.onCreate() before
MainFragment﹕ onAttach() getActivity=com.example.MainActivity@d7b283e
MainActivity﹕ super.onCreate() returned

A: TL;DR:
In order to not break the design consistency amongst different UI components in android,the onCreate() method will have similar functionality across all of them.
When linking Containers to Contents  like Window to Activity and Activity to Fragment a preliminary check needs to be done to determine the state of container.
And that explains the use and position of onAttach() in the fragment lifecycle.
Too short;Need longer:
The answer is in the archetype code itself,
@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

Another example would be in Jake Wharton's ActionBarSherlock library.
Why would you want to use a method like onCreate() which is has the same purpose in an activity ,service.
The onCreate() is meant to handle issues with respect to that particular context creation.It does not make sense if onCreate() is used to check the state of its container.
The second reason that I can come determine is that a fragment is designed to be activity independent.The onAttach() provides an interface to determine the state/type/(other detail that matters to the fragment) of the containing activity with reference to the fragment before you initialize a fragment.
EDIT:
An activity exists independently and therefore has a self sustaining lifecycle.
for a fragment :

*

*The independent lifecycle components(same as any other components):

*

*onCreate()

*onStart()

*onResume()

*onPause()

*onStop()

*onDestroy()

*The interaction based components:

*

*onAttach()

*onCreateView()

*onActivityCreated()

*onDestroyView()

*onDetach()

from the documentation:

The flow of a fragment's lifecycle, as it is affected by its host
  activity, (...) each successive state of the activity determines which
  callback methods a fragment may receive. For example, when the
  activity has received its onCreate() callback, a fragment in the
  activity receives no more than the onActivityCreated() callback.
Once the activity reaches the resumed state, you can freely add and
  remove fragments to the activity. Thus, only while the activity is in
  the resumed state can the lifecycle of a fragment change
  independently.
However, when the activity leaves the resumed state, the fragment
  again is pushed through its lifecycle by the activity.

answering another question which came up in the comments:

Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.

The design philosophy states that a Fragment is designed for reuse. A fragment (by design) could(and should) be used across multiple activities.
The onCreate by definition is responsible  to create a fragment.
Consider the case of orientation,your fragment could be:
- using different layouts in different orientations.
- applicable only in portrait orientation and not landscape
- To be used only on tables and mobile phones.
All these situations would require a check before the fragment is initialized from the android perspective(onCreate()) and the view inflated(onCreateView()).
Also consider the situation of a headless fragment.The onAttach() provides you the interface required for preliminary checks.

A: Two Points from Android developer Site hints at why onAttach() is called before onCreate() in case of Fragment Life cycle.

*

*A fragment must always be embedded in an activity. Now this means for Fragment to EXIST, there has to be a "living" Activity.
Also, When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy.

So Fragment must FIRST "attach" itself to activity to defines its own view layout

*onCreateis Called to do initial creation of a fragment.

It is obvious that you will create something only when its pre-condition of creation is in place (and the pre-condition is A fragment must always be embedded in an activity, and it must be attached to its Activity)

A: Because onAttach() assigns hosting activity to the Fragment. If it had been called after onCreate() then there would be no context for your fragment (getActivity() would return null) and you would not be able to do anything in onCreate() method without that context anyway.
Another fitting reason is that Fragment's lifecycle is similar to Activity's lifecycle. In Activity.onAttach() activity gets attached to its parent (a window). Similarly in Fragment.onAttach() fragment gets attached to its parent (an activity), before any other initialization is done.


text:
Q: Elasticsearch Transport Client connection I'm building a Search Web Application using Servlet which connects to Elasticsearch. I have a question regarding the Transport module of Elasticsearch. I'm opening the connection to Elasticsearch using the TransportClient in the class that implements ServletContextListener. Below is the code for ElasticsearchServletContextListener class.
public class ElasticsearchContextListener implements ServletContextListener {

  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    System.out.println("Starting up!");

    try {
      Client client = TransportClient.builder().build().addTransportAddress(
          new InetSocketTransportAddress(InetAddress.getByName("IP-address"),9300));
    //Storing the client connection in a static variable
      Parameters.setESclient(client);

    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }

  @Override
  public void contextDestroyed(ServletContextEvent servletContextEvent) {
    Parameters.getESclient().close();
    System.out.println("Shutting down!");
  }
}

Now whenever the user searches for a query it uses the same 'client' connection that is initialized in the ServletContextListener class. Can the client connection handle multiple requests at the same time? Or does every user need a separate client connection to query the elasticsearch? Thank you for your assistance.

A: That Client instance is able to handle multiple calls and handle multiple threads. And you should have one Client instance only as it's expensive to create one.


text:
Q: How to make style in ListView SelectedItem.? I am working on a WPF application and I want to make style on ListViewItem. I have made a style for this but this does not give me the exact result what I want. Apart from this I want CornerRadius in this style so how I can add this?
            <ListView x:Name="MenuBarList"
                    Grid.Row="1"
                    Height="{Binding MainMenuHeight}"
                    Width="{Binding MainMenuWidth}"
                    ItemsSource="{Binding Path=Menu.Options}"
                    SelectedItem="{Binding Path=SelectedMainMenuOption, Mode=TwoWay}"
                    Foreground="White"
                    Background="Transparent"
                    VerticalContentAlignment="Center"
                    HorizontalContentAlignment="Center"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    IsSynchronizedWithCurrentItem="True"
                    IsTabStop="False">

                <ListView.Style>
                    <Style TargetType="{x:Type ListView}">
                        <Setter Property="BorderBrush" Value="White"/>
                        <Setter Property="BorderThickness" Value="0"/>
                        <Setter Property="Margin" Value="0"/>
                        <Setter Property="Width" Value="300"/>
                        <Style.Resources>
                            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#9449b0"/>
                            <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#9449b0"/>
                    </Style.Resources>
                    </Style>
                </ListView.Style>

                <ListView.ItemTemplate>
                    <DataTemplate>

                        <StackPanel Orientation="Horizontal" Focusable="False" VerticalAlignment="Center" HorizontalAlignment="Center">
                            <Image Source="{Binding IconPath}"
                                   Focusable="False"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center"
                                   IsHitTestVisible="False"/>

                            <TextBlock Text="{Binding Title}"
                                       Focusable="False"
                                       HorizontalAlignment="Center"
                                       VerticalAlignment="Center"
                                       FontFamily="Segoe UI"
                                       FontSize="26"
                                       IsHitTestVisible="False"/>
                        </StackPanel>
                </DataTemplate>

                </ListView.ItemTemplate>
            </ListView>

A: Quick solution is to override item template. You may reffer to WPF or Silverlight themes about contols styling. See the BureauBlue.xaml for ListViewItem complete template.
<ListView x:Name="uiList">
    <ListView.Resources>
        <ControlTemplate x:Key="SelectedTemplate" TargetType="ListViewItem">
            <Border SnapsToDevicePixels="true"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}"
                    Background="{TemplateBinding Background}"
                    CornerRadius="5" x:Name="border">
                <ContentControl
                    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                    Margin="2,2,2,2"
                    VerticalAlignment="Stretch"
                    Content="{TemplateBinding Content}" />
            </Border>
        </ControlTemplate>
        <Style TargetType="ListViewItem">
            <Style.Triggers>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsSelected" Value="true" />
                        <Condition Property="Selector.IsSelectionActive" Value="true" />
                    </MultiTrigger.Conditions>
                    <Setter Property="Background" Value="Pink" />
                    <Setter Property="Template" Value="{StaticResource SelectedTemplate}" />
                </MultiTrigger>
            </Style.Triggers>
        </Style>
    </ListView.Resources>
    <ListViewItem Content="10" />
    <ListViewItem Content="11" />
</ListView>


text:
Q: What is the AWS NAT Gateway? I'm not sure what caused it, maybe Elastic Beanstalk, but at some point AWS created me a "NAT Gateway" which costs more than my EC2 server instances themselves.
What does it do, why does it cost so much, and why do I need it for things like EC2?
It seems like I can I do without it, just delete it, and things still work while saving a ton?

A: AWS say

You can use a network address translation (NAT) gateway to enable
  instances in a private subnet to connect to the internet or other AWS
  services, but prevent the internet from initiating a connection with
  those instances. For more information about NAT, see NAT.

In short, it's an internet proxy that lets you initiate outgoing connections, but prevents anyone initiating connections to you. It's for security.
AWS don't tend to create resources without you asking for them. The VPC Wizard will sometimes create one of these when you create your VPC.

A: In short - NAT Gateway provides public internet access to EC2 instances without public IP address.
Whether or not you can remove the NAT Gateway depends on your VPC and EC2 configuration.

*

*If your EC2 instance is in a subnet with IGW (Internet Gateway) and has public or elastic IP attached then you don't need NAT gateway.

*If your EC2 instance is in a subnet without IGW you do need NAT gateway.
If you want to remove the NAT gateway make sure your EC2 instance has a public IP attached to it an it's in a subnet with IGW.
Also note that adding a public IP to your instance puts it directly on the public internet - double check the instance Security Group (i.e. firewall) to ensure it's locked down as much as possible.


text:
Q: Get Current Date from TXT/LOG File Just started using LogParser recently, and I'm new to SQL queries.
I'm trying to get LogParser to find a log file with today's date, then outputting specific contents of the file into a text document. For example:
Select Text INTO D:\LogParser\output\BlahYYYY-MM-DD.txt
From 'C:\Logs\BlahYYYY-MM-DDBlah.log'
where Text like '%exception%'

How do I get my query to search for today's date in the file name, while keeping the YYYY-MM-DD format, and output to a text file with the same date and format?

A: Unfortunately there is no way to use functions in the FROM (nor in the INTO) clause.
If you can get the date from some other means, you could save the query to a file, specify e.g. %MYDATE% instead of the date, and then run the query specifying the parameter values as follows:
LogParser file:myQuery.sql?MYDATE=...


text:
Q: MySQLi multiple conditions, what's wrong I am trying to do prepared statements as follows:
    $stmt = $mysqli->prepare("SELECT COUNT(*) FROM table WHERE from = '?' && to = '?' LIMIT 1");
    $stmt->bind_param('ii', $fromId, $toId);
    $stmt->execute();
    $stmt->bind_result($db_offeredAlready);
    $stmt->fetch();
    $stmt->close();

I get the following error:
 Fatal error: Call to a member function bind_param() on a non-object in /path/to/script.php on line 97

Adding ` and ' gives me
    $stmt = $mysqli->prepare("SELECT COUNT(*) FROM `table` WHERE `from` = '?' && `to` = '?' LIMIT 1");

and the following
 Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in /path/to/script.php on line 97

Obviously the number of BIND vars match the number of ? marks.  I have tried all combinations of adding and removing ` and ' to no avail.  What's wrong with this prepared statement?  I can do a SELECT with one condition just fine, but it complains with multiple.

A: Placeholders  (?) need not to be quoted.
$stmt = $mysqli->prepare("SELECT COUNT(*) FROM `table` WHERE `from` = ? && `to` = ? LIMIT 1");


text:
Q: front camera take very dark capture in android I am taking photo capture using front camera using my custom camera app not using system camera app.But the captured photo is very dark so can see photo properly.
my code
mCamera = Camera.open(1);
Camera.Parameters params =mCamera.getParameters();
params.setSceneMode(Camera.Parameters.SCENE_MODE_NIGHT);
mCamera.setParameters(params);

And to take picture
if (mCamera != null) {
try {
 mCamera.setPreviewDisplay(mSurfaceHolder);
 mCamera.startPreview();
 mCamera.takePicture(null, mPictureCallback,
 mPictureCallback);
} catch (IOException e) {
 e.printStackTrace();
    }
}

Thanks in advance. Please give me suggestions. any help will be appreciated.

A: I have found following solution for this, And that worked for me
Wait for some time  i.e. 500 ms before capture image using
mCamera.takePicture(null, mPictureCallback,mPictureCallback);

A: To solve this problem you could take the picture after some time. Try this:
new Handler().postDelayed(new Runnable() {
  @Override
  public void run() {
      camera.takePicture(null, null, cameraCallback);
  }
}, 1000);

A: All the answers in this thread mention an arbitrary delay where as the root cause of this problem is not addressed.
The camera in an android phone does the autofocus activity after the start of the preview and before capturing the picture. The code snippet in the question mentions call to mCamera.takePicture(null, mPictureCallback,mPictureCallback); right after mCamera.startPreview();.
Taking the picture during the autofocus process gives rise to the exposure issues in the image captured, resulting into dark photos. The delays mentioned in the answers give android the time to complete its autofocus and the image captured is perfect. This might not be the case with every device and an arbitrary number may result into failure on some devices.
My recommendation would be following code snippet -
Camera.AutoFocusCallback autoFocusCallBack = new Camera.AutoFocusCallback();
static autoFocusCallBack(){
    mCamera.takePicture(null, mPictureCallback,
     mPictureCallback);
}
if (mCamera != null) {
   try {
     mCamera.setPreviewDisplay(mSurfaceHolder);
     mCamera.startPreview();
     mCamera.autoFocus(autoFocusCallBack);
    } catch (IOException e) {
       e.printStackTrace();
    }
 }

This flow ensures that the takePicture() is called in the autofocus callback implying autofocus was successful. This will give a proper image with appropriate exposure and brightness.
This will also remove the arbitrary delay.
Read this link for Camera.AutoFocus().
Read this link for Camera.takePicture().
Read this link for Camera.startPreview().


text:
Q: copied Xcode 5 Button does not correctly center align in IB in xcode 7 for all sizes I have read through several tutorials and stack overflow posts about this but I can't get it to work.
Here is what I'm doing:

*

*Create fresh Xcode project

*Add Button to center of default view in IB

*Make sure size is set to Any, Any

*click align button in lower right corner to Add New Alignment Constraint

*Check box for Horizontally in Center: 0

This works as expected. However, if I copy and paste a button from an existing project, and go through the same steps, I encounter problems.
For example, if I resize to a compact width, the new, copied button is not centered, and instead has a +100.5 next to its constraint.
I have compared the settings of the two buttons and they are the same.
What is the issue here?
I have a number of views from an old project (xcode 5) that I would not like to create, but all elements have this issue.

A: Just for future reference to this issue, the issue was related to not adding constraints on the second screen. One easy way to do that is by asking Xcode to add suggested constraints for you.
When you drag your button in the middle of screen, you can see that Xcode gives you some hints and shows you horizontal and/or vertical lines when you move the view in the middle of the screen. You can make sure that the view is in the middle of the screen if you can see both horizontal and vertical lines:

And then you can ask Xcode to add missing constraints for you by tapping the first item in the lower right, and choose Add Missing Constraints

For more information on Auto Layout and how to use it, I would suggest checking out Auto Layout sessions in Apple WWDC sessions.


text:
Q: Оператор приведения типа для объектных типов Есть два
NSNumber *floatNumber

содержащие дробные значения.
Каким образом привести значения этих объектов к целочисленным(оставить значение просто отбросив дробную часть) и каким образом их потом сравнить уже как целочисленные (то есть не приводя их к примитивным типам а оставив объектными) ? Для сравнения использовать  метод isEqualToNumber или что-то иное?
A: Для возвращения целочисленного значения используйте [floatNumber intValue] либо [floatNumber integerValue]
В первом случае возвращается тип int, во втором же - NSInteger.
PS Да, для сравнения лучше использовать isEqualToNumber.


text:
Q: CUrl PUT with xml data I'm facing a problem with curl as I am unable to issue a PUT request with inline XML data, I'm not sure how its done but I hade a couple of goes on it with different techniques. First I tried using the CURLOPT_UPLOAD as its the default CURL option for PUT and tried to append the xml data manually:
    typedef map<string, string> headers_t;
    std::string strCommand = <XMLCOMMAND>

PUTRequest(param1, param2, ...)
    {
...
    headers_t headers;
    int nLen = strCommand.length();
    stringstream issLen;
        issLen << nLen;
        issLen >> strln;
    curl_easy_setopt(curl, CURLOPT_UPLOAD, true); // HTTP PUT
    headers.append("Content-Length: "+ strln); //
    headers.append(strCommand);
...
    }

Then I tried the same method but using the CURLOPT_POSTFIELDS and CURLOPT_POSTFIELDSIZE instead of manually appending the command to the HTTP headers.... did not work.
Then I tried customizing the PUT request using the CURLOPT_CUSTOMREQUESToption and setting the parameter to PUT and also manually appending the command and using the POSTFIELDS method.
Sadly none worked and now I'm clueless as of what to try next.

A: When using CURLOPT_UPLOAD, you are appending the XML to the headers of the request rather then to the body where it belongs.  You need to use CURLOPT_READDATA (with CURLOPT_READFUNCTION if your XML is not in a file) to provide the XML data when curl asks for it, and also use CURLOPT_INFILESIZE/CURLOPT_INFILESIZE_LARGE so curl can generate a proper 'Content-Length' header (don't append that header manually).
If you use CURLOPT_POST, then use CURLOPT_POSTFIELDS and CURL_POSTFIELDSIZE/CURLOPT_POSTFIELDSIZE_LARGE to provide the actual XML data, but then you also have to use CURLOPT_HTTPHEADER to override the default 'Content-Type' header so you can change it from the default value of 'application/x-www-form-urlencoded' to 'text/xml' instead.


text:
Q: How get text from htmlEditor ? I want   get text from htmlEditor ? It's possible ?
example of creating form :
  Ext.onReady(function(){
        var formPanel = Ext.create('Ext.Panel', {
            title: 'Редактор текста',
            width: 350,
            height:200,
            layout: 'fit',
            items: [{
                xtype: 'htmleditor',
                id:'s78d',
                     name: 'msg',
            value : 'abcd',
            id: 'myeditor'
            }],
            renderTo: Ext.getBody()
        });
    });

Thank you.

A: Decide which id property you actually want to use (remove the other) then try some thing like:
var editorValue = Ext.getCmp('myeditor').getValue();

» fiddle


text:
Q: How to define an empty vector to store 'names' in R? I want to store names in other vector. So, first I will have to create an empty vector to store these names.
I know how to define numeric vector. g <- numeric(length=10). But not sure about how to define vector to store names.

A: Another option :
  names_vec  <- vector(mode='character',length=10)

A: This does the trick:
names_vec = character(length = 10)

A: If you do not know the number of values in advance, you can start with an empty vector and append to it. This is slow, so don't do it for large quantities of data.
names <- c()
for (r in 1:numNames) {
  names <- append(names, "someName")
}


text:
Q: SDL keyboard strange behaviors Only function keys get caught by SDL_KEYDOWN and they get printed normally , normal letters and numbers sometimes get caught by  SDL_TEXTINPUT(unpredictably) but when i try to print them i get either nothing or things like "Æëçó" , the key dosen't get caught at all by the if statement . Does anyone have the same problem ?
This is on win 10 Visual Studio 19 and i get the same results when using on screen keyboard .
switch (g_event->type)
    {
        case SDL_KEYDOWN: //here only ctrl , alt , caps get caught
            std::cout << SDL_GetKeyName(g_event->key.keysym.sym); //this prints out the names correctly
            break;
        case SDL_TEXTINPUT: //here normal keys get caught sometimes(letters,numbers...)
            std::cout << SDL_GetKeyName(g_event->key.keysym.sym); //this prints out things like this "ⁿÆëçó" or nothing at all
            if(g_event->key.keysym.sym==SDLK_f)   //the key isn't caught no matter what
            {std::cout<<"f";}
            break;
    }

A: You would not access g_event.key.keysym.sym in a SDL_TEXTINPUT event.
It gives you a parameter as g_event.text.text where you have the inputed text as a char array.


text:
Q: swift ios why use didSet in this example I am trying to understand why didSet it used in this example. Its a piece from a pagecontroller that displays images (image slider)
Code:
import UIKit

class PageItemController: UIViewController {

    // MARK: - Variables
    var itemIndex: Int = 0
    var imageName: String = "" {

        didSet {

            if let imageView = contentImageView {
                imageView.image = UIImage(named: imageName)
            }

        }
    }

    @IBOutlet var contentImageView: UIImageView?

    // MARK: - View Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        print(imageName)
        contentImageView!.image = UIImage(named: imageName)

    }
}

I have tried the same code but wihtout the didSet and I dont notice any changes in speed etc, so why is it used?

A: Actually didSet will set the uiimage with imageName string if imageName is set.
If you are assigning imageName from anyother view then, You should use the code like :
override func viewDidLoad() {
        super.viewDidLoad()
    }

A: If you use didSet you can change your displayed Image by setting imageName.

A: Rather use this:
let image = UIImage(named: "*Name of image in assets*")
 and make sure the actual image is in the project assets.


text:
Q: Identifying controls uniquely in an SWT application How to identify controls in an SWT application uniquely? Some Controls may be inactive at first but later activated. Is there a way to identify and assign unique ids to all the controls?

A: You can associate arbitrary data with a control using the setData and getData methods:
control.setData("id key", "control id");

String id = (String)control.getData("id key");

A: Every SWT widget (org.eclipse.swt.widgets.Widget) has:

getData
public Object getData(String key)
Returns the application defined property of the receiver with the specified name,
  or null if it has not been set.
  Applications may have associated arbitrary objects with the receiver in this
  fashion. If the objects stored in the properties need to be notified when the
  widget is disposed of, it is the application's responsibility to hook the Dispose
  event on the widget and do so.

You can use this is conjunction with public void setData(String key, Object value)


text:
Q: Calling strange field of JSON in NodeJS im working with NodeJS and services SOAP in XML.
To call the soap I use strong-soap and to transform XML in JSON use xml2js.
All ready works good, the response shows like:
{ 'SOAP-ENV:Envelope':     { '$':
      { 'xmlns:SOAP-ENV': 'http://schemas.xmlsoap.org/soap/envelope/',
        'xmlns:ns1': 'http://sandbox.coordinadora.com/agw/ws/guias/1.5/server.php',
        'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
        'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
        'xmlns:SOAP-ENC': 'http://schemas.xmlsoap.org/soap/encoding/',
        'SOAP-ENV:encodingStyle': 'http://schemas.xmlsoap.org/soap/encoding/' },
     'SOAP-ENV:Body': [ [Object] ] } }

But in javascript I can call response.SOAP-ENV:Body because show me error.
What I can do to handle this data?

A: - and : aren't valid characters in javascript variables, so you'll have to use bracket notation like this:
let body = response['SOAP-ENV:Body']


text:
Q: Git Auto pull from Azure Repos and run on VM I am not very good at Git, I have a project to run same python code located in AzureDevops Repos on multiple VMs.
How can I create a .bat file that pulls code from AzureDevops Repo and run on VM? I need it because in case there are some changes needed to be applied on the code, I will not need to go to each VM to change and save it.

A: If you want to use .bat file to pulls code from AzureDevops Repo and run on VM through command, please see whether the following steps help:
1.Click the 'copy' icon to get the URL.

2.Go to the folder that you would like to save the .bat file and the git file. Create a .txt file and write 'git clone URL' in it, save and close, modify the file name as ***.bat.

Create a .txt file and write the added content(here I use it as example, you could add wanted command here), then do 'git add .''git commit -m""'and 'git push'.save and close, modify the file name as *****.bat.
cd a1p
echo hello world(echo to add content) >> README.md (the modified file name)
echo How are you? >> README.md
type README.md
git add .
git commit -m"goodcommit1"(name your commit)
git push

3.Double click ***.bat first and after it finishes, click *****.bat file.
you will get things like this when double click the ***.bat file:

It will automatically close when finishing the clone. And here you could see the folder named a1p in the target folder.
Then double click *****.bat file, after it finish, you will see these like this in the README file:

Push the changes to your repo then you could pull it to other VMs with the changes. Hope it could do some help.


text:
Q: Encapsulating async method in Task.Factory.StartNew I have a good understanding of Task and the async/await pattern but recently someone fixed a deadlock that he said was caused by :
public async Task<HttpResponseMessage> GetHttpResponse()
{
    using (var client = new HttpClient())
    {
        return await client.SendAsync(new HttpRequestMessage()).ConfigureAwait(false);
    }
}

He says that he fixed it with some kind of Task.Factory.StartNew pattern.
public HttpResponseMessage GetHttpResponse()
{
    using (var client = new HttpClient())
    {
        return Task.Factory.StartNew(() => client.SendAsync(new HttpRequestMessage()).Result).Result;
    }
}

First thing is that troubles is me is why would he change the return statement to be an HttpResponseMessage as opposed to a Task<HttpResponseMessage>.
My second question, is why would this code solve a deadlock bug. From my understanding, the fact that he calls a .Result forces the GetHttpResponse Thread to wait (and freeze) until the client.SendAsync completes.
Can anyone try to explain me how this code affects any TaskScheduler and SynchronizationContext.
Thank you for your help.
EDIT : Here is the caller method to provide more context to the problem
public IWebRequestResult ExecuteQuery(ITwitterQuery twitterQuery, ITwitterClientHandler handler = null)
{
    HttpResponseMessage httpResponseMessage = null;

    try
    {
        httpResponseMessage = _httpClientWebHelper.GetHttpResponse(twitterQuery, handler).Result;

        var result = GetWebResultFromResponse(twitterQuery.QueryURL, httpResponseMessage);

        if (!result.IsSuccessStatusCode)
        {
            throw _exceptionHandler.TryLogFailedWebRequestResult(result);
        }

        var stream = result.ResultStream;

        if (stream != null)
        {
            var responseReader = new StreamReader(stream);
            result.Response = responseReader.ReadLine();
        }

        return result;
    }
// ...

A: Modified code to fix the deadlock is very poor usage of Task APIs, I can see so many issues there:

*

*It has converted the Async call to Sync call, It is a blocking call due to usage of Result on the Task

*Task.Factory.StartNew, is a big No, check StartNew is Dangerous by Stephen Cleary
Regarding your original code, following is the most probable reason for deadlock:

*

*Reason why ConfigureAwait(false) doesn't work is you need to use it in complete Call stack in all the Async calls, that's why it is leading to Deadlock. Point is client.SendAsync and complete call chain needs to have a ConfigureAwait(false), for it to ignore the Synchronization context. It doesn't help to be just in one place and there's no guarantee for calls which are not in your control

Possible Solution:

*

*Here the simple removal shall work, you don't even need Task.WhenAll, as there are no multiple tasks
 using (var client = new HttpClient())
{
    return await client.SendAsync(new HttpRequestMessage());
}

Another not so preferred option would be:

*

*Make your code Synchronous as follows (now you don't need ConfigureAwait(false) in whole chain):
public HttpResponseMessage GetHttpResponse()
{
   using (var client = new HttpClient())
   {
       return await client.SendAsync(new
         HttpRequestMessage()).ConfigureAwait(false).GetAwaiter().GetResult();
  }
}

A: The deadlock wasn't caused by return await client.SendAsync(new HttpRequestMessage()).ConfigureAwait(false);. It was caused due to a blocking call down the stack. Since it is very unlikely that MS implementation of HttpClient.SendAsync() has some blocking code inside (which might deadlock), it must be one of the callers to public async Task<HttpResponseMessage> GetHttpResponse() that use .Wait() or .Result on the returned Task. All your colleague did is to move the blocking call up the stack, where it is more visible. Further more, this "fix" does not even solve the classic deadlock since it use the same synchronization context(!). You can deduce that somewhere else down the stack some other function offloads a new Task without asp.net synchronization context, and in that new (probably default) context your blocking GetHttpResponse() executes, otherwise the "fix" would have deadlock too!
Since in the real world it is not always possible to refactor production legacy code to be async all the way, you should use your own interface of async HttpClient, and make sure the implementation use .ConfigureAwait(false), as all infrastructure libraries should.

A: @mrinal-kamboj @panagiotis-kanavos @shay
Thank you all for your help. As mentioned I have started to read the Async in C# 5.0 from Alex Davies.
What I found
In Chapter 8 : Which Thread Runs My Code, he mentions our case and I think I found an interesting solution there :

You can get around the deadlock problem by moving to the thread pool before starting the async code, so that the SynchronizationContext captured is the thread pool rather than the UI thread.

var result = Task.Run(() => MethodAsync()).Result;

By calling Task.Run he actually forces the async call SynchronizationContext to be the SynchronizationContext of a ThreadPool (which makes sense). By doing so he also insures that the code MethodAsync is neither started nor returned to the main thread.
My solution
By taking this into consideration I changed my code as followed :
public HttpResponseMessage GetHttpResponse()
{
    using (var client = GetHttpClient())
    {
        return TaskEx.Run(() => client.SendAsync(new HttpRequestMessage())).Result;
    }
}

This code seems to work properly for Console, WPF, WinRT and ASP.NET. I will conduct further testing and update this post.
Questions

*

*Do you think this new code makes sense?

*Do you think it will prevent any potential deadlock?

NOTE
In the book, I learnt that .ConfigureAwait(false) only prevents the callback to call the SynchronizationContext.Post() method to be run on the caller Thread. To determine the thread the callback should run on, the SynchronizationContext check if the thread it is associated with is important. If it is, then it picks another thread.
From my understanding it means that the callback can be run on any thread (UI-Thread or ThreadPool). Therefore it does not guarantee a non-execution on the UI-Thread but makes it very unlikely.
NOTE (2)
It is interesting to note that the following code does not work :
public async Task<HttpResponseMessage> GetHttpResponse()
{
    using (var client = GetHttpClient())
    {
        return await TaskEx.Run(() => client.SendAsync(new HttpRequestMessage()));

When I attempted to have this code I had in mind that the the .Result could be used outside of the scope of the ThreadPool awaited .Result. To some extent it makes sense to me but if any one wants to comment on this too, he will be welcome :)

A: I think adding ConfigureAwait to your Note(2) code would have made it work.
The ASP.NET context only allows 1 thread to run in it at a time. The Thread pool context allows more than 1 thread at a time to run.
The await returns code execution back to the calling method. The calling method is on the ASP.net context and the call to .Result blocks. When client.SendAsync returns it goes to finish the method on the ASP.net context but can't because there is already a thread in the context blocking (for .Result).
If you used ConfigureAwait with  client.SendAsync, it would be able to finish the method in a different context than the ASP.Net context and finish off the method to get to .Result in the calling method.
i.e. .Result is waiting for the end of the GetHttpResponse method to finish while the end of the GetHttpResponse method is waiting for. Result to get out of the ASP.net context to finish.
In your original example it was .Result in the calling method blocking while client.SendAsync was waiting for .Result to get out of the ASP.net context to continue. Like you said ConfigureAwait(false) only affects the context on the code executing from the return after await. While Client.SendAsync is waiting to get into the ASP.NET context to execute.


text:
Q: How reliable is using TrueTime for getting device independent time? I recently found a library called TrueTime for getting the time which does not depend on device time. It uses NTP to get the time.
https://github.com/instacart/TrueTime.swift
As this library is primarily built for swift 3. But I found a post in which there were some changes made in files to make it swift 4 compatible.
https://github.com/instacart/TrueTime.swift/issues/39
As I am using swift & using pod for this library. I unlocked the pods & made changes in the library to make work with swift 4.
How reliable is this library?
My concerns are

*

*Apple approval after submitting an app.

*Support for coming swift & iOS versions.
Are there better alternatives to this library?

A: Apple definitely won't reject that. It's not in the Review Guidelines. I even have an app that uses TrueTime on the app store.
Regarding reliability, if you mean reliability by "how reliable it is to get correct true time", then it's quite reliable. It seems like that the library gets the time from time.apple.com. That seems to be from Apple, so I would say you can rely on it.
If you mean reliability by "how reliable it is to make successful requests" then that depends a lot: the user's Internet connection, bugs in the TrueTime library etc. According to the README,

*

*Reachability events are automatically accounted for to pause/start
  requests.

*UDP requests are executed in parallel, with a default limit of 5
  parallel calls. If one fails, we'll retry up to 3 times by default.

So that's how the requests will behave.


text:
Q: How to create initial value for .reduce based on enum? I have a reduced function that needs initial values based on an enum. See simplified code below:
items.reduce<Record<RoleType, Community[]>>(
    (acc, community) => {
        ... // this works
    },
    { [RoleType.LEADER]: [], [RoleType.FACILITATOR]: [], [RoleType.EDITOR]: [], [RoleType.EXPERT]: [], [RoleType.MEMBER]: [] }
);

The enum looks like this:
export enum RoleType {
    EXPERT = 'EXPERT',
    LEADER = 'LEADER',
    FACILITATOR = 'FACILITATOR',
    EDITOR = 'EDITOR',
    MEMBER = 'MEMBER'
}

I don't want to explicitely list every member of the enum though. I tried with the following:
{ ...Object.values(RoleType).map((role) => ({ [role]: [] })) }

Is there a way to simply add empty arrays for all of the enum's members? Best case would be if there was proper typing too.
My attempt above throws this error (which I really don't know what to do with):

Type '{ [n: number]: { [x: string]: any[]; }; length: number; toString(): string; toLocaleString(): string; pop(): { [x: string]: any[]; }; push(...items: { [x: string]: any[]; }[]): number; concat(...items: ConcatArray<{ [x: string]: any[]; }>[]): { ...; }[]; concat(...items: ({ ...; } | ConcatArray<...>)[]): { ...; }[];...' is missing the following properties from type 'Record<RoleType, Community[]>': EXPERT, LEADER, FACILITATOR, EDITOR, MEMBER

A: { ...Object.values(RoleType).map((role) => ({ [role]: [] })) }

will create an object with indices of the array as key.
{
  "0": { "EXPERT": [] },
  "1": { "LEADER": [] },
  "2": { "FACILITATOR": [] }
  ...
}

You need to use something like this:
Object.assign({}, ...Object.values(RoleType).map(r => ({ [r]: [] })))

A: I have made a TS transformer that allows you to grab, amongst others, all values of an enum - it's called ts-reflection and it works like this:
enum MyEnum {
  NO = 0,
  MAYBE = 1,
  YES = 2
}

const valuesOfMyEnum = valuesOf<MyEnum>(); // [0, 1, 2]

Here's how you set it up


text:
Q: GO REST Endpoint for File Uploads But Not Using ParseMultipartForm Newbie here. I'm trying to build a web server with a RESTful API so that I can test a curl command for file uploads. I was able to create the web server and an endpoint for file uploads.
Here is my upload endpoint:
func Upload(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseMultipartForm(MAX_MEMORY); err != nil {
        log.Println(err)
        http.Error(w, err.Error(), http.StatusForbidden)
    }

    fmt.Println("Endpoint hit: Upload")

    for key, value := range r.MultipartForm.Value {
        fmt.Fprintf(w, "%s:%s ", key, value)
        log.Printf("%s:%s", key, value)
    }

    for _, fileHeaders := range r.MultipartForm.File {
        for _, fileHeader := range fileHeaders {
            file, _ := fileHeader.Open()
            path := fmt.Sprintf("files/%s", fileHeader.Filename)
            buf, _ := ioutil.ReadAll(file)
            ioutil.WriteFile(path, buf, os.ModePerm)
            log.Println(http.StatusOK, fmt.Sprintf("file %s has been uploaded", fileHeader.Filename))
        }
    }
}

This endpoint works with the following curl command:
curl -F 'data=@/path/to/file/foo.tar.gz' localhost:8080/upload

However, this curl command does not:
curl -f -s -S -T /path/to/file/foo.tar.gz http://localhost:8080/upload
curl: (22) The requested URL returned error: 405 Method Not Allowed

I need help creating an endpoint that will accept
curl -f -s -S -T /path/to/file/foo.tar.gz http://localhost:8080/upload

Thank you.
Edit: Here is my routes.go file.
package main

import (
    "net/http"
    "github.com/gorilla/mux"
)

type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

func NewRouter() *mux.Router {
    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        router.
        Methods(route.Method).
        Path(route.Pattern).
        Name(route.Name).
        Handler(route.HandlerFunc)
    }

    return router
}

var routes = Routes{
    Route{
        "Index",
        "GET",
        "/",
        Index,
    },
    Route{
        "Upload",
        "POST",
        "/upload",
        Upload,
    },
}

A: Using curl -f -s -S -T /path/to/file/foo.tar.gz http://localhost:8080/upload without any additional options that would set the content type, if there are such options (i'm not sure, my curl knowledge is almost non existent), you are sending a request with minimal headers, none of them indicating the type of the content.
For example logging the r.Header will print something like this:
map[Accept:[*/*] Content-Length:[18] Expect:[100-continue] User-Agent:[curl/7.54.0]]

This means that all that multipart code in your Upload handler is simply not necessary.

The content of the body is what you want, so you can use io.Copy to store that body into a file.
func Upload(w http.ResponseWriter, r *http.Request) {
    f, err := os.Create("filename")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    if _, err := io.Copy(f, r.Body); err != nil {
        panic(err)
    }
    if err := f.Sync(); err != nil {
        panic(err)
    }
    fmt.Fprintln(w, "upload done...")
}

Since you're using curl -f -s -S -T ... the Upload handler does not know what the name, nor the type, of the file being uploaded is, you will have to generate a random name, or a timestamp name, or whatever in order to be able to create and store more than just one file.
You could also pass some of the file info (name, type) in the query parameters but i'm not sure if that satisfies your requirements. E.g.
curl -f -s -S -T /path/to/file/foo.tar.gz http://localhost:8080/upload?name=foo.tar.gz


text:
Q: Equation for Cube Edge-Lenth y that results in n-number of points with spacing x I would need to find an equation that gives me the edge length l of a 3D cube that results in a specific number of points n inside the cube when their spacing is x. It's probably similar to the below but in 3D and simpler as edge length in XYZ is constant. For now, I assume that the point spacing x in XYZ is constant.
How to evenly space a number of points in a rectangle?
For constant d as described by @achille hui
l=x⌈(n^(1/3))−1⌉
How would this change for different x along different dimensions?