Cmake linking to shared library cannot find library

Question: On Ubuntu, I have two directories: build and src. In src, my CMakeLists.txt file has the lines:
add_executable(Test main.cpp)

target_link_libraries(Test libCamera.so)

After running cmake in the build directory (cmake ../src), I then copy my library file libCamera.so into the build directory. After running make, the main.cpp.o file compiles successfully, but I receive the following error during linking:
/usr/bin/ld: cannot find -lCamera

Why is this? The shared library is in the same directory that I am building in... and the same thing happens if I copy the library to /usr/bin...
Answer: You should not put prefix lib and suffix .so of the library, so just use:
target_link_libraries(Test Camera)

if your library not found you may need to add directory, where library is located:
link_directories( /home/user/blah ) # for specific path
link_directories( ${CMAKE_CURRENT_BINARY_DIR} ) # if you put library where binary is generated

Note: you copied lib to /usr/bin but unlike Windows where dll files stored with executables, in Linux that is not the case, so it would be /usr/lib, not /usr/bin. Also you may change LD_LIBRARY_PATH variable to make your program to find a library in a custom location.
Comment: If I do that, then I get the same error message as before: `Linking CXX executable Test`, `/usr/bin/ld: cannot find -lCamera`
Comment: I have added the line `link_directories(/home/karnivaurus/Projects/Test/build)` to my CMakeLists.txt file, but I still get the same error.... However, if I copy the library to `/usr/lib`, as you suggested, it compiles fine.... Any idea why the first attempt did not solve it?
Comment: @Karnivaurus btw for `build` you should use cmake var as mentioned above, but full path should still work. Why it does not is difficult to say without looking into actual CMakeLists.txt
Comment: @Karnivaurus note that binary is being buit and linked in build/src subdirectory. If you put lib there you may not need to add that dir. But normally you should not copy library there but use `find_library()` instead


Why Eclipse Glassfish does not support Eclipse Microprofile

Question: Why Eclipse Glassfish does not support Eclipse Microprofile ?
And I am confused about Eclipse Microprofile Application,
Eclipse Microprofile Application can be a servlet application(war) nor ony a jar application?
I think servlet-api not nessary for Eclipse Microprofile Application.
Answer: I'll start with your last question and work backwards.
You are correct.  The Servlet API is not part of Eclipse MicroProfile. So an implementation of the MicroProfile spec need not support servlet. If you take a look at the various MicroProfile implementations you'll see that some of them are derived from application servers, and some are not.  Those that have roots in an application server might support servlet, but others might not.
The MicroProfile spec does not specify application packaging or deployment. Just the APIs that must be supported. So some MicroProfile implementations might support war files (likely those with roots in application servers) but others won't. Most of them will support some form of an executable jar and runtime dependency management so that you can create a self-contained, immutable Docker image of your application and its runtime dependencies. In this scenario the value of war packaging is questionable.
Eclipse GlassFish is a Jakarta EE implementation, and the focus has been to deliver a Jakarta EE 8 release. MicroProfile is part of Eclipse, but it is not part of Jakarta EE (at least not yet). So there is no requirement for Eclipse GlassFish to implement MicroProfile (at least not yet).


Dummy debug class stuck on std::endl overload

Question: I thought I was going to do a quick-and-dirty __DEBUG enabled tracing with something like this:
#ifdef __DEBUG
#   define  dbg std::cout
#   define  err std::cerr
#else

#include <iostream>

class dummy_cout
{
private:

public:
    dummy_cout & operator << ( auto &obj )
    { return *this; }

    dummy_cout & operator << ( std::result_of< decltype( &std::endl ) >::type &obj )
    { return *this; }
};

#   define  dbg dummy_cout()
#   define  err dummy_cout()
#endif

int main( int argc, char *argv[] )
{
    dbg << "Bla, bla. bla..." << std::endl;
}

But it gives me:
cond_dbg.cpp:16:66: error: decltype cannot resolve address of overloaded function
  dummy_cout & operator << ( std::result_of< decltype( &std::endl ) >::type &obj )

I have also tried a half-dozen variations of decltype, result_of, ostream, etc. but I still haven't gotten any step further.
It oughta be simple. If I compile the code defining __DEBUG, I'd have cout and cerr. If I make a normal compilation, I'd have my dummy_cout, that simply does nothing but allows my code to compile without changes and little clutter.
Any help will be greatly appreciated.
Comment: Why do you need to treat `std::endl` separately?  It should be captured by the templated version.
Comment: A comment on your `operator <<` overload in `dummy_cout` class: That is just not how you overload C++ `std::ostream` insertion operators....
Comment: Thanks @Henri Menke. This was my very first trial but didn't work. `template argument deduction/substitution failed`
Answer: You can't write decltype(&std::endl) because std::endl isn't a function, it's a function template:
template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );

As such, it doesn't have a type, so it doesn't make sense to ask for it. Moreover, even if it did have a type, the subsequent result_of wrapping wouldn't make any sense.
The reason that std::cout << std::endl works is that there is an overload that accepts a specific type of function pointer:
basic_ostream& operator<<(
    std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );

This operator is not a function template (it is a member function of basic_ostream, which is a class template), and so overload resolution here triggers instantiation of a specialization of endl.
To get this to work, you should just do the same thing:
dummy_cout& operator<<( std::ostream&(*p)(std::ostream&) );

or pick some appropriate CharT and Traits for your dummy type:
dummy_cout& operator<<( std::basic_ostream<C,T>&(*p)(std::basic_ostream<C,T>& ) );

Just a note. This declaration is ill-formed any C++ standard:
dummy_cout& operator<<(auto& obj);

Terse function template syntax is a feature of the Concepts TS, which is still a TS. Unless you're using -fconcepts, you need to write:
template <class T>
dummy_cout& operator<<(T& obj);

Comment: Shouldn't you additionally point out the issue with the member function declaration: `dummy_cout& operator << ( auto &obj );`?.. Or is it now a legal declaration in C++XX?
Comment: @WhiZTiM Sure, added a note.
Comment: Thank you very much @Barry. `dummy_cout& operator<<( std::ostream&(*p)(std::ostream&) )` works simply out of the box. I've just edited my question to show some results and I'd be really thankfull if you could comment on that.
Comment: @fljx Please don't edit solutions into your questions, I've rolled back your edit. If you have a new question, just ask a new question.


Assignment has more non-singleton rhs dimensions than non-singleton subscripts error in matlab

Question: U can see a part of my code in MATLAB. when i run it, i receive this error:
Assignment has more non-singleton rhs dimensions than non-singleton
subscripts.
please help me to correct it and know it's reasons. tnx a lot.
while Time < t_stop

for i4 = 1:x
for j4 = 1:y
for k4 = 1:z

% t1 has been defined in another place and updates in every cycle
t2 = find(t1 ~= -1); %t2 is not empty because t1 has non-(-1) elements
t3 = zeros(1,numel(t2));
for i5 = 1:numel(t2)
t3(i5) = t1(t2(i5));
end;
var1 = min(t3(:));
min_time(i4,j4,k4) = var1;
if numel(find(t1 == var1)) == 1
    min_IND (i4,j4,k4) = find(t1 == var1);
else
    Temp_find = find(t1 == var1);
    min_IND (i4,j4,k4) = Temp_find(randi(numel(find(t1 == var1))));
end;

t1 = zeros(1,41)-1;
end;
end;
end;

Time=Time+1;

end;

Comment: where is the error occuring? Can you show the output of whos right before the error?
Comment: hi benoit. it occurs in this line: " min_time(i4,j4,k4) = var1; "
Comment: ok. what does 'whos' output if you put it right before this line? You will see the size of var1 and min_time, which probably are not the same thus throwing the error.
Answer: Why is your error happening?
This is due to the fact that your t2 = find(t1 ~= -1) statement returns an empty array.  This means that your t1 array does not have any entries that are not equal to -1.  As you start going down into your code, t3 = zeros(1,numel(t2)) will create an empty matrix as the number of elements in t2 are 0 due to the find call from earlier.
Next, when you get to this statement:
for i5 = 1:numel(t2)
    t3(i5) = t1(t2(i5));
end

This for loop does not execute as the number of elements in t2 equals 0.  When you get to this statement after:
var1 = min(t3(:));

var1 will also give you an empty matrix.  Finally, when you get to this statement:
min_time(i4,j4,k4) = var1;

You are trying to assign an empty value into a location in min_time.  Specifically, you are trying to assign one value to a location in min_time which should be stored in var1, but because it's empty, this is why you are getting this error.   As such, you need to double check your t2 variable to ensure that this isn't empty before you proceed with your code.

So where is the error happening?
I can see why you are getting this error, and where this is happening.  If you look towards the end of your code, you have this statement:
t1 = zeros(1,41)-1;

What you are doing is you are making t1 such that the entries are all -1.  When you go back into the next iteration of your loop, the t2 = find(t1 ~= -1) statement will return an empty array as all values of t1 are equal to -1.  Because find could not find any values that are not equal to -1, find returns an empty array stating that it could not find any locations in t1 that were not equal to -1.  This is probably not what you intended to do.
Your comment states that t1 is being set outside of the for loops before your code is executed.  Though that may be the case, you are changing t1 after the first iteration of your for loops, which will inevitably give you that error you are seeing.
As such, you probably need to correct this statement - either by removing it, or modifying it so that it is the definition that you are seeking.

Some tips for you
It really helps if you debug your code so that you can figure out what's going on.  As such, MATLAB has some great facilities to help you debug your code so you can figure out why it isn't working.  You need to set MATLAB to debug mode if you'd like to do this.  If this is something you want, in your MATLAB editor, go to the line where you see the t2 = find(t1 ~= -1); statement, and click on the horizontal dash beside the line number.  You'll see a red dot indicating that when the function runs, the function will pause at this point.
In debug mode, you are able to see what the current state of execution your code is in.  You can also examine what the variables look like, as well as step through line by line after this point so you can see what each line is doing.  You can either type in dbstep when you're in debug mode to go to the next line, or you can do this in your MATLAB editor by clicking on the Step buttons.  There are also different buttons you can choose from:

Continue - Continue running your code until you reach the next breakpoint or the function exits
Step - Run the next line of code
Step In - Run the next line of code.  If this line is a function, then you will go inside the function and be able to debug the statements within there.  If you just do Step, it runs the function, but doesn't go inside.  As such, this runs the entire function before pausing at the next line.
Step Out - If you are inside a function, doing this will run the code until the function leaves.  The code will then pause right after the point where you leave the function and you continue from there.

For more information on MATLAB debugging, check out this great MathWorks link here: http://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html#brqxeeu-178


Guess the Subset Strategy

Question: Guess the Subset Game
The game works like this. You play against an adversary.
Setup

There is a fixed set of numbers A (such as {1, 2, ... , 30})
The adversary chooses a secret subset S by removing up to k elements (such as 0-5).

