Golang requirements.txt equivalent

Question: Coming from a python/django world, it'd be great to have something like a requirements.txt equivalent for go/revel.  How can I do this? I know I can just write a requirements.txt file and then do something like
cat requirements | xargs go get

But what if my requirements ALSO have requirements? The above command would attempt to "go get" them, and then they'd fail to build, since I don't have those requirements installed.
Is there something I'm missing?
Comment: `go get` should grab all of the requirements needed for each package. You shouldn't need to specify them. Try it and see if it does what you require.
Comment: Unlike Python or most other programming languages, Go has import statements _in each source file_ which specify where the imported code comes from. That's why there is no seperate package-descriptor file needed. (This only comes into play when you need to specify version constraints, see https://github.com/golang/go/wiki/vgo which is the tool for that from Go 1.11 and 1.12 onwards.)
Answer: The command go get does exactly what you need: It finds all dependencies and downloads and installs the missing ones. Focus on "all": go get really traverses your dependency graph.
Have a look at the documentation:
https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them
The Go documentation is really clean, short and well written. I would recommend always to have a look at the documentation first before making assumptions which are based on experience with other tools or tool-chains.
They also provide useful blog posts, https://blog.golang.org/using-go-modules
Comment: yes, but it's not unrelated to the question you are trying to answer here.
Comment: The link you've shared doesn't explain how I can write my own dependencies, though. Also developers and users may have a diffferent set of dependencies.
Comment: @erikbwork Could you explain what "my own dependencies" are? And what do you mean by "different set of dependencies" of users and developers? Are you thinking of dependencies needed only by the test code? If so: Go get handles this (see command line flags) If you talk about additional tools needed (e.g. `go generates` relies on yacc or m4) then go get is not for you. Go get downloads and build Go packages from source, it is not a package manager or system provisioning tool.
Comment: I don't know `go` so I can't explain it in these terms to you. But usually modern software requires some additional packages, e.g. your program might parse yaml files. Then you need the go-yaml-library in version 3.1.5. If you've never written it down somewhere, I doubt that `go get`will figure it out.
The difference between devs and users is mostly stability. Devs may use version 3.4.5 instead of 3.1.5, because it contains all the new features, but it may break. Users get 3.1.5 with the latest release though, because it breaks less often.
Comment: @erikbwork You are talking about package management and there are lots of tools out there, some almost official. Such a discussion is unrelated to `go get`.
Answer: I just found that the kubernetes guys actually have created an overview page for themselves here.
Summary is this: Currently stable is Glide and the cool new toy is called dep
Comment: this is outdateed as of 2019

Golang requirements.txt equivalent


PHP File upload form verification

Question: So i want to read if the user did not upload a file on form submission, it work before but for some reason it no longer works. It says my error vars $errorImg & $errorThumb Are undefined. but the others with the same set up are fine. I must be making an eror somewhere, i just can't seem to find it.
PHP
    $newChair_name='';
    $newPrice='';
    $newManu='';
    $newRegion='';
    $newStock='';
    $newThumb='';
    $newimg='';

if($_POST){
    $all_valid = true;

    if(empty($_POST['uChair_name'])){
        $all_valid = false;
    $errorNames= 'Please enter a name';
    }else{

    $newChair_name = $_POST['uChair_name'];
    }

    if(empty($_POST['uprice'])){
            $all_valid = false;

        $errorPricess = 'You must enter a price';

    }else if(!is_numeric($_POST['uprice'])){
                $all_valid = false;

        $newPrice = 'Price must be a number';
    }else{

        $newprice=$_POST['uprice'];
        }

    if(empty($_POST['uManu'])){
            $all_valid = false;

        $errorManu = 'We need to know the manufacturer';

    }else{

        $newManu=$_POST['uManu'];
    }

    if(empty($_POST['uRegion'])){
            $all_valid = false;

        $errorRegion = 'We need to know the region made';

    }else{

        $newRegion=$_POST['uRegion'];
    }

    if(empty($_FILES['uthumb'])){ //not being read
            $all_valid = false;

        $errorThumb = 'We need a thumbnail';
    }else{
       $newThumb=$_FILES['uthumb'];

    }

    if(empty($_FILES['ulrgthumb'])){
            $all_valid = false;
         $errorImg = 'We need a large image';
    }else{

         $newimg=$_FILES['ulrgthumb'];
     }

}

HTML
 <form class="chair_form" action="<?php //echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">

    Chair Name:
    <input type="text" name="uChair_name" placeholder="Azual blue" value="<?php echo $newChair_name; ?>" />

<?php echo $errorNames; ?>

    Price:
    <input type="text" name="uprice" placeholder="999.99" value="<?php echo $newPrice; ?>" />

<?php echo $errorPricess; ?>

    Manufacturer:
    <input type="text" name="uManu" placeholder="America" value="<?php echo $newManu; ?>" />

<?php echo $errorManu; ?>

    Region:
    <input type="text" name="uRegion" placeholder="China" value="<?php echo $newRegion; ?>" />

<?php echo $errorRegion; ?>

    Stock:*
    <input type="number" name="uStock" placeholder="200"  value="<?php echo $newStock; ?>" />

    Image of chair 120 x 200:
    <input type="file" name="uthumb"/>

<?php echo $errorThumb; ?>

    Large Image of chair 400 x 500:
    <input type="file" name="ulrgthumb"/>

<?php echo $errorImg; ?>

    Description:*
    <textarea  rows="6" cols="27" name="uDescrip"></textarea>

    <input type="submit">

Comment: Are you seeing the variables as always undefined, only undefined when files are submitted, or only undefined when files are NOT submitted?
Answer: while the above method had worked, this appears more stable
if(empty($_FILES['uthumb']['name'])){
     $all_valid = false;
     $errorThumb = 'We need a large image';
}else{
    $newThumb=$_FILES['uthumb'];
 }

 if(empty($_FILES['ulrgthumb']['name'])){
     $all_valid = false;
     $errorImg = 'We need a large image';
}else{
    $newimg=$_FILES['ulrgthumb'];
 }

PHP File upload form verification


Triangular sides

Question:
In a triangle the least angle is $45º$ and the tangents of the angle are in arithmetic progression. If its area is $27\text{cm}^2$, find the length of the sides.

I tried to solve the problem in this way
Let the smallest angle in the triangle $ABC$ (say) be $A=45º$, where $\tan A$, $\tan B $ and $\tan C$ are in $AP$, then according to question
$$\begin{array}
2\tan B=\tan A+\tan C\\
\implies 2\tan B=\frac{\sin A\cos C+\cos A\sin C}{\cos A\cos C}\\
\implies 2\tan B=\frac{\sin B}{\cos A\cos C}\\
\implies \cos B=2\cos A\cos C
\end{array}$$
As we know that $\cos A=\frac{1}{\sqrt2}$ hence
$$\cos B=\sqrt2\cos C$$
squaring both sides would give
$$\cos^2B=2\cos^2C$$
Changing the cosines to sines we get
$$1-\sin^2B=2-2\sin^2C$$
$$=2\sin^2C-\sin^2B=1$$
Now as we already know that $\sin C=\frac{2\Delta}{ab}$ and similarly $\sin B=\frac{2\Delta}{ac}$ where $\Delta$ is the area of the triangle and $a,b,c$ the sides of the respective triangle.
But now when I put the sine formula in the equation and take $\Delta=27\text{cm}^2$ I get stuck with the product of $abc$ what should I do to get the sides.
Answer: HINT:
$\tan A=1,$
If $\tan B=p,\tan C=\tan(135^\circ -B)=\dfrac{p+1}{p-1}$
We have $$\tan A+\tan C=2\tan B\implies1+\dfrac{p+1}{p-1}=2p$$
Can you take it from here using
$$27=\dfrac12bc\sin A\iff bc=54\sqrt2$$
Comment: @HarshSharma, If $\tan A=2,\sin A=\dfrac2{\sqrt{2^2+1^2}}$ etc. $$\triangle=\dfrac{abc}{4R}$$ and use https://en.wikipedia.org/wiki/Law_of_sines to find $R$
Comment: From this I got the tangents of angles but how can I go on to find the sides. If I apply cosine formula for angle $A$ I must be having the perimeter of the triangle. Please help for the sides.

Triangular sides


Angular merge map for one after another http calls

