Check on UIAlertController TextField for enabling the button

Question: I have an AlertController with a text field and two button: CANCEL and SAVE. This is the code:
@IBAction func addTherapy(sender: AnyObject)
{
    let addAlertView = UIAlertController(title: "New Prescription", message: "Insert a name for this prescription", preferredStyle: UIAlertControllerStyle.Alert)

    addAlertView.addAction(UIAlertAction(title: "Cancel",
                                         style: UIAlertActionStyle.Default,
                                         handler: nil))

    addAlertView.addAction(UIAlertAction(title: "Save",
                                         style: UIAlertActionStyle.Default,
                                         handler: nil))

    addAlertView.addTextFieldWithConfigurationHandler({textField in textField.placeholder = "Title"})

    self.presentViewController(addAlertView, animated: true, completion: nil)

}

What I want to do is implement a check on the textfield for disabling the SAVE button when the textfield is empty just like Pictures Application of iOS when you want create a NewAlbum. Please someone can explain me what to do?
Answer: There is a much simpler way without using notification center, in swift:
weak var actionToEnable : UIAlertAction?

func showAlert()
{
    let titleStr = "title"
    let messageStr = "message"

    let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.alert)

    let placeholderStr =  "placeholder"

    alert.addTextField(configurationHandler: {(textField: UITextField) in
        textField.placeholder = placeholderStr
        textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
    })

    let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (_) -> Void in

    })

    let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (_) -> Void in
        let textfield = alert.textFields!.first!

        //Do what you want with the textfield!
    })

    alert.addAction(cancel)
    alert.addAction(action)

    self.actionToEnable = action
    action.isEnabled = false
    self.present(alert, animated: true, completion: nil)
}

func textChanged(_ sender:UITextField) {
    self.actionToEnable?.isEnabled  = (sender.text! == "Validation")
}

Comment: On the Swift 3 code, `actionToEnable` variable defintion is missing
Comment: Superb..! Cool Answer
Comment: Swift 5 changed the functions quite a bit. Xcode at least suggests the edits, apart from one thing: `#selector(self.textChanged(_:))` doesn't work like that anymore, it just gives an error (`Type 'MyClass' has no member 'textChanged'`) - yes, the function is there. I tried all the versions suggested [here](https://stackoverflow.com/a/41049859/2016165) but nothing worked.
Answer: I would first create the alertcontroller with the save action initially disabled. Then when adding the textfield inculde a Notification to observe its change in the handler and in that selector just toggle the save actions enabled property.
Here is what I am saying:
//hold this reference in your class
weak var AddAlertSaveAction: UIAlertAction?

@IBAction func addTherapy(sender : AnyObject) {

    //set up the alertcontroller
    let title = NSLocalizedString("New Prescription", comment: "")
    let message = NSLocalizedString("Insert a name for this prescription.", comment: "")
    let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
    let otherButtonTitle = NSLocalizedString("Save", comment: "")

    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    // Add the text field with handler
    alertController.addTextFieldWithConfigurationHandler { textField in
        //listen for changes
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField)
    }

    func removeTextFieldObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields[0])
    }

    // Create the actions.
    let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
        NSLog("Cancel Button Pressed")
        removeTextFieldObserver()
    }

    let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in
        NSLog("Save Button Pressed")
        removeTextFieldObserver()
    }

    // disable the 'save' button (otherAction) initially
    otherAction.enabled = false

    // save the other action to toggle the enabled/disabled state when the text changed.
    AddAlertSaveAction = otherAction

    // Add the actions.
    alertController.addAction(cancelAction)
    alertController.addAction(otherAction)

    presentViewController(alertController, animated: true, completion: nil)
}

    //handler
func handleTextFieldTextDidChangeNotification(notification: NSNotification) {
    let textField = notification.object as UITextField

    // Enforce a minimum length of >= 1 for secure text alerts.
    AddAlertSaveAction!.enabled = textField.text.utf16count >= 1
}

I am doing this in another project - I got this pattern directly from apple examples.  They have a very good example project outlining a few of these patterns in the UICatalog examples:  https://developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html
Comment: Using a notification is way too heavy-handed (and unreliable, and too much work). This is why there are text field delegates and actions. See my answer here: http://stackoverflow.com/a/25628065/341994
Comment: Matt's answer is better
Comment: You help me a lot! Thank you very much!
Comment: It is giving error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Naina.SearchVillageTableViewController handleTextFieldTextDidChangeNotification:]: unrecognized selector sent to instance 0x7f802dc41f50'
Answer: Swift 3.0 Updated Solution given By @spoek
func showAlert()
    {
        let titleStr = "title"
        let messageStr = "message"

        let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.alert)

        let placeholderStr =  "placeholder"

        alert.addTextField(configurationHandler: {(textField: UITextField) in
            textField.placeholder = placeholderStr
            textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
        })

        let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (_) -> Void in

        })

        let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (_) -> Void in
            let textfield = alert.textFields!.first!

            //Do what you want with the textfield!
        })

        alert.addAction(cancel)
        alert.addAction(action)

        self.actionToEnable = action
        action.isEnabled = false
        self.present(alert, animated: true, completion: nil)
    }

    func textChanged(_ sender:UITextField) {
        self.actionToEnable?.isEnabled  = (sender.text! == "Validation")
    }

Comment: Really helpful. Thanks :)
Comment: Unfortunately this doesn't work in Swift 5: There's an error for `#selector` (`Argument of '#selector' refers to instance method 'textChanged' that is not exposed to Objective-C`) but if I change the function to `@objc func textChanged`, then I get a different error (`@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes`) and it wants me to remove it again.
Answer: I implemented a subclass of UIAlertController for conveniently adding text fields and associated enabling and disabling of buttons. The basic logic is similar to that Sourabh Sharma but everything is encapsulated in this subclass for tidiness. This should be helpful if your project involves a lot of such alert functionalities.
public class TextEnabledAlertController: UIAlertController {
  private var textFieldActions = [UITextField: ((UITextField)->Void)]()

  func addTextField(configurationHandler: ((UITextField) -> Void)? = nil, textChangeAction:((UITextField)->Void)?) {
      super.addTextField(configurationHandler: { (textField) in
        configurationHandler?(textField)

        if let textChangeAction = textChangeAction {
            self.textFieldActions[textField] = textChangeAction
            textField.addTarget(self, action: #selector(self.textFieldChanged), for: .editingChanged)

        }
    })

}

  @objc private func textFieldChanged(sender: UITextField) {
    if let textChangeAction = textFieldActions[sender] {
        textChangeAction(sender)
    }
  }
}

To use it, just provide a textChangeAction block when adding the text fields:
    alert.addTextField(configurationHandler: { (textField) in
        textField.placeholder = "Your name"
        textField.autocapitalizationType = .words
    }) { (textField) in
        saveAction.isEnabled = (textField.text?.characters.count ?? 0) > 0
    }

For the full example, see the git page.


Set PHP to be include file

Question: I have an email template that is inside a PHP script.  I am using PHPmailer and the message that is sent is stored in a variable called $msg.
How can I set $msg to be the email template include file?  I'm hoping there is a way to do this dynamically with an include file so that I don't have to store 20 copies of the template in different scripts.
Answer: Not sure if I am understanding you correctly, but why can't you just do this?
include_once('filename.php');

Answer: You have multiple approaches, three of which I will mention below.
Solution no. 1 - simple inclusion
First of all, if you include a file like in the following example:
include('myfile.php');

its code will be executed exactly as if it was pasted instead of the above mentioned line. Thus if you will add value declaration in myfile.php, the variable will be available just after include() function call (mentioned above).
So, basically, you can do something like that in myfile.php file:
<?php

$msg = 'my template';

and use $msg variable anywhere after include() call in the main file (unless the variable has been overwritten).
Solution no. 2 - inclusion with use of return
For use in some cases, eg. when you only include files containing some values you want to use (the main purpose of the file is to give some value to be processed), you may wish to use the following example. It should not interfere with your current variables (if used correctly).
In the main file:
$msg = include('myfile.php');

and in the myfile.php file:
<?php

return 'my template';

This way your file works only by returning specific variable and does not break the naming convention from your other files. Also you are free to call the variable the way you like without the need to change the configuration file's content.
Solution no. 3 - output buffering
In some cases (messy coding, HTML etc.) you may be required to use this solution. The following code catches everything emitted by the file and saves it into variable $msg, then turns the buffering off.
ob_start();
include('myfile.php');
$msg = ob_end_flush();

This way, if you have eg. echo calls, or some static HTML, within the included file, it will not be written "as is" and could be processed further (eg. some tokens from your template may be replaced with the actual data you want to use).
So, basically, in this case you can even write in myfile.php something like:
<?php

echo 'my template';

or even:
my template

(just a text, not PHP code).
Comment: Please _never_ do #2. It seems reasonable, right up until your code needs modifying to do some calculations on what to return. Suddenly you're faced with trying to pick variable names that won't clash, and coding around function redefinitions (speaking from recent experience)
Comment: @PhilLello: You may not know, but this is common practice for configuration files, eg. in some mature PHP frameworks. Thus I still suggest using this solution. Furthermore, calculation on what to return as configuration option seems like a basic mistake - in my opinion configuration options should not depend on some heavy calculations (rather the opposite) and the solution no. 2 ensures it  (partially).
Comment: Oh believe me, I know. I've also been bitten by it. Consider what happens when you're migrating between frameworks and want to share incompatible config file formats. Changing a function implementation to read a common file and return the expected format is simple; fixing every place that includes the config is more maintenance, and has a higher chance of error. Or even when sticking to one framework, you might want to swap the backing mechanism for config - perhaps INI files, perhaps XML, perhaps results from a database query.
Answer: You can have $msg = "…"; in a PHP script and include this where necessary. However, if it's just plain text, you may want to consider saving it as a .txt file and using file_get_contents.
Answer: You can write in your template file:
$msg = """ the message
bla bla bla""";

Then when you include the file from another php module you can access to this variable.
Answer: You can either save it into a raw text file and load it with file_get_contents, or save a string with the text in it in another php file and include it.
Example:
Template.php:
<?php
$globalMessage = "template string goes here";
?>

Every other file:
<?php
include 'Template.php';
echo $globalMessage; // has access
?>

Answer: If you want to get the contents of the template file into the $msg variable you can do the following:
<?php
 $msg= get_include_contents('email_template_file.php');

 function get_include_contents($filename) {
 if (is_file($filename)) {
    ob_start();
    include $filename;
    return ob_get_clean();
 }
 return false;
 }

