C++ variadic template empty argument specialization

Question: What's the correct way to write a specialization for an empty argument variadic template. Take bellow code as an example:
#include <iostream>
#include <memory>
#include <tuple>
#include <functional>
#include <cassert>

using namespace std;

struct message {
    int type;
};

struct X: message {
    int payload;
    X(): message{1} {
    }
};

struct Y: message {
    int payload;
    Y(): message{2} {
    }
};

struct Z: message {
    int payload;
    Z(): message{3} {
    }
};

template<typename T>
constexpr int message_type = -1;

template<>
constexpr int message_type<X> = 1;

template<>
constexpr int message_type<Y> = 2;

template<>
constexpr int message_type<Z> = 3;

struct M {
    int payload;
    M(int payload): payload{ payload } {
    }
};

template<typename P, typename T1, typename... Ts>
tuple<int, unique_ptr<M>> helper(unique_ptr<message> &msg, function<int(unique_ptr<T1>&)> fn1, function<int(unique_ptr<Ts>&)>... fn) {
    if (msg->type == message_type<T1>) {
        unique_ptr<T1> m(static_cast<T1*>(msg.release()));
        auto result = fn1(m);
        return {result, make_unique<M>(m->payload)};
    } else {
        return helper<void, Ts...>(msg, fn...);
    }
}

template<typename P>
tuple<int, unique_ptr<M>> helper(unique_ptr<message> &msg) {
    assert(false);
    return {0, unique_ptr<M>()};
}

template<typename... Ts>
tuple<int, unique_ptr<M>> dispatch_msg(unique_ptr<message> &msg, function<int(unique_ptr<Ts>&)> ...fn) {
    return helper<void, Ts...>(msg, fn...);
}

int main() {
    auto *real_message = new Z;
    real_message->payload = 101;

    unique_ptr<message> msg(real_message);

    auto [result, m] = dispatch_msg<X, Y, Z>(msg, [](auto &x) {
        return x->payload + 1;
    }, [](auto &y) {
        return y->payload + 2;
    }, [](auto &z) {
        return z->payload + 3;
    });
    cout << result << '\n' << m->payload << endl;
    return 0;
}

The helper function takes variadic template arguments. If it checked all given type arguments and failed. e.g. run to the empty arguments. I want to assert and stop the process.
The current code works but I'm wondering is there any straightforward way to write a specialization.
I simplified the core requirements into the code below:
template<typename T, typename... Ts>
void func(int val, T arg, Ts... args) {
    if (condition_hold<T>(val)) {
        return;
    } else {
        return func<Ts...>(val, args...);
    }
}

template<>
void func(int val) {
    assert(false);
}

int main() {
    func<int, double, float>(100);
    return 0;
}

