text:
Q: How can I add a Path, that has been defined in the XAML ResourceDictionary, multiple times to a WPF form at runtime? I have a defined path in XAML:
<UserControl.Resources>
    <ResourceDictionary>
        <Path x:Key="N44" Width="20" Height="80" Stretch="Fill" Fill="#FF000000" Data="M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z "/>
    </ResourceDictionary>
</UserControl.Resources>

I want to add it to a WPF Gird & doing it once like this works:
System.Windows.Shapes.Path aPath = new System.Windows.Shapes.Path();
aPath = (System.Windows.Shapes.Path)this.Resources["N44"];
LayoutRoot.Children.Add(aPath);

However if I add this code on a button click event and then click the button twice, an error is thrown stating

"Specified Visual is already a child
  of another Visual or the root of a
  CompositionTarget."

I then attempted to create two instances of the resource but I have continued to receive the same error. Below is the code that I used for this test:
private void cmbTest_Click(object sender, System.Windows.RoutedEventArgs e)
  {
   System.Windows.Shapes.Path aPath = new System.Windows.Shapes.Path();
   aPath = (System.Windows.Shapes.Path)this.Resources["N44"];

   if (LayoutRoot.Children.Contains(aPath) == true){
    System.Windows.Shapes.Path bPath = (System.Windows.Shapes.Path)this.Resources["N44"];
    LayoutRoot.Children.Add(bPath);
   }else{
    aPath.Name = "a";
    aPath.Tag = "a";
    LayoutRoot.Children.Add(aPath);
   }
  }

As such, how can I add an XAML Path, which has been defined in the ResourceDictionary, multiple times to a WPF form at runtime?

A: Just create style for Path, and apply it.

A: There's an easier, built-in way to do this.
Set x:Shared="False" on the resource. This will allow it to be reused. Then use it as many times as you want.
<UserControl.Resources>
    <ResourceDictionary>
        <Path x:Shared="False" x:Key="N44" Width="20" Height="80" Stretch="Fill" Fill="#FF000000" Data="..."/>
    </ResourceDictionary>
</UserControl.Resources>

A: I've since found that I had missed an important part of the documentation from MSDN:

Shareable Types and UIElement Types:
A resource dictionary is a technique for
  defining shareable types and values of
  these types in XAML. Not all types or
  values are suitable for usage from a
  ResourceDictionary. For more
  information on which types are
  considered shareable in Silverlight,
  see Resource Dictionaries.
In particular, all UIElement derived
  types are not shareable unless they
  come from templates and application of
  a template on a specific control
  instance. Excluding the template case,
  a UIElement is expected to only exist
  in one place in an object tree once
  instantiated, and having a UIElement
  be shareable would potentially violate
  this principle.

Which I will summarise as, that's not the way it works because it's not creating a new instance each time I execute that code – it's only creating a reference to the object – which is why it works once but not multiple times.
So after a bit more reading I've come up with 3 potential ways for a resolution to my problem.
1) Use a technique to create a deep copy to a new object. Example from other StackOverflow Question - Deep cloning objects
2) Store the XAML in strings within the application and then use the XAML reader to create instances of the Paths:
System.Windows.Shapes.Path newPath = (System.Windows.Shapes.Path)System.Windows.Markup.XamlReader.Parse("<Path xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'  Width='20' Height='80' Stretch='Fill' Fill='#FF000000' Data='M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z ' HorizontalAlignment='Left' VerticalAlignment='Top' Margin='140,60,0,0'/>");
LayoutRoot.Children.Add(newPath);

3) Only store the Path data in the Resource Dictionary. Create a new instance of a Path in code, apply the Path data to the new Path and then add the other properties I am interested in manually.
The XAML - The Path data is stored as a StreamGeometry:
<UserControl.Resources>
    <ResourceDictionary>
        <StreamGeometry x:Key="N44">M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z</StreamGeometry>
    </ResourceDictionary>
</UserControl.Resources>

The C# code to then create an instance and apply the other values:
System.Windows.Shapes.Path bPath = new System.Windows.Shapes.Path();
bPath.Data = (System.Windows.Media.Geometry)this.FindResource("N44");

bPath.Width = 20;
bPath.Height = 80;

bPath.VerticalAlignment = System.Windows.VerticalAlignment.Top;
bPath.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

left = left + 40;

System.Windows.Thickness thickness = new System.Windows.Thickness(left,100,0,0);
bPath.Margin = thickness;

bPath.Fill = System.Windows.Media.Brushes.Black;
LayoutRoot.Children.Add(bPath);


text:
Q: Training a model with LUIS using Phrase List Features with overlapping words I have a word for example ABC SSS. I need this to be recognised as one entity. At the same time this ABC SSS phrase precedes a lot of other words that need to be recognised as one entity which are not interchangeable. For example ABC SSS word. How can I train LUIS to be able to do this. I tried ABC SSS as a phrase feature but then LUIS doesn't recognise ABC SSS word as an entity. Currently, I marked ABC SSS as a feature phrase and word as a separate feature phrase. This is not ideal. Thanks for your help.

A: You'll want to create composite entities, not use phrase lists for this.
Here's a screenshot of the entities creation page on LUIS. I've created three simple entities and one composite entity which takes the other three entities:

Here are some snippets from a response I got from LUIS on a query. This first bit indicates the actual query and matched intent.
"query": "order large pepperoni pizza",
"topScoringIntent": {
    "intent": "OrderPizza",
    "score": 0.9999995
},

Under the entities list you'll find your simple and composite entities together, like the following.
{
    "entity": "large",
    "type": "PizzaSize",
    "startIndex": 6,
    "endIndex": 10,
    "score": 0.9186653
},
{
    "entity": "large",
    "type": "Pizza", // This is the composite entity!
    "startIndex": 6,
    "endIndex": 10,
    "score": 0.940835536
}

And here is the list for composite entities:
"compositeEntities": [
    {
      "parentType": "Pizza",
      "value": "large",
      "children": [
        {
          "type": "PizzaSize",
          "value": "large"
        }
      ]
    },
    {
      "parentType": "Pizza",
      "value": "pepperoni",
      "children": [
        {
          "type": "PizzaTopping",
          "value": "pepperoni"
        }
      ]
    },
    {
      "parentType": "Pizza",
      "value": "pizza",
      "children": []
    }
]

A: Composite Entities are ideal for this case:
Set "ABC SSS" as an entity 1, but then tag "ABC SSS" plus those other words into a composite entity 2. This should be enough to both capture "ABC SSS" as entity 1 and the whole sentence as entity 2 in the case those other phrases appear.
Also, you can also tag those other words as Entities by themselves if you want to capture them while you are on it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C API for Quantifiers I want to solve constraints that contain quantifiers using Z3 C API.
I am struggling to use the functions like "Z3_mk_exists()" as I don't find any example either online or in the test examples in the tar file.
I don't exactly understand all the arguments required by these functions and exact significance of them.
Can anyone help?
Thanks.
Kaustubh.

A: Here is a complete example with universal quantifiers. Comments are inline:
Z3_config cfg = Z3_mk_config();
Z3_set_param_value(cfg, "MODEL", "true");
Z3_context ctx = Z3_mk_context(cfg);
Z3_sort intSort = Z3_mk_int_sort(ctx);
/* Some constant integers */
Z3_ast zero  = Z3_mk_int(ctx, 0, intSort);
Z3_ast one   = Z3_mk_int(ctx, 1, intSort);
Z3_ast two   = Z3_mk_int(ctx, 2, intSort);
Z3_ast three = Z3_mk_int(ctx, 3, intSort);
Z3_ast four  = Z3_mk_int(ctx, 4, intSort);
Z3_ast five  = Z3_mk_int(ctx, 5, intSort);

We create an uninterpreted function for fibonacci: fib(n). We'll specify its meaning with a universal quantifier.
Z3_func_decl fibonacci = Z3_mk_fresh_func_decl(ctx, "fib", 1, &intSort, intSort);

/* fib(0) and fib(1) */
Z3_ast fzero = Z3_mk_app(ctx, fibonacci, 1, &zero);
Z3_ast fone  = Z3_mk_app(ctx, fibonacci, 1, &one);

We're starting to specify the meaning of fib(n). The base cases don't require quantifiers. We have fib(0) = 0 and fib(1) = 1.
Z3_ast fib0 = Z3_mk_eq(ctx, fzero, zero);
Z3_ast fib1 = Z3_mk_eq(ctx, fone,  one);

This is a bound variable. They're used within quantified expressions. Indices should start from 0. We have only one in this case.
Z3_ast x = Z3_mk_bound(ctx, 0, intSort);

This represents fib(_), where _ is the bound variable.
Z3_ast fibX = Z3_mk_app(ctx, fibonacci, 1, &x);

The pattern is what will trigger the instantiation. We use fib(_) again. This means (more or less) that Z3 will instantiate the axiom whenever it sees fib("some term").
Z3_pattern pattern = Z3_mk_pattern(ctx, 1, &fibX);

This symbol is only used for debugging as far as I understand. It gives a name to the _.
Z3_symbol someName = Z3_mk_int_symbol(ctx, 0);

/* _ > 1 */
Z3_ast xGTone = Z3_mk_gt(ctx, x, one);
Z3_ast xOne[2] = { x, one };
Z3_ast xTwo[2] = { x, two };
/* _ - 1 */
Z3_ast fibXminusOne = Z3_mk_sub(ctx, 2, xOne);
/* _ - 2 */
Z3_ast fibXminusTwo = Z3_mk_sub(ctx, 2, xTwo);
Z3_ast toSum[2] = { Z3_mk_app(ctx, fibonacci, 1, &fibXminusOne), Z3_mk_app(ctx, fibonacci, 1, &fibXminusTwo) };
/* f(_ - 1) + f(_ - 2) */
Z3_ast fibSum = Z3_mk_add(ctx, 2, toSum);