 ?>

Now your $msg variable has the text of your email. If you have some generic terms like Username, phone-no etc you want to be different for different users. Store them in tokens like {username}, {phone-number} in your template file. Once you get the contents in $msg variable, you can use the below:
<?php str_replace('{username}',$username,$msg); ?>

to change the values dynamically for each user you want to send mail.

Set PHP to be include file


Fatou's lemma extension and dropping lim inf.

Question: Let $(f_n)_{n\in \Bbb N}$ be a sequence of elements in $M(X,S)$, let $g\in M^+(X,S)$ such that $\int gd\mu<\infty$ and $f_n\ge-g\ $ $(a.e.- \mu)\ \forall n\in \Bbb N\ $ in $E\in S$. Then, it follows from Fatou's lemma that:
$$\int_{E} \liminf_{n\to \infty} (f_n)d\mu\le \liminf_{n\to \infty} \int_E f_nd\mu$$
Question 1 Can someone please give me a reference for the above generalised fatou's lemma.
Question 2 What is the condition on $(f_n)_{n\in \Bbb N}$ so that we may drop $\lim \inf$ and we have $$\int_{E} \lim_{n\to \infty} (f_n)d\mu\le \lim_{n\to \infty} \int_E f_nd\mu$$
My try: Define $$h_n=f_n+g$$ Then $h_n\geq 0$.
Applying fatou's lemma to $h_n$ we have $$\int_{E} \liminf_{n\to \infty} (h_n)d\mu\le \liminf_{n\to \infty} \int_E h_nd\mu$$
So we get $$\int_{E} \liminf_{n\to \infty} (f_n+g)d\mu\le \liminf_{n\to \infty} \int_E (f_n+g)d\mu$$
How do we conclude?
Comment: I don't have the book on me to confirm, but this should probably be in *Real Analysis* by Royden and Fitzpatrick?
Comment: @Zim So both of my questions are answered there? Can you please give a brief idea for the proof.
Comment: This is just Fatou's Lemma applied to $f_n+g$. Nobody would state this separetely as a theorem.
Comment: @Kavi Rama Murthy So the condition that $g>0$ is needed or not?
Comment: No. It is not needed.
Comment: @Kavi Rama Murthy So we get $$\int_{E} \liminf_{n\to \infty} (f_n+g)d\mu\le \liminf_{n\to \infty} \int_E (f_n+g)d\mu$$
How do we conclude?
Comment: $\lim \inf (a_n+b)=\lim \inf a_n +b$.
Comment: @Kavi Rama Murthy Thank you so much. Please answer my question 2 in the post. In what condition can we write $\lim$ in place of $\lim \inf$ in the inequality?
Comment: The limit on both sides have to exist. That is it. No extra condition is needed.
Comment: @Kavi Rama Murthy Then why sir we have $g>0$ given in every "Extension of Fatou's lemma"?
Comment: @Kavi Rama Murthy So if $\lim_{n\to \infty} f_n$ exist and the integral  $\int_{E} \lim_{n\to \infty} (f_n)d\mu$  is finite and also
$   \lim_{n\to \infty} \int_E f_nd\mu$ is finite then we will have the following:         $$\int_{E} \lim_{n\to \infty} (f_n)d\mu\le \lim_{n\to \infty} \int_E f_nd\mu$$  Is this true?
Comment: @Kavi Rama Murthy Please reply Sir.
Answer: Let $g_n(x)=\inf\{f_i(x) : i \geq n \}$.  Then $g_n(x)$ increases monotonically to $\liminf f_n$ and by the monotone convergence theorem, $\int g_n = \int \liminf f_n$.  Since $g_n \leq f_n$ for every $n$, we have $\int g_n \leq \int f_n$.  Your result then follows.


How to get specific text when clicking on button?

Question: I want to get the specific text that is shown and tweet it out.
http://codepen.io/anon/pen/mOeXVM
below its my code:
function tweet () {
  var phrase = $(this).text();
  alert(phrase);
 // var phrase = document.getElementsByClassName('panel-body')[0];

  var tweetUrl = 'https://twitter.com/share?text=' +
    encodeURIComponent(phrase) ;

  window.open(tweetUrl);
}

Comment: Was going to post an answer but RatHat beat me to it, so here's the codepen: http://codepen.io/anon/pen/WoQyym - Also, you spelled "Quotes" wrong, and your sentence should read "These are ra**n**dom quotes, some nice ones!"
Answer: By using var phrase= $(this).text(), you are getting the 'Text' of the clicked button since it's the element that called the function. Instead you need to get the text of the panel that's currently visible. The following jQuery should do the trick
function tweet () {
  var newarr = $('.panel-body:visible').text();
  alert(newarr);
  //var phrase = document.getElementsByClassName('panel-body')[0];

  var tweetUrl = 'https://twitter.com/share?text=' +
    encodeURIComponent(newarr) ;

  window.open(tweetUrl);
}

Comment: I believe you should change `encodeURIComponent(phrase)` to `encodeURIComponent(newarr)`.
Comment: @Santi you are absolutely correct. Just updated the code.


findall(X,condition,List) list is filled with pointers and not real objects

Question: I am trying to get a list full of objects from the database that fit my condition.
Here is my database:

student(1234,[statistics/a,algorithms/b,prolog/a,infi/b]).
student(4321,[java/a,algorithms/a,prolog/b,probability/b,infi/a]).
student(1111,[algorithms/a,prolog/a,c/a,infi/a]).
student(2222,[c/b,algorithms/b,prolog/b,infi/a]).
student(3333,[java/b,algorithms/b,prolog/a,infi/a]).
student(4444,[java/a,c/a,prolog/a]).
student(5555,[java/a,c/a,prolog/b,infi/b]).
student(6666,[java/a,c/a,prolog/b,infi/b,probability/b,algorithms/b]).

I wrote a predicat that queries which student has a string in the list attached to him that has: "infi/a"
findall(Ns,(student(Id,List),subset([infi/a],List)),L1)

The problem is that L1 does not return me a list as the following:

L1 = [student(2222,[c/b,algorithms/b,prolog/b,infi/a]),
      student(1111,[algorithms/a,prolog/a,c/a,infi/a]) etc...]

It returns:
L1 = [_G2044, _G2041, _G2038, _G2035].

Why does this happen and how can I fix this?
Comment: Those aren't "pointers". Those are uninstantiated anonymous variables. It is because your `Ns` doesn't appear anywhere in your `findall/3` condition (second argument), so `findall/3` fills `L1` with empty variables.
Answer: You probably need to look up the specifications of the findall/3 predicate the first parameters is the Template (or yield): it specifies what you want to put into the list.
So you should not simply write X, but a term in which you are interested. For instance:
findall(Id,(student(Id,List),subset([infi/a],List)),L1).
will generate all the Ids of the students with infi/a in their list of courses; or if you are interested in the student/2 objects, you can write:
findall(student(Id,List),(student(Id,List),subset([infi/a],List)),L1).
So typically you work with the variable(s) you specify in the Goal (the second parameter), in case there is a free variable in your yield, it will make new free variables.
Comment: Thanks! This did the trick. From some reason it was hard for me to grasp this "first parameters is the Template", but now after your answer I understand the concept!


How to find the list and order of classes the JVM is trying to load (rather than the ones already loaded)

Question: I'm trying to debug an issue where Sun JVM is trying to load a class which is not used by the static method I call, and it is resulting in a NoClassDefFoundError. Details below:
Method A.x() calls B.getTZ_OFFSET() and it runs into NoClassDefFoundError for OraclePreparedStatement even before the control reaches getTZ_OFFSET. I had a look at the all the static variables and blocks in B and none of them refer to OraclePreparedStatement or anything even closely related to that. I'm assuming that just importing the class doesn't cause the class to be loaded.
How do I find out the dependency, based on which JVM is trying to load OraclePreparedStatement?
The switch -verbose:class only gives the list of classes that have successfully been loaded, not the ones the JVM is trying to load. Is there a way to get that info as well?
Any help will be highly appreciated.
I'm aware that importing ojdbc.jar causes the problem to vanish, but I'm more interested in the root cause, as to why it's trying to load it in the first place.
Answer: The class your JVM cannot find may be referenced in a number of places: in the argument list of the method you call, return type, class (static) members of the class you are using, class members of any super classes and static initializers. You have to check all these places to find the hidden reference. The NoClassDefFoundError may also be masking some other error you get, for example an exception object that gets created and references the non existent class.
One way to determine the order classes are loaded is to implement your own class loader. You only need to extend class ClassLoader and override method loadClass(String, boolean), whereby you could print to standard out the name of the class being requested and then delegate to super.loadClass(String, boolean).


I want to show the numbers at risk in a survival or cumulative incidence plot under the x-axis

Question: Under the x-axis marks, I'd like to annotate the y-values corresponding to those x-values. Best explained by this graph:
Example
Comment: There are more x axis points in that plot than there are summaries beneath it.  Because there is no clear mapping of summary to x-axis values, it doesn't even appear to represent what you've requested.  At a higher level, it looks like a bad way to present data.
Comment: Please post a reproducible example of the code you have so far.  Guidance on doing so is here http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Answer: If Frank Harrell were a contributor here I would wait for him to post but since he's not, here's a minor modification from the first example in help(survplot) in his great "rms" package:
require(rms)
n <- 1000
set.seed(731)
age <- 50 + 12*rnorm(n)
label(age) <- "Age"
sex <- factor(sample(c('male','female'), n, TRUE))
cens <- 15*runif(n)
h <- .02*exp(.04*(age-50)+.8*(sex=='female'))
dt <- -log(runif(n))/h
label(dt) <- 'Follow-up Time'
e <- ifelse(dt <= cens,1,0)
dt <- pmin(dt, cens)
units(dt) <- "Year"
dd <- datadist(age, sex)
options(datadist='dd')
S <- Surv(dt,e)

# When age is in the model by itself and we predict at the mean age,
# approximate confidence intervals are ok

survplot(f, age=mean(age), conf.int=.95,
               n.risk=TRUE, adj.n.risk=.75, y.n.risk=-0.15,
               xlab="")
title(main="Simulated Survival Plot Demonstrating Annotation of N-at-risk")
mtext("Follow-up Years", side=1, line=2)


MANCOVA or several ANCOVAS

Question: I am analyzing pre- and post- intervention data for which I have 6 dependent variables for two groups (treatment, no treatment). I want to know if, controlling for pre scores from the 6 measures, post scores differ between the two groups. (Some DVs show significant correlations with each other.)
I want to know whether a MANCOVA is appropriate, with all 6 DVs and the corresponding 6 pre tests entered as covariates, or whether running a separate ANCOVA for each DV and the corresponding pre test as covariate is more appropriate.
Other ideas for analysis are welcome, thank you in advance.
Answer: Since you are using pre-treatment and post-treatment scores, I believe you should be considering that these scores are highly correlated due to within-subject variance. I would recommend doing 6 repeated measures ANOVA instead, with pre and post scores being the within subject variable. You could have the two groups as a factor in the repeated measures ANOVA.
This will allow you to see (1) how the 6 DVs change over time and (2) whether these changes over time differ between the two groups (i.e., if there is an interaction).

MANCOVA or several ANCOVAS


Como faço para fazer uma interação entre duas tabelas () com AJAX?

Question: Preciso fazer uma interação entre duas tabelas em uma aba lateral, onde inicialmente uma tabela "resposta" fica escondida e a tabela "pergunta" estará disponível e assim que no input de pesquisa acima delas eu digitar algo via AJAX automaticamente aparecerá na tabela "pergunta", até ai resolvi
Como esconder a segunda tabela que é a que eu quero que apareço somente após eu clicar em um item? Ou seja, a pergunta da primeira tabela e a primeira tabela suma neste momento.
Comment: Se a questão é SOMENTE de "sumir" e "aparecer", você pode usar `$('#tabela_para_sumir').css('display', 'none');` e `$('#tabela_para_aparecer').css('display', 'block');`, acrescente no elemento de `id="tabela_para_aparecer"` o parâmetro `style="display:none;"`. Se você não estiver usando JQuery, utilize funções similares, com a finalidade de alterar o `display` do CSS. Você também pode obter por usar `$(...).hide()` e `$(...).show()`, para as respectivas funções, caso use JQuery.
Comment: Você só precisa utilizar ajax caso vá fazer alguma requisição no banco. Na questão você não menciona isso. Se não for fazer nenhuma requisição pode tentar o que o amigo acima sugeriu.
Comment: Então Inkeliz e Joao Paulo, obrigado pelas explicações , me ajudaram a clarear a mente, pois bem eu utilizei no document.ready o $("#teste_faq_resposta").hide(); e logo quando acesso a pagina esta escondida beleza mas ai na tabela onde eu consigo captar os dados do BD que preciso que são as perguntas da tabela no mysql chamada "nomeconfidencial"_faq ao clicar em uma linha onde esta a pergunta a qual eu preciso que apareça a resposta posteriormente não consigo fazer aparecer a outra tabela ou seila qual tipod e tag usar ja tentei usar "p" para aparecer a resposta e esconder a pergunta.
Comment: pessoal valeu pelas dicas consegui fazer desaparecer e aparecer outra tabela com as respostas agora meu próximo passo é fazer aparecer exatamente a resposta da pergunta a qual selecionei, alguem tem alguma dica? agradeço de coração!
Answer: Para saberes qual foi a linha que selecionaste poderás fazer o seguinte, no html:

  A
  B

  C
  D

e em jquery para obteres essa mesma linha poderás fazer o seguinte
$('tr[id=' + id + ']').remove();
// id será o valor que queres passar no caso é 2 , neste caso vai apagar a linha

exemplo em uma função:
function qualLinha(){
$('#table tr').click(function (event) {
      alert($(this).attr('id')); //alerta qual foi o id da linha que selecionaste
 });
}


EILSEQ with fgetws() and UTF-8

Question: The following C code reads lines from stdin using fgetws() and writes them to stdout.
#include <stdio.h>
#include <locale.h>
#include <wchar.h>

#define STR_LEN 128

int main(int argc, char **argv)
{
    FILE *infile = stdin, *outfile = stdout;
    wchar_t str[STR_LEN];

    if (setlocale(LC_ALL, "en.UTF-8") == NULL) {
        fprintf(stderr, "Cannot set locale\n");
        return 1;
    }

    for (;;) {

        if (!fgetws(str, STR_LEN, infile)) {
            if (feof(infile)) {
                break;
            }
            perror("fgetws()");
            continue;
        }
        str[wcscspn(str, L"\r\n")] = L'\0';

        if (fwprintf(outfile, L"%ls\n", str) < 0) {
            perror("fwprintf()");
        }

    }

    return 0;
}

It always works perfectly with ASCII files, but sometimes it gets EILSEQ error (Illegal byte sequence) from fgetws() when reading UTF-8 data, and I cannot figure out why.
In the output file, the line which causes the error is truncated, then some characters are missing and the remaining part is on the next line.
The strange thing is that if I give only that line, then I will not get any error.
For example, if I read a file with just a few UTF-8 lines, it's ok; if I repeat the same lines many times, then I get EILSEQ.
I'm almost sure that the file is correctly encoded.
I use Linux with musl-libc.
What's wrong in my code?
EDIT:
I get several EILSEQ errors, depending on the input size, but I don't know the exact relationship beetween the two.
With the same input I get the same errors at the same lines.
It does not seem to be a specific offset or character which triggers the error, but I might be wrong.
EDIT 2:
I tested the code also on OpenBSD and it works. At this point I suspect that this issue is related to Linux or musl-libc.
Comment: `str[strcspn(str, "\r\n")] = 0;` might be a better way.
Comment: Does it always fail at the same point in the file? Do you get one EILSEQ errors or two? What is the precise byte offset of the character which triggers the error and the utf-8 code for that character?
Answer: UTF-8 uses char to store characters, it works the same way as ANSI. The only difference is that a linguistic character can be longer than one character.
wchar_t and wide-c string functions are used for UTF-16 in Windows. In Linux you would use char16_t to store UTF-16, but only if you are working with UTF-16 files. That's clearly not the case here.
Just use char functions to handle UTF-8, the exact same way you work with ANSI:
char str[STR_LEN];
while(fgets(str, STR_LEN, infile))
{
    str[strcspn(str, "\r\n")];
    fprintf(outfile, "%s\n", str);
}

Comment: Yes, the above program will work even with `char` strings. But if I need to manipulate single characters after reading, then I will need `wchar_t`, right? I prefer to not use external libraries (e.g. ICU), because I need to do only simple things.
Comment: Aren't you using Linux? `whcar_t` is used in Windows, it's rarely used in Linux. Just use `char`. You can parse the text if you are just searching for ANSI characters like `'\n'` or `','` because those characters don't repeat elsewhere. Treat it as regular ANSI text. But if you have something like `"ελληνικά"` then it's very difficult to find `'η'`, because `'η'` is a combination of different characters, you would rarely need that option.
Comment: Unfortunately I need to perform operations on non-ASCII characters.
Comment: Okay, then you may need external libraries. Your console input is UTF-8. You have to convert to UTF-32. Then store it in `char32_t` (or `wchar_t`). Now each character occupies 4 bytes. That's if you wanted to find the position of `'η'` in `"ελληνικά"`. Note however, it's easy to find the position of `','` in `"ελλ,ηνικά"` (it won't be at index 3, but you just go through the string and find it)

EILSEQ with fgetws() and UTF-8


Disable scrollTop when triggering mousewheel or trackpad

Question: I'm using a fullscreen slider and found this little snippet:
jQuery(window).ready(function(){
  setTimeout(scX, 6000);
});

function scX() {
  hPos = jQuery("#hideMe").offset().top;
  hHeight = jQuery("#hideMe").height();
  jQuery("html, body").animate({scrollTop: +(hPos + hHeight)}, 1200);
}

All it does is scrolling down to the next section after 6 seconds.
Now my question: I want to disable the snippet if the user starts scrolling before the script auto scrolls to the next section.
I hope you can help me, best regards Julian.
Comment: Put the `setTimeout` in a variable which can then be cleared using `clearTimeout` when the user starts scrolling (the scroll event).
Answer: Try this.
jQuery(window).ready(function(){
  var abc = setTimeout(scX, 3000);
  $(window).scroll(function() {
    clearTimeout(abc);
    });
});


The program will compile but the table will not print out

Question: The program complies but I cannot get the results table to print out. The program is supposed to analyze a random table of 1's and 0's and print out  a table that counts the number is 1's in  sequence. The table size is generated by input created by the user. That works correctly but I can not get the results table to print.  I was thanking a different type of the random utility might work.
Now I just get a table full of zeros....
import java.util.Scanner;
import java.util.Random;

 public class Project1a {
    static int[][] results;
    static int[][] sample;

    static int goodData = 1;

    public static void main(String[] args) {   // main comes first (or last)
       scanInfo();
        analyzeTable();
       printTable(results);

    }

  public static void scanInfo()
     {
       Scanner input = new Scanner(System.in);
       System.out.println("Enter number of rows: ");
       int rows = input.nextInt();
       System.out.println("Enter number of columns: ");
       int columns = input.nextInt();
       Random randomNumbers = new Random();
       sample = new int[rows= randomNumbers.nextInt(50)][columns = randomNumbers.nextInt(50)];
       results = new int[rows][columns];

    }

    static void analyzeTable() {   // no argument.  static var sample is assumed
       int row=0;
       while (row < sample.length) {
          analyzeRow(row);
          row++;
       }
    }
    static void analyzeRow(int row) {   // assume sample is "global"
       int xCol = 0;
       int rCount = 0;
       while (xCol < sample[row].length) {
          rCount = analyzeCell(row,xCol);
          results[row][xCol] = rCount; // instead of print
          xCol++;
       }
    }
    static int analyzeCell(int row, int col) {
       int xCol = col;
       int runCount = 0;
       int rowLen = sample[row].length;
       int hereData = sample[row][xCol];
       while (hereData == goodData && xCol < rowLen) {
          runCount++;
          xCol++;
          if (xCol < rowLen) { hereData = sample[row][xCol];}
       }
       return runCount;
    }

   public static void printTable(int[][] aTable ) {
     for (int[] row : aTable) {

       printRow(row);
       System.out.println();
     }
   }
   public static void printRow(int[] aRow) {
     for (int cell  : aRow) {
       System.out.printf("%d ", cell);
     }
   }
 }

Answer: Your problem is this line.
sample = new int[rows= randomNumbers.nextInt(1)][columns = randomNumbers.nextInt(2)];

You see, nextInt(1) will always return 0, so you're setting rows to zero, and you end up with a couple of arrays with no rows at all.
From the Javadoc for nextInt -

public int nextInt(int n)
Returns a pseudorandom, uniformly
  distributed int value between 0 (inclusive) and the specified value
  (exclusive), drawn from this random number generator's sequence.


Prove that $\sum_{k=1}^{n}\sqrt{\frac{1}{\left(x_{k}+1\right)^{2}}+\frac{x_{k+1}^{2}}{\left(x_{k+1}+1\right)^{2}}}\ge\frac{n}{\sqrt{2}}$

Question: For all $x_{1},x_{2},...,x_{n}\ge0$, let $x_{n+1}=x_{1}$. Prove that
$$\sum_{k=1}^{n}\sqrt{\frac{1}{\left(x_{k}+1\right)^{2}}+\frac{x_{k+1}^{2}}{\left(x_{k+1}+1\right)^{2}}}\ge\frac{n}{\sqrt{2}}$$
Since this sequence is of the form $\sqrt{a}+\sqrt{b}+...$, I squared both sides to obtain $\sum_{\text{cyc}}^{ }a+2\sum_{\text{cyc}}^{ }ab$, and on substituting all of the terms under $\sum_{\text{cyc}}^{ }a$ appropriately and combining terms with a common denominator, I was able to get that $\sum_{\text{cyc}}^{ }a\ge\frac{n}{2}$.
$$\implies\sqrt{\sum_{\text{cyc}}^{ }a}\ge\sqrt{\frac{n}{2}}$$
However, I'm not able to proceed further. Could anyone help out?
Answer: I think that you can employ the Minkowski inequality and the Cauchy-Schwarz inequality to deal with your desire inequality.
Recall that the Minkowski inequality states that:
For any $a_{1},\ldots,a_{n},b_{1},\ldots,b_{n}$, we have
$$ \sum_{k=1}^{n}\sqrt{a_{k}^2+b_{k}^2}\geq \sqrt{(\sum_{k=1}^{n}a_{k})^2+(\sum_{k=1}^{n}b_{k})^2}$$
As a result, we have
$$ \sum_{k=1}^{n}\sqrt{\frac{1}{(x_k+1)^2}+\frac{x_{k+1}^{2}}{(x_{k+1}+1)^2}}\geq \sqrt{A^2+(n-A)^2}\geq \frac{n}{\sqrt{2}}, $$
where $A:=\sum_{k=1}^{n}\frac{1}{x_k+1}$, and the last inequality is due to the Cauchy-Schwarz ineqaulity.
Comment: Learned about the Minkowski inequality just now. Superb solution!


Criando uma fila encadeada com matriz de char dentro da scruct

Question: O problema que estou tendo é que preciso colocar dentro da struct uma qntd x de string de 281 character.
Onde um bloco pode ter 5, 10 ... ifinito de strings, eu pensei em fazer matriz, e até onde eu comecei deu certo, pórem quando comecei a imprimir os char que começou os erros.
Se tiver alguma forma até mais facil, agradeço se alguem poder ajudar, e sim ta cheio de gambiarras e até rendundancias.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct no{
    int qndtweet;

    struct no * prox;
    struct no * ant;
    char twe[][281];
}NO;

NO *inicio = NULL;
NO *fim = NULL;
int tam = 0;
int count = 0;
char tweet[281];

void adicionar(int qntd);
void digite();
void imprimir();

int main(){
    system("clear");
    int qntd=0, qntdt=0;
    printf("Digite a quantidade de tweets por bloco: ");
    scanf("%d", &qntd);
    getchar();
    printf("Digite a quantidade de tweets: ");
    scanf("%d", &qntdt);
    getchar();

    for(int i = 0; i < qntdt; i++){
        adicionar(qntd);
    }

    imprimir();
    printf("\n");
    return 0;
}

void adicionar(int qntd){
    if(qntd == 0){
        printf("Qntd == 0\n");
        return;
    }
    digite();

    if(tam == 0 || count == qntd){ // INICIALIZACAO DO BLOCO
        NO *novo =(NO*) malloc (sizeof(NO));

        novo->qndtweet = qntd;
        strcpy(novo->twe[0], tweet);
        novo->prox = NULL;
        novo->ant = NULL;

        if(inicio == NULL && fim == NULL){ //tam == 0 - lista vazia :D
            inicio = novo;
            fim = novo;
            tam++;
        }

        else if(inicio != NULL && fim != NULL){// no fim da lista
            fim->prox = novo;
            novo->ant = fim;
            fim = novo;
            tam++;
        }
        else{// no fim
            printf("insercao invalida! :/");
        }
        count = 0;
    }
    else if(count < qntd && tam != 0){ //Aqui add dentro do bloco que ja existe
        NO *aux = fim;
        strcpy(aux->twe[count], tweet);
    }
    else
        printf("insercao invalida! :/");
    count++;
}

void digite(){
    int lent;
    printf("Tweet: ");
    fgets(tweet, sizeof tweet, stdin);
    lent = strlen(tweet);
    if (tweet[lent - 1] == '\n') {
    /* nome completo, com ENTER incluido */
        tweet[--lent] = 0; // apagar o ENTER
    }
    else {
    /* ENTER e possivelmente outros caracteres ficaram no buffer */
    int ch;
    do
        ch = getchar();
    while (ch != '\n'); // limpa caracteres extra
    }
}

void imprimir(){
    NO *aux = inicio;
    int i;
    printf("\n*--------------------Imprimindo--------------------*\n");
    if(inicio == NULL){
        printf("Vazio!!\n");
    }else{

        printf("Tam: %d\n", tam);
        printf("Count: %d\n", count);
        printf("Qntd: %d\n", aux->qndtweet);

        do{
            printf("\n");
            for(i=0; i < tam ; i++){
                for(int j=0; j < aux->qndtweet; j++){
                    printf("Bloco[%d]\n        Tweet[%d]: %s \n",i+1, j, aux->twe[j]);
                    //if(i == tam-1 && aux->qndtweet - j == count)
                       // break;
                }
                aux = aux->prox;
            }
        } while(aux != NULL);
    }
    printf("*-------------------------------------------------*\n");
    free(aux);
}

Codico rodando com exemplo do erro
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Seu programa não está bom. Assim é frágil e vai dar um trabalho enorme para terminar.
Escreva em torno dos dados. A única estrutura que tem em seu código é de um suposto nó de uma lista. É pouco.
E nunca misture os dados com a estrutura da lista ou nunca vai poder usar sua lista em outro código ou outra lista nesse código. E toda a razão de escrever um programa é poder usar e reusar uma solução.
Seu dado é um tweet
Podia ser
typedef struct
{
    char txt[281];
} Tweet; // um tweet

Mas os tweets vem em blocos. Um bloco podia ser
    typedef struct
{
    int     N;  // quantos?
    Tweet** tweet;
}   Tweets; // o bloco

E deve dar certo, já que TODO programa em C tem uma estrutura dessas: o protótipo de main é algo como
    int main( int argc, char** argv);

E os Tweets vão numa lista ligada.O que é uma lista?
Podia ser
typedef struct
{
    size_t size;
    size_t limite;

    Node* ini;
    Node* fim;
} Lista;

Pois é: a lista é de nós. E cada nó aponta para um registro de dados. Que pode ser qualquer coisa.
typedef Tweets Dado;  // essa lista e de Tweets

E assim pode reusar as funções da lista.
E como seria um nó?
 typedef struct st_node
{
    struct st_node* ant;
    struct st_node* prox;
    Dado*           D;
} Node; // um no da lista, que aponta para um Dado

O simples: um nó aponta para um dado, para o próximo nó e para o nó anterior.
um esqueleto mais completo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char txt[281];
} Tweet; // um tweet