Basically the func is checking against every given type whether a condition hold for the input val. If all check failed I want to do something, like the assert here. So I wrote a specialization takes empty argument, but this can't compile.
Comment: A very, very careful search of the shown code find no evidence of any existence of the `help()` function that you are asking about in your question. It should be possible for you replace the shown code with a much easier to read [mre] that uses simple types, instead of all of these complicated ones, to demonstrate the C++ principle or concept you're asking about.
Comment: How about `std::variant`? [Demo](http://coliru.stacked-crooked.com/a/a5eac2e7bffbbc0b).
Comment: Can you use C++17?
Comment: @SamVarshavchik should be `helper` function. Let me simplify it later.
Comment: what is `unique_ptr` supposed to be for? It seems to just be another wrapper for the result
Comment: @JanSchultke Please refer to the simplified code, it can't compile even in C++20. The unique_ptr in the original code is just a demo for using the input, can simply ignore it. The simplified code is more suitable for my question.
Answer: In C++17, you don't need to split parameter packs into head and tail in most cases. Thanks to fold expressions, many operations on packs become much easier.
// Some generic predicate.
template <typename T>
bool condition_hold(T) {
    return true;
}

// Make this whatever you want.
void do_something_with(int);

template<typename... Ts>
auto func(int val, Ts... args) {
    // Fold expression checks whether the condition is true for all
    // elements of the parameter pack.
    // Will be true if the parameter pack is empty.
    if ((condition_hold(args) && ...))
        do_something_with(val);
}

int main() {
    // Ts type parameters are deduced to <float, float>.
    func(100, 1.f, 2.f);
    return 0;
}

To check whether the pack was empty and handle this case specially, you can do:
template<typename... Ts>
auto func(int val, Ts... args) {
    if constexpr (sizeof...(Ts) == 0) {
        // handle empty pack
    }
    else {
        // handle non-empty pack
    }
}

Your specialization couldn't have worked because func<> needs to take at least one parameter. A specialization such as
template<typename T>
void func<T>(int val);

Wouldn't be valid either, because it wold be a partial specialization which is only allowed for classes.
However, if the base template only takes a pack, we can fully specialize it:
template<typename... Ts>
void func(int val, Ts... args);

template<>
void func<>(int val);

Comment: thanks for the answer. but seems in this approach, we can't know which type makes the condition hold? One possible solution I came up with is that we can put the computation into the condition check function, but this way we can't retrieve the computation result.
Comment: @libo isn't the computation result only coming from the `int`? I thought all the other parameters are only for testing whether the condition holds true. But what you have described is also possible. But if there are multiple computation results, which one should be returned?
Comment: The computation result only comes from the `int`. Only one type argument can make the condition hold, I need to do some computation based on the type that makes the condition hold. In the real case, it's a class type, not a plain `int`, I need to do some typecast when the condition hold. I just thought about it again. In the condition check function, when the condition hold I know the type and the val, so I can do my computation. To get the computation result I can pass in one additional container to store the result.


How to test for overfitting in a TAR model in R?

Question: I want to fit a threshold autoregressive model, and I'm using the tar package in R. For ARIMA models, I could check if a model was overfit by looking at the values of standard errors as compared to estimates. If errors were much smaller, I would assume there is no overfit. However, I don't see a provision to check overfit in TAR model. There is no standard error, and so I wouldn't know where to stop fitting. I can check for residual whiteness to prevent underfitting, but how would I prevent high orders? When I check AIC, I find that the higher the order, the smaller the AIC. So that's not helpful.
Answer: So my friend found out how to get the standard errors. In the tar function, set print = TRUE, and this will print out the standard error.


When writing harmonic/melodic scales without a key signature, is it bad practice to put a natural sign?

Question: Question is in the title,
assuming I'm writing say a f harmonic minor scale WITHOUT a key signature at the beginning. Is it more correct to emphasize that the E should be natural and not Eb by a natural sign, or is it best to leave it "blank"?
Answer: No, there is no automatic need for a courtesy accidental here.  Use one if a previous E♭ triggers the usual rule for a courtesy accidental.  But only if.
Answer: It's generally a bad practice to use accidentals redundantly, because they clutter up the music, and they can confuse musicians - if I'm sight reading a piece and see an accidental that's not needed, it causes a brief moment of panic (did I miss a key signature change??)
If you do want to use a redundant accidental for clarity, it's a good idea to enclose the accidental in parenthesis to show it's a "courtesy accidental".
Answer: If you write an unnecessary natural it's likely to confuse people. If there is any possibility that the note might be intended to be an E-flat (maybe there was an E-flat in the previous measure) then it helps to add the natural sign.
Answer: It is probably a bad or uncommon practice to write a scale without a key signature.
Only exception if you want to demonstrate how the flat scales are developed from the tetrachord of a scale with one flat less: c minor has c,d,eb,f. Now I think it is necessary to set a courtesy natural sign in parentheses to make clear that in f minor the upper tetrachord c,d,e,f has a natural e.
Comment: In music with no key signature it's still very common to find scale passages.
Answer: The key signature for F♯ minor is the same as that for A major - 3♯s. So reflect that in the notes with accidentals.
Think about it. In key C, with no ♯ or ♭, it's only when you come across an accidental that you think 'out of key'. The default is therefore nothing. Obviously were there a previous accidental in that bar, and the next same name note needed to be natural, it would be signed. Otherwise no.
However, if it's the scale of F♯ melodic minor, with no barlines, and E♯ ascending,then you'll need that natural sign before the E descending. And, for the D notes similar. There will be a sharp for the E whatever in F♯ harmonic minor. You may want to write in cautionary signs (maybe in brackets), to remind beginners.


CKFinder 3 with Laravel 6 and Vuejs - 404 Error when accessing File Browser from vue

Question: have this nearly working in being able to upload files to my laravel installation from CKEditor and the CKFinder file browser works from route myurl/ckfinder/browser.
But when i click on the image browser icon in CKEditor or open a CKFinder Popup from my vue file then the CKFinder File Browser popup opens but with a 404 error.
Uploading is ok and browser route is working - am sure is a config I am missing.
Current code:
editor: ClassicEditor,
<code>    editorConfig: {

ckfinder: {
         uploadUrl: '/ckfinder/connector?command=QuickUpload&type=Images&responseType=json',
         openerMethod: 'popup',
        },
        toolbar: [ 'ckfinder', 'imageUpload', '|', 'undo', 'redo', 'removeFormat' ],

    },
</code>
Have got so close , but so far - Any help  very welcome.
Answer: Had been a long week and issue was caused by forgetting to add the following in the template file:

CKFinder.config( { connectorPath: '/ckfinder/connector' } );
Comment: Hi, the main problem was caused by not having the following in the Laravel layout file for the page.

So make sure in /views/layouts/app.blade.php (or whatever your layout file is)
you have the following code
Comment: Hi, there I am suffering on this topic as well.
Can you share your code in the index.html of VUE and the code in Laravel
Comment: Thanks for your explain, may I know your Vue is together with Laravel, or it is separately.


Dividir termo de pesquisa para ampliar resultados e ordenar resultados de acordo com o termo

Question: Digamos que eu tenha uma tabela chamada carros.
Nessa tabela tenho alguns carros registrados. Ex:
ID | Name
1  | Corsa Amarelo
2  | Camaro 2 Portas Amarelo
3  | Camaro V12 Amarelo
4  | Camaro Esportivo Amarelo
5  | Fusca Amarelo
6  | Camaro Amarelo
7  | Gol Amarelo
8  | Ferrai Vermelha
9  | Ferrari 490 cv vermelha

Se eu usar a seguinte consulta SELECT * FROM carros WHERE carros_name LIKE %camaro amarelo% vou ter como resultado apenas a seguinte linha
6  | Camaro Amarelo

Se eu só dividir os termos da busca desse jeito carros_name LIKE %camaro amarelo% OR carros_name LIKE %camaro% OR carros_name LIKE %amarelo% o resultado vem todo misturado.
Porém eu gostaria obter como resultado tudo aquilo que tivesse as palavras do termo de pesquisa, organizando os resultados pelo termo mais parecido em diante. Algo como:
ID | Name
1  | Camaro Amarelo
4  | Camaro V12 Amarelo
5  | Camaro Esportivo Amarelo
3  | Camaro 2 Portas Amarelo
2  | Corsa Amarelo
6  | Fusca Amarelo
7  | Gol Amarelo

Como pode observar no resultado acima, o resultado vem com uma classificação onde o termo buscado aparece primeiro, resultados com todas as palavras da busca em 2 segundo e por ultimo qualquer resultado que tenha alguma palavra do termo buscado.
Comment: Obs: 'rankear' não existe, o termo certo é `classificar` ou `ordenar`
Comment: Use o `match ... against` (https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html) ao invés do `like`...
Comment: @Inkeliz isso resolveu! Muito obrigado! Se você formular uma resposta posso votar como a melhor.
Answer: Porque não usa no final um "ORDER BY carros_name ASC"?
Assim ele ter retorna o resultado em ordem alfabética se e isso que quer.


How do I set the activity of the Android Up-button dynamically?

Question: The following two methods seem like they should do the trick, but I can't get them to work. Does anyone how to get these methods to work, or know of another way?
getSupportParentActivityIntent
http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html#getSupportParentActivityIntent()
onCreateSupportNavigateUpTaskStack
http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html#onCreateSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)
Answer: How to implement getSupportParentActivityIntent() to set the activity dynamically for up-button in android


How can I create a view page that takes taxonomy machine name and has depth?

Question: This question is a followup to How to load nodes that are associated with the child of a taxonomy term and refers to this answer in particular, but is standalone, so you need only visit those if you want more background.
I want to create a view that functions like the Taxonomy term view that comes with views with depth turned on in the contextual filter, but taking the term's machine name instead of tid as the contextual argument.

I have pathauto set up to alias /taxonomy/term/tid to /vocabulary/term, and I would like to override the page there with views to make it show nodes associated with the children of the term as well as the parent.
So if I had the following Taxonomy:
Vocabulary 1 (vocab_1)

Term 1 (term_1)

Term 2 (term_2)
Term 3 (term_3)

Term 4 (term_4)

Term 5 (term_5)

and nodes as follows:
Node 1 - Term 2, Term 5
Node 2 - Term 5
Node 3 - Term 3
A visitor to /vocab_1/term_1 should get a list that contains nodes 1 and 3 because they are associate with children of Term 1.
I haven't been able to figure out how to do that with the term machine_name as the contextual filter instead of the tid.
Comment: "but taking the term's machine name instead of tid as the contextual argument" FYI: Terms don't have machine names.
Comment: Ok, not machine name, but whatever path auto generates for it.
Answer: You can use the contextual filter Content: Has taxonomy term ID (with depth) without adding a Relationship.  Use this settings for the contextual filter:
When the filter value is NOT available: Provide default value
Type: Taxonomy Term ID from URL
Make sure Load default filter from term page is checked.
Please note: When you visit a pathauto destination path, in this case with a source of /taxonomy/term/% pointing at /vocabulary_name/term_name, drupal passes the source path as a query variable, and your view still uses the source path to gather information.  This means your path in the view should not change, it should stay as taxonomy/term/%
Comment: Will that give me depth?  All the modes will be associated with child terms of the term in the URL.
Comment: I've changed my answer, after reading your question once again.
Comment: As far as I can tell your answer is assuming the url contains a tid, but it doesn't.  It creates the term name as adjusted by pathauto.  I suppose it is possible that that somehow carries the tid along with it, so I'll look into it.
Comment: Reviewing this it seems not to take the name of the term, but instead expects the tid.  since I have pathauto set up to alias /vocabulary/termname to the term page this doesn't seem like it will work.
Comment: @UltraBob Yes it expects the tid, but it should work with pathauto.
Comment: In my testing it didn't.  It is possible that I did something wrong, but it seemed not to be able to know what term I was looking for when I used the pathauto converted term name.  I've been trying to write that functionality myself, so if you can confirm that it does actually work for sure, it could save me some time, to so figure out why my test didn't work when yours does instead of writing this custom code.
Comment: @UltraBob what are you using as contextual filter?
Comment: Content: Has taxonomy term ID (with depth)
Content: Has taxonomy term ID depth modifier

as instructed in your answer as best I can tell

path: area/%
Comment: In the {url_alias} table I have source taxonomy/term/tid pointed at /area/term-name for terms in the area vocabulary
Comment: It takes the filter from the main url, not from the url generated by pathauto. That means if you visit 'taxonomy/term/1', and pathauto rewrites it as 'area/first', the view takes the argument '1', not 'first'.
Comment: I don't think that is how pathauto works (if I visit taxonomy/term/tid I get server the page at /taxonomy/term/tid, not redirected), perhaps you also have some kind of redirect module enabled? Also, I'm redirecting to the pathauto url from module code like so: `drupal_goto(drupal_get_path_alias('taxonomy/term/' . $tid), array(), 301);` after determining the tid.  The tid seems not to come through to views as far as I can tell.
Comment: I thought, you've set your page path in your views page settings as 'taxonomy/term/%'. At least, on the screenshot in your question, the path is 'taxonomy/term/%'. If you work with redirects, it won't work.
Comment: Hi, I misunderstood.  After I ran through the debugger and saw how it was routing things, I see as you were trying to explain, that my path needs to be set to /taxonomy/term/%.  Once I did that I get a list of nodes.  I just need to confirm that they are the right ones (the display is weird).
Comment: I just edited your answer to add the details that I was missing.  Have a look.  If you agree I'll accept this answer.
Answer: Unfortunately looks like there isn't a term machine name contextual filter option. There is one, but only for vocabulary machine name.
If you really want this, you will have to get your hands dirty.
Create a custom module with a custom page that has a variable url. ex: /taxonomy/% the % being a place holder for the machine name.
Then on page load using using current_path() along with some php function (perhaps str_ireplace() to remove the taxonomy/ part), you grab machine name from the url. Then you query the database, using db_query(), to grab the term id that belongs to that machine name.
Once you have the term id you can render the view on your screenshot using php. So you just pass the term id as the argument.
<?php
print views_embed_view('my_view', 'block_1', $arg,);
?>

so in your case it would be:
<?php
print views_embed_view('taxonomy_term', 'page', $term_id,);
?>

Update:

After looking at the taxonomy term table (taxonomy_term_data) turns
  out that there is no machine name column for taxonomy terms (which explains
  why there is no contextual filter in views).

Therefore, the only alternative would be to use the taxonomy term name. As long as you have unique term names, this will be fine.
First, you need to go to the taxonomy term view (the one in your screenshot) and press on  and add a block and save.
Here is a working module I created called term finder.
/sites/all/modules/term_finder

term_finder.info
name = Term Finder
description = Creates variable pages for taxonomy term names and shows a view.
core = 7.x

term_finder.module
<?php

/**
 * Implements hook_menu().
 */
function term_finder_menu() {
  $items = array();

  $items['taxterm/%'] = array( // this will be our custom page url. The % allows us to put anything after, ex: taxterm/[anything can go in here]
    'title' => 'Your Title Goes Here',
    'access callback' => TRUE,
    'page callback' => 'term_finder_page', // the name of the function that gets runed when we visit our taxterm/[anything] page.
    'type' => MENU_NORMAL_ITEM,
    'menu' => 'navigation',
  );

  return $items;
}

/**
 * Page callback for taxterm/%.
 */
function term_finder_page() {
  $path = current_path(); // gets the current page url. ex: taxterm/hello-world and saves it on a variable
  $path = str_ireplace('taxterm/','', $path); // removes the taxterm/ from our variable, so we are left with hello-world
  $path = str_ireplace('-',' ', $path); // replaces the - with a space, so we have hello world
  $term_id = db_query("SELECT tid from {taxonomy_term_data} WHERE name = :name LIMIT 1", array(":name" => $path))->fetchField(); // queries the DB to find the tid that belongs to hello world.
  if ($term_id != '') { // we check if grabbed a term id, is not empty.
    $show_view = views_embed_view('taxonomy_term', 'block_1', $term_id); // creates the view, which passes the tid we got from the DB as an argument.
    return $show_view;
    }
  else { // if the term id is empty, then we show "not found".
  return 'not found';
  }
}

Lets assume you have a term called Hello World.
What this does is if you go to /taxterm/hello-world or (in firefox) /taxterm/hello world
It will look up in the DB for Hello World and get the term id and pass it to the view.
PS: In case you are wondering why the mysql query looks the way it does, see Writing secure code and How do I get only one result using db_query()
Comment: Actually I'd love to do that, I just don't know where to get started with creating a module listening for a specific page.  I'll try to dig further into the docs to figure that out, but any pointers for the right place to look would be appreciated.  Being able to do that would let me avoid loading the views infrastructure until I am actually ready to render a page rather than when I'm still going to do a redirect.
Comment: I've been trying to follow the early examples [here](https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7), but every time I flush cache and load the new path that it seems my hook_menu should have created I get access denied and my function is never called.  I'm sure when I discover what I've been doing wrong it will have been something simple, but for tonight it has defeated me.
Comment: @UltraBob updated my answer, sorry for the delayed reply. Somehow I missed the comment notification.
Comment: You are my favorite person!  I can't figure out how one might pm here, but if you have an amazon wishlist or something I'd love to give something back.  This isn't exactly what I need, but it shows me everything I need to get there, and teaches me some extra important information in the meantime.  Thank you!  I'll go implement my version and come back and accept.
Comment: @UltraBob Thank you for the kind words, glad to hear my answer helped you in some way. I help people in here without the expectation of getting something back nor I want something back. I learned Drupal from the Community by watching videos tutorials, reading tutorials and reading Q & A's here. This is the beauty of Drupal, it has a great community.
Comment: The irc channels are next to useless in my time zone, so this is the best resource I know of for getting help, and you are consistently incredibly helpful.  Thank you again!
Comment: I forgot to ask, is there some particular reason why you used a block instead of a page?
Comment: @UltraBob I tried using page at first, but I kept getting a blank page when I did that. So looks like it only works with block.


What interpretation do REML/fREML values provide in generalized additive models (GAMs)?

Question: I'm continuing my slow trudge through Simon Wood's book on generalized additive models (GAMs), and it has given me some new useful insights. However, I am still confused after reading through Chapter 2 about what value the REML/fREML estimates provide in GAM summaries. For example, I have fit these two models using REML below:
#### Load Libraries ####
library(mgcv)
library(gamair)

#### Load Data ####
data("wesdr")
wes <- tibble(wesdr)

#### Fit Candidate Models ####
fit.1 <- gam(
  ret ~ s(dur, bs = "cr"),
  data = wes,
  method = "REML"
)

fit.2 <- gam(
  ret ~ s(dur, bs = "tp"),
  data = wes,
  method = "REML"
)

#### Summarize ####
summary(fit.1)
summary(fit.2)

The REML values for these two GAMS are the following:

fit.1: 467.41
fit.2: 469.33

I rarely every hear or see anything about these values from most articles and videos I have seen on GAMs. I also see pretty much no explanation about these values elsewhere here. However, I feel like they exist for a reason. What utility do these values have?
Answer: All the fitting methods in gam()/bam() return some form of smoothness selection score:

GCV
UBRE (AIC)
GACV
REML score
ML score
...

and this is what is displayed in the summary output.
Their main utility is as a quick way to compare models (in the same way you might compare models based on AIC); the lower the score the "better" the model. Note that for ML or REML scores, these are not the log-likelihood of the data given at the MLEs of the model parameters: you'll get slightly different values from logLik():
r$> logLik(fit.1)
'log Lik.' -457.0239 (df=6.872103)

r$> logLik(fit.2)
'log Lik.' -456.9475 (df=7.106575)

and I'm not exactly sure why (probably the REML/ML scores aren't including certain other parameters that are in the log likelihood of the data.)
As to your specific example, the model using thin plate regression spline fits slightly better (it has a slightly lower negative log restricted likelihood score), but uses a bit more wiggliness than the CRS model (fit.1). But the difference is negligible and certainly not worth bothering in this case.
library("gratia")
compare_smooths(fit.1, fit.2) |>
    draw()


