text:
Q: 2D Array with variable size What I'm trying to accomplish is have something like
String[][] array = new String[sizeX][sizeY]

SizeX would be based on the length of a root JSON array, and sizeY based on the length of an array inside the root JSON array.
Thinking about it, I could use a single array of arrays, but I'm not sure how I'd reference the internal array to get information back from it. For example:
String[] array = new String[sizeX];
array[i] = new String[sizeY]; // initialized to variable size of JSON

From here, how would I reference the internal array the objects in the internal array?
The JSON
{"23591778": {
   "pages": [
      {
         "masteries": [
            {
               "id": 4211,
               "rank": 2
            },
            {
               "id": 4214,
               "rank": 2
            },
            {
               "id": 4134,
               "rank": 3
            },
            {
               "id": 4124,
               "rank": 1
            },
            {
               "id": 4114,
               "rank": 1
            },
            {
               "id": 4222,
               "rank": 3
            },
            {
               "id": 4112,
               "rank": 4
            },
            {
               "id": 4221,
               "rank": 1
            },
            {
               "id": 4144,
               "rank": 1
            },
            {
               "id": 4122,
               "rank": 3
            },
            {
               "id": 4152,
               "rank": 3
            },
            {
               "id": 4141,
               "rank": 1
            },
            {
               "id": 4111,
               "rank": 1
            },
            {
               "id": 4132,
               "rank": 1
            },
            {
               "id": 4232,
               "rank": 1
            },
            {
               "id": 4162,
               "rank": 1
            },
            {
               "id": 4131,
               "rank": 1
            }
         ],
         "id": 34787712,
         "name": "Blind",
         "current": false
      },
      {
         "masteries": [
            {
               "id": 4212,
               "rank": 2
            },
            {
               "id": 4233,
               "rank": 3
            },
            {
               "id": 4242,
               "rank": 1
            },
            {
               "id": 4214,
               "rank": 2
            },
            {
               "id": 4114,
               "rank": 1
            },
            {
               "id": 4251,
               "rank": 1
            },
            {
               "id": 4112,
               "rank": 4
            },
            {
               "id": 4222,
               "rank": 3
            },
            {
               "id": 4122,
               "rank": 3
            },
            {
               "id": 4262,
               "rank": 1
            },
            {
               "id": 4224,
               "rank": 1
            },
            {
               "id": 4252,
               "rank": 3
            },
            {
               "id": 4132,
               "rank": 1
            },
            {
               "id": 4241,
               "rank": 3
            },
            {
               "id": 4232,
               "rank": 1
            }
         ],
         "id": 34787713,
         "name": "AD/Tank Jungle",
         "current": false
      },
      {
         "masteries": [
            {
               "id": 4242,
               "rank": 1
            },
            {
               "id": 4233,
               "rank": 3
            },
            {
               "id": 4243,
               "rank": 1
            },
            {
               "id": 4211,
               "rank": 2
            },
            {
               "id": 4214,
               "rank": 2
            },
            {
               "id": 4213,
               "rank": 2
            },
            {
               "id": 4114,
               "rank": 1
            },
            {
               "id": 4252,
               "rank": 2
            },
            {
               "id": 4222,
               "rank": 3
            },
            {
               "id": 4113,
               "rank": 4
            },
            {
               "id": 4221,
               "rank": 1
            },
            {
               "id": 4123,
               "rank": 3
            },
            {
               "id": 4262,
               "rank": 1
            },
            {
               "id": 4224,
               "rank": 1
            },
            {
               "id": 4133,
               "rank": 1
            },
            {
               "id": 4234,
               "rank": 1
            },
            {
               "id": 4232,
               "rank": 1
            }
         ],
         "id": 34787714,
         "name": "Mumu",
         "current": true
      },
      {
         "masteries": [
            {
               "id": 4211,
               "rank": 2
            },
            {
               "id": 4121,
               "rank": 1
            },
            {
               "id": 4214,
               "rank": 2
            },
            {
               "id": 4134,
               "rank": 3
            },
            {
               "id": 4114,
               "rank": 1
            },
            {
               "id": 4222,
               "rank": 3
            },
            {
               "id": 4112,
               "rank": 4
            },
            {
               "id": 4144,
               "rank": 1
            },
            {
               "id": 4221,
               "rank": 1
            },
            {
               "id": 4152,
               "rank": 3
            },
            {
               "id": 4122,
               "rank": 3
            },
            {
               "id": 4141,
               "rank": 1
            },
            {
               "id": 4111,
               "rank": 1
            },
            {
               "id": 4132,
               "rank": 1
            },
            {
               "id": 4232,
               "rank": 1
            },
            {
               "id": 4162,
               "rank": 1
            },
            {
               "id": 4131,
               "rank": 1
            }
         ],
         "id": 34787715,
         "name": "vi/j4/wuk/xin/noc",
         "current": false
      },
      {
         "masteries": [
            {
               "id": 4212,
               "rank": 2
            },
            {
               "id": 4353,
               "rank": 3
            },
            {
               "id": 4211,
               "rank": 2
            },
            {
               "id": 4311,
               "rank": 1
            },
            {
               "id": 4362,
               "rank": 1
            },
            {
               "id": 4322,
               "rank": 3
            },
            {
               "id": 4334,
               "rank": 1
            },
            {
               "id": 4332,
               "rank": 1
            },
            {
               "id": 4352,
               "rank": 1
            },
            {
               "id": 4222,
               "rank": 3
            },
            {
               "id": 4314,
               "rank": 1
            },
            {
               "id": 4221,
               "rank": 1
            },
            {
               "id": 4331,
               "rank": 3
            },
            {
               "id": 4324,
               "rank": 1
            },
            {
               "id": 4313,
               "rank": 3
            },
            {
               "id": 4232,
               "rank": 1
            },
            {
               "id": 4342,
               "rank": 1
            },
            {
               "id": 4341,
               "rank": 1
            }
         ],
         "id": 34787716,
         "name": "Support",
         "current": false
      },
      {
         "masteries": [
            {
               "id": 4211,
               "rank": 2
            },
            {
               "id": 4214,
               "rank": 2
            },
            {
               "id": 4124,
               "rank": 1
            },
            {
               "id": 4114,
               "rank": 1
            },
            {
               "id": 4112,
               "rank": 4
            },
            {
               "id": 4222,
               "rank": 3
            },
            {
               "id": 4113,
               "rank": 4
            },
            {
               "id": 4122,
               "rank": 3
            },
            {
               "id": 4152,
               "rank": 3
            },
            {
               "id": 4224,
               "rank": 1
            },
            {
               "id": 4132,
               "rank": 1
            },
            {
               "id": 4142,
               "rank": 3
            },
            {
               "id": 4232,
               "rank": 1
            },
            {
               "id": 4162,
               "rank": 1
            }
         ],
         "id": 34787717,
         "name": "AD Jungle",
         "current": false
      },
      {
         "masteries": [
            {
               "id": 4212,
               "rank": 2
            },
            {
               "id": 4211,
               "rank": 2
            },
            {
               "id": 4121,
               "rank": 1
            },
            {
               "id": 4134,
               "rank": 3
            },
            {
               "id": 4124,
               "rank": 1
            },
            {
               "id": 4114,
               "rank": 1
            },
            {
               "id": 4222,
               "rank": 3
            },
            {
               "id": 4112,
               "rank": 4
            },
            {
               "id": 4221,
               "rank": 1
            },
            {
               "id": 4122,
               "rank": 3
            },
            {
               "id": 4152,
               "rank": 3
            },
            {
               "id": 4141,
               "rank": 1
            },
            {
               "id": 4142,
               "rank": 1
            },
            {
               "id": 4132,
               "rank": 1
            },
            {
               "id": 4232,
               "rank": 1
            },
            {
               "id": 4162,
               "rank": 1
            },
            {
               "id": 4131,
               "rank": 1
            }
         ],
         "id": 34787718,
         "name": "ADC",
         "current": false
      },
   ],
   "summonerId": 23591778
}}

A: UPDATE: since you updated your post with more info, here is my new answer.
You don't have a JSON array of JSON arrays, but an array of JSON objects. These objects, in turn, have one property that is a map (I believe), but it does not matter. You're trying to use a 2D-array instead of a 1D-array of objects.
Create a class to represent your objects:
public class MasteryPage {
    private long id;
    private String name;
    private boolean current;
    private Map<Long,Integer> masteries = new HashMap<>();

    public MasteryPage(long id, String name, boolean current) {
        this.id = id;
        this.name = name;
        this.current = current;
    }

    public void addMastery(long id, int rank) {
        masteries.put(id, rank);
    }

    // add getters/setters...
}

Then use your class to create the array:
JSONArray jArray = json.getJSONArray("pages");
MasteryPage[] arr = new MasteryPage[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
    JSONObject jsonMasteryPage = jArray.getJSONObject(i);
    long id = jsonMasteryPage.getLong("id");
    String name = jsonMasteryPage.getString("name");
    boolean current = jsonMasteryPage.getBoolean("current");
    MasteryPage page = new MasteryPage(id, name, current);
    JSONArray jsonMasteries = jsonMasteryPage.getJSONArray("masteries");
    for (int j = 0; j < jsonMasteries.length(); j++) {
        JSONObject jsonMastery = jsonMasteries.getJSONObject(i);
        page.addMastery(jsonMastery.getLong("id"), jsonMastery.getInt("rank"));
    }
    arr.add(page);
}

You can then create each mastery page and parse the JSON to fill its fields.

A: Declare it like this:
String[][] arr = new String[][numRows];

And then add arrays to it by either of the following means:
arr[0] = new String[lengthOfJSONArray];
arr[0] = getStringArray();


text:
Q: Getter for arbitrary property of object I have a class that looks like this
export default class {
  constructor () {
    this.store = {}
  }

  setX (x, y) {
    this.store[x] = y
  }
}

How would I define a getter on this.store to return 0 when getting an undefined value?
Let me give an example:
setX('a', 1) would set this.store['a'] to 1
then this.store['a'] would return 1, as expected.
But this.store['b'] would return undefined, but I want the getter to return 0 instead (and maybe call setX('b', 0), not sure yet).
I know I can use Object.defineProperty to define a custom getter, I just can't wrap my head around how to access an arbitrary, not yet defined property of the store object.
Is this at all possible or do I have to use a work-around like this?
getX (x) {
  return this.store[x] || 0
}

I would like to avoid that, because this.store[x] seems so much cleaner.

A:
How would I define a getter on this.store to return 0 when getting an undefined value?

Unless you can anticipate all possible property names you want to support and define getters for them, to do that you need a Proxy with a get trap, which is new as of ES2015 (and cannot be polyfilled). Proxies are expensive in performance terms, use them only when you really need them.
Example:

class Example {
  constructor () {
    this.store = new Proxy({}, {
      get(target, property) {
        return property in target ? target[property] : 0;
      }
    });
  }