    typedef struct
{
    int     N;  // quantos?
    Tweet** tweet;
}   Tweets; // o bloco

typedef Tweets Dado;  // essa lista e de Tweets

typedef struct st_node
{
    struct st_node* ant;
    struct st_node* prox;
    Dado*           D;
} Node; // um no da lista, que aponta para um Dado

typedef struct
{
    size_t size;
    size_t limite;

    Node* ini;
    Node* fim;
} Lista;

Lista* l_apaga(Lista*);
Lista* l_cria(int);
int    l_insere(Dado*, Lista*);
int    l_mostra(Lista*, const char*);

Tweets* t_apaga(Tweets*);
Tweets* t_gera(int);
int     t_mostra(Tweets* twe);

int main(void) { return 0; };

Compare com o modo como escreveu e se não entender as diferenças quando der tempo posso aumentar o exemplo até um programa completo


Servlet(Jersey2), send error message from filter class in json form

Question:     ObjectMapper mapper = new ObjectMapper();
        String jsonInString = mapper.writeValueAsString(erresp);
        svltresp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        svltresp.setContentType("application/json");
        PrintWriter writer = svltresp.getWriter();
        writer.println(jsonInString);

i am not sure this is best or not but found the way.
I am working on a Jersey2 Application.
Here is my error model class
@XmlRootElement(name = "ErrorResponse")
public class ErrorResponse {
@XmlElement
private String errorInstanceId;

@XmlElement
private String errorCode;

@XmlElement
private String errorMessage;

@XmlElement
private String errorAdditionalDescription;

public String getErrorInstanceId() {
    return errorInstanceId;
}

public void setErrorInstanceId(String errorInstanceId) {
    this.errorInstanceId = errorInstanceId;
}

public String getErrorCode() {
    return errorCode;
}

public void setErrorCode(String errorCode) {
    this.errorCode = errorCode;
}

public String getErrorMessage() {
    return errorMessage;
}

public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
}

public String getErrorAdditionalDescription() {
    return errorAdditionalDescription;
}

public void setErrorAdditionalDescription(String errorAdditionalDescription) {
    this.errorAdditionalDescription = errorAdditionalDescription;
}

public ErrorResponse() {
}

public ErrorResponse(String errorInstanceId, String errorCode, String errorMessage, String errorAdditionalDetails) {
    this.errorInstanceId = errorInstanceId;
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
    this.errorAdditionalDescription = errorAdditionalDetails;
}

}
and i am sending error message in json
ErrorResponse errorResponse = new ErrorResponse(UUID.randomUUID().toString(), "error",
                "Failed", null);
        throw new WebApplicationException(Response.status(400).entity(errorResponse).build());