This is now the body of the axiom. It says: _ > 1 => (fib(_) = fib(_ - 1) + fib(_ - 2),  where _ is the bound variable.
Z3_ast axiomTree = Z3_mk_implies(ctx, xGTone, Z3_mk_eq(ctx, fibX, fibSum));

At last we can build a quantifier tree, using the pattern, the bound variable, its name and the axiom body. (Z3_TRUE says its a forall quantifier). The 0 in the argument list specifies the priority. The Z3 doc recommends to use 0 if you don't know what to put.
Z3_ast fibN = Z3_mk_quantifier(ctx, Z3_TRUE, 0, 1, &pattern, 1, &intSort, &someName, axiomTree);

We finally add the axiom(s) the to context.
Z3_assert_cnstr(ctx, fib0);
Z3_assert_cnstr(ctx, fib1);
Z3_assert_cnstr(ctx, fibN);


text:
Q: Ruby on Rails database query not working on heroku I have this piece of code for a search query in my ruby on rails application. It works locally on the rails local server but not when I deploy on Heroku. Here's the line of code for that query:
@courses = Course.where("name LIKE? ","%#{params[:search][:course].downcase}%").all

A little bit of context: Course is my database model and it has a field called "name", here I am searching for all the courses with names containing certain words as specified from the user, that query word is passed in via the form params.
UPDATE:
Thank you Danilo and Brad! Solved with putting a space in between LIKE and ? and used ILIKE instead of LIKE.
@courses = Course.where("name ILIKE ? ","%#{params[:search][:course].downcase}%")

A: You have to put a space after LIKE and the ?, and you don't need to call .all method when you are using where, it's redundant.
@courses = Course.where("name LIKE ? ","%#{params[:search][:course].downcase}%")


text:
Q: How do I get highest degree of by using Deep-first-search algorithm First I have a txt file that contains thousands pairs of nodes and it looks like this:
1 3
1 5
1 8
1 7
2 3
2 4
2 5
2 6
3 2
3 4....
Every pair of node can be one edge, so I was using scanner to read them and and put every pair of nodes into a linked-list. Now I want to find the nodes(like top 10 or top 20 of them) with high degree and at the same time I want to output their followers as well. So I tried code as following:
import java.io.*;
import java.util.*;
import java.util.Arrays;
class Main {
    public static class Edge{
        int from;
        int to;
        public Edge(int from, int to){
            this.from = from;
            this.to = to;
        }

        public String toString(){
            return from+"->"+to;
        }
    }

    public static class Scanfile{
        public Scanner x;
        public void openFile(){
            try{
                x = new Scanner(new File("face.txt"));
            }
            catch(Exception e){
                System.out.println("could not open file");
            }
        }

        public void readFile(){
            LinkedList<Edge> adj = new LinkedList<Edge>();
            while(x.hasNext()){
                String a = x.next();
                int resa = Integer.parseInt(a);
                String b = x.next();
                int resb = Integer.parseInt(b);
                Edge edge = new Main.Edge(resa, resb);
                adj.add(edge);
              // System.out.println(edge);

            }
            //System.out.println(adj);
       }
        public void closeFile(){
            x.close();
        }
    }

public static class Graph extends Scanfile{
        private int V;
        private LinkedList<Integer> degree[];
        Scanfile u = new Scanfile();
        Graph(int resa){
          V=resa;
          degree  = new LinkedList(resa);
          for(int i=0;i<resa;i++)
          degree[i] = new LinkedList();
        }

        public void DFSUtil(int resa,boolean visited[]) {
        // Mark the current node as visited and print it
        visited[resa] = true;
        System.out.print(resa+" ");

        // Recur for all the vertices adjacent to this vertex
        Iterator<Integer> i = degree[resa].listIterator();
        while (i.hasNext())
        {
            int n = i.next();
            if (!visited[n])
                DFSUtil(n, visited);
        }
    }
    public void DFS(){
      boolean visited[]=new boolean[V];
      for(int i=0;i<V;i++)
      if(visited[i]==false)
      DFSUtil(i, visited);
      }
    }

    public static void main(String[] args) {
        Scanfile s = new Scanfile();
        s.openFile();
        s.readFile();
        s.closeFile();
        Graph g=new Graph();
        g.DFS();
    }
}

The code is never gonna work and the error messages are:
1.Can't find symbol resa
2.Incompatible types: int cannot be converted to Collection:degree  = new LinkedList(resa)
3.Constructor Graph in class Graph cannot be applied to given types;Graph g=new Graph()
I think the way that I passing the variables were wrong(Is there a way to pass the whole linked-list as varible?). I'm a real fresh man in java field. I would appreciate for any suggestions. Hope someone can help me!


text:
Q: COUNT(*) of GROUP BY I have a query which returns 644 rows, grouped by several columns. I need to get a count of these rows, 644.
This is the query:
SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,SUM(Properties.Value) as [sales value], COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho INNER JOIN Properties ON Properties.head_office_code = ho.id
WHERE Somecondition
GROUP BY ho.ID,ho.honame,ho_status ORDER BY ho_status

Despite trying COUNT(*), wrapping it in another query and removing the GROUP BY, I can't get '644' back. The closest I've come is 644 rows, all containing '1'. Is this possible?

A: The easy way to do it is thusly:
SELECT count(1) as NumRows from
(SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,SUM(Properties.Value) as [sales value], COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho INNER JOIN Properties ON clients.head_office_code = ho.id
WHERE Somecondition
GROUP BY ho.ID,ho.honame,ho_status ORDER BY ho_status) x

If you want the count plus your columns, use over:
SELECT
    count(1) over () as NumRows,
    x.ID,
    x.ho_status,
    x.[sales value],
    x.[property count]
from
(SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,SUM(Properties.Value) as [sales value], COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho INNER JOIN Properties ON clients.head_office_code = ho.id
WHERE Somecondition
GROUP BY ho.ID,ho.honame,ho_status ORDER BY ho_status) x

A: You will get 1 more row to your list which contains null values for everything but property count and properties value.  That record will have a count and the sum of all property values.
SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,
SUM(Properties.Value) as [sales value],
COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho
INNER JOIN Properties
  ON clients.head_office_code = ho.id
WHERE Somecondition
GROUP BY Grouping sets((ho.ID,ho.honame,ho_status),())
ORDER BY ho_status

A: This should work
SELECT COUNT(ID)
FROM (
SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,
       SUM(Properties.Value) as [sales value],
       COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho
     INNER JOIN Properties ON clients.head_office_code = ho.id
WHERE Somecondition
GROUP BY ho.ID, ho.honame, ho_status ) t


text:
Q: How to prove that $\lim_{x\to\infty} f(x)=\lim_{x\to 0}f(\frac{1}{x})$? I'm stuck at this problem. I tried to write down the hypothesis but it eludes me how we can use them to obtain the thesis.
Suppose that $\lim_{x\to\infty} f(x)=L$, a real number.
By definition that means that for any fixed $\epsilon$ there exists a $g$ such that if $x>g$ then $L-\epsilon<f(x)<L+\epsilon$.
But now, how can I work on $f(x)$ in such a way to obtain some expression for $f(\frac{1}{x})$?

A: To Prove:
$$\lim_{x \to \infty} f(x) = L \implies \lim_{x \to 0^+} f(1/x) = L. \tag1 $$
$$\lim_{x \to 0^+} f(1/x) = L \implies \lim_{x \to \infty} f(x) = L. \tag2 $$

$\underline{\text{Proof of (1)}}$
$\forall \epsilon > 0, ~\exists y > 0,~$ such that
$x > y \implies |f(x) - L| < \epsilon.$
Take $\delta = (1/y) \implies \delta > 0$.
Then, $0 < x < \delta \implies (1/x) > y \implies |f(1/x) - L| < \epsilon.$

$\underline{\text{Proof of (2)}}$
$\forall \epsilon > 0, ~\exists \delta > 0,~$ such that
$0 < x < \delta \implies |f(1/x) - L| < \epsilon.$
Take $g = (1/\delta) \implies g > 0$.
Then, $x > g \implies 0 < (1/x) < \delta \implies
\displaystyle \left|f\left(\frac{1}{1/x}\right) - L\right| < \epsilon.$
Since $\displaystyle \left(\frac{1}{1/x}\right) = (x)$, you have that
$x > g \implies |f(x) - L| < \epsilon.$


text:
Q: ANTRL4 grammar cannot cover all cases // Define a grammar called Hello
grammar Hello;

r  : element* ;

element
    : number Whitespace
    | string Whitespace
    ;

string
    : '(' Charactor* ')'
    ;

Charactor
    : [a-zA-Z] |'!' | '"'| '#' | '$' | '%' | '&' | '\'' | '\\(' | '\\)' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '`' | '{' | '|' | '}' | '~' | '_'
    ;

number
    : '-'? integer ('.' integer)?
    ;

integer
    : digit+
    ;

digit
    : D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | D8 | D9
    ;

Whitespace
    : ' ' | '\n'
    ;

D1 : '1';
D2 : '2';
D3 : '3';
D4 : '4';
D5 : '5';
D6 : '6';
D7 : '7';
D8 : '8';
D9 : '9';
D0 : '0';

//WS : [ \t\r\n]+ -> skip ; skip spaces, tabs, newlines

I used the above .g4 grammar file to parse the following sequence of characters.

➜  Hello antlr4 Hello.g4 ➜  Hello javac Hello*.java ➜  Hello grun
Hello r -tree
1.1 -1.2 333 -222 (((*&^%$#@!~<>,?"'\|[[]]{}~) (r (element (number (integer (digit 1)) . (integer (digit 1)))  ) (element (number - (integer (digit 1)) . (integer (digit 2)))  ) (element (number (integer (digit 3) (digit 3) (digit 3)))  ) (element (number - (integer (digit 2) (digit 2) (digit 2)))  ) (element (string ( \( \( * & ^ % $ # @ ! ~  < > , ? " ' \ | [ [ ] ] { } ~ ))  ))

This case works well.
But when I input the string "1.1 -1.2 333 -222 (-.#$?)", it doesn't parse it correctly.

➜  Hello grun Hello r -tree
1.1 -1.2 333 -222 (-.#$?) line 1:19 mismatched input '-' expecting {')', Charactor} line 1:20 mismatched input '.' expecting {'1', '2',
'3', '4', '5', '6', '7', '8', '9', '0'} line 1:21 mismatched input '#'
expecting {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'} (r
(element (number (integer (digit 1)) . (integer (digit 1)))  )
(element (number - (integer (digit 1)) . (integer (digit 2)))  )
(element (number (integer (digit 3) (digit 3) (digit 3)))  ) (element
(number - (integer (digit 2) (digit 2) (digit 2)))  ) (element (string
() ) (element (number - integer . (integer # $ ?
)))  )) ➜  Hello

This special sequence of characters is an array that includes numbers or strings.
The number can come with these ways like 1.1, -1.2, -222, 222
The string starts with '(', and ends with ')', if '(' or ')' appear in it, it could be escaped. It's noted that the string can include the character '-' or '.'.  So when '-' or '.' appears in the numbers and strings at the same time, it seems Antlr cannot parse it correctly.
Does anyone know how to fix this issue?  Thanks!

A: ANTLR has a strict separation between parser- and lexer rules. Whenever you use literal tokens in parser rules (like '-' and '.' in the number rule), ANTLR creates lexer rules behind the scenes for you. So the grammar:
number
    : '-'? integer ('.' integer)?
    ;

Charactor
    : [a-zA-Z] | ... | '-' | '.' | ...
    ;

really looks like this:
number
    : T_0? integer (T_1 integer)?
    ;

T_0 : '-';

T_1 : '.';

Charactor
    : [a-zA-Z] | ... | '-' | '.' | ...
    ;

And since the strict separation, ANTLR creates tokens independently from the parser. This means that for the characters - and ., it will never happen that these become Charactor tokens. They will always become T_0 and T_1 tokens. There is no way around this. If you freely want to used any character/token in any rule, look for "scannerless parsing" or "PEG parser" instead of using ANTLR.
To make your current grammar work with as little changes as possible, do something like this:
grammar Hello;

r  : element* ;

element
    : number Whitespace
    | string Whitespace
    ;

string
    : '(' (Charactor | Minus | Dot)* ')'
    ;

Minus : '-';
Dot : '.';

Charactor
    : [a-zA-Z] |'!' | '"'| '#' | '$' | '%' | '&' | '\'' | '\\(' | '\\)' | '*' | '+' | ',' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '`' | '{' | '|' | '}' | '~' | '_'
    ;

number
    : Minus? integer (Dot integer)?
    ;

integer
    : digit+
    ;

digit
    : D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | D8 | D9
    ;

Whitespace
    : ' ' | '\n'
    ;

D1 : '1';
D2 : '2';
D3 : '3';
D4 : '4';
D5 : '5';
D6 : '6';
D7 : '7';
D8 : '8';
D9 : '9';
D0 : '0';

But ideally, you'd use ANTLR more as it is intended to be (clearly defining tokens instead of constructing tokens in parser rules):
grammar Hello;

r  : element* EOF;

element
    : Number Whitespace
    | string Whitespace
    ;

string
    : '(' character* ')'
    ;

character
    : Character
    | Minus
    | Dot
    ;

Minus
    : '-'
    ;

Dot
    : '.'
    ;

Character
    : [a-zA-Z] | '!' | '"'| '#' | '$' | '%' | '&' | '\'' | '\\(' | '\\)' | '*' | '+' | ',' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '`' | '{' | '|' | '}' | '~' | '_'
    ;

Number
    : '-'? Integer ('.' Integer)?
    ;

Integer
    : Digit+
    ;

Whitespace
    : [ \t\r\n]
    ;

fragment Digit
    : [0-9]
    ;

A few tips:

*

*do not mix lexer and parser rules: start with parser rules, followed by lexer rules

*do not use literal tokens (like '.') inside parser rules

If you do that, it will be more clear when a token will be chosen over another token: the lexer:

*

*matches rules from top to bottom, always choosing the longest possible match, and

*when 2 (or more) lexer rules match the same amount of characters, the rule defined first "wins"

That is why (in my second grammar) the input "-1" will become a single Number token, and not a Minus token followed by a Number token (longest match "wins").


text:
Q: MediaPlayer: error (-19, 0) I tried all the solutions provided in this site & still i am getting this error.Don't know why it happen! please help me.
Here my code.
    MediaPlayer  mediaPlayer;
     mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.square);

                mediaPlayer.setOnErrorListener(MainActivity.this);
                mediaPlayer.start();

     mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mWinMusic[blocks].release();
                        }
                    });

    public boolean onError(MediaPlayer mp, int what, int extra) {

    mp = MediaPlayer.create(getApplicationContext(), R.raw.square);

          mp.start();
            return true;

}