Objective
You know A and k, and your job is to figure out the subset by making guesses.
Guessing
You guess a subset B.
The adversary tells you Yes if B ⊆ S (i.e. if all of the elements that you guessed are in the secret subset S) and No otherwise.

Question
What strategy can you use to figure out the subset in the fewest number of guesses?

Playable Version
You can play the game here. Choose A and k, and you can make guesses. Reveal the Secret when you think you have it figured out. Re-run the snippet to try again.

// Random Integer in [min, max)
const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
};

class GuessSubsetGame extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numGuesses: 0,
      guess: '',
      prevGuesses: [],
      revealed: false
    };
  }

  isValid = (guess) => guess
     .split(',')
     .map(val => val.trim())
     .every(element => this.props.secret.includes(element)) ? 'Yes' : 'No';

  onSubmit = (e) => {
    this.setState((state, props) => ({
      guess: '',
      numGuesses: state.numGuesses + 1,
      prevGuesses: [{guess: state.guess, valid: this.isValid(state.guess)}, ...state.prevGuesses]
    }));
    e.preventDefault();
  }

  renderPrevGuesses() {
    return this.state.prevGuesses.map(({guess, valid}) => {
      return (

          {valid} - {guess}

      );
    });
  };

  render() {
    return (

        {this.state.revealed ? 'Secret was ' + this.props.secret : <button onClick={() => this.setState({revealed: true})} >Reveal Secret</button> }

          {'Guess Number: ' + this.state.numGuesses}

        <form onSubmit={this.onSubmit}>

            Guess a Subset (like 1,2,3):
            <input
              type="text"
              name="guess"
              id="guess"
              value={this.state.guess}
              onChange={(e) => this.setState({guess: e.target.value})} />

            <input type="submit" value="Guess" />

        </form>

History

          {this.renderPrevGuesses()}

    );
  }
}

class GuessSubsetGameCreator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isBuilt: false,
      A: '1,2,3,4,5,6',
      k: 2,
      secret: null
    };
  };

  onSubmit = (e) => {
    const actualK = getRandomInt(0, parseInt(this.state.k) + 1);
    const aAsArray = this.state.A.split(',');
    const shuffled = aAsArray.sort(() => 0.5 - Math.random());
    const secret = shuffled.slice(0, shuffled.length - actualK).sort();
    this.setState({
      isBuilt: true,
      secret
    });
    e.preventDefault();
  };

  render() {
    let result;
    if (!this.state.isBuilt) {
      return (
        <form onSubmit={this.onSubmit}>

            What are the elements of A?
            <input
              type="text"
              name="A"
              id="A"
              required
              value={this.state.A}
              onChange={(e) => this.setState({A: e.target.value})} />

             How many elements can be removed?
             <input
               type="number"
               name="k"
               id="k"
               required
               value={this.state.k}
               onChange={(e) => this.setState({k: e.target.value})} />

            <input type="submit" value="Start Game" />

        </form>
      );
    }
    else {
      return <GuessSubsetGame A={this.state.A} secret={this.state.secret} />
    }
    return result;
  }
}

ReactDOM.render(
  <GuessSubsetGameCreator />,
  document.getElementById("root")
);
div {
  padding-top: 5px;
}

Thoughts

If k = size of A, I don't think we can do any better than guessing each element one at a time. i.e. {1}, {2}, {3}, ... , {30}, because each element's inclusion is independent of every other. This gives 30 guesses in the example above.
If k = 1, we could start by guessing A to see if no element was removed, and then find the missing element with a binary search. This gives about 6 guesses in the example above.
I'm still trying to puzzle out k = 2.
It seems a bit like mastermind which has been solved see this puzzling.stackexchange question, but in mastermind the adversary tells you how many of your guess are right, instead of just Yes/No.
By the way, I ran into this problem while trying to update 30 library dependencies for a software module. The build failed after updating all of them, but I strongly suspected that no more than 5 of them were causing the build to fail. (In this case, I got some more information from the logs about which one failed than a single No which helped, but it was still a lengthy process since testing the build takes about 5-7 minutes per guess).
Comment: Are you trying to minimize the *worst-case* number of guesses, or the *average-case* number of guesses? If *k* is greater than |A|/2, then the worst-case number of guesses is certainly not better than |A|, because in that case there are more than 2^(|A|-1) possible choices of the secret subset *S*, so there's no way to distinguish all of them with only |A|-1 bits of information.
Comment: The best solution would be just to guess every number. It is never beneficial to guess larger subsets. After asking about every number you have B... but like you mentioned if k is not arbitrary you can do better
Comment: With |A|=5 and k=2, there are 16 subsets, which means it would be possible to win in 4 guesses if you could cut the possibilities exactly in half with each guess. Unfortunately, that doesn't work for the first guess. Guessing one element splits it 11-5 and guessing two elements splits it 7-9.
Comment: Well, If the input is set **A** and **K** numbers, then I think it's impossible to find a faster way than trying all possible **B**. BUT, if, and only if you have a helper input like a number in **B** range. That's will help too much.
Comment: @MitchelPaulin: Re: "if k is not arbitrary you can do better": Doesn't that contradict the rest of your comment? After all, the entire question is about the case where *k* is not arbitrary.
Comment: @j_random_hacker When k=1, the adversary can choose to remove either 0 or 1 elements from the set.
Comment: If you partition |A| into k+1 parts (which need not even be of equal size), at least one of those parts must yield a "yes" answer when used as a query.  This is not necessarily part of an optimal solution, but might be a useful heuristic.
Comment: @ruakh I was going for worst-case. I like the reasoning about the k > |A|/2, I just ran the numbers for |A|=5 and k=3. There are 26 subsets the adversary could choose (5 choose 5) + (5 choose 4) + (5 choose 3) + (5 choose 2), and since we only get one bit of info each guess (Yes/No) we would need at least log2(26) ~= 4.7 guesses, which rounds up to 5 since there's always a whole number of guesses.
Comment: More generally, partitioning A into k+m parts and using each part as a query must yield at least m "yes" answers.  It's reasonable to suppose that making all parts as equal in size as possible is best in the worst case.
Comment: The way to solve this exactly is by framing it as a minimax game tree. If it could be proven that it's never beneficial to make a query that involves elements from two disjoint earlier queries, then the state space and number of "player" moves shrinks: in this case, the complete state at any point in time can be described by k, plus a list of *the sizes of* disjoint subsets of A, each of which we know contains at least one element not in S; on each "player" turn, he must choose one of these subsets, and a number less than its size. But I suspect that such "combining" queries can be beneficial.
Comment: Addenda to my previous comment: the same logic actually applies if *k* ≥ |A| / 2 (not only if *k* > |A| / 2), and it would also actually apply to the average case as well (not just to the worst case), assuming we average over all possible choices of *S*.
Comment: Is there any interest in my solution?
Answer: The following C++ program will report the length of an optimal strategy, computed according to a generalisation of the minimax game tree strategy I mentioned in a comment, and using dynamic programming for speed.  It can optionally output a trace showing a maximum-length sequence of queries under this strategy.  (It would not be difficult to output the entire tree, but as this could be a nearly complete binary tree with more than 20 levels, it's not very interesting to a human.)
Essentially it turns out that the complete state of knowledge about all elements can be represented succinctly, even if we allow queries that involve elements from multiple different earlier queries.  A state of knowledge is represented in the program as a vector in which the first element is k, the second is the number of items in A about which we know nothing (I forgot about this aspect of state in my comment), and all remaining vector elements are the sizes of disjoint "marked" subsets of A, listed in increasing order.  A "marked" subset is a subset that we know misses at least one element of S.  Knowledge state vectors are always normalised (see the normalise() function).  The same vector representation is used for representing a "player move" (a choice of some number of elements from each of the disjoint subsets of A), even though the first element (where k would be) is meaningless in this context.
One surprise was the discovery that there exist worst-case sequences of queries that cause loops in the sequence of knowledge states -- that is, there are query sequences that are infinitely long in the worst case.  Fortunately the DP could be adjusted to take care of this.
To run the program, specify k as the first command-line parameter and |A| as the second.  To add a traceback showing a particular maximum-length sequence of queries under the optimal strategy, give -t as the first parameter.
For example, running fewest_tests -t 5 30 produces:
Minimum number of queries required in the worst case: 20
One possible maximum-length sequence of queries that follow an optimal strategy:
Height=20.  Knowledge state: [5 30]
Choose [0 3]: Adversary replies YES.  (Other answer also leads to height-19 subtree.)
Height=19.  Knowledge state: [5 27]
Choose [0 3]: Adversary replies YES.  (Other answer also leads to height-18 subtree.)
Height=18.  Knowledge state: [5 24]
Choose [0 3]: Adversary replies YES.  (Other answer also leads to height-17 subtree.)
Height=17.  Knowledge state: [5 21]
Choose [0 2]: Adversary replies YES.  (Other answer also leads to height-16 subtree.)
Height=16.  Knowledge state: [5 19]
Choose [0 2]: Adversary replies YES.  (Other answer also leads to height-15 subtree.)
Height=15.  Knowledge state: [5 17]
Choose [0 2]: Adversary replies YES.  (Other answer also leads to height-14 subtree.)
Height=14.  Knowledge state: [5 15]
Choose [0 2]: Adversary replies YES.  (Other answer also leads to height-13 subtree.)
Height=13.  Knowledge state: [5 13]
Choose [0 1]: Adversary replies YES.  (Other answer leads to height-11 subtree.)
Height=12.  Knowledge state: [5 12]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-11 subtree.)
Height=11.  Knowledge state: [5 11]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-10 subtree.)
Height=10.  Knowledge state: [5 10]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-9 subtree.)
Height=9.  Knowledge state: [5 9]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-8 subtree.)
Height=8.  Knowledge state: [5 8]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-7 subtree.)
Height=7.  Knowledge state: [5 7]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-6 subtree.)
Height=6.  Knowledge state: [5 6]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-5 subtree.)
Height=5.  Knowledge state: [5 5]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-4 subtree.)
Height=4.  Knowledge state: [5 4]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-3 subtree.)
Height=3.  Knowledge state: [5 3]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-2 subtree.)
Height=2.  Knowledge state: [5 2]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-1 subtree.)
Height=1.  Knowledge state: [5 1]
Choose [0 1]: Adversary replies YES.  (Other answer also leads to height-0 subtree.)
Height=0.  Knowledge state: [5 0]

This takes about 16s on my laptop, and uses about 110Mb.  Note that I needed to increase the default stack size (/L on MSVC++); with the default of 1Mb, the largest problem that could be tackled without crashing was 5 23.  I increased it to 512Mb to be on the safe side.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cassert>

using namespace std;

bool verbose = false;

//DEBUG: Enable output of vectors
template <typename T>
ostream& operator<<(ostream& os, vector<T>& v) {
    os << '[';
    for (unsigned i = 0; i < v.size(); ++i) {
        if (i > 0) {
            os << ' ';
        }

        os << v[i];
    }

    os << ']';
    return os;
}