but the question i have is that,
when i write that source code in the servlet, it works fine, i can see the error in json format, However, when i write that in filter class, i only can see in normal apache html error page.
Could anyone explain what is going on here and suggest me any solution?
Thanks in advance
Comment: Try setting [this property](http://stackoverflow.com/a/36600434/2587435)
Comment: since i am not using JerseyConfig class(using web.xml), could you please explain where to put application.properties file and let my application read this ?
Comment: That's only for spring boot. If you are using web.xml, just set it as an `init-param` to your Jersey servlet. If you click the link to the javadoc of the ServleProperties, you should see the string value (`jersey.config.server.response.setStatusOverSendError`) you can use for the init-param name
Comment: ok i tried, and still only can see html error page not in json format.
Comment: and actually why i need to put that property param into servlet?? i want to implement it from filter class though?
Answer: When the exception is thrown from resource or servlet, based on the MIME media type in  @Produces, response will be produced accordingly.
If the exception is thrown from filters(outside resource), we should add media type explicitly to response object.
Response.ResponseBuilder response = Response.status(400).entity(errorResponse);
response = response.type(MediaType.APPLICATION_JSON);
throw new WebApplicationException(response.build());

Comment: i followed as what you said, however, still getting HTML page but i found a way, i added to the post


Specifying range criteria without the use of a structured table

Question: I am working on a table that holds the total amount for products sold or bought in the total column with a reference column that refers to the product id which the total points to.
I need to mark of those products for which the total amount (debit/received) calculates to 0 for each product reference.
For this, I am currently using structured table references to specify the range in my SUMIFS formula like this
<code>=ROUND(SUMIFS([Total],[Reference],[@Reference]),2)=0
</code>
Could you please help with how to do the same using the range instead of table references as in
<code>=ROUND(SUMIFS(AD:AD,AC:AC, ..............),2)=0
</code>
Please help me on how to write the formula in this case.
Comment: before u down vote a question please please please point out the reason for doing so. It might help us with modifying our question to get better answers
Answer: You need to enter this at a given row, say row 2:
<code>=ROUND(SUMIFS(AD:AD,AC:AC,AC2),2)=0
'                          ^^^ The row you type in
</code>
and then copy/paste in the cells below; the row number will automatically adjust for each row.


Answer format for ordinary differential equations

Question: My professor's worked example for solving a partial differential equation using variable splitting seems to choose the format of solutions for the ordinary differential equations at random. For example, splitting the 1D diffusion equation $\frac{\delta^2\rho}{\delta x^2} = \frac{1}{c}\frac{\delta \rho}{\delta t}$ into $\rho(x, t) = X(x)T(t)$ gave me the ODE $\frac{d^2 x}{dx^2} + kx^2 = 0$, which I solved as $X(x) = Ae^{ikx}+Be^{-ikx}$ (which is correct). My professor gave $X(x) = A\sin(kx) + B\cos(kx)$. I'm aware that these are equivalent, but why did she choose to answer using trig functions? We've been taught to solve ODEs using exponentials so it's not like the answer was just in that form, and the other ODE was answered using an exponential. I understand that it could make the rest of the problem easier to solve but is that even recognisable at that point in the working?
Comment: The expression for $X(x)$ is manifestly real, and in applications one often only wants real solutions.
Comment: In your solution, the coefficients $A,B$ are complex numbers; in your professor's, they are real. They both (should!) amount to the same solution, which can be verified with Euler's formula.
Comment: And also, the representation in terms of sines and cosines lends itself to apply boundary conditions.
Answer: A lot of this just comes from experience with a variety of results. There are ways to do this rigorously (via, e.g. variation of parameters and the Wronskian matrix), but one of the earliest results you encounter in ODEs is that the general solution to
$y'' + k^2 y = 0$
where $y$ is a real-valued function of $x$, is $y = A \cos kx + B \sin kx$.
You can do this just by identifying that the DE can also be written as $y'' = -k^2 y$, and noting that the sine and cosine functions both have the property that their second derivatives are the negative of the function itself.
As you noted, you can also write the general solution as $y = C e^{ikx} + D e^{-ikx}$, but you then have to do extra work to note that if $y$ is restricted to taking real values then there are restrictions on $C$ and $D$ (which are going to be complex numbers) to ensure that the imaginary parts of the expression cancel out.


Building a dashboard with fluent-ui in React and the cards and table appear at bottom of screen when they're not supposed to

Question: I am following a tutorial to build a dashboard using fluentui in React, and am going to customise it and change it afterwards. However I have followed the tutorial exactly and got no errors but for some reason the cards and table appear at bottom of screen, not looking like how they are styled and the table has no data in it.
My code is exactly the same as the tutorial found here: https://www.youtube.com/watch?v=P9s6dsdu_9c. I will post a screenshot below of how mine looks atm and all relevant code below that.

code:
App.js
import React from 'react';
import { BrowserRouter as Router} from 'react-router-dom';
import './App.css';
import 'office-ui-fabric-react/dist/css/fabric.css';

import Chart3 from './Components/Chart/Chart3';
import Jumbo from './Components/Jumbotron/Jumbotron';

import Footer from './Components/Footer/Footer';
import Header from './Components/Navbar/Navbar';
import Navigation from './Navigation/Navigation';
import CardsSection from './Components/Cards/Card';
import Table from './Components/Table/Table';

function App() {
  return (

          <Navigation />

            <CardsSection />

  );
}

export default App;

Navigation.js
import React from 'react';
import {Nav, initializeIcons} from '@fluentui/react';

const Links = [
    {
        links: [
            {
                name: 'Dashboard',
                url: '/',
                key: 'key1',
                iconProps: {
                    iconName: 'News',
                    styles: {
                        root: {
                            fontSize: 20,
                            color: '#106ebe'
                        }
                    }
                }
            },
            {
                name: 'Settings',
                url: '/',
                key: 'key2',
                iconProps: {
                    iconName: 'SwitcherStartEnd',
                    styles: {
                        root: {
                            fontSize: 20,
                            color: '#106ebe'
                        }
                    }
                }
            },
            {
                name: 'Charts',
                url: '/',
                key: 'key3',
                iconProps: {
                    iconName: 'StackedLineChart',
                    styles: {
                        root: {
                            fontSize: 20,
                            color: '#106ebe'
                        }
                    }
                }
            }
        ]
    }
]

//Styling for the navigation
const navigationStyles = {
    root: {
        height: '100vh',
        boxSizing: 'border-box',
        border: '1px solid',
        overFlowY: 'auto',
        paddingTop: '10vh'
    }
}

const Navigation = () => {
    initializeIcons(); //initalizing so we can see icons when we use them
    return (

    )
}

export default Navigation;

Card.js
import React from 'react';
import { Card } from '@uifabric/react-cards';
import { Text, initializeIcons} from '@fluentui/react';
import 'office-ui-fabric-react/dist/css/fabric.css';

const container = {
    display: 'flex',
    justifyContent: 'center',
    margin: '10vh 0'
}

const icon = {
    fontSize: 24,
    padding: 15,
    verticalAlign: 'middle',
    paddingLeft: 0,
    color: '#0078d4'
}

const styles = {
    cardStyles: {
        root: {
            backgroundColor: 'white',
            padding: 20,
            borderTop: '5px solid #0078d4',
            width: '90%',
            maxWidth: '90%',
            margin: 'auto'

        }
    },
    header: {
        root: {
            fontSize: 20,
            fontWeight: 'bold',
        }
    },
    amount: {
        root: {
            fontSize: 26,
            paddingBottom: 20,
            paddingTop: 30,
        }
    },
    amount: {
        root: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#0078d4'
        }
    }
}

const cards = [
    {
        title: 'current balance',
        amount: '21',
        icon: 'Money',
        percentage: '2.3',
    },
    {
        title: 'current expenses',
        amount: '215',
        icon: 'PaymrntCard',
        percentage: '2.3',
    },
    {
        title: 'current income',
        amount: '21',
        icon: 'Savings',
        percentage: '2.3',
    },
]

const CardsSection= () => {
    initializeIcons();//initailizing icons so can be used
    return (

            {cards.map((card) => (

                    <Card styles={styles.cardStyle}>
                        <Card.Section>
                            <Card.Item>
                                <i style={icon} className={`ms-Icon ms-Icon--${card.icon}`} aria-hidden="true">
                                <Text styles={styles.header}>{card.title}</Text>
                            </Card.Item>
                            <Card.Item>
                                <Text styles={styles.amount}>{card.amount}</Text>
                            </Card.Item>
                            <Card.Item>
                                <Text styles={styles.percentage}>{card.percentage}%</Text>
                            </Card.Item>
                        </Card.Section>
                    </Card>

            ))}

    )
}

export default CardsSection;

Table.js
import React from 'react';
import { DetailsList } from '@fluentui/react';
import { mergeStyleSets } from 'office-ui-fabric-react/lib/Styling';
import 'office-ui-fabric-react/dist/css/fabric.css';

const operations = [
    {
        from: '0000 0284 7529 304304',
        to: '0000 9876 9876 5678 4123',
        amount: '1.343',
        date: '20-05-2020'
    },
    {
        from: '0000 0284 7529 304304',
        to: '0000 9876 9876 5678 4123',
        amount: '1.343',
        date: '20-05-2020'
    },
    {
        from: '0000 0284 7529 304304',
        to: '0000 9876 9876 5678 4123',
        amount: '1.343',
        date: '20-05-2020'
    },
    {
        from: '0000 0284 7529 304304',
        to: '0000 9876 9876 5678 4123',
        amount: '1.343',
        date: '20-05-2020'
    },
    {
        from: '0000 0284 7529 304304',
        to: '0000 9876 9876 5678 4123',
        amount: '1.343',
        date: '20-05-2020'
    }
]

const columns = [
    { key: 'column1', name: 'From', fieldName:'From', minWidth: 100, maxWidth: 300, isResizable: true },
    { key: 'column2', name: 'To', fieldName:'To', minWidth: 100, maxWidth: 300, isResizable: true },
    { key: 'column3', name: 'Amount', fieldName:'Amount', minWidth: 100, maxWidth: 300, isResizable: true },
    { key: 'column4', name: 'Date', fieldName:'Date', minWidth: 100, maxWidth: 300, isResizable: true },
]
const classNames = mergeStyleSets({
    teble: {
        margin: 'auto'
    }
});;
const Table = () => {
    return (

            <div className={`s-Grid-col ms-sm9 ms-xl9 ${classNames.table}`}>
                <DetailsList
                items={operations}
                columns={columns}
                selectionMode={0}
                />

    )
}

export default Table

Answer: In Table.js, there is a typo in the className. It has to be ms-Grid-col and not s-Grid-col


Why the sum of this following function is the linear function?

Question: At the binomial point process of 2-D, there is the fallowing the distance PDF between a point and n-th nearest points from the point.
$f_{R_n}(r)=2/R\times B(n+1/2,N-n+1)/B(N-n+1,n) \times \beta(r^2/R^2;n+1/2,N-n+1)$
where $β(x; a,b)$ is the beta density function. $B(a,b)$ is the beta function.
$N$ is the total number of points and $R$ is the point distribution range.
I add all these functions as follows.
$\sum_{n=1}^{N} f_{R_n}(r)$
So, the $\sum_{n=1}^{N} f_{R_n}(r)$ for $0<r<R$ is the same as the Linear function $f(r)=2 N/R^2\times r$.
I don't know why.
Comment: Could you define better or provide a link for what you mean by binomial point proess of $2D$?
Comment: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.313.2143&rep=rep1&type=pdf
This paper illustrates the binomial point process of 2D well.
Answer: By your link, $R_n$ is the distance to the origin of the $n$-th nearest point from the origin. Notice that
\begin{align*}
f_{R_n} (r)
&= \frac{d}{dr} \ P[\textrm{dist}(0, \text{$n$-th nearest neighbor}) \le r] \\
&= \frac{d}{dr} \ P[\Phi(B(r)) \geq n].
\end{align*}
Here, I am using the notation from the paper you linked, in which $\Phi(V)$ is the random variable that counts the number of points that are on $V$. Summing on $n$, we get
\begin{align*}
\sum_{n=1}^N f_{R_n} (r)
&= \frac{d}{dr} \ \left( \sum_{n=1}^N P[\Phi(B(r)) \geq n] \right) \\
&= \frac{d}{dr} \ E[\Phi(B(r))] \\
&= \frac{d}{dr} \ \left( N \cdot \frac{\pi r^2}{\pi R^2} \right) \\
&= \frac{2Nr}{R^2}.
\end{align*}
In the third equality, we used that each point has independently probability $\textrm{Volume}(B(r)) / \textrm{Volume}(B(R))$ of landing inside $B(r)$.


Apache 500 Error when proxying api subdirectory