A: Create player like this and add mediaPlayer.prepare(); and when ready then start in onPrepared()
public class MainActivity extends Activity {

    MediaPlayer mediaPlayer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.square);
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Toast.makeText(MainActivity.this, "Some problem ", Toast.LENGTH_LONG).show();
                    return false;
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Toast.makeText(MainActivity.this, "track completed", Toast.LENGTH_SHORT).show();
                    //mWinMusic[blocks].release();
                }
            });
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "Some problem " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}


text:
Q: Angular : Property formGroup is not provided by any applicable directives nor by form element I'm facing a problem with ReactiveFormsModule. It shows me an error : Property formGroup is not provided by any applicable directives nor by form element and the same for Event ngSubmit is not emitted by any applicable directives nor by form element
here's my html code :

            Sign in with

        <button type="button" class="btn btn-primary btn-floating mx-1">

        </button>

        <button type="button" class="btn btn-primary btn-floating mx-1">

        </button>

Or

        <input type="email" id="form3Example3" class="form-control form-control-lg"
               placeholder="Enter a valid email address" formControlName="email" required />
        Email address

        <input type="password" id="form3Example4" class="form-control form-control-lg"
               placeholder="Enter password" formControlName="password" required />
        Password

          <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" />

            Remember me

        Forgot password?

        <button type="button" class="btn btn-primary btn-lg"
                style="padding-left: 2.5rem; padding-right: 2.5rem;">Login</button>

Don't have an account? Register

    </form>

and here's my ts code :
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {AuthService} from "../services/auth.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  errorMessage = '';
  constructor(private formBuilder: FormBuilder, private authService: AuthService, private router: Router) { }

  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [ Validators.required])
    });
  }
  get f() { return this.loginForm.controls; }

  login() {
    this.authService.login(
      {
        email: this.f.email.value,
        password: this.f.password.value
      }
    )
      .subscribe(success => {
        if (success) {
          console.log('login successfully');
          this.router.navigate(['/dashboard']);
        }
      }, error => {
        this.errorMessage = 'Login et / ou mot de passe incorrecte';
      });
  }

}

and here is my app.module :
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

imports: [
    CommonModule,
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    NgbModule,
    RouterModule.forRoot(Approutes, { useHash: false, relativeLinkResolution: 'legacy' }),
    PerfectScrollbarModule,
  ]

it seems that everything is ok and I don't know what's the problem. thank you in advance


text:
Q: SGen can not generate an assembly for a valid type I have a valid for a XmlSerializer type:
public class MyItem
{
  public MyItem() {
    Values = new List<string>();
  }

  public List<string> Values { get; private set; }
}

It successfully serialized and deserialized (Full code example here http://ideone.com/s2PvSB). But, I can not generate .XmlSerializers.dll for this type, SGen failed with:
Microsoft (R) Xml Serialization support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.33440]
Copyright (C) Microsoft Corporation. All rights reserved.
EXEC : error : Unable to generate a temporary class (result=1).
EXEC : error CS0200: Property or indexer 'TestSGen.MyItem.Values' cannot be assigned to -- it is read only

SGen called from a PostBuild event as
"$(TargetFrameworkSDKToolsDirectory)SGen.exe" /Assembly:"$(TargetFileName)" /Type:"TestSGen.MyItem" /Force

Is it a bug in SGen or [somewhere] documented behavior?

A: This seems strange, as the code linked does indeed work for me.
It doesn't work if you change the List<string> to string[]. Is VS doing something strange with collection initializers? Maybe that allows your code to run normally, but SGen doesn't have access to the same trick?


text:
Q: Correct layout of h:outputLabel and rich:combobox components on same line With richfaces, how can I get my h:outputLabel and rich:combobox components to display directly adjacent to each other on the same line?
Here are the two approaches I've tried.

#1 rich:Layout
I first tried using rich:layout & rich:layoutPanel, but the components appear on separate lines. Here's the code:

<rich:layout>
  <rich:layoutPanel position="left" width="100%">
    <h:outputLabel for="timeSpanUnitsCombo2" value="Time Span " />
    <rich:comboBox id="timeSpanUnitsCombo2" value="#{bean.timeSpanUnitsLabel}" enableManualInput="false">
      <f:selectItems value="#{bean.timeSpanUnitsList}" />
    </rich:comboBox>
  </rich:layoutPanel>
</rich:layout>

And here's the rendered output:

#2 h:panelGrid
Next I tried using a h:panelGrid, but again no success - the components are evenly spaced over the available area, instead of being directly adjacent and left-aligned as I intended. Here's the code:

<h:panelGrid columns="2">
  <h:outputLabel for="timeSpanUnitsCombo3" value="Time Span " />
  <rich:comboBox id="timeSpanUnitsCombo3" value="#{bean.timeSpanUnitsLabel}" enableManualInput="false">
    <f:selectItems value="#{bean.timeSpanUnitsList}" />
  </rich:comboBox>
</h:panelGrid>

And here's the rendered output:

Component layout with richfaces is proving to be thoroughly frustrating. I'll give second prize to anyone who has some good references on layout with richfaces. :)

A: This can be done by many ways. One of them is to use fragment
<s:fragment>
      <h:outputText value="Time Span" />
      <rich:comboBox id="timeSpanUnitsCombo2" value="#{bean.timeSpanUnitsLabel}" enableManualInput="false">
            <f:selectItems value="#{bean.timeSpanUnitsList}" />
      </rich:comboBox>
</s:fragment>

Or you can use a div instead of fragment. <div> your code...</div>

A: If you are using seam, you can wrap it in <s:decorate> and use <s:label>
From Seam in Action
....<s:label> and <s:message>. The benefit of using the Seam tags is
that they are automatically correlated with the adjacent input component, a feature
of <s:decorate>


text:
Q: jQuery extendable function to filter "case-insensitive" After search in jQuery functions I found .Contains() but it's not help me
I want make new function that can filter case-insensitive

A: That's easy!
jQuery.expr[':'].iContains = (a, b, c) => jQuery(a).text().toUpperCase().indexOf(c[3].toUpperCase()) >= 0;


text:
Q: dynamic Auto Layout resize I have a container with a UITextView inside it. The container is supposed to resize according to the height of the text view. I'm currently using there lines to make it work
 let fixedWidth = textView.frame.size.width
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    let textViewHeight = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

    containerView.frame.size = textViewHeight

The thing is, i'm using Auto Layout on the rest of the constraints and I would like to manage this as an Auto Layout as well.
I've tried using .greatestFiniteMagnitude in my auto layout but that didn't do much for me.

A: Here is the layout and constraints to allow the text field to auto-size and auto-expand its containing view.
The containerView (blue) is constrained Top/Leading/Trailing, but not Bottom or Height.
The textView is constrained Top/Leading/Trailing/Bottom, all at 8, and Scrolling is Disabled.
Small amount of text:

Longer amount of text:

At run-time, when you set the text -- or when typing in the field -- its Height will auto-size based on the amount of text.


text:
Q: text from JSpinner to JTextArea How can I transfer text from a JSpinner to a JTextArea? I thought about .getText(); but it's not working.
dobDate = new JSpinner(new SpinnerDateModel(today, null, null,Calendar.MONTH));
dateEdit = new JSpinner.DateEditor(dobDate, "dd/MM/yy");
dobDate.setEditor(dateEdit);
dobDate.setBounds(215,270, 120, 25);

A: From JSpinner you can use getValue().  From JTextArea you can use insert() or append()


text:
Q: Allowing the User to choose a picture from the pictures folder I am trying to write code that will allow the user to choose a picture from the pictures folder and send that picture to the internet. I am new to Android so any help would be much appreciated.
Thanks in advance.

A: You first need to start an Activity which asks the user to pick a picture. You next need to handle the result of that choice.
1: CHOOSE PICTURE
Intent choosePictureIntent = new Intent(MediaStore.ACTION_PICK, Images.Media.INTERNAL_CONTENT_URL);
startActivityForResult(choosePictureIntent, REQUEST_CHOOSE_IMAGE);

2: Handle the result of the Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CHOOSE_IMAGE) {
        if (resultCode == RESULT_OK) {
            // send picture to Internet
        }
    }
}

How exactly you send the picture is a completely separate question.

A: I've not done any android programming but this looks very useful: OpenIntents, file picker that can be incorporated into an app.

A: You should look at this previous answer.