  setX (x, y) {
    this.store[x] = y;
  }
}

const e = new Example();
console.log("Setting a");
e.setX("a", "foo");
console.log("a = " + e.store.a);
console.log("b = " + e.store.b);

Of course, if you make store private, you could enforce access only through a getX method on the object, which would avoid the use of a proxy at the expense of defining setX and getX on a per-instance basis (for now, private data is coming):

class Example {
  constructor () {
    const store = {};
    this.setX = (x, y) => {
      store[x] = y;
    };
    this.getX = x => {
      return x in store ? store[x] : 0;
    };
  }
}

const e = new Example();
console.log("Setting a");
e.setX("a", "foo");
console.log("a = " + e.getX("a"));
console.log("b = " + e.getX("b"));

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to save an Offer to Google Wallet using JWT? Actually I want to save an offer to 'Google Wallet'. As I haven't worked on it before I did some RND and came across this documentation. In this documentation they are creating Offer class object at Android side but, in my case the Offer class object is creating at our back-end server and I'm getting ready-made JWT token just by hitting one API to our back-end server, now using that JWT token I want to save the offer to the 'Google-Wallet'. Now my question is, is it possible? if Yes please tell me How? Also please let me know if I can provide more details so that you can understand my problem. Thank you

A: I have been working on this at PassNinja. The most convenient method for your use case would be to use the JWT link and intent.
Fill in your generated JWT and class ID:
https://www.android.com/{classid}/savetoandroidpay/{jwt_generated}
Use an ACTION_VIEW intent to open the deep link from the Save to Google Pay button.
Make sure that the button that triggers the intent uses the Brand guidelines.
Intent webIntent = new Intent(Intent.ACTION_VIEW,
        Uri.parse("https://www.android.com/payapp/savetoandroidpay/" + JWT));