Question: I am trying to redirect PUT request for a specific endpoint to another host.
The said endpoint resides under /internal and accepts only PUT requests.
The other endpoints under /internal will continue to be served by my main host/server.
I have tried setting it up using both rewrite rules and using the proxy ([P]) flag and using the ProxyPass directive - all resulting in a 500 Internal Server Error and the request never makes it to the new host
My client application uses a simple REST client that cannot handle redirects, so I have to use some kind of proxying.
Apache logs show the following
[Thu Feb 10 08:56:20.394444 2022] [rewrite:trace1] [pid 8579] mod_rewrite.c(480): [client XXX.XXX.XXX.XXX:XXXXX] XXX.XXX.XXX.XXX - - [subdomain1.mydomain.com/sid#55d4ed07ecb0][rid#55d4ed2c5f20/initial] go-ahead with proxy request proxy: https://subdomain2.mydomain.com/internal/my-endpoint [OK]

Here's the current configuration for the specific vhost
<VirtualHost *:80>
 ServerName subdomain1.mydomain.com
  ProxyPass /soap ajp://localhost:7007/soap retry=3
  ProxyPreserveHost On
  Redirect /  https://subdomain1.mydomain.com/
  ErrorLog /var/log/httpd/subdomain1_error
</VirtualHost>

<VirtualHost *:443>
  ServerName subdomain1.mydomain.com
  Options FollowSymlinks
  ProxyRequests On
  ProxyPreserveHost On
  #RewriteEngine On

  #RewriteCond %{REQUEST_URI} '^/internal/my-endpoint'
  #RewriteCond %{REQUEST_METHOD} ^(PUT)
  #RewriteRule "^/(.*)" "https://subdomain2.mydomain.com/internal/my-endpoint" [P]

  ProxyPass /internal/my-endpoint https://subdomain2.mydomain.com/internal/my-endpoint
  ProxyPassReverse /internal/my-endpoint https://subdomain2.mydomain.com/internal/my-endpoint
  ProxyPreserveHost On

  LogLevel alert rewrite:trace3
  CustomLog /var/log/httpd/subdomain1_access_log common
  ProxyPass / ajp://localhost:7007/ retry=3
  ProxyPassReverse / ajp://localhost:7007/ retry=3
  ProxyPreserveHost Off
  ErrorLog /var/log/httpd/subdomain1
  SSLEngine on
</VirtualHost>

Answer: Ok- after enabling the debug in the apache logs it turns out the issue was related to the SSL certificates as the proxying was to a server which was accepting HTTPS connections only
Had to update the apache configuration to the one below to make it work
<VirtualHost *:80>
 ServerName subdomain1.mydomain.com
  ProxyPass /soap ajp://localhost:7007/soap retry=3
  ProxyPreserveHost On
  Redirect /  https://subdomain1.mydomain.com/
  ErrorLog /var/log/httpd/subdomain1_error
</VirtualHost>

<VirtualHost *:443>
  ServerName subdomain1.mydomain.com
  Options FollowSymlinks
  ProxyRequests Off
  ProxyErrorOverride off
  ProxyPreserveHost On
######
  SSLEngine on
  SSLProxyEngine on
######

  ProxyPass /internal/my-endpoint https://subdomain2.mydomain.com/internal/my-endpoint
  ProxyPassReverse /internal/my-endpoint https://subdomain2.mydomain.com/internal/my-endpoint

  LogLevel alert rewrite:trace3
  CustomLog /var/log/httpd/subdomain1_access_log common
  ProxyPass / ajp://localhost:7007/ retry=3
  ProxyPassReverse / ajp://localhost:7007/ retry=3
  ProxyPreserveHost Off
  ErrorLog /var/log/httpd/subdomain1
  SSLEngine on
</VirtualHost>


Why are baseline hazard functions after Cox PH regression different in Stata and R

Question: I am a Stata user now teaching myself R. I have been trying to recapitulate analyses done in Stata using R but have got stuck. A multi-variable Cox regression with an offset in Stata and R give identical results
The data can be downloaded from
https://www.dropbox.com/s/r26sgzjy3rytw3r/test.csv?dl=0
Stata code
stset fu, failure(br)
stcox ag1 ag2 sz nd grade screen , offset(hc1) nohr

R-code
    library(survival)
    fit <- Surv(er1$fu, er1$br)
    mva <- coxph(fit ~ ag1 + ag2 + sz + nd + grade + screen +
                offset(hc1), data = er1)
However when I then derive the cumulative baseline hazard functions they are different.  This does not occur if I remove the offset term.
Stata code
predict h0, basechazard
twoway scatter h0 _t

R-code
h0 <- basehaz(mva, centered = F)
ggplot(data=h00, aes(x=time, y=hazard)) + geom_point()

Comment: You posted this at https://stackoverflow.com/questions/47021000/why-the-estimate-of-the-cumulative-baseline-hazard-after-cox-ph-in-stata-differs  and got the good advice to try here. Fine, but https://stats.stackexchange.com/help/on-topic explains that cross-posting is not encouraged on SE. So, the implication is that you should post at just one site at once (and delete the post at the other). In either forum, the lack of a reproducible example is problematic, as we can't see your data. Experts in survival analysis (not me) may be able to help without it.
Comment: This question is quite interesting, I did some experiments, it is true, when there are no offset variables, the baseline cumulative hazards are the same for STATA and R (using same methods to handle ties), when there are the offset varialbes, the  baseline cumulative hazards are quite different from the two software.
Comment: @NickCox Thank you. I had not realised cross-posting was frowned upon.  I am not sure how to add the data file on which the analysis is based.
Comment: In this particular case, a reproducible example should be possible, I imagine, with a simpler dataset invented for the purpose. The bigger deal is someone seeing this who understands exactly how offsets are handled in both programs, not me, and so far no takers.
Answer: This is an old question, but in case someone ends up here looking for the answer:
By default, survival::coxph demeans any non-binary covariates (and any offsets, regardless of their measurement level), to make any baseline cumulative hazard/survivor estimates from survival::survfit more stable.  (survival::basehaz is a wrapper for survival::survfit.)  By contrast, Stata's stcox does not demean its covariates.
Demeaning doesn't affect the coefficient estimates.  That's why R's and Stata's Cox model output still matches, provided you use the same tie correction method.  Stata's default (breslow) is not R's default (efron).
For more on coxph's demeaning behavior, see the second paragraph under the "Details" section of coxph's help file (survival 3.3-1).  See also the nocenter option in that help file, which affects only covariates, not offsets.
MWE
Stata
// (picking female as offset, arbitrarily)
* not demeaned
webuse catheter, clear
stcox age, offset(female) efron
predict double H0, basec            // WON'T MATCH R

* demeaned
foreach x of varlist age female{
    sum `x' if(e(sample)==1)
    gen double `x'_dem = `x' - `r(mean)'
}
stcox age_dem, offset(female_dem) efron
predict double H0_dem, basec        // WILL MATCH R

* print the quantities
bysort _t: gen flag = _n==1
list _t H0* if(flag==1), noobs

    ** (INSERTED THE OUTPUT)
    +-----------------------------+
    |  _t          H0      H0_dem |
    |-----------------------------|
    |   2   .00442489   .01208141 |
    |   4   .00442489   .01208141 |
    |   5   .00442489   .01208141 |
    |   6   .00442489   .01208141 |
    |   7   .01390727   .03797142 |
    |-----------------------------|
    |   8    .0236089   .06446007 |
    |   9   .02865578   .07823973 |
    |  12   .03885037    .1060743 |
    |  13   .04399411    .1201184 |
    |  15   .05477359   .14954993 |
    |-----------------------------|
    |  16   .06027266   .16456422 |
    |  17   .06591772   .17997709 |
    |  22   .07160917   .19551662 |
    |  23   .07746653   .21150915 |
    |  24   .08345176   .22785078 |
    |-----------------------------|
    |  25   .08967049   .24482998 |
    |  26   .09606417   .26228683 |
    |  27   .10261635   .28017644 |
    |  28    .1093372   .29852657 |
    |  30   .13734608   .37500003 |
    |-----------------------------|
    |  33   .14474793   .39520951 |
    |  34   .15235003   .41596575 |
    |  38   .16017444   .43732899 |
    |  39   .16821064   .45927044 |
    |  40    .1764812    .4818518 |
    |-----------------------------|
    |  43   .18484174   .50467883 |
    |  46   .18484174   .50467883 |
    |  53   .19374013   .52897436 |
    |  54   .19374013   .52897436 |
    |  58   .20328969   .55504782 |
    |-----------------------------|
    |  63   .21320181   .58211117 |
    |  66   .22325786    .6095675 |
    |  70   .22325786    .6095675 |
    |  78   .23413436   .63926391 |
    |  96   .24547173   .67021867 |
    |-----------------------------|
    | 108   .24547173   .67021867 |
    | 113   .24547173   .67021867 |
    | 114   .25838971   .70548901 |
    | 119   .27192819   .74245352 |
    | 130   .28606182   .78104298 |
    |-----------------------------|
    | 132   .30099395   .82181262 |
    | 141   .31659951   .86442093 |
    | 149   .31659951   .86442093 |
    | 152   .35238347   .96212294 |
    | 154   .37160181   1.0145953 |
    |-----------------------------|
    | 156   .39134013   1.0684874 |
    | 159   .39134013   1.0684874 |
    | 177   .41406096   1.1305228 |
    | 185   .43900652   1.1986324 |
    | 190   .46665975   1.2741348 |
    |-----------------------------|
    | 196   .49734176   1.3579068 |
    | 201   .53249754   1.4538937 |
    | 245    .5731822   1.5649762 |
    | 292   .61953858   1.6915444 |
    | 318   .67502001    1.843027 |
    |-----------------------------|
    | 402   .74292041   2.0284174 |
    | 447   .83017281   2.2666452 |
    | 511   .95265565   2.6010637 |
    | 536   1.1827563   3.2293142 |
    | 562   1.9349645   5.2830905 |
    +-----------------------------+

R
library(survival)  # 3.3-1
library(broom)     # 1.0.0

# Load data
cath <- haven::read_dta("https://www.stata-press.com/data/r17/catheter.dta")

# Est model
mod <- coxph(Surv(`_t0`, `_t`, `_d`) ~ age + offset(female), data=cath)

# Get H0
sf.mod <- survfit(mod)

# Get into df for easy viewing
sf.mod.df <- tidy(sf.mod)
sf.mod.df$estimate <- sf.mod$cumhaz

# Print
print(as.data.frame(sf.mod.df[,c("time","estimate")]),
      digits=7,
      row.names=FALSE)

## (INSERTED THE OUTPUT)
time   estimate
   2 0.01208141
   4 0.01208141
   5 0.01208141
   6 0.01208141
   7 0.03797142
   8 0.06446007
   9 0.07823973
  12 0.10607430
  13 0.12011840
  15 0.14954993
  16 0.16456422
  17 0.17997709
  22 0.19551662
  23 0.21150915
  24 0.22785078
  25 0.24482998
  26 0.26228683
  27 0.28017644
  28 0.29852657
  30 0.37500003
  33 0.39520951
  34 0.41596575
  38 0.43732899
  39 0.45927044
  40 0.48185180
  43 0.50467883
  46 0.50467883
  53 0.52897436
  54 0.52897436
  58 0.55504782
  63 0.58211117
  66 0.60956750
  70 0.60956750
  78 0.63926391
  96 0.67021867
 108 0.67021867
 113 0.67021867
 114 0.70548901
 119 0.74245352
 130 0.78104298
 132 0.82181262
 141 0.86442093
 149 0.86442093
 152 0.96212294
 154 1.01459533
 156 1.06848744
 159 1.06848744
 177 1.13052280
 185 1.19863239
 190 1.27413483
 196 1.35790683
 201 1.45389369
 245 1.56497621
 292 1.69154439
 318 1.84302697
 402 2.02841741
 447 2.26664521
 511 2.60106372
 536 3.22931416
 562 5.28309054


Find a unit vector that maximizes the directional derivative at a point

Question: Given the function
$f(x,y)=g(2x+y), g'(3)=3$
Find the coordinates of a unit vector $v=(v_1,v_2)$ that finds the maximum directional derivative $D_ uf(1,1)$ of f in the point $(1,1)$.
I know that I should find $\nabla f(x,y)*u$ in such a way that u maximizes it. But I am uncertain how to do so.
Comment: Hint: the directional derivative is maximized by selecting a vector parallel to the gradient
Comment: I found the gradient $f(1,1)=(6,3)$ Would dividing the gradient at the point over the length of the gradient at the point equal the max?
Answer: note that the partial derivatives of $f(x,y)$ are:
$$
f_x=g' \frac{\partial}{\partial x}(2x+y)=2g' \qquad f_y=g' \frac{\partial}{\partial y}(2x+y)=g'
$$
so the gradient at $(1,1)$ is:
$$
\nabla f(x,y)= (2g'(3),g'(3))^T=(6,3)^T
$$
and, as noted in the comment, the directional derivative is maximized for a vector parallel to the gradient.
Comment: Yes....sorry. and thank you :)
Answer: We have given $y=g(t),\, \dfrac{dg}{dt}=g^\prime(t),\, g^\prime(3)=3,\,t=2x+y,\,f(x,y)=g(2x+y)$
Therefore, by the chain rule, $f_x(x,y)=\dfrac{dg}{dt}\cdot\dfrac{\partial t}{\partial x}=2g^\prime(t)$ and $f_y(x,y)=\dfrac{dg}{dt}\cdot\dfrac{\partial t}{\partial y}=g^\prime(t)$.
So $\nabla f(1,1)=\langle2,1\rangle g^\prime(t)=\langle2,1\rangle g^\prime(3)=\langle6,3\rangle$
$\vert \nabla f(1,1)\vert=3\sqrt{5}$, therefore $u=\dfrac{\nabla f(1,1)}{\vert \nabla f(1,1)\vert}=\left\langle \dfrac{2\sqrt{5}}{5},\dfrac{\sqrt{5}}{5}\right\rangle$.
Comment: Thank you. I believe I understand. Can you confirmed if this other example is correct.

Given $f(x,y)=g(4x+3y), g'(10)=-1$. The directional derivative at the point $(1,2)$ is $(-4,-6)$? And the max directional derivative would be $(-2sqrt(13)/13, -3sqrt(13)/13)$
Comment: The $(-4,-6)$ should be $\langle-4,-3\rangle$ since $f_x(x,y)=4g^\prime(t)$ and $f_y(x,y)=3g^\prime(t)$ with $t=4x+3y$. So $\nabla f=\langle4,3\rangle g^\prime(t)$. Thus, $\nabla(1,2)=\langle4,3\rangle g^\prime(10)=\langle-4,-3\rangle$. So $u=\langle-\frac{4}{5},-\frac{3}{5}\rangle$.


DataTableReader.NextResult() causes false results from HasRows()

Question: I have a generic exe that use to create files based on a SqlDataReader.  There could be more than one recordset within this reader.  There are also extended libs that can be added to run more complex data queries, but would return a SqlDataReader.  I recently had to change, because of the extended libs that run off the SqlDataReader can't write to SQL anymore to build it's table from multiple data sources.   So now those libs create a internal DataTableReader, which could have 1 or more recordsets, just currently they have only one.
My problem is, I found once I switched over to DataTableReaders within my generic EXE, that when I call .NextResult() to get the next recordset, then call if(reader.HasRows()) to verify if a recordset exists, it always returns true, even when there is only one recordset.
Is there something I have to do when creating the DataTableReader to ensure the HasRows returns the correct results?
I've tried two different ways when creating the DataTableReader.
1: dataTable.CreateDataReader();
2: new DataTableReader(new DataTable[] { dataTable });

Both cases still return true on HasRows after a .NextResult() method is called.
Answer: Don't use "HasRows" to check if next recordset exists. Verify what is returned by actual call to DataTableReader.NextResult(). If it's False then no next recordset exists.
Check out basic sample in MSDN docs.
Comment: Yea, I guess I was playing lazy with SqlDataReaders, because HasRows does return the expected results.  Thanks,
Answer: Hello for me it's normal that HasRows return true because you actually have one record in your table. If you want to know if there is no more record in youe reader you should put your reading code in while (yourReader.read()) then do you reading code in the while loop
Comment: That was already being done, this is after the fact.  Thanks though.


Deezer API - Pegando valores do Json e PHP

Question: Estou tentando pegar algumas informações da API, consegui filtrar algumas coisas, mas por exemplo, estou tentando chegar no link 'preview' para tocar 30 segundos de música e não consigo chegar, fiz isso até agora :
<?php

$url = 'https://api.deezer.com/2.0/search?q=Alok';
$jsonStr = file_get_contents($url);
$jsonArr = json_decode($jsonStr, true);

$album = array();

foreach ($jsonArr['data'] as $row) {
    $album[] = $row['album'];//['cover_xl'];

}

echo '
'.print_r($album, true).'
';

?>

Answer: Consegui, na verdade, o acesso é direto.
foreach ($jsonArr['data'] as $row) {
    $album[] = $row['preview'];//['cover_xl'];

}


RewriteRule a working URI to a new format

Question: I am formatting the redirect of my site URL using this. I got a problem on redirecting properly.
browser link is like that :
http://www.exampledomain.com/1234/user

my project need it to be like that :
http://www.exampledomain.com/index.php?id=1234&username=user

but i don't know how to do that .
RewriteRule ^/?([-a-zA-Z0-9_+]+)$ index.php?id=$1

Answer: Try this...
RewriteEngine on
RewriteBase /

RewriteRule ^/?([-a-zA-Z0-9_+]+)/?([-a-zA-Z0-9_+]+)/?$ /index.php?id=$1&username=$2

sory:
new correction  without / before index.php
RewriteRule ^/?([-a-zA-Z0-9_+]+)/?([-a-zA-Z0-9_+]+)/?$ index.php?id=$1&username=$2 [L]

and if your base url is  www.domanin.com/folder1/folder2  then  this line will be:
RewriteBase /folder1/folder2

Comment: I added your code in .htaccess and restart my httpd but when i request url /1234/user i get 404 not found . should i do any others to get it work ?
Comment: what is your base url?
Comment: sorry you try this. RewriteRule ^/?([-a-zA-Z0-9_+]+)/?([-a-zA-Z0-9_+]+)/?$ index.php?id=$1&username=$2
Comment: it works with the first answer perfect just i add [L] at the end of line , thank you so much Ahosan


Small tweak to get this regex to get it to do what I want

Question: I wrote a coldfusion regex to match times of day in the source code of a page in which they appear scattered throughout the page like this:
10.30 stuff 10.45-11.15 other stuff 17.00

I want the matches to be "10.30" "10.45-11.15" and "17.00".
Instead, I am getting "10.30" "10.45" "11.15" and "17.00".
I have tried:
rematch("(\b[0-2][0-9]\.[0-5][0-9]\b)|(\b[0-2][0-9]\.[0-5][0-9]-[0-2][0-9]\.[0-5][0-9]\b)",mystring)

Thank you for correcting my error! Surely something to do with the little b's and the hyphen.
Comment: Change the order, do the hyphenated first. You also can do it all in one capture group, https://regex101.com/r/udlyAS/2.
Answer: You can just make the part of the pattern that matches the second part of the range optional with the help of an optional non-capturing group (?:...)? and note that your regex also matches up to 29 hours that can also be corrected.
Use
\b(?:2[0-3]|[0-1][0-9])\.[0-5][0-9](?:-(?:2[0-3]|[0-1][0-9])\.[0-5][0-9])?\b

See the regex demo
Details:

\b - leading word boundary
(?:2[0-3]|[0-1][0-9]) - either 2 followed with a digit from 0 to 3 or 0 / 1 followed with any digit (=hour)
\. -  a literal dot
[0-5][0-9] - a digit from 0 to 5 followed with any digit (=minute)
(?:-(?:2[0-3]|[0-1][0-9])\.[0-5][0-9])? - an optional non-capturing group matching a - and then the same pattern described above followed with...
\b - a trailing word boundary.
Comment: Th*nks, Wiktor. (I'm not supposed to write "thanks" in this box.) I tried your solution first and it worked perfectly. Gave Mr. Twoyears the green check mark because his solution is short and sweet!
But where am I supposed to say "thank you" if not in this box?
Comment: @user1781623 You can use the arrow next to the answer here. The `up vote` is kind of a way to thank a user. http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow
Answer: I don't think you need the 'or', just make the range optional as follows:
\b[0-2]\d\.[0-5]\d(-[0-2]\d\.[0-5]\d)?\b

Here is the JavaScript equivalent snippet:

var re = /\b[0-2]\d\.[0-5]\d(-[0-2]\d\.[0-5]\d)?\b/g;
var s = "10.30 stuff 10.45-11.15 other stuff 17.00";

console.log(s.match(re));


Can a standard JPEG file format be abused to create lossless or uncompressed files?

Question: I am aware that producing JPEG files results in lossy compression, and that there is a lossless JPEG format, but I actually wonder if the standard JPEG format can be "hacked" in a certain way that allows it to store uncompressed pixels.
One seemingly possible way I have found is decreasing the MCU size from 8x8 to 1x1. If the format itself allowed such a change, would the color information remain unchanged for the whole image, or would the compression algorithm still mess with it?
Comment: You're free to disable color subsampling (4:4:4) and use quantization tables of all 1's, but there will still be some modification to the pixel values due to limited precision of the DCT and potential colorspace conversions. This will generate huge files and basically defeat the purpose of JPEG compression. Is this what you're after?
Comment: @BitBank So, basically, if the color space of the source bitmap matched the DCT precision, the image can be stored in this way without any loss? I suppose the coversion to Y′CBCR can be turned off. And yes, this is what I am looking for. Just a curiosity.
Comment: There is Lossless JPEG 2000 (.jp2) https://en.wikipedia.org/wiki/Lossless_JPEG Paint.net can save to this format. However it's not basic jpg if that is what your meant by 'standard'.
Comment: @borisdj As I said, I know this exists and it is not what I mean by "standard".
Answer: No matter what you do you are going to get some attempt at compression and some loss in "standard" jpeg. The would be the case even if you set all your quantization tables to {1, 1, ....} and did not subsample.
You are going to get "loss" during the RGB => YCbCr transformation. You get going to get additional loss in the DCT.
Comment: It seems the RGB => YCbCr conversion can be skipped. If so, can you elaborate on the nature of the loss in the DCT? Does it affect only individual pixels, i.e. does it limit the number of colors, for example?
Comment: In both cases, you do floating point arithmetic and store the result in integer values.For the YCbcr conversion, you also have the problem that there is not a 1:1 mapping of the colorspaces.


Python calling mutiple URLs and pulling data from them

Question: I'm trying to write a script that will call up a webpage (http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Tree&id=7742&lvl=3&lin=f&keep=1&srchmode=1&unlock), scan it, and then pull out the orders, families, genera, and species within each nested taxonomic group. However, I only want the vertebrates (a very small section of the entire website) but the URLs associated with the various vertebrate taxa are not in any discernible pattern (i.e. sequential). Is there a way to do this reasonable? I've been having a lot of problems trying to formulate different ways to accomplish this goal.
Comment: This is called **web-scraping** and there are many prior Q&A on this (500 alone of them tagged Python). In Python, _twill_ is a useability layer which sits on top of _mechanize_ (for the automation); and _BeautifulSoup_ for the actual scraping.
Comment: [twill](http://twill.idyll.org/commands.html) specifically makes following links easier than plain mechanize, specifically its [follow](http://twill.idyll.org/commands.html) command works by link title (rather than URL). If this doesn't solve your question, show us some sample html snippet of these links?
Answer: It isn't very clear (at least, to me) what do you exactly want to do, but, for what I understood, you need to create some sort of crawler that looks for links in the pages, navigate the site and categorize them?
If so, go for mechanize, that allows you to emulate a web browser, and navigate along the site, easily extracting and following links, submitting forms, etc. etc.


How would I make a simple encryption/decryption program?

Question: I'd like to know (just as the question says) how to make a simple encryption and decryption program.
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
I'd like the latter section to be what the letters of the alphabet are encrypted to and if the user chooses the decrypt it, I'd like it to be reversed or reverted back into the alphabet form.
Is this too complicated because from the examples I've looked over, all they seem to do is shift the alphabet 3 or 4 spaces and use that as their encryption code.
Comment: Is there a webpage or something where I can read over about that?
Comment: You could also just convert each letter to its corresponding number in the alphabet minus one and that's the index of the encryption/decryption string.
Answer: Use two dicts to do the mapping, one from letters to encryption_code and the reverse to decrypt:
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'

enc = dict(zip(letters,encryption_code))

dec = dict(zip(encryption_code, letters))

s = "HELLO WORLD"

encr = "".join([enc.get(ch, ch) for ch in s])
decr = "".join([dec.get(ch, ch) for ch in encr])

print(encr)
print(decr)

Output:
IAMMP EPCMO
HELLO WORLD

Using your method your input will have to be uppercase and the user is restricted to A-Z for the letters to be encrypted, if you want to allow other characters just add the mapping to the dicts.
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
enc = dict(zip(letters,encryption_code))

dec = dict(zip(encryption_code, letters))

s = "HELLO world"

encr = "".join([enc.get(ch, ch) for ch in s])
decr = "".join([dec.get(ch, ch) for ch in encr])

print(encr)
print(decr)

Output:
IAMMP epcmo
HELLO world

Any characters not in letters will be the same in encr and decr i.e:
 s = "HELLO world!#}%"
 IAMMP epcmo!#}% # encr
 HELLO world!#}% # decr

Comment: Thank you, it works perfectly now!
Comment: No prob, you're welcome.
Answer: you create an encoder and a decoder:
enc = str.maketrans(letters, encryption_code)
dec = str.maketrans(encryption_code, letters)

and use them:
encr = 'HELLO WORLD'.translate(enc)
decr = encr.translate(dec)


Why is RAM Disk so much faster than an SSD drive?

Question: Why is RAM Disk so much faster than an SSD drive?
Comment: The same reason flying a jet is faster than walking from New York to Los Angeles. They're completely different technologies.
Answer: It has to do with a number of factors.  Bandwidth to memory vs SSD, also write latency speeds, DRAM is constantly refreshed and thus has a latency measured in nanoseconds, whereas Flash requires a high voltage to write into the gate along with a few other details, often SSD latency is measured in microseconds.
http://en.wikipedia.org/wiki/Solid-state_drive
Comment: Great answer, so just suggesting an addition: an SSD has to pass through a storage controller, whereas modern chips have on-die MMUs, so (as a simple way to explain it, I know it's not a perfect analogy), RAM is "closer" to the CPU.  Also, depending on what FS you're using, something like tmpfs writes marginally less data to the storage medium than does (f.ex.) ext3, since it's worried about crash recovery and is not journaling.


An identity about Bessel functions

Question: How can I  prove
$\frac { 2n}{\rho}J_n (\rho)=J_{n-1}(\rho)+J_{n+1}(\rho)$
?
When $J_n$ is n'th order Bessel function.
I tried a lot, but I don't know how to construct  $"n"$ in the LHS.
Is there any hint?
Thanks for your help.
Answer: Bessel functions appear in a particular generating function :
$$ \exp\left(\frac{\rho}{2}\left(t-\frac{1}{t}\right)\right)=\sum_{n\in\mathbb{Z}} J_n(\rho)\,t^n. \tag{1}$$
By differentiating both sides of the previous identity with respect to $t$ we get:
$$ \frac{\rho}{2}\left(1+\frac{1}{t^2}\right)\exp\left(\frac{\rho}{2}\left(t-\frac{1}{t}\right)\right) = \sum_{n\in\mathbb{Z}} J_n(\rho)\, n t^{n-1}\tag{2} $$
hence:
$$ \frac{\rho}{2}\left(t+\frac{1}{t}\right)\sum_{n\in\mathbb{Z}}J_n(\rho)\, t^n = \sum_{n\in\mathbb{Z}} J_n(\rho)\, n t^n\tag{3} $$
and by equating the coefficients of $t^n$ in the LHS and RHS of $(3)$ your identity follows.

An identity about Bessel functions


Como fazer esta requisição

Question: tenho este endepoint:
@GET("b1s/v1/ServiceCalls?\$filter")
@Headers("Prefer:odata.maxpagesize=1000")
fun getService(@Header("Cookie")token: String,
               @Query("TechnicianCode")TechnicianCode: Int,
               @Query("Status") codigo: Int): Call<ServicesValue>

estou usando o retrofit, desta forma a minha url esta ficando assim:
https://XXXXXXXXXX/b1s/v1/ServiceCalls?$filter=TechnicianCode = 201 & Status = -3

mas a api que estou fazendo a requisição do aceita desta forma:
https://XXXXXXXXX/b1s/v1/ServiceCalls?$filter=TechnicianCode eq 201 and Status eq -3

como consigo subtituir o sinal de '=' por 'eq', porque o @Query adiciona '=' automático?
Answer: Acredito que o Retrofit não suporte tal configuração a cerca do caractere "=" do @Query, pois o mesmo representa um query parameter conforme a spec do HTTP. É por isso que o Retrofit adiciona o "=" automático, respondendo a tua pergunta.
O mais adequado, no seu caso, acredito ser criar um @Query com nome $filter e criar o valor que será passado ao parâmetro fora do Retrofit, numa implementação própria.
Exemplo:
@GET("b1s/v1/ServiceCalls")
@Headers("Prefer:odata.maxpagesize=1000")
fun getService(@Header("Cookie") token: String,
               @Query("$filter") filter: String): Call<ServicesValue>

fun makeFilter(technicianCode: Int, status: int) =
    "TechnicianCode eq $technicianCode and Status eq $status"

Uso:
val filter = makeFilter(201, -3) // TechnicianCode eq 201 and Status eq -3
retrofitService.getService(token, filter)

Comment: Obrigado assim deu certo e esclareceu minhas duvidas.

Como fazer esta requisição


Sum of weight of edges of each vertex of a $4$ regular graph can be made $0$.

Question: Suppose we have $4$ regular graph $G$. We have to show that each edge can be labelled with $-1$ or $1$ such that the total flow in a vertex is $0$.
There is also a question related to it:
To find an example of a $6$ regular graph where this type of edge labelling is not possible.

I am finding it difficult to prove the fact. I tried the method of contradiction.
I also thought of rephrasing the problem: In any $4$ regular graph, the edges can be given direction such that the in-degree and out-degree are the same for each vertex.
Can someone provide some hints on how to proceed?
Answer: Wlog we can assume the graph is connected.
Notice that the number of edges is, by handshake lemma, even.
This graph is Eulerian since each node has even degree. So we have Euler cycle $E$ in it. Let start at node $v$ and label ecah edge on $E$ alternatively with $1$ and $-1$ on this cycle starting with $+1$ at $v$.
Clearly this procedure gives the desired labelling.

Clearly $K_7$, which is $6$-regular graph, does not have such a labelling: If it would have then make a new graph where two nodes are connected iff edge between them has labelling $1$. Then we get a $3$-regular graph on $7$ vertices which existence is contradicting handshake lemma.
Comment: How do you know all the Euler cycles have even length?
Comment: @MJD Length of Euler cycle = total # edges = (4 \* # vertices) / 2 = even.
Answer: Aqua's answer is correct. However, as pointed out by MJD, it should be noted that since the graph is 4-regular, from Handshaking Lemma the number of edges must be even.


Transforming data

Question: If I want to make a regression model where sales in billions are dependent variable and my independent variables consist of very low values, for example rainy days (highest number is 15). My question is, is there any problem if I do a regression with original data, or should I do some transformation and therefore make my variables comparable? And which transformation would you suggest? Is sensible to use logarithmic transformation of data here?
I tried to find similar discussion, but struggled to do it.
Comment: As @mdewey wisely answers, the coefficients do the scaling but as a matter of practicality changing units to get coefficients closer to 1 is often a good idea. But your description to me raises a more fundamental question. Sales can't be negative, presumably, but they could be highly skewed. For that reason alone I'd expect Poisson regression (or the same beast under any other name) to be a better bet. For more on why, one way in is http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/ (That sales are measured not counted is **not** crucial!)
Comment: Poisson regression arguably has all the advantages of logarithmic transformation and none of the disadvantages. Note that predictions are automatically of sales, not of log sales.
Comment: as @NickCox suggests, sales can be highly - I would add positively - skewed. So a log transformation may be better choice, as it scales the response and may make it look more symmetric.
Comment: Those are good points @NickCox, I had assumed that sales were in some currency unit. I will update my answer to clarify.
Comment: @mdewey My guess is the same as yours, that sales may be in currency units and they could then be regarded as counts of whatever the smallest currency unit is. Whether they behave as counts are expected to behave (according to some model) can only be checked with access to the data!
Comment: @NickCox, my bad. I see it now. I have deleted my previous comment.
Comment: @NickCox actually the Poisson regression has a disadvantage, it assumes mean=variance, although this may be relaxed to some extent by using a quasi Poisson regression.
Comment: That point is covered explicitly by the link I gave earlier. Modern accounts of Poisson regression give about as much weight to distributional  assumptions as do modern accounts of plain or vanilla linear regression. The functional form is the main thing, $Y = \exp(X\beta)$ rather than $X\beta$.
Answer: There is no particular reason for wanting to transform your data as far as the adequacy of the model is concerned. However you may want to re-scale your outcome to make the coefficients lie in a more manageable range. For instance instead of having sales as the raw count you might express it as so many millions or so many thousands. This would have the effect of dividing your coefficient for rainy days by 1000 or 1000000 which might make it look more sensible. This is often done for predictor variables but in your case from your description it is the outcome which needs attention.
Your model adequacy is not changed though which is the important thing.
As pointed out by commentators I am assuming that sales are billions of some currency unit which if it is the sales of different products sold at different prices may well fulfill the usual assumptions of linear regression. However if it is billions of umbrellas and hence a count then a different model such as Poisson may be appropriate.
Answer: Transformations are like drugs ... Some are good for you and some aren't.
Transforming data by scaling is almost always a good idea .
Transforming time series  data like taking differences can be a bad idea as an unwarranted difference can actually inject structure into the data.
Transforming data by replacing anomalous values by cleansed values enabling a clearer picture robust to the anomalies is also a good idea just as long as you get motivated to find out why the data was anomalous AND enable confidence limits that include the possibility of anomalous values . See @Aksakal's very wise words on this How to fit a model for a time series that contains outliers
Power Transforms like logs or any other assumed transformation can be a bad idea . See When (and why) should you take the log of a distribution (of numbers)? for a discussion of when and why you should transform. One caveat there are certain model objectives i.e. specific models which require transformations but these are usually special purpose and rare.

Transforming data