// Call f with every valid choice of items.
template <typename F>
void for_each_choice(vector<unsigned>& v, F f, vector<unsigned>& u, bool takenSomethingYet) {
    unsigned i = u.size();
    if (i == v.size()) {
        // We have chosen amounts to take from every subset.
        if (takenSomethingYet) {
            if (verbose) cerr << "From " << v << " we have chosen " << u << "." << endl;     //DEBUG
            f(u);
        }
    } else {
        // "+ (i == 1)": Only try choosing all the items in a subset for the unknown subset, v[1].
        // "(i <= 2 ... u[i - 1])": For a sequence of equal-size subsets, only choose a nondecreasing sequence of item counts (symmetry).
        u.push_back(0);
        for (unsigned j = (i <= 2 || v[i] != v[i - 1] ? 0 : u[i - 1]); j < v[i] + (i == 1); ++j) {
            // Try choosing j items from this set
            u.back() = j;
            for_each_choice(v, f, u, takenSomethingYet);
            takenSomethingYet = true;
        }
        u.pop_back();
    }
}

// For convenience.
template <typename F>
void for_each_choice(vector<unsigned>& v, F f) {
    vector<unsigned> u(1, 0);       // First position, where k would be, is ignored
    for_each_choice(v, f, u, false);
}

void normalise(vector<unsigned>& r) {
    if (verbose) cerr << "normalise(" << r << ") called." << endl;       //DEBUG
    // Get rid of all subsets of size 0 or 1.
    unsigned j = 2;
    for (unsigned i = 2; i < r.size(); ++i) {
        if (r[i] <= 1) {
            r[0] -= r[i];       // Decrease k whenever we have a singleton marked subset: its single member must be marked
        } else {
            r[j++] = r[i];
        }
    }
    r.erase(r.begin() + j, r.end());

    // If the maximum possible number of marked elements are already accounted for by disjoint marked subsets, then all "unknown" elements
    // are really known not to be marked.
    if (r.size() == r[0] + 2) {
        r[1] = 0;
    }

    sort(r.begin() + 2, r.end());
    if (verbose) cerr << "Result of normalise(): " << r << "." << endl;       //DEBUG
}

// Return configuration resulting from the adversary saying "yes" to the choice u
vector<unsigned> yes(vector<unsigned> v, vector<unsigned> u) {
    if (verbose) cerr << "From " << v << ", answer YES to " << u << "." << endl;     //DEBUG
    vector<unsigned> r = v;
    for (unsigned i = 1; i < v.size(); ++i) {
        r[i] -= u[i];
    }

    normalise(r);
    return r;
}

// Return configuration resulting from the adversary saying "no" to the choice u
// Note that, because normalise() sets v[1] to 0 if all marked elements are already exhausted by marked disjoint subsets, this function can never
// produce a contradictory knowledge state (that is, one with more than v[0] disjoint marked subsets).
vector<unsigned> no(vector<unsigned> v, vector<unsigned> u) {
    if (verbose) cerr << "From " << v << ", answer NO to " << u << "." << endl;     //DEBUG
    vector<unsigned> r = v;
    r.push_back(0);
    for (unsigned i = 1; i < v.size(); ++i) {
        if (u[i] > 0) {
            r[1] += v[i] - u[i];    // Tricky: In every subset that we chose some elements from, every *unchosen* element goes back in the "we dunno" pile.
            r[i] -= v[i];           // For all i >= 2, this will set r[i] to 0, and this element will be deleted by normalise()
            r.back() += u[i];
        }
    }

    normalise(r);
    return r;
}

// First element is k, the maximum number of marked items.
// Second element is number of items about which we know nothing.
// Remaining items are in sorted order, and are the sizes of disjoint subsets of items: we know that each of these subsets contains at least one marked item.

map<vector<unsigned>, int> memo_;           // Holds solutions already computed
map<vector<unsigned>, vector<unsigned>> nextMove_;      // Holds a best move for already-computed solutions

unsigned solve(vector<unsigned> v) {
    if (verbose) cerr << "solve(" << v << ") called." << endl;      //DEBUG

    auto us = memo_.find(v);
    if (us != memo_.end() && (*us).second == -1) {
        if (verbose) cerr << "solve(" << v << ") returning " << (UINT_MAX - 1) << " because the current state already appeared in the history, indicating an infinite loop." << endl;      //DEBUG
        return UINT_MAX - 1;            // -1 so that it survives the +1 it gets later
    }

    // Because v has been normalised, we have identified all marked states iff there are no unknown elements and no marked subsets.
    if (v.size() == 2 && v[1] == 0) {
        if (verbose) cerr << "solve(" << v << ") returning 0 since no unknown elements could be marked." << endl;      //DEBUG
        return 0;
    }

    if (us == memo_.end()) {
        // Haven't computed the solution to this subproblem yet: do it now
        us = memo_.insert(make_pair(v, -1)).first;      // Tell descendant calls that this state is in the history and would lead to a worst-case infinite loop

        // Generate every possible successor state
        unsigned best = UINT_MAX;
        vector<unsigned> bestMove;
        for_each_choice(v, [&](vector<unsigned> u) {
            unsigned cur = 1U + max(solve(yes(v, u)), solve(no(v, u)));
            if (cur < best) {
                best = cur;
                bestMove = u;
            }
        });

        (*us).second = best;
        nextMove_[v] = bestMove;
    }

    if (verbose) cerr << "solve(" << v << ") returning " << (*us).second << "." << endl;      //DEBUG
    return (*us).second;
}

// You must call solve() first to populate nextMove_[].
void traceBack(vector<unsigned> v) {
    cout << "One possible maximum-length sequence of queries that follow an optimal strategy:\n";
    while (true) {
        unsigned iSteps = solve(v);
        vector<unsigned> u = nextMove_[v];
        cout << "Height=" << iSteps << ".  Knowledge state: " << v << endl;

        if (iSteps == 0) {
            break;
        }

        cout << "Choose " << u << ": Adversary replies ";

        unsigned hYes = solve(yes(v, u));
        unsigned hNo = solve(no(v, u));
        if (hYes == iSteps - 1) {
            cout << "YES.  (Other answer " << (hYes == hNo ? "also " : "") << "leads to height-" << hNo << " subtree.)\n";
            v = yes(v, u);
        } else {
            assert(hNo == iSteps - 1);
            cout << "NO.  (Other answer " << (hYes == hNo ? "also " : "") << "leads to height-" << hNo << " subtree.)\n";
            v = no(v, u);
        }
    }
}

int main(int argc, char** argv) {
    int nArgs = 0;
    bool showTraceback = false;

    if (string(argv[1]) == "-v") {
        verbose = true;
        ++nArgs;
    }

    if (string(argv[nArgs + 1]) == "-t") {
        showTraceback = true;
        ++nArgs;
    }

    unsigned k = atoi(argv[nArgs + 1]);
    unsigned n = atoi(argv[nArgs + 2]);

    vector<unsigned> v(2);
    v[0] = k;
    v[1] = n;

    normalise(v);       // Needed in case k=0.

    cout << "Minimum number of queries required in the worst case: " <<  solve(v) << endl;

    if (showTraceback) {
        traceBack(v);
    }

    return 0;
}

Comment: I'll try the code out this weekend. It's not clear from your trace output what the choose [0,3] means...I'm guessing that means "guess a set with three elements that you haven't seen before"...also, am I reading the trace correctly that the best strategy takes the most steps when the adversary always says YES, i.e. no elements were removed from the initial set?
Comment: "Choose [0 3]" means "Take 3 items from the set of items we know nothing about", which is not necessarily the same as the set of items we haven't seen before (although they mean the same thing until such time as we take items from a set that we know something about).  Although the adversary always YES in this trace, notice that at all but one adversary choice point, choosing NO leads to a tree of the same height, and thus a sequence of the same length.
Comment: I tried out the code and played around with it just a bit, and changing "if (hYes == iSteps -1)" to "if (hYes == iSteps -1 && hYes != hNo)" made the output a lot more interesting for "-t".

It results in the same height of tree, but gives a better description of how the knowledge state changes with both YES and NO answers and how to guess within subsets that were previously guessed but gave a NO.
Comment: Yes, that should add some variety.  It would actually be pretty easy to make that function print out the entire tree -- it could just call itself recursively, with an extra "starting point" parameter, to handle *both* the hYes and hNo cases.  Not sure how to present it "nicely" though (maybe outputting a .dot graph?)

Guess the Subset Strategy


Função para pontos que coincidem

Question: Em um exercício, preciso criar uma função que retorne TRUE caso os pontos sejam idênticos. Para os pontos, foi implementada uma estrutura como a seguir:
typedef struct //Estrutura definida para os pontos.
{
    double x; //Coordenadas X e Y.
    double y;
} Ponto;

A função que criei foi a seguinte:
int pontoCoincide(Ponto P, Ponto Q)
{
    int coincide = 0;
    if(P.x == Q.x && P.y == Q.y)
        coincide = 1;
    return coincide;
}

Gostaria de saber se o que fiz está correto e é simplesmente isso, ou se há algo de errado. Lembrando que preciso criar a função com exatamente esses parâmetros.
Answer: Seu raciocínio está correto e pode ser implementado de outras maneiras:
Usando operadores ternários:
int pontoCoincide( Ponto P, Ponto Q )
{
    return (P.x == Q.x && P.y == Q.y) ? 1 : 0;
}

Ou simplesmente:
int pontoCoincide( Ponto P, Ponto Q )
{
    return (P.x == Q.x && P.y == Q.y);
}

Função para pontos que coincidem


Queries on System.Out.Println

Question: I have a question pertaining the method in the java, I have checked for online resources but i could not get the answer that i wanted.
I would like to know why the "out" and "println" in the statement below has to be in lowercase letters ?
System.Out.Println()