how can you put samples together and make a drum machine out of them for midi instruments?

Question: how can you add samples together in garageband to make a drum set on a midi? I want to group my samples of 1 beat drums into an instrument so I can play the midi like a drum machine. Lmk
Answer: That feature is available on the EXS24 sample editor in Logic Pro but I'm almost certain you can't do it in GarageBand. GarageBand does have many pre programmed drum kits though.


Infinite power summation

Question: I was playing around with fractions in my head when I realized the infinite summation of $\frac{1}{b^n}=\frac{1}{(b-1)}$ for when $b>1$.
I tried writing a proof for this and researching the function, but found nothing, so does anyone have any insights to how I can prove this? Thanks in advance.
Comment: I don't understand how you can realize this without proving it. Anyways, this is a standard Geometric Series (proof enclosed): http://mathworld.wolfram.com/GeometricSeries.html
Answer: I assume you sum up from $n=1$ to $\infty$. This is a very well-known result. For each $q\in\mathbb C$ with $|q|<1$ holds
$$
\sum_{n=0}^\infty q^n=\frac1{1-q}.
$$
The series on the LHS is called geometric series. If you google proof geometric series you find some.
Now if you choose $b>1$ and $q=\frac1b$ you get $|q|=\frac1b<1$ and
$$
\sum_{n=1}^\infty \frac1{b^n}=\sum_{n=1}^\infty q^n = \frac1{1-q}-1=\frac{b}{b-1}-1=\frac1{b-1}
$$

Infinite power summation


Module to separate the links of menus by language?

Question: A few days ago I found a module to separate the links of menus by language. Given a localized menu then you get the links separated by languages. Very useful I think.
But now I can't remember its name. Does anyone know it?
Answer: I found it, it's a sandbox project though: http://drupal.org/sandbox/TimBrandin/1835360


Use of angular proxy in production

Question: I read that angular proxies are specific to development and are not intended for production use.
Can someone please explain me why ?
Comment: angular proxy (which is webpack proxy under the hood) is just the simple proxy with almost no security logic involved as well as it is probably far less performant as the usual proxy. also if you are using proxy you are most likely using development server, which does not make sense for production as well
Comment: @Andrei make it an answer ;)
Answer: angular proxy (which is webpack proxy under the hood) is just the simple proxy with almost no security logic involved as well as it is probably far less performant as the usual proxy. Also if you are using proxy you are most likely using development server, which does not make sense for production as well

Use of angular proxy in production


jQuery .toggleClass() não está a funcionar como esperado

Question: Tenho este código mas não entendo porquê o método .toggleClass() não está a funcionar como esperado para alterar a opacidade do elemento:
Exemplo no JSFiddle
HTML

Admin

    <form method="POST" action="loginAdmin.php">Username:

        <input type="text" name="username" />

Password:

        <input type="password" name="password" />

            <button id="btn" name="send" type="submit" value="enviar">Login</button>

    </form>

CSS
#admin {
    position: absolute;
    margin-top: 140px;
    right: 200px;
    width: 224px;
    z-index: 1;
    height: 140px;
}
#admin p {
    font-family: Lato-Light;
    float: right;
    cursor: pointer;
    color: blue;
    bottom: 0;
    right: 15px;
    position: absolute;
    font-size: 11px;
    opacity: 0.3;
}
.adminPvisible {
    opacity:1;
}
#admin p:hover {
    opacity: 1;
}
#admin form {
    display: none;
    font-family:Lato-Light;
    font-size: 11px;
    margin:35px 0 0 100px;
}
#btn {
    display: none;
    font-size: 12px;
    margin: 5px 0 0 0;
    font-family: Lato-Regular;
}
#admin input {
    width: 120px;
    font-size: 12px;
    margin: 0;
    height: 20px;
}

jQuery
$(document).ready(function () {
    $('#admin > p').click(function () {
        $(this).toggleClass('adminPvisible');
        var right = $('#admin > p').css('right') == '135px' ? '0' : '135px';
        $('#admin > p').animate({
            right: right,
            width: '50px'
        });
        $('#admin > form, #btn').stop(true).slideToggle();
    })
})

Answer: O que está acontecendo não é uma falha do jQuery, porém uma função do CSS.
Ele é organizado por ordem de especificidade, regras com maior prioridade são aplicadas mesmo se declaradas antes das de menor especificidade. Aplica-se uma regra de pontuação:

Estilos vindos do atributo style valem 1000 pontos, ids (#admin), 100 pontos, classes (.adminPvisible), 10 pontos, e tags(p) tem prioridade mínima, 1 ponto.
Pseudo-classes, pseudo-elementos, @media e similares não influenciam na pontuação.
No fim as pontuações são somadas, ou, se forem regras marcadas com !important ,tornam-se de prioridade máxima. Caso múltiplas regras encaixem-se na mesma situação ganha a definida pelo style ou a última.

Para resolver o problema você tem algumas opções:

(recomendada) Nunca use IDs no CSS: por eles terem uma especifidade tão alta eles geralmente não podem ser sobrescritos.
Ao declarar uma regra que vai sobrescrever uma regra definida por uma ID inclua ela junto: .adminPvisible vira #admin > p.adminPvisible.
(não recomendado) use !important.

Mais informações: MDN | SmashingMagazine - Demonstração: JSFiddle
Answer: Basicamente o que faltava era apenas colocar !important no css do .adminPvisible dessa forma ele força a opacidade ser 1 enquanto a classe estiver no elemento.
No exemplo que você postou o .toggleClass() funciona perfeitamente, você só precisa dizer que a classe .adminPvisible é mais importante que o #admin p
jsfiddle
Comment: No caso ele adicionar o !important é desnecessário e geralmente deve ser evitado. Ele precisa apenas especificar melhor as regras a serem aplicadas, como dito na resposta do Gustavo Rodrigues
Answer: Como já referenciado em outras respostas, o jQuery .toggleClass() (Inglês) está a funcionar, o problema é a classe de CSS tem uma prioridade mais baixa que as definições dadas previamente via #admin p.
De forma resumida, ao passares estilos para o selector #admin p estás a ser muito rigoroso, e quando uma classe não rigorosa é atribuída, o navegador não a vai respeitar para sobrepor as definições.
Duas formas simples de resolveres a tua questão:

Classes para cada definição
Ao invés de usares uma classe para sobrescreve a definição de um elemento, se essa definição é mutável, o mais prático é teres duas classes, cada uma com o estado pretendido e alternar entre elas:
Exemplo no JSFiddle
CSS
.adminPnearInvisible {
    opacity: 0.3;
}
.adminPvisible {
    opacity:1;
}

HTML

Admin

    ...

jQuery
...
$(this).toggleClass('adminPvisible adminPnearInvisible');
...

O que estamos a fazer é usar o .toggleClass() (Inglês) para alternar duas classes. Como estava no elemento a classe .adminPnearInvisible, ao alternar entre ela e a .adminPvisible, estamos efectivamente a remover uma e adicionar outra, atribuindo assim ao elemento o estilo que cada uma contém sem precisarmos de nos preocupar com os estilos "base" do elemento.
Definir de forma rigorosa o estilo a subscrever
Podes optar por definir com o mesmo rigor os dois estados da opacidade, o que vai dizer ao navegador que prevalece o que vem em 2º lugar se aplicável:
Exemplo no JSFiddle
CSS
Passamos a ter a tua classe .adminPvisible com o mesmo rigor dos estilos do elemento onde defines a opacidade inicial. Como já tens o valor no :hover, estou a juntar as duas coisas para evitar duplicar declarações na folha de estilos:
#admin p:hover,
#admin p.adminPvisible{
    opacity: 1;
}

HTML
Sem alterações ao teu inicial...
jQuery
Sem alterações ao teu inicial...

Não relacionado mas pode ser útil é uma ligeira optimização do teu código para reduzir o mesmo e ao mesmo tempo evitar consultas recorrentes ao DOM para localizar o mesmo elemento:
Exemplo no JSFiddle
$('#admin > p').click(function () {
    var $this = $(this);
    $this.toggleClass('adminPvisible').animate({
        right: $this.css('right') == '135px' ? '0' : '135px'
    });
    $('#admin > form, #btn').stop(true).slideToggle();
});

Explicação
// colocar elemento em cache para não andarmos sempre à procura dele
var $this = $(this);