text:
Q: How to use OffscreenCanvas in TypeScript project I'd like to use OffscreenCanvas in a typescript project, but I have no idea how to do this. When I try:
let offscreen = new OffscreenCanvas(256, 256);

my ide says "Cannot find name OffscreenCanvas".
Any hints ?

A: For the time being, you'll need to modify your lib.dom.d.ts or similar.
In node_modules/typescript/lib/lib.dom.d.ts, find interface HTMLCanvasElement extends HTMLElement and append the lines
interface HTMLCanvasElement extends HTMLElement {
    // ...
    transferControlToOffscreen(): OffscreenCanvas;
}

interface OffscreenCanvasRenderingContext2D extends CanvasState, CanvasTransform, CanvasCompositing, CanvasImageSmoothing, CanvasFillStrokeStyles, CanvasShadowStyles, CanvasFilters, CanvasRect, CanvasDrawPath, CanvasUserInterface, CanvasText, CanvasDrawImage, CanvasImageData, CanvasPathDrawingStyles, CanvasTextDrawingStyles, CanvasPath {
    readonly canvas: OffscreenCanvas;
}
declare var OffscreenCanvasRenderingContext2D: {
    prototype: OffscreenCanvasRenderingContext2D;
    new(): OffscreenCanvasRenderingContext2D;
}
interface OffscreenCanvas extends EventTarget {
    width: number;
    height: number;
    getContext(contextId: "2d", contextAttributes?: CanvasRenderingContext2DSettings): OffscreenCanvasRenderingContext2D | null;
}
declare var OffscreenCanvas: {
    prototype: OffscreenCanvas;
    new(width: number, height: number): OffscreenCanvas;
}

And finally, edit the Transferable definitions in lib.dom.d.ts and lib.webworker.d.ts:
type Transferable = ArrayBuffer | MessagePort | ImageBitmap | OffscreenCanvas;

At that point, you'll have worked up the functions to change everything.
Also note: OffscreenCanvass' width and height members are modifiable, and when using canvas.transferControlToOffscreen() the width and height of the element will be synchronised on the next frame if changed.
Note that this does not work with webgl contexts as that's a little more in-depth. Or rather, there's so much to copy that it makes no sense to unless you're trying to set it up.
This is hacky, but works. Ideally, you would go back through and make a PR on the typescript thing but right now this is more than enough.

A: You can install @types/offscreencanvas to your project.
Yarn
yarn add @types/offscreencanvas

npm
npm i @types/offscreencanvas

Now enjoy it!
For more https://www.npmjs.com/package/@types/offscreencanvas

A: All variables need a type definition in Typescript, that's why it's called Typescript.
When we don't have type definitions for an object, we can define the type ourselves, or use any:
let offscreen: any = new OffscreenCanvas(256, 256);
Note that using any is discouraged in Typescript, if you do it for every variable you may as well not use Typescript.
Read about declaration files here:
https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html


text:
Q: Are there any benefits or drawbacks to using nested 'forall' loops I would like to know the benefits and drawbacks to using nested 'forall' loops. One thing I do understand is that 'forall' will invoke either the 'standalone' or 'leader' iterator, which may or may not induce additional parallelism, even across multiple locales. However, the amount of tasks that spawn are limited by default to 'here.maxTaskPar', and so we can only gain so much parallelism. If both 'forall' loops are over distributed data, I can see arguments in favor of using nested 'forall' statements, but what about when they are both local? When one of them is local and the other isn't?

A: As you note, the short answer to this question is "it depends" since Chapel's forall loops invoke iterators that could have been written by anyone and therefore could do anything.  But as you also allude to, for many of Chapel's standard types, there are certain knobs that govern the execution policies, as documented in Executing Chapel Programs::Controlling Degree of Data Parallelism, and certain conventions that are followed.  The rest of my answer will be written with respect to such cases.
For a completely local nested forall loop in which all iterations do a similar amount of work, you should not see a huge difference between using a nested forall loop:
forall i in 1..m do
  forall j in 1..n do
    var twoPi = 2*pi;

and using a serial for loop for the inner loop:
forall i in 1..m do
  for j in 1..n do
    var twoPi = 2*pi;

The reason for this, as I think you're anticipating, is that the outer forall loop will create dataParTasksPerLocale tasks where this value defaults to here.numPUs() (the number of processing units, or cores, on the current locale, or compute node).  Then, when each inner loop starts running, if dataParIgnoreRunningTasks is false, as it is by default, its iterator will note that dataParTasksPerLocale are already running, and so will avoid creating additional tasks.  The result is that each inner loop will likely run all of its iterations serially since it assumes that all processor cores are already busy running tasks.
Now, imagine that the iterations of the outer loop are extremely load imbalanced such that some of the outer loop tasks will complete long before other ones.  For example, here's a particularly artificial loop in which the second half of the iterations do much less work than the first half:
forall i in 1..m do
  if (i < m/2) then
    forall j in 1..n do
      var twoPi = 2*pi;

In this case, any task whose iterations are all in the range m/2+1..m will likely complete before those that own iterations in 1..m/2.  Let's say that this applies to half the tasks (which is likely for loops over ranges like the above, where tasks tend to be assigned consecutive chunks of iterations).  These tasks should complete quite rapidly.  Once that happens, each of the inner loops executed by the other half of the tasks may see that fewer than dataParTasksPerLocale / 2 tasks are running and create additional tasks to execute their iterations.  Why do I say "may"?  Because if multiple outer loop tasks are running simultaneously, there will be multiple simultaneous inner loops, and each will each be querying the number of running tasks and competing to create dataParTasksPerLocale - here.runningTasks() additional ones, so some may execute their inner loops in parallel, others serially using a single task.
Of course, this "inner loops may be parallelized" behavior can occur even for more realistic nested loops than the above, such as one where the amount of work may vary dramatically across values of i and j:
forall i in 1..m do
  forall j in 1..n do
    computeForPoint(i,j);  // imagine the amount of work here varies significantly based on i and j

In any poorly-balanced loop, some outer-loop tasks may complete before others, freeing up tasks for subsequent inner loops to use.  In cases like this, another option is to use a Dynamic Iterator for the outer loop to keep the work balanced better between outer loop tasks.  Note that even in the most well-balanced loops, it's likely that not all outer-loop tasks will finish simultaneously, in which case the final inner loop instances may be executed in parallel (and this is why I used "likely" in the final sentence describing my initial well-balanced case).
In the local case, if I only want to make one loop of a loop nest parallel (and either could be), I typically make it the outer loop in order to minimize the number of tasks that are created and destroyed.  That is, I'd typically choose:
forall i in 1..m do
  for j in 1..n do
    ...

over:
for i in 1..m do
  forall j in 1..n do
    ...

Because the former creates ~dataParTasksPerLocale tasks where the latter creates ~m * dataParTasksPerLocale.   Alternatively, I might make both parallel and rely on the iterators and runtime to avoid creating excessive tasks:
forall i in 1..m do
  forall j in 1..n do
    ...

But in many cases, the "right" choice can also depend on the trip counts of the loops, the computation within the loop, etc.  I.e., there's not necessarily a one-size-fits-all answer.
Now, moving to loops over distributed data structures:  As of Chapel version 1.17, for standard array distributions, serial loops over those data structures are always computed on the current locale where the task encountering the loop is currently executing.  By contrast, forall loops over distributed data structures create at least one task on each target locale, and potentially up to dataParTasksPerLocale per target locale based on the same heuristics as in the local case above.  For this reason, loops over distributed data structures should typically use forall loops whenever possible to optimize for locality and improve the chances of creating scalable code.


text:
Q: Finding a maximum solution to system of inequalities with Z3Py I have a solver in Z3Py to which I've added a number of constraints. Each constraint is an inequality involving variables and/or real numbers. Here's what the first few entries in the solver might look like:
[a + b >= 1.5,
 a <= 1.5 + b,
 b <= 1.5 + a,
 2.27 + c >= 1.41, ... ]

What I would like to do is, given this solver, return a single solution [a = ..., b = ..., c = ..., ...] with a,b,c real numbers with the property that any other solution has a smaller value for one of the variables. Since there may be multiple such "maximum" solutions, I just want the first one found. I'm not that familiar with Z3, so I don't know how to return multiple solutions / a range of solutions for a system of inequalities, how to compare them, etc. How can I do this?

A: This sort of optimization is known as finding the Pareto front. The elements of the Pareto front have the property that to find another optimal solution for one objective, you have to make some other objective a bit "worse."
Z3 has direct support for this support of optimization. See Section 8.1 of https://theory.stanford.edu/~nikolaj/programmingz3.html
Based on this, here's how you can code your example in z3:
from z3 import *

a, b, c = Reals('a b c')

opt = Optimize()
opt.set(priority='pareto')
opt.add(a + b >= 1.5)
opt.add(a <= 1.5 + b)
opt.add(b <= 1.5 + a)
opt.add(2.27 + c >= 1.41)

ma = opt.maximize(a)
mb = opt.maximize(b)
mc = opt.maximize(c)

while opt.check() == sat:
  print ("a =", ma.value(), "b =", mb.value(), "c =", mc.value())

Alas, the optimizer is not very good at handling this program. I ran it for a few minutes but it did not produce any results. Adding extra constraints to further reduce the space might help it converge faster.


text:
Q: Derivative with respect to $x + t$ I am reading through Princeton's lectures in analysis and I am on the 10th page of the first book on Fourier series.
In analyzing the wave equation, they state that $\xi = x + t $ and $\eta = x -t$ and $v(\xi,\eta) = u(x,t)$ and then $$ \frac{\partial^2 v}{\partial \xi \partial \eta} = 0.$$
The partials are confusing me, but I need to know why that equates to zero. It might also be useful to note that $$ \frac{ \partial^2 u}{\partial x^2} = \frac{ \partial^2 u}{\partial t^2}. $$
Even a hint in the right direction would suffice. My differential calculus is rusty.

A: This is just an application of the chain rule.
$$v_\xi = v_xx_\xi + v_t t_\xi = u_x + u_t \\ v_{\xi\eta} = (u_x + u_t)_\eta = u_{xx} x_{\eta} + u_{xt}{t_\eta}+u_{tx}x_\eta + u_{tt}t_\eta = (x_\eta+t_\eta)(u_{xx}+u_{xt})$$
But $x_\eta+t_\eta = (1)+(-1) = 0$.  Therefore $v_{\xi\eta}=0$.