context.startActivity(webIntent)`

For more info on deep links and Save to Google Pay, here is a video.


text:
Q: Number points along polyline while keeping information on preceding point I'm working with river networks and need to create ID for points along it. Trick is that points need to have its own ID and also keep the ID of the preceding point (in  two separate columns of course).
It would look like this:

Are there any tools/plugins in QGIS that I could use to create such data? Preferably without coding.

A: The solution that was used at the end included QGIS and FME, so it went a bit outside of the scope of the question.
First I created a line shapefile in QGIS and manualy drew individual lines connecting points. It was important to draw single lines (not polylines) and draw them in the desired direction. Meaning to draw from the preceeding point to the receiving one, i.e. on my original picture it would be start drawing in point 1 and end at 2. 2 to 3 and so on.
Then I used FME and SpatialRelator tool to get the order of points.


text:
Q: Javascript break string into variables and add space I'm brand new to javascript and I've been at this for a while. I have
var formula =  '({qty} <=91999  && {qty} >= 91000  && ({oval}) && ({2inchby3inch}) && !{whitebopp}'

I need to break the ({qty} <=91999  && {qty} >= 91000 into a quantity variable, && ({oval}) into shape variable, && ({2inchby3inch}) into size variable, and && !{whitebopp} into status variable. I'm pretty sure I should use the split function but I'm having trouble with it.
I need to add a space in between the = and 9 to go from ({qty} <=91999 to ({qty} <= 91999, how do I do this? Thank you!


text:
Q: Recursive lambda functions in C++11 I am new to C++11. I am writing the following recursive lambda function, but it doesn't compile.
sum.cpp
#include <iostream>
#include <functional>

auto term = [](int a)->int {
  return a*a;
};

auto next = [](int a)->int {
  return ++a;
};

auto sum = [term,next,&sum](int a, int b)mutable ->int {
  if(a>b)
    return 0;
  else
    return term(a) + sum(next(a),b);
};

int main(){
  std::cout<<sum(1,10)<<std::endl;
  return 0;
}

compilation error:
vimal@linux-718q:~/Study/09C++/c++0x/lambda> g++ -std=c++0x sum.cpp
sum.cpp: In lambda function:
sum.cpp:18:36: error: '((<lambda(int, int)>*)this)-><lambda(int, int)>::sum' cannot be used as a function
gcc version
gcc version 4.5.0 20091231 (experimental) (GCC)
But if I change the declaration of sum() as below, it works:
std::function<int(int,int)> sum = [term,next,&sum](int a, int b)->int {
   if(a>b)
     return 0;
   else
     return term(a) + sum(next(a),b);
};

Could someone please throw light on this?

A: With C++14, it is now quite easy to make an efficient recursive lambda without having to incur the additional overhead of std::function, in just a few lines of code:
template <class F>
struct y_combinator {
    F f; // the lambda will be stored here

    // a forwarding operator():
    template <class... Args>
    decltype(auto) operator()(Args&&... args) const {
        // we pass ourselves to f, then the arguments.
        return f(*this, std::forward<Args>(args)...);
    }
};

// helper function that deduces the type of the lambda:
template <class F>
y_combinator<std::decay_t<F>> make_y_combinator(F&& f) {
    return {std::forward<F>(f)};
}

with which your original sum attempt becomes:
auto sum = make_y_combinator([term,next](auto sum, int a, int b) -> int {
  if (a>b) {
    return 0;
  }
  else {
    return term(a) + sum(next(a),b);
  }
});

In C++17, with CTAD, we can add a deduction guide:
template <class F> y_combinator(F) -> y_combinator<F>;

Which obviates the need for the helper function. We can just write y_combinator{[](auto self, ...){...}} directly.

In C++20, with CTAD for aggregates, the deduction guide won't be necessary.

In C++23, with deducing this, you don't need a Y-combinator at all:
auto sum = [term,next](this auto const& sum, int a, int b) -> int {
  if (a>b) {
    return 0;
  }
  else {
    return term(a) + sum(next(a),b);
  }
}

A: I ran a benchmark comparing a recursive function vs a recursive lambda function using the std::function<> capture method.  With full optimizations enabled on clang version 4.1, the lambda version ran significantly slower.
#include <iostream>
#include <functional>
#include <chrono>

uint64_t sum1(int n) {
  return (n <= 1) ? 1 : n + sum1(n - 1);
}

std::function<uint64_t(int)> sum2 = [&] (int n) {
  return (n <= 1) ? 1 : n + sum2(n - 1);
};

auto const ITERATIONS = 10000;
auto const DEPTH = 100000;

template <class Func, class Input>
void benchmark(Func&& func, Input&& input) {
  auto t1 = std::chrono::high_resolution_clock::now();
  for (auto i = 0; i != ITERATIONS; ++i) {
    func(input);
  }
  auto t2 = std::chrono::high_resolution_clock::now();
  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count();
  std::cout << "Duration: " << duration << std::endl;
}

int main() {
  benchmark(sum1, DEPTH);
  benchmark(sum2, DEPTH);
}

Produces results:
Duration: 0 // regular function
Duration: 4027 // lambda function

(Note: I also confirmed with a version that took the inputs from cin, so as to eliminate compile time evaluation)
Clang also produces a compiler warning:
main.cc:10:29: warning: variable 'sum2' is uninitialized when used within its own initialization [-Wuninitialized]

Which is expected, and safe, but should be noted.
It's great to have a solution in our toolbelts, but I think the language will need a better way to handle this case if performance is to be comparable to current methods.
Note:
As a commenter pointed out, it seems latest version of VC++ has found a way to optimize this to the point of equal performance.  Maybe we don't need a better way to handle this, after all (except for syntactic sugar).
Also, as some other SO posts have outlined in recent weeks, the performance of std::function<> itself may be the cause of slowdown vs calling function directly, at least when the lambda capture is too large to fit into some library-optimized space std::function uses for small-functors  (I guess kinda like the various short string optimizations?).

A: I have another solution, but work only with stateless lambdas:
void f()
{
    static int (*self)(int) = [](int i)->int { return i>0 ? self(i-1)*i : 1; };
    std::cout<<self(10);
}

Trick here is that lambdas can access static variables and you can convert stateless ones to function pointer.
You can use it with standard lambdas:
void g()
{
    int sum;
    auto rec = [&sum](int i) -> int
    {
        static int (*inner)(int&, int) = [](int& _sum, int i)->int
        {
            _sum += i;
            return i>0 ? inner(_sum, i-1)*i : 1;
        };
        return inner(sum, i);
    };
}

Its work in GCC 4.7

A: Here is a refined version of the Y-combinator solution based on one proposed by  @Barry.
template <class F>
struct recursive {
  F f;
  template <class... Ts>
  decltype(auto) operator()(Ts&&... ts)  const { return f(std::ref(*this), std::forward<Ts>(ts)...); }

  template <class... Ts>
  decltype(auto) operator()(Ts&&... ts)  { return f(std::ref(*this), std::forward<Ts>(ts)...); }
};

template <class F> recursive(F) -> recursive<F>;
auto const rec = [](auto f){ return recursive{std::move(f)}; };

To use this, one could do the following
auto fib = rec([&](auto&& fib, int i) {
// implementation detail omitted.
});

It is similar to the let rec keyword in OCaml, although not the same.

A: To make lambda recursive without using external classes and functions (like std::function or fixed-point combinator) one can use the following construction in C++14 (live example):
#include <utility>
#include <list>
#include <memory>
#include <iostream>

int main()
{
    struct tree
    {
        int payload;
        std::list< tree > children = {}; // std::list of incomplete type is allowed
    };
    std::size_t indent = 0;
    // indication of result type here is essential
    const auto print = [&] (const auto & self, const tree & node) -> void
    {
        std::cout << std::string(indent, ' ') << node.payload << '\n';
        ++indent;
        for (const tree & t : node.children) {
            self(self, t);
        }
        --indent;
    };
    print(print, {1, {{2, {{8}}}, {3, {{5, {{7}}}, {6}}}, {4}}});
}

prints:
1
 2
  8
 3
  5
   7
  6
 4

Note, result type of lambda should be specified explicitly.

A: Think about the difference between the auto version and the fully specified type version.  The auto keyword infers its type from whatever it's initialized with, but what you're initializing it with needs to know what its type is (in this case, the lambda closure needs to know the types it's capturing).  Something of a chicken-and-egg problem.
On the other hand, a fully specified function object's type doesn't need to "know" anything about what is being assigned to it, and so the lambda's closure can likewise be fully informed about the types its capturing.
Consider this slight modification of your code and it may make more sense:
std::function<int(int, int)> sum;

sum = [term, next, &sum](int a, int b) -> int {
    if (a > b)
        return 0;
    else
        return term(a) + sum(next(a), b);
};

Obviously, this wouldn't work with auto.  Recursive lambda functions work perfectly well (at least they do in MSVC, where I have experience with them), it's just that they aren't really compatible with type inference.

A: In C++23 deducing this (P0847) will be added:
auto f = [](this auto& self, int i) -> int
{
    return i > 0 ? self(i - 1) + i : 0;
}

For now its only available in EDG eccp and (partially) available in MSVC:
https://godbolt.org/z/f3E3xT3fY

A: The trick is to feed in the lambda implementation to itself as a parameter, not by capture.
const auto sum = [term, next](int a, int b) {
    auto sum_impl = [term, next](int a, int b, auto& sum_ref) mutable {
        if (a > b) {
            return 0;
        }
        return term(a) + sum_ref(next(a), b, sum_ref);
    };
    return sum_impl(a, b, sum_impl);
};

All problems in computer science can be solved by another level of indirection. I first found this easy trick at http://pedromelendez.com/blog/2015/07/16/recursive-lambdas-in-c14/
It does require C++14 while the question is on C++11, but perhaps interesting to most.
Here's the full example at Godbolt.
Going via std::function is also possible but can result in slower code. But not always. Have a look at the answers to std::function vs template

This is not just a peculiarity about C++,
it's directly mapping to the mathematics of lambda calculus. From Wikipedia:

Lambda calculus cannot express this as directly as some other
notations:
all functions are anonymous in lambda calculus, so we can't refer to a
value which is yet to be defined, inside the lambda term defining that
same value. However, recursion can still be achieved by arranging for a
lambda expression to receive itself as its argument value

A: You can make a lambda function call itself recursively. The only thing you need to do is to is to reference it through a function wrapper so that the compiler knows it's return and argument type (you can't capture a variable -- the lambda itself -- that hasn't been defined yet).
  function<int (int)> f;

  f = [&f](int x) {
    if (x == 0) return 0;
    return x + f(x-1);
  };

  printf("%d\n", f(10));

Be very careful not to run out of the scope of the wrapper f.

A: This is a slightly simpler implementation of the fixpoint operator which makes it a little more obvious exactly what's going on.
#include <iostream>
#include <functional>

using namespace std;

template<typename T, typename... Args>
struct fixpoint
{
    typedef function<T(Args...)> effective_type;
    typedef function<T(const effective_type&, Args...)> function_type;

    function_type f_nonr;

    T operator()(Args... args) const
    {
        return f_nonr(*this, args...);
    }

    fixpoint(const function_type& p_f)
        : f_nonr(p_f)
    {
    }
};

int main()
{
    auto fib_nonr = [](const function<int(int)>& f, int n) -> int
    {
        return n < 2 ? n : f(n-1) + f(n-2);
    };

    auto fib = fixpoint<int,int>(fib_nonr);

    for (int i = 0; i < 6; ++i)
    {
        cout << fib(i) << '\n';
    }
}

A: C++ 14:
Here is a recursive anonymous stateless/no capture generic set of lambdas
that outputs all numbers from 1, 20
([](auto f, auto n, auto m) {
    f(f, n, m);
})(
    [](auto f, auto n, auto m) -> void
{
    cout << typeid(n).name() << el;
    cout << n << el;
    if (n<m)
        f(f, ++n, m);
},
    1, 20);

If I understand correctly this is using the Y-combinator solution
And here is the sum(n, m) version
auto sum = [](auto n, auto m) {
    return ([](auto f, auto n, auto m) {
        int res = f(f, n, m);
        return res;
    })(
        [](auto f, auto n, auto m) -> int
        {
            if (n > m)
                return 0;
            else {
                int sum = n + f(f, n + 1, m);
                return sum;
            }
        },
        n, m); };

auto result = sum(1, 10); //result == 55

A: Here's the proof that a recursive lambda with a small body almost has the same performance like a usual recursive fuction which can call itself directly.
#include <iostream>
#include <chrono>
#include <type_traits>
#include <functional>
#include <atomic>
#include <cmath>

using namespace std;
using namespace chrono;

unsigned recursiveFn( unsigned x )
{
    if( x ) [[likely]]
        return recursiveFn( x - 1 ) + recursiveFn( x - 1 );
    else
        return 0;
};

atomic_uint result;

int main()
{
    auto perf = []( function<void ()> fn ) -> double
    {
        using dur_t = high_resolution_clock::duration;
        using urep_t = make_unsigned_t<dur_t::rep>;
        high_resolution_clock::duration durMin( (urep_t)-1 >> 1 );
        for( unsigned r = 10; r--; )
        {
            auto start = high_resolution_clock::now();
            fn();
            dur_t dur = high_resolution_clock::now() - start;
            if( dur < durMin )
                durMin = dur;
        }
        return durMin.count() / 1.0e9;
    };
    auto recursiveLamdba = []( auto &self, unsigned x ) -> unsigned
    {
        if( x ) [[likely]]
            return self( self, x - 1 ) + self( self, x - 1 );
        else
            return 0;
    };
    constexpr unsigned DEPTH = 28;
    double
        tLambda = perf( [&]() { ::result = recursiveLamdba( recursiveLamdba, DEPTH ); } ),
        tFn = perf( [&]() { ::result = recursiveFn( DEPTH ); } );
    cout << trunc( 1000.0 * (tLambda / tFn - 1.0) + 0.5 ) / 10.0 << "%" << endl;
}

For my AMD Zen1 CPU with current MSVC the recursiveFn is about 10% faster. For my Phenom II x4 945 with g++ 11.1.x both functions have the same performance.
Keep in mind that this is almost the worst case since the body of the funtion is very small. If it is larger the part of the recursive function call itself is smaller.

A: You need a fixed point combinator. See this.
or look at the following code:
//As decltype(variable)::member_name is invalid currently,
//the following template is a workaround.
//Usage: t2t<decltype(variable)>::t::member_name
template<typename T>
struct t2t
{
    typedef T t;
};

template<typename R, typename V>
struct fixpoint
{
    typedef std::function<R (V)> func_t;
    typedef std::function<func_t (func_t)> tfunc_t;
    typedef std::function<func_t (tfunc_t)> yfunc_t;

    class loopfunc_t {
    public:
        func_t operator()(loopfunc_t v)const {
            return func(v);
        }
        template<typename L>
        loopfunc_t(const L &l):func(l){}
        typedef V Parameter_t;
    private:
        std::function<func_t (loopfunc_t)> func;
    };
    static yfunc_t fix;
};
template<typename R, typename V>
typename fixpoint<R, V>::yfunc_t fixpoint<R, V>::fix =
[](fixpoint<R, V>::tfunc_t f) -> fixpoint<R, V>::func_t {
    fixpoint<R, V>::loopfunc_t l = [f](fixpoint<R, V>::loopfunc_t x) ->
        fixpoint<R, V>::func_t{
            //f cannot be captured since it is not a local variable
            //of this scope. We need a new reference to it.
            auto &ff = f;
            //We need struct t2t because template parameter
            //V is not accessable in this level.
            return [ff, x](t2t<decltype(x)>::t::Parameter_t v){
                return ff(x(x))(v);
            };
        };
        return l(l);
    };

int _tmain(int argc, _TCHAR* argv[])
{
    int v = 0;
    std::function<int (int)> fac =
    fixpoint<int, int>::fix([](std::function<int (int)> f)
        -> std::function<int (int)>{
        return [f](int i) -> int{
            if(i==0) return 1;
            else return i * f(i-1);
        };
    });

    int i = fac(10);
    std::cout << i; //3628800
    return 0;
}

A: Here is the final answer for the OP. Anyway, Visual Studio 2010 does not support capturing global variables. And you do not need to capture them because global variable is accessable globally by define. The following answer uses local variable instead.
#include <functional>
#include <iostream>

template<typename T>
struct t2t
{
    typedef T t;
};

template<typename R, typename V1, typename V2>
struct fixpoint
{
    typedef std::function<R (V1, V2)> func_t;
    typedef std::function<func_t (func_t)> tfunc_t;
    typedef std::function<func_t (tfunc_t)> yfunc_t;

    class loopfunc_t {
    public:
        func_t operator()(loopfunc_t v)const {
            return func(v);
        }
        template<typename L>
        loopfunc_t(const L &l):func(l){}
        typedef V1 Parameter1_t;
        typedef V2 Parameter2_t;
    private:
        std::function<func_t (loopfunc_t)> func;
    };
    static yfunc_t fix;
};
template<typename R, typename V1, typename V2>
typename fixpoint<R, V1, V2>::yfunc_t fixpoint<R, V1, V2>::fix = [](tfunc_t f) -> func_t {
    return [f](fixpoint<R, V1, V2>::loopfunc_t x){  return f(x(x)); }
    ([f](fixpoint<R, V1, V2>::loopfunc_t x) -> fixpoint<R, V1, V2>::func_t{
        auto &ff = f;
        return [ff, x](t2t<decltype(x)>::t::Parameter1_t v1,
            t2t<decltype(x)>::t::Parameter1_t v2){
            return ff(x(x))(v1, v2);
        };
    });
};

int _tmain(int argc, _TCHAR* argv[])
{
    auto term = [](int a)->int {
      return a*a;
    };

    auto next = [](int a)->int {
      return ++a;
    };

    auto sum = fixpoint<int, int, int>::fix(
    [term,next](std::function<int (int, int)> sum1) -> std::function<int (int, int)>{
        auto &term1 = term;
        auto &next1 = next;
        return [term1, next1, sum1](int a, int b)mutable ->int {
            if(a>b)
                return 0;
        else
            return term1(a) + sum1(next1(a),b);
        };
    });

    std::cout<<sum(1,10)<<std::endl; //385

    return 0;
}

A: This answer is inferior to Yankes' one, but still, here it goes:
using dp_type = void (*)();

using fp_type = void (*)(dp_type, unsigned, unsigned);

fp_type fp = [](dp_type dp, unsigned const a, unsigned const b) {
  ::std::cout << a << ::std::endl;
  return reinterpret_cast<fp_type>(dp)(dp, b, a + b);
};

fp(reinterpret_cast<dp_type>(fp), 0, 1);

A: You're trying to capture a variable (sum) you're in the middle of defining. That can't be good.
I don't think truely self-recursive C++0x lambdas are possible. You should be able to capture other lambdas, though.


text:
Q: Absolute value of the difference is sufficiently small implies the quotient is close to 1 Let $|\cdot|$ be an absolute value on a field $K.$
Let $\alpha \in K^\times$ and $\varepsilon>0$ be given.
I am stuck trying to prove the following statement:
"There exists $\eta>0$ such that for all $\beta \in K^\times$ with $|\alpha-\beta|<\eta\,$ one has $|\alpha\beta^{-1}-1|<\varepsilon$"

So for any $\eta>0$ one has
$$|\alpha-\beta|<\eta \; \Rightarrow \; |\alpha\beta^{-1}-1|<\eta|\beta|^{-1}$$
and so I want to choose my $\eta$ so that
$$\eta<\varepsilon|\beta| \; \text{ for all } \; \beta \in K^\times \; \text{ such that } \; |\alpha-\beta|<\eta.$$
But now I'm stuck because I want a lower bound $|\beta|$ but the inequality is "the wrong way around".
Help greatly appreciated!

EDIT (following hint below): Choose $\eta>0$ such that
$$\eta<\min(1,\varepsilon)\cdot\frac{|\alpha|}{2}.$$
Then, since $\eta<|\alpha|/2,$ one has
$$|\beta|\geq |\alpha|-|\alpha-\beta|>|\alpha|-\frac{|\alpha|}{2}=\frac{|\alpha|}{2}$$
and so, since $\eta<\varepsilon|\alpha|/2,$ it follows that
$$\varepsilon|\beta|>\eta.$$

A: Hint: Show there is an $\eta'$ such that for $|\alpha-\beta|<\eta'$, we have $|\beta|>|\alpha|/2$. Then choose $\eta < \min(\eta', \frac{1}{2}\epsilon |\alpha|)$.


text:
Q: Manipulating large amounts of keyword arguments in a Pythonic manner I have a class who's _init_ function requires quite a few keyword arguments. I'd like to be able to basically rewrite this bit of code so that it's syntactically cleaner (less hard coding). Preferably I'd like to be able to get it so that simply adding a keyword argument to _init_ would change all the attributes/arguments in the null function respectively.
class Class :

    def __init__ (self, kw0=0, kw1=1, kw2=2) :

        ''' The keyword arguments as strings. '''
        self.Keys = ['kw0', 'kw1', 'kw2']

        ''' Their values. '''
        self.Values = [kw0, kw1, kw2]

        ''' A dictionary made from the keys and values. '''
        self.Dict = self.make_dict()

        ''' As individual attributes, '''
        self.KW0, self.KW1, self.KW2 = self.Values

    def make_dict (self) :
        ''' Makes a dictionary '''

        keys   = self.Keys
        values = self.Values

        _dict = {}
        for i in xrange(len(keys)) :
            key   = keys[i]
            value = values[i]

            _dict[key] = value

        return _dict

    def null (self, kw0=None, kw1=None, kw2=None) :
        ''' The same keyword arguments as **__init__** but they all default
            to **None**. '''

        pass

c = Class()
print c.Keys
print c.Values
print c.Dict
print c.KW0
print c.KW1
print c.KW2

A: This is one thing I love about python. In your __init__
def __init__ (self, **kwargs):
    self.__dict__.update(kwargs)

Will append those members defined in a dictionary kwargs as members of the class.
EDITED - to reflect proper syntax for **kwargs, and update() instead of append()

A: Why not accept any keyword arguments. You can use a class attribute for allowable keyword names and their default values.
class Class(object):

     _defaults = dict(kw0=42, kw1=None, kw2=True, kw3="Ni!")

     def __init__(self, **kwargs):

        # Raise exception if any non-supported keywords supplied
        if set(kwargs.keys()) - set(self._defaults.keys()):
            raise KeyError("unsupported keyword argument")

        # Update our instance with defaults, then keyword args
        self.__dict__.update(self._defaults)
        self.__dict__.update(kwargs)

If you want the same functionality in more than one method (e.g. __init__() and null()) then just break the argument handling code out into its own method and call it from both places.
One downside is that help() and other Python documentation tools won't show the allowable keyword arguments, since they aren't in your method signature.
As an aside, I'm not quite sure why you're storing keys and values separately. Just store them as a dictionary, then get the keys or values when you want them using the dictionary's .keys() or .values() method.


text:
Q: Want to exclude slider from page.php in header I know this is a dumb question, but for the love of my life, I can't get the code to work. I have three page templates: home, page and another page-by category. I have a slider that I want to excluded from the default page.php file but to show everywhere else. I have tried to do this with is_page_template , but that isn't working. any help will be much appreciated. I'm not sure if you need my header  code. If you do then leave a comment please and I'll paste in in pastebin. Thanks a lot in advance.

A: Did you consult the is_page_template() Codex entry?
If you want to query for the page.php page template, then you need to pass that filename to is_page_template(); i.e.:
<?php
if ( ! is_page_template( 'page.php' ) ) {
    // The current page template is NOT page.php;
    // do something
}
?>

Sidenote: if you want to query for being a static page AND not a specific page template:
<?php
if ( is_page() && ! is_page_template( 'page.php' ) ) {
    // Current page is a static page AND
    // The current page template is NOT page.php;
    // do something
}
?>


text:
Q: Which is better? Passing the entire contents as a string, or string concatenation? Hi, I have 20 strings, each of which will have same package structure except for the class name. These strings need to be passed to method as required. Refer to the code below:
public static final String RECENT_MSG_        = "com.foo.xxs.RecentMessage";
public static final String PROJ_              = "com.foo.xxs.Proj";
public static final String FORECAST           = "com.foo.xxs.Forecase";
public static final String REQUEST            = "com.foo.xxs.Request";
public static final String UNAPPROVED         = "com.foo.xxs.UnApproved";
public static final String UNPOSTED           = "com.foo.xxs.Unposeted";
public static final String VACANT             = "com.foo.xxs.Vacant";
public static final String ORG_VIOL           = "com.foo.xxs.OrgViolation";
public static final String ORG_WARN           = "com.foo.xxs.OrgWarning";
public static final String EMP_VIOL           = "com.foo.xxs.EmpViolation";
public static final String EMP_WARN           = "com.foo.xxs.EmpWarning";
public static final String TS_WARN            = "com.foo.xxs.TSWarn";
public static final String TS_VIOL            = "com.foo.xxs.TSViolation";
public static final String AGE_GROUP          = "com.foo.xxs.AgeGroup";

private void rescheduleTasks(long _taskType,String value)
{
    if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(RECENT_MSG_)==null))
    {

    // do something
    }

}

This can also be done as follows:
public static final String RECENT_MSG_        = "RecentMessage";
public static final String PACK                       ="com.foo.xxs."

And concatenating the strings like so:
if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(PACK+RECENT_MSG_)==null))

Which one would be better?

A: They will have the same performance - the concatenation will be performed at compile time rather than execution time as both parts are constants. There will be fewer strings in the constant pool in the original version, admittedly - but that's unlikely to make a difference.
Which do you find more readable? I can't say there's much in it for me - I dislike the repetition of the first form, but equally I'm not sure I'd want to concatenate everywhere.
Another alternative is:
public static final String PACK               = "com.foo.xxs."
public static final String RECENT_MSG_        = PACK + "RecentMessage";

etc - so you perform the concatenation at the point of the constant declaration. Then you can just use RECENT_MSG_ in the code, as per the first snippet, but avoid the "com.foo.xxs" duplication as per the second.
EDIT: Another option you may want to consider is using an enum.

A: I would go for the first version, you just make it easier for a reader to immediately see what the strings mean and what classes you're referring too. In addition, should you ever want to introduce a class from a different namespace, you'll be able to do so.
The second version, in contrast, introduces some logic which needs to be interpreted by a reader first.
If you go for the second version, use Jon's alternative instead, so that at least you still have the option to introduce classes from other namespaces.


text:
Q: Error parsing HTML in Android with JSOUP I am trying to parse the following link:
http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1
As you can see it is a very simple page and I am just trying to extract the text on the page with JSoup. My current implementation returns the wrong HTML and I am not sure why. Here is my code:
public class RetreiveCurrencies extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... arg0) {
        Document html = null;
        try {
            Log.i("wbbug",arg0[0]);
            html = Jsoup.parse((arg0[0]));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.i("wbbug",html.toString());
        return null;
    }

}

Which is called with:
AsyncTask<String, Void, String> rc = new RetreiveCurrencies().execute("http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1");
However, instead of returning the correct HTML with the text you see when clicking the link, my Log.i returns:
<html>
   <head></head>
   <body>
     http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1
   </body>
</html>

What am I doing wrong and how can I extract the text you see when clicking the link?

A: Jsoup.parse() takes a String argument, so currently your code is parsing the URL as if it was a String of html code.
To parse a Document from a remote URL you should use Jsoup.connect(), for example:
Document doc = Jsoup.connect("URL").get();

For your specific example (which appears to be returning JSON, not HTML):
Document doc = Jsoup.connect("http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1").ignoreContentType(true).get();
System.out.println(doc.text());

Will output:
{"to": "EUR", "rate": 0.73757499999999998, "from": "USD", "v": 0.73757499999999998}

The reason I had to add ignoreContentType(true) is because otherwise it throws an UnsupportedMimeTypeException.


text:
Q: Copy files with double credentials (windows) Assume we have c:\DirA that can be read by User1 only, and c:\DirB that can be written by User2 only. Both credentials are know.
How can I copy files from DirA to DirB directly?

A: Assuming the process is run in the context of the first user, run LogonUser to obtain a security token for the second user. Spawn a thread and call ImpersonateLoggedOnUser, passing the token as a parameter. The second thread will have access to DirB. Read data in the first thread, pass them to the second and write them from there.
If the user you're running under has backup or restore privileges, the easier way would be to activate them with OpenProcessToken followed by AdjustTokenPrivileges.


text:
Q: Is it possible to 'refresh' WPF data bindings I've got a xaml TabControl and on one page, there are 3 RadioButtons each bound to a different property on the selected value of an adjacent ListView. After switching between selected items in the ListView, my radio buttons seem to forget they're bound and don't refresh.
So watching it in the debugger, when I switch to a new selected item, I see the non user code first checking the value on all 3 properties, then only the first two, and eventually only the first. However, if I change the tab and change back, it seems to give me another few uses.
The binding itself is fairly straightforward. a TwoWay binding of a bool property to IsChecked. It's 4 levels deep (Path=DataModel.Selected.A.B), but I have other things at the same depth that work fine.
Is this something people have heard about and know what might be going on? Or if the binding is somehow getting forgotten, is there a way to explicitly remind the xaml?

A: It is possible to manually update bindings like this:
TestCheckBox
    .GetBindingExpression(CheckBox.IsCheckedProperty)
    .UpdateTarget();

That being said, I don't have 100% confidence that this will correct your underlying issue. I haven't had this sort of issue before with WPF bindings, but I have had a couple weird issues with the tab control.

A: This is apparently somewhat of a known issue:
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/8eb8280a-19c4-4502-8260-f74633a9e2f2/
In short, a RadioButton (through .Net 3.5sp1) somehow kills bindings of other RadioButtons when when it's checked while trying to uncheck any other buttons. The simple fix (read: hack) is to assign each radiobutton a different GroupName and then they don't try to mess with eachother

A: Another way to resolve this issue is to fake up a list of properties in a ListBox and have the ListBoxItem template be a radiobutton.


text:
Q: How can I fill my dataframe Can someone please tell me how I can fill in the missing values of my dataframe? The missing values dont come up as NaN or anything that is common instead they show as two dots like .. How would i go about filling them in with the mean of that row that they are in?
                     1971     1990     1999     2000     2001     2002

Estonia                ..     17.4      8.3      8.5      8.5      8.6
Spain                61.6    151.2    205.9    222.2    233.2    241.6
SlovakRepublic       10.9     25.5     28.1     30.8     31.9     32.2
Slovenia               ..     12.4     13.3     13.6     14.5     14.6

My headers are the years and my index are the countries.

A: It seems you can use mask, compare by numpy array created by values and replace by mean, last cast all columns to float:
print (df.mean(axis=1))
Estonia            10.26
Spain             210.82
SlovakRepublic     29.70
Slovenia           13.68

df = df.mask(df.values == '..', df.mean(axis=1), axis=0).astype(float)
print (df)
                 1971   1990   1999   2000   2001   2002
Estonia         10.26   17.4    8.3    8.5    8.5    8.6
Spain            61.6  151.2  205.9  222.2  233.2  241.6
SlovakRepublic   10.9   25.5   28.1   30.8   31.9   32.2
Slovenia        13.68   12.4   13.3   13.6   14.5   14.6

A: You should be able to use an .set_value
try df_name.set_value('index', 'column', value)
something like
df_name.set_value('Estonia','1971', 50)


text:
Q: How do I SQL query for words with punctuation in Postgresql? If I have strings/phrases like this stored in the database:

*

*What are Q-type Operations?

*Programmer's Guide

*A.B.C's of Coding

Is there a way to pass a query parameter in like "Programmers" or "abc" or "q-type" and have it find "Programmer's", "A.B.C" and "Q-type"?

A: tsvector
Use the tsvector type, which is part of the PostgreSQL text-search feature.
postgres> select 'What are Q-type Operations?'::tsvector;
              tsvector
-------------------------------------
 'Operations?' 'Q-type' 'What' 'are'
(1 row)

You can use familiar operators on tsvectors as well:
postgres> select 'What are Q-type Operations?'::tsvector
postgres>        || 'A.B.C''s of Coding'::tsvector;
                           ?column?
--------------------------------------------------------------
 'A.B.C''s' 'Coding' 'Operations?' 'Q-type' 'What' 'are' 'of'

From tsvector documentation:

A tsvector value is a sorted list of distinct lexemes, which are words that have been normalized to merge different variants of the same word (see Chapter 12 for details). Sorting and duplicate-elimination are done automatically during input

If you also want to do language-specific normalization, like removing common words ('the', 'a', etc) and multiplies, use the to_tsvector function. It also assigns weights to different words for text search:
postgres> select to_tsvector('english',
postgres> 'What are Q-type Operations? A.B.C''s of Coding');
                      to_tsvector
--------------------------------------------------------
 'a.b.c':7 'code':10 'oper':6 'q':4 'q-type':3 'type':5
(1 row)

Full-blown text search
Obviously doing this for every row in a query will be expensive -- so you should store the tsvector in a separate column and use ts_query() to search for it. This also allows you to create a GiST index on the tsvector.
postgres> insert into text (phrase, tsvec)
postgres>   values('What are Q-type Operations?',
postgres>   to_tsvector('english', 'What are Q-type Operations?'));
INSERT 0 1

Searching is done using tsquery and the @@ operator:
postgres> select phrase from text where tsvec @@ to_tsquery('q-type');
           phrase
-----------------------------
 What are Q-type Operations?
(1 row)

A: You could try with an ILIKE with a TRANSLATE function, see here.
For example: translate(field, '.-\'', '')

A: Here's another link that can be relevant. Strip the value of the field from all punctuation before comparing it to the search string.
SQL Server: How do you remove punctuation from a field?

A: This sounds like you want something along these lines:
http://www.postgresql.org/docs/9.0/static/fuzzystrmatch.html
I'm not 100% sure if that will cover what you want though.
EDIT I had to run this up locally to check (Using PostgreSQL 9.0 on Windows)
Here's what I found:
template1=> select soundex('Programmers'), soundex('Programmer''s');
 soundex | soundex
---------+---------
 P626    | P626
(1 row)

template1=> select soundex('abc'), soundex('A.B.C.');
 soundex | soundex
---------+---------
 A120    | A120
(1 row)

template1=> select soundex('Q-type'), soundex('q-type');
 soundex | soundex
---------+---------
 Q310    | Q310
(1 row)

So if you were to do soundex(colname) = soundex(<user param>) should get you what you need in the where clause.
You will need to install the fuzzystrmatch module:
psql -U <dbowner> -d <database> -f SHAREDIR/contrib/fuzzystrmatch.sql
Refer to the documentation on how to locate SHAREDIR
EDIT I just noticed what I overlooked, I think this combined with the ts_vector functionality may get you where you are aiming for.

A: Postgresql supports full-text searching by converting text input to tsvector types:
steve@steve@[local] =# select input, to_tsvector('english', input)\
   from (values('What are Q-type Operations?'),('Programmer''s Guide'),('A.B.C''s of Coding')) x(input);
            input            |            to_tsvector
-----------------------------+------------------------------------
 What are Q-type Operations? | 'oper':6 'q':4 'q-type':3 'type':5
 Programmer's Guide          | 'guid':3 'programm':1
 A.B.C's of Coding           | 'a.b.c':1 'code':4
(3 rows)

As you can see, the stemming used by default will make "programming" "programmer" and "programmer's" all match identically.
You would typically use this by having an indexed tsvector column or expression, and then using the @@ operator to match that with a tsquery, e.g.:
steve@steve@[local] =# select input, to_tsvector('english', input) \
   from (values('What are Q-type Operations?'),('Programmer''s Guide'),('A.B.C''s of Coding')) x(input)\
   where to_tsvector('english', input) @@ plainto_tsquery('english', 'programmers');
       input        |      to_tsvector
--------------------+-----------------------
 Programmer's Guide | 'guid':3 'programm':1
(1 row)

Here plainto_tsquery analyses a user input string, and produces a query where every non-stop word in the query has to be matched by a tsvector.

A: Postgres supports pattern matching so you can build a regular expression in your where clause
http://www.postgresql.org/docs/8.3/static/functions-matching.html


text:
Q: Symfony / Doctrine: Restful API design and design pattern about repository injection I'm new to Symfony and these questions were brought about in the recent course of learning.
Take a store as an example, I'll create two entities, Product and Category, which have a bidirectional Many-to-One relationship.
class Product
{
    private $id;
    private $name;
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="products")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id", nullable=false)
     */
    private $category;
}

class Category
{
    private $id;
    private $name;
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category")
     */
    private $products;
}

So my 1st question is:
If I want to get all the products in a particular category, should the URL be

/categories?categoryId=1&limit=20&orderBy=name
  (I know it's a bit silly, but should a Category record contains all the Product information?)

or

/products?categoryId=1&limit=20&orderBy=name

For the latter one, here comes the 2nd question:
I injected the ProductRepository to the ProductController
class ProductController extends Controller
{
    private $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    ...
}

In order to get all the product in a category, I wrote a method like this:
public function findByCategory(Category $category): array
{
    return $this->createQueryBuilder('p')
        ->andWhere('p.category = :category')
        ->setParameter('category', $category)
        ->orderBy('p.name', 'ASC')
        ->setMaxResults(20)
        ->getQuery()
        ->getResult()
    ;
}

So, in the ProductController, how should I get the Category object from the query string 'categoryId' in the URL? Should I inject CategoryRepository as well or should I simply inject an entity manager object?

A: Marco Pivetta aka Ocramius (one of the main developers of Doctrine) said:

Avoid bi-directional associations
Bi-directional associations are overhead
Code only what you need for your domain logic to work
Hack complex DQL queries instead of making them simpler with bidirectionality

So maybe
you don't need bi-directional association here.
For your first question, the second solution is better in my opinion:

/products?categoryId=1&limit=20&orderBy=name

For your second question yes, you should inject the CategoryRepository if you want to access Category object, avoid accessing the whole entityManager in your controller even if it is possible.
You should inject services in your controllers. Your services should expose public methods to perform custom CRUD access to the DB through data mappers. Note that a repository is not a data mapper but it

mediates between the domain and data mapping layers, acting like an in-memory domain object collection.

P of EAA Catalog - Martin Fowler
Repositories are services in fact so that's fine to inject them into the controller.
Some people defend the position that repositories should not contain CREATE, UPDATE or DELETE but only READ. They say that these operations make collections (which are accessible through repositories) inconsistent.
This post can help too: How should a model be structured in MVC?

A: To me, the problem here is a very clear confusion between what the ORM does in Symfony and Database Design, Modelling and Querying.
In the database (using PhpMyAdmin), you'll notice that on the product table there is a column called category (or category_id). Keep it simple, to get products belonging to a category, all you need is the category_id. Take that knowledge to Symfony, you DO NOT need the Category Object, please just use the category ID that you got from the request. Also, just use the EntityManager in the controller, don't complicate stuff, especially since it seems you're just starting out.
use Symfony\Component\HttpFoundation\Request;

class ProductController extends Controller
{
    public function get_product_from_categoryAction(Request $request)
    {
        $category_id = (int) $request->get('category');
        $limit = (int) $request->get('limit');
        $orderBy = strip_tags($request->get('orderBy'));

        $em = $this->getDoctrine()->getManager();
        $products = $em
            ->getRepository('AppBundle:Products')
            ->queryProductsByCategoryId($category_id, $limit, $orderBy);

    }

    ...
}

And the repo
public function queryProductsByCategoryId(int $category_id, int $limit = 10, string $orderBy = 'name')
{
    return $this->createQueryBuilder('p')
        ->andWhere('p.category = :category')
        ->setParameter('category', $category_id)
        ->orderBy('p.name', 'ASC')
        ->setMaxResults($limit)
        ->getQuery()
        ->getResult()
    ;
}

Keep things simple, then when you got to be more advanced, try the more fancy stuff if you so please.


text:
Q: maven: Adding classes in war/web-inf/classes as dependency to a Jar module The task is to create customization to the core project. The core project can not be modified by my team.
The requirement is to change the control flow to the core and implement controller and services extending or using the core classes. Here the customization will be delivered as Jar and Core product will be war. That means the classes that i am going to extend are in web-inf/classes folder of a war. Both customization and core product uses maven.
The problem I am facing here is that, I am not sure how to add war as dependency to my jar (customization)
Any thought please. Also please let me know if there is a good design to do.

A: Maybe not for your case - but solved my problems,  you can create a separate jar from the war,  that will contain only classes
https://pragmaticintegrator.wordpress.com/2010/10/22/using-a-war-module-as-dependency-in-maven/
<build>
...
  <plugins>
  ...
     <plugin>
      <artifactId>maven-war-plugin</artifactId>
      <version>2.1-beta-1</version>
      <configuration>
        <attachClasses>true</attachClasses>
      </configuration>
    </plugin>
  ...
  </plugins>
...
</build>

produces xxx.war and xxx.classes.jar that you can include
<dependency>
  <groupId>net.pascalalma.adapters</groupId>
  <artifactId>my-adapter</artifactId>
  <version>1.0-SNAPSHOT</version>
  <classifier>classes</classifier>
  <scope>test</scope>
</dependency>


text:
Q: How to freeze TensorFlow ckpt with queuerunner? I used tf.train.shuffle_batch while training, and do not use any placeholder, when I freezed the ckpt to pb file, I did not get any input tensor, though I can feed thing to shuffle_batch tensor, but it need the feed has the same size with the shuffle_batch data. How to fix it? I know I can rewrite a net and restore params, then freeze, but it is not wise?
The train
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
import os
trainsize=35680
testsize=889

batch_size=32
inputW=224
inputH=480
TRAIN_TFRECORD='./train.tfrecords'
TEST_TFRECORD='./test.tfrecords'
BATCH_CAPACITY=512
MIN_AFTER_DEQU=256
MAX_Cycle=100000
TRAIN_CYCLE=int(trainsize/batch_size)
TEST_CYCLE=int(testsize/batch_size)
learning_rt = 0.001
savepath='./ckpt/'
logpath='./logs/'

def network(inputs,is_train,reuse):
    BITW =8
    BITA=8
    Decay=0.99
    Epsi=1e-5
    with tf.variable_scope('Model',reuse=reuse):
        net=InputLayer(inputs,name='input') #224*480

        net=QuanConv2dWithBN(net,32,(3,3),(1,1),'SAME',tf.nn.relu, decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv1_1')

        net=QuanConv2dWithBN(net,64,(3,3),(2,2),'SAME',tf.nn.relu, decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv1_2') #112*240

        net=QuanConv2dWithBN(net,64,(3,3),(1,1),'SAME',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv2_1')
        net=QuanConv2dWithBN(net,128,(3,3),(2,2),'SAME',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv2_2') #56*120

        net=QuanConv2dWithBN(net,128,(3,3),(1,1),'SAME',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv3_1')

        net=QuanConv2dWithBN(net,64,(1,1),(1,1),'SAME',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv3_2')

        net=QuanConv2dWithBN(net,128,(3,3),(2,2),'SAME',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv3_3') #28*60

        net=QuanConv2dWithBN(net,64,(3,3),(1,1),'SAME',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv4_1')

        net=QuanConv2dWithBN(net,96,(3,3),(2,2),'VALID',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv4_2') #14*30

        print(net.outputs)
        net=QuanConv2dWithBN(net,128,(3,3),(2,2),'SAME',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv5_1') #7*30

        net=QuanConv2dWithBN(net,128,(3,3),(1,2),'VALID',tf.nn.relu,decay=Decay, epsilon=Epsi,  is_train=is_train,  bitW=BITW,bitA=BITA,name='Conv5_2') #3*30

        net=QuanConv2d(net,128,(3,3),(1,2),'VALID',tf.nn.leaky_relu,bitW=BITW,bitA=BITA,name='Conv5_3') #1*30
        print(net.outputs)
        net=FlattenLayer(net,name='flat1')
        net=QuanDenseLayer(net,128,act=tf.nn.leaky_relu,bitW=BITW,bitA=BITA,name='dense1')

        net=DropoutLayer(net,0.5,is_fix=True,is_train=is_train,name='drop1')
        net=DenseLayer(net,1,name='dense2')
        outnet=net
        volcume=net.outputs
        print(volcume)
        return outnet,net.outputs,volcume

def inference(inputs,is_train,reuse):
    return network(inputs,is_train,reuse)

def read_and_decode(filename):
    filename_queue = tf.train.string_input_producer([filename])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'img': tf.FixedLenFeature([], tf.string),
                                           'num' : tf.FixedLenFeature([], tf.float32),
                                       })

    img = tf.decode_raw(features['img'], tf.uint8)
    img = tf.reshape(img, [480, 240, 3])
    img=tf.random_crop(img,[480,224,3])
    img = tf.image.random_brightness(img, max_delta=0.3)
    img = tf.image.random_contrast(img, lower=0.1, upper=0.5)
    # img = tf.image.random_hue(img, max_delta=0.1)
    # img = tf.image.random_saturation(img, lower=0, upper=2.5)
    img = tf.image.per_image_standardization(img)
    label = tf.reshape( tf.cast(features['num'], tf.float32)*(1./230.)-0.5,[1])
    return img, label

def read_and_decode_test(filename):
    filename_queue = tf.train.string_input_producer([filename])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'img': tf.FixedLenFeature([], tf.string),
                                           'num' : tf.FixedLenFeature([], tf.float32),
                                       })

    img = tf.decode_raw(features['img'], tf.uint8)
    img = tf.reshape(img, [480, 240, 3])
    img=img[:,8:232,:]
    img = tf.image.per_image_standardization(img)
    label = tf.reshape( tf.cast(features['num'], tf.float32)*(1./230.)-0.5,[1])
    return img, label

def smooth_L1(x):
    return tf.where(tf.less_equal(tf.abs(x), 1.0), tf.multiply(0.5, tf.pow(x, 2.0)), tf.subtract(tf.abs(x), 0.5))

def cal_loss(logits,labels):
    # return tf.clip_by_value(tf.reduce_mean(tf.losses.mean_squared_error(labels,logits)) ,0.000001,10000000.)
    return tf.reduce_mean(tf.where(tf.less_equal(tf.abs(logits-labels), 0.02),0.00001*tf.ones_like(logits-labels),  tf.multiply(1., tf.pow(logits-labels, 2.0))))
    # return tf.clip_by_value(tf.reduce_sum(smooth_L1(labels-logits)),0.0000001,100.)

def cal_acc(logits,labels):
    return tf.reduce_mean( tf.cast( tf.less_equal(tf.abs(labels-logits),tf.ones_like(labels)*.1),tf.float32))

if __name__ == '__main__':

    img_train,num_train  = read_and_decode(TRAIN_TFRECORD)
    img_test,num_test  = read_and_decode(TEST_TFRECORD)
    img_train_batch,  num_train_batch = tf.train.shuffle_batch(
        [img_train, num_train], batch_size=batch_size, capacity=BATCH_CAPACITY,
        min_after_dequeue=MIN_AFTER_DEQU)
    img_test_batch,  num_test_batch = tf.train.batch(
        [img_test,num_test], batch_size=batch_size)
    net,_,logits_train=inference(img_train_batch,True,None)
    _,_,logits_test=inference(img_test_batch,False,True)
    loss_train=cal_loss(logits_train,num_train_batch)
    loss_test=cal_loss(logits_test,num_test_batch)
    acc_test=cal_acc(logits_test,num_test_batch)
    acc_train=cal_acc(logits_train,num_train_batch)
    global_step=tf.train.create_global_step()
    #tf.train.get_global_step()
    learning_rate=tf.train.exponential_decay(learning_rt, global_step,
                                           5000, 0.9, staircase=True)
    train = tf.train.MomentumOptimizer(learning_rate,momentum=0.9).minimize(loss_train,global_step=global_step)
    # train = tf.train.AdamOptimizer(learning_rt).minimize(loss_train)

    tf.summary.scalar('loss_train', loss_train)
    tf.summary.scalar('acc_train', acc_train)
    merged = tf.summary.merge_all()
    with tf.Session(config=tf.ConfigProto()) as sess:
        trainwrite = tf.summary.FileWriter(logpath, sess.graph)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        sess.run(tf.global_variables_initializer())
        saver = tf.train.Saver()
        run_cycle=0
        if os.path.exists(savepath+'313.ckpt.index') :
            print('\nStart Restore')
            saver.restore(sess, savepath+'33.ckpt')
            print('\nEnd Restore')
        print('\nStart Training')
        try:

            while not coord.should_stop():

                while run_cycle < MAX_Cycle:

                    run_cycle+=1
                    # if run_cycle%10==0:
                    #     learning_rt*=0.6
                    # if run_cycle%200==0:
                    #     learning_rt*=2.
                    l_tall=0
                    a_tall=0

                    l_teall=0
                    a_teall=0

                    for train_c in range(TRAIN_CYCLE):

                        _,l_train,a_train=sess.run([train,loss_train,acc_train])
                        l_tall+=l_train
                        a_tall+=a_train

                        if (train_c+1)%100==0:
                            print('train_loss:%f'%(l_tall/100.))
                            print('train_acc:%f'%(a_tall/100.))
                            l_tall = 0
                            a_tall = 0
                        if (train_c+1)%500==0:
                            print('Global Step:',sess.run(global_step))
                            result_merged=sess.run(merged)
                            trainwrite.add_summary(result_merged, run_cycle*TRAIN_CYCLE+train_c)
                    for test_c in range(TEST_CYCLE):
                        l_test,a_test=sess.run([loss_test,acc_test])
                        l_teall+=l_test
                        a_teall+=a_test
                        if (test_c+1)%TEST_CYCLE==0:
                            print('------------------')
                            print('test_loss:%f'%(l_teall/TEST_CYCLE))
                            print('test_acc:%f'%(a_teall/TEST_CYCLE))
                            print('------------------')
                            l_teall = 0
                            l_teall = 0
                    saver.save(sess, savepath+ str(run_cycle) + '.ckpt')

        except tf.errors.OutOfRangeError:
            print('Done training!!!')
        finally:
            # When done, ask the threads to stop.
            coord.request_stop()

        coord.join(threads)
        sess.close()

Freeze code
import os, argparse
import tensorflow as tf
from tensorflow.python.framework import graph_util

dir = os.path.dirname(os.path.realpath(__file__))

def freeze_graph(model_folder, output_nodes='y_hat',
                 output_filename='frozen-graph.pb',
                 rename_outputs=None):
    # Load checkpoint
    checkpoint = tf.train.get_checkpoint_state(model_folder)
    input_checkpoint = checkpoint.model_checkpoint_path

    output_graph = output_filename

    # Devices should be cleared to allow Tensorflow to control placement of
    # graph when loading on different machines
    saver = tf.train.import_meta_graph(input_checkpoint + '.meta',
                                       clear_devices=True)

    graph = tf.get_default_graph()
    onames = output_nodes.split(',')

    # https://stackoverflow.com/a/34399966/4190475
    if rename_outputs is not None:
        nnames = rename_outputs.split(',')
        with graph.as_default():
            for o, n in zip(onames, nnames):
                _out = tf.identity(graph.get_tensor_by_name(o + ':0'), name=n)
            onames = nnames

    input_graph_def = graph.as_graph_def()

    # fix batch norm nodes
    for node in input_graph_def.node:

        if node.op == 'RefSwitch':
            node.op = 'Switch'
            for index in range(len(node.input)):
                if 'moving_' in node.input[index]:
                    node.input[index] = node.input[index] + '/read'
        elif node.op == 'AssignSub':
            node.op = 'Sub'
            if 'use_locking' in node.attr: del node.attr['use_locking']

    with tf.Session(graph=graph) as sess:
        saver.restore(sess, input_checkpoint)

        # In production, graph weights no longer need to be updated
        # graph_util provides utility to change all variables to constants
        output_graph_def = graph_util.convert_variables_to_constants(
            sess, input_graph_def,
            onames  # unrelated nodes will be discarded
        )

        # Serialize and write to file
        with tf.gfile.GFile(output_graph, "wb") as f:
            f.write(output_graph_def.SerializeToString())
        print("%d ops in the final graph." % len(output_graph_def.node))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Prune and freeze weights from checkpoints into production models')
    parser.add_argument("--checkpoint_path",
                        default='./regressionDir/',
                        type=str, help="Path to checkpoint files")
    parser.add_argument("--output_nodes",
                        default='Model/dense2/bias_add',
                        type=str, help="Names of output node, comma seperated")
    parser.add_argument("--output_graph",
                        default='reg.pb',
                        type=str, help="Output graph filename")
    parser.add_argument("--rename_outputs",
                        default='out_vol',
                        type=str, help="Rename output nodes for better \
                            readability in production graph, to be specified in \
                            the same order as output_nodes")
    args = parser.parse_args()

    freeze_graph(args.checkpoint_path, args.output_nodes, args.output_graph, args.rename_outputs)

Test inference code
import tensorflow as tf
    import numpy as np
    from PIL import Image
    import time
gf = tf.GraphDef()
gf.ParseFromString(open('reg.pb', 'rb').read())
print([n.name + '=>' + n.op for n in gf.node])

output_graph_path = './reg.pb'
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    output_graph_def = tf.GraphDef()
    with open(output_graph_path, "rb") as f:
        output_graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(output_graph_def, name="")

    input_img = sess.graph.get_tensor_by_name("shuffle_batch:0")
    print(input_img)
    out_vol = sess.graph.get_tensor_by_name("out_vol:0")
    out_voln = sess.graph.get_tensor_by_name("shuffle_batch:0")
    a = np.random.random([48, 480, 224, 3])
    for x in range(100):
        ntime1 = time.time()
        vol = sess.run(out_vol, {input_img: a})
        ntime2 = time.time()
        print(ntime2 - ntime1)


text:
Q: Split data in a column to multiple rows I have an excel sheet where column A contains month and column B contains sales. 1 month can have multiple rows with different sales. I need to sum up the sales in every month. And then output in a new worksheet titled "Report" with each row for a new month.
I could have:
Month     Sales
Jan       15
Jan       5
Feb       3
Mar       4
Mar       8

I need to produce this:
Month     Sales
Jan       20
Feb       3
Mar       12

A: Try using a pivot a table. Select the data range, go to Insert tab then press Pivot Table and OK (it will put the Pivot table into a new sheet by default).
Put Month into Rows box and Sales into Values box.

A: Have in mind that data appears in Column A (Month) & Column B (Sales). Range A2:B6.

Steps:

*

*Select D2

*Go Data - Data Tools tab - Consollidate

*Reference: $A$2:$B$6

*Press Add and ensure that the reference appears in All references box

*Use labels in: Left Column

*Press OK

Results:


text:
Q: How to set the genre of iPad application at development level
Possible Duplicate:
Genre of application in iTunes

Hi
I want to set a specific category or genre like "Productivity" of my
iPad Application at development level.
I added the iTunesMetadata.plist in the project folder and set the
genre key as "Productivity" But it does not work for me...
When I drags the app into iTunes, it shows "Unknown Genre".
Can anyone suggest how can I set the genre of my app ?
Thanks in advance.

A: You would get the option of setting the genre of your app on iTunesConnect when you submit it for approval process


text:
Q: Template class compilation "expected constructor, destructor, or type conversion before '<' token" error I'm having trouble with compiling my template class. This is my list.cpp
using namespace std;

template <class T>
List<T>::List()
{
    length = 0;
}

template <class T>
List<T>::~List()
{

}

template <class T>
List<T> & List<T>::operator=(const List<T> & rhs)
{
    List<T> hha;
    return hha;
}

template <class T>
int List<T>::size()
{
    return length;
}

ANd this is my list.h
#ifndef _LIST_H_
#define _LIST_H_

#include <iterator>
#include <ostream>

using namespace std;

template <class T>
class List
{
    private:

        class ListNode
        {
            public:
                ListNode();
                ListNode(const T element);

                ListNode *next;
                T data;
        };

    public:

        // big3
        List();
        ~List();
        List<T> & operator=(const List<T> & rhs);

        int size();
        bool empty();
        void print(ostream & os) const;

    private:
        ListNode * head;
        ListNode * tail;
        int length;
};

#include "list.cpp"

#endif

when I run g++ list.cpp
I get errors
expected constructor, destructor, or type conversion before '<' token
for definitions of constructor, destructor, and operator...
I don't know what seems to be wrong

A: The template implementation goes in the header.
It is a bit of a hack but it is how it is done.

A: The problem you currently encounter is that you list.cpp doesn't include you list.h: the compiler sees a couple of definitions for things which aren't declared, yet. You can fix this problem by including list.h at the top of your file:
#include "list.h"
...

However, this will essentially lead to a problem coming: if you actually want to use your List<T> with some type, the compiler will need to see the template definition where the class template is used. That is, typically you will implement your templates in the header file. The alterntaive is to implement templates in an implementation file and explicitly instantiating the types it is to be used with. This is quite reasonable for some templates but for something intended to be used for an unknown number of types this isn't practical.
BTW, you are using names which you are not allowed to touch: names starting with an underscore followed by a capital letter are reserved for the C++ implementation, i.e. the compiler and the standard library. Names using two consecutive underscores anywhere are also reserved.

A: Since list.hpp doesn't get #included in list.cpp, the compiler doesn't know about the template definition in that header when you try to compile list.cpp.

A: You compile list.cpp, that defines your list member functions. But it doesn't contain the template class declaration - that is in the header.
I see you include cpp in your list header. This will sort of work if you include the list header in some other cpp file and make sure list.cpp will not be compiled as a separate compilation unit.
What I mean is i.e. file main.cpp:
#include "list.h"
int main()
{}

Then compile this with g++ main.cpp.
Usually you just want to avoid cpp files when using templates altogether. Just stuff everything in the header and include that. Or alternatively I would at least rename your list.cpp to list.impl or some other name. This way one might be less tempted to actually try to compile that file directly.


text:
Q: How does sign_in_and_redirect in devise work? if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
end

This method is present in the facebook omniauth callbacks controller. The problem that I am facing is that I do not get the user's phone number from facebook and thus @user is not a valid object (I have a validation). So, I want to redirect the user to another page where I can ask for the phone number.
How can I modify the sign_in_and_redirect @user to redirect me to that page and not the root url.

A: Sign_in_and_redirect method uses after_sign_in_path_for method to determine where to redirect the user after sign in.
You can easily customize your after_sign_in_path_for method to check for the phone presence and either call super or redirect to the page where user can enter their phone number.


text:
Q: Problem withlimits on Line Integral Problem:

Evaluate the line integral of the vector  field  $$f(x,y)=(x^2-2xy)i+(y^2-2xy)j$$ from $(-1,1)$ to $(1,1)$ along the parabola $y=x^2$.

I can't understand how to set limits on the Line Integral. While I identified $f(x,y)$ as the vector field defined and bounded on the graph of $\alpha$, I can't understand how to get $\alpha$ (the piecewise smooth path in n-space defined on the interval $[a,b]$-as it says in my textbook), nor how to work out $f.d\alpha$.

A: By definition, if you have a line parametrised as $\gamma: [a,b]\to \mathbb R^n$ and a vector field $f: \mathbb R^n\to\mathbb R^n$, then the interval of the vector field along the line is defined as
$$\int f d\gamma = \int_a^b f(\gamma(t))\cdot \gamma'(t) dt$$
In your case:
$$f(x,y) = (x^2 - 2xy, y^2-2xy)\\
\gamma(t) = (t, t^2) \text{ on } [-1,1]$$
Now, just plug in the numbers and see what comes out.


text:
Q: How to crop ( cut) automatically image taken from custom camera as specific frame I am creating a custom camera app . I want to the taken image 's cropped as specific frame ( in my app , it's a drawable file ) , it's similar like this ( sorry , i can post image ) :
This is main UI of camera app :
http://i.imgur.com/fY1Wk1D.jpg
and the result is :
http://i.imgur.com/S2Md7K6.jpg
Any idea ?? I have search around but it's seem i can't find the right answer. Thanks!!


text:
Q: Replacing capacitors in older electronics I was working on a supplementary power supply board in an old arcade cabinet. It has a capacitor with some markings that I was unable to identify and was curious if they were important. Also, I would like any advice that could help me avoid damaging the arcade.
The markings on the capacitor that I am confused by is "CE04 W". I don't know if this is just manufacturer specific or what? Accordingly, the rest of the capacitor markings are as follow:
25V 4700uf
85 degrees

A: That's a bulk capacitor for a simple linear power supply, so nothing special is required. It is made by Nippon Chemi-con, so it is not a cheap bad quality capacitor to my understanding. The CE04 W is the capacitor model series, CE04 is very old and at least the datasheet I found on CE04 series does not list capacitors with this high capacitance.
Almost any capacitor with matching capacitance (4700 uF) and matching or exceeding the other parameters is fine. So the voltage must be at least 25V, but it can be more if you can't find a 25V capacitor. The temperature rating may be rated for 85 C due to longevity reasons even if the temperature does not go up to 85 C. So for same reasons, you might want to have the same 85 C rating, or if you can't find one then larger temperature rating is fine.

A: The Nippon Chemi Con CE04W is rated for 2,000 hours at +85 degC: -

2,000 hours is 83.33 days but, for every 10 degC the capacitor operates at below 85 degC the life time doubles. So at 35 degC average temperature, the lifetime can be expected to be 64,000 hours (2667 days or 7.3 years).
If the voltage actually applied is about 50% of the rated voltage (25 volts) then the operational lifetime doubles again.
See this calculator: -

So, choose a replacement that is good for many years is my advice - if needs be choose one rated at 105 degC or a higher voltage if it helps finding one that fits the space envelope but, whichever you choose look for the lifetime hours in the data sheet - if the capacitor says it's 85 degC rated but doesn't give a number of hours then it's likely to be a poor capacitor. Don't choose a capacitor that hasn't got a temperature rating of at least 85 degC even if it appears to have a lifetime figure.
Also note that the capacitor has a tolerance of +/- 10% or +/-20% and this is usually a sign of reasonable quality because crappy electrolytic caps are usually specified at +80% / -20% in order to overcome their inherent weakening electrolyte over time.
So, choose a decent cap - your arcade machine deserves it!!
So,

A: It's a 4700uF/25V aluminum electrolytic capacitor. Radial package (two leads - at least- coming out of the bottom).
If you go to a distributor such as Digikey and search for capacitors of that value and voltage rating you can find a number. I get 53 that are currently in stock and of those exact values.
Look at the bottom and see if there is a third hole for mechanical stability.
Try to match the lead spacing so the part will fit down on the board- if the board is really old you may not be able to find one that big without going to a higher voltage rating (higher is fine). Personally I would use a 105°C rated part so it will last longer.
When you install the new one you have to make sure you observe polarity. On aluminum electrolytic capacitors the polarity is indicated by a stripe on the NEGATIVE side. If you don't get it right, the new capacitor will vent noxious electrolyte and you might blow a fuse or worse.

A: This type of radial aluminum electrolytic capacitor is known as a "snap-in" cap. The pins are crooked to make it hold onto the PCB so it doesn't fall off when you turn it around to solder it.

These usually last a very long time.
On the picture, I see a rectifier bridge right behind the cap, so that means it's a power supply smoothing cap. This means characteristics don't matter much as long as it has a voltage rating and capacitance equal to or higher than the old one.
To pick a proper replacement cap, make sure it fits, so check pin spacing. These caps are available in plenty of diameter/height combinations. Since the diode bridge is very close, make sure the new cap isn't too wide. Height may be a factor if some other device in the arcade cabinet is mounted right above the board, so check that too. Also look if the original has more than two pins, if this is the case check which pins are for mechanical stability and which are for electrical connection.
Since modern technology squeezes more µF into a smaller size you may have to get a higher value cap to get the correct pin spacing.
Get a snap-in cap which will have thick crooked pins as shown on the pic above. A standard radial cap will have much thinner pins, thus plenty of empty space left in the holes, which makes soldering more difficult and less reliable.


text:
Q: How to save the updated stae values back to database(mongo db) in react-dnd I am a beginner in learning react.js. I have developed a simple todo app using react-dnd. I was able to implement react onDragEnd function where the cards in each column are able to be dragged and dropped within and between columns. However, once I refresh the page the page is reset and all the dragged elements are not saved.
Therefore, I want to know, how to permanently save the position of the dragged element in react dnd with backend. Here the names defined under useState as "TO-DO, INPROGRESS,READY" are recognized as keys in retrieving data. Also, stage.staus has the same value (either TO-DO, INPROGRESS OR READY) stored in database
sample picture of the frontend
My code:
function ProjectsDashboard() {
  const [state, setState] = useState({
    //creating 3 columns
    "TO-DO": {
      title: "To do",
      items: [item, item2], //temporary data valuesa
    },
    "IN-PROGRESS": {
      title: "In Progress",
      items: [],
    },
    READY: {
      title: "Completed",
      items: [],
    },
  });

  //for retrieval
  const [stages, setStages] = useState("");

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getStages());
  }, [dispatch]);
  const { stage } = useSelector((state) => state.stage);

  const handleDragEnd = (result) => {
    if (!result.destination) return;
    const items = stage;
    const [recordedItem] = items.splice(result.source.index, 1);
    recordedItem.status = result.destination.droppableId;
    items.splice(result.destination.index, 0, recordedItem);
    setStages(items);
    setStages({ status: result.destination.droppableId });
    console.log(stage, "STAGE");
    console.log("STATE");
  };

  return (
    <GridWrapper>

        <DragDropContext onDragEnd={handleDragEnd}>
          {_.map(state, (data, key) => {
            return (

                {console.log(key, "KEY")}
                <ProjectWrapper className="border">

{data.title}

                </ProjectWrapper>
                <Droppable droppableId={key}>
                  {(provided, snapshot) => {
                    return (

                          {stage.map((stages, index) => {
                            console.log("map");
                            if (stages.status === key)
                              return (
                                <Draggable
                                  key={stages._id}
                                  index={index}
                                  draggableId={stages._id}
                                  className="drag"
                                >
                                  {(provided, snapshot) => {
                                    console.log(snapshot);
                                    return (

                                        {/* card name */}

                                        <button
                                          className="stageDetails"
                                          style={{
                                            padding: "0",
                                            border: "none",
                                            background: "none",
                                          }}
                                          onClick={() => {
                                            setFormData(stages);
                                            dispatch(
                                              getSpecificStages(stages._id)
                                            );
                                            //handleShow();
                                            stageclickPopup(true);
                                          }}
                                        >
                                          {stages.stageName}
                                        </button>
                                        <button
                                          className="btn-delete"
                                          onClick={() => {
                                            deleteS(stages._id);
                                            handleClose();
                                          }}
                                        >
                                          <DeleteOutlinedIcon className="delete" />
                                        </button>

                                    );
                                  }}
                                </Draggable>
                              );
                          })}
                          {provided.placeholder}

                    );
                  }}
                </Droppable>

            );
          })}
        </DragDropContext>

    </GridWrapper>
  );
}

export default ProjectsDashboard;


text:
Q: Should an IBOutlet only be used for interface UI elements? Basic question here about the structure of a basic iOS MVC app..
I know IBOutlets are used for accessing view elements such as buttons and labels and such and modifying or getting their values..
Is it normal though to use an IBOutlet to access another object in your app FROM a view??
For example..
@interface CustomView : UIView {
    IBOutlet Person *person;
}

Should we use an outlet to the person(Model) in order for the view to display information about the person?
Or should the view just instantiate a Person object directly without using IBOutlets and Interface Builder.
Thank you for your clarifications.
*For some reason, the tutorial I'm following put the Model class in the nib.

A: IBOutlet is nothing more than an annotation that tells Interface Builder which properties and/or instance variables of a given class should be visible (and therefore available to connect) in IB. You generally need to connect one or more subclasses of UIViewController to the view instances in a given nib file, but in accordance with the Model-View-Controller design pattern, you should avoid connecting View objects directly to model objects.
Apple has an overview of this design pattern in their iOS Tutorial. You should also read Apple's Human Interface Guidelines -- it'll really shed light on a lot of these kinds of issues for you.

A: You don't have to use IBOutlet unless you want to bind an object from a nib to this variable in Interface Builder. The compiler ignores the IBOutlet "keyword" (it's not really a keyword, but an empty preprocessor macro), it just tells interface builder that it can be connected to an object instantiated in a nib.
If you need your Person object in the nib create it in Interface Builder and connect it to an outlet. If you don't need to access it from the nib you might as well create it in code and not make it an outlet.


text:
Q: how to prove the $n$-times self-product of a map is null-homotopic Let $k$ be a fixed positive integer and $\Sigma_k$ the $k$-th symmetric group. By letting $\Sigma_k$ permuting an orthonormal basis of a $k$-dimensional Euclidean space, there is a "regular representation"
$$
r_k: \Sigma_k\longrightarrow O(k)
$$
which induces a map between classifying spaces
$$
\rho_k: B\Sigma_k\longrightarrow BO(k).
$$
Let $X$ be a finite CW-complex and a map
$$
f: X\longrightarrow B\Sigma_k.
$$
For any positive integer $n$, we produce a map by taking self-product of $f$ for $n$-times
$$
\prod_n f: X\longrightarrow \prod_n B\Sigma_k
$$
and have a composition
$$
g_n: X\overset{\prod_n f}{\longrightarrow}\prod_n B\Sigma_k\overset{\prod_n \rho_k}{\longrightarrow}\prod_n BO(k)\longrightarrow BO(nk)=G_{nk}(\mathbb{R}^\infty).
$$
where the last map is induced by the inclusion
$$
\prod_n O(k)\longrightarrow O(nk).
$$
Question: I want to prove that for any $k$, any finite CW-complex $X$ and any map $f$,  there exists a positive integer $n$ such that $g_n$ is null-homotopic. Is it true? How to prove?

A: Yes, this is true.
Your map $B\Sigma_k\rightarrow BO(k)$ gives rise to a map $B\Sigma_k\rightarrow BO$, i.e. an element in the reduced K-theory group $\tilde{ko}^0(B\Sigma_k)$.
Now that whole group is probably not torsion, but the Atiyah-Hirzebruch spectral sequence tells you that, if $K$ is a finite-dimensional $CW$ complex with torsion homology groups, $\tilde{ko}^0(K)$ is torsion.
So if you take $K$ to be a suitably modified skeleton of $B\Sigma_k$ (see below), it follows that there is $n$ such that the map
$$K\rightarrow B\Sigma_k\rightarrow BO(k)\rightarrow BO(nk)$$
is null homotopic, where the last map is the times $n$ map.
But if $X$ is a finite-dimensional $CW$-complex, the map $X\rightarrow B\Sigma_k$ will factor over $K$ if we choose $K$ to be a sufficiently high-dimensional "skeleton".
I was imprecise above about $K$ being a "suitably modified skeleton", let me clarify this:
If $Y$ is a CW-complex with torsion homology groups, then, for each $n$, there is an $n+1$-dimensional CW complex $K$ with torsion homology groups and a map $K\rightarrow Y$ that induces isomorphisms on homology up to degree $n-1$.
To build that $K$, simply take $\tilde{K}$ to be the $n$-skeleton of $Y$. Now the $n$-th homology of that is not necessarily torsion, but since rationalized homotopy and rational homology agree, we can choose maps from $S^n$ to $\tilde{K}$ such that they are nullhomotopic in $Y$, and their images in $H_n(\tilde{K})$ generate it rationally. But then form $K$ by attaching cells along those maps. $K$ comes with a map to $Y$, and has torsion homology.


text:
Q: how to check if a field in one file does not contain list of values from another file in UNIX I have two files, one has the data that is transactional value for that column. Suppose currency code and the another file has the valid/expected currency code.
File1 :
ID|col1|curr_cd
1|abc|INR
2|def|USD
3|xyz|3AB
4|tuv|ABC
....
File2
curr_cd
INR
USD
CAD
....
I need the list of values those are invalid, which means is present in File1 but is not present in File2. File1 may contain millions of transactions, so I need an AWK or a command that could give me the result faster.
Can anyone help me here please.

A: # Returns whole row
fgrep -vf file_2 file_1

# Returns just the bad value
fgrep -vf file_2 file_1 | awk -F '|' '{print $2}'


text:
Q: Is it possible to Debug iOS app on Windows/Linux? is there a way how to debug an iOS mobile app on Windows or Linux (Ubuntu)?
I have an application which runs fine on Android, but it has some flaws on iOS. For Android debugging, I always used the Chrome device inspector and I am wondering if it's possible for iOS too?
The Webkit Adapter I found (https://github.com/RemoteDebug/remotedebug-ios-webkit-adapter) works for debugging websites opened on iPhone via SAFARI browser, but not for the mobile app. Any ideas?
Thanks a lot for any suggestions.

A: Yes, you can develop your own lldb to support debugging non-jailbroken iOS device on Window, like this