Question: The getDetails() method returns an Details[] and with that array and there is a name property which I am passing to another http call
Details {
    name: String;

Details
 getDetails()
     return this.https.get("/someValue") //this return Details[] from here I have to take  name property

return
{name : hello}

Information
 getInformations(name:string) {
    return this.https.get("/anotherValue"+"?"+ name)
 }

I am trying to first call getDetails() and pass the name property to
Information{
  Hieght:string
  age:string
}

getInformations()
this.getDetails().pipe(mergeMap(x =>
 this.getInformations(x.name)).subscribe((inforamtionResults:Information[])=>{
  console.log("Checking Informations"+inforamtionResults.length)

return
 {height:160,
   age: 23
   }

This is not working as x value is an array. How do iterate the array and pass the array property as parameter?
Answer: As you said, you need to iterate each this.getInformations(x.id) Details. You can do this by simply using Array.map(). However, mergeMap wants one observable, but what we have is an array of observables. Thankfully, we can combine those array of observable to just one observable using rxjs' forkJoin.
this.getDetails()
  .pipe(
    mergeMap((details) =>
      forkJoin(details.map((x) => this.getInformations(x.id)))
    )
  )
  .subscribe((x) => console.log(x));

Here is a sample demo. I've used a different API but the implementation is similar.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221415/discussion-between-subham-and-blackraspberryyy).
Comment: When dealing with rxjs, this [operator decision tree](https://rxjs-dev.firebaseapp.com/operator-decision-tree) helps me a lot so I'll just put this here.
Comment: For x I am getting  double array vaue x[][]
Comment: `forkJoin` isn't deprecated as said [here](https://rxjs-dev.firebaseapp.com/api/index/function/forkJoin) (I am using `rxjs 6.5.4`). Can you update your question to also show the structure of your data that you'll receive from `getDetails()` and `getInformations()`?
Comment: I have updated the question...Can you please have a look.I dont want to iterate each  this.getInformations(x.id).Just want to do a sequence HTTP calls first retriev get details and take the name propert from there and then pass the same property to the another call getInformation(x.id)
Comment: Is `getDetails()` really returning an array? But in your question, you said that it returns `{name: "hello"}` which is clearly not an array. Also, `Details` does not have an `id` property, but you tried to access it here: `this.getInformations(x.id)`. I am more confused now. Can you create a [fiddle](https://jsfiddle.net/), or a working demo at [codesandbox](https://codesandbox.io/) so we can help you better?
Answer: You need to try Like this.
 getDetails() {
    return this.http.get("/someValue")
      .pipe(
        mergeMap((x) => {
          return this.getInformations(x.id)
        })
      );
  }

Comment: Why you are using response??


calculando data no update mysql

Question: Bom preciso de dar update em minhas contas que estão vencidas a mais de 5 meses, queria fazer isso direto no mysql. O update está assim:
UPDATE contas
SET baixa_valivade = true
WHERE data_vencimento (Preciso verificar se já esta vencida a mais de 5 meses)

Answer: Use o DATE_ADD():
UPDATE contas
SET baixa_valivade = true
WHERE data_vencimento BETWEEN DATE_ADD(CURRENT_DATE(), INTERVAL -5 MONTH) AND CURRENT_DATE()

Se a necessidade for atualizar os itens com data de atraso maior que 5 meses, o código ficaria o seguinte:
UPDATE contas
SET baixa_valivade = true
WHERE data_vencimento < DATE_ADD(CURRENT_DATE(), INTERVAL -5 MONTH)

Comment: Ok, deu certo. Obrigado
Comment: Bom testei aqui e não funcionou muito bem, tenho 2 contas. 2017-09-26 e 2018-07-26. Deveria atualizar a conta 2017-09-26, porém esta atualizando a conta 2018-07-26.
Comment: pela data de hoje, 5 meses pra trás pegaria a de 07/18 (-2 meses).. a 09/12 está -12 meses.. não entendi o erro =p
Comment: Bom acho que eu não soube explicar direito, o update deve ser dado nas contas que tem mais de 5 meses atrasadas. A conta 09/17 tem mais de 5 meses atrasadas e a conta 07/18 ainda não completou 5 meses.
Comment: saquei.. atualizei a resposta, veja se resolve!

calculando data no update mysql


Taxonomy List with Node Count, exclude those with 0

Question: I have a view that is used to display blog categories on a blog with the corresponding count of blog posts in that category. In cases where there are 0 blog posts, I want to exclude that item from the list. Here is my view:
<code>$view = new view();
$view->name = 'blog_categories';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Blog Categories';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Blog Categories';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Header: Global: Unfiltered text */
$handler->display->display_options['header']['area_text_custom']['id'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['table'] = 'views';
$handler->display->display_options['header']['area_text_custom']['field'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['content'] = 'Categories:';
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: COUNT(DISTINCT Content: Nid) */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count_distinct';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['nid']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['nid']['prefix'] = '(';
$handler->display->display_options['fields']['nid']['suffix'] = ')';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'blog_categories' => 'blog_categories',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['block_description'] = 'Blog Categories Menu Block';
$translatables['blog_categories'] = array(
  t('Master'),
  t('Blog Categories'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Categories:'),
  t('node'),
  t('Block'),
  t('Blog Categories Menu Block'),
);
</code>
Here is a screenshot of the view config page and one of the output:

How do I configure the view to exclude terms with a 0 count?
Answer: Added the count NID field as a filter:

Add new filter
Select Content: Nid
Set Aggregation type to Count DISTINCT
Set Relationship to node (should be default)
Set Operator to Is greater than
Set Value to 0

Here is the new view:
<code>$view = new view();
$view->name = 'blog_categories';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Blog Categories';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Blog Categories';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Header: Global: Unfiltered text */
$handler->display->display_options['header']['area_text_custom']['id'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['table'] = 'views';
$handler->display->display_options['header']['area_text_custom']['field'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['content'] = 'Categories:';
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: COUNT(DISTINCT Content: Nid) */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count_distinct';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['nid']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['nid']['prefix'] = '(';
$handler->display->display_options['fields']['nid']['suffix'] = ')';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'blog_categories' => 'blog_categories',
);
/* Filter criterion: COUNT(DISTINCT Content: Nid) */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['relationship'] = 'nid';
$handler->display->display_options['filters']['nid']['group_type'] = 'count_distinct';
$handler->display->display_options['filters']['nid']['operator'] = '>';
$handler->display->display_options['filters']['nid']['value']['value'] = '0';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['block_description'] = 'Blog Categories Menu Block';
$translatables['blog_categories'] = array(
  t('Master'),
  t('Blog Categories'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Categories:'),
  t('node'),
  t('Block'),
  t('Blog Categories Menu Block'),
);
</code>


Regular Expression Pattern optional group depending on space

Question: I am pretty new to regular expressions and I need to create a pattern that could be used in matching up different text values(cases). I can use the created pattern but it can only be used in a single case. I would like to maximize the search pattern so that it can be used to different search texts.
By the way, I am using Java 8.
Objective:
Display matcher.find() by group.
Sample Search Texts and Expected output (Group):
Search Text: "employeeName:*borgy*";
Expected Output:
-
(employeeName) (:) (*) (borgy) (*)
-

Search Text: "employeeName:Borgy Manotoy*";
Expected Output:
-
(employeeName) (:) () (Borgy Manotoy) (*)
-

Search Text: "employeeName:*Borgy Manotoy*";
Expected Output:
-
(employeeName) (:) (*) (Borgy Manotoy) (*)
-

Search Text: "employeeEmail:*firstname.lastname@example.com*";
Expected Output:
-
(employeeEmail) (:) (*) (firstname.lastname@example.com) (*)
-

Search Text: "employeeEmail:firstname.lastname@example.com";
Expected Output:
-
(employeeEmail) (:) () (email@example.com) ()
-

Search Text: "employeeName:*Manotoy*, employeeEmail:*@iyotbihagay.*";
Expected Output:
-
(employeeName) (:) (*) (Manotoy) (*)
(employeeEmail) (:) (*) (@iyotbihagay.com) (*)
-

Search Text: "employeeName:*Manotoy*, employeeEmail:*@iyotbihagay.*, employeeRole:*bouncer*";

Expected Output:
-
(employeeName) (:) (*) (Manotoy) (*)
(employeeEmail) (:) (*) (@iyotbihagay.com) (*)
(employeeRole) (:) (*) (bouncer) (*)
-

Search pattern:
String searchPattern = "(\\w+?)(:|!)(\\p{Punct}?)(\\w+?) (.+?)?(\\p{Punct}?),";

Sample search texts:
String text1  = "employeeName:borgy";
String text2  = "employeeName:Borgy*";
String text3  = "employeeName:*borgy*";
String text4  = "employeeName:*Borgy*";
String text5  = "employeeName:*Borgy Manotoy*";
String text6  = "employeeEmail:*firstname.lastname@example.com*";
String text7  = "employeeEmail:firstname.lastname@example.com";
String text8  = "employeeEmail:borgymanotoy@iyotbihagay.*";
String text9  = "employeeEmail:*@iyotbihagay.*";
String text10 = "employeeName:*Manotoy*, employeeEmail:*@iyotbihagay.*";

Search texts using the given pattern:
processUserSearch(text1, searchPattern);
processUserSearch(text2, searchPattern);
processUserSearch(text3, searchPattern);
...
processUserSearch(text10, searchPattern);

Display found
private void processUserSearch(String searchText, String searchPattern) {
    if (!Util.isEmptyOrNull(searchText) && !Util.isEmptyOrNull(searchPattern)) {
        Pattern pattern = Pattern.compile(searchPattern);
        Matcher matcher = pattern.matcher(searchText + ",");
        while(matcher.find()) {
            System.out.println("[matcher-count]: " + matcher.groupCount());
            System.out.print("found: ");
            for (int x = 1; x <= matcher.groupCount(); x++) {
                System.out.print("(" + matcher.group(x) + ") ");
            }
            System.out.println("\n");
        }
    }
}

Comment: What do you need to do? What are the expected results per each test case?
Comment: Without clarification, it is hard to help you. See https://regex101.com/r/57uNcy/1
Comment: Using a single searchPattern only, I could use it in searching (regexp) different text values like (text1 ... text10).
Comment: sorry for the incomplete problem, I have added the objective or expected outputs. Just want to display the matcher.find() groups values.
Comment: For `employeeName:*Manotoy*, employeeEmail:*@iyotbihagay.*`, you can't have `(employeeEmail) (:) (*) (@iyotbihagay.com) (*)`. Only `(employeeEmail) (:) (*) (@iyotbihagay.) (*)`
Comment: that is ok, it a lot closer. I tried the sample you gave and it almost works on all cases except for text9 and text10. Thanks a lot.
Answer: I suggest using
private static final Pattern pattern = Pattern.compile("(\\w+)([:!])(\\p{Punct}?)(.*?)(\\p{Punct}?)(?=$|,)");
private static void processUserSearch(String searchText) {
    if (!searchText.isEmpty() && searchText != null) {
    //if (!Util.isEmptyOrNull(searchText) && !Util.isEmptyOrNull(searchPattern)) {
        Matcher matcher = pattern.matcher(searchText);
        while(matcher.find()) {
            System.out.println(searchText + "\n[matcher-count]: " + matcher.groupCount());
            System.out.print("found: ");
            for (int x = 1; x <= matcher.groupCount(); x++) {
                System.out.print("(" + matcher.group(x) + ") ");
            }
            System.out.println("\n");
        }
    }
}

Note you can compile it once outside of the matching method for better  efficiency.
Use as
String[] texts  = new String[] { "employeeName:*borgy*","employeeName:Borgy Manotoy*","employeeName:*Borgy Manotoy*",
                           "employeeEmail:*email@example.com*","employeeEmail:email@example.com",
                           "employeeName:*Manotoy*, employeeEmail:*@iyotbihagay.*",
                           "employeeName:*Manotoy*, employeeEmail:*@iyotbihagay.*, employeeRole:*bouncer*"};
for (String s: texts) {
        processUserSearch(s);
    }
}

See the Java demo
Here is the regex demo:
(\w+)([:!])(\p{Punct}?)(.*?)(\p{Punct}?)(?=$|,)

Details

(\w+) - Group 1: one or more word chars
([:!]) - Group 2: a : or !
(\p{Punct}?) - Group 3: an optional punctuation char
(.*?) - Group 4: any 0+ chars other than line break chars
(\p{Punct}?) - Group 5: an optional punctuation char
(?=$|,) - an end of string or , should come immediately to the right of the current location (but they do not get added to the match value since it is a positive lookahead).
Answer:
I would like to maximize the search pattern so that it can be used to different search texts.

And what are "different search texts"? Be specific!
Your problem doesn't seem specific to Java. Your current pattern contains (:|!), but none of the examples suggest how !s may occur in the input. You use \p{Punct} to match the * surrounding the names and emails, but you have no examples of other enclosures than *. You don't say what the purpose of the *s are; are they enclosures, wildcard patterns, what?
The following pattern seems to work for some purposes:
(?:employee(Name|Email)):([\w*@. ]+)


Multivariable uniform convergence and differentiation

Question: There is a well known theorem on the relationship between uniform convergence of univariate functions and differentiation.  Quoting Theorem 7.17 from Rudin 1976, Principles of Mathematical Analysis:
Theorem: Suppose $\{f_n\}$ is a sequence of functions, differentiable on $[a, b]$ and such that $\{f_n(x_0)\}$ converges for some point $x_0$ on $[a,b]$. If $\{f_n'\}$ converges uniformly on $[a,b]$, then $\{f_n\}$ converges uniformly on $[a,b]$ to a function $f$, and $f'(x) = \lim_{n\rightarrow\infty} f_n'(x)$.
My question is, does a generalisation of this theorem exist for sequences of functions $f_n: \mathbb{R}^n \rightarrow \mathbb{R}?$ For example, can $f'_n$ be replaced by $\nabla f_n$ and $[a,b]$ be replaced by a compact set?
Answer: After some thought, I have this corollary to the theorem quoted in the question.
Corollary:
Let $f_n : \mathcal{X} \rightarrow \mathbb{R}$ be a family of functions on a
    subset $\mathcal{X} \subseteq \mathbb{R}^n$ and suppose $\{f_n(x)\}$ converges pointwise to a
    function $f$ on a convex set $\mathcal{C} \subseteq \mathcal{X}$.  Further,
    suppose that $\nabla f_n$ converges uniformly on $\mathcal{C}$.  Then
    $\{f_n\}$ converges uniformly on $\mathcal{C}$ and $\nabla f =
 \lim_{n\rightarrow \infty} \nabla f_n$.
Proof:
Fix two points $a, b \in \mathcal{C}$.  By convexity of $\mathcal{C}$, all
    points $g(t)$ on the straight line connecting $a$ and $b$ are in
    $\mathcal{C}$:
    $$
  g(t) = (1-t)a + tb \in \mathcal{C}\; \forall\; t\in[0,1].
 $$
    Then we have $f_n \circ g$ pointwise convergent on $t\in[1,0]$.  Furthermore,
    $(\nabla f_n \cdot (b-a))\circ g$ is uniformly convergent on $t\in[0,1]$.
    Indeed, fixing $\epsilon > 0$, by the Cauchy-Schwarz inequality, we have
    $$
  |(\nabla f_n (x) - \nabla f_m (x))\cdot(b-a)| \leq
  ||b-a||\,||\nabla f_n(x) - \nabla f_m(x)||,
 $$
    and by uniform convergence of $\nabla f_n$, there is some $N(\epsilon)$ such
    that, whenever $n > N$ and $m > N$, the right hand side is less than
    $||b-a||\epsilon$.  It is quick to verify that $(\nabla f_n \cdot (b-a))\circ
 g = \partial f_n \circ g/\partial t$.  It follows from the theorem stated in the question
    that $f_n \circ g(t)$ converges uniformly to $f\circ g(t)$ on $[0, 1]$ and
    $$
  \frac{\partial}{\partial t}f \circ g(t) = \lim_{n\rightarrow \infty} \frac{\partial}{\partial t} f_n \circ
  g(t).
 $$
    As the choice of $a$ and $b$ is arbitrary, this shows that $\nabla f_n\cdot l
 \rightarrow \nabla f \cdot l$ in all directions $l$.  Choosing $l$ to be the
    basis vectors, this shows $\nabla f_n \rightarrow \nabla f$.
Comment: Thanks for the answer. Just one comment: in your corollary, I think you may want the domain of $f_n$ to be some subset of $\mathbb{R}^d$; metric space is not enough to talk about derivatives.
Comment: Thanks Jiaqi Li, good point.  I'll update the answer.
Comment: It seems that if $\mathcal{C}$ is assumed to be open, then the convexity assumption can be dropped, since ultimately we only care about the directional derivative, in which the direction $l$ can be chosen to have very small length. Then, simply choose $a,b$ to be points sufficiently close so that they are both contained in an open ball $B\Subset\mathcal{C}$, and the ball is clearly convex.


Desenvolvimento Ionic para ios em um ambiente windows ou linux é possível?

Question: Queria saber se existe alguma maneira de criar aplicações para iOS quando o nosso sistema operacional é windows ou linux.
Segundo essa informação do cordova, teríamos que ter um sistema operacional OS-X.
Existe algum workaround?
Answer: Não é possível pois é necessário recursos do MacOS e XCode tal como o ambiente iOS SDK para compilar aplicativos iOS.
As opções mais próximas seriam:

Cloud
São serviços de compilação de apps nas nuvens.
Nesse caso, qualquer sistema operacional pode ser usado pois o trabalho de compilação é determinado pelos computadores da empresa que fornece o serviço.
Aqui você "perde" a privacidade e até segurança do projeto, pois está dando de "bandeja" os códigos para um terceiro. Mas não é uma opção ruim. Cada um deve calcular os seus próprios riscos. Contudo, isso é outro assunto não pertinente ao que pergunta.
Virtualização
Instalar o MacOS por meio de ambiente virtualizado (VirtualBox, VMWare, etc).
É normalmente uma tarefa complicada e dificilmente terá um resultado satisfatório. Na maioria das vezes não compensa mas é o mais simples e próximo do que necessita.
Hackintosh
Fazer modificações em configurações de hardware de um PC para poder instalar um MacOS. Nesse caso deixa de ser Windows ou Linux, o que fugiria do seu objetivo. A única "vantagem" é não precisar comprar um Mac.
É também uma tarefa muito complicada e na maioria das vezes é ineficaz. Além disso é considerado crime pois é usado versões piratas do MacOS. Obviamente que não deve fazer isso num ambiente corporativo.

Opinião pessoal, não se iluda muito com gambiarras. A princípio podem trazer algum resultado (bem porco), mas não conseguirá manter de forma segura e estável. *referente a hachintosh e virtualização
O "segredo" dessas plataformas "híbridas" de desenvolvimento é na verdade uma grande gambiarra. É tudo baseado em HTML/JavaScript que rodam sob uma classe "webView" do sistema operacional alvo (Android / iOS).
Basicamente abre-se uma janela do browser dentro do app. Resumindo grosseiramente, o app final é apenas um "buraco" na tela que chama o browser padrão do sistema operacional e captura eventos JavaScript. Esses eventos JavaScript são capturados pelos recursos nativos do dispositivo, por isso, é possível o acesso a determinados recursos nativos.
Comment: Depende muito do que o app necessita. Para coisas simples que pode resolver com HTML/JavaScript eu também prefiro escrever o app em HTML pois não faz diferença. A difrença maior é que torna o desenvolvimento 1000% mais simples. Eu particularmente não uso ferramentas como phonegap pois desenvolvi moldes semi-prontos e apenas replico os apps. Na hora de compilar, se é para iOS trabalho com o Mac. Se for para Android vou no Windows ou dependendo do caso faço tudo no Mac. Para apps mais complexos vc vai perceber que nem tudo se resolve com HTML/JavaScript.
Comment: Daniel, tenho vários amigos que fazem apps em phonegap, e pergunto-lhes se vêm alguma diferença entre essas apps e as apps nativas a 100%, e eles dizem que não. O que acha? Parece ter experiencia no assunto daí a minha pergunta, acha que é uma má ideia porquê mais precisamente?
Comment: Entendo, obrigado pelo esclarecimento Daniel
Comment: Daniel, valeu pela informação. Eu já tinha imaginado isso, que os apps desenvolvidos com essas ferramentas eram apenas uma espécie de browser do celular.  Então na prática teríamos que ter 2 computadores para desenvolvimento? Um iOS e outro windows? O que vc considera coisas não simples. Quais exemplos não seriam resolvidos com ionic ou phonegap? Uma pergunta um mac poderia desenvolver para Android e Windows?
Comment: No Intel XDK vc consegue desenvolver para android, ios e windows phone com html/css, da até para gerar o arquivo .ipa e instalar no seu iphone, só vai precisar de um mac para mandar o aplicativo para loja. Eu faço utilizando Ionic, em androids mais antigos fica bem lento, agora em androids, iphones e windows phones mais novos fica show, tem muitos plugins para poder usar os recursos nativos do celular, mas é claro, nativo fica sempre melhor, hibrido é mais rápido na hora do desenvolvimento, nativo demora mais porém fica com um resultado final bem melhor.


Adding an Interceptor to existing Castle.DynamicProxy proxy

Question: Let's say I have a Castle.DynamicProxy object that is created by a third party. In this case Rhino.Mocks.
var rhinoObj = MockRepository.GenerateMock<IMyType>();

For one reason or another I want to be able to use this generated object by Rhino and add another interceptor to it so I can manipulate it without using Rhino itself.
I understand this may seem weird, its for a mocking library I'm writing myself that I want integrated with other mocking frameworks that use Castle, such as Rhino.
I have tried:
 generator.CreateInterfaceProxyWithTarget(rhinoObj, new MyInterceptor())

But Rhino complains when I wish to use anything such as .Stub(..) that this is not a mocked object - so clearly the rhino interceptors are overwritten.
Comment: Have you looked at the [Rhino.Mocks source code](https://github.com/ayende/rhino-mocks) to see what conditions make the `Stub` method complain?  Might give you some insight into the issue.
Comment: Yes, It seems that Rhino keep hold of references to proxies/mocks they produce. So if somebody else creates it, it can't do anything with it. Sadly I don't think my plan is possible!
Answer: I know it is an old question but I had the same problem. Reading my own answer 2 days ago would have saved me several hours...
The Problem
Rhino.Mocks with the help of castle dynamic proxy generates a new type based on your interface, creates an instance of it and returns it to you. This instance is also used as a rhino.mock-internal key to look up all mocking-things (assertions, return values, ...).
Now you create a proxy (means: another new type and another new instance) around the rhino.mock-object and the lookup-by-instance does not work anymore. You need the original object somehow.
Option 1
You need to keep the original object from rhino.mocks around. How this will look depends on your overall setup. Maybe all instances creation goes through a central repository and you can add handy accessor methods like those:
internal interface IMockRepository
{
    void Add(object key, object mock);
    T GetMock<T>(T key);
    object GetMock(object key);
}

This should the trick any mocking framework, not just rhino.mocks. On the minus-side is extra infrastructure and boilerplate code. And the akward feeling that you create a proxy around a proxy.
Option 2
(based on this answer): Rhino.mocks also uses castle dynamic proxies and interceptors. Maybe we can sneak in our own interceptor? We can!
var mock = Rhino.Mocks.MockRepository.GenerateStub(type);
dynamic dyn = mock;
dyn.__interceptors = new[] {new MyInterceptor(), dyn.__interceptors[0]};

You need to use IInterceptor and IInvocation from Castle.Core.Interceptor instead of Castle.DynamicProxy but the interfaces are identical. The original proxy must come last.
This relies on rhino.mocks-internals which might change in any future release without notice. But I think it is save to assume that (a) rhino.mocks will continue to use castle dynamic proxies and (b) dynamic proxies will be dynamics also in future. So if something breaks, it should be fixable.
This is more "hacky" but I use this solution. No "proxy-of-proxy"-thing and no boilerplate.


"A property holds if it cannot be rejected"

Question: Most examples in my Time Series Analysis slides and Multivariate Analysis textbook (Applied Multivariate Statistical Analysis, 6th Edition) conduct a hypothesis testing on data's normality, or zero correlation, or independence, or homogeneity of variance, or whatever, and readily assume these properties to be true on failure to reject the hypothesis. Actually, I am explicitly taught that a property holds if it cannot be rejected.
For example, in Example 6.14 (A profile analysis of love and marriage data) from the textbook AMSA, authors "conclude that the hypothesis of parallel profiles for men and women is tenable" when $H_0$ cannot be rejected. In addition, they also said "... we cannot reject the hypothesis that the profiles are coincident. That is, the responses of men and women to the four questions posed appear to be the same." Here is the whole example: P.325, P.326, P.327, P.328, where the quotes are from the bottom of P.327 and the top of P.328 respectively.
This seems ridiculous, as absence of evidence is not evidence of an absence. Even if $p = 1$, it's still circular reasoning, let along cases where $p$ isn't even remotely close to 1. Back when I was learning Mathematical Statistics, the professor would kick their ass if someone accept $H_0$ on failure to reject it, but the standard is clearly loosened a lot in upper division courses.
I just want to know is this practice a de facto procedure in intermediate Statistic courses like Time Series Analysis and Multivariate Analysis? If so, what the rationale?
Comment: @NickCox I see, so hypothesis testing is more of a means to check/verify the data at hand don't drift too much from the ideal conditions of inference procedures to be employed, but still, nothing can be *proved* from this check. I will know if my assumptions are absurdly wrong, but there is a chance that the data will pass the check while the assumptions aren't meet, but that's OK since tiny drifts don't invalidate the applicability of inference procedures.
Comment: @mkt The whole example is way too long to be typed by hand, so I have included it as screenshots in the original post. Hope you don't mind.
Comment: Can you provide more context? Your examples (normality, etc.) suggest these claims have to do with assumptions of inferential tests/procedures. If so, while never strictly true (as you say), a lack of evidence for non-normality of residuals (for example) is taken as evidence that the assumption of normality is *approximately* true; i.e. the deviation is not so strong that you need to alter your procedures & conclusions.
Comment: @mkt Hi, I'm not sure what do you mean by "context", but on failure to reject normality, the authors usually go on to apply statistical methods only applicable to data drawn from a (multivariate) normal distribution. Another example is *Example 6.14 (A profile analysis of love and marriage data)* from the textbook AMSA, where authors "conclude that the hypothesis of parallel profiles for men and women is tenable" when $H_0$ cannot be rejected.
Comment: Most of us do not have access to the book you are referring to, so relevant quotations that expand on your claims about what the authors say is what I meant by 'context'. In the one quote you provide, concluding that two groups being similar 'is tenable'  based on a failure to reject H0 hardly seems like a radical claim.
Comment: "the standard is clearly loosened a lot in upper division courses": you are making a statement based on a sample of 1 textbook. Otherwise, I agree. I don't like the wording you cite from that text. Failure to reject the null is not establishing it as true.
Comment: @NickCox Yeah I did jump to a conclusion, but my professor told us this textbook is really well-established and that "everyone uses it", so I was under the impression that it can represent the whole field?
Comment: "Everyone uses it". Well, this is the same kind of problem. I have heard of it but never used it, even opened it. Is that enough refutation? More seriously, even good textbooks can be wrong, so never believe something puzzling just because you find it in one place. As a serious example, the multivolume text by M.G. Kendall, later Kendall and A. Stuart, later Stuart and J.K. Ord still contains some amazing errors. A standard blood sport for some decades was to write a review of each new edition pointing out what was wrong. (Some "errors" were lack of rigour by the reviewer's standards.)
Comment: @NickCox Thanks for the insight! Actually, can you refer me to a better textbook? From my current understanding, hypotheses are chained together in profile analysis, so you are supposed to make some assumption about the first claim to proceed. Also, many other Statistical methods require normality, but hypothesis testing can only reject rather than prove it. How can this be resolved?
Comment: All I could do is point to multivariate texts I like. I don't think that any necessarily says much about time series analysis. I have no idea what your background and tastes are. But -- as said, without reading it --  the Johnson and Wichern text I am guessing to be rather old-fashioned. Most recent texts show a lot of awareness of machine learning. I think you'll find that multivariate normality, although convenient when you have it, isn't nearly as central to multivariate analysis as some older texts imply. Any text with first edition before say 2000 is unlikely to be updated enough.
Comment: @NickCox Thanks sir, I'll have a look. Regarding the (relative) insignificance of normality, let's consider homogeneity of variance or independence instead, which are presumably much more important. Again, hypothesis testing can only reject them, and failure to reject is sometimes incorrectly interpreted as acceptance. I'm curious to learn methods which can prove these properties.
Comment: You can't prove that properties are satisfied absolutely.  This is where you started! Even independence isn't crucial. What's crucial is whether procedures you use assume it.
Comment: @NickCox Oh, you mean I should make assumptions about the data (sample), and then pick inference precedures accordingly?
Comment: Say rather: Whatever assumptions you make should be checked, although that's not always easy. My final comment is that the term _assumptions_ isn't always helpful. It's true that there is much theory that says if this is so, then that is so. But in practical data analysis the assumptions serve more as _ideal conditions_, and not everything falls over if they aren't satisfied. In applying PCA, for example, I might find it better to work on a transformed scale, so that distributions are roughly symmetrical and outliers pulled in, but exact normality is never needed for any use I make of PCs.
Answer: Here is a demonstration using four samples of size $n = 15$ from uniform, gamma, beta, and normal populations.
Tests of normality. In all four cases the data 'pass' a Shapiro-Wilk test
for normality. That is, we cannot reject the null hypothesis that data are normal. Approximate P-values for the normality test are 0.40, 0.48, 0.09, and 0.36, respectively--all clearly above 0.05.
The PDFs of the first three distributions are all substantially different from normal, but $n = 15$ observations are not enough to
detect the departure from normality.
Robustness of the t test: Also, in all four cases we use a one-sample t test
to test a null hypothesis about the population mean
that is false. For all four samples, the null hypothesis is (correctly) rejected. Even for a sample size as
small as $n = 15,$ the test detects that the various hypothetical values of the population mean  are not correct.
The t test is said to be 'robust' against
departures from normality---as long as there are no
extreme outliers. Although the first three samples are non-normal, the t test still gives useful results.
Here are boxplots of the four samples;

<code>set.seed(1234);  n = 15
u = runif(n);  shapiro.test(u)$p.val;  t.test(u, mu=.7)$p.val
[1] 0.3963761   # P-value for normality test
 [1] 0.0145073  # P-value for t test

v = rgamma(n, 5, 1); shapiro.test(v)$p.val;
t.test(v, mu=2)$p.val
[1] 0.4827358
 [1] 5.112448e-05

w = rbeta(n,3,4); shapiro.test(w)$p.val;
t.test(w,mu=.7)$p.val
[1] 0.08774671
 [1] 9.815778e-05

z = rnorm(n); shapiro.test(z)$p.val;
t.test(z,mu=.7)$p.val
[1] 0.3592276
 [1] 0.003356458
</code>
Note: The seed for the simulation is given so that you can reproduce exactly the same simulated data used here. Different seeds might give substantially different results.


custom content type

Question: I have created a custom content type (Testimonial), with the following fields: customer name, testimonial, company name. Each of them is stored in a different table.
How can I use the records to display in the front end? Is it advisable to use custom content type for this purpose?
Comment: Look into the Views module ( http://drupal.org/project/views ) as it will allow you to show your (and all other) content types in all kinds of ways on your site.
Answer: Drupal has is own storage system in database. Your don't really need to know how datas are stored and even if datas are in severals tables, you can use functions like node_load() or node_view(), which are awesome because you do not write any joined sql queries and fields datas are automaticly returned in a node object
Use the Views module to display a list of nodes of a certain type.

custom content type


Is there any list of doping that could be found in daily food?

Question: As WADA states in DIETARY AND NUTRITIONAL SUPPLEMENTS:

CAN AN ATHLETE TEST POSITIVE FROM USING DIETARY/NUTRITIONAL SUPPLEMENTS? UP

Extreme caution is recommended regarding supplement use.
The use of dietary supplements by athletes is a concern because in
  many countries the manufacturing and labeling of supplements may not
  follow strict rules, which may lead to a supplement containing an
  undeclared substance that is prohibited under anti-doping regulations.
  A significant number of positive tests have been attributed to the
  misuse of supplements and taking a poorly labeled dietary supplement
  is not an adequate defense in a doping hearing.

And in PROHIBITED LIST:

CAN I TEST POSITIVE FOR INGESTING GLYCEROL FOUND IN FOODSTUFFS AND TOILETRIES OR FOR USING IT AS A LUBRICANT? UP

Glycerol is prohibited as a plasma expander. The consumption of
  quantities of glycerol far beyond those commonly found in e.g. foods,
  beverages, personal care products, medicinal tablets tuffs, cough
  syrup is required to produce an Adverse Analytical Finding. Therefore,
  its prohibition is not intended to prevent the ingestion of this
  substance in the amounts commonly found in foodstuffs and toiletries,
  as such small quantities will not cause an athlete to test positive
  for this Prohibited Substance.
In addition, athletes with disabilities may use glycerol as a
  lubricant agent for a catheter but this will not cause a problem in a
  doping control for the aforementioned reasons.

Is there any cases like positive doping test because athlete ate some meat that was grown with hormones or steroids?
I am not asking about medicine. I am asking about daily food, is there anything that should be avoided?
Answer: Absolutely.
I boxed in the late 90s while in college.  My dining hall was not feeding me enough so I was heavily smuggling food out for late night snacks.  I found out that the easiest food to smuggle out and that would actually take decent were the bagels.  And the only ones they had left at the end of the meals were the poppy seed ones.  So I was eating 4-5 very large poppy seed bagels a day for snacks.
Right before golden gloves finals we were taken to a facility, met agents, talked with some of us about joining Olympic team (not me), allowed our trainers to train us there... lots of fun actually.  But we also had weigh-ins and a drug test the first day.  And since I was a light middle weight weighing 190 I was having at least 5 of the poppy seed bagels a day to gain weight.
I was a completely drug free person (save beer).  Failed my first test - told me traces of morphine in my system.  It took two days to figure out why and many meetings with officials.  I also had doctors raising an eye brow when I explained to them I was eating 25-30 poppy seed bagels a week.  It was like a bad sitcom episode.  The only thing that kept me from getting kicked out is they actually called the school, spoke to the lady who ran the dining hall, and she knew I was taking the bagels every night - I listened to her on speaker.  (I think her exact words were that skinny guy who eats like a horse takes all the bagels every night.  We would throw them out anyway so I never cared.)
Answer: According to the article "Non-Intentional Doping in Sports" (by Mauricio Yonamine, Paula Rodrigues Garcia, Regina Lúcia Moreau) which refers to several real cases of positive doping tests and several researces, it is really possible to recieve banned substances into your body unintentionally (e.g. non-smokers could passively inhale enough marijuana, or eat as much poppy-seed-containing food so that it could result in positive test, as in @Coach-D case)
But the article is of 2004 year and limits (concentration of banned substance in urine) could have changed from that time.
Anyway it is possible to intentionally avoid consumption of such stuff.
P.S.: this is still not full answer to my question becouse there is no up to date list of daily products that could possibly contain banned substances (and better with evaluation of concentration wich is enough to be detected)


JDBI failure case

Question: I am looking at some examples of using the JDBI library for Java database access.
One such example is as follows....
List<String> names = mJdbi.withHandle(handle ->
    handle.createQuery("select name from test_table")
          .mapTo(String.class)
          .list());

I am confused as to what happens when this call fails. For example, what if there is no table called test_table. What should I expect the outcome of this code to be in that case?
Answer: Well, what should you expect if any call fails in java? Maybe an Exception?
Be happy that jdbi unburdens you from dealing with SQLException directly. Here is what you will be facing https://jdbi.org/apidocs/org/jdbi/v3/core/JdbiException.html (or ady subclass thereof, probably StatementException in your case)
On a side note: it is <5 minutes of work setting up a project with in-mem db to try it out...

JDBI failure case


Remainder of $2^y$ and $3^y$

Question: When is $$2^y\mod  3^x = 1$$
where $x,y\geq0$ and $x,y$ are integers.
I know the trivial solutions but can anyone please provide non-trivial solutions.
Thanks.
Comment: What are the trivial solutions? $y=0$; $x=1,2|y$; $x=2, 6|y$; and in general $2\cdot 3^{x-1}|y$?
Comment: how do you do >= in Tex?
Comment: Please try to avoid double `$$` in titles. `\geq` yields $\geq$, and `\leq` yields $\leq$.
Comment: Oh ok thanks. Sorry about the title.
Comment: Use a \geq for greater than/equal to and \leq for less than/equal to.
Comment: Or \ge and \le.
Comment: @Hagen: aren't those all solutions?
Comment: @GeoffRobinson: I don't know. These are all I know, but Euler is a oneway street.
Answer: Let $x\ge 2$. Then since $2$ is a primitive root of $3^2$, it is a primitive root of $3^x$. It follows that $2$ has order $\varphi(3^x)=2\cdot 3^{x-1}$ modulo $3^x$.
(One can prove the order result with less machinery.)
Thus the "trivial" Euler's Theorem solutions are the only ones.
Answer: Do not know if you consider this not trivial, but by Euler's theorem, and the fact that $\phi(3^x)=2\cdot3^{x-1}$, you get the set of solutions $(x,k\cdot2\cdot3^{x-1})$ for any $k,x$ positive integers
Comment: I do not see a question. This seems a bit chatty or such.
Seems like a case of ' not a real question '.

Remainder of $2^y$ and $3^y$


Finding circumcenter

Question: In a triangle A(1,2) B(2,3) C(3,1) and $\angle A = cos^{-1}(4/5)$, $\angle B = \angle C = cos^{-1}(\frac{1}{\sqrt{10} }) $ Ordinate of circumcentre of the $\triangle$ is ?

I have tried solving by finding the equation for line perpendicular to AC and BC and then finding the intersection point. The ordinate I found was 11/3, but the answer provided is 0. Can anyone pls solve this using the angles provided, and also tell me whether my method is correct or not? Thanks.
Answer: Your method is correct but the calculation may be off because it is $\frac{11}{6}$ . There is no way it can be $0$ though.
The angles were probably given because the circumcentre's Y co-ordinate can also be expressed as:
$$Y_c=\frac{y_1sin2A+y_2sin2B+y_3sin2C}{sin2A+sin2B+sin2C}$$
Where $y_1,y_2,y_3$ are the ordinates of the vertices and A,B,C are the angles at those vertices.
Comment: +1 And what about the angles?
Comment: Check out the edit.

Finding circumcenter


Filter out digits from a CSV File using Java

Question: I am new to CSV Parsing. I have a CSV file where the 3rd column (a description field) may have one or more 6 digit numbers along with other values. I need to filter out those numbers and write them in the adjacent column corresponding to each row.
Eg:
3rd column                       4th column
=============                    ===========
123456adjfghviu77                123456

shgdasd234567                    234567

123456abc:de234567:c567890d      123456-234567-567890

12654352474

Please help. This is what I have done so far.
        String strFile="D:/Input.csv";
        CSVReader reader=new CSVReader(new FileReader(strFile));

        String[] nextline;
        //int lineNumber=0;
        String str="^[\\d|\\s]{5}$";
        String regex="[^\\d]+";

        FileWriter fw = new FileWriter("D:/Output.csv");
        PrintWriter pw = new PrintWriter(fw);

        while((nextline=reader.readNext())!=null){
            //lineNumber++;
            //System.out.println("Line : "+lineNumber);
            if(nextline[2].toString().matches(str)){
            pw.print(nextline[1]);
            pw.append('\n');
            System.out.println(nextline[2]);
            }

        }
        pw.flush();

Comment: *may have one or more 6 digit numbers along with other values* -> You have to show us sample input and output
Comment: You forgot to add the appropriate output for the given input.
Comment: @RiteshSatapathy you are the one setting the problem, so you should tell us what you want in that case...
Comment: The issue is that you are simply checking if the regex pattern _matches_ and then printing the line if it does. You need to use capturing groups and print the _submatches_ instead.
Comment: @Ritesh: http://ideone.com/pzXA3c. Just use `"\\d{6}"`  with `Matcher#find()`.
Comment: sorry...updated the question with the sample input.
Comment: _could you please give me an example ?_
Comment: What should be the output, if the 3rd column is '123456adjfghviu77'?
Comment: @WiktorStribiżew I think this should be posted as an answer (and be accepted).
Comment: @RiteshSatapathy: Have you had a look at my sample code? Is working as expected?
Comment: @WiktorStribiżew the problem here is not with the string, but with reading one or more strings from a cell in a csv file.
Comment: Actually, that is a question to you. See the [updated code example](http://ideone.com/pzXA3c): for  "123456adjfghviu77234567", it will produce `123456`, `772345`.
Comment: @vefthym please see the update qn..
Comment: Try http://ideone.com/1ikOew
Comment: @WiktorStribiżew you have proposed the best solution. just try to use a StringBuilder in your example.
Comment: @RuudyGarcia: see my answer, but from what I know, string concatenation is ok in Java since under the scenes it uses StringBuilder.
Answer: I suggest just matching 6-digit chunks, and build a new string when collecting matches:
String s = "123456abc:de234567:c567890d";
StringBuilder result = new StringBuilder();
Pattern pattern = Pattern.compile("(?<!\\d)\\d{6}(?!\\d)");  // Pattern to match 6 digit chunks not enclosed with digits
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    if (result.length() == 0)  {              // If the result is empty
        result.append(matcher.group(0));      // add the 6 digit chunk
    } else {
       result.append("-").append(matcher.group(0)); // else add a delimiter and the digits after it
    }
}
System.out.println(result.toString());      // Demo, use this to write to your new column

See the Java demo
UPDATE: I have changed the pattern from "\\d{6}" to "(?<!\\d)\\d{6}(?!\\d)" to make sure we only match 6-digit chunks that are not enclosed with other digits.
See the regex demo
Comment: @RiteshSatapathy: Imagine you read a question from a stranger. What should I understand from your comment? *I need to get something  from something else to turn it into something more else*. Please be specific. What are the *criteria* for *matching*? 6-digit chunk that is not enclosed with other digits? Then you need a `"(?<!\\d)\\d{6}(?!\\d)"` regex.
Comment: thanks for this, however it keeps on appending the values..i need separate outputs for separate rows
Comment: Also, you need to reset the StringBuilder (just place it in the right place in your code) each time you are reading a new row.
Comment: please I apologize, but if you see the qn, i have updated the the input and output. 3rd column is the input column and 4th column is the output column
Answer: All righ, this is what you need to do to get the digits in the third column  :
while((nextline=reader.readNext())!=null){
     //For every column (columnNumber)
     String digitsInColumn = nextline[columnNumber].replaceAll("\\D+","");
     // Your treatment

}

Comment: I agree with this..but if that cell has multiple 6 digits values.. i mean something like this `123456hdfhg, sdfg567890`...it will append them together..but i dont want that, i want them separate in another cell
Comment: Well it can't have a comma like in your example, elswhere it won't be the same column. In your explanation. What you said "may have one or more 6 digit numbers along with other values. I need to filter out those numbers and write them in the adjacent column corresponding to each row". digitsInColumn will have the digits in this column, you have to do the same thing for every column to get the digits
Comment: @RiteshSatapathy how would you append the result of 123456adjfghviu77234567 in next column of your output csv file ? Your problem lacks of spec of this usecase
Comment: My bad..the separators are not comma, they are `;` or `:`
Comment: In this case I think that @Wiktor Stribiżew's solution is the one to choose. You have just to loop over the matcher's result using a StringBuilder and add the result to the output csv


Show drop down box with values when select value from another dropdown

Question: I need to show a new drop down box upon selecting a value from another drop down box which is already available in the page. First drop down is already available in the page and second will be hidden based on boolean value I am getting from Bean class.
The problem is the hidden drop down is not visible until I refresh the page. When I refresh the page, then only I can see the hidden drop down box. When I unselect another value from first drop down box, the second dropdown should be hidden which is also happening, but I have to refresh the page.
See my code below for reference:
instrumentDetails.xhtml

        <h:outputText id="product_Group"
            value="#{msg.instrument_add_edit_product_group}" escape="false" />
        <a4j:region>
            <h:selectOneMenu
                value="#{instrumentBean.instrumentData.productGroupId}"
                valueChangeListener="#{instrumentBean.populateProductTypeByServiceProvider}"
                style="width:140px" styleClass="dropDown">
                <f:selectItem itemValue="0"
                    itemLabel="#{msg['gobal.select.default.label']}" />
                <f:selectItems var="productGroupItem"
                    itemValue="#{productGroupItem.id}"
                    itemLabel="#{productGroupItem.label}"
                    value="#{referenceMaster.productGroupLabelKeyList}" />
                <a4j:ajax event="valueChange"   render="productTypeListInstrument,servList,showServiceId"
                    execute="@this" />
            </h:selectOneMenu>
        </a4j:region>

<a4j:outputPanel ajaxRendered="true" id ="showServiceId" rendered="#{instrumentBean.showService}">
        <h:outputText id="serviceId" value="#{msg.instrument_add_edit_service}"
            escape="false" />
        <h:selectOneMenu value="#{instrumentBean.instrumentData.service}"
            style="width:140px" styleClass="dropDown" >
            <f:selectItem itemValue="0" itemLabel="Mobile" />
            <f:selectItem itemValue="1" itemLabel="Telephone" />
            <f:selectItem itemValue="2" itemLabel="ISDN BRI" />
        </h:selectOneMenu>
    </a4j:outputPanel>

InstrumentBean.java
private boolean showService;

    public void populateProductTypeByServiceProvider(ValueChangeEvent event) {
        try {
            Integer rowindex = new Integer(event.getNewValue().toString());
            if (!CommonUtil.isBlankInteger(instrumentData
                    .getServiceProviderId())
                    && !CommonUtil.isBlankInteger(rowindex)) {

                int productGroupId = rowindex.intValue();

                List<LabelKeyTO> labelKeyTOList = findProductsByGroupAndServiceProvider(
                        productGroupId, instrumentData.getServiceProviderId());

                Collections.sort(labelKeyTOList);
                this.productTypeDetailList = labelKeyTOList;
                setDefaultDetailsListSerRate();
                defaultServiceTable();

            } else {
                if (CommonUtil.isBlankInteger(instrumentData
                        .getServiceProviderId())) {
                    this.instrumentData.setProductGroupId(0);
                }
                this.instrumentData.setProductTypeId(0);
                setDefaultDetailsListProdSerRate();
                defaultServiceTable();
            }

            if(rowindex == 1){
                showService = true;
            }else if(rowindex == 2){
                showService = true;
            }else{
                showService = false;
            }

        } catch (Exception e) {
            this.instrumentData.setProductTypeId(0);
            setDefaultDetailsListProdSerRate();
            defaultServiceTable();
            String reasonFailure = e.getMessage();
            validationMessage(reasonFailure, reasonFailure, reasonFailure,
                    FacesMessage.SEVERITY_ERROR);
        }
    }

Comment: You already have implemented mechanism for re-rendering second drop down box when value in first box is changed (``). You need only check if rendering condition for parent of second drop down box working correctly: `rendered="#{instrumentBean.showService}"` a probably fix it.
Comment: @VasilLukach..  Dear Vasil, Thanks for your answer. As you can see above in my code, I have already used  : rendered="#{instrumentBean.showService}"  in my second drop down. But it is shown only after refreshing the page. This is the issue.  Kindly suggest on the same.
Comment: Related to http://stackoverflow.com/questions/4932810/valuechangelistener-is-invoked-on-submit-without-changing-options-in-selectoneme `ValueChangeListener` are only invoked on submit. You need to use AJAX to change the value server-side.
Answer: I have done it using 'listener'.
I have added the code in first dropdown for listener. Please see below the updated code :

<h:outputText id="product_Group"
    value="#{msg.instrument_add_edit_product_group}" escape="false" />
<a4j:region>
    <h:selectOneMenu
        value="#{instrumentBean.instrumentData.productGroupId}"
        valueChangeListener="#{instrumentBean.populateProductTypeByServiceProvider}"
        style="width:140px" styleClass="dropDown" >
        <f:selectItem itemValue="0"
            itemLabel="#{msg['gobal.select.default.label']}" />
        <f:selectItems var="productGroupItem"
            itemValue="#{productGroupItem.id}"
            itemLabel="#{productGroupItem.label}"
            value="#{referenceMaster.productGroupLabelKeyList}" />
        <a4j:ajax event="valueChange"   render="productTypeListInstrument,servList" execute="@this" />
        <a4j:ajax event="change"  listener="#{instrumentBean.onChangeProductGroup}" />
    </h:selectOneMenu>
</a4j:region>

Thanks for your answers guys.


Regex em Javascript: agrupando

Question: Como entrada por parte do usuário estou esperando pares de números separados por vírgulas:
// se for um par só
1-2

// se for mais de um par
1-2,3-4,5-6

Espero da saída algo assim:
[
  [1, 2],
  [3, 4],
  [5, 6]
]

Eu estou em dúvida em como obter essa saída em Javascript.
Código até aqui no JSFiddle (tá dando loop infinito): http://jsfiddle.net/cbLs8/7/
<input type="text" id="entrada" value="1-2,3-4,5-6"></input>
<button id="botao">Testar</button>

$("#botao").click(function () {
    var regex = new RegExp(/(\d+)-(\d+)/);
    var match;
    var string = $("#entrada").val();
    if (match = regex.exec(string)) {
        while (match !== null) {
            console.log(match);
            match = regex.exec(string)
        }
    } else {
        alert("no match");
    }
});

Comment: Que tal `/((\d+)-(\d+))+/`?
Comment: É isto que quer?: http://jsfiddle.net/cbLs8/8/
Answer: De forma simples, o delimitador para expressões regulares é a barra /. Se você passar uma string para o construtor, não deve passar as barras dentro da string, senão serão interpretadas como literais. Então use assim:
var regex = new RegExp(/(\d+)-(\d+)/);

Ou assim:
var regex = new RegExp("(\\d+)-(\\d+)");

Note o uso de duplo escapes para os dígitos. Um para o literal da string e outro para a regex propriamente dito.
Mas nem faz sentido declarar o tipo explicitamente, pode usar apenas assim:
var regex = /(\d+)-(\d+)/;

Agora, se você precisa usar o método exec múltiplas vezes na mesma string, deve habilitar a opção g:
var regex = /(\d+)-(\d+)/g;

Ou:
var regex = new RegExp("(\\d+)-(\\d+)", "g");

Isso é tudo, sua lógica funciona. Mas usar expressões regulares é realmente necessário? Para processamentos simples como o seu, usar uma regex é excessivo. Além de ser mais lento, deixa o código pouco legível. Você pode fazer o mesmo muito mais diretamente.
No caso, você tem uma sequencia de partes que usa a vírgula como separador
"1-2,3-4,5-6".split(",");
    // => ["1-2", "3-4", "5-6"]

Cada uma delas é um par separado por um hífen:
"1-2,3-4,5-6".split(",").map(function(s) {return s.split("-")});
    // => [["1", "2"], ["3", "4"], ["5", "6"]]

Você pode ainda transformar cada string em um número se quiser usando mais um nível de map.
Em resumo: Use regex para procurar por um padrão dentro de um texto maior ou para validar por alto uma entrada. Não use regex para fazer parse de strings, em particular nesses casos simples.
Comment: Dá pra dar um destaque na última parte? "Pra que regex" foi a primeira coisa que pensei quando li a pergunta.
Comment: Perfeito! Agradeço a sugestão Guilherme e @bfavaretto, realmente fica bem mais simples assim, com `split` e `map`. =)
Comment: @bfavaretto expliquei um pouco mais.
Comment: Valeu Guilherme!
Comment: A quem interessar ver no JSFiddle: http://jsfiddle.net/PU5CZ/2/
Answer: O seu problema está no while e na expressão regular que está utilizando. Para executá-la múltiplas vezes, você tem que utilizar a opção g. Veja mais detalhes no site da mozilla.
Utilize a expressão regular: /[(\d-\d)]+/gi
Exemplo
Html:

JavaScript:
var $out = $("#out");
var re = /[(\d-\d)]+/gi
var str = "1-2,3-4,5-6";

do{
    var x = re.exec(str);
    if (x == null)
        break;

    $out.append("
" + x + "
");
}while(x != null);

O exemplo está aqui: http://jsfiddle.net/andrenmaia/sNHqD/4/
Comment: Sua resposta foi útil, não sabia que tinha que ter o `g`. Obrigado!

Regex em Javascript: agrupando


What are the best LAN communication systems?

Question: What are the best messaging and VOIP systems for medium to large corporate networks?
What have you found to be the best in your experience and why?
It should support:

Instant messaging
Video and audio calls
File transfer
And it should be easy to setup - 10 servers with arcane configs, not accepted

Bonus features would be:

Conference calls (multiple participants)
Screen sharing

I expect a server/client setup, though a client-only solution (P2P) would be welcome as well.
If the system is open-source, then its perfect for my setup.
I've heard of:

Microsoft Communicator
IBM SameTime
BigAnt
Answer: Microsoft Office Communication Server 2007 R2 is an excellent product. It has all the features you've mentioned and more should you need them (like integrating with hardware PBX's and what not).
In my organisation we have 300 employees across 2 geographically distant sites so we had a Standard Edition OCS server at each site. The only downside is there is no easy way to manage contact lists for users you have to use the Resource Kit's LCSAddContacts.wsf script.
We started out using a Jabber Server which was free called OpenFire I think. It was simple and has LDAP integration but we favoured OCS in the end because of centralised administration of user accounts, it's video/voip functionality and the fact the client integrates seamlessly with Outlook and Sharepoint.
If you need more info just let me know.
Comment: I would hope that scripting is coming for the next release of OCS
Comment: As users don't need to add or approve eachother to start talking (just use the builtin search in the client) I don't see the scripting of user's contacts as a problem. If they want to add contacts to quickly spot presence they can do it manually, I can still chat with them regardless, one-click from their mail in Outlook or whatnot ^^
Comment: Thanks for the info, I'll look into it and let you know if I need help!
Comment: The contact list/script thing was only a problem for us because we wanted to keep the user experience as similar as possible to the Jabber/Pidgin setup we had which has contacts lists organised by team.

Oskar is completely correct though all users can find and communicate with each other without the need for the script.
Answer: You could always look at open-source solutions like freeswitch and asterisk... Pair either of those with a XMPP server like Openfire and their native Spark client or any flavor of XMPP client of your choosing, and you can do everything you're talking about very seamlessly.  There are a few pre-built distributed images you can use for $0.00.  Elastix might be just what you're looking for.
Answer: I've used OCS and I've used Sametime.  OCS just plain works. It's not a simple set up but you can get it going without too much trouble (it just alot of little things), and maintenance is relatively straightforward.   Sametime seems to need a herd of babysitters to keep it running everywhere I've used it, and of course it's not something you can just pick up because its pretty quirky in the way it works (although Notes admins seem to understand it- which should give you an idea of why it's not an install and run product).
I'd probably look at OCS, Bigant (open source et al) then finally, if I was forced to I'd evaluate Sametime.
Answer: Only one I've used is OCS. I've not been involved in the back-end config, so not sure how many servers are really required... if your environment is already a Microsoft Office/Exchange/Sharepoint, it may not be so hard as starting from scratch.
The Microsoft Office Communicator client is intuitive, and ties in with the other Microsoft products really well. You may consider that a pro or a con.
It's expensive, but very easy for users to pick up. No experience with any similar Open Source products, so I can't really offer suggestions there.
Could Skype work? Also very easy to use (managed to train my parents), quick to install (client side only needed). It offers IM, voice, video; but I realise it doesn't meet all of your requirements.
Finally, are you sure your network is ready for this? If you are all on one high-speed switched campus, you should be fine, but if you need to run over slower speed WAN links, you'll need to ensure that there is sufficient bandwidth - lots of point-to-point video streams will start hammering your network and affect other applications.
Comment: It doesn't need a lot of servers, a single Standard Edition server can support up to 5000 users. In terms of licensing it can get complicated because there are different levels of CALs and client licensing options.

In a corporate environment I'd never recommend using products like Skype, there are often clauses that mean any conversations over those products belong to the company (MSN Messenger used to have that clause and still might) plus you're trusting all your conversations to these other companies, not good if you are discussing private business
Answer: If you are looking for one big tool doing everything I think MS Office Communicator is a good choice.
For instant messaging, we use dMessage as a dedicated tool for IT support because you can send pop-ups to users according to their workstation configuration (presence of a specific file or application on the workstation, server ...).


SQL 2-table query results need to be concatenated

Question: My current SQL:
SELECT B.MESSAGENO, B.LINENO, B.LINEDATA
  FROM BILL.MESSAGE AS B, BILL.ACTIVITYAS A
  WHERE A.MSGNO = D.MESSAGENO AND A.FUPTEAM = 'DBWB'
    AND A.ACTIVITY = 'STOPPAY' AND A.STATUS = 'WAIT'
    AND A.COMPANY = D.COMPANY

MESSAGENO   LINENO  LINEDATA
1234567     1       CHEQUE NO  : 9999999               RUN NO    : 55555
1234567     2       DATE ISSUED: 12/25/2020            AMOUNT    : 710.51
1234567     3       PAYEE      : LASTNAME, FIRSTNAME
1234567     4       ACCOUNT NO : 12345-67890
1234567     5       USER       : USERNAME

there are 550 sets of 5 lines per MESSAGENO
What I am trying to figure out is how I can get something like where LINENO = 1, concatenate LINEDATA so I just get 9999999 as checkno, where LINENO = 2, concatenate LINEDATA so I get 710.51 as amount, where LINENO = 3, concatenate LINEDATA so I get LASTNAME, FIRSTNAME as payee, where LINENO = 4, concatenate LINEDATA so I get LASTNAME, FIRSTNAME as payee, and lastly, the same thing for USERNAME.
I just cannot seems to conceptualize this. Every time I try, my brain starts turning into macaroni. Any help is appreciated.
Comment: @marc_s thanks for the input. It was a very good read and definitely something I need to start incorporating into my future work.
Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was replaced with the *proper* ANSI `JOIN` syntax in the ANSI-**92** SQL Standard (**almost 30 years** ago) and its use is discouraged
Comment: So this entire thing is in one entry: `CHEQUE NO  : 9999999               RUN NO    : 55555`
Comment: @ChrisStrickland yes. each LINEDATA field is a character field of 70
Comment: Aside from a horrible structure to work with getting your data, you have SQL listed but that is generic.  Which specific database.. Sql-Server, MySQL, Oracle, etc.  And if you can change this data structure now before its too late, I would strongly consider.  Also, for the line data.  Are they FIXED POSITION values, especially check/run and date/amount?  Especially trying to parse.  If so fixed, please confirm ordinal position of the starting values might help too.
Answer: UPDATED ANSWER, extracts all fields from stored strings:
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e22d26866053ea6088aa78dc23c4d809
Check this fiddle.
It uses a SUBSTRING_INDEX in the internal query to split the fields at the : or by a combination of : and "  ".  I used the two spaces because I wasn't sure what your actual whitespace was, and when I copied the data out of your post it was just spaces.
Then MAX is used in the outer query to get everything on one line,  grouping by the messageNo.  Since some lines have two pieces of data to extract, a second string parser was added.  Here is the code from the fiddle, for reference.  In this case, the table test was created from the output of OP's initial query, since I didn't have enough info to build both tables and completely recreate his output.
SELECT MESSAGENO,
    MAX(if(LINENO = 1, extractFirst, null)) as checkNo,
    MAX(if(LINENO = 1, extractLast, null)) as runNo,
    MAX(if(LINENO = 2, extractFirst, null)) as issued,
    MAX(if(LINENO = 2, extractLast, null)) as amount,
    MAX(if(LINENO = 3, extractFirst, null)) as payee,
    MAX(if(LINENO = 4, extractFirst, null)) as accountNo,
    MAX(if(LINENO = 5, extractFirst, null)) as username

FROM (
    SELECT MESSAGENO, LINENO,
        trim(substring_index(substring_index(LINEDATA, ": ", -2), "  ", 1)) as extractFirst,
        trim(substring_index(LINEDATA, ":", -1)) as extractLast
    FROM test
) z
GROUP BY MESSAGENO

Again, you will be much better off to alter your tables so that you can use simpler queries, as shown in the last fiddle.
===============================================
ORIGINAL ANSWER (demo of string parsing, suggestion for data model change)
You can achieve this with some string parsing BUT ABSOLUTELY DO NOT unless you have no choice.  The reason you are having trouble is because your data shouldn't be stored this way.
I've included a fiddle incorporating this case statement and substring_index to extract the data.  I have assumed mySQL 8 because you didn't specify SQL version.
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=068a49a2c819c08018691e54bcdf91e5
case when LINENO = 1 then trim(substring_index(substring_index(LINEDATA, "RUN NO", 1), ":", -1))
    else trim(substring_index(LINEDATA, ":", -1)) end
  as LDATA

See this fiddle for the full statement.  I have just inserted the data from your join into a test table, instead of trying to recreate all your tables, since I don't have access to all the data I would need for that.  In future, set up a fiddle like this one with some representative data and the SQL version, and it will be easier for people to help you.
=========================================
I think this is a better layout for you, with all data stored as the proper type and a field defined for each one and the extra text stripped out:
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=11d52189b005740cdc53175466374635
Comment: Thanks Chris. I think I could've done a better job of explaining. Your first fiddle is almost what I need, except I was looking for a result like your second fiddle's result, where each LINEDATA concatenated would be in its own column. I'm going to play around with CASEs and perhaps I will stumble upon the solution. Thank you again sir! Very illuminating.
Comment: I don't think you're using concatenated correctly.  So you need to produce something like the second fiddle?  I can adjust for that, give me just a second.


O Texto do banco de dados não aparece no TDBMemo

Question: Tenho uma tabela que uma das colunas é ligada a um TDBMemo só que os texto que está na tabela não aparece no TDBMemo quando a tabela está aberta, tanto em modo de Execução como no de Design.
Já verifiquei todas as ligações com a tabela e está tudo correto...
Answer: Não sei ao certo o porque disso acontecer mais para repara basta apagar a TFDtabel e o DataSource no Delphi e reponha novos e faça todas as ligações com o Banco de dados e pronto ele ira funcionar perfeitamente...


Property doesn't update when set in the Business Logic

Question: I need to set a property in the Business Logic with a method in the Business Logic. If you run my code you can see the first String "Target Location" changes successfully, but the second one "Some Other String" doesn't change its value in the view. "PropertyChanged" in the BusinessLogic.cs is null. I have absolutely no idea WHY it's null! Can someone explain me this behaviour and how I can fix this?
I have the following files in my project:
MainWindow.xaml
<Window x:Class="TestWpf.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestWpf"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <TextBox Text="{Binding Path=TargetLocation}"></TextBox>
    <TextBox Text="{Binding Path=SomeOtherString}"></TextBox>
    <Button Click="ChangeTextButton_Click">Change Target Location</Button>
    <Button Click="ChangeSomeOtherStringButton_Click">Change some other string</Button>
</StackPanel>

MainWindow.xaml.cs
public MainWindow()
{
    InitializeComponent();

    MainViewModel mainViewModel = new MainViewModel();
    mainViewModel.TargetLocation = @"A:\Old_Location";
    mainViewModel.SomeOtherString = "Old String...";

    DataContext = mainViewModel;
}

private void ChangeTextButton_Click(object sender, RoutedEventArgs e)
{
    MainViewModel mainViewModel = (MainViewModel)DataContext;
    mainViewModel.TargetLocation = @"B:\New_Location";
}

private void ChangeSomeOtherStringButton_Click(object sender, RoutedEventArgs e)
{
    MainViewModel mainViewModel = (MainViewModel)DataContext;
    mainViewModel.ChangeSomeOtherString();
}

MainViewModel.cs
public class MainViewModel : INotifyPropertyChanged
{
    private string targetLocation;

    public string TargetLocation
    {
        get
        {
            return targetLocation;
        }
        set
        {
            targetLocation = value;
            OnPropertyChanged("TargetLocation");
        }
    }

    public string SomeOtherString
    {
        get
        {
            return BusinessLogicClass.GetInstance().SomeOtherString;
        }
        set
        {
            BusinessLogicClass.GetInstance().SomeOtherString = value;
            OnPropertyChanged("SomeOtherString");
        }
    }

    public void ChangeSomeOtherString()
    {
        BusinessLogicClass.GetInstance().ChangeSomeOtherString();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

BusinessLogicClass
public class BusinessLogicClass : INotifyPropertyChanged
{
    private static BusinessLogicClass instance;

    public static BusinessLogicClass GetInstance()
    {
        if (instance == null)
        {
            instance = new BusinessLogicClass();
        }

        return instance;
    }

    private BusinessLogicClass()
    {

    }

    private string someOtherString;

    public string SomeOtherString
    {
        get
        {
            return someOtherString;
        }
        set
        {
            someOtherString = value;
            OnPropertyChanged("SomeOtherString");
        }
    }

    public void ChangeSomeOtherString()
    {
        SomeOtherString = "New String!";
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Answer:
"PropertyChanged" in the BusinessLogic.cs is null. I have absolutely no idea WHY it's null!

PropertyChanged in the BusinessLogic class is null because there are no bindings that use properties in this class as their source.  The source properties for both of your bindings are on your MainViewModel class.
WPF doesn't scan through all classes that happen to implement INotifyPropertyChanged.  And even if it did, how would it know that a PropertyChanged event fired from your BusinessLogic class means that it needs to update the TextBox bound to the SomeOtherString property on your MainViewModel?  WPF can't read your code to find this out.
The simplest fix is to fire a PropertyChanged event inside your ChangeSomeOtherString() method:
    public void ChangeSomeOtherString()
    {
        BusinessLogicClass.GetInstance().ChangeSomeOtherString();
        OnPropertyChanged("SomeOtherString");    // Add this line
    }

This way WPF knows that the value of the SomeOtherString property has changed and will perform the necessary update to the TextBox.
Comment: Thank you very much for the explanation! The fix works for me :)


A sequence doesn't converges $\iff\exists\epsilon _0 >0$ and a subsequence $(x_{n_k})$ of $(x_n)$ such that $d(x_{n_k},x^*) \geq \epsilon _0$

Question: Prove that sequence doesn't converges $\iff\exists\epsilon _0 >0$ and a subsequence $(x_{n_k})$ of $(x_n)$ such that $d(x_{n_k},x^*) \geq \epsilon _0$
My try:
Definition of not convergence: there exists $\epsilon _0 >0$ such that $\forall N=N(\epsilon_ 0)\in \mathbb{N}$ exists $n\geq N$ such that $d(x_n,x^*)\geq \epsilon _0$.

For $N=1$ exits $n_1 \geq 1$ such that $d(x_{n_1},x^*)\geq \epsilon _0$.
For $N= n_1 +1, n_2 \geq N >n_1$ such that $d(x_{n_2},x^*)\geq \epsilon _0$
If $n_1<n_2<...<n_k$ are such that $d(x_{n_j},x^*)\geq \epsilon _0$, we choose $N=n_k+1, n_k+1 \geq N$ such that $(d(x_{k+1},x^*) \geq \epsilon _0$.
Finally, we obtain the subsequence $(x_{n_k})$ of $(x_n)$ such that $d(x_{n_k},x^*) \geq \epsilon _0$

I don't know if this is enough to prove both inclusions. Any suggestions would be great!
Comment: Your proof only works for $\Longrightarrow$. But can be shortened to: leong the subsequent to be just the original sequence $(x_n)$.
Comment: I know this is a silly thing to say, but this is just the negation of "a sequence converges iff all its subsequences have the same limit", so you can use that proof (which is in every textbook) and conclude this statement is true by contrapositive.
Answer: For the direction of $\Longleftarrow$:
Suppose on the contrary the sequence $(x_n)$ converges. Then for any $\epsilon>0$, there is some $M\in\mathbb{N}$ such that whenever $n\geq M$, one has $d(x_n,x)<\epsilon$. But by assumption, there is a subsequence $(x_{n_k})$ such that there exists $\epsilon_0>0$, $ N\in\mathbb{N}$ such that $d(x_{n_k},x)\geq\epsilon_0$ (for all $n_k\geq N$). Choose $\epsilon=\epsilon_0$. Then we get a contradiction.
Answer: A sequence $(x_n)_{n\in \Bbb N}$ converges to $x^*$ in a metric space  $(X,d)$ iff $\{n\in \Bbb N:x_n\not \in B_d(x^*,r)\}$ is finite whenever $r>0,$  ... where $B_d(x^*,r)=\{y\in X:d(y,x)<r\}.$  This comes directly from  the def'n of $\lim_{n\to \infty}d(x_n,x^*)=0.$
So suppose $(x_n)_{n\in \Bbb N}$ does not converge to $x^*.$ Take  $\epsilon_0=r>0$   such that the set$S=\{n\in \Bbb N:x_n\not \in B_d(x^*,r)\}$ is infinite.  Then $(x_n)_{n\in S}$ is the desired sub-sequence.


Como obter múltiplos JSONObject com a mesma key?


Basic formula of Probability

Question: I was wondering how probability of an event is equal to favourable cases/total cases
like on tossing a coin probaility of getting a head is 1/2 so why is it alwars favourable cases/total cases Does this formula or law has any proof.
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: It's not clear what you're asking. The description of probability as "favorable cases/total cases" is too vague to prove (or to use as a definition). Is there a task you're having trouble with, or can you elaborate on your concern?
Comment: This is very vague.  It is certainly true that the first examples of probability one usually encounters are just counting, as you say.  That corresponds to a  *uniform* probability distribution on the set of possible outcomes.  But you can have non-uniform outcomes.  Maybe your coin is biased, in which case the probability of getting $H$ is not $\frac 12$, for instance.
Comment: the Laplace formula, favourable cases divided by total cases, is used when we think that the random variable involved have an uniform distribution, that is, that any of it values it equally likely to occur
Answer: The (# favorable outcomes)/(# total outcomes) rule does not always hold. It is only true when there are finitely many outcomes, and these outcomes are all equally likely. Given these two assumptions, here is how you prove that the rule works:
Theorem: In a probability space $\Omega$ with finitely many outcomes where all outcomes are equally likely, $P(E)=|E|/|\Omega|$ for any event, $E$.
Proof: Let $n=|\Omega|$, and let $\omega_1,\omega_2,\dots,\omega_n$ be the complete list of outcomes.
Let $p$ be the probability of any particular outcome. Using the axiom $P(\Omega)=1$, we have
$$
1=P(\Omega)=P(\{\omega_1,\dots,\omega_{n}\})\stackrel{*}=P(\{\omega_1\})+\dots+P(\{\omega_n\})=p+\dots+p=np
$$
We can then solve for $p$, getting $p=1/n$. Finally, for any event $E$ with $k$ outcomes $e_1,\dots,e_k$, we have
$$
P(E)=P(\{e_1,\dots,e_k\})\stackrel{*}=P(\{e_1\})+\dots+P(\{e_k\})=\frac1n+\dots+\frac1n=\frac kn=\frac{|E|}{|\Omega|}
$$
The claim has been proven. To be crystal clear, in the $\stackrel{*}=$ equations, we use the probability axiom $P(A\cup B)=P(A)+P(B)$ whenever $A$ and $B$ are disjoint events.  This further implies that $P(A_1 \cup \dots \cup A_n)=P(A_1)+\dots+P(A_n)$ whenever the events $A_1,\dots,A_n$ are pairwise disjoint, which can be proven by induction on $n$.

The assumption of all outcomes being equally likely is essential. For example, say you had a loaded die where the six face is more likely to come up than the other faces (because the opposite face, one, has the fewest pips, so is heaviest). Specifically, suppose the probability of rolling six is $25\%$, and the probability of rolling any other face is $15\%$. To compute the probability of the event of rolling an even number, the rule (# good outcomes)/(# total outcomes) would give $3/6$, which is incorrect. The correct answer is $$P(\text{even})=P(\{2,4,6\})=P(\{2\})+P(\{4\})+P(\{6\})=0.15+0.15+0.25 = 0.55$$

Basic formula of Probability


Which test to use to see if tumor weight increases at different stages?

Question: I have 60 cancer patients. I have checked their staging and the weight of their tumour in gram. One variable is cancer staging - Stage 1, Stage 2, Stage 3 and Stage 4 (in increasing order). Another variable is Tumour weight - a continuous variable. I want to check as stage increases from Stage 1 to 4, whether tumour weight also increases. Could you please suggest which test should I use?
Comment: Have you seen the [UCLA test decision tree](http://www.ats.ucla.edu/stat/mult_pkg/whatstat/)?
Answer: You may be interested in Cuzick's trend test. This is available as the function "nptrend" in Stata, but I couldn't find an official version in R. A user-contributed version of the test in R is here.
Comment: @gung I don't believe [nptrend](http://www.stata.com/manuals13/rnptrend.pdf#page=3) requires panel data. You just need the groups to be ordered.
Comment: Is that a within patients test? It's not clear if these are repeated measures.
Answer: You could consider ordinal logistic regression with stage as your dependent variable and weight as an independent variable.
heres a nice tutorial:
http://www.ats.ucla.edu/stat/r/dae/ologit.htm
Comment: Isn't tumor size the outcome?
Comment: logistic regression is fancy like that


How to combine multiple text entries for a variable once dplyr has grouped by another variable

Question: For hundreds of matters, my data frame has daily text entries by dozens of timekeepers.  Not every timekeeper enters time each day for each matter.  Text entries can be any length.  Each entry for a matter is for work done on a different day (but for my purposes, figuring out readability measures for the text, dates don't matter).  What I would like to do is to combine for each matter all of its text entries.
Here is a toy data set and what it looks like:
> dput(df)
structure(list(Matter = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
3L, 4L, 4L), .Label = c("MatterA", "MatterB", "MatterC", "MatterD"
), class = "factor"), Timekeeper = structure(c(1L, 2L, 3L, 4L,
2L, 3L, 1L, 1L, 3L, 4L), .Label = c("Alpha", "Baker", "Charlie",
"Delta"), class = "factor"), Text = structure(c(5L, 8L, 1L, 3L,
7L, 6L, 9L, 2L, 10L, 4L), .Label = c("all", "all we have", "good men to come to",
"in these times that try men's souls", "Now is", "of", "the aid",
"the time for", "their country since", "to fear is fear itself"
), class = "factor")), class = "data.frame", row.names = c(NA,
-10L))

Dplyr groups the time records by matter, but I am stumped as to how to combine the text entries for each matter so that the result is along these lines -- all text gathered for a matter:
1   MatterA Now is the time for all good men to come to
5   MatterB the aid of their country since
8   MatterC all we have
9   MatterD to fear is fear itself in these times that try men's souls

dplyr::mutate() does not work with various concatenation functions:
textCombined <- df %>% group_by(Matter) %>% mutate(ComboText = str_c(Text))
textCombined2 <- df %>% group_by(Matter) %>% mutate(ComboText = paste(Text))
textCombined3 <- df %>% group_by(Matter) %>% mutate(ComboText = c(Text)) # creates numbers

Maybe a loop will do the job, as in "while the matter stays the same, combine the text" but I don't know how to write that.  Or maybe dplyr has a conditional mutate, as in "mutate(while the matter stays the same, combine the text)."
Thank you for your help.
Comment: `df %>% group_by(Matter) %>% summarise(ComboText = paste0(Text, collapse = " "))`
Answer: Hi you can use group by and summarise with paste,
> df %>% group_by(Matter) %>% summarise(line= paste(Text, collapse = " "))

# A tibble: 4 x 2
#  Matter  line
#  <fct>   <chr>
#1 MatterA Now is the time for all good men to come to
#2 MatterB the aid of their country since
#3 MatterC all we have
#4 MatterD to fear is fear itself in these times that try men's souls


How do I show the username field in the user edit form?

Question: I need to show username textfield in user edit form. Normally, it shows only for administrator user. How do I show this for all users' edit form?
Answer: Go to admin/people/permissions and select the Change own username for the roles you need to be able to change their username.