A: This is one big application of the chain rule!
Note:
$x= \xi - t \Rightarrow \frac {\partial x}{\partial \xi} = 1$,
$x = \eta +t \Rightarrow \frac {\partial x}{\partial \eta} = 1$
$t=\xi -x \Rightarrow \frac {\partial t}{\partial \xi} = 1$,
$t=x-\eta \Rightarrow \frac {\partial t}{\partial \eta} = -1$
Now,
$\frac {\partial v}{\partial \eta} = \frac {\partial u}{\partial \eta} = \frac {\partial u}{\partial t}\frac {\partial t}{\partial \eta} + \frac {\partial u}{\partial x}\frac {\partial x}{\partial \eta}  = -\frac {\partial u}{\partial t} +  \frac {\partial u}{\partial x}$
$\frac {\partial^2 v}{{\partial \xi}{\partial \eta}} = -\frac {\partial^2 u}{{\partial \xi}{\partial t}} + \frac {\partial^2 u}{{\partial \xi}{\partial x}} = -\frac {\partial^2 u}{{\partial^2 t}}\frac {\partial t}{\partial \xi} -\frac {\partial^2 u}{{\partial x}{\partial t}}\frac {\partial x}{\partial \xi} + \frac {\partial^2 u}{{\partial^2 x}}\frac {\partial x}{\partial \xi} + \frac {\partial^2 u}{{\partial t}{\partial x}}\frac {\partial t}{\partial \xi} $
$= -\frac {\partial^2 u}{{\partial^2 t}} + \frac {\partial^2 u}{{\partial^2 x}} + \frac {\partial^2 u}{{\partial t}{\partial x}} - \frac {\partial^2 u}{{\partial x}{\partial t}} = 0 + \frac {\partial^2 u}{{\partial x}{\partial t}} - \frac {\partial^2 u}{{\partial x}{\partial t}} = 0 $
Since u satisfies the wave equation, $\frac {\partial^2 u}{{\partial^2 t}} = \frac {\partial^2 u}{{\partial^2 x}} \Rightarrow -\frac {\partial^2 u}{{\partial^2 t}} + \frac {\partial^2 u}{{\partial^2 x}} = 0$
and because u is continuous,$\frac {\partial^2 u}{{\partial x}{\partial t}} = \frac {\partial^2 u}{{\partial x}{\partial t}} \Rightarrow \frac {\partial^2 u}{{\partial x}{\partial t}} - \frac {\partial^2 u}{{\partial x}{\partial t}}= 0$

A: Chain Rule:
$$
\begin{align}
\frac{\partial}{\partial x}
&=\frac{\partial\xi}{\partial x}\frac{\partial }{\partial\xi}+\frac{\partial\eta}{\partial x}\frac{\partial }{\partial\eta}\tag{1}\\
\frac{\partial}{\partial t}
&=\frac{\partial\xi}{\partial t}\frac{\partial }{\partial\xi}+\frac{\partial\eta}{\partial t}\frac{\partial }{\partial\eta}\tag{2}
\end{align}
$$
Composing $(1)$ with $(1)$:
$$
\begin{align}
\frac{\partial^2}{\partial x^2}
&=\frac{\partial^2\xi}{\partial x^2}\frac{\partial }{\partial\xi}+\frac{\partial^2\eta}{\partial x^2}\frac{\partial }{\partial\eta}\\
&+\left(\frac{\partial\xi}{\partial x}\right)^2\frac{\partial^2 }{\partial\xi^2}+2\frac{\partial\xi}{\partial x}\frac{\partial\eta}{\partial x}\frac{\partial^2}{\partial\xi\partial\eta}+\left(\frac{\partial\eta}{\partial x}\right)^2\frac{\partial^2 }{\partial\eta^2}\tag{3}
\end{align}
$$
Composing $(2)$ with $(2)$:
$$
\begin{align}
\frac{\partial^2}{\partial t^2}
&=\frac{\partial^2\xi}{\partial t^2}\frac{\partial }{\partial\xi}+\frac{\partial^2\eta}{\partial t^2}\frac{\partial }{\partial\eta}\\
&+\left(\frac{\partial\xi}{\partial t}\right)^2\frac{\partial^2 }{\partial\xi^2}+2\frac{\partial\xi}{\partial t}\frac{\partial\eta}{\partial t}\frac{\partial^2}{\partial\xi\partial\eta}+\left(\frac{\partial\eta}{\partial t}\right)^2\frac{\partial^2 }{\partial\eta^2}\tag{4}
\end{align}
$$
since
$$
\frac{\partial(\xi,\eta)}{\partial(x,t)}=\begin{bmatrix}1&1\\1&-1\end{bmatrix}\tag{5}
$$
is constant, higher derivatives must be $0$. Applying $(5)$ to $(3)$ and $(4)$ gives
$$
\begin{align}
\frac{\partial^2}{\partial x^2}
&=\frac{\partial^2 }{\partial\xi^2}+2\frac{\partial^2}{\partial\xi\partial\eta}+\frac{\partial^2 }{\partial\eta^2}\tag{6}
\end{align}
$$
and
$$
\begin{align}
\frac{\partial^2}{\partial t^2}
&=\frac{\partial^2 }{\partial\xi^2}-2\frac{\partial^2}{\partial\xi\partial\eta}+\frac{\partial^2 }{\partial\eta^2}\tag{7}
\end{align}
$$
Therefore, the Laplacian becomes
$$
\frac{\partial^2}{\partial x^2}+\frac{\partial^2}{\partial t^2}
=2\left(\frac{\partial^2}{\partial\xi^2}+\frac{\partial^2}{\partial\eta^2}\right)\tag{8}
$$
and the Wave Operator becomes
$$
\frac{\partial^2}{\partial x^2}-\frac{\partial^2}{\partial t^2}
=4\frac{\partial^2}{\partial\xi\partial\eta}\tag{9}
$$
Equation $(9)$ gives the Wave Operator in the rotated coordinates.


text:
Q: Get Invalid use of default parameter using adInteger I have a problem with this statement. for some reason I get the error: Microsoft][ODBC SQL Server Driver]Invalid use of default parameter
The statement work fine until the last parameter where it is suppose to add an integer to the SQL statement. If I comment out the last parameter the statement works fine but for some reason it crashes when the last statement is add.  I hope someone can tell me why it tells me that this is an invalid use of default parameter.  I have tried every combination I can come up with. I have check and it is not null, I have hard coded a value in for the variable and still get the same error. Any help will be greatly appreciated.
set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = tadsdb

cmd.CommandText = "insert into poc_data (poc_userid, POC_FNAME,POC_LNAME, POC_EMAIL, POC_ORG, DSN_PHONE, DSN_FAX, POC_TYPE_ID,UNIT_ID) values(?,?,?,?,?,?,?,?,?)"
cmd.CommandType = adCmdText
    cmd.Parameters.Append cmd.CreateParameter("@new_id",adVarChar,,50,new_id)
    cmd.Parameters.Append cmd.CreateParameter("@first_name",adVarChar,,50,first_name)
    cmd.Parameters.Append cmd.CreateParameter("@last_name",advarchar,,50,last_name)
    cmd.Parameters.Append cmd.CreateParameter("@email",adVarChar,,50,email)
    cmd.Parameters.Append cmd.CreateParameter("@organization",adVarChar,,50,organization)
    cmd.Parameters.Append cmd.CreateParameter("@dsn_phone",adVarChar,,50,dsn_phone)
    cmd.Parameters.Append cmd.CreateParameter("@dsn_fax",advarchar,,50,dsn_fax)
    cmd.Parameters.Append cmd.CreateParameter("@user_type",advarchar,,50,user_type)
    cmd.Parameters.Append cmd.CreateParameter("@unit_id",adInteger,,unit_id)
    'cmd.Parameters.Append
    cmd.Execute
    set cmd = Nothing


text:
Q: iOS app vanishing from Notification Center after update I have an iOS app written in Titanium Studio using Push Notifications, Badges and Sounds through Urban Airship. After my last update people who upgraded are having problems with the Notification Center. At first my app still appears in the Notification Center, but the "Badges, Sounds, Banners" that normally appear under the app's name have vanished. If you go into the app's settings in the Notification center, the options to change these things simply are not there. Of course Push Notifications don't work at this point either.
Now, if you either restart the phone or reinstall the app, the programs entry in the notification center vanishes completely. I have found that after reinstalling the app and restarting the phone enough times the entry in the Notification Center will reappear and Pushes will work again. This is of course an absurd thing to ask all our users to do.
Even while all this is happening I still receive proper APID's from the phones, and the push messages claim to go though correctly. The phone just does not display them.
On the one fresh install I have tried everything worked great right off the bat.
I am completely stumped on where to go on this one. Any suggestions?
Edit 1:
Here is the relevant section of the code. I only changed one line from the previous version the only and only line of code to change from the previous version is noted.
var Urbanairship = require("com.0x82.urbanairship");
Urbanairship.options = {
  APP_STORE_OR_AD_HOC_BUILD: true,
  DEVELOPMENT_APP_KEY: "xxx",
  DEVELOPMENT_APP_SECRET: "xxx",
  PRODUCTION_APP_KEY: "yyy",
  PRODUCTION_APP_SECRET: "yyy",
  LOGGING_ENABLED: true,
  LOG_LEVEL: 5
};

  Ti.Network.registerForPushNotifications({
  types: [
    Ti.Network.NOTIFICATION_TYPE_BADGE,
    Ti.Network.NOTIFICATION_TYPE_ALERT,
    Ti.Network.NOTIFICATION_TYPE_SOUND
  ],
  success: function(e){

    var token = e.deviceToken;
    Urbanairship.autoBadge = true;
    Urbanairship.pushEnabled = true; //Added this line, only line to change
    Urbanairship.registerDevice(token);
    userData.pushID = token; //save pushid
    Ti.App.Properties.setString('userData', JSON.stringify(userData));
  },
  error: function(e){
    alert("The Push Servers appears to be down. Please restart the app and try again");
    if(DEBUG == true){Ti.API.debug("Apple Push Error: "+e.error)}
  },
  callback: function(e){
  pushReceived(e.data.type);
  }
})

A: If the notification settings have disappeared, it's unlikely to be a code problem. The code can only request notifications, it can't change the setting altogether.
It's possible that your update was built with an older provisioning profile, one that does not have push enabled. In the profile the "aps-environment" flag would not be found, and when the app attempts to register it will display this error in the xcode console:
https://support.urbanairship.com/customer/portal/articles/60710-can-t-get-a-device-token-%22no-valid-aps-environment-entitlement-%22-seen-in-console
If this is the issue, you can delete the existing provisioning profiles from your xcode installation for safety, and then modify and re-download the provisioning profile from the portal, and re-build and re-submit the app.


text:
Q: MongoDB: How to query field array by _id how to get the specific message by _id.
I have a database schema as shown below:
{
    "_id": ObjectID("5846eedaf0b51ed02ed846e2"),
    "name": "conversation name"
    "messages": [
        {
            "_id": ObjectID("584820a96866b6283361a4b9"),
            "content": "hello",
            "status": 0,
            "type": 0
        },
        {
            "_id": ObjectID("584820d56866b6283361a4ba"),
            "content": "voices/1481122005696.mp3",
            "status": 0,
            "type": 3
        }
    ]
}

A: db.collection.find({}, {
    'messages': {
        $elemMatch: {
            '_id': ObjectId("584820a96866b6283361a4b9")
        }
    }
})

This will match on all documents in your collection, and return the matching array subfield in the projection.  See the link posted in Yogesh's comment.