// jQuery permite encadeamento dos métodos, por isso numa linha podes
// fazer a alternância da classe e chamar a animação
$this.toggleClass('adminPvisible').animate(...

// podes ter a verificação do valor e atribuição do novo para a animação
// na declaração do valor pretendido para animar o right
right: $this.css('right') == '135px' ? '0' : '135px'

E passei a largura de 50px para a folha de estilos pois a mesma não está a ser manipulada, ou seja, estás a dizer que a partir do primeiro clique o elemento fica com 50 pixeis de largura.
Comment: Muito obgado mais uma vez Zuul, muito claro e directo à questão, esclareceste mais do que uma duvida. Cheers


Ports will not open windows server 2012 r2

Question: I recently Purchased a VPS that runs windows server 2012 on it and I cannot seem to open any ports.
I have gone into Windows Firewall with Advanced Security, and making a new inbound and outbound rule for the port, but when I check if the port is open via http://www.yougetsignal.com/tools/open-ports/ it says it's closed
Cheers
Tom
Comment: Well, can you call your provider? Support, you know. There is a chance there is another firewall in front and you just do not bother to read the documentation which would point you to a website where you could handle that.
Comment: Does the VPS have a network firewall, akin to a Security Group in AWS or an NSG in Azure?
Comment: Does the output of `netstat -an` show the the port as listening?
Comment: @MassNerder Nope, doesn't show there
Comment: @TomTom I contacted the host, apparently the VPS controls it's own Ports through Firewall
Comment: Then nothing is listening on that port. Review your application configuration, make sure the app is running and configured to run on the correct port
Answer: Since the output of netstat -an does not show a process listening on that port it means the application is not configured to run on that port or the application is not running. Check your application configuration, make sure it is configured to run on the specific port you want and make sure the application is running


nonlinear least squares versus maximum likelihood in R, nls() or nlm()?

Question: I am estimating the model $$E(Y|X) = Pr(Y=1|X) = \alpha_0 + (1 - \alpha_0 - \alpha_1)\phi(X'\beta),$$ where $\alpha_0$ and $\alpha_1$ are parameters, $\beta$ is a $p$-length vector of parameters, $X$ is a $p \times n$ matrix of data, $Y$ the dependent variable is a binary, and $\phi()$ is a probit model, so the cumulative distribution function of the standard normal distribution. To derive the expectation the assumption was made that the errors are normal and mean zero.
The source for the model is here (see equations 6 and 7), and per the paper I can estimate the model either via nonlinear least squares or maximum likelihood. I tried both approaches in R, using the nls() function for nonlinear least squares and the nlm() function for maximum likelihood. Experimentation suggests the results are very similar for my application, but nls() is faster. Is there a reason to favor one approach over the other? How should I think about picking a method, e.g. do similar assumptions underly both approaches?
Any suggestions for thinking through the differences between these two approaches, or suggestions for relevant literature to consult would be greatly appreciated.
Comment: With regards to faster solution did you ensure that nls and nlm used same optimizer? If you used different optometrist that could explain why one would be faster than the other.
Comment: Good question. I did not check that - I will investigate. Speed is not so important in my application that I would be ill-disposed towards using either model. I'm more interested in knowing whether there are theoretical reasons to prefer one over the other.
Comment: What kind of variable is $y$? Is it numerical, categorical, binary, etc.? What is $\phi$? And what is your statistical model? What you wrote is not a model - there is no error term. At most, it could be an expression for the conditional mean of $y$ with respect to $x$. If $y$ is a continuous random variable and you assume additive iid Gaussian errors with zero mean and constant variance, then the NLS estimator and the MLE estimator are the same.
Comment: Thanks @DeltaIV, I have edited the post to make it clearer. It is an expression of the conditional mean of y with respect to x as you surmised, and y is binary.
Answer:
To derive the expectation the assumption was made that the errors are
  normal and mean zero.

If that is your assumption, MLE and NLS should be mathematically identical, and differences would probably be explained by the choice / setting of the optimizer.
Whether a normal distribution for a binary response is a good idea is another question. An alternative would be a logistic glm with your nonlinear predictor, estimated with MLE.
If you do MLE, you might want to consider using https://cran.r-project.org/web/packages/bbmle/index.html instead of nlm(), more options for CIs and so on.


Drupal 7 db_error() equivalent?

Question: I'm trying to figure out how to get the last database error after a query fails, and I'm having trouble finding the appropriate function. It seems up until Drupal 7 there was a db_error() function that would return the information.
How should I retrieve a database error in Drupal 7?
My code:
try {
    $q = db_query($q);
} catch (Exception $e) {
    $error = db_error(); // this is what I'd like to do
    $transaction->rollback();
    watchdog_exception('my_module', $e, t('Caught an error: ' . $error));
}

I'm aware that I can get some information from the exception, but I'd like to get it directly from the Drupal 7 API.
Answer: The Drupal 7 database API piggy-backs straight onto PDO. It doesn't define its own exceptions, or messages; it actually doesn't even attempt to handle any exceptions, it leaves them for the caller to handle directly.
The most descriptive error message you can get is in the exception object.
catch (\PDOException $e) {
  $error = $e->getMessage();

Comment: @Mołot I don't think that's necessary; I really hope no-one is using <=PHP5.2 any more (for their sake, not mine). If they are, and they get an exception using this code, I would hope it serves as a wake-up call that they seriously need to upgrade their server or move to a new host as soon as possible. 5.2 has some serious problems and I don't want to encourage its use (quite the opposite), even if it's viable as a technical exercise.
Comment: FYI, [meta thread about syntax highlight](http://meta.stackexchange.com/q/204415/225745) - I admit it fooled me at first glance.
Comment: I'm too shy to edit your code, but isn't that `\` in  `\PDOException` a typo?
Comment: @Mołot The \ just denotes that `PDOException` is in the root namespace; a good habit to get into if you use namespaces a lot
Comment: But namespaces exist only in PHP >= 5.3.0 and Drupal 7 requires 5.2.5 - could you at least warn that your code might not work on setups that are perfectly fine for Drupal itself?
Comment: @Mołot Nice one, I meant to do that yesterday but forgot :)
Comment: Not what I thought I was looking for, but I really was looking for the Drupal way of doing things. I expected something more specific because I've seen Drupal convenience functions before, and there used to be a specific `db_error()` function.
Comment: @JoBu1324 Because D6 had to support older versions of PHP it couldn't be done like this (hence the helper method). D7 can take advantage of newer language features so it defers to those, and since PDO already defines detailed exception messages I guess the decision was taken not to re-invent that particular wheel. Things like this also makes adoption of Drupal just that little bit easier for incoming PHP developers, which is something they've been trying to do for a while. D8 takes it even further with the "Proudly Invented Elsewhere" attitude, instead of the old "Not Invented Here" mentality
Comment: @Clive That makes sense. Drupal is powerful, but full of quirks, especially to new developers.
Answer: the Past Log module will log the exception for you,
not sure if the db_error is included like you need.

Drupal 7 db_error() equivalent?


Criação de uma State Machine sem bibliotecas no JavaScript

Question: Estava procurando como programar uma state machine no google e cheguei a vários resultados que me levavam a bibliotecas direcionadas a tal, mas gostaria de entender a forma que ela é processada e como chegar a uma state machine simples e funcional.
Pretendo utilizar ela para um jogo de turno simples no elemento canvas, sou iniciante na área e gostaria de qualquer ajuda que eu pudesse receber, grato!
Comment: Que tipo de máquina de estados você quer? Um autômato de estados finito?
Comment: maquina de estados finita
Answer: Uma máquina de estados finito é uma máquina com um conjunto finito de estados (como o nome já diz). Ela é modelada como um grafo, no qual os vértices são os estados e as arestas são as transições. Para uma dada entrada partindo-se de um determinado estado, chega-se em um outro estado.
Um dos estados da máquina de estados é denominado de estado inicial. Então para cada símbolo de entrada, você navega nas transições de um estado para outro. Observe que a única coisa que é memorizada é o estado atual.
Implementando isso, talvez o que você queira seja algo assim:

function MaquinaDeEstados() {
  var estados = new Map();

  var erro = {
    adicionarTransicao: function(entrada, destino) {
      return this;
    },
    proximo: function(entrada) {
      return erro;
    },
    valor: function() {
      return "{erro}";
    }
  };

  function Estado(valor) {
    var transicoes = new Map();

    this.adicionarTransicao = function(entrada, destino) {
      transicoes.set(entrada, destino);
      return this;
    };

    this.proximo = function(entrada) {
      var retorno = transicoes.get(entrada);
      return typeof retorno === "undefined" ? erro : retorno;
    };

    this.valor = function() {
      return valor;
    };
  }

  this.estado = function(chave) {
    var estado = estados.get(chave);
    if (typeof estado === "undefined") {
      estado = new Estado(chave);
      estados.set(chave, estado);
    }
    return estado;
  };
}

/* Teste. Criando uma máquina de estados: */
var chave1 = "A", chave2 = "B", chave3 = "C";
var maquina = new MaquinaDeEstados();
var estado1 = maquina.estado(chave1);
var estado2 = maquina.estado(chave2);
var estado3 = maquina.estado(chave3);
estado1.adicionarTransicao(0, estado1);
estado1.adicionarTransicao(1, estado2).adicionarTransicao(2, estado3);
estado2.adicionarTransicao(3, estado3).adicionarTransicao(2, estado3);
estado3.adicionarTransicao(1, estado1);

/* Teste. Executando a máquina de estados: */
var entrada = [0, 1, 3, 1, 0, 2, 1, "lugar nenhum", 2, 2];
var atual = estado1; // Definimos que este é o estado inicial.
var passeio = atual.valor();
for (k in entrada) {
  var v = entrada[k];
  atual = atual.proximo(v);
  passeio += " " + atual.valor();
}

document.write(passeio);

No código de teste, você notará a seguinte entrada:
[0, 1, 3, 1, 0, 2, 1, "lugar nenhum", 2, 2]

Se você clicar no botão azul ► Executar que está acima, ele vai te mostrar isso:
A A B C A A C A {erro} {erro} {erro}

Inicialmente ele estava no estado A (estado inicial). Ao receber o 0, ele continuou no estado A. Ao receber o 1, ele foi para o estado B. Do estado B ao receber 3 ele foi para o estado C, e então voltou ao A com 1.
Se uma entrada inválida for dada, tal como o "lugar nenhum" do exemplo, então ele vai para o estado de erro, de onde ele nunca sai.
Observe também que a própria máquina de estados não armazena qual é o estado atual. O estado atual é mantido em uma variável fora da máquina, pelo código que a está percorrendo. Isso permite que possamos começar a iteração a partir de qualquer estado, não necessariamente o estado inicial, e também permite que vários códigos possam iterar uma mesma máquina em partes diferentes sem um interferir com o outro. Aliás, isso também permite que não precisemos nem mesmo armazenar dentro da máquina qual é o estado inicial, vez que podemos começar do estado que quisermos. Se um estado inicial é obrigatório, basta começarmos sempre do mesmo estado como o exemplo faz.
Comment: @Randrade Aumentei a explicação e simplifiquei também um pouco o javascript.
Comment: Para mim está "perfeito" agora!
Comment: +1 pela explicação. Só achei a falta da explicação do que é "State Machine", tanto na pergunta tanto na resposta.
Comment: compreendi o funcionamento da state machine, mas fiquei um pouco confuso com o código, mas muito obrigado foi de grande ajuda


Removing duplicate links from scraper I'm making

Question: #!/usr/bin/python3

import requests
from bs4 import BeautifulSoup
import re

url = input("Please enter a URL to scrape: ")
r = requests.get(url)
html = r.text
print(html)

soup = BeautifulSoup(html, "html.parser")

for link in soup.find_all('a', attrs={'href': re.compile("^https://")}):
    print(link.get('href'))

down at the bottom, where it prints the link... I know it'll go in there, but I can't think of a way to remove duplicate entries there. Can someone help me with that please?
Comment: You can add the urls to a [set](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset) to remove dups.
Answer: Use a set to remove duplicates. You call add() to add an item and if the item is already present then it won't be added again.
Try this:
#!/usr/bin/python3

import requests
from bs4 import BeautifulSoup
import re

url = input("Please enter a URL to scrape: ")
r = requests.get(url)
html = r.text
print(html)

soup = BeautifulSoup(html, "html.parser")
urls = set()
for link in soup.find_all('a', attrs={'href': re.compile(r"^https://")}):
    urls.add(link.get('href'))
print(urls) # urls contains unique set of URLs

Note some URLs might start with http:// so may want to use the regexp ^https?:// to catch both http and https URLs.
You can also use set comprehension syntax to rewrite the assignment and for statements like this.
urls = {
    link.get("href")
    for link in soup.find_all("a", attrs={"href": re.compile(r"^https://")})
}

Answer: instead of printing it you need to catch is somehow to compare.
Try this:
you get a list with all result by find_all and make it a set.
data = set(link.get('href') for link in soup.find_all('a', attrs={'href': re.compile("^https://")}))

for elem in data:
    print(elem)


How to compare s shaped curves?

Question: I have two variables A and B that can take positive values, they are two different counters of "votes" for a group of about 400 individuals. My hypothesis is that these two kind of votes are related with some degree of direct proportionality: if a subject takes x votes for vote type A (A = x), he will likely take y votes for vote type B (B = y); if another subject takes xx votes for vote type A with xx > x, he will likely take yy votes for vote type B with yy > y. Etc.
So now I have two series of votes distributed in an exponential-like curve: it means that there is a lot of people with few votes and very few people with a lot of votes (both for A and B type of vote). In order to study the relationship between the two types of vote I tried to do a linear regression of the log of the exponential curves and look at the correlation value, which is around 0,7.
The problem is that the log of the exponential curve has not a linear shape, it has a S shape, visually similar to a logit (but with a central section almost linear). Is it wrong to do linear regression in a case like this? How else can I test the correlation? Is there some other type of test I can do?
(as you can guess I'm a total beginner in statistics)
Answer: I don't see the problem with Pearson correlation usage from your description. You may try rank order correlations such as Spearman and Kendall tau.
Comment: Thanks Aksakal for the suggestions. I tried Spearman too, but not Kendall tau.

How to compare s shaped curves?


Minimum AND operation on subset

Question: Given an array of size N .
Let's create all the subsets of this array which contain at least 2 elements. Now, operate AND over the elements of each subset, and store the results in a new array.
I need  to find out the minimum value of this new array.
Example : N=3 and array be {1,2,3}
Then answer is 0 as Possible Subset : (1,2) , (1,3) , (2,3) , (1,2,3) : Minimum value from
{( 1&2 ) , ( 1&3 ) ,( 2&3 ) , ( 1&2&3 )}  =  Minimum value from { 0,1,2,0 } is 0.
Main problem is N is upto 10^5 so we cant generate all subsets.So please help to solve this problem.
Answer: The lowest value will be when you AND all elements in the array.  Each extra element will either leave it unchanged or lower it, so bring in all the elements.

Minimum AND operation on subset


ValueError: too many values too unpack (expected 2)

Question: I'm trying to parse DNA strings.
The input.txt contains:

Rosalind_6404CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCCTCCCACTAATAATTCTGAGG>Rosalind_5959CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCTATATCCATTTGTCAGCAGACACGC>Rosalind_0808CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGACTGGGAACCTGCGGGCAGTAGGTGGAAT

The code is:
f = open('input.txt', 'r')
raw_samples = f.readlines()
f.close()
samples = {}
cur_key = ''
for elem in raw_samples:
    if elem[0] == '>':
        cur_key = elem[1:].rstrip()
        samples[cur_key] = ''
    else:
        samples[cur_key] = samples[cur_key] + elem.rstrip()
print(samples)
for p_id, s in samples.values():
    samples[s_id] = (s.count('G') + s.count('C'))*100
print (samples)`

I keep getting the error:

  File "C:/Python34/test.py", line 18, in <module>
    for p_id, s in samples.values():
ValueError: too many values to unpack (expected 2)

Comment: What did you expect to get for `p_id` and `s` here? You are trying to unpack the values (strings) into two variables but you only have the one string with more than 2 characters in them. Did you mean to use `samples.items()` instead?
Comment: `for p_id, s in samples.values()`  iterates a one dimensional list as if it was a two dimensional list.
Comment: Also, I'm not sure using a dictionary to concatenate the continuation lines is the right approach for reading a FASTA file.
Comment: Last but not least, what is `s_id` supposed to mean?
Comment: @Martijn Pieters do you have another approach?
Comment: Are the lines not starting with `>` not just continuations of the DNA sequence? Let me look for older answers of mine.
Comment: I handled some [FASTA reading](https://stackoverflow.com/questions/12611491/using-regex-to-transform-data-into-a-dictionary-in-python/12611576#12611576) before using the same technique you are using, but the line format didn't include the DNA sequence on that first line like you have in your question here.
Answer: I was able to solve the problem by changing
for p_id, s in samples.values() to
for p_id, s in samples.items()
I also noticed that p_id and s_id were different, they were meant to be the same.
Answer: import csv
reader = csv.reader(open("input.txt"), delimiter=">", quotechar="'")
dkeys = [item for item in next(reader) if item.strip()]
dvalues = [(item.count('G')+item.count('C')*100) for item in dkeys]
print(dict(zip(dkeys, dvalues)))

I hope it's useful. :D


Cadastro para menores de idade -Php - JavaScript

Question: Boa tarde galera, então estou criando um cadastro de usuários, porém quero que usuários menores de idade não possam se cadastrar, já tentei de varias formas mais não consegui, se alguém puder me explicar como fazer e me dar um exemplo eu agradeço, preciso que seja em php, então meu formulario está assim...

<?php
session_start();
//apartir daqui faz o cadastro do usuario ao clicar no botão cadastrar que receber o nome de btnCadastrar
$btnCadastrar = filter_input(INPUT_POST, 'btnCadastrar', FILTER_SANITIZE_STRING);
if($btnCadastrar){
include_once ("conn/conexao.php");
$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$dados['senha']= md5($_POST["senha"]);
//aqui insere os dados na tb_usuario
$result_usuario = "INSERT INTO tb_usuario(permissao, nome, dtnasci, email, senha, saldo)VALUES(
 '".$dados['permissao']."',
 '".$dados['nome']."',
 '".$dados['dtnasci']."',
 '".$dados['email']."',
 '".$dados['senha']."',
 '".$dados['saldo']."'
 )";
$resultado_usuario = mysqli_query($conexao, $result_usuario) or die (mysqli_error($conexao));
if($resultado_usuario):
 echo "";
else:
 echo "";
endif;
}

?>

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

<title>Lance Web</title>

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

     <form class="form-group" action="" method="post">

    Nome
    <input class="form-control" type="text" name="nome" maxlength="50" value="Digite seu nome" onfocus="this.value='';" style="text-align: center;" required>

    E-mail
    <input class="form-control" type="email" name="email" maxlength="50" value="Digite seu email" onfocus="this.value='';" style="text-align: center;" required>

    Data de Nascimento
    <input class="form-control dtnasci" type="date" name="dtnasci" maxlength="10" onfocus="this.value='';"  style="text-align: center;" required/>

    Senha
    <input class="form-control" type="password" name="senha" maxlength="8" style="text-align: center;" required>

    Saldo
      <select class="form-control" name="saldo" required>
        <option>Selecione</option>
        <option>5</option>
        <option>10</option>
        <option>20</option>
        <option>50</option>
      </select>

    <input class="btn btn-danger btn-lg" type="button" value="Voltar">

    <input class="btn btn-info btn-lg submit-botao" type="submit" value="Cadastrar" name="btnCadastrar">

  </form>

Comment: Tem um erro no seu html `style="text-align: center;"> required/>` Você está fechando o `input` antes do `require`.
Comment: Coloca o código que você ja fez junto na pergunta, senão não temos como dizer onde você está errando.
Comment: editei e coloquei o formulário, eu apaguei o que tinha feito na data, não funcionava está meio que sem ação
Comment: Você quer que ele verifique na hora que coloque a data, se for menor, não deixar enviar é isso ?
Comment: Seria isso AnthraxisBR, na hora que for digitar a data e ver que e menor não envia.
Comment: Obrigado Gabriel Heming
Answer: De forma direta, você apenas precisa captar a data de envio, e data de hoje, e calcular a diferença entre as duas:

$('.dtnasci').on('input',function(){
    var dtnasci = $(this).val();
    var hoje = new Date();
    var data1 = new Date(dtnasci);
    var data2 = new Date(hoje - data1);
    var idade = (data2.toISOString().slice(0, 4) - hoje.getFullYear());
    if(idade < 18){
        $('.submit-botao').prop('disabled',true)
        $('.resposta-msg').html('Você não pode se cadastrar').show();
    }else{
        $('.submit-botao').prop('disabled',false);
        $('.resposta-msg').html('').hide();
    }
})
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

    <title>Lance Web</title>

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

     <form class="form-group" action="" method="post">

     Nome
     <input class="form-control" type="text" name="nome" maxlength="50" value="Digite seu nome" onfocus="this.value='';" style="text-align: center;" required>

     E-mail
     <input class="form-control" type="email" name="email" maxlength="50" value="Digite seu email" onfocus="this.value='';" style="text-align: center;" required>

     Data de Nascimento
     <input class="form-control dtnasci" type="date" name="dtnasci" maxlength="10" onfocus="this.value='';"  style="text-align: center;" required/>

     Senha
     <input class="form-control" type="password" name="senha" maxlength="8" style="text-align: center;" required>

     Saldo
       <select class="form-control" name="saldo" required>
         <option>Selecione</option>
         <option>5</option>
         <option>10</option>
         <option>20</option>
         <option>50</option>
       </select>

     <input class="btn btn-danger btn-lg" type="button" value="Voltar">

     <input class="btn btn-info btn-lg submit-botao" type="submit" value="Cadastrar" name="btnCadastrar">

   </form>

Referência original:
https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/67949/discussion-on-answer-by-anthraxisbr-cadastro-para-menores-de-idade-php-javasc)
Answer: É só verificar a diferença entre a data de nascimento que o usuário tentou cadastrar e a data atual:
$dataBR = "03/07/1994";
$dataConvert = date("Y-m-d", strtotime($dataBR));
$dateStart = new DateTime($dataConvert);
$dateNow   = new DateTime(date('Y-m-d'));

$dateDiff = $dateStart->diff($dateNow);
echo $dateDiff->y;

Usando apenas Javascript, você pode usar essa função:
function calcularIdade(aniversario) {
    var nascimento = aniversario.split("/");
    var dataNascimento = new Date(parseInt(nascimento[2], 10),
    parseInt(nascimento[1], 10) - 1,
    parseInt(nascimento[0], 10));

    var diferenca = Date.now() -  dataNascimento.getTime();
    var idade = new Date(diferenca);

    return Math.abs(idade.getUTCFullYear() - 1970);
}

https://jsfiddle.net/kodrw5sj/
Comment: blz, mais a onde eu coloco no meu código, para que na hora que o usuário digitar a senha e for menor ele não deixar enviar?
Comment: Utilize `DateTime::createFromFormat` ao invés de usar as funções `date` e `strtotime` desnecessariamente.
Comment: Gabriel, teria como você me da um exemplo, porque meu professor me disse para usar em um _POST, dessa maneira que estão falando não sei como fazer com que o usuário não cadastre ao ser menor de idade.
Comment: entendi, como faço isso em javascript? porque não tenho nenhuma noção... Desculpa e que estou começando a programar agora


Swift 3.0 - Sprite Kit - Multitouch

Question: I'm new to Swift SpriteKit, I want to make a game like a virtual joystick and two buttons(two nodes), I've enabled the multi-touch. However, whenever I move both virtual joystick and attack Spritenode, the virtual joystick of the button seems to be Jagging. How am I gonna separate the touches of virtual joystick from touches attackbutton
<code>class GameScene: SKScene {

var defend : Bool = false
var attack : Bool = false
var stickMove : Bool = false
var stickEnd:Bool = false
var moveattack:Bool = false
var movedefend:Bool = false

var playermovement:Bool = true

let vj1 = SKSpriteNode(imageNamed: "vj1")
let vj2 = SKSpriteNode(imageNamed: "vj2")
let player = SKSpriteNode(imageNamed: "player")
let rotationSpeed :CGFloat = CGFloat(M_PI)
let rotationOffSet : CGFloat = -CGFloat(M_PI/2.0)
let attackvj = SKSpriteNode(imageNamed: "attackvj")
let defendvj = SKSpriteNode(imageNamed: "defendvj")

private var touchPosition: CGFloat = 0
private var targetZRotation: CGFloat = 0

override func didMove(to view: SKView) {
    self.view?.isMultipleTouchEnabled = true
    self.backgroundColor = SKColor.black

    //position of joystick
    vj1.zPosition = 1
    vj1.xScale = 1.5
    vj1.yScale = 1.5
    self.addChild(vj1)

    vj1.position = CGPoint(x: self.size.width*15/100, y:self.size.height*30/100)

    vj2.zPosition = 1
    vj2.xScale = 1.5
    vj2.yScale = 1.5
    self.addChild(vj2)

    vj2.position = vj1.position

    player.zPosition = 0
    player.physicsBody = SKPhysicsBody(rectangleOf: player.size)
    player.physicsBody!.affectedByGravity = false
    player.position = CGPoint(x: self.size.width/2, y:self.size.height/2)
    self.addChild(player)

    attackvj.anchorPoint = CGPoint(x: 0.5, y:0.5)
    attackvj.position = CGPoint(x: self.size.width*80/100, y:self.size.height*30/100)
    attackvj.xScale = 2.0
    attackvj.yScale = 2.0
    self.addChild(attackvj)

    defendvj.anchorPoint = CGPoint(x: 0.5, y:0.5)
    defendvj.position = CGPoint(x: self.size.width*90/100, y:self.size.height*50/100)
    defendvj.xScale = 2.0
    defendvj.yScale = 2.0

    self.addChild(defendvj)

    vj1.alpha = 0.4
    vj2.alpha = 0.4
    attackvj.alpha = 0.4
    defendvj.alpha = 0.4

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in (touches){
        let location = touch.location(in: self)

        if vj2.contains(location){

            stickEnd = false
            stickMove = true
        }

        if defendvj.contains(location){
            defend = true
        }

        if attackvj.contains(location){
            attack = true
            attackvj.xScale = 2.5
            attackvj.yScale = 2.5

        }

        if(stickMove == true && attack == true){
            moveattack = true
        }
        if(stickMove == true && defend == true){

            movedefend = true
        }

    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in (touches){
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)
        let v = CGVector(dx: location.x - vj1.position.x, dy: location.y - vj1.position.y)
        print("locationsss" , location , "previouslocationsss", previousLocation)
        let angle = atan2(v.dy, v.dx)
        targetZRotation = angle + rotationOffSet
        let length:CGFloat = vj1.frame.size.height / 2

        let xDist:CGFloat = sin(angle - 1.57079633) * length
        let yDist:CGFloat = cos(angle - 1.57079633) * length
        if(stickMove == true){

            if(vj1.frame.contains(location)){

                vj2.position = location
            }
            else{

                vj2.position = CGPoint(x: vj1.position.x - xDist, y: vj1.position.y + yDist)
            }
            if(attackvj.frame.contains(location)){//How am I gonna make this location in attackvj, not to influence my joystick location?

            }

        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    if(stickMove == true && attack == false && defend == false){
        let move:SKAction = SKAction.move(to: vj1.position, duration: 0.2)
        move.timingMode = .easeOut
        vj2.run(move)
        stickEnd = true
        stickMove = false
    }
    if(attack == true){
        attack = false
        attackvj.xScale = 2.0
        attackvj.yScale = 2.0
        moveattack = false
    }
    if(defend == true){
        defend = false
        movedefend = false
    }
}

override func update(_ currentTime: TimeInterval) {
    //rotation
    if (stickEnd == false) {
    var angularDisplacement = targetZRotation - player.zRotation
    if angularDisplacement > CGFloat(M_PI) {
        angularDisplacement = (angularDisplacement - CGFloat(M_PI)*2)
    }
    else if angularDisplacement < -CGFloat(M_PI) {
        angularDisplacement = (angularDisplacement + CGFloat(M_PI)*2)
    }

    if abs(angularDisplacement) > rotationSpeed*(1.0/60.0){
        let angularVelocity = angularDisplacement < 0 ? -rotationSpeed : rotationSpeed
        player.physicsBody!.angularVelocity = angularVelocity

    } else {
        player.physicsBody!.angularVelocity = 0

        player.zPosition = targetZRotation
    }

    }
    else{
        player.physicsBody!.angularVelocity = 0
    }
    //movement but use attack button to testing
    if (attack == true)
    {
        player.position = CGPoint(x:player.position.x + cos(player.zRotation + 1.57079633),y:player.position.y + sin(player.zRotation + 1.57079633))
    }
}
</code>
Comment: The problem you're experiencing is that you're not tying your touches to the behavior of your various controls.  You can store the UITouch objects between the touchesBegan and touchesMoved calls so that you can track which touch is which, and understand them separately.  Use touchesBegan to start tracking touches of various types, and just use touchesMoved as a signal that things might have changed for one of the touches you're tracking.
Comment: A (perhaps) better approach for what you're trying to do would be to have separate "touch pads" for your various buttons, and have them communicate game events up the chain to your game logic, rather than trying to make one big item that tries to take every possible UI element into consideration.  That way, you could build your UI elements in the manner you show in your code sample, but there would be no crosstalk between multiple contexts to confuse things.
Comment: Hi, cc, I really appreciate your response toward this topic, i've begin searching over the net and trial and error for nights, still no satisfying output.
Comment: Hi, cc, I really appreciate your response toward this topic, i've begin searching over the net and trial and error for nights, still no satisfying output.
when i holding down the joystick and moved around + holding attack button and moved around, the joystick seem affected by the "new" touch location of the buttons. Is there any way to fire touches seperately for each buttons?
Comment: Yuan, I've added an answer below that should illustrate the process.  Basically, it's about tracking which touch goes with which function - that's the part you were missing.
Answer: The problem you are facing is that you are mixing the contexts for your touches.  This is making things more difficult and complicated than they need to be.
The easiest thing to do would be to make your virtual joystick a separate SKSpriteNode class that tracks its own touches and reports them.  Same with the buttons - they track their own touches and report their state.
But if you want to continue with your current approach of having a high-level object track multiple touches, what you want to do is capture the context that each touch is associated with in touchesBegan, and then just update things on touchesMoved as necessary, canceling the touches in touchesEnded.
For instance, you want to associate a particular touch with the virtual joystick, because you don't want weirdness if they drag their finger off of it and over to the button, say.  And you want to know exactly which touch is lifted off when the user lifts a finger.
Here's some sample code that should illustrate the process:
<code> //
 // This scene lets the user drag a red and a blue box
 // around the scene.  In the .sks file (or in the didMove
 // function), add two sprites and name them "red" and "blue".
 //

 import SpriteKit
 import GameplayKit

 class GameScene: SKScene {

    private var redTouch:UITouch?
    private var blueTouch:UITouch?

     override func didMove(to view: SKView) {
        super.didMove(to: view)
        isUserInteractionEnabled = true
     }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        //  Grab some references to the red and blue sprites.
        //  (They must be direct children of the scene, or the
        //  paths must be amended.)
        guard let redBox = childNode(withName: "red") else { return }
        guard let blueBox = childNode(withName: "blue") else { return }

        for touch in touches {
            //  Get the location of the touch in SpriteKit Scene space.
            let touchLocation = touch.location(in: self)
            //  Check to see if the user is touching one of the boxes.
            if redBox.contains( touchLocation ) {
                //  If we already have a touch in the red box, do nothing.
                //  Otherwise, make this our new red touch.
                redTouch = touch
            } else if blueBox.contains( touchLocation ) {
                //  If we already have a touch in the blue box, do nothing.
                //  Otherwise, make this our new blue touch.
                blueTouch = touch
            }
        }

    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        //  We have already established which touches are active,
        //  and we have already tied them to the two contexts, so
        //  we just need to read their current location and update
        //  the location of the red and blue boxes for the touches
        //  that are active.
        if let redTouch = redTouch {
            guard let redBox = childNode(withName: "red") else { return }
            let location = redTouch.location(in:self)
            redBox.position = location
        }
        if let blueTouch = blueTouch {
            guard let blueBox = childNode(withName: "blue") else { return }
            let location = blueTouch.location(in:self)
            blueBox.position = location
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        //  The parameter touches contains a list of ending touches,
        //  so we check the touches we are currently tracking to
        //  see if they are newly lifted.  If so, we cancel them.
        if let touch = redTouch {
            if touches.contains( touch ) {
                redTouch = nil
            }
        }
        if let touch = blueTouch {
            if touches.contains( touch ) {
                blueTouch = nil
            }
        }
    }

 }
</code>
In the above code, we have separated out the touches on the red box and the blue box.  We always know which touch is dragging the red box around and which touch is dragging the blue box around, if any.  This is a simple example, but it's generalizable to your situation, where you'd have touches for the virtual joystick and each individual button.
Note that this approach works well for multitouch elements, too.  If you have a map that you want to be zoomable, you can keep track of two touches so that you can compare them for pinch gestures.  That way, if your pinch gesture accidentally strays over a button, you've already marked it as part of the pinch gesture, and know not to start triggering that button.
But again, a better approach would be to have a separate SKSpriteNode subclass that just tracks the joystick touches and reports its state to some higher-level manager class.  You already know everything you need to know to do this - it's like what you have without all the extra checking to see if there are other buttons pressed.  Same with the buttons.  The only new part would be messaging "up the chain" to a manager, and that's pretty straightforward to deal with.
Comment: Nice and clear explanation. Previously, I've actually mixed up all the touch. And I tried your coding, you basically assign each touch for each node. That makes the touch location not mixed up. Appreciate your help.  I've accepted your answer.

Swift 3.0 - Sprite Kit - Multitouch


Git branch no branch make data disappear

Question: I had this issue that the output of git branch used to be
* (no branch)
  master

Then I committed the changes and switched to the master branch, by running
git checkout master

Now I have to get back some files in *(no branch). How can I do that? The application is in production and has several changes, but I can't access...
Comment: you can use git reflog to see when you switched the branch
Comment: possible duplicate of [gitx How do I get my 'Detached HEAD' commits back into master](http://stackoverflow.com/questions/4845505/gitx-how-do-i-get-my-detached-head-commits-back-into-master)
Answer: Run git reflog to see where your HEAD has been before. Then it's best to use
git checkout -b some_new_branch_name commit_hash_from_reflog

to create a branch from that "lost" commit. You can then normally work with that branch and e.g. merge it.


Roland PHA-4 keybed -- what is the octave width?

Question: One of Roland's keybed is PHA-4, used for example in FP-E50 or Fantom 08 keyboards/digital pianos.
I didn't find it in specification, thus my question -- what is the octave width in this keybed?
Octave width -- the distance/width from key X, for example C4, to the same key but octave higher, in this example C5.
Comment: Might be a good question for the manufacturer.
Answer: This is an 88-note weighted keyboard, designed to emulate a piano keyboard. It's inconceivable that such a keyboard would have 'mini keys'.   So the octave width will be 165mm, same as every other modern piano.
Comment: 160 mm is not that unusual, for example Yamaha CK series AFAIK has such width. So there is a difference between "it has" and "it  will have". But of course it could be 165 mm, but I am asking to be sure, not to guess.
Comment: The question is a good one, because, sadly, there is no real standard on keyboard width.  Especially electronic keyboards may vary by as much as 20-30 mm from one end of the keyboard to another, making  vertical alignment of stacked keyboards by different vendors problematic.

Indeed, there is a niche market of custom narrow-gage piano keyboard replacements for small-handed keyboard players (like myself).
Comment: I'd be unhappy to have to play a keyboard with just-slightly-narrower-than-standard keys, I have to say...


number of ways to get n pairs of sticks

Question: I was practicing problems from CMU HW. In problem 3: Suppose that each of n sticks is broken into one long and one short part. The 2n parts are then
shuffled and arranged into n pairs from which new sticks are formed
It says
The total number of ways to get n pairs is $\frac{(2n)!}{(2^n)n!}$
Can someone please explain the denominator part of it.
Answer: HINT: if you order everything you will get your numerator..so you start by taking pairs in that order, at the end you will end up with an ordered set of pairs and each pair is going to have an order on it.
Comment: I understand that there will be 2n pieces now and that gives (2n)! . I dont understand the rest of it
Comment: So, in how many ways can you order the pairs if you have $n$ of them?
And inside the pairs you have $2$ elements..but there are $n$ pairs.
Comment: Okay. I have 2n pieces of sticks which gives (2n)!. And n pairs of them can be arranged in n! ways and in each pair we have 2 arrangements for n pairs.
So should it not be (2n)! * (2^n) * n! ?
Comment: No, but 0k see it this way. Call $D$ to your number, then you know that if you have your pairs **without any order** and then you order the pairs $n!$ and you order each pair $2^n$ then you will get $D *n!*2^n$ but that is the same as just order everything $2n!$.
Comment: Ya. That's true. But I still don't understand it clearly as to why it goes to denominator
Comment: Because is like an equivalent relationship between unordered pairs and each class(the classes are exactly what you are counting) has the same number of elements in it (i.e., $n!2^n$). So, in the end, you are dividing the whole ordered set of sticks on those equivalent classes.

number of ways to get n pairs of sticks


Django not recognize UUID Foreign Key

Question: I had this current model:
class Apps(models.Model):
    """
    Apps são os aplicativos que terão financeiro gerido, uma empresa/usuario pode ter multiplos apps conectados
    """
    app_code = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True, primary_key=True)
    chave_app = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True)
    usuario = models.ForeignKey(Usuario, on_delete=models.CASCADE)
    descricao = models.CharField(max_length=100)

The usuario field is an ForeignKey...
The usuario model is this:
class Usuario(AbstractBaseUser):
    """
    Classe que ira gerir o cliente final, cadastrado via APP ou Webapp
    """
    user_id = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True, primary_key=True)
    nome = models.CharField(max_length=120)
    celular = models.CharField(max_length=20, unique=False)
    email = models.EmailField(max_length=100, unique=True)
    ativo = models.BooleanField(default=True)
    chave_api = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = AccountManager()

    USERNAME_FIELD = 'chave_api'
    REQUIRED_FIELDS = ['email', 'nome', 'celular']

    class Meta:
        ordering = ('-created_at',)

All works nice, but when i try to list apps on django-rest-framework as list. I did same way on anothers models, with no foreign key, and listing is all ok. The error is giving only on this view with Foreign Key.

TypeError at /apps/
  str returned non-string (type UUID)

At database, my fields was inserted with this values:
[
  {
    "app_code": "423676e9968d41beaeeeb2da43fc56d8",
    "chave_app": "86c18ae7809e4bda88830090f309a00c",
    "descricao": "Matrix Cashback 2.0",
    "usuario_id": "998339b46bde40bca053978670626a6f"
  }
]

I'm using Django-rest-framework and Django in an personal project.
Don't know what to do now, did try lots of variants. It just do not recognize the Foreign Key as UUID.
My Serializer View is this:
class AppSerializer(serializers.Serializer):
    app_code = serializers.UUIDField(read_only=True)
    usuario = serializers.UUIDField(read_only=True)
    descricao = serializers.CharField(required=True, max_length=100)
    chave_app = serializers.UUIDField(read_only=True)
    chave_api = serializers.UUIDField(required=True)

    class Meta:
        model = Apps
        fields = ('app_code', 'chave_app', 'usuario', 'descricao')

    def create(self, validated_data):
        usuario = Usuario.objects.get(chave_api=validated_data.get('chave_api'))
        return Apps.objects.create(
            descricao=validated_data.get('descricao'),
            usuario=usuario
        )

    def update(self, instance, validated_data):
        instance.descricao = validated_data.get('descricao', instance.descricao)
        instance.save()
        return instance

Some help will be welcome! Thanks.
This is the error on browser when try to "list" all apps.
Answer: Founded the problem...
When try to list the serializer, i used UUIDField on usuario. But need to be ReadOnlyField
My correct AppSerializer now was:
class AppSerializer(serializers.Serializer):
    app_code = serializers.UUIDField(read_only=True)
    usuario = serializers.ReadOnlyField(source='usuario.user_id')
    descricao = serializers.CharField(required=True, max_length=100)
    chave_app = serializers.UUIDField(read_only=True)
    # chave_api = serializers.UUIDField(required=True)

    class Meta:
        model = Apps
        fields = ('app_code', 'chave_app', 'usuario', 'descricao')

    def create(self, validated_data):
        usuario = Usuario.objects.get(chave_api=validated_data.get('chave_api'))
        return Apps.objects.create(
            descricao=validated_data.get('descricao'),
            usuario=usuario
        )

    def update(self, instance, validated_data):
        instance.descricao = validated_data.get('descricao', instance.descricao)
        instance.save()
        return instance

Comment: Can you describe with some code how I could achieve the same thing without posting using the UUID field but another unique field? Thanks.

Django not recognize UUID Foreign Key


TStringList problem with values at index

Question: So I have several summary files that I want to read and get the values from.
I am doing the following:
OutputSummary := TStringList.Create;
for idx := 0 to 82 do
  OutputSummary.Insert(idx, '');

to initialize the values I'm using
then, I have a loop:
for idx := 0 to SummaryFiles.Count - 1 do
  begin
    AssignFile(finp, SummaryFiles[idx]);
    ReSet(finp);

    for ndx := 0 to 5 do
      ReadLn(finp, buff);

    for ndx := 0 to 82 do
      begin
        ReadLn(finp, buff);
        temp := GetToken(buff, ' ');
        buff := GetRemains(buff, '|');
        temp := GetToken(buff, '|');
        valuestring := OutputSummary[ndx] + delimiter + temp;
        OutputSummary.Insert(ndx, valuestring);

      end;

    CloseFile(finp);

end;

The first 0 to 5 loop skips the lines I don't want to read, and the 0 to 82 reads lines that look like
1. Initial Wait List|1770

So I was debugging the program to see how it works with just 2 SummaryFiles.
The first time through, it works perfectly. The line is read correctly, I get the value and when I insert valuestring, it looks like ",1770" (for example), and I can also highlight OutputSummary[ndx] after the insert command and see that the value was inserted correctly.
Then I open the second file, which also works fine until the line
valuestring := OutputSummary[ndx] + delimiter + temp;

the first time, OutputSummary[0] is correct and the correct line is added.
However, OutputSummary[1] through OutputSummary[82] is the same as OutputSummary[0]! This makes no sense since when I was first adding those values, I could see that OutputSummary[1] through 82 were unique and correct.
Can anyone see a problem? Is it a debugger error? Am I just missing something obvious that I don't see?
thanks
Answer: It looks to me like you're trying to create a table of some sort, with one column per input file and one row per line in the file, with the columns separated by the delimiter. If so, calling .Insert on the string list isn't going to quite work right, since you'll end up inserting 83 * SummaryFiles.Count rows.
Instead of the Insert call, you need something like this:
if OutputSummary.count > ndx then
  OutputSummary[ndx] := valuestring
else OutputSummary.Add(valuestring);

See if that helps.
Also, you might want to consider replacing the "magic number" 82 with a meaningful constant, like const LINES_TO_READ = 82. That makes it easier to read the code and understand what it's supposed to be doing.
Comment: Thanks, that worked! I think I originally had it this way but it gave me problems before I initialized the values, and I never changed it back.


Devise and Lazy Signup / Gradual Engagement password requirement

Question: I'm trying to implement gradual engagement with Devise as described here in Rails 3:
https://github.com/plataformatec/devise/wiki/How-To:-Email-only-sign-up
At the first step:
%h2 Sign up. All we need is your email address.   =
   semantic_form_for(resource, :as => resource_name, :url =>
   user_registration_path(resource)) do |form|
   = devise_error_messages!
   = form.inputs do

  = form.input :email, :input_html => {:autofocus => true}
= form.actions do
  = form.action :submit, :label => "Sign up"   = render 'shared/links'

I run into a "password cannot be blank" problem.
Under User.validators:
#<ActiveModel::Validations::PresenceValidator:0x007fe53fe264f0 @attributes=[:password],

but I do not have any validator for password in my user.rb file. Is this standard behavior for Devise?
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model
attr_accessible :password, :password_confirmation, :remember_me

The tutorial didn't mention configuring Devise beforehand. How should I fix this to allow for lazy engagement?
Answer: Override this method in user.rb
  def password_required?
    if !persisted?
      false
    else
      !password.nil? || !password_confirmation.nil?
    end
  end


how can I change the admin url?

Question: Is it possible to have the administration pages on a different place than /admin?
so something like: www.mysite.com/someotheradminlocation
I don't want the admin location to be guessable by hackers.
Comment: Knowing the URL for the administration pages is not a security issue in itself, and it should never be.
Comment: Security through obscurity is a waste of time, you should concentrate your efforts elsewhere. Enforce a strong password policy for administrators and make sure your permissions are set up correctly, keep up to date with security updates for core and contrib modules, etc
Comment: You can look at using [two factor authentications](http://groups.drupal.org/node/235938) to make log in more secure
Comment: I was just looking for an additional security method. After the site has been 'hacked'/'defaced' for 2 times in 2 month, I thought having the admin page hidden might add to making it more secure.
Answer: There is a module to do what monymirza suggested - http://drupal.org/project/rename_admin_paths

The purpose of this module is to secure drupal backend by overriding
  admin path.
Comment: This module is only for D7, OP tagged the question with D6.
Comment: Good point, Nikhil, though the project page does give some advice for Drupal 6.
Answer: This should be very easy. It's under Site building > URL aliases > Add alias (admin/build/path/add)
You can add a new URL alias there.
So if you can't find it you might need to install the pathauto module
solution 2
If you are using Drupal 6, you can get the same feature by using the following code in your settings.php file.
<code>function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
    if (preg_match('|^admin(?![^/])(.*)|', $path, $matches)) {
        $path = 'backend'. $matches[1];
    }
}

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
    if (preg_match('|^backend(?![^/])(.*)|', $path, $matches)) {
        $result = 'admin'. $matches[1];
    }
    if (preg_match('|^admin(?![^/])(.*)|', $path, $matches)) {
        $result = '404'. $matches[1];
    }
}
</code>
Comment: But by using outbound function will it not change admin -> new admin path and yet still allow a user to access new admin page  when you type in admin ?
Comment: The "solution 2" makes sense to me. @Toad, just replace "backend" with your unguessable string and it should work.
Comment: The preferred solution should make the admin path unguessable.

how can I change the admin url?


Comparing scientific studies (p-values, q-values)

Question: I am comparing two studies. Each study consists of an affected (cancer) and control groups of patients, for which a number of biomarkers (gut microbial species) were studied. For each biomarker univariate testing is performed (Mann-Whitney or Kruskal-Wallis) and the p-values are then adjusted using the Benjamini-Hochberg procedure (resulting in q-values).
The difficulty arises when comparing the results of the two experiments, since they contain different number of biomarkers, which only partially overlap. It seems that one cannot compare significance of the results based on the q-values, since these depend on all the biomarkers tested in each experiment.
I see two possible solutions

Comparing significance of results (for common biomarkers) based on the p-values.
Recalculating the BH correction only for the common biomarkers.

I will appreciate the input on whether these constitute valid procedures (and more generally, on the ways of carrying a comparison between two experiments).
Update
To put it in a more formal way: in an experiment $\nu$ we study a collection of biomarkers $\mathcal{A}^{(\nu)}=\{a_i^{(\nu)},i=1..M^{(\nu)}\}$. Every experiment consists of two groups of subjects, (affected and control), producing the results $x_{ij}$, $y_{ij}$ (the subjects are not paired and the sizes of the affected and control groups are not necessarily the same). Pairwise testing is then performed for every marker, so test if it is expressed differently in the two groups (null hypothesis: no difference), resulting in a vector of p-values $p_i^{(\nu)}$. The p-values are then adjusted using the Benjamini-Hochberg procedure, $\mathbf{q}^{(\nu)}=BH(\mathbf{p}^{(\nu)})$, and the decision of the faulure of the null hypothesis for each biomarker is made, respective to some threshold $\alpha$: $q_i{(\nu)}<\alpha$.
Biomarkers used in different experiments are not identical, but overlap, that is the set of common biomarkers is $\mathcal{B} = \mathcal{A}^{(1)}\cap\mathcal{A}^{(2)}$.
How can we compare the results of the two studies? (Note that the results may come from different scientific groups, different equipment, somewhat different procedures, so the data are not necessarily comparable. However, it is likely that the differences are reduced to a proportionality coefficient.)
Remark
I am not talking about comparing the p-values themselves, but rather how to judge which results are significant in both experiments, and which are not, and how to adjust for multiple testing in this context.
Comment: It is not meaningful to compare either p-values or q-values between studies. Can you explain what you mean by "compare two studies"? For example, can you formulate a null and alternative hypothesis? Are there any parameters/quantities of interests that can be estimated from most studies?
Comment: @dipetkov in every study one carried a series of tests, identifying some markers as significant. The question is whether the two studies are consistent. E.g., does the second study confirm/contradict the results of the first?
Comment: And the only data you have from the two studies are p-values?
Comment: @dipetkov there's more than that, but I do not want to deviate from the question.
Comment: @dipetkov if it makes things easier, you may assume that I have all the data used to obtain the p-values. The point is that the experiments are not identical.
Answer:
rather how to judge which results are significant in both experiments, and which are not,

If one study finds significance and the other does not, it means that either one makes an alpha error or the other a beta error. The alpha error should not exceed 5% probability whilst very littls is known about the beta error except that it's probablity will depend on sample size. So if one study yields significance and the other not, that is not necessarily contradictory. p-values are random numbers and there is not much point in comparing them.

However, it is likely that the differences are reduced to a proportionality coefficient

you may assume that I have all the data used to obtain the p-values

Wouldn't it be much more worthwhile to take the original data, estimate the "proportionality" constant with it's confidence intervall for both studies and compare, how well those go together?
As far as I understand the question I'd compare the estimates of the common "proportionality factor" and not the p-(or q-)values
Comment: Thanks, it helps - both the remark about the alpha/beta errors, and testing the proportionality constants. The problem arises in the context of testing a new bioinformatics pipeline against the existing standard - that is I am more interested in proving that I reproduce the results of the previous study, rather than combining the two.


Computing the closed subschemes of the projective line over a field

Question: (Specifically, this is III-15 in E&H, but I feel like I've hit a brick wall in actually applying the definitions they've given to this example.)
In Chapter I of The Geometry of Schemes, E&H define the closed subscheme $Y \subseteq X$ associated to an ideal $I \subseteq R$ by quotienting $\mathscr{O}_X$ by the sheaf of ideals $\mathscr{J}$ induced by sending basic open sets $X_f \mapsto I \cdot R_f$, so that (denoting by $j$ the inclusion $|Y| \hookrightarrow |X|$) we have $j_*(\mathscr{O}_Y) = \mathscr{O}_X / \mathscr{J}.$
How do I show, using this definition, that the closed subschemes defined by the ideals $(x_0)$ and $(x_0^2,x_0x_1)$ consist of one point and are identical? (In particular, how can I figure out what $\mathscr{J}$ looks like by computing what the ideals look like under localization for each basic open set?)
Any help would be greatly appreciated.
Answer: The associated ideal sheaf you you define makes sense only for affine schemes. For a projective scheme $X$ with projective coordinate ring $S$, given a homogeneous element $f \in S_+$ the basic open set it defines is $D_+(f)=Spec{ S_{(f)}}$.
So the corresponding ideal should be the zero grading of the ideal $I \cdot S_f$.
Globally you just need to take the homogeneous ideal $I=(f)$.
In your case these are the ideals $I=(x_0)$ and $I=(x_0^2,x_0x_1)$.

The projective line $\mathbb{P}^1_A = Proj {A[x_0,x_1]}$ over a ring $A$ is covered by the open sets $U_i= \{x_i \neq 0 \}$, $i=0,1$.
These sets are affine $U_i = Spec{A[\frac{x_0}{x_i},\frac{x_1}{x_i}]}=\mathbb{A}^1_A$. Also $A[\frac{x_0}{x_i},\frac{x_1}{x_i}]$ is the zero grading of the localization $A[x_0,x_1]_{x_i}$.
The ideal sheaf $\mathcal{I}$ corresponding to a closed subscheme defines ideals $\mathcal{I}(U_i) \subset A[\frac{x_0}{x_i},\frac{x_1}{x_i}]$. Now you can apply everything you know about affine schemes to the $U_i$'s.
Comment: Does this help or to add more details?
Comment: I'm processing; this does help, thank you :); if possible, could elaborate on how this follows from the general definition of a closed subscheme of an arbitrary scheme defined by an ideal?