Comment: @BasilBourque: When editing the question and formatting the last part as code, you changed the capitalization - which I had taken to be the OP's *expected* capitalization. Given that the capitalization is the topic of the question, perhaps it's worth reverting that aspect? (I admit it's somewhat unclear given that the code snippet is just tacked on the end without any explanation of "this is what I have to write" or "this is what I expected to write".)
Comment: That's because that's how the java API implemented it. The `System` is the class, thus it's uppercase by convention. The `out` is a variable, thus lowercase and `println()` is a method in `PrintStream`, thus lowercase by convention as well.
In general Coding is *usually* case-sensitive so watch out for that.
Comment: @JonSkeet I do not see how my edit changes the nature of the question, as the prose explicitly says *why "out" and "println" has the be in lowercase*. Showing uppercase immediately after asking "why lowercase" seems confusing to me. But given your name, sure, I'll make the rollback.
Comment: @BasilBourque: It says they *have* to be - but given the use of capitals in both the title and the question, I read that as "This is the code I'd expect to write." I don't *think* it was an accidental capitalization there.
Comment: Related: [*What is System, out, println in System.out.println() in Java*](https://stackoverflow.com/q/12002170/642706) and [*What's the meaning of System.out.println in Java?*](https://stackoverflow.com/q/3406703/642706)
Answer: System is the name of a class (java.lang.System) and follows normal conventions.
out is a static field. This is conventionally named, but it's quite rare to see public fields for anything other than constants.
The type of out is PrintStream, and println() is just a method on PrintStream - again, conventionally named.
It may help (in terms of understanding) to break things up:
PrintStream outputStream = System.out; // Access to the out field
outputStream.println();                // Just a method call

Now as for why you have to use a lower case 'o' and a lower case 'p' in the code System.out.println() - that's just because Java is case sensitive, and the names are out and println(), not Out and Println(). They could have been named in the latter way, but that would violate normal Java naming conventions.
Answer: The System part is a class. out and println() are both instances of a type and a class respectively. Someone can correct me if I'm wrong. Unless this isn't exactly what OP asked
Comment: I don't know what you mean by "instances of a type and a class respectively", but `out` is a field and `println()` is a method
Comment: The `out` is a variable while the `println()` is a method of `out` which is of Type `PrintStream`
Answer: As Jon Skeet explained in his answer:

Java is case sensitive,
this (System, out and println) is how the respective identifiers for the class, field and method (respectively) have been specified, and
this choice of identifiers conforms to the normal Java naming conventions.

There is however one small wrinkle.
The out variable is declared as a static final field and is (from a certain perspective) a constant.  It arguably could therefore have been named as OUT rather than out.
Q: Why isn't it?
A: A couple of reasons:

The conventions for what qualifies for "constant-ness" are unclear.
While you cannot assign a value to System.out, the object it refers to is mutable by design.
In fact, there is an official / supported way to change System.out ... despite it being declared as static final.  (The System.setOut method.)

Queries on System.Out.Println


PHP session expires while in use

Question: Recently my webhost changed the PHP configuration. The only complaint I have is that sessions expire while in use.
Generally, I just write once to the session, but read many times, so I thought this may be because the filemtime wasn't changing, so every time I read, I also write by incrementing a counter. Still nothing, after 24 minutes, whether the session is being used or not, it gets cleared.
Any ideas on how to fix this?
Comment: You could set up a your own [`session.save_path`](http://nl1.php.net/manual/en/session.configuration.php#ini.session.save-path) to a dir under your control. But really, your webhost should fix this themselves asap.
Comment: BTW: it seriously sounds like they've mounted a disk with `noatime` option.. Which indeed, would let PHP time out the session. Tell them that, and ask for a session save path on a disk _with_ atime.
Answer: PHP constantly reads and writes the session data file when you start a session and end the script (or call session_write_close()), so the file mtime should change. There is no need to change the atime option of the filesystem.
But things can easily go wrong beyond that, including having strange cronjob scripts running that delete session files. Without you complaining at the service desk, they will never fix it.

PHP session expires while in use


$r=3 i \cos (t \omega )+4 j \cos (t \omega )+5 k \sin (t \omega )$ Speed

Question: Vector Valued Function
Ive been aksed to find the velocity, speed and acceleration and describe the motion of a particle whose position at time t is:
$$r=3 i \cos (t \omega )+4 j \cos (t \omega )+5 k \sin (t \omega )$$
$$\frac{dr}{dt}=-3 i \omega  \sin (t \omega )-4 j \omega  \sin (t \omega )+5 k \omega  \cos (t \omega )$$
My problem is that the speed is given as the absolute value of the velocity, but I am not able to see that the speed is 5[Omega]
Answer: from what you get
$$\begin{align}
\frac{dr}{dt}&=-3i\omega\sin(t\omega)-4j\omega\sin(t\omega)+5k\omega\cos(t\omega)\\
\left|\frac{dr}{dt}\right|^2&=\frac{dr}{dt}\cdot\frac{dr}{dt}\\
&=\left[-3i\omega\sin(t\omega)-4j\omega\sin(t\omega)+5k\omega\cos(t\omega)\right]\cdot\left[-3i\omega\sin(t\omega)-4j\omega\sin(t\omega)+5k\omega\cos(t\omega)\right]\\
&=9\omega^2\sin^2(t\omega)+16\omega^2\sin^2(t\omega)+25\omega^2\cos^2(t\omega)\\
&=25\omega^2\cos^2(t\omega)+25\omega^2\sin^2(t\omega)\\
&=25\omega^2[\cos^2(t\omega)+\sin^2(t\omega)]\\
&=25\omega^2\\
\left|\frac{dr}{dt}\right|&=5|\omega|
\end{align}$$


.filter not a function error?

Question: Created a function that returns the sum of the two lowest positive integers from an array. My problem is that it seems to work fine on CodeWars website, but when I run it in Chrome console it's giving me the .filter is not a function error. I suspect its a syntax error in the arrow functions, but I can't for the life of me work it out!
function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

sumTwoSmallestNumbers(544, 32654, 34297, 9237, 343, 98); // 441

Comment: You haven't passed an array.
Comment: `sumTwoSmallestNumbers([544, 32654,......])`
Comment: simple debugging `function sumTwoSmallestNumbers(numbers) { console.log(numbers); `
Answer: You need to pass an array like,

function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1)
  filter.sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers([544, 32654, 34297, 9237, 343, 98])); // 441

Or in ES6 you can use spread operator like,

    function sumTwoSmallestNumbers(...numbers) {
      const filter = numbers.filter(x => x > -1)
      filter.sort((a, b) => a - b);
      return filter[0] + filter[1];
    }

    console.log(sumTwoSmallestNumbers(544, 32654, 34297, 9237, 343, 98)); // 441
Answer: You have to use an array like so:

function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers([544, 32654, 34297, 9237, 343, 98])); // 441
Comment: christ, that's embarrassing! I was so focused on the functions that I completely missed that...
Answer: In JavaScript, filter is a method implemented on array. You have to pass the parameter (numbers) in the form of an array:

function sumTwoSmallestNumbers(numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers([544, 32654, 34297, 9237, 343, 98]));
Answer: Use Rest parameters to represent an indefinite number of arguments as an array.

function sumTwoSmallestNumbers(...numbers) {
  const filter = numbers.filter(x => x > -1).sort((a, b) => a - b);
  return filter[0] + filter[1];
}

console.log(sumTwoSmallestNumbers(544, 32654, 34297, 9237, 343, 98));
Comment: This does work too but my mistake was not putting square brackets around my array!
Comment: @daggett - Alright. However, in future you can try this value out too as it will not require brackets :)

.filter not a function error?


Why weren't the Eagles penalized for illegal touching on this quick kick in 1986?

Question: In this video you can see the Eagles punting the ball away on 2nd down and 40. Randall Cunningham punts the ball into the back of one of his offensive linemen and the ball pops up in the air but continues to travel downfield. The Redskins field the punt and return it for a few yards.
What I don't understand is why this isn't considered a 0-yard "illegal touching" penalty. Normally when a punt is touched by a member of the kicking team, the return team has the option of taking the ball at the spot where it was touched. This is the process by which a kicking team "downs" a punt. So why couldn't the Redskins have taken the ball at the spot where it hit the offensive lineman?
Answer: Because the lineman who was hit by the ball during this play was not beyond the line of scrimmage.
As Eagles lineman #63 was behind the line of scrimmage when hit by the ball, then Article 9-2-1 (Touching Behind the Line) would apply which legalizes contacting a kicked ball before it crosses the line of scrimmage.
NFL Rule 9-2-1:

TOUCHING BEHIND THE LINE.
   Any touching of the ball behind the line of scrimmage by a kicking team player
  is legal, even if the ball has crossed the line and returns behind the line.

A first touching penalty would only apply if the kicking team player who makes contact with the ball is beyond the line of scrimmage in accordance with the NFL Rulebook Article 9-2-2. (First Touching Beyond the Line):

ARTICLE 2. FIRST TOUCHING BEYOND THE LINE. "First touching" is when a player of the kicking team touches a
  scrimmage kick that is beyond the line of scrimmage before it has been touched by a player of the receiving team beyond the
  line. If the ball is first touched by a player of the kicking team, it remains in play. First touching is a violation, and the receivers
  shall have the option of taking possession of the ball at the spot of first touching, provided no penalty is accepted on the play,
  or at the spot where the ball is dead. First touching does not offset a foul by the receivers; if there is a foul by the receivers that
  is enforced, either before or after the first touching violation, the violation is disregarded, and the penalty is enforced as
  customary.


Problema com rotas angular 5x

Question: Criei um novo modulo em minha aplicação com a minhas rotas e fiz os inports necessário em meu app.modules, porem no console do navegador da um erro o qual não consegui resolver e também não achei nenhuma resposta para o angular 5x.
O erro que da é:

ERROR Error: StaticInjectorError[ChildrenOutletContexts]:
    StaticInjectorError[ChildrenOutletContexts]:

Meu arquivo de rotas é:
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CursosComponent } from './cursos/cursos.component';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

const APP_ROUTES: Routes = [
    { path: 'cursos', component: CursosComponent },
    { path: 'login', component: LoginComponent },
    { path: '', component: HomeComponent }
];

const routing: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES);

E meu app.module seria esse:
import { BrowserModule } from '@angular/platform-browser';
import { MaterializeModule } from 'angular2-materialize';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { CursosComponent } from './cursos/cursos.component';
import { RouterModule, Routes } from '@angular/router';