A: Since you tagged mongoose, I put it like this, but the query syntax is valid because is part of mongoDB query syntax:
Conversation.findOne({
  "messages._id": "584820a96866b6283361a4b9"
}, function(err, document){
    if (err) {
        console.log(err)
        return
    }
    var message = document.messages.id("584820a96866b6283361a4b9")
})

The finOne() method will return the full parent document with all the messages (subdocuments) and other properties. You then need to filter out the subdocument. Mongoose provides a way to do this easily with: document.messages.id("584820a96866b6283361a4b9") where document would be the data object passed to the find callback
See:
Match a Field Without Specifying Array Index on
https://docs.mongodb.com/v3.2/tutorial/query-documents/#query-on-arrays


text:
Q: Firestore collection document not saving after entering document id
As per the reference image attached, am trying to create a new document, but for some reason, the save button is disabled even though all. fields are filled.
Is there anything else I need to do for the button to be enabled?

A: The solution to this was to refresh the page and ensure that the Document ID exists before adding any field.
Thanks to @prabir in the post comment.


text:
Q: como buscar fechas en java en un db con jdatachooser buenas quiero almacenar datos en una db pero me sale error
@Override
public List<Ausentismo> list05(Date fechai, Date fechaf, Date fechaMesA, Date fechaMesS) {

    List<Ausentismo> list05 = null;

    String sql = "SELECT AU.COD_MOTIVO, AU.CODIGO, AU.FECHA_SALIDA, AU.FECHA_RETORNO, AU.DIAS_CIA \n"
            + "FROM RH_AUSENTISMO AU WHERE FECHA_SALIDA BETWEEN '01-07-2018' AND '31-08-2018' \n"
            + "AND FECHA_RETORNO BETWEEN "+fechai+" AND '30-09-2018' AND AU.COD_MOTIVO ='LS'";
    try {

        Connection cn = db.getConnection();
        PreparedStatement st = cn.prepareStatement(sql);

esa es la consulta
 private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    Date fechaf = (Date) fechaFinal.getDate();
    Date fechai = (Date) fechaInicio.getDate();
    Date mesSig = (Date)  mesSiguiente.getDate();
    Date mesAnt = (Date)  mesAnterior.getDate();

    snl snl = new snl();
    snl.grabar_snl(fechai ,fechaf, mesSig,mesAnt,a, m);

esa es donde envió desde el jdchooser y el erroe q  sale es este.

Error: ORA-03115: unsupported network datatype or representation

espero su ayuda.

A: Tu problema es que cuando concatenas la fecha fechai el query se corrempe.
Primero: porque no agregas las comillas simple y
Segundo: fechai concatenara con el format de fecha predeterminado.
Te pongo este ejemplo, para que veas el error:
Date fechai = new Date();

String sql= "SELECT * FROM RH_AUSENTISMO WHERE FECHA_RETORNO BETWEEN " + fechai + " AND '30-09-2030'";

System.out.println(sql);

Muy parecido a lo que tienes, pero mira como queda la salida:
SELECT * FROM RH_AUSENTISMO WHERE FECHA_RETORNO BETWEEN Thu Dec 13 12:20:13 COT 2018 AND '30-09-2030'

Lo que debes hacer es formatiar la salida de la fecha y agregar las comillas simples:
Date fechai = new Date();

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String dateString = format.format(fechai);

String sql = "SELECT * FROM RH_AUSENTISMO WHERE FECHA_RETORNO BETWEEN '" + dateString + "' AND '30-09-2030'";

Y la salida sera:
SELECT * FROM RH_AUSENTISMO WHERE FECHA_RETORNO BETWEEN '13-12-2030' AND '30-09-2018'

Algunas veces es mejor utilizar el TO_DATE para no tener problemas entre ambientes ya sea tu maquina, el de pruebas, pre-produccion o produccion. Pero la mejor opcion es pasar las fechas con parametros.
Un ejemplo del TO_DATE:
SELECT * FROM RH_AUSENTISMO WHERE FECHA_RETORNO BETWEEN TO_DATE('13-12-2018','DD-MM-YYYY') AND TO_DATE('30-09-2030','DD-MM-YYYY')


text:
Q: Do we have any API available for Avature? I am looking for the APIs available to fetch data from Avature and am not able to find any documentation on their site.
Do we have any APIs available to get data from Avature?
My goal is to fetch documents from Avature and store them in SharePoint.


text:
Q: On AJAX refresh all JavaScript events are breaking I am doing an AJAX call to replace everything below the header and everything above the footer of a the page when the user clicks a filter link.
The problem is that after the AJAX event, all the JavaScript events bound to the various DOM elements break. This makes sense as those were bound on a much lower module level example
$(".innerDiv").on("click",function(){doSomething();}

and by replacing the content of the parent container these events are no longer bound.
What is the correct way of handling this problem? I could add the event listener to a much higher level e.g
$(document).on("click",".innerDiv",function(){doSomething();}

But this would have the same inefficiencies and issues for which the live() function in jQuery was deprecated.
The other solution that I have found suggested is to rebind the events after the AJAX call. The problem is that this is a fairly complex page I am dealing with, and it contains a lot of JavaScript modules each of which have their own bindings. How would I keep track of every event that gets binded? Is there any way of accessing this information from within jQuery? should i be maintaining my own datastructure of all elements which have events bound to them?
Also would I need to unbind events using the "off()" function before making the AJAX  request?
Thanks for your help

A: In JQuery could use beforeSend http://api.jquery.com/jQuery.ajax/ to unbind the events


text:
Q: Installing application after download: `There is a problem parsing the package` I am trying to download an install a .apk file from an application. Here are 3 different situations:
1. From Eclipse to Tablet via adb > Run application > No problems
2. From Eclipse > Sign & Export > Transfer .apk file to tablet via USB > Install & Run application > No problems
3. From Eclipse > Sign & Export > (The same file from 2.) Upload .apk file to a server > Download .apk file from application > Try to install > "There is a problem parsing the package"
code for downloading the application:
private class DownloadFile extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... sUrl) {
        try {
            URL url = new URL(sUrl[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + "Download" + File.separator + "Design102.apk");

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Why am I getting "There is a problem parsing the package" error for the same .apk file after downloading?

A: The following minor modification fixed my problem:
       while ((count = input.read(data)) > 0)


text:
Q: Failed to create Release artifact directory error after cancelling Release and starting new one This seems to only happen if I cancel a release deployment and then start a new one. It forces me to go into the agents and manually restart them.
The actual error is..
"Failed to create Release artifact directory 'C:\agent_work\r3\a'. ---> System.IO.IOException: The process cannot access the file '\?\C:\agent_work\r3\a' because it is being used by another process."
Is there a way in TFS to clean up any of these potential issues when creating a new release after a cancelled one? If I let it fully run its course, the new release runs fine no problem. This only happens when I cancel and attempt to start a new one.

A: You can use utility like handle to write a script that releases locked files or folders.
For example:
$pathToRelease = $env:System.DefaultWorkingDirectory
Write-Host "$PathToRelease is locked! trying to kill the process..."
$processes = path\to\handle64.exe -nobanner -accepteula $PathToRelease

# Remove empty lines
$processes = $processes | Where-Object {$_ -ne ""}
Write-Host $processes.ForEach({ Write-Host $_ })

if($processes -notmatch "No matching handles found.")
{
   foreach($process in $processes)
   {
       # Some excluded processes, you can decide what which you want
       if($process -match "explorer.exe" -or $process -match "powershell.exe"
       {
                continue
       }
       $pidNumber = $process.Substring(($process.IndexOf("pid") + 5),6)
       $isProcessStillAlive = Get-Process | Where-Object {$_.id -eq $pidNumber}
       if($Null -ne $isProcessStillAlive)
       {
           Stop-Process -Id $pidNumber -Force
           Start-Sleep -Seconds 1
       }
   }
}
else
{
   exit 0
}

Configure the script to run even the release is canceled.


text:
Q: How to compare local copy of file with latest one in Subversion using Tortoisesvn? How to compare local copy of a file with latest one in Subversion using Tortoisesvn?
I have all my files committed but there seems to be a difference somewhere and I am trying to find it.

A: The option you're searching is called "Diff".
This feature shows you both versions of the same file (local copy and latest in repository), highlighting any difference between them.

A: You right-click on the file you want to compare, expand TortoiseSVN and choose Diff.
If the file you have locally was edited since the last svn update you performed, it will have a red exclamation mark watermark on it's icon, if it doesn't then maybe you need to run svn update again and check the differences again.

A: Right click on the checked out folder and do "check for modifications" from the TortoiseSVN menu - this shows you all the files that have not yet been committed.
If you are paranoid that there are differences when someone else checks out the code you could just do a 2nd check out to some other folder and use a tool like kdiff3 to compare the two.

A: Try using 'Cleanup' to attempt to resolve any inconsistencies.

A: This seems to be an old thread, however I would like to answer this as I do not see this answer above.
If you are not seeing 'diff' and only able to see 'Diff with previous version' this means your local copy is identical to what in repository and there is no difference to show, hence no 'diff' option.
Hope this answer your question.


text:
Q: How to create a COUNTIF to find text that's in a cell in a column containing long strings I am trying to find how to search for specific key words in a string of answers from a survey. For example, trying to find the word excited in a list of 100 survey string answers.
I currently am using the following formula
=COUNTIF(G3:G24,""*"&C4&"*"")

However the issue I'm having is that the double quotation marks are recognized as a zero but I'm looking to perform a countif on "*excited*" but trying to use the cell to dictate what word will searched for. The way i have it currently written it is performing a COUNTIF on ""*excited*""
How do I get rid of the double quotes on either side and keep it as only a single set so that it can properly search?


text:
Q: offer zip for download in php I'm really getting mad after having spent four hours without result. I want to offer a zip file for download. not via link but with readfile (maybe there's another way?) Whatever I have tried, the zip is empty after downloading it.
$file = 'Passiv1.zip';
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Content-Length: '.filesize($file) );
readfile($file);

Can anyone help me out?

A: The following works for me:
header("Content-Disposition: attachment; filename=\"".$file."\"");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

Also, make sure you don't have another problem, like Passiv1.zip not being readable.
Try to test that with something like this:
if (is_readable($file)){
  echo "OK!";
} else {
  echo "NOT OK!";
}

A: Problem solved: no content should be sent before header, not even whitespaces


text:
Q: What should be the PHPMailer settings for GoDaddy for sending email? What will be the settings for the godaddy for sending email?
$mail->isSMTP();
$mail->Host = 'mail.trottolaw.com';
$mail->SMTPAuth = true;
$mail->Username = 'info@trottolaw.com';
$mail->Password = 'my password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->addReplyTo('info@trottolaw.com','Mazhar');
$mail->setFrom('info@trottolaw.com', 'Mazhar');
$mail->addAddress('contact@trottolaw.com', 'Mazhar');
$mail->addAddress('contact@trottolaw.com');

I was expecting it to send email but it's not sending any email and also not giving any error message.

A: Search before you post; This has been asked and answered many times before. Also, why would you not look at GoDaddy's support area before posting here?
GoDaddy blocks outbound SMTP; you cannot use any SMTP servers other than GoDaddy's own. This also means you usually cannot use your own email addresses as from addresses because it will cause SPF failures (unless you add GoDaddy to your SPF, which isn't a good idea).
To send through GoDaddy's servers, either do not use SMTP at all (which means that PHPMailer will fall back to using mail(), which will send via localhost, and that works with GoDaddy's shared hosting), or use these settings:
$mail->isSMTP();
$mail->Host = 'relay-hosting.secureserver.net';
$mail->Port = 25;
$mail->SMTPAuth = false;

You don't need to provide a username or password as it whitelists shared hosts.

A: I also went through the same issue of mails not being sent and recieved from Godaddy.
The following steps solved my issue:
1) Go to Cpanel
2) Click on MX Entry under Email Section
3) Check Email Routing
4) If you are using Cpanel emails then you need to select Local Mail Exchanger and If you are using Google or any external email service then you need to select Remote Mail Exchanger.


text:
Q: Is it necessary to use "The" on product name "The Last Words"? EDIT:
The company that I work is developing a game and we are deciding the best name of the game. The final one was "Last Words" but we were not sure if we have to use the "The Last Words" or just "Last Words".
The doubt is:
Is using just "Last Words" grammatically incorrect? Do you guys see any problem of using only "Last Words"?
Without "the" seems cleaner and simpler.
Thanks for all help!

A: "Last Words" sounds okay. Mispronounced by a non-Anglophone, it may get passed along as "Lost Words".
Try saying "The End" as opposed to "End". "The Last Words" has the same appeal to me, as the former.


text:
Q: How can I make this shape? How can I make the following with HTML and CSS, when I have been provided with background-image.
 defence personnel

A: So a variation of it is possible with CSS, but my version is the ugliest piece of shit you'll find. Check it out: http://jsfiddle.net/7s4L0jhy/
I have an extra element for the half circle thing, but other than that, it's all variable according to the text in your element.
.p {
    border: 3px solid #fff;
    border-top: 0;
    display: inline-block;
    margin: 0 auto;
    padding: 30px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

And then I create the top bar, but leave space for the circle:
.p:before {
    content: '';
    position: absolute;
    right: calc(50% + 35px);
    left: -3px;
    height: 3px;
    top: 0;
    background: #fff;
}
.p:after {
    content: '';
    position: absolute;
    left: calc(50% + 35px);
    right: -3px;
    height: 3px;
    top: 0;
    background: #fff;
}

And lastly, the fake circle thingy:
.p .bar {
    position: absolute;
    height: 70px;
    width: 70px;
    border-radius: 50%;
    border: 3px solid #fff;
    border-left: 0;
    border-bottom: 0;
    border-right: 0;
    top: -30px;
    left: 50%;
    transform: translateX(-50%);
}

As per the other answer, an image would definitely be easier for you, but this should work for anything ie10+. Good luck.

A: There are many approaches to solve this. However I think the requirement here is high scalability, that is we can change the size of the outside element (the wrapper) and the shape should keep scaling accordingly. Doing so requires a little trick relating to overflow:hidden, the top shape includes a nearly half circle at center and the 2 lines besides, the trick here is we need to fix the ends (of the 2 lines) connecting to the nearly half circle and let the other ends free, so that when scaling up/down the overflow:hidden will cut off those ends if there is any error in calculation.
Here is the code:
HTML:

    Defense personnel

CSS:
.frame > .top, .top > .peak {
  position:absolute;
}
.frame {
  position:relative;
}
.frame > .top {
  overflow:hidden;
  left:-3px;
  right:-3px;
  padding-top:100%;
  bottom:100%;
}
.frame > .top:before, .frame > .top:after {
  content:'';
  position:absolute;
  border-top:3px solid white;
  width:30%;
  bottom:0;
}
.frame > .top:before {
  right:70%;
}
.frame > .top:after {
  left:70%;
}
.top > .peak {
  border:3px solid white;
  border-radius:50%;
  left:50%;
  width:40%;
  padding-top:40%;
  bottom:0;
  -webkit-transform:translate(-50%,44%);
}
.frame {
  width:300px;
  height:200px;
  margin-top:100px;
  border:3px solid white;
  border-top:0;
}
.frame > .content {
  width:100%;
  height:100%;
  text-align:center;
  padding-top:20px;
  font-size:30px;
  color:white;
}
body {
  background:url(http://lorempixel.com/800/600);
}

Demo.
Try resizing the .frame and you'll see how flexable it is.

A: .some-cl{background:#003 /*bg color*/ url(your_image.jpg) no-repeat 50%; text-transform:uppercase; text-align:center; padding-top:40px /*adjust at will */ }

there are better and more complex methods, but since you're asking extremely basic CSS questions, I assume this should be enough


text:
Q: Is it a bad idea to get my production servers software source code from github Usually I use apt-get but apt-get can get out of date.
It seems that quite a nice solution may be to get the source code for my software (for example, nginx) from github and then build it each time.
Is there any reason why this may not be a good idea?
In my mind it means I have the most up to date code each time including the latest bug fixes.

A: First you should look around, you might find a ppa having the new version. That is the easiest way.
In the case there isn't:
Building and installing software from source can lead to messed up libraries or binaries on the system, as another package might overwrite something or vice-versa.
To avoid this, there are 2 solutions:

*

*Only build the source, and use the binaries locally, but this means
you have to write your own init or upstart service for it, if you
want to handle them properly.

*In my opinion the best: Get the repository version of source code with apt-get source, overwrite it with the new source, and build it the debian way. There is a quite good tutorial on package building here. The only drawback is, if there is some change in the building  process, you have to make the changes in the debian scripts too.

You should also consider, that a new version might depend on a newer library than your repository has. In this case you might find a ppa of a newer build, or you should build one yourself with the same way, but this can be a quite long process, walking through all the dependencies.
In short, if you are luck you may get through this fairly quick and easy. If you are not, then you are better using your distro's version.

A: It all depends how critical your production system is. Can you afford down time if changes in the way the downloaded version works cause an issue with your system? The latest version of the software may have a bug or bugs which were not in the previous version. Or side-effects of the latest version may affect your system - perhaps in a subtle way that is difficult to identify and correct.
Introducing new software in this way is risky. Yes it is tempting to keep up-to-date with the latest software. The opposing strategy of not updating software can result in systems with software running from ten or even twenty years ago. This does actually happen with real production systems.
Downloading the software to a test system which mirrors the production system and then applying a full suite of testing before considering applying the changes to production would be a safer practice. Automated testing can help with the burden of testing an entire system. Of course, that can be a substantial effort. It's a trade-off between the importance of maintaining reliable service and the resources required to assure those concerned the system will be safe if the changes are applied.


text:
Q: Remove from List based on sub-string match sampleList.RemoveAll(a=>a.reference.Contains("123"));

This line of code does not remove any item from the list whereas
sampleList.RemoveAll(a=>!a.reference.Contains("123"));

removes all the items.
I have currently resorted to making another list and going through a for loop and adding stuff to the second list, but I dont really like this approach.
Is there a cleaner way to achieve what I am trying ?

A: The fact that the second example "removes all the items" and the first removes none, leads me to conclude that none of the item's reference property in the list contains the string "123".
Elementry my dear watson ;)

A: I would guess your sampleList contains no elements containing "123". This is proven by the fact that the first attempt removes nothing, and the second attempt (which is the reverse of the first) removes everything.
Here is a sample console application I wrote to test out what I think your trying to achieve, and it works:
static void Main(string[] args)
{
    List<string> sampleList = new List<string>(new string[]
    {
        "Some String", "Some Other String", "Hello World", "123456789", "987654123"
    });

    Console.WriteLine("Items:");
    foreach (string item in sampleList)
    {
        Console.WriteLine(item);
    }

    Console.WriteLine("\nRemoving items containing \"123\"...");

    int itemsRemoved = sampleList.RemoveAll(str => str.Contains("123"));
    Console.WriteLine("Removed {0} items.", itemsRemoved);

    Console.WriteLine("\nItems:");
    foreach (string item in sampleList)
    {
        Console.WriteLine(item);
    }

    Console.ReadKey();
}

Start by checking the values of the items in your collection. Once you've made sure the values contain what they should, check the return value of RemoveAll(...) to check the right number of elements have been removed.


text:
Q: log4j don't log after redeploy We have common configuration for log4j2.xml under catalina base directory. so all the modules under webapps use this configuration. Also log4j-core, log4j-web and log4j-api libraries under shared lib of tomcat. When we restart the tomcat all the modules wrote their logs. But when redeploy any of them only that module logs others not. For example we have A,B and C module under the webapps folder. If we redeploy C module after restart then we see only C module logs. How can I solve this problem? I could not found any reson why this happen
I enabled the log4j logs to see what is happening. After redeploy log4j print this kind of logs
2021-04-13 17:40:56,930 Catalina-utility-1 DEBUG Registering MBean org.apache.logging.log4j2:type=457e2f02
2021-04-13 17:40:56,930 Catalina-utility-1 DEBUG Registering MBean org.apache.logging.log4j2:type=457e2f02,component=StatusLogger
2021-04-13 17:40:56,930 Catalina-utility-1 DEBUG Registering MBean org.apache.logging.log4j2:type=457e2f02,component=ContextSelector
2021-04-13 17:40:56,930 Catalina-utility-1 DEBUG Registering MBean org.apache.logging.log4j2:type=457e2f02,component=Loggers,name=

457e2f02 this should be the our module name but why log4j print random text
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG" monitoring="10">
    <Properties>
        <Property name="log.level">ALL</Property>
        <Property name="framework.log.level">WARN</Property>
        <Property name="file.pattern">%d{DEFAULT}: [%level{WARN=WAR, DEBUG=DBG, ERROR=ERR, TRACE=TRC, INFO=INF, FATAL=FTL}] %-c.%M[%L] - %m%n</Property>
        <Property name="console.pattern">%highlight{%d{DEFAULT}: [%level{WARN=WAR, DEBUG=DBG, ERROR=ERR, TRACE=TRC, INFO=INF, FATAL=FTL}] %-c.%M[%L] - %m%n \n}{FATAL=red blink, ERROR=red bold, WARN=yellow bold, INFO=green bold, DEBUG=white bold, TRACE=cyan}</Property>
        <Property name="logs.dir">logs</Property>
        <Property name="app.name">magus</Property>
        <Property name="script.test.mode">false</Property>
    </Properties>

    <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <PatternLayout pattern="${console.pattern}"/>
        </Console>
    <Socket name="GELF" protocol="tcp" host="graylog.host" port="12201">
            <!-- gelf tcp does not support compression-->
            <GelfLayout includeStackTrace="true" host="${hostName}" includeThreadContext="true" includeNullDelimiter="true"
                  compressionType="OFF">

                <KeyValuePair key="host" value="${hostName}"/>
                <KeyValuePair key="version" value="1.1"/>
                <!--<KeyValuePair key="short_message" value="$${event:Message}"/>--><!--   not required             -->
                <!--<KeyValuePair key="application_name" value="$${ctx:application}"/>-->
                <KeyValuePair key="thread_id" value="$${event:ThreadId}"/>
                <KeyValuePair key="thread_name" value="$${event:ThreadName}"/>
                <KeyValuePair key="timestamp" value="$${event:Timestamp}"/>
                <!--<KeyValuePair key="level" value="1"/>--><!-- default level type is number so we don't use-->
                <KeyValuePair key="log_level" value="$${event:Level}"/><!-- for readabilty and filtering-->
            </GelfLayout>
        </Socket>
        <RollingFile name="LOG" fileName="${logs.dir}/${app.name}.log"
                     filePattern="${logs.dir}/$${date:yyyy-MM}/${app.name}-%d{yyyy-MM-dd}.log.gz">
            <PatternLayout pattern="${file.pattern}"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
            </Policies>
            <DefaultRolloverStrategy max="3">
                <!--
                Nested conditions: the inner condition is only evaluated on files
                for which the outer conditions are true.
                -->
                <Delete basePath="${logs.dir}" maxDepth="2" testMode="${script.test.mode}">
                    <IfFileName glob="*/${app.name}*.log.gz">
                        <IfLastModified age="90d">
                            <IfAny>
                                <IfAccumulatedFileCount exceeds="10"/>
                            </IfAny>
                        </IfLastModified>
                    </IfFileName>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="CONSOLE"/>
            <AppenderRef ref="LOG"/>
        <AppenderRef ref='GELF' />
        </Root>

        <Logger name="xxx.project" level="${log.level}"/>
        <Logger name="org.hibernate" level="${framework.log.level}"/>
        <Logger name="com.zaxxer" level="${framework.log.level}"/>
        <!--<Logger name="org.hibernate" level="ALL"/>-->
        <Logger name="org.reflections" level="OFF"/>
    <!-- show executed queries -->
        <!--<Logger name="org.hibernate.SQL" level="DEBUG"/>-->
        <!-- show query params -->
    <!--
    <Logger name="org.hibernate.type.descriptor.sql" level="TRACE"/> -->
        <!--
        <AsyncLogger name="az.sanco.projects.ais.server.filter" additivity="false" level="${log.level}">
            <AppenderRef ref="AUDITOR"/>
        </AsyncLogger> -->
    </Loggers>
</Configuration>

Tomcat version: 9.0
Java version: 1.8
log4j2 version: 2.14.0

A: The random name 457e2f02 of your LoggerContext suggests that all your applications are using a single context. When one of your applications is stopped, the stop method is called on the context and no further messages can be logged. Meanwhile the reloaded application creates a context for itself.
This can occur, if you are using the Log4j API directly in your applications, but you don't ship the applications with a copy of log4j-api: in this situation the LogManager class in the shared Tomcat classloader will be used by all applications.
Try adding log4j-api.jar to your applications.

A: Actually @PiotrP.Karwasz answer solves the log4j problem. But don't solve our problem. If we applied him answer then we should move all log4j-core, log4j-api, and log4j-web jars to each of our applications WEB-INF\lib folder which is not efficient way. because we have almost 20 modules and in this case we copy jars to all these modules and occupies more resource. According log seperation documentation we should not do any further configuration for this requirements. Log4j context selector should choose context auto for each war modules. But in practice we saw that it does not work properly. Maybe bug or may be we did not configure correctly. I did the third option org.apache.logging.log4j.core.selector.JndiContextSelector from documentation. And this solve our problems. We keep log4j-core, log4j-api, and log4j-web jars in common path and each of our modules use these jars. Now log4j works properly when we redeploy one of our module.


text:
Q: having trouble storing and adding values using this-> operator in c++ When I use this-> operator it saves the value of complex number having higher magnitude of real value in compare function, but it also overrides the value of real variable. I am unable to assess the value of c2.real.
#include <iostream>
using namespace std;
class Complex
    {
       int real,img;
       public:
       void get()
         {
            cin>>real>>img;
         }
      void display()
       {
           cout<<real<<"+"<<img<<"i"<<endl;
       }

     Complex &compare(Complex&);
     Complex &add(Complex&);

  };

int main()
  {
      Complex c1,c2,c3;
      c1.get();
      c2.get();
      c3=c1.compare(c2);
      c3.display();
      c3=c1.add(c2);
      c3.display();
      return 0;
   }

For example for inputs 2+4i and 7+9i this function compare check for real value having high magnitude and saves the value 7 and 9 in real and img variables.
  Complex& Complex::compare(Complex &a)
     {
        if(real>a.real)
            {
               this->real=real;
               this->img=img;
            }

       else
         {
           this->real=a.real;
           this->img=a.img;
         }

         return *this;
     }

But now when I use add function it gives a sum of 14+18i which is 7+8i + 7+8i
why the value of object c2.real and c2.img have been overwritten and what can i do to have a sum of 2+4i and 7+8i.
Also this is a hacker rank question so the main function and class block are locked and cannot be edited I can only edit the compare and add function definitions.
    Complex& Complex::add(Complex &b)
             {
            this->real=real+b.real;
            this->img=img+b.img;
            return *this;
             }


text:
Q: Playwright get element from array with specific filter via C# I try to click on specific item in item list, in my cases [img alt="Amazon Logo"]:
Amazon git cart items in DOM structure.
https://i.stack.imgur.com/0HnMI.jpg
I do like this:
 await this.driver.Page.GetByRole(AriaRole.Img, new () { NameRegex = new Regex ("Amazon Logo") }).ClickAsync();

But playwright driver throws exception:
'Error: strict mode violation: GetByRole(AriaRole.Img, new() { Name = "Amazon Logo" }) resolved to 2 elements:
1)  aka GetByRole(AriaRole.Button, new() { Name = "Amazon Logo", Exact = true })
2)  aka GetByRole(AriaRole.Button, new() { Name = "Amazon Logo - Blue Flower" })