@NgModule({
        declarations: [
                AppComponent,
                HomeComponent,
                LoginComponent,
                CursosComponent
        ],
    imports: [
        BrowserModule,
        RouterModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Alguém tem alguma ideia de como resolver isso?
Answer: Olá!
No seu app.module você deve importar o RouterModule já invocando o método forRoot(), conforme está abaixo:
imports: [
    BrowserModule,
    RouterModule.forRoot(APP_ROUTES)
]

Acredito que este é o problema.
Espero ter ajudado.
Answer: Apesar de ter algum tempo já esta pergunta, o problema parece está no seu app.module, é como o Pedro Buzzi Filho disse, a invocação deve ser realizada no momento da importação dentro do seu app.module.
import { BrowserModule } from '@angular/platform-browser';
import { MaterializeModule } from 'angular2-materialize';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { CursosComponent } from './cursos/cursos.component';
import { RouterModule, Routes } from '@angular/router';

@NgModule({
        declarations: [
                AppComponent,
                HomeComponent,
                LoginComponent,
                CursosComponent
        ],
    imports: [
        BrowserModule,
        RouterModule.forRoot(APP_ROUTES)
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Ou
Você no seu arquivo de rotas, inserir o ngModule, fazer as importações e exportação da sua classe:
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CursosComponent } from './cursos/cursos.component';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

const APP_ROUTES: Routes = [
    { path: 'cursos', component: CursosComponent },
    { path: 'login', component: LoginComponent },
    { path: '', component: HomeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(APP_ROUTES)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Problema com rotas angular 5x


Pra que serve o comando "res.send()" em Express?

Question: Estou estudando NodeJS para fins acadêmicos e durante a implementação de um projeto me deparei com esse comando. Pra que ele serve?
Answer: Node.js é um motor, essa função pode ser de qualquer "lib", no caso provavelmente é do Express, que é uma lib que pode ser usada junto com NodeJS
No caso você deve ter escrito errado, deve se referir a .send(), em um exemplo:
var express = require('express'); //Importa a lib express

var app = express();//Inicia a lib

app.get('/', function(req, res) {
  res.send('Olá mundo');
});

Cada argumento tem um significado:

req é a interface de requisição HTTP, você pode pegar o cabeçalho enviado pelo cliente/navegador, por exemplo pode pegar um upload
res é a interface de resposta HTTP, você pode enviar cabeçalhos e o corpo para o navegador.

O req (requisição) e res (resposta) em app.get('/', function (req, res) {, são os mesmos objetos que o Node fornece, para que seja possível chamar o req.pipe(), req.on('data', callback) e qualquer outra coisa que desejaria fazer sem o envolvimento do Express.

Mais detalhes clicando na tag: express

Note que os nomes deles podem mudar em function(req, res), pode fazer assim:
app.get('/', function(foo, bar) {
  bar.send('Olá mundo');
});

Então .send() envia para a resposta HTTP algo que você desejar, por exemplo se fizer isso:
app.get('/foo/bar', function(req, res) {
  res.send('Olá mundo');
});

Ao acessar a url http://meusite.com/foo/bar você irá visualizar isto na página:
Olá mundo

A resposta HTTP que chegará no browser deve ser algo como:
HTTP/1.1 200 OK
Date: Sun, 10 Oct 2017 23:26:07 GMT
Content-Length: 10
Content-Type: text/html

Olá mundo!

A primeira quebra de linha, após o ultimo header é o que divide o cabeçalho do corpo

Então essa resposta HTTP irá ser renderizada pelo navegador, é importante entender isto porque a comunicação HTTP funciona com estas duas etapas, ou seja é assim que os sites funcionam, o navegador envia uma requisição o servidor/script processa e devolve uma resposta (que você programou), algo como isto:

Views no Express
O Express tem outro métodos chamado .render para popular views e enviar como resposta, isto não tem necessariamente haver com http pois ocorre antes, ou seja é processado no servidor.
Antes do Express poder renderizar arquivos de modelo, as seguintes configurações do aplicativo devem ser feitas:
views é o diretório onde os arquivos de modelo estão localizados, por exemplo:
app.set('views', './views')

view engine é o mecanismo de modelo a ser usado, por Exemplo:
app.set('view engine', 'jade')

Em seguida instale o pacote npm correspondente ao mecanismo de modelo, digite isto no terminal/cmd:
 npm install jade --save

Após o mecanismo de visualização estar configurado, você não precisa especificar o mecanismo ou carregar o módulo do mecanismo de modelo no seu aplicativo; o Express carrega o módulo internamente, como mostrado abaixo (para o exemplo acima).
app.set('view engine', 'jade');

Crie um arquivo de modelo do Jade chamado index.jade no diretório views, com o seguinte conteúdo:
html
  head
    title!= title
  body
    h1!= message

Em seguida crie uma rota para renderizar o arquivo index.jade. Se a propriedade view engine não estiver configurada, é preciso especificar a extensão do arquivo view. Caso contrário, é possível omiti-la.
Você pode criar um estrutura para passar os dados assim { title: 'Meu titulo', message: 'Olá mundo!'}, deve ficar mais ou menos assim:
app.get('/', function (req, res) {
  res.render('index', { title: 'Meu titulo', message: 'Olá mundo!'});
});

Ao fazer uma solicitação à página inicial, o arquivo index.jade será renderizado como HTML.
Comment: @GuilhermeNascimento `+1`. Sugiro mudares `jade` para `pug`. O [Jade foi abandonado](https://pt.stackoverflow.com/q/127261/129)
Comment: entendi. Mas me tire por favor uma outra dúvida, esta resposta enviada pelo .send() para a view pode ser "atribuída" a alguma variável na view?
Comment: @MonitorLPI .send não tem haver com view, talvez vc esteja falando de `res.render`, que é uma outra função: https://github.com/expressjs/express/blob/master/lib/response.js#L985, é isso?
Comment: Estou me referindo ao .send() mesmo. Bom, é que na resposta você disse que o send() envia para a resposta HTTP o que você deseja e que esta resposta é que aparece nessa página, então achei que essa resposta pudesse ser atribuída a algum lugar. Fiquei confuso sobre o porque de executar esse comando para enviar uma resposta já que a página de resposta vai ficar "em branco" apenas com essa resposta enviada, mas acho isso já é conteúdo pra outra pergunta. Obrigado por responder e pela paciência.
Comment: @MonitorLPI editei a resposta, adicionei sobre o `Views no Express`, nesse exemplo usasse o Jade.
Comment: @MonitorLPI deve dá pra fazer sem Jade, assim que eu conseguir testar eu posto um exemplo.
Answer: @MonitorLPI
Basicamente esse é um código para rodar um servidor node na porta 3000:
const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('
Olá mundo
')
})

app.listen(3000,  (err) => {
  if (err) {
    console.log('Não foi possível rodar o servidor do JobFy');
  }else {
    console.log('Servidor rodando');
  }
})

Essa parte do método send() pode ser colocada em uma variável sim, porém tem que ser o a função toda. Ex:
const server = app.get('/', (req, res) => {
  res.send('
Olá mundo
')
})

então na parte onde o servidor fica escutando a requisição para responder, você pode usar assim:
server.listen(3000,  (err) => {
  if (err) {
    console.log('Não foi possível rodar o servidor do JobFy');
  }else {
    console.log('Servidor rodando');
  }
})

Perceba que o método send ficou dentro de "server".
"send()" é um envio. Pode usar 0 "end()" também, porém o html fica sem o "charset UTF-8".
Normalmente a galera usar o render().


Turn the uncorrelated variables into correlated ones using covariance matrix.

Question: https://scipy-cookbook.readthedocs.io/items/CorrelatedRandomSamples.html
I am wondering if there's a way to turn uncorrelated variables into correlated ones using covariance matrix.
The link above does so using the Cholesky decomposition for the normal distribution. But should it work for non-normal distributions such as poisson, uniform, etc?
Comment: Sounds like you're looking to use a Gaussian copula https://en.m.wikipedia.org/wiki/Copula_(probability_theory)#Gaussian_copula
Answer: You can use a Gaussian copula approach to combine a correlation-based dependence structure with a (pretty much) arbitrary collection of marginal distributions. This works best for continuous marginal distributions but can probably be adapted for discrete/mixed distributions too.
Let's suppose you have $n$ marginal distributions with cumulative distribution functions $F_1,\ldots,F_n : \mathbb{R}\rightarrow[0,1]$, and an $n\times n$ correlation matrix $\Sigma$. You can generate a random sample of $n$ variables with the given marginal distributions and dependence structure based on $\Sigma$ as follows:

Sample a random vector ($X_1,\ldots,X_n$) from a multivariate standard normal distrbution with correlation matrix $\Sigma$. (You already know how to do this.)
For $i=1,\ldots,n$ compute $Y_i=F^{-1}_i(\Phi(X))$, where $F^{-1}_i$ is the $i$th inverse cumulative distribution function and $\Phi$ is the standard normal cumulative distribution function.

The $Y_i$ computed in this way will be have marginal distribution $F_i$ and will have dependence structure given by the correlation matrix $\Sigma$.
Notes:

You will need to know how to compute the inverse cumulative distribution functions $F^{-1}_i$ for your chosen distributions, but that's a separate problem.
The dependence structure of the $Y_i$ is determined by $\Sigma$, which is the correlation matrix of the $X_i$, but that's not the same as saying that the correlation matrix of the $Y_i$ is $\Sigma$. In general, this will will not be the case. Indeed, depending on the marginal distributions $F_i$, the correlation of the $Y_i$ might not even be defined.


Proof of $p \mid (x,y) \Rightarrow p \mid x$ and $p \mid y$

Question: I have some troubles with the next step in my book:

$p$ is a prime number
$(x,y)$ is the GCD of $x$ and $y$

Why is it true that:
$p \mid (x,y) \Rightarrow p \mid x$ and $ p \mid y$
Comment: This is not anything special about prime numbers. The factors of $(x,y)$ are precisely the common factors of $x$ and $y$.
Comment: That's basically the definition of the GCD.
Answer: Because if we say $(x,y) = g$, then $x = ng$ and $y = mg$ with $(m,n) = 1$. Therefore, if $p|g$, obviously, $p|x$ and $p|y$.
Comment: Is  p∣x and p∣y ⇒ p∣(x,y) also true?
Comment: Yes, that's also true. If $p|x$ and $p|y$, then $x = pm$, $y = pn$. Then we have $(x,y) = p\cdot(m,n)$ so $p | (x,y)$.


NodeJS route title. What is it there for?

Question: Please forgive my ignorance. This is such a basic question I'm almost too embarrassed to ask it, but perhaps it will help some other ignoramus down the line.
In my route:
router.get('/my-page'
  , function (req, res) {
    res.render('my-page', { title: 'some page' });
  }
);

What is the title 'some page' for?
I don't think there's a HTTP Response title header, so i'm assuming it's not for that...
Does it simply set a default HTML title element, in case you don't add a title element in your HTML?
Which would imply that the route renderer checks if you added a title?
Is it necessary to include the { title: 'some page' }
Am I asking a question that I could probably get answered with 2 minutes of playing around. Yes.
Do I want you to link me to some NodeJS/express documentation? No.
Thanks <3
#ignoramusesunite
Answer: This is just a piece of data that you can use inside your HTML page however you like.
In your case, I assume you are using ejs
So you can open you ejs file and add
<%= title %>
Anywhere in your file and the title value that you passed will show!
So long story short, just a piece of data passed to your ejs file
Comment: Ohhhhh, silly me. It's simply passing data to the template/view engine. lol.
Answer: This is the documentation I was (not) looking at. Silly me
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#rendering_data_views


Azure Backup Failures

Question: We use Azure to backup some of our servers. We had 2 servers backing up successfully and tonight had to switch the Azure account they were backing up to - pretty straight forward.
Now the backup services are re-linked; one server is working totally fine and the other is presenting issues.
The backup service fails with a generic error, doing a little digging I was advised to run (Inside Diskshadow):
 SET CONTEXT VOLATILE NOWRITERS
 SET METADATA C:\Metadata.cab
 SET VERBOSE ON
 ADD VOLUME C: ALIAS systemVolumeShadow
 BEGIN BACKUP
 CREATE
 END BACKUP
 EXIT

This fails with the following error
Returned HRESULT: 80042306
Error Text: VSS_E_PROVIDER_VETO

Looking in the Event Logs I see this

The shadow copies of volume c: were aborted because of a failed free space computation.

Extra Info
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="volsnap" />
  <EventID Qualifiers="49158">20</EventID>
  <Level>2</Level>
  <Task>0</Task>
  <Keywords>0x80000000000000</Keywords>
  <TimeCreated SystemTime="2014-12-03T22:53:20.407073500Z" />
  <EventRecordID>519784</EventRecordID>
  <Channel>System</Channel>
  <Computer>WIN-GRT860AHGKA</Computer>
  <Security />
  </System>
- <EventData>
  <Data>\Device\HarddiskVolumeShadowCopy4</Data>
  <Data>C:</Data>
  <Binary>000000000200300000000000140006C0020000009A0000C003000000000000000000000000000000</Binary>
  </EventData>
  </Event>

Any suggestions?
------ Edit
The machine has around 80gig of spare space.
All the Writers show Stable and No Error.
Answer: That error can happen is you have not enougth free space (VSS_E_PROVIDER_VETO) and the shadow copie seem to direct to the same direction.
If you got a lot of free space please run a chkdsk. Last step, run a;
vssadmin list writers

and make sure they have no error there.
Comment: Thanks, theres around 70 gig of free space. I cant run a CHKDSK at the moment as its a live server, the list writers all comes back stable and no error.

Azure Backup Failures


Are there any distributions to model a customer's spend per transaction?

Question: Are there any distributions that model a person's spending habits?
Comment: My answer is not about the distribution of the customer's spend, but there's a nice thing called market basket analysis. It uses algorithm (like APRIORI) to find probabilities and some metrics that tries to explains the relations between items inside a customer's basket
Answer: Check this paper out and others like them from this guy. In my experience, it's the closest thing that's comprehensible (you'll need some decent probability/stats knowledge) and general (and works, again in my experience) to model customer lifetime value - which is very related to "spending habits".


Updating cursor rects immediately when scrolling stops

Question: I have a custom view as a documentView of a NSScrollView, which maintains its own cursor rects  with - (void)resetCursorRects.
When scrolling the view with mouse wheel (or a trackpad) it takes a while after the scrolling has stopped before Cocoa calls the - (void)resetCursorRects method. Looks like it waits for overlay scrollbars to disappear before calling it.
This takes too long, since as a user I can position my mouse to a place where a cursor rect should be before they're updated.
So how can I expedite Cocoa for calling the update method? I could manually call the method, but that is probably not the correct way of doing it.
Answer: Looks like the best way is to use NSTrackingAreas and update the cursor in its - mouseEntered and - mouseExited events.


Incluir aspas em valor de variável String

Question: Gostaria de saber como faço para declarar uma variável do tipo String em que o valor possui aspas no Visual Basic .net?
Por exemplo:
Public frase As String = "E ele disse: -"Olá a todos!""

Existe alguma expressão de escape para o Visual Basic entenda que as aspas no valor da variável fazem parte do valor, e não estão finalizando a declaração da variável?
Answer: A forma de incluir aspas duplas como texto numa String em Visual Basic é colocando duas seguidas, assim "".
O seu código de exemplo deve passar a ser:
Public frase As String = "E ele disse: -""Olá a todos!"""

Veja este exemplo no .Net Fiddle
Pode também ver um exemplo deste padrão na documentação
Answer: Sim, existe uma forma.
Você deve usar \ antes das "
Por Exemplo:
String Frase = " O cachorro é \"BRAVO\"  ";

Comment: Não existe `\"` em Visual Basic. [Veja um exemplo da documentação](https://msdn.microsoft.com/en-us/library/267k4fw5(v=vs.85).aspx)
Answer: O mais simples é usar a representação ANSI para aspas duplas: Chr$(34).
Exemplo1:
Código1:
Debug.Print wsh.CodeName & ".Range(" & Chr$(34) & Loc.Address & Chr$(34) & ")"

Resultado1: Planilha1.Range("$A$1")
Exemplo2:
Código2:
Debug.Print Chr$(34) & "Olá Mundo" & Chr$(34)

Resultado2: "Olá Mundo"
Obs.: É possível declarar uma variável para isso também caso queira:
         ExemploAspasDuplas = Chr$(34)

Referência: Incluir uma variável que representa aspas - docs.microsoft


Views : how to combine fields in exposed filter using is between operator

Question: In a view showing commerce products, with exposed filters, I need to make a slider filter for commerce_price field. This is easy with exposed filters (is between operator) and BEF module, but ...
commerce_price field is retrieved in the view by its relationship to Product variation type, and I've got 2 different Product variation types for the same product display :

And

This means you can make a slider for each one, but this makes no sense for end-user to have 2 prices slider !
And by default Views 3.x  Global: Combine fields filter doesn't provide "is between" operator, it only works with strings and operators like equal to, begins...
How can I filter the values of both relationships in a single slider for that Price field ?
Is there a Views setup way or a module to do that? If not, how can I add a custom filter to my view using API ?
Comment: If you're using Views to filter by price, be aware that you can't filter by _calculated_ price out of the box, see https://www.drupal.org/node/1020050.
Answer: This is a "smoke and mirrors" situation, in which you want the end user to experience one thing when the code is doing something completely different.
I would do a little bit of jQuery trickery.  First, I would expose all 4 fields (the high and low for each of the 2 fields) as text boxes.  Then, I would use the jQuery UI slider (which ships with Drupal Core) to update the high and low values as the user changes them.  Of course, the jQuery should hide the actual text boxes as well.  This will give you the effect that you are looking for.
Finally, if you wanted this to be ultra simple in the event that Javascript fails, you can use a form alter to hide one of the pairs of text boxes and then, when the form is submitted or the view loaded, populate the values for the other filter programmatically.
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'THE-FORM-YOU-WANT-TO-TARGET') {
    // you'll have to look through the $form array for the field you want
    // I suggest installing Devel and running dsm($form);

    $form['YOUR-FORM-ELEMENT']['#default_value'] = isset($_SESSION['max']) ? $_SESSION['max'] : 1000;
    // Do this for all the applicable form elements...

    // Finally, tell Drupal that you want to see the form when it is submitted.
    array_unshift($form['#submit'], 'MYMODULE_filter_submit');
  }
}

function MYMODULE_filter_submit($form, &$form_state) {
  $_SESSION['max'] = $form_state['values']['YOUR-FORM-ELEMENT'];
}

You'll have to double-check to see what the variables actually look like.  I suggest installing the Devel module and putting dsm($form); and dsm($form_state); at the beginning of the functions.
Lastly, any time that you add a hook, don't forget to clear your cache or Drupal won't find it.
Comment: I added code in my original answer, since the comments don't seem to support it.
Comment: I can't give you exact code, because so much of it depends on your installation, field names, view names, etc.  There are plenty of examples for this type of action, however.  In the link I provided to the jQuery UI slider, click the "View Source" link and see how they provide a function for the `slide` event that updates values on the page.  Yours will do the same, except with form elements.  The form itself can be intercepted using a `hook_form_alter()`, which can also provide a "remember last setting" by storing values in the PHP `$_SESSION` variable.
Comment: I didn't mean exact code of course :) just a snippet to illustrate your answer. And what about "Remember the last setting the user gave this filter." ?
Comment: `hook_form_alter()` is your friend here.  You can, for example, add a `#submit` hook (you probably want to put it first in the list using the PHP `unshift()` function) that reads the submitted values and stores them in `$_SESSION['min']` and `$_SESSION['max']` variable.  Then, in the `hook_form_alter()`, if the `min` and `max` values are set, then make them the default for the form values.  In other words, `hook_form_alter()` is your starting point to setting initial form values and for telling Drupal that you want to see the form when it is submitted.
Answer: I had a similar problem and my solution was to write a custom query that fetches distinct values from the desired tables in ascending order & populating the slider with the query's result. Here are the steps:
1.
 In the .module file of your custom module,
function <module_name>_preprocess_views_view(&$vars)
{
    $view = $vars['view'];
    $query = $view->query;

    //Use this to find out the machine name of view
    //drupal_set_message('
' .print_r($view->name,TRUE). '
');

    switch($view->name)
    {
        case '<view_name>':

        //Fetch distinct price values from the price table(s) & sort in ascending order since a slider ranges from min to max!
        $arr = db_query("SELECT DISTINCT column1_value FROM {price_table1},{price_table2} ORDER BY column1_value ASC")->fetchCol();

        //Convert associative arrays to normal arrays
        foreach($arr as $key=>$value)
            $normal_arr[] = (float)$value;

        //Pass variables from .module to .js file
        drupal_add_js(
            array(
                'views_slider' => array(
                    'arr_values' => $normal_arr
                    )
                ),
                array('type' => 'setting')
            );

         //Include appropriate .js file
         drupal_add_js(drupal_get_path('module', '<module_name>') . '<path_to_js_file_within_module>/<js_file>.js');

         break;
     }
}

2.
In the .js file, populate the jQuery slider using the result of the query as reference. Cookies are used to retrieve values on the slider & its textboxes even after page load/views exposed form submit.
    function ($) {
    Drupal.behaviors.views_slider = {
        attach: function (context, settings) {
            var arr_val = Drupal.settings.views_slider.arr_values;

            var min = getCookie("price-min");
            var max = getCookie("price-max");

            //Here 'edit-field-price-value-wrapper' is the id of the BEF slider wrapper.
            //You can find this by using Firebug or similar element-inspecting browser apps.
            $("div#edit-field-price-value-wrapper div.ui-slider").slider({
                min: 0,
                max: arr_val.length-1,
                values:[min, max],
                slide: function(event, ui) {
                    if (ui.values[0] > ui.values[1])
                    {
                        return false;
                    }
                    $("#edit-field-price-slider-value-min").val(arr_val[ui.values[0]]); //Id of min textbox in BEF slider
                    $("#edit-field-price-slider-value-max").val(arr_val[ui.values[1]]); //Id of max textbox in BEF slider
                    setCookie("price-min", ui.values[0], 1);
                    setCookie("price-max", ui.values[1], 1);
                },
                //When incorrect values are entered,this event updates the textboxes to their closest value
                change: function (event, ui) {
                    if (ui.values[0] > ui.values[1])
                    {
                        return false;
                    }
                    $("#edit-field-price-slider-value-min").val(arr_val[ui.values[0]]); //Id of min textbox in BEF slider
                    $("#edit-field-price-slider-value-max").val(arr_val[ui.values[1]]); //Id of max textbox in BEF slider
                    setCookie("price-min", ui.values[0], 1);
                    setCookie("price-max", ui.values[1], 1);
                }
            });
        }
    }
})(jQuery);

Hope this helps.
Comment: Thanks Supriya for your answer. This does not solves the question. I would need to mix your answer with coreyp's one in order to populate not 2 but 4 min/max textboxes. Also theme_preprocess_views_view(&$vars) should go into template.php, not custom module. And I implemented your code but despite all my adjustments (testing if min an max are null & so on), could not make it work. There's always sthing wrong with min max values and slider behavior ... tks anyway
Comment: Hello,
Did you manage to solve this problem?If yes, please post your answer here. I would like to find out the optimal solution for our problem!
Thank you.
Comment: Currently on holydays ;) I'll try to remember to post something when back. I used smoke and mirrors solution. ..


How to prevent dplyr::select from combining names rather than assigning a new name?

Question: I'm trying to select columns based on another named vector and assign a new name for that column at the same time. However dplyr appears to combine the names and I can't see an option to stop this in the documentation.
# dplyr '1.1.2'
# R Version 4.3.0

data <- data.frame(day = 1,
                   week = 2,
                   n_in_year = 365)

new_values <- c(period = "day",
 n = 365)

# This combines the names rather than assigning a new name
data %>%
  dplyr::select(time = new_values[1])

# e.g
#   time...period
# 1             1

# I want it to behave like this
data %>%
  dplyr::select(new_values[1]) %>%
  dplyr::rename(time = period)

Comment: what is your goal here, how does the final data.frame should look like? Currently with `select`, you end up with only one column from `new_values`, so you wouldn't need `data` in the first place
Comment: `data %>% select(setNames(new_values[1], "time"))`
Comment: Also, the output from `print(new_values)` may be informative: you're attempting to combine character and numeric values in the same vector.  The result may not be what you expect.
Comment: This reprex, is just to show the (IMO undesirable) behaviour of dplyr::select.
Answer: Issue
Your issue is that new_values still has its names():
data %>% dplyr::select(time = new_values[1])
#>   time...period
#> 1             1

data %>% dplyr::select(time = unname(new_values)[1])
#>   time
#> 1    1

This behavior is intentional, for the "tidy selection" used by dplyr::select().  Passing a named character vector (like new_values) of column names will allow a programmatic user to "combine" and "propagate" column names in various hierarchies.  This is illustrated by the documentation below, with symbols rather than strings:

mtcars %>% select_loc(foo = c(mpg, cyl))
#> foo1 foo2
#>    1    2

mtcars %>% select_loc(foo = c(bar = mpg, baz = cyl))
#> foo...bar foo...baz
#>         1         2

mtcars %>% select_loc(foo = c(bar = c(mpg, cyl)))
#> foo...bar1 foo...bar2
#>          1          2

Solution
While unname() does the job, you're better off just using [[ to extract the value without the name (period)...
#                                       |---|
data %>% dplyr::select(time = new_values[[1]])
#>   time
#> 1    1

#                                       |----------|
data %>% dplyr::select(time = new_values[["period"]])
#>   time
#> 1    1

...or better yet, making new_values a list, so its values (like 365) are not all coerced to strings (like "365") in a character vector:
# Original 'new_values' as a vector...
new_values <- c(period = "day", n = 365)
new_values
#> period      n
#>  "day"  "365"

# ...and new 'new_values' as a list:
new_values <- list(period = "day", n = 365)
new_values
#> $period
#> [1] "day"
#>
#> $n
#> [1] 365

# Easily select() what you want:        |-----|
data %>% dplyr::select(time = new_values$period)
#>   time
#> 1    1

Comment: Thanks Greg for this clear and comprehensive answer
Answer: Please check the updated code below
# dplyr '1.1.2'
# R Version 4.3.0

data <- data.frame(day = 1,
                   week = 2,
                   n_in_year = 365)

new_values <- c(period = "day",
                n = 365)

# This combines the names rather than assigning a new name
data %>%
  dplyr::select(time = new_values[[1]])

  time
1    1

# I want it to behave like this
data %>%
  dplyr::select(new_values[[1]]) %>%
  dplyr::rename(time = day)

Comment: Thanks I agree, this works, It's actually what I implemented. But I'm still wondering why dplyr::select does this for named vectors.
Comment: @JCran  According to the [documentation here](https://tidyselect.r-lib.org/articles/syntax.html#renaming-variables) for "tidy selection", this behavior is intentional: it lets programmatic users (ie. with dynamic sets of column names like `new_values`) rename columns in hierarchical fashion: `foo1` and `foo2`, or `foo...bar` and `foo...baz`, or even `foo...bar1` and `foo...bar2`.
Comment: @JCran I have [updated](https://stackoverflow.com/posts/76566608/timeline#history_cf9c4a52-f40b-4f72-a732-86d48a2070ff) my [answer](https://stackoverflow.com/a/76566608) with further explanation.


Prove the following using the definition of the limit? (Complex analysis)

Question: We want to prove the following:
$\lim_{z\to i} [z^2 + (1+i)z + 2] = i$
I got this far but I don't know if it's right:
$|(z^2 + (1+i)z + 2)- i| < \epsilon$
$|z^2 + z + iz + 2 - i| < \epsilon$
$|(z - i) + (z^2 + iz + 2)| < \epsilon$
$|(z - i) + (z - i)(z + 2i)| < \epsilon$
$|(z - i)(1 + (z+2i))| < \epsilon$
$|(z - i)||(1 + (z+2i))| < \epsilon$
Now what do I do? Should I restrict z or z+2i ...? I have no clue.
Thank you.
Comment: Since you make $|z-i|<\delta$ all you are left with is to _bound_ $|1+2i+z|<C$ for $z$ in some neighborhood of $i$, say $z\in B_1(i)$
Answer: Try to put $w=z-i$, so that $w \to 0$. Then $z^2=(w+i)^2=w^2+2iw-1$ and $(1+i)z=
(1+i)(w+i)=w+i+iw-1$. Hence
$$
z^2+(1+i)z+2=w^2+2iw-1+w+i+iw-1+2=w^2+(3i+1)w+i.
$$
Now, pick $\epsilon>0$ and choose $\delta<\min \{\sqrt{\frac{\epsilon}{2}},\frac{1}{2}\frac{\epsilon}{|3i+1|}\}$ and deduce that
$$
\left| z^2+(1+i)z+2 -i \right| = \left| w^2+(3i+1)w+i -i \right|= \left| w^2+(3i+1)w \right|
$$
and
$$
\left| w^2+(3i+1)w \right| \leq |w|^2+|3i+1||w|\leq\frac{1}{2}\left(\epsilon + \epsilon\right)=\epsilon
$$
provided that $|w|<\delta$.
Answer: As $z$ tends to $i$, $z-i$ becomes as little as you please, so bound the other term.
Let's say that $\quad|z-i|<\delta<1$
It implies that $\quad|1+z+2i|=|1+3i+z-i|\le|1+3i|+|z-i|<4+\delta<5$
So you have
$$|(z - i)||(1 + (z+2i))| < 5\delta$$


Find a basis of $A = (\{1, \sin(x), (\cos)^2(x), (\sin)^2(x)\})$ and determining its dimension.

Question: We consider a space F(R, R) of functions of R in R.
Let A = ({1, $\sin(x)$, $\cos^2(x)$, $\sin^2(x)$})
Find a basis of the vector subspace of F(R,R) and determine its dimension.
So I used the identity $1 - \cos^2(x) = \sin^2(x)$, so that means that $(\cos)^2(x)$ is already a linear combination of 2 of the vectors in that space, right? So the dimension would automatically be 3. so we make the basis B = $({1, \sin(x)$, $(\sin)^2(x)$}).
But in the mark scheme, it says that we need to show that this basis B is free/linearly independent. They say let 3 scalars,: a, b, c ∈ R such that
$a · 1 + b · \sin(x) + c · (\sin)^2(x) = 0$, so we need to show that $a = b = c = 0. $
They pose $x = 0, x = π/6$ and $x = π/2$ and they get a system of linear equations where:
$a = 0$
$a + b/2 + c/4 = 0$
$a + b + c = 0$
This is where I get confused. Why do they let $x = 0, π/2$ and $π/6$? And how did they get this system of linear equations? why over $2$ and over $4$? And lastly, when a question giving us a set of values, and they ask us to find a basis, what are the steps needed to take in order to find it? Do you first cancel all columns which are a linear combination of the others and that is a basis?
Sorry if that's a long question.
Thanks!
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: To be more exact, you'd better write :

$$ A = \mathrm{Span} \Big(\left\{ x \, \mapsto \, 1, \, x \, \mapsto \, \sin(x), \, x \, \mapsto \, \cos^{2}(x), \, x \, \mapsto \, \sin^{2}(x) \right\}\Big) $$

because the way you wrote it, $A$ is not a linear subspace of $\mathcal{F}(\mathbb{R},\mathbb{R})$. Moreover, this way, you insist on the fact that the elements of $A$ are *functions*.
Comment: thanks for that, i'm bad with notations and i just wrote it as was asked in the question, but this is better for sure :)
Answer: Hint: Note that you can write $A$ as

$$ A = \left\{ 1, \sin(x), \frac{1}{2}-\frac{\cos(2x)}{2}, \frac{\cos(2x)}{2}+\frac{1}{2} \right\}. $$
Answer: When we say that $ a + b\sin x + c \sin^2 x  = 0$ we mean so for every $x \in \Bbb R$. Note that this is not an equation of $x$ but an equation of functions. So the resulting function $f(x) = a + b\sin x + c \sin^2 x  $ should be so that $f$ must be the zero function from $\Bbb R$ to $\Bbb R$ that is $f$ should be the function that is uniformly $0$ for every $x \in \Bbb R$. So setting $x = 0$ is totally justified since the equation should hold for that value.
Then since $\sin 0 = 0 $ we have that $a = 0$. It seems the other two equations were given by taking $x = \dfrac {\pi}{ 6}$ and $x = \dfrac {\pi}{2}$. Again we can do this due to the reasons explained above.
Answer: By definition, your base is linearly independent if and only if $\forall x \in \mathbb{R}$ $a\times 1 + b\times \sin x + c \times \sin ^2 x = 0 \Rightarrow a=b=c=0$.
That gives you an infinite number of equations, but you only have 3 unknowns. So the easiest thing to do is to take 3 clever values which will give you 3 equations and solve for those, in order to prove the above. As you can see, the values chosen are the ones of which you know the sine explicitly.


Bass-Guitar - How much "Bent Wrist" is still ok?

Question: I'm struggling with a good left hand position, and there are multiple things that I'm not sure about. I will concentrate on one particular element here in this question:
What one usually reads (which makes sense) is that the hand should ideally be in a relaxed middle position, like the following graphic indicates:

However, it seems that for playing the lower frets on a bass, I don't have an option other than bending my wrist, especially if my thumb is placed adjacent to the index finger, as (for example) the following video of a big music educator suggests.
I have also added a screenshot from the video. I see bends like this regularly on youtube, and I was wondering - Is that level of bentness ok?

To be specific, by bentness I only mean the flexion of the hand here, not the radial or ulnar deviations - those are separate topics that I want to cover in another question.
Comment: Does 'How to hold a bass guitar while playing' answer your question?
Comment: Link to the question mentioned by @Tim https://music.stackexchange.com/questions/3390/how-to-hold-a-bass-guitar-while-playing I would say that does not answer the question, as "wrist" is only mentioned in two answers, and only with respect to strap height.
Comment: How is your hand so red?
Comment: @ElementsinSpace That's not his hand, and it's a red glove.
Answer: This musician disagrees!  I recommend watching that Adam Neely video in full, even though it is not nearly as well-produced as his more recent content, because it will give you some contrasting ideas to think about with regards to technique.  The key part is between 2:10 and 4:20.
To summarize, if you place the thumb between the index and middle finger, as the above video suggests, and you place your fingers perpendicular to the strings, also demonstrated in that video, you are predisposed to the awkward wrist angle that you see.  Adam Neely suggests placing the thumb outside the index finger, pointing almost toward the headstock, when playing in the lower positions (close to the headstock).
I guess the actual answer to "Is that level of bentness ok" would be "yes, if it doesn't cause injury"... but you can't test that out without possibly causing injury.  At the very least, if it causes pain, stop doing it.
Comment: I know Adams video, it's just that the vid is 13 years old and there still seems to be disagreement on the topic, so this thumb placement is either not yet settled, or it isn't a big deal in the end, and hence my question here in Stack exchange.

I tried playing like Adam suggests for some time, but I then run into other problems: The 45 ° angle of the index finger in the low frets makes it hard to press the strings by simple flexing.
Answer: Somebody else's rules regarding how to hold your hand and your wrist might just be perfect.
For them.
I will add this much.
Leave your arms, elbows, wrists, hands FREE to move about in whatever angle works for you.
As Edward implied, you want to avoid injury.
You want to avoid restrictive postures, chair arms, structures, couches, bed pillows, anything that causes you to contort your wrists and tendons in an unnatural and uncomfortable position.
That's why I am a fan of practicing and performing standing up, with the bass guitar strapped on high on your belly.
Free yourself.
Find that which feels natural and comfortable.
And that will lead to your groove, your own vibe, and your long life of bass playing without injury.
Comment: I hope it will come like that, but at the moment I feel like the thing that causes me to contort my wrists and tendons in an unnatural and uncomfortable position is the bass-guitar.


Alterar TextView com evento na ListView

Question: Gostaria de alterar o valor total sempre q um item for alterado...
Class que faz a soma:
public class Somar {

    private List<Carrinho_Item> lista;
    private double total = 0;

    public Somar(List<Carrinho_Item> lista) {
        this.lista = lista;

        for (int i = 0; i < lista.size(); i++){

            this.total = total + lista.get(i).getPreco() * lista.get(i).getQuantidade();

        }
    }

    public double getTotal() {
        return total;
    }

}

Activity principal (Funções relevante):
public void AdicionarProduto(final List<Produto> list, Cores cor_final, String tamanho_final, String quantidade, List<Cores> cores, int total_pedido) {
        contador++;
        carrinho_item.add(new Carrinho_Item(list.get(contador).getIdProduto(), list.get(contador).getDescricao(), list.get(contador).getCodigoProduto(), cor_final.getCor(), cor_final.getPreco(), cor_final.getIdVariacao(), tamanho_final, Integer.parseInt(quantidade), contador));
        listView.setAdapter(new ProdutoAdapter(Carrinho.this, R.layout.list_carrinho, carrinho_item, cores));

        SomarTotal();

    }

public void SomarTotal(){
    Somar soma = new Somar(carrinho_item);

    total.setText("R$: "+soma.getTotal());
}

Evento da Lista que deve alterar TextView da Activity:
 public View getView(final int pos, View convertView, ViewGroup parent) {
        final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView2 = inflater.inflate(R.layout.activity_carrinho, parent, false);

        final TextView txtTotal = (TextView) rowView2.findViewById(R.id.total);

        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getContext());

                alert.setTitle("Edição do pedido")
                        .setCancelable(false)
                        .setIcon(R.drawable.ic_editar)
                        .setView(viewDialog)
                        .setPositiveButton("Editar pedido", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                item.get(pos).setQuantidade(Integer.parseInt(txtQuantidade.getText().toString()));
                                Somar soma = new Somar(item);
                                txtTotal.setText("R$: "+ soma.getTotal());
                                notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("Voltar", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .show();

            }
        });

        return rowView;
    }

Answer: Declarar
Runnable run;

No seu onCreate
 run = new Runnable() {
     public void run() {

         adapter.notifyDataSetChanged();
         listView.invalidateViews();
         listView.refreshDrawableState();
     }
 };

Após alteração da lista
runOnUiThread(run);

ou, se estiver em um fragmento
getActivity().runOnUiThread(run);

Answer: Utilize uma interface e faça sua Activity observar a mudança.
public interface Observer {
   void onChange(Soma soma);
}

Depois faça sua Activity implementar a interface Observer e passe uma referência para a ListView via construtor ou método setter.
Tendo uma referência do "observador", emita o evento quando a mudança acontecer chamando onChange()
Observer listener;

/*...*/

public void setObserver(Observer listener) {
   this.listener = listener;
}

/*...*/

public void LocalOndeOcorreAmudanca() {
    listener.onChange(soma); // Emita o evento passando como parâmetro a soma
}

Agora na Activity, sobrescreva o método onChange e atualize o TextView
@Override
public void onChange(Soma soma) {
   tvTotalSoma.setText(String.valueOf(soma.getTotal()));
}

Esse é um pseudo padrão Observer, porém deve funcionar. É o terceiro problema que proponho essa solução. Espero que ajude, abraço!

Alterar TextView com evento na ListView


ASP.NET WebService - Object with Properties named ABC and ABCField

Question: I have an object with two properties 'ABC' and 'ABCField'. When this object is passed to an .NET application (.NET 3.5 CF) via a WebService a Reference.vb object is created on the client which declares the properties which access variables with the same name + 'Field'.
As a result I get

Error 2   'abcField' is already declared as 'Private aBCField As
  ABCOption' in this class.

<code>  '''<remarks/>
    Public Property ABC() As ABCOption
        Get
            Return Me.aBCField
        End Get
        Set
            Me.aBCField = value
        End Set
    End Property

    '''<remarks/>
    Public Property ABCField() As String
        Get
            Return Me.aBCFieldField
        End Get
        Set
            Me.aBCFieldField = value
        End Set
    End Property
</code>
For compatibility reasons I would prefer not to rename or remove the properties in this object.
Is there a way arround this? Is there an attribute which can be set to change the name of the property as it is sent over the Web Service?
Answer: Its funny how once you submit a question inspiration strikes.
I have used the  Xml.Serialization.XmlIgnore() attribute in the object on the service side to hide the property 'ABC' from the client and created a new property called 'ABCProxy' property which gets and sets 'ABC'.


Roman numeral anaysis help

Question:
Hello,
I'm trying to do a roman numeral analysis of this piece, but i could not figure out the first two bars. Especially the third beat of the second bar.
Comment: Why not show us what you *have* figured out?
Comment: One hint: the low Ab in those opening measures is sometimes just a pedal tone, not always part of the harmony.
Answer: Ok this one is a little Tricky because you have Pedal point on the tonic (Ab) in the start. Which means other chords (that does not consist the Tonic) may appear.

In the example I'll write 3:2 to indicate measure 3, beat 2.
Here's what I think should be there:

you are on Ab-Major so the first one is obviously "I" (in the pickup measure)
1:1 It's obviously "I" too.
1:2 it's "V7" (Eb7) BUT the Prima (Eb) is missing and instead you have still the Pedal point Ab. perups that's what made is so difficult to understand.
2:1 "I" (Obviously)
2:2 second beat of second measure is "V", I think. It's the same idea only now you're missing two notes which are replaced by the pedal point. (I really don't like the compositional decision here, I think it would work much better without the Pedal point).
Measure 3-4,  it's IV (Db) but you have a "delayed G note, which is not part of the harmony but a part of the melody. Trying playing that and it will be obvious.

And I believe you can work up with that. Good luck!
Answer: I think the G, Bb, and Db in bar 2 are being used as passing notes for two reasons:

The G Bb and Db sound on a weak beat in the bar
The G Bb and Db are one step in pitch between the strong beats either side.
The Ab bass notes are held in bb 1 - 3.

Roman numeral anaysis help


Switching Handedness on Guitar

Question: Long story short, a few years back my dad had a Black Sabbath-style accident with a car door that took off one of the digits on the ring finger of his fretting hand.  He occasionally picks up my instruments to tool around a bit, but he quickly becomes frustrated when he can't apply enough pressure with his shortened finger and hands the instrument back to me.
I've suggested using something like an archery finger guard to help make up the difference, but he hasn't been interested in that option.
Recently, however, he conceded that he might try to learn to play left-handed.  He's naturally ambidextrous to a degree, and has been known to do some things left-handed (e.g. playing pool), so I'm looking at getting him an inexpensive instrument to test this out and see if it's something that he wants to pursue further.
Just trying it out myself, I've been amazed at how foreign a left-handed guitar feels.  I was wondering if anyone happened to have any advice on transitioning to playing with your off hand, and how to become comfortable with it.
Comment: There have been several questions with good answers, similar to this. Unfortunately, the 'related' part on the right of screen has picked up on the key word switching, which sadly isn't a great deal of help to anyone.
Answer: Tips I have for people trying to enter ambidexterity with guitar:

Play in front of a mirror.
Tune to an open tuning and focus on training one hand at a time.
Invoke the good vibes of Sir Paul McCartney and Jimi Hendrix before practicing.
Practice tightening your fret-board hand on heavy jugs of milk/water (carrying them around).
Remember that nobody is born with these skills, and that practice shall make perfect.
Be happy / play happy / rejoice in whatever progress you make or don't make.
Enjoy discovering muscles you did not know you had.
Try and apply effort in sustaining awareness of the arm muscles in your non-dominant arm.
Answer: Maybe "Handedness" isn't as hard-wired as you might think!
I am left handed(I write & throw with my left hand).
I took up the guitar 18 months ago (at the tender age of 54) and play it right-handed, which feels perfectly natural.
I also hold a bat & swing a golf club right-handed.
Chris
Comment: Is handed-ness activity specific? perhaps(?)
Answer: I suspect it would be much easier for him to adapt his technique without switching hands. It is possible to play just as well if not better with less fingers (the obvious example of Django Reinhardt comes to mind) as the added constraint forces you to really think about the technique and the underlying music (as opposed to simply applying finger patterns learned off a chart).
If he is intent on switching hands, then learning each hand separately will be necessary. For the fretting hand, a good way to stimulate muscle memory is to place your fingers in a chord position, press down as if to play it, then release completely, open up your hand, then place your fingers back down again in the same chord position, release, etc. etc. It's a quick way to get your fingers to remember where to go. Overall though, he'll have to have a good dose of patience since it'd really be about trying to rewire the brain, and that takes time.
Comment: When trying to rewire the brain it often helps doing something irrational as well as the thing you are trying to do. Perhaps counting backwards from 57 while practising chord positions.
Answer: Right-handed people do all the clever stuff on guitar with their left hands.   Does any more need to be said?
Comment: So much more needs be said, but I agree with you.  Balance.

Switching Handedness on Guitar