Because it finds two items:
alt="Amazon Logo"
alt="Amazon Logo - Blue Flower"

If I try press to Name="Amazon Logo - Blue Flower":
await this.driver.Page.GetByRole(AriaRole.Img, new () { NameRegex = new Regex ("Amazon Logo - Blue Flower") }).ClickAsync();

Result:
All well, but how do you click on [img alt="Amazon Logo"]?


text:
Q: How to make multiple if statements run faster in python I have following pandas dataframe
 Code      Sum      Quantity
 0         -12      0
 1          23      0
 2         -10      0
 3         -12      0
 4         100      0
 5         102      201
 6          34      0
 7         -34      0
 8         -23      0
 9         100      0
 10        100      0
 11        102      300
 12        -23       0
 13        -25       0
 14        100      123
 15        167      167

My desired dataframe is
Code      Sum      Quantity    new_sum
0         -12      0          -12
1          23      0           23
2         -10      0          -10
3         -12      0          -12
4         100      0           0
5         102      201         202
6          34      0           34
7         -34      0          -34
8         -23      0          -23
9         100      0           0
10        100      0           0
11        102      300         302
12        -23       0          -23
13        -25       0          -25
14        100      123         100
15        167      167         167

Logic is:
First I will check for non zero values in the quantity column. In the above sample data we got the first non zero occurance of quantity at index 4, which is 201. Then I want to add column sum till I get negative value in the row.
I have written a code, which uses nested if statements.However,it takes lot of time to execute the code because of multiple if's and row wise comparison.
current_stock = 0
for i in range(len(test)):
    if(test['Quantity'][i] != 0):
        current_stock = test['Sum'][i]
        if(test['Sum'][i-1] > 0):
            current_stock = current_stock + test['Sum'][i-1]
            test['new_sum'][i-1] = 0
            if(test['Sum'][i-2] > 0):
                current_stock = current_stock + test['Sum'][i-2]
                test['new_sum'][i-2] = 0
                if(test['Sum'][i-3] > 0):
                    current_stock = current_stock + test['Sum'][i-3]
                    test['new_sum'][i-3] = 0
                else:
                    test['new_sum'][i] = current_stock
            else:
                test['new_sum'][i] = current_stock
        else:
            test['new_sum'][i] = current_stock
    else:
        test['new_sum'][i] =  test['Sum'][i]

Is there any better way to do it?

A: Let's look at three solutions and provide performance comparisons at the end.
One approach that tries to stay close to pandas would be the following:
def f1(df):
    # Group together the elements of df.Sum that might have to be added
    pos_groups = (df.Sum <= 0).cumsum()
    pos_groups[df.Sum <= 0] = -1
    # Create the new column and populate it with what is in df.Sum
    df['new_sum'] = df.Sum
    # Find the indices of the new column that need to be calculated as a sum
    indices = df[df.Quantity > 0].index
    for i in indices:
        # Find the relevant group of positive integers to be summed, ensuring
        # that we only consider those that come /before/ the one to be calculated
        group = pos_groups[:i+1] == pos_groups[i]
        # Zero out all the elements that will be part of the sum
        df.new_sum[:i+1][group] = 0
        # Calculate the actual sum and store that
        df.new_sum[i] = df.Sum[:i+1][group].sum()

f1(df)

One place where there's possibly room for improvement would be in pos_groups[:i+1] == pos_groups[i] which checks all i+1 elements when, depending on what your data looks like, it could probably get away with checking a fraction of those. However, chances are this is still more efficient in practice. If not, you may want to iterate by hand to find the groups:
def f2(sums, quantities):
    new_sums = np.copy(sums)
    indices = np.where(quantities > 0)[0]
    for i in indices:
        a = i
        while sums[a] > 0:
            s = new_sums[a]
            new_sums[a] = 0
            new_sums[i] += s
            a -= 1
    return new_sums

df['new_sum'] = f2(df.Sum.values, df.Quantity.values)

Finally, depending once again on what your data looks like, there is a decent chance that the latter approach can be improved using Numba:
from numba import jit
f3 = jit(f2)
df['new_sum'] = f3(df.Sum.values, df.Quantity.values)

For the data provided in the question (which might very well be too small to provide a proper picture) the performance tests looks as follows:
In [13]: %timeit f1(df)
5.32 ms ± 77.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [14]: %timeit df['new_sum'] = f2(df.Sum.values, df.Quantity.values)
190 µs ± 5.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each

In [18]: %timeit df['new_sum'] = f3(df.Sum.values, df.Quantity.values)
178 µs ± 10.1 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Here, most of the time is spent on updating the data frame. If the data were 1000 times larger, the Numba solution would end up being a clear winner:
In [28]: df_large = pd.concat([df]*1000).reset_index()

In [29]: %timeit f1(df_large)
5.82 s ± 63.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [30]: %timeit df_large['new_sum'] = f2(df_large.Sum.values, df_large.Quantity.values)
6.27 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [31]: %timeit df_large['new_sum'] = f3(df_large.Sum.values, df_large.Quantity.values)
215 µs ± 5.76 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)