text:
Q: CSS selector for specific rect in a SVG I'm trying to select all element from a SVG that follows a pattern to change the cursor for those elements :
Here is a code sample :
<g id="group418-1085" transform="translate(1975.93,-1403.11)" v:mID="418" v:groupContext="group">
        <v:custProps>
            <v:cp v:nameU="idApplication" v:lbl="idApplication" v:type="0" v:sortKey="1" v:langID="1036" v:val="VT4(216)"/>
            <v:cp v:nameU="labelFR" v:lbl="labelFR" v:type="0" v:sortKey="3" v:langID="1036"
                    v:val="VT4(Product Ref)"/>
            <v:cp v:nameU="labelEN" v:lbl="labelEN" v:type="0" v:sortKey="4" v:langID="1036"
                    v:val="VT4(Product entity)"/>
            <v:cp v:nameU="color" v:lbl="color" v:type="0" v:sortKey="99" v:langID="1036" v:val="VT4()"/>
            <v:cp v:nameU="type" v:lbl="type" v:type="0" v:sortKey="5" v:langID="1036" v:val="VT4(Business)"/>
            <v:cp v:nameU="name" v:lbl="name" v:type="0" v:sortKey="2" v:langID="1036" v:val="VT4(FundLife)"/>
            <v:cp v:nameU="External" v:lbl="External" v:type="0" v:langID="1036" v:val="VT4(FALSE)"/>
            <v:cp v:nameU="appLevel" v:lbl="appLevel" v:type="0" v:langID="1036" v:val="VT4(2)"/>
            <v:cp v:nameU="_VisDM_status" v:lbl="status" v:type="2" v:langID="1036" v:val="VT0(1):26"/>
        </v:custProps>
        <v:userDefs>
            <v:ud v:nameU="msvStructureType" v:prompt="" v:val="VT4(Container)"/>
            <v:ud v:nameU="msvSDContainerMargin" v:prompt="" v:val="VT0(0.078740157480315):24"/>
            <v:ud v:nameU="Label" v:prompt="" v:val="VT0(2):26"/>
            <v:ud v:nameU="ShapeVersion" v:prompt="" v:val="VT0(1):26"/>
            <v:ud v:nameU="LightColorText" v:prompt="" v:val="VT0(0):5"/>
            <v:ud v:nameU="TechnicalVue" v:prompt="" v:val="VT0(0):5"/>
            <v:ud v:nameU="MainColor" v:prompt="" v:val="VT4(RGB(213;213;213))"/>
        </v:userDefs>
        <title>Application.51</title>
        <g id="shape419-1086" v:mID="419" v:groupContext="shape">
            <title>Feuille.419</title>
            <v:userDefs>
                <v:ud v:nameU="visVersion" v:val="VT0(14):26"/>
            </v:userDefs>
            <rect x="0" y="1641.26" width="113.386" height="42.5197" class="st56"/>
        </g>
        <g id="shape418-1088" v:mID="418" v:groupContext="groupContent">
            <v:textBlock v:margins="rect(4,4,4,4)" v:tabSpace="42.5197"/>
            <v:textRect cx="56.6929" cy="1662.52" width="113.39" height="42.5197"/>
            <text x="44.24" y="1652.02" class="st4" v:langID="1036"><v:paragraph v:horizAlign="1"/><v:tabList/>FundLife<v:newlineChar/><v:newlineChar/><tspan
                        x="6.06" dy="2.4em" class="st55">Product referential for all entities of </tspan><tspan x="36.1"
                        dy="1.2em" class="st55">Owner</tspan></text>            </g>
    </g>

So what I'm trying to select is the rect.
The rectI wanna select are always children of a g that is a child of another g that has a descendant with a v:nameU attribute with the value idApplication.
(This descendant is always a v:cp child of a v:custoProps child of the g like in the code above, but I dont think it's necessary to use this.)
So I was thinking of :
g v:cp[v:nameU="idApplication"] > g > rect {cursor: help;}

But this is not working.

A: The g element that is the parent of the rect element is a following sibling of the v:custProps element containing the v:cp element in question:
<v:custProps>
    <v:cp v:nameU="idApplication" v:lbl="idApplication" v:type="0" v:sortKey="1" v:langID="1036" v:val="VT4(216)"/>
    <!-- ... -->
</v:custProps>
<!-- ... -->
<g id="shape419-1086" v:mID="419" v:groupContext="shape">
    <rect x="0" y="1641.26" width="113.386" height="42.5197" class="st56"/>
</g>

Since the v:cp element is a child of the v:custProps, while it is possible to represent the v:cp and rect elements separately like so:
@namespace v 'http://schemas.microsoft.com/visio/2003/SVGExtensions/';

g[id="group418-1085"] > v|custProps > v|cp[v|nameU="idApplication"] { /* ... */ }
g[id="group418-1085"] > v|custProps ~ g > rect { /* ... */ }

It is not possible to target the rect element based on that v:cp element in a single selector. Furthermore, combinators are linear and only accept two compound selectors at a time, and you can't change this, so it is not possible to combine the above two selectors into one.
(Also, to represent namespaced elements and attributes in selectors, you need to declare a namespace prefix and use the appropriate syntax as shown above, but that's a side issue and fixing it won't be of much use here.)


text:
Q: Schema Best Practice: Is it ever OK to store duplicates of a record? This is a general question about good schema design. In my case I'm using Rails 4 and PostgreSQL.
Let's say I have a storefront, with many products. The store also has many orders, each with many products.
On Monday, a customer pays for an order. So now, we have a product that belongs to both a storefront and an order.
On Tuesday, the store decides to change the price of one of the products.
Clearly, I don't want to change the record of what the customer purchased on Monday, so this leads me to believe I should store two copies of the product - one copy of what the store is selling now (ie Tuesday), another copy for what the customer bought on Monday.
However, I know that duplicating data like this something generally to be avoided.
Is there a best-practice for handling a situation like this?

A: That only sounds like duplication because you're using the same name for them. One price is the price the customer paid. The other is the price a product is currently sold at. They're separate pieces of data, even though in a lot of the cases they have the same value. I'd just give them separate names (e.g. Order#paid v. Product#price), and store the Product#price in Order#paid at the time of the sale. That way the product price can be change however needed without affecting the order.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++-style private access in Scala? In C++, one can have (please forgive errors as I haven't done C++ in a while and corrections are appreciated):
class Super {
    private: virtual void g() = 0;
    public: void f() {
        g();
    }
};

class Sub: public Super {
    private: virtual void g() {
    }
};

such that Sub defines g but cannot call it directly.
Can the same thing be done in Scala?

A: If you try it like this
abstract class Super {
  private def g()

  def f() {
    g()
  }
}

the compiler will give you this error messge:

scala: abstract member may not have private modifier
    private def g()

You have to declare g() at least protected.

A: I think the closest thing is
abstract class Super {
  protected[this] def g: Int
  def f { println(g) }
}
class Sub extends Super {
  protected[this] def g = 5
}

but this does not give Super any more access rights than Sub; it just prevents Sub from calling that method on other instances.
The exact same pattern is not possible in Scala.  (It would have to be a compiler fiction, as the JVM doesn't support it, but many of the access patterns are already compiler fictions.)


text:
Q: Multiple word queries on solr
*

*I am using solr 3.3.0 working out of the box using the example folder

*solrQueryParser defaultOperator = "OR"

My problem is that Solr doesn't seem to be returning good results when I search for a multiple word phrase.
The following search return no results.

*

*http://localhost:8080/solr/select/?q=roof+fixing
However, when I search for roof or fixing, they both return a few good results.

*

*http://localhost:8080/solr/select/?q=roof returns 4 results

*http://localhost:8080/solr/select/?q=fixing returns 3 results
On the query for "roof fixing", I expect solr to return 7 results. The 4 records for roof  and 3 records for fixing.
Is any special configuration necessary for that to happen?

A: You just expressed your query incorrectly.
Try the following query from the Admin page:
(roof OR fixing)
Or, if you want to find that in a particular field:
fieldname:(roof OR fixing)
When you give SOLR a query like "roof fixing" you are effectively asking for all documents which have "roof" AND "fixing" in the default field (or the default dismax set of fields. The only way to change the meaning is to rewrite the query that your users type in. That's what we do, but on a larger scale. We have a front end interface that provides a whole bunch of options and generate a SOLR query from it. People can enter a search term in a specific field and if there is more than one word and it's not quoted, we add the AND. Then we OR together all of the fields that are filled in. Some fields are special and have a MIN and a MAX version which we turn into a range query :[0 TO 125000]. And there are some dropdowns that support multiple selections which we also turn into an OR, e.g. State:("WA" OR "CA" OR "OR" OR "NV")

A: Solr won't necessarily return 7 results for "roof OR fixing" as one result could include both "roof" and "fixing". Suppose "roof" has 3 results, "fixing" has 4, but both "roof" and "fixing" appear in 2 results. You will get only 5 results on a search for "roof OR fixing" as Solr will not return duplicate results.
Have you tried using a url-encoded space ("%20") instead of the "+" sign? If the default operator is OR you should not need to include that operator.


text:
Q: prolog query gets stuck even when base predicates are defined i am creating a rubiks cube solver in prolog. i have implemented the predicates for solving white edges.
but when i query it, it gets stuck.
this is the code:
:-use_module(library(random)).
print_lis([]).
print_lis([Head|Tail]):-
    write(Head),nl,
    print_lis(Tail).
cube([[w,w,w,w,w,w,w,w,w],[r,r,r,r,r,r,r,r,r],[b,b,b,b,b,b,b,b,b],[o,o,o,o,o,o,o,o,o],[y,y,y,y,y,y,y,y,y],[g,g,g,g,g,g,g,g,g]]).
m([[W1,W2,W3,W4,w,W6,W7,W8,W9],[R1,R2,R3,R4,r,R6,R7,R8,R9],[B1,B2,B3,B4,b,B6,B7,B8,B9],[O1,O2,O3,O4,o,O6,O7,O8,O9],[Y1,Y2,Y3,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,G7,G8,G9]],
  g,
  [[O3,O6,O9,W4,w,W6,W7,W8,W9],[W3,R2,R3,W2,r,R6,W1,R8,R9],[B1,B2,B3,B4,b,B6,B7,B8,B9],[O1,O2,Y9,O4,o,Y8,O7,O8,Y7],[Y1,Y2,Y3,Y4,y,Y6,R1,R4,R7],[G7,G4,G1,G8,g,G2,G9,G6,G3]]).
m([[W1,W2,W3,W4,w,W6,W7,W8,W9],[R1,R2,R3,R4,r,R6,R7,R8,R9],[B1,B2,B3,B4,b,B6,B7,B8,B9],[O1,O2,O3,O4,o,O6,O7,O8,O9],[Y1,Y2,Y3,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,G7,G8,G9]],
  o,
  [[W1,W2,B3,W4,w,B6,W7,W8,B9],[R1,R2,R3,R4,r,R6,R7,R8,R9],[B1,B2,Y3,B4,b,Y6,B7,B8,Y9],[O7,O4,O1,O8,o,O2,O9,O6,O3],[Y1,Y2,G3,Y4,y,G6,Y7,Y8,G9],[G1,G2,W3,G4,g,W6,G7,G8,W9]]).
m([[W1,W2,W3,W4,w,W6,W7,W8,W9],[R1,R2,R3,R4,r,R6,R7,R8,R9],[B1,B2,B3,B4,b,B6,B7,B8,B9],[O1,O2,O3,O4,o,O6,O7,O8,O9],[Y1,Y2,Y3,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,G7,G8,G9]],
  b,
  [[W1,W2,W3,W4,w,W6,R9,R6,R3],[R1,R2,Y1,R4,r,Y2,R7,R8,Y3],[B7,B4,B1,B8,b,B2,B9,B6,B3],[W7,O2,O3,W8,o,O6,W9,O8,O9],[O7,O4,O1,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,G7,G8,G9]]).
m([[W1,W2,W3,W4,w,W6,W7,W8,W9],[R1,R2,R3,R4,r,R6,R7,R8,R9],[B1,B2,B3,B4,b,B6,B7,B8,B9],[O1,O2,O3,O4,o,O6,O7,O8,O9],[Y1,Y2,Y3,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,G7,G8,G9]],
  r,
  [[G1,W2,W3,G4,w,W6,G7,W8,W9],[R7,R4,R1,R8,r,R2,R9,R6,R3],[W1,B2,B3,W4,b,B6,W7,B8,B9],[O1,O2,O3,O4,o,O6,O7,O8,O9],[B1,Y2,Y3,B4,y,Y6,B7,Y8,Y9],[Y1,G2,G3,Y4,g,G6,Y7,G8,G9]]).
m_u([[W1,W2,W3,W4,w,W6,W7,W8,W9],[R1,R2,R3,R4,r,R6,R7,R8,R9],[B1,B2,B3,B4,b,B6,B7,B8,B9],[O1,O2,O3,O4,o,O6,O7,O8,O9],[Y1,Y2,Y3,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,G7,G8,G9]],
  [[W7,W4,W1,W8,w,W2,W9,W6,W3],[B1,B2,B3,R4,r,R6,R7,R8,R9],[O1,O2,O3,B4,b,B6,B7,B8,B9],[G9,G8,G7,O4,o,O6,O7,O8,O9],[Y1,Y2,Y3,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,R3,R2,R1]]).
m_d([[W1,W2,W3,W4,w,W6,W7,W8,W9],[R1,R2,R3,R4,r,R6,R7,R8,R9],[B1,B2,B3,B4,b,B6,B7,B8,B9],[O1,O2,O3,O4,o,O6,O7,O8,O9],[Y1,Y2,Y3,Y4,y,Y6,Y7,Y8,Y9],[G1,G2,G3,G4,g,G6,G7,G8,G9]],
  [[W1,W2,W3,W4,w,W6,W7,W8,W9],[R1,R2,R3,R4,r,R6,B7,B8,B9],[B1,B2,B3,B4,b,B6,O7,O8,O9],[O1,O2,O3,O4,o,O6,G3,G2,G1],[Y7,Y4,Y1,Y8,y,Y2,Y9,Y6,Y3],[R9,R8,R7,G4,g,G6,G7,G8,G9]]).
right(r,b).
right(b,o).
right(o,g).
right(g,r).
left(X,Y):-right(Y,X).
back(o,r).
back(b,g).
back(X,Y):-back(Y,X).
f(Cube,Col,NewCube):-
    write('F'),write(Col),nl,
    m(Cube,Col,NewCube).
r(Cube,Col,NewCube):-
    write('R'),write(Col),nl,
    right(Col,Col2),
    m(Cube,Col2,NewCube).
l(Cube,Col,NewCube):-
    write('L'),write(Col),nl,
    left(Col,Col2),
    m(Cube,Col2,NewCube).
b(Cube,Col,NewCube):-
    write('B'),write(Col),nl,
    back(Col,Col2),
    m(Cube,Col2,NewCube).
u(Cube,NewCube):-
    write('U'),nl,
    m_u(Cube,NewCube).
d(Cube,NewCube):-
    write('D'),nl,
    m_d(Cube,NewCube).
f_(Cube,Col,NewCube):-
    write('F\''),write(Col),nl,
    m(NewCube,Col,Cube).
r_(Cube,Col,NewCube):-
    write('R\''),write(Col),nl,
    right(Col,Col2),
    m(NewCube,Col2,Cube).
l_(Cube,Col,NewCube):-
    write('L\''),write(Col),nl,
    left(Col,Col2),
    m(NewCube,Col2,Cube).
b_(Cube,Col,NewCube):-
    write('B\''),write(Col),nl,
    back(Col,Col2),
    m(Cube,Col2,NewCube).
u_(Cube,NewCube):-
    write('U\''),nl,
    m_u(NewCube,Cube).
d_(Cube,NewCube):-
    write('D\''),nl,
    m_d(NewCube,Cube).
cube('W','R','B','O','Y','G').
write_face([A,B,C,D,E,F,G,H,I]):-write([A,B,C]),nl,write([D,E,F]),nl,write([G,H,I]),nl.
display([W,R,B,O,Y,G]):-
    write('W:'),write_face(W),
    write('R:'),write_face(R),
    write('B:'),write_face(B),
    write('O:'),write_face(O),
    write('Y:'),write_face(Y),
    write('G:'),write_face(G).
face(w,[F,_,_,_,_,_],F).
face(r,[_,F,_,_,_,_],F).
face(b,[_,_,F,_,_,_],F).
face(o,[_,_,_,F,_,_],F).
face(y,[_,_,_,_,F,_],F).
face(g,[_,_,_,_,_,[A,B,C,D,E,F,G,H,I]],[I,H,G,F,E,D,C,B,A]).
rot(b,Face,Face).
rot(r,[A,B,C,D,E,F,G,H,I],[C,F,I,B,E,H,A,D,G]).
rot(o,[A,B,C,D,E,F,G,H,I],[G,D,A,H,E,B,I,F,C]).
rot(g,[A,B,C,D,E,F,G,H,I],[I,H,G,F,E,D,C,B,A]).
:-op(1000,fx,display).
white_edge(Cube,Col,SolCube):-
    back(Col,B),
    left(Col,L),
    right(Col,R),
    face(Col,Cube,Cf),
    face(B,Cube,Bf),
    face(L,Cube,Lf),
    face(R,Cube,Rf),
    face(w,Cube,W),
    face(y,Cube,Y),
    rot(Col,W,Wf),
    rot(Col,Y,Yf),
    from(edge,Cube,Col,Cf,Bf,Lf,Rf,Wf,Yf,SolCube).
from(edge,Cube,C,
     [_,C,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,w,_],
     [_,_,_,_,_,_,_,_,_],
     Cube).
from(edge,Cube,C,
     [_,_,_,C,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,w,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    f(Cube,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,C,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,w,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    f_(Cube,c,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,C,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,w,_,_,_,_,_,_,_],
     Solcube):-
    f(Cube,C,C1),
    f(C1,C,Solcube).
from(edge,Cube,C,
     [_,w,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,C,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    f(Cube,C,C1),
    f(C1,C,C2),
    d(C2,C3),
    r(C3,C,C4),
    f_(C4,C,C5),
    r_(C5,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,w,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,C,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    f(Cube,C,C2),
    d(C2,C3),
    r(C3,C,C4),
    f_(C4,C,C5),
    r_(C5,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,w,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,C,_,_,_,_,_,_,_],
     Solcube):-
    d(Cube,C3),
    r(C3,C,C4),
    f_(C4,C,C5),
    r_(C5,C,Solcube).
from(edge,Cube,C,
     [_,_,_,w,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,C,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    f_(Cube,C,C2),
    d(C2,C3),
    r(C3,C,C4),
    f_(C4,C,C5),
    r_(C5,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,w,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,C,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    r(Cube,C,C1),
    d_(C1,C2),
    r_(C2,C,C3),
    f_(C3,C,C4),
    f_(C4,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,w,_,_,_],
     [_,_,_,C,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    l_(Cube,C,C1),
    d(C1,C2),
    l(C2,C,C3),
    f(C3,C,C4),
    f(C4,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,C,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,w,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    b_(Cube,C,C1),
    d_(C1,C2),
    d_(C2,C3),
    b(C3,C,C4),
    f_(C4,C,C5),
    f_(C5,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,C,_,_,_],
     [_,_,_,w,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    b(Cube,C,C1),
    d(C1,C2),
    d(C2,C3),
    b_(C3,C,C4),
    f(C4,C,C5),
    f(C5,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,C,_,_,_,_,_,_,_],
     [_,_,_,_,_,w,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    r(Cube,C,C1),
    r(C1,C,C2),
    d_(C2,C3),
    f(C3,C,C4),
    f(C4,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,w,_,_,_,_,_,_,_],
     [_,_,_,_,_,C,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    r_(Cube,C,C1),
    f_(C1,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,w,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,C,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     Solcube):-
    l_(Cube,C,C1),
    l_(C1,C,C2),
    f(C2,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,w,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,C,_,_,_,_,_],
     Solcube):-
    l(Cube,C,C1),
    f(C1,C,C2),
    l_(C2,C,Solcube).
from(edge,Cube,C,
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,_,_,w,_],
     [_,_,_,_,_,_,_,_,_],
     [_,_,_,_,_,C,_,_,_],
     Solcube):-
    r(Cube,C,C1),
    f_(C1,C,C2),
    r_(C2,C,Solcube).
white_edges(Cube,SolCube):-
    white_edge(Cube,g,C1),
    white_edge(C1,o,C2),
    white_edge(C2,b,C3),
    white_edge(C3,r,SolCube).
mov(0,w).
mov(1,r).
mov(2,b).
mov(3,o).
mov(4,y).
mov(5,g).
mov(Cube,Col,JumCube):-f(Cube,Col,JumCube).
jumble(0,Cube,Cube).
jumble(X,Cube,JumCube):-
    random_between(0,5,C),
    write(C),
    Y is X-1,
    write(Y),nl,
    mov(C,Col),
    mov(Cube,Col,C1),
    jumble(Y,C1,JumCube).
jumble(Cube,JumCube):-
    random_between(10,30,S),
    write(S),nl,
    jumble(S,Cube,JumCube).

when i input this query:-
?-white_edges(X,Y),display(Y).

:(assuming X to be any jumbled state of cube)
it gets stuck without printing a thing.
it would be even better if you can provide me with implementation of any other algorithm or a better implememtation of mine (preferrably using my predicates for f,f',u,r,b,etc.

A: You can find an implementation in SWI-Prolog.
Start XPCE IDE (for instance, on Linux):
$ swipl
Welcome to SWI-Prolog (threaded, 64 bits, version 8.1.15)
...

?- emacs.

then open the menu Help \ Xpce Manual
From the small window titled XPCE Manual, open File \ Demo programs. The last line of the newly opened window should be
Rubiks cube      THe Rubiks Cube Game

The code is fairly sophisticated, being very compact and a lot of it being devoted to the graphical processing. From the XPCE editor of rubikpce.pl, right click on
:-use_module(rubik).

and inspect the solver. The code is well commented, and you can use the debugger by means of
?- gtrace,rubikpce.

Good luck...


text:
Q: Something like the "old" visual basic for web development Do you remember the old "good" times when, to make an app, you basically used only one language? Well, that wasn't completely true, because you always has to squeeze some sql here and there, but basically 90% of the time your app was only one language. No matter if was Visual Basic, Delphi, PowerBuilder, or C++, what I like of desktop applications is precisely that: in my opinion, one bad abstractions is better that 5 good ones.
Well, you could agree or not, but the truth is that, to make a web app, you need sql, php (or c#, or java, or ruby, or what ever other language), and javascript, and HTML and CSS.
I will like to know if exists something that abstracts all of this languages and let create web app as desktop apps.
Do you know any technology like that? more points if is open source and stable.

A: I believe that what you are asking for can be built using libraries from the Clojure ecosystem. Basic building blocks would include

*

*A wrapper around HTTP,

*A library taking care of interactions with a relational database,

*An HTML generator or a templating engine,

*A DSL abstracting away the nightmare of CSS, and

*ClojureScript, which compiles Clojure to JavaScript.

As a result all languages listed in your question would be hidden behind abstractions written in Clojure, including both the back- and front-end of the application.
I cannot point you to any complete web application stack which fully solves the problem you're describing. The reason is the fact that in the Clojure ecosystem it is conventional to build and publish small libraries which focus on a single problem. As a result you're free to choose the subset of tools which is most appropriate for your use case. You don't get the gorilla and the jungle.

A: I believe GWT maybe what you are looking for. You write Java code with the JavaScript generated for you. It is also much more broadly supported than Clojure.


text:
Q: Main page of SO is telling me there are no questions I clicked on the logo for Stack Overflow to go back to the home page and it told me no questions were found. This also happens when I open a new tab and go to stackoverflow.com.

My last view had been tags=WPF with the Needs Answer tab selected, so I know there are plenty of questions here.
I had noticed going back to the main page was being obnoxiously slow today, so suspect this is just a timeout instead of an actual problem with no results found.
Can you fix the slowness of going back to the main page of SO by clicking on the logo? Alternatively, perhaps load the default SO page if a timeout occurs retrieving the user's last used question filter.
(PS. I'm in favor of having the logo go back to the default view of SO in all cases, with no filters applied. That would be my preferred "solution") :)
Edit I do not think this is an exact duplicate of The search is incorrectly returning a no results message because I obtained this message by going to StackOverflow's homepage, not by using search results. In addition, the only answer posted there is status-norepro.
Having a message that there are no questions on the homepage seems like a bigger deal than encountering that message when searching, and additional code may be required to handle this correctly.
Edit #2 I just went to stackoverflow.com from a new browser window, and got the same error screen.
I didn't realize my previous filter was cached and re-used when I visit the page in a separate session. This seems like something that should definitely be addressed if timeout issues are common.


text:
Q: Почему стоит отказываться от HttpUrlConnection? Был сегодня на интервью.Ответил на все вопросы ,но вот на один они сказали ответ не правилен .Было задание подключиться к web-services ну и там по апи сделать разные дейтсвия.Всё окей только отметили что для этого я использовал HttpUrlConnection и сказали лучше найти ей альтернативу .Ясное дело я не смог у них спросить почему)Так вот, чем плох HttpUrlConnection и что посоветуете в замен.И почему

A: Я бы не стал за использование HttpUrlConnection бить по рукам. Просто это более низкоуровневый механизм.
Вам необходимо заботиться о многих вещах самому:

*

*Необходимо оборачивать это дело в AsycnTask.

*Хендлить случаи со сворачиванием игры.

*Обрабатывать повороты экрана.

*Писать кеш свой.

Тот же Retrofit из коробки будет быстрее, так как там встроенный механизм кеша.
Поэтому и рекомендуют volley/retrofit использовать. Уменьшается вероятность ошибки, меньше кода писать. Код читабельней и т.п.
Но, опять же, лично я бы не стал за ответ с использованием HttpUrlConnection минус ставить.


text:
Q: Showing the data over a year in a graph in Excel Is it possible to have a graph in excel show the collected data over the past year automatically?
Background information:
I collect data and I wish to present it in a graph showing the last year. At the moment i need to manually adjust the dates wich are showing. I have a feeling this can be automated, but wasn't able to find a solution on our great big friend Google

A: Make yourself a "named range" and in your case that range will be a formula.  you can define a Named Range or Named Formula using the ribbon, Formulas tab and in the Defined Names section:

Lets say your data is listed vertically in column C starting in row 4 because you have some header and row information before the data.
You could use the TODAY() function to define today as your reference point.  However it is a volatile function and could cause a some excess calculations that could bog down your system.  Not a big issue on small data, but particularly bad in array functions.  I would hazard a guess that you want 365 days before a certain date.  Like the day you prepared your presentation/report, not necessarily the day of your presentation or date of print.  I would therefore place the reference date some cell.  For this case lets use E2 for the end reference date and E3 for the start reference date.
In E2 Just enter the last date to report to.
In E3 either manually enter the last date you want to report to use the following formula to automatically grab a date 365 days earlier:
=E2-365

365 being the number of days in a regular year.  If you want to get more complex you can replace 365 with a formula that determines leap year or not but thought I would keep this on the simpler side for now.
The next step is to determine the row of your first date of interest.  Assuming your dates are in ascending order C4:C1000 you can use MATCH to find the earliest entries.  This can then be passed to INDEX to get the address of the first row.
INDEX($C:$C,IFERROR(MATCH($E$2,$C:$C,1),0)+1)

The IFERROR is there to handle the case of the the date in E3 being off the start of your list.  The +1 is to handle the Match result of being the date before your cut off off.  It bumps the ruslt to the next row.  The MATCH(,,1) finds the largest value that is less than or equal to the search value.  I am guessing at being off 1 date entry is not that big a deal, but if it is you  can change the +1 to see if the match result for and approximate search is the same as for an exact search or the value in E3.
And then something very similar can be done for finding the last row.
INDEX($C:$C,IFERROR(MATCH($E$2,$C:$C,1),1))

The IFERROR result here is set to 1 since there is no +1 option to consider.  by doing so it makes the first date in your list the only result when your selected date range is before all your data.
now that you have the start and end point of your desired date range, define your range in the format:
INDEX():INDEX()

in this case it is:
INDEX($C:$C,IFERROR(MATCH($E$2,$C:$C,1),0)+1):INDEX($C:$C,IFERROR(MATCH($E$2,$C:$C,1),1))

The above covers your dates, but you will also want to adjust it for your Y value (other data).  To do so, you just need to change the C:C reference for the INDEX range to the column of your other data.  In this example set it would be change C:C to D:D as follows:
INDEX($D:$D,IFERROR(MATCH($E$2,$C:$C,1),0)+1):INDEX($D:$D,IFERROR(MATCH($E$2,$C:$C,1),1))

Now that your have a formula for a range you need to place it in a defined name.  Having said that I would place the above formulas in a cell to take care of bracket count checking and making range selection easier.  The cell will evaluate to an error when the two indexes are combined but that is ok.  You can check the individual indexes to see if it working right.  The other reason for putting them in a cell, is you can copy the formula to the clip board before going to the named formula.
Click on Define Name in the ribbon as pointed out at the start of the answer.  A windows like the following should appear:

Enter a name for you X series.  No spaces and I am not sure but to save grief I would avoid special characters with the exception of underscore.  In the example you can see I called it X_Series.  At the bottom paste or type in your formula formula corresponding to the series name.  Repeat this process for each of the other series you need.  In my example I did it again for Y_Series. as you can see in the Name Manager window below:

Finally insert your graph and go to your DATA SERIES information.  In this example I was using an X-Y Scatter plot.

Then edit the series and set the x series to workbook/filename ! Named Formula.  This means you need to save your workbook first for it to work.  In this case I save the workbook as DEMO.xlsx.  You can see how I filled out the series below:

You can also verify that the series are being appropriately picked by selecting the graph and seeing where in the C:C or D:D column in this case is being highlighted:

So now when you change the date in cell E2 the graph will update on its own accordingly.  Make sure your remove any manual limits you placed on your graph if you want to see the updates happen as the update may wind up pushing you beyond the limits you previously imposed.


text:
Q: Multi-series in dimplejs I am tinkering with a multi-series chart in dimplejs and got a bit stuck with the multi axis logic.
With the following data:
var data = [
  {"Month":"01/2013", "Revenue":2000, "Profit":2000, "Units":4},
  {"Month":"02/2013", "Revenue":3201, "Profit":2000, "Units":3},
  {"Month":"03/2013", "Revenue":1940, "Profit":14000, "Units":5},
  {"Month":"04/2013", "Revenue":2500, "Profit":3200, "Units":1},
  {"Month":"05/2013", "Revenue":800, "Profit":1200, "Units":4}
]

I try to get a chart showing, by months, my revenue and my profit on the same y axis and my units on a secondary y axis.
With the code below, I could manage to display the 3 series. But the Profit series isn't really on the same axis as the Revenue one, and the whole thing seems more like a hack than a proper solution.
var chart = new dimple.chart(svg, data);

chart.setBounds(60,20,680,330);

var x = chart.addCategoryAxis("x", "Month");
var y1 = chart.addMeasureAxis("y", "Revenue");
chart.addSeries("null", dimple.plot.line, [x,y1]);
var y2 = chart.addMeasureAxis("y", "Units");
chart.addSeries("null", dimple.plot.bar, [x,y2]);
var y3 = chart.addMeasureAxis("y", "Profit");
chart.addSeries("null", dimple.plot.line, [x,y3]);

I guess my logic might be wrong with how to rightly play with series. Any help would be great.
Thanks a lot,
Xavier
Full code:
var svg = dimple.newSvg("body", 800, 400);

var data = [
    {"Month":"01/2013", "Revenue":2000, "Profit":2000, "Units":4},
    {"Month":"02/2013", "Revenue":3201, "Profit":2000, "Units":3},
    {"Month":"03/2013", "Revenue":1940, "Profit":14000, "Units":5},
    {"Month":"04/2013", "Revenue":2500, "Profit":3200, "Units":1},
    {"Month":"05/2013", "Revenue":800, "Profit":1200, "Units":4}
]

var chart = new dimple.chart(svg, data);

chart.setBounds(60,20,680,330);

var x = chart.addCategoryAxis("x", "Month");
var y1 = chart.addMeasureAxis("y", "Revenue");
chart.addSeries("null", dimple.plot.line, [x,y1]);
var y2 = chart.addMeasureAxis("y", "Units");
chart.addSeries("null", dimple.plot.bar, [x,y2]);
var y3 = chart.addMeasureAxis("y", "Profit");
chart.addSeries("null", dimple.plot.line, [x,y3]);

x.dateParseFormat = "%m/%Y";
x.addOrderRule("Date");

chart.draw();

A: EDIT:
This is no longer required since version 2.  You can now use composite axes.
ORIGINAL:
I see the problem here, the issue isn't with multiple axes, it is with trying to draw multiple measures against a single axis which Dimple doesn't really support yet.  I'm afraid the best I can do for now is a bit of a data hack:
<div id="chartContainer">
  <script src="http://d3js.org/d3.v3.min.js"></script>
  <script src="/dist/dimple.v1.min.js"></script>
  <script type="text/javascript">
      var svg = dimple.newSvg("#chartContainer", 800, 400);

      // Data hack required to get revenue and profit on the same axis, units are
      // arbitrarily allocated to revenue but the values will be summed by date
      var data = [
          {"Month":"01/2013", "Metric":"Revenue", "Revenue/Profit":2000, "Units":4},
          {"Month":"02/2013", "Metric":"Revenue", "Revenue/Profit":3201, "Units":3},
          {"Month":"03/2013", "Metric":"Revenue", "Revenue/Profit":1940, "Units":5},
          {"Month":"04/2013", "Metric":"Revenue", "Revenue/Profit":2500, "Units":1},
          {"Month":"05/2013", "Metric":"Revenue", "Revenue/Profit":800, "Units":4},
          {"Month":"01/2013", "Metric":"Profit", "Revenue/Profit":2000, "Units":0},
          {"Month":"02/2013", "Metric":"Profit", "Revenue/Profit":2000, "Units":0},
          {"Month":"03/2013", "Metric":"Profit", "Revenue/Profit":14000, "Units":0},
          {"Month":"04/2013", "Metric":"Profit", "Revenue/Profit":3200, "Units":0},
          {"Month":"05/2013", "Metric":"Profit", "Revenue/Profit":1200, "Units":0}
      ];

      var chart = new dimple.chart(svg, data);
      chart.setBounds(60,20,680,330);

      // Add your x axis - nothing unusual here
      var x = chart.addCategoryAxis("x", "Month");
      // First y axis is the combination axis for revenue and profit
      var y1 = chart.addMeasureAxis("y", "Revenue/Profit");
      // Second is the units only
      var y2 = chart.addMeasureAxis("y", "Units");

      // Plot the bars first - the order of series determines their dom position
      // from back to front, this means bars are at the back.  It's important
      // to note that the string here "Unit Sales" is NOT in the data.  Any string
      // not in the data is just used to apply a label which can be used for colouring
      // as it is here and will also appear in tool tips
      var bars = chart.addSeries("Unit Sales", dimple.plot.bar, [x,y2]);
      // Use a simple line by metric for the other measures
      var lines = chart.addSeries("Metric", dimple.plot.line, [x,y1]);

      // Do a bit of styling to make it look nicer
      lines.lineMarkers = true;
      bars.barGap = 0.5;
      // Colour the bars manually so they don't overwhelm the lines
      chart.assignColor("Unit Sales", "black", "black", 0.15);

      x.dateParseFormat = "%m/%Y";
      x.addOrderRule("Date");

      // Here's how you add a legend for just one series.  Excluding the last parameter
      // will include every series or an array of series can be passed to select more than
      // one
      chart.addLegend(60, 5, 680, 10, "right", lines);

      chart.draw();

      // Once Draw is called, this just changes the number format in the tooltips which for these particular
      // numbers is a little too heavily rounded.  I assume your real data isn't like this
      // so you probably won't want this line, but it's a useful tip anyway!
      y1.tickFormat = ",d";

  </script>
</div>

This is currently a bit of a limitation but I've just had an idea for a really good implementation I can do to add proper support for composite axes like this.  Hopefully that will be possible in the not too distant future.
Good luck
John


text:
Q: Javascript sort array on property array So I have this array of users that looks something like this:
[{
    userName: 'Jim',
    roles: ['Member']
}, {
    userName: 'Adam',
    roles: ['Administrator']
}, {
    userName: 'Suzy',
    roles: ['SuperUser']
}, {
    userName: 'Greg',
    roles: ['SuperUser']
}, {
    userName: 'Ady',
    roles: ['Administrator']
}, {
    userName: 'Jeremy',
    roles: ['Administrator']
}]

I would like to sort this array by it's roles.
I tried doing this:
items.sort(function (a, b) {
    var aValue = a.roles[0];
    var bValue = b.roles[0];

    if (aValue < bValue) return -1;
    if (aValue > bValue) return -1;
    return 0;
});

But it doesn't do what I expect. Does anyone know how to solve this issue?

A: You can use localeCompare method for string comparison inside sort().

var data = [{"userName":"Jim","roles":["Member"]},{"userName":"Adam","roles":["Administrator"]},{"userName":"Suzy","roles":["SuperUser"]},{"userName":"Greg","roles":["SuperUser"]},{"userName":"Ady","roles":["Administrator"]},{"userName":"Jeremy","roles":["Administrator"]}]

data.sort(function(a, b) {
  return a.roles[0].localeCompare(b.roles[0])
})

console.log(data)

A: give this a shot
function SortByRole(a, b){
  var aRole = a.roles[0];
  var bRole = b.roles[0];
  return ((aRole < bRole) ? -1 : ((aRole > bRole) ? 1 : 0));
}

array.sort(SortByRole);


text:
Q: Why is my interval of consecutive rdtsc calls periodic? I am profiling interval of consecutive rdtsc calls as suggested by this talk by David Gross.
My system is aws c5a.8xlarge instance, ubuntu 22.04 LTS server, no other user packages installed and there is no any other work load on it.
Each data point on below graph is the mean/std deviation of interval of 256 consecutive rdtsc calls. (eg. mean/std deviation of 255 intervals). I do the 256 calls once a second,
As you can see in the graph, it's periodic. Can anybody explain this for me? thanks.
The cpu frequncy is 2799.932 Mhz from cpuinfo. I converted the rdtsc value to nanosecond by dividing it with 2.799932.

The code of mean/std calculation for one data point is as below:
std::pair<double, double> trial(std::size_t nSamples) {
    folly::fbvector<uint64_t> samples(nSamples);
    for (uint64_t& s : samples) {
        s = folly::hardware_timestamp();
    }

    folly::fbvector<uint64_t> diff1(nSamples-1);
    for (std::size_t i = 0; i < nSamples-1; i++) {
        diff1[i] = samples[i+1] - samples[i];
    }
    std::cout << folly::format("{}, {}, {}", diff1[0], diff1[1], diff1[2]) << std::endl;

    double sum = std::accumulate(diff1.begin(), diff1.end(), 0.0);
    double mean = sum / diff1.size();

    folly::fbvector<double> diff1Diff(diff1.size());
    std::transform(diff1.begin(), diff1.end(), diff1Diff.begin(), [mean](double x) { return x - mean; });

    double sq_sum = std::inner_product(diff1Diff.begin(), diff1Diff.end(), diff1Diff.begin(), 0.0);
    double stddev = std::sqrt(sq_sum / diff1Diff.size());

    std::cout << folly::format("mean:{}, stddev:{}", mean, stddev) << std::endl;
    return std::make_pair(mean, stddev);
}


text:
Q: Have equal-sized elements in css grid? I made a grid with css grid through sass. I want there to be 40 squares of equal size in an overall square shape. However the squares on the right hand side keep autosizing to be much smaller than the others.
The grid is here: https://codepen.io/nessaek/pen/rJmWrv
The key sizing details are here:
ul {
   display: grid;
    grid-template-columns: repeat(10, 1vw);
    grid-template-rows: repeat( 10, 1vw);
    justify-content: center;
    align-content: center;
    grid-gap: 1rem;
    min-height: 90vh;
    list-style: none;
    margin: 0 0 2vw;
    padding: 0;
    font-size: calc(2vw + 10px);
  }

Weirdly when I only have 16 squares, the squares all the same size. But when there are 40 the squares change to be unequal. Grateful for any advice in making all the squares equal size! Many thanks,

A: As you have 11 columns and 11 rows, you may set the ul as,
grid-template-columns: repeat(11, 1vw);
grid-template-rows: repeat(11, 1vw);

Please let me know whether this helps.


text:
Q: How do you include a header file that may or may not exist? Let's assume I define BAR in foo.h.  But foo.h might not exist.  How do I include it, without the compiler complaining at me?
#include "foo.h"

#ifndef BAR
#define BAR 1
#endif

int main()
{
    return BAR;
}

Therefore, if BAR was defined as 2 in foo.h, then the program would return 2 if foo.h exists and 1 if foo.h does not exist.

A: In general, you'll need to do something external to do this - e.g. by doing something like playing around with the search path (as suggested in the comments) and providing an empty foo.h as a fallback, or wrapping the #include inside a #ifdef HAS_FOO_H...#endif and setting HAS_FOO_H by a compiler switch (-DHAS_FOO_H for gcc/clang etc.).
If you know that you are using a particular compiler, and portability is not an issue, note that some compilers do support including a file which may or may not exist, as an extension.  For example, see clang's __has_include feature.

A: Use a tool like GNU Autoconf, that's what it's designed for. (On windows, you may prefer to use CMake).
So in your configure.ac, you'd have a line like:
AC_CHECK_HEADERS([foo.h])

Which, after running configure, would define HAVE_FOO_H, which you can test like this:
#ifdef HAVE_FOO_H
#include "foo.h"
#else
#define BAR 1
#endif

If you intend to go down the autotools route (that is autoconf and automake, because they work well together), I suggest you start with this excellent tutorial.


text:
Q: Iterative DFS to find path from source to destination I would appreciate help debugging my implementation of DFS to find a path. My implementation generally works well but in a certain edge case will add an extra node to the result which is visited by the algorithm but should not included within the solution as a path from it to the next node in the result list does not exist. The issue is likely to be caused by where Result.add(nextNode) is positioned, but I have not been able to fix this bug.
An example of the problem is attached below (weights arbitrary), whereby the algorithm returns [0 2 4 1 3 5] as a result even though no edge from 4 to 1 exists.
Example
Can anybody suggest how to modify my code so that a node like 4 is not added to the result please?
 public static ArrayList<Integer> pathDFS(Integer source, Integer destination, WeightedGraph graph) {
            ArrayList<Integer> Result = new ArrayList<Integer>();
            ArrayList<Integer> Visited = new ArrayList<Integer>();
            Stack<Integer> s = new Stack<>();
            s.push(source);
            Visited.add(source);
            while (!s.isEmpty()) {
                Integer v = s.pop();
                    for (int nextNode : getAdjacentNodes(v, graph)) {
                        if (!Visited.contains(nextNode)) {
                            s.push(nextNode);
                            Visited.add(nextNode);
                            **Result.add(nextNode);**
                            if (nextNode == destination)
                                return Result;
                    }
                }
            }
            return Result;
        }

A: Adding the node to the result list every time you add it to visited list is clearly wrong (the set of visited nodes is not necessarily contains just the path. It can have a bunch of other nodes, not just one).
To fix it, you can create a parent list to store the parent of each node (and populate it when discover a new node). This way, you'd just need to go from the target node by the parent links to the source to reconstruct the path.


text:
Q: Push a multidimensional array in Jquery I have an array set to "values", and within the array is an multidimensional array called items.
values = {
         full_name: fullname,
         items: [{'item-id': '001', 'item-special': 'nothing'}, {'item-id': '031', 'item-special': 'Make it blue'}],
         address_full: address
         };

How would I push more items into the array?
{'item-id': '055', 'item-special': 'Extra large'}

A: Something like:
values.items.push({'item-id': '055', 'item-special': 'Extra large'});

should work :)


text:
Q: Could I ensure the convergence by setting the min and max boundary of state variables in Dymola? I was struggling to improve the convergence performance of my model in Dymola during the last month. Now I am thinking about that If I define the min and max attributes of the state variables, like the max mass flow rate is 10000kg/s, the min mass flow rate is 0.01kg/s, during the iteration, when the results reaching to the max or min boundary, would the iteration be continued or it just stops?
I am considering if when the iteration result reaches the boundary, the iteration would bounce back in the opposite direction,  it might ensure the convergence of my model.
I prepare to do some tests about my idea, If anyone got the same question or opinion, welcome to comment or answer.

A: Setting min/max for variables is unlikely to significantly improve performance in Dymola.
If min/max assertions are active for a variable the solver will reject the step with values out of bounds, and currently not try to map them back to valid values in a clever way. That may skip some computations based on the out-of-bounds values, but it is rare that it matters much - and there is also a cost of rejecting the step etc.


text:
Q: Bukkit plugin doesn't work on server When I was testing a Bukkit plugin on a local server it worked perfectly, but later on I uploaded it to an online minecraft server and this was the output it gave me:
16.05 20:30:55 [Multicraft] Skipped 12 lines due to rate limit (30/s)
16.05 20:30:54 [Server] INFO at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.security.AccessController.doPrivileged(Native Method) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.net.URLClassLoader.access$100(URLClassLoader.java:71) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.lang.ClassLoader.defineClass(ClassLoader.java:800) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO at java.lang.ClassLoader.defineClass1(Native Method) ~[?:1.7.0_80]
16.05 20:30:54 [Server] INFO Caused by: java.lang.UnsupportedClassVersionError: nl/calbas/transferEnchantments/TransferEnchantments : Unsupported major.minor version 52.0
16.05 20:30:54 [Server] INFO at java.lang.Thread.run(Thread.java:745) [?:1.7.0_80]
16.05 20:30:54 [Server] INFO at net.minecraft.server.v1_9_R1.MinecraftServer.run(MinecraftServer.java:506) [craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at net.minecraft.server.v1_9_R1.DedicatedServer.init(DedicatedServer.java:182) [craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at net.minecraft.server.v1_9_R1.DedicatedPlayerList.<init>(SourceFile:14) [craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at net.minecraft.server.v1_9_R1.PlayerList.<init>(PlayerList.java:69) [craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at org.bukkit.craftbukkit.v1_9_R1.CraftServer.<init>(CraftServer.java:255) [craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at org.bukkit.craftbukkit.v1_9_R1.CraftServer.loadPlugins(CraftServer.java:293) [craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:251) [craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:328) ~[craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:133) ~[craftbukkit-1.9.2.jar:git-Bukkit-4cb3258]
16.05 20:30:54 [Server] INFO org.bukkit.plugin.InvalidPluginException: java.lang.UnsupportedClassVersionError: nl/calbas/transferEnchantments/TransferEnchantments : Unsupported major.minor version 52.0
16.05 20:30:54 [Server] INFO [20:30:54 ERROR]: Could not load 'plugins/TransferEnchantments.jar' in folder 'plugins'
16.05 20:30:54 [Server] INFO [20:30:54 INFO]: This server is running CraftBukkit version git-Bukkit-4cb3258 (MC: 1.9.2) (Implementing API version 1.9.2-R0.1-SNAPSHOT)

Does someone know what the problem might be? I could upload the code if it is helpful, but the code worked fine on my own computer.

A: The error states that the class it's trying to load is of version 52.0, this is the class version of Java 8.
If you see this error, it means you need to run Java 8 in order for the plugin to work. If you see version 51.0, it refers to Java 7.
To ensure you can run this plugin, you need to either update to Java 8, or submit a ticket with your hosting provider to update their Java versions to Java 8, which they should be doing due to EOL of both Java 6 and 7.

A: I think there is another version of CraftBukkit/Spigot on your server, because the plugin could not find some classes. It makes a diffrence between 1.9.2 1.9.3 1.9.4 because in CraftBukkit/Spigot some classes are named diffrent. Upload your CraftBukkit/Spigot jar onto the server and try again :)

A: http://wiki.bukkit.org/Setting_Up_Your_Workspace#Which_version_of_the_JDK.3F tells you that most bukkit servers run Java 7, this means that the server you uploaded to probably does too, if you're not using JDK 7, the server will most likely not be able to load your plugin, try to download JDK 7 and compile your plugin with that instead.


text:
Q: Material Design Lite table refresh issue with AngularJS I am using mdl-data-table mdl-js-data-table and ng-repeat to implement a simple pagination feature. It works, but has an annoying issue: whenever I turn a page, the table flashes. e.g. if the table has 20 rows and each page has 10, mdl table will first display 20 then within tenth of a second, shrink that into 10 rows.
If I remove class mdl-data-table mdl-js-data-table and just use table, everything works fine, no flash at all. But I lost MDL style of course.
I wonder if both angular and MDL updates DOM, and somehow MDL update the table twice. But I don't know where to look at to fix it. calling mdl window.componentHandler.upgradeAllRegistered(); doesn't seem matter one way or the other.
Please help. Thanks.
part of the code is as below. initData function just sets the initial value for pagination variables and data array.

            Name

            {{$index}}

    <button class="mdl-button mdl-js-button mdl-button--icon mdl-button" ng-disabled="curPage == 0" ng-click="curPage=curPage-1">
        skip_previous
    </button>
    Page {{curPage + 1}} of {{ numberOfPages() }}
    <button class="mdl-button mdl-js-button mdl-button--icon mdl-button" ng-disabled="curPage >= datalists.length/pageSize - 1" ng-click="curPage = curPage+1">
        skip_next
    </button>

A: MDL is for static websites and not for webapps.
consider using Angular Material

A: I found what is causing the problem is the mdl-data-table class and the background color change animation. So I ended up creating a new table class by copying the style of the material design table minus the background transition. Here is the CSS:
.my-table {
    position: relative;
    border: 1px solid rgba(0, 0, 0, .12);
    border-collapse: collapse;
    font-size: 14px;
    background-color: #ffffff;
}
.my-table th, td {
    position: relative;
    vertical-align: middle;
    text-align: left;
    text-overflow: ellipsis;
    height: 48px;
    box-sizing: border-box;
    padding: 12px 12px 12px 18px;
    border-top: 1px solid rgba(0, 0, 0, .12);
    border-bottom: 1px solid rgba(0, 0, 0, .12);
}
.my-table th {
    font-size: 12px;
    color: rgba(0, 0, 0, .54);
    font-weight: bold;
}

Replace mdl-data-table with my-table class to table, although it's not actually fixing the repeated data-binding in AngularJS, it should work.

A: Don't waste your time building up your table.
Use mdDataTable available in npm and in bower
Link: https://github.com/iamisti/mdDataTable
Here is the demo of it: http://iamisti.github.io/mdDataTable/


text:
Q: Can Windows logoff events be tracked? I'm working on an application to track network user logon/logoff events in an Active Directory domain; the application will work by auditing security logs on domain controllers.
Auditing logon events can get somewhat tricky, but it can succesfully be done.
My problem: how can I track logoff events?
Based on some research I've done, it looks like these events are only logged locally on workstations, but not on DCs; also, the "lastLogoff" attribute exists on AD user objects, but it's not actually used by anyone.
This is a very specific question: is something logged on DCs when a user logs off from a domain workstation?
To clarify: I'm not intereseted in other auditing mehods, I can't deploy logon/logoff scripts and I can't install anything anywhere; I also know opened and closed network sessions are logged, but this is not what I'm looking for. I need to audit interactive logons and logoffs to domain workstations, and I can do this by only reading domain controllers security logs; reading each workstation's local event logs is out of question.
If this can't be done, it's ok; but I need a clear answer on that.

*

*Can this be done?

*If yes, how?

A: You are correct, they aren't logged on your DC's. However, I believe (but am not positive) that if your auditing is high enough on the DC's, an event is logged when someone disconnects a network drive. So if you are mapping drives for your users, you could potentially track their log offs but looking for that 'dismount' event. Even then, I'm not sure I would want to rely on that. You said you can't deploy scripts, but I'm just mentioning that in case you already are in your environment.

A: Looks like this just can't be done.
Nothing gets logged on DCs when a user logs off, apart from closed network sessions (but they can be closed anytime, not only upon logoffs).


text:
Q: error using plotly " more elements in the method signature (2) than in the generic signature (1) for function 'asJSON'" My error here is similar to this post, but I couldn't understand how to use the solution for that post for my situation.- I am using xtabs to convert data in columns to a matrix for a plotly surface plot as per this. In the real df, there is more than one value in the second column (the dataset was created using expand.grid to get some model predictions).
An example:
df <- read.table(text =
  "WtavR  WcsavR      pred
1  18.62672 0.03825 0.6113332
2  18.73131 0.03825 0.6079856
3  18.83590 0.03825 0.6046379
4  18.94049 0.03825 0.6012903
5  19.04508 0.03825 0.5979427
6  19.14967 0.03825 0.5945950
7  19.25426 0.03825 0.5912474
8  19.35885 0.03825 0.5878998
9  19.46344 0.03825 0.5845521
10 19.56803 0.03825 0.5812045
11 19.67262 0.03825 0.5778568
12 19.77721 0.03825 0.5745092
13 19.88180 0.03825 0.5711616
14 19.98639 0.03825 0.5678139
15 20.09098 0.03825 0.5644663
16 20.19557 0.03825 0.5611187
17 20.30016 0.03825 0.5577710
18 20.40475 0.03825 0.5544234
19 20.50934 0.03825 0.5510758
20 20.61393 0.03825 0.5477281", header = T)

p6 <- plot_ly(z = ~xtabs(pred ~ WtavR + WcsavR, data = df)) %>% add_surface()

p6

This gives the following error

Error in matchSignature(signature, fdef) :
more elements in the method signature (2) than in the generic signature (1) for function 'asJSON'

I would appreciate any help. I am just after a surface plot of model predictions.

A: xtabs() produces an object of class xtabs rather than a plain matrix.
By removing that class, I found that I could get plotly to behave:
df      <- expand.grid(x=0:9, y=0:9) %>% mutate(z=x*y)
surface <- unclass(xtabs(z ~ x + y, data = df))
plot_ly(z = ~surface) %>% add_surface()


text:
Q: tapestry chenillekit chart : problem to defined trackFormatter function I need help to display chart in tapestry pages. I'm using tapestry 5.2.4 and chenillekit 1.3.0.
My problem is that I want to defined a custom javascript function to display date in the mouse track. The option for Flotr is trackFormatter : function(obj){...}.
In my case, I send option for the graph with JSON.
When the function is called, i have error like this:
"n.mouse.trackFormatter is not a function" for firefox,
"Uncaught TypeError: Property 'trackFormatter' of object # is not a function" for chrome.
Does someone have the same problem and/or have find a solution to delcare custom javascript function like trackFormatter? thanks!
My code:
...
import org.apache.tapestry5.json.JSONLiteral;
import org.apache.tapestry5.json.JSONObject;
...

@Import(library = { "mymouseeventhandler.js" })
public class LineChart extends Chart {

private static final Logger logger = LoggerFactory.getLogger(LineChart.class);

/**
 * Map  .
 */
@Parameter(required = true, defaultPrefix = BindingConstants.PROP)
private Map<String, List<XYDataItem>> counterDataWithLabel;

/**
 * Map  .
 */
@Parameter(required = false, defaultPrefix = BindingConstants.PROP)
private Map<String, List<XYDataItem>> thresholdDataWithLabel;

@Parameter
private Date startTime;

@Parameter
private String graphCaption;

/**
 * Configure Flotr Graph
 *
 *

 * ChenilleKit Reference
 *

 *

 * Flotr Options
 *

 *
 */
protected void configure(JSONObject config) {
    // TODO add attributes to LineChart, for being able to parameterize the graph.
    // counterDataWithLabel;
    StringBuilder dataString = new StringBuilder("[");
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(getStartTime());
    int startMillisecond = calendar.get(Calendar.MILLISECOND);

    int i = 0;
    for (Map.Entry<String, List<XYDataItem>> entry : counterDataWithLabel.entrySet()) {
        String label = entry.getKey();
        List<XYDataItem> dataItems = entry.getValue();
        dataString.append(String.format("{data: %s, label: '%s' , lines:{lineWidth: 1}}",
                Arrays.toString(dataItems.toArray()), label));
        dataString.append(",");
        i++;
    }
    if (!org.apache.commons.collections.MapUtils.isEmpty(thresholdDataWithLabel)) {
        int j = 0;
        for (Map.Entry<String, List<XYDataItem>> entry : thresholdDataWithLabel.entrySet()) {
            String label = entry.getKey();
            List<XYDataItem> dataItems = entry.getValue();
            dataString.append(String.format(
                    "{data: %s, label: '%s' , points: {show: false} , lines:{lineWidth: 3 }}",
                    Arrays.toString(dataItems.toArray()), label));
            if (j < thresholdDataWithLabel.size() - 1) {
                dataString.append(",");
            }
            j++;
        }
    }

    dataString.append("]");
    config.put("data", new JSONArray(dataString.toString()));

    JSONObject options = new JSONObject();

    options = flotrChart.getOptions();
    options.put("HtmlText", false);
    JSONObject mouse = new JSONObject();
    mouse.put("track", true);
    mouse.put("trackFormatter", new JSONLiteral("dateFormatter(obj)").toString());
    options.put("mouse", mouse);

    config.put("options", options);

    logger.debug("## config : " + config.toString());

}

/**
 * @return the startTime
 */
public Date getStartTime() {
    return startTime;
}

/**
 * @param startTime
 *            the startTime to set
 */
public void setStartTime(Date startTime) {
    this.startTime = startTime;
}
}

mymouseeventhandler.js:
function dateTracker(obj){
    var dateToDisplay = new Date(parseInt(obj.x));
    var fullYear = dateToDisplay.getFullYear();
    var month = dateToDisplay.getMonth();
    var date = dateToDisplay.getDate();
    return '('+fullYear+'-'+month+'-'+date+' , '+obj.y+')';
}

A: The function is not well recognized because of double quote "" added when creating JSONObject. Here is a solution to avoid double quote :
...
mouse.put("trackFormatter", new JSONLiteral(
("\"function(obj){ return dateTracker(obj) }\"").replace("\"", "")));
...

I hope it will help someone else :)


text:
Q: What happens if you connect a hot resistor to a cold resistor? Kind of an extension to this question:
If you heat up an object, and put it in contact with a colder object, in an ideal insulated box, the heat from one will transfer to the other through thermal conduction and they will eventually reach an equilibrium temperature at the midpoint, correct?
Now if you have a hot resistor (electrical component) and a cold resistor, and connect them by their leads, so that they make a circuit:

there will be the same conduction and radiation heat transfers.  But also, the hotter resistor will have a larger noise current, right?  So will there additionally be a transfer of electrical energy from one resistor to the other?  Would completing the circuit allow them to reach equilibrium temperature faster than if they were just touching through an insulator with the same thermal conductivity?

A: A resistor at a temperature T has a fluctuating voltage. This is a consequence of the fluctuation dissipation theorem which you can use to calculate the spectrum of the voltage. The wikipedia article on the Fluctuation Dissipation Theorem has a section on resistor thermal noise. When measured over a bandwidth $\Delta\nu$, the average squared voltage is:
$$\langle V^2\rangle = 4Rk_BT\Delta\nu$$
where $k_B= 1.38\times 10^{-23}$J/K is Boltzmann's constant.
Suppose we have a resistor $R$ maintained at a temperature T, and hooked up to a resistor $R_0$ initially at absolute zero. The thermal noise of the warm resistor will be as given above. When you apply a voltage $V$ to a resistor $R_0$, the dissipation (in watts) will be given by $IV = V^2R_0$, so the watts applied to the resistor initially at absolute zero, over a bandwidth $\Delta\nu$ will be
$$\langle V^2\rangle = 4R_0Rk_BT\Delta\nu.$$
As that resistor warms up to temperature $T_0$, it will apply a fluctuating voltage on the warm resistor. Following the above, but with the two resistors swapped, the power applied to the warm resistor by the colder resistor at temperature $T_0$ will be:
$$\langle V^2\rangle = 4RR_0k_BT_0\Delta\nu.$$
The system will be in balance when the above two powers are equal. This happens algebraically when $T=T_0$.

A possible source of paradoxical confusion is that the above calculation was done over a limited bandwidth range. But the calculation does not depend on frequency; instead the power transmitted is simply proportional to the range of bandwidths.
For the usual physical system, we consider frequencies that run from 0 to infinity. Thus the total bandwidth is infinite. This suggests that the power flow in the above should be infinite. This paradox is avoided by noting that physical resistors have a limited bandwidth. There is always a parasitic capacitance so that the bandwidth is limited on the high side. Thus the power transfer rate depends on how ideal your resistors are.

As an example calculation, suppose that a resistor has a maximum frequency of 100 GHz $= 10^{11}$ Hz, a (room) temperature of 300K, and a resistance of 1000 ohms. Then the power transfer rate is:
$$ 4\times 1000 \times 1.38\times 10^{-23} 10^{11} \times 300 = 1.66\;\;\textrm{uWatts}$$
Given the heat capacity of the resistor, you can compute the relaxation time with which the colder resistor exponentially approaches an equal temperature.

A: Actually, that's exactly what happens: heat is transported by freely moving electrons. - but you wouldn't call it noise current, you would call it heat transfer, regardless of whether it's phonons or electrons which carry the heat.
The whole thing really has nothing to do with the resistors, it would work equally well with any passive component (proof: otherwise you could use that to build a 2nd order perpetuum mobile).

A: 4kTBR is an approximation.
For very high frequencies or very low temperatures, quantum effects kick in. That's what limits the amount of power transferred, not the RF properties of real resistors.
Look it up on Wikipedia - Johnson Noise


text:
Q: Shell script tar specific files with retention period I am new to Unix Shell script. I need to keep file for retention period of one month and archive other.
Example:
File format: WE20160225.log (20160225 YYYYMMDD)
Say in the directory /oracle/Sales has 3 files:
WE20160130.log
WE20151201.log
WE20151109.log
I need to tar.gz the WE20151201.log and WE20151109.log
But not WE20160130.log because the file is less than one month from now. How can I do this? (probably need to substring the filename)
I'm able to change directory but don't know what to do next. My logic is loop through the file and substring the date from file and check with current date
I need to use the filename date, not the file modification date.
SALES_DIR="/oracle/sales/"
cd $SALES_DIR

A: Probably something along those lines:
list=`ls *.log`

limit=`date --date 'Last Month' +%Y%m%d`

for filename in $list
  do
    if [ ${filename:2:8} -lt $limit ]
      then
        tar -czf "$filename.tar.gz" $filename
      fi
  done;

A: You can use this for loop:
curr=$(date '+%s')
for file in WE*.log; do
   f="${file%.*}"
   ts=$(date -d "${f:2}" '+%s')
   (( (curr - ts) > 30*86400 )) && echo "$file"
done | tar cvzf backup.tgz -T-

Basically we are getting current date-time in unix seconds and then extracting date from file and finding it's EPOCH (unix ts) value using date.
Finally we are comparing difference of 2 timestamps with 30*86400 (30 days) and printing the filename. Whole thing is piped to a tar command to create a tar zipped file.


text:
Q: How to display text in LWJGL using version 3.2 or above I've been using the lwjgl wiki to learn about how to use the library, and I've been setting up LWJGL with the following (as per this tutorial):
PixelFormat pixelFormat = new PixelFormat();
ContextAttribs contextAttributes = new ContextAttribs(3, 2)
                                       .withForwardCompatible(true)
                                       .withProfileCore(true);
Display.setTitle("Title");
try
{
    Display.setFullscreen(true);
    Display.setVSyncEnabled(true);
    Display.create(pixelFormat, contextAttributes);
}
catch(LWJGLException e)
{
    e.printStackTrace();
}

glViewport(0, 0, sizeX, sizeY);
glClearColor(0, 0, 0, 1);

Another tutorial explains how to draw text. However, TrueTypeFont is deprecated so I replaced it with the now standard UnicodeFont. I Initialize and use it like this:
UnicodeFont font = null;
try
{
    font = new UnicodeFont(Font.createFont(Font.TRUETYPE_FONT,
                              new File("path/to/font.ttf")).deriveFont(24)));
}
catch (FontFormatException | IOException e)
{
    e.printStackTrace();
}

while(true)
{
    glClear(GL_COLOR_BUFFER_BIT);
    font.drawString(50.0f, 50.0f, "Hi there.",
                           new Color(1.0f, 1.0f, 1.0f, 1.0f));
}

This generates the following error:
Exception in thread "main" java.lang.IllegalStateException: Function is not supported
at org.lwjgl.BufferChecks.checkFunctionAddress(BufferChecks.java:58)
at org.lwjgl.opengl.GL11.glColor4f(GL11.java:881)
at org.newdawn.slick.opengl.renderer.ImmediateModeOGLRenderer.glColor4f(ImmediateModeOGLRenderer.java:119)
at org.newdawn.slick.Color.bind(Color.java:180)
at org.newdawn.slick.TrueTypeFont.drawString(TrueTypeFont.java:367)
at org.newdawn.slick.TrueTypeFont.drawString(TrueTypeFont.java:359)

at the line where drawString is called. How do I fix this?

A: You're creating an OpenGL 3.2 forward compatible context, but apparently the font renderer is using immediate mode rendering, which is removed from that version of OpenGL. Either create a compatibility context or switch to some other method of rendering fonts.


text:
Q: Highstock, error: Uncaught TypeError: w[(intermediate value)(intermediate value)(intermediate value)] is not a constructor I am trying to create a highstock chart, but am getting the following error:

error: Uncaught TypeError: w[(intermediate value)(intermediate
  value)(intermediate value)] is not a constructor

My JSON seems valid, and my javascript too, any idea howto fix this?
Javascript:
    $.getJSON('<?php echo SITE_URL; ?>analytic/weekly_views_json', function(data)
    {
       // Create the chart
        $('#container2').highcharts('StockChart', {

            rangeSelector: {
                selected: 1
            },

            title: {
                text: 'AAPL Stock Price'
            },

            series: [{
                name: 'AAPL Stock Price',
                data: data,
                type: 'spline',

            }]
        });
    });

Json:
[[1420547368,1],[1423225768,1],[1425644968,1],[1428319768,1],[1430911768,1],[1433590168,1],[1452083368,1],[1454761768,1],[1457267368,1],[1458131368,1],[1459942168,1],[1494070168,1]]

A: First solution:
I had same error, i used highchart as below in my HTML code:
<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
...
</head>

and my js code was:
$('#container').highcharts('StockChart', {
...
});

with respect to highchart documention, we must use Highcharts.Chart to create new highstock.
so i changed my code to:
<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
...
</head>

and my js code was:
var chart = new Highcharts.Chart({
        chart: {
                renderTo: 'container'
            },
...
});

and this error has been resolved!
Second solution:
also with respect to this documentation,  if you are running Chart and StockChart in combination, you only need to load the highstock.js file.
so changed my code to:
<head>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
...
</head>

and my js code was:
var chart = new Highcharts.Chart({
        chart: {
                renderTo: 'container'
            },
...
});

A: This worked for me
<script src="../lib/highcharts.js"/>
<script src="../lib/highcharts-more.js"/>

 var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: 'Temperature'
                    },
                    title: {
                        text: 'HighStock'
                    },
                    legend: {
                        enabled: true
                    },
                    xAxis: {
                        categories: ['1','2','3','4'],
                        title: {
                            text: 'day'
                        }
                    },
                    yAxis: {
                        title: {
                            text: 'values'
                        }
                    },
                    series: [{
                        name: 'temperature',
                        data: [
                            [5,30],[10,35],[15,40],[20,45]
                        ],
                    }]
                });


text:
Q: break a text file into several blocks with perl I have a file that contains a diff output, that looks like this:
26c26
< Or in the bright light of morning
---
> Or in the bright light of evning
34c34,36
< clouds will roll back clear of the summits.
---
> hello world
> I came here to ask
> some questions
43,44c45
< How to imagine an orchid boat?
< It gets harder. But days come and go,
---
> don't you cry tonigh,
49,50c50,52
< though only caught that imprisoning moment.
< A golden leaf in autumn spins into a dark river
---
> che che che che changes.
> la la la la la
> good song

i wnat to process this file block by block, where twho blocks are sepreated by a delimeter of the form:
{number}c{number}      for example 48c70
or
{number},{number}c{number}  for example 90,120c70
or
{number},{number}c{number},{number}  for example 36,40c88,1020
or
{number}c{number},{number}  for example 99,100c70
for example, the file above containes 4 blocks:
block 1:
26c26
< Or in the bright light of morning
---
> Or in the bright light of evning

block 2:
34c34,36
< clouds will roll back clear of the summits.
---
> hello world
> I came here to ask
> some questions

block 3:
43,44c45
< How to imagine an orchid boat?
< It gets harder. But days come and go,
---
> don't you cry tonigh,

block 4:
49,50c50,52
< though only caught that imprisoning moment.
< A golden leaf in autumn spins into a dark river
---
> che che che che changes.
> la la la la la
> good song

how can I do that using Perl?
thank you

A: Split the string based on
(?=^(\d+,)?\d+c\d+(,\d+)?$)

Here is online demo

A: Since you're just dealing with output from diff, you simply need to look for lines that begin with a digit:
my @blocks = split /^(?=\d)/m, do {local $/; <DATA>};

use Data::Dump;
dd @blocks;

__DATA__
26c26
< Or in the bright light of morning
---
> Or in the bright light of evning
34c34,36
< clouds will roll back clear of the summits.
---
> hello world
> I came here to ask
> some questions
43,44c45
< How to imagine an orchid boat?
< It gets harder. But days come and go,
---
> don't you cry tonigh,
49,50c50,52
< though only caught that imprisoning moment.
< A golden leaf in autumn spins into a dark river
---
> che che che che changes.
> la la la la la
> good song

Outputs:
(
  "26c26\n< Or in the bright light of morning \n---\n> Or in the bright light of evning \n",
  "34c34,36\n< clouds will roll back clear of the summits. \n---\n> hello world\n> I came here to ask\n> some questions \n",
  "43,44c45\n< How to imagine an orchid boat? \n< It gets harder. But days come and go, \n---\n> don't you cry tonigh, \n",
  "49,50c50,52\n< though only caught that imprisoning moment. \n< A golden leaf in autumn spins into a dark river \n---\n> che che che che changes. \n> la la la la la \n> good song",
)


text:
Q: How to fill the area of different classes in scatter plot matplotlib? I am plotting my pandas data using matplotlib, My plot looks like this:

There are four classes in the dataset. I want to color the backgroud area for each class, something like this

My matplotlib code looks like this:
import pandas as pd
df = pd.read_csv('normalized.csv')
fig    = plt.figure(figsize=(8,8))
plt.scatter(df['p1'], df['p2'], c= list(df['cs']), alpha=0.9)
plt.show()

I also tried sns for this:
import pandas as pd
df = pd.read_csv('normalized.csv')
sn.FacetGrid(df, hue="cs", size = 8).map(plt.scatter, "p1", "p2").add_legend()
plt.show()

How I can fill the backgroud area for four classes in any of module?

A: A filled contour could serve as background:
import numpy as np
import matplotlib.pyplot as plt

N = 100
M = 4
points = np.random.normal(np.tile(np.random.uniform(1, 10, 2 * M), N)).reshape(-1, 2)
group = np.tile(np.arange(M), N)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 5), sharey=True, sharex=True)
cmap = plt.cm.get_cmap('tab10', 4)
ax1.scatter(points[:, 0], points[:, 1], c=group, cmap=cmap)

ax2.scatter(points[:, 0], points[:, 1], c=group, cmap=cmap)
ax2.tricontourf(points[:, 0], points[:, 1], group, levels=np.arange(-0.5, 4), zorder=0, cmap=cmap, alpha=0.3)
plt.show()

Note that the contour plot also creates some narrow zones of inbetween values, because it only looks at numeric values and supposes that between a zone 0 and a zone 2 there must exist some small zone 1.
A bit more involved approach uses a nearest neighbor fit:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors

N = 100
M = 4
points = np.random.normal(np.tile(np.random.uniform(1, 10, 2 * M), N)).reshape(-1, 2)
groups = np.tile(np.arange(M), N)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 5), sharey=True, sharex=True)
cmap = ListedColormap(['orange', 'cyan', 'cornflowerblue', 'crimson'])
ax1.scatter(points[:, 0], points[:, 1], c=groups, cmap=cmap)

ax2.scatter(points[:, 0], points[:, 1], c=groups, cmap=cmap)

clf = neighbors.KNeighborsClassifier(10)
clf.fit(points, groups)

x_min, x_max = points[:, 0].min() - 1, points[:, 0].max() + 1
y_min, y_max = points[:, 1].min() - 1, points[:, 1].max() + 1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 50),
                     np.linspace(y_min, y_max, 50))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
ax2.imshow(Z, extent=[x_min, x_max, y_min, y_max], cmap=cmap, alpha=0.3, aspect='auto', origin='lower')
plt.show()

A: If you don't need to fill the space and do not bother about areas overlap (your data points show some overlap) then you can try to fill out the convex hull defined by each subset.
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import ConvexHull
N = 100
points = [np.random.normal(np.tile(np.random.uniform(1, 5, 2), N)).reshape(-1, 2) for i in range(4)]
colors = ['r', 'g', 'b', 'k']
for k in range(4):
    hull = ConvexHull(points[k])
    plt.plot(points[k][:,0], points[k][:,1], '.', color = colors[k])
    plt.fill(points[k][hull.vertices,0], points[k][hull.vertices,1], color = colors[k], alpha=0.3)

stack.imgur.com/2562R.png


text:
Q: Supporting a TerribAD Carry Bot Solo queue and our team needs support; lock in Sona. Go to lane, AD carry turret dives 60% health Sion and Taric. Complains to Sona for not supporting well enough. Game goes on and AD carry continues to make terrible decisions and complains about support. What should a support character do in this sort of situation?

A: This is a tough question to answer because you aren't in control of the other person's actions. Generally speaking, it's far easier to support more passive gameplay, and the difficulty of supporting increases as the carry becomes more aggressive. Ultimately, like in the situation you present, supporting becomes impossible in any meaningful manner. The way I see it, you have three options:

*

*You can voice your concerns to them and see if you can get them to be less aggressive, which makes supporting them easier (or possible)

*You can accept that they're going to be very aggressive and tune your play to match as best you can.

*If things are truly hopeless, you can switch to a more roaming role and try to help other lanes win their matchups. Careful about stealing experience, but with Sona's ultimate and some well-placed heals (for instance), you can be a force for good for the rest of the team.
The first option is the one you should pursue first. The relationship between AD Carry and Support needs to be tight-knit for success. Often, even aggressive AD carries realize this. The second option is what you'll be doing a lot. You have a duty to your carry to support them (hence the name of the role). Try not to die, obviously, but do everything else in your power to help them accomplish whatever they're trying to do. The third option should be an absolute last resort. Just giving up on your lane isn't something to be done lightly.

A: If the AD carry is aggressive you should be prepared to ward the river for ganks, and force trades too if possible. If he's being overly retardet and just impossible to co-operate with, hit up the fancy ignore button.
What if the support is bad? I'm a decent AD player and I sometimes get way too passive supports. For example, i was playing corki and had a Leona supporting me who should be an aggressive laner who forces trades and keeps the opposing carry in fear of the pull-stun combo, but instead she just literally AFK'd at our bush.
They had Graves & Blitzcrank combo which was hella aggressive, so i was forced to play passively because 2v1 was not an option. Once blitz caught me off guard with his pull, i was able to valkyrie away and stay alive with heal, but right afterwards the leona decides to go in 2v1 while i had literally 100 hp left? and dies right off the bat, giving the graves 1-0 lead. From then on the lane just snowballed to their favour making us lose the lane and i got all the blames from it from the team. ''Nice feed corki'' etc
So its not just the AD carry who needs to be good, its also the support. When i do get a good support i usually end up with a 12-4, 8-2 17-4 ~~ ish score on any AD.

A: There is not not much you can do. The support role is about supporting good carries; if the carry is bad, support during the lane phase can only help so much.


text:
Q: How to synchronize two onloadend functions in angular 2? I'm new to Angular 2/4 and I've reached a place that I can read multiple files from local directory. In my function, data (from each file) is parsed and pushed into 2 different arrays but after onloadend functions I can't access arrays data and I suppose this is a synchronization problem.
My Code:
changeListener($event: any) {
       this.readFile($event.target);
    }
readFile(input: any) {
  var self = this;
  var files : File [] = input.files;
  var employeeSet : Employee [] = new Array<Employee>();
  var serviceSet : Service [] = new Array<Service>();
  for (let i=0; i < files.length; i++) {
            console.log(files[i].name);

            if (files[i].name == 'employees') {
              var employeeReader : FileReader = new FileReader();
              employeeReader.readAsText(files[i]);

              employeeReader.onload = function(e) {
              var alldata = employeeReader.result;
              var allTextlines = alldata.split(/\r?\n/);

              for (var i=0; i < allTextlines.length; i++) {
                var columns = allTextlines[i].split('|');
                var employee : Employee = new Employee();
                if (columns[0] != '') {
                  employee.id = Number(columns[0]);
                  employee.firstName = columns[1];
                  employee.lastName = columns[2];
                  employee.jobPosition = columns[3];
                  employee.status = columns[4];
                  employee.company.name = columns[5];
                  employee.mobilePhone = columns[6];
                  employee.iternalNumber = columns[7];
                  employee.email = columns[8];
                  employee.hireDate = columns[9];
                  var totalServices = columns[10].split(',');
                  for (var j = 0; j < totalServices.length; j++) {
                    var serviceDescr = totalServices[j];
                    employee.services.push(serviceDescr);
                  }

                  employeeSet.push(employee);

                }
                // self.apiServ.addUser(user).subscribe(
                //   (data) => {
                //     if( data instanceof Observable) {
                //       data.subscribe(
                //         (f) => {console.log(f);
                //         });
                //     }
                //   }
                // );
              }
              console.log(employeeSet);
              self.complete.next(employeeSet);
              // console.log('Tha steiloume ston server to akoloutho array: \n', resultSet);
            };
          } else if(files[i].name == 'services') {

            var serviceReader : FileReader =  new FileReader();
            serviceReader.readAsText(files[i]);

            serviceReader.onload = function(e) {
            var alldata = serviceReader.result;
            var allTextlines = alldata.split(/\r?\n/);
            for (var i=0; i < allTextlines.length; i++) {
              var columns = allTextlines[i].split('|');
              var service : Service = new Service();
              if (columns[0] != '') {
                service.id = Number(columns[0]);
                service.description = columns[1];
                service.price = columns[2];
                service.cost = columns[3];

                serviceSet.push(service);

              }
            }
            console.log(serviceSet);
            self.complete.next(serviceSet);
          };

  }

}

// Here I want to access the data but i cant.

}

Any help? Thanks in advance!

A: I achieve something similar working with Promises (it remains being async but in a better way to handle it). You should be able to work with your arrays inside the then method.
ImageHelper.ts
export class ImageInfo {

  name: string;
  size: number;
  width: number;
  height: number;

}

export class ImageHelper {

  static getImageInfo(image: File): Promise<ImageInfo> {

    const imageInfo: ImageInfo = new ImageInfo();

    return new Promise<ImageInfo>((resolve, reject) => {

      try {

        imageInfo.name = image.name;
        imageInfo.size = image.size;

        const reader = new FileReader();

        reader.onloadend = (onLoadEvent) => {

          const imageAux = new Image();
          imageAux.src = reader.result;

          imageAux.onload = function () {

            imageInfo.width = imageAux.width;
            imageInfo.height = imageAux.height;

            resolve(imageInfo);
          };
        };
        reader.readAsDataURL(image);
      } catch (error) {

        reject(error);
      }
    });
  }

}

And wherever.
principalUpload(event) {

  ImageHelper.getImageInfo(event.target.files[0])
    .then((imageInfo: ImageInfo) => console.log(imageInfo));
  ...
}

I hope this help someone more.


text:
Q: Why is the GDI DrawString call behaving differently in PrintDocument vs. rendering to an image? I am working on a printing application in C# using the PrintDocument class.  I have gotten the physical printing part working the way I want, but one of the requirements is that I save an image file as well.
I have created an image and use the same GDI calls that rendered the printed page.  It looks pretty close except for the text.  The printed page is fine, but the saved image is causing the 8pt Courier font to show up as what appears to be a 0.1pt font.
I have tried adding the following, with no luck:
 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
 g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

Any ideas as to why the difference in text rendering?

A: Not enough code to look at, the posted snippets are not relevant to font scaling.
The big difference between a printed page and an image is the drastic difference in resolution.  600 dpi vs 96 dpi, typically.  Default scaling for the printer is 1 pixel = 0.01 inch, making text and images almost the same size when rendered to the screen vs paper.  Changing that scaling causes the kind of trouble you're having.
Look for any assignments to Graphics.PageUnit in your code, for example.


text:
Q: Is it possible to log variable name in JavaScript? Is it possible to log variable name (not value) in JavaScript?
var max_value = 4;
console.log(max_value); // should log "max_value" as a string

UPDATE: I need a testing function that should be able to log any variable name (passed as an argument) as a string, not just this one variable.

A: There is a solution that can help you. I grabbed this function from this stackoverflow answer, which is able to get the name of the function parameters:
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '');
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(result === null)
     result = [];
  return result;
}

then all you need to do now, is to use the name of your variable as a parameter of an anonymous function and pass all the function as argument of the getParamNames :
variablesNames = getParamNames(function (max_value, min_value) {});

This will return an array like this :
result => ["max_value", "min_value"];

Let's make it practical, first change the name of the getParamNames function to something easy and small like this :
function __ (func) {
   // code here  ...
}

second thing, instead of returning an array, just return the first element of the array, change this :
return result;

to this :
return result.shift();

now, you can get the name of your variable like this :
__(function( max_value ){});


text:
Q: How to optimize interpolation of large set of scattered points? I am currently working with a set of coordinate points (longitude, latitude, about 60000 of them) and the temperature at that location. I need to do a interpolation on them to compute the values at some points with unknown temperature as to map certain regions.
As to respect the influence that the points have between them I have converted every (long, lat) point to a unit sphere point (x, y, z).
I have started applying the generalized multidimension Shepard interpolation from "Numerical recipes 3rd Edition":
Doub interp(VecDoub_I &pt)
    {
        Doub r, w, sum=0., sumw=0.;
        if (pt.size() != dim)
            throw("RBF_interp bad pt size");
        for (Int i=0;i<n;i++)
        {
            if ((r=rad(&pt[0],&pts[i][0])) == 0.)
                return vals[i];
            sum += (w = pow(r,pneg));
            sumw += w*vals[i];
        }
        return sumw/sum;
    }

    Doub rad(const Doub *p1, const Doub *p2)
    {
        Doub sum = 0.;
        for (Int i=0;i<dim;i++)
            sum += SQR(p1[i]-p2[i]);
        return sqrt(sum);
    }

  As you can see, for the interpolation of one point, the algorithm computes the distance of that point to each of the other points and taking it as a weight in the final value.
Even though this algorithm works it is much too slow compared to what I need since I will be computing a lot of points to map a grid of a certain region.
One way of optimizing this is that I could leave out the points than are beyond a certain radius, but would pose a problem for areas with few or no points.
Another thing would be to reduce the computing of the distance between each 2 points by only computing once a Look-up Table and storing the distances. The problem with this is that it is impossible to store such a large matrix (60000 x 60000).
The grid of temperatures that is obtained, will be used to compute contours for different temperature values.
If anyone knows a way to optimize this algorithm or maybe help with a better one, I will appreciate it.

A: Radial basis functions with infinite support is probably not what you want to be using if you have a large number of data points and will be taking a large number of interpolation values.
There are variants that use N nearest neighbours and finite support to reduce the number of points that must be considered for each interpolation value. A variant of this can be found in the first solution mentioned here Inverse Distance Weighted (IDW) Interpolation with Python. (though I have a nagging suspicion that this implementation can be discontinuous under certain conditions - there are certainly variants that are fine)

A: Your look-up table doesn't have to store every point in the 60k square, only those once which are used repeatedly. You can map any coordinate x to int(x*resolution) to improve the hit rate by lowering the resolution.
A similar lookup table for the power function might also help.


text:
Q: Is $SL_n(\mathbb{Z}_p)$ profinite? Serre's Galois Cohomology states that $SL_n(\mathbb{Z}_p)$ is a profinite group. How can one see this? Is there a way to identify the open normal subgroups of finite index of $SL_n(\mathbb{Z}_p)$ (when we see it with the product topology, for example)?
EDIT: I am considering the definition:
$$SL_n(\mathbb{Z}_p) = \left\{M \in \text{Mat}_{n\times n}(\mathbb{Z}_p) | \det(M) = 1\right\}$$
and the topology induced by the product topology in $\prod_{n^2} \mathbb{Z}_p$. We know it's a topological group but it's not obvious to us why we have the characterization
$$SL_n(\mathbb{Z}_p) = \varprojlim SL_n(\mathbb{Z}/p^k\mathbb{Z})$$
which would surely make it the limit of finite discrete groups, and thus, profinite.


text:
Q: Is there a Python analog to matlab's "save()" function? Say I ran some code that produces multiple arrays as its output. How might I save the entire output in one go as in matlab?
In matlab I'd simply say save(data) -> load('data').
Apologies if this is a basic quesiton.

A: How to save a python object:
To save objects to file in Python, you can use pickle:

*

*Import the pickle module.

*Get a file handle in write mode that points
to a file path.

*Use pickle.dump to write the object that we want to
save to file via that file handle.

How to use it:
   import pickle
   object = Object()
   filehandler = open(filename, 'w')
   pickle.dump(object, filehandler)

How to load a python object:

*

*Import the pickle module.

*Get a file handle in read mode that points to a file path that has a file that contains the serialized form of a Python object.

*Use pickle.load to read the object from the file that contains the serialized form of a Python object via the file handle.

How to use it:
   import pickle
   filehandler = open(filename, 'r')
   object = pickle.load(filehandler)

Extras : save multiple objects at once
Obviously, using a list you can also store multiple objects at once:
object_a = "foo"
object_b = "bar"
object_c = "baz"

objects_list = [object_a , object_b , object_c ]
file_name = "my_objects.pkl"
open_file = open(file_name, "wb")
pickle.dump(objects_list, open_file)
open_file.close()


text:
Q: Release a file being used by another process I'm implementing "copy map to clip" as an image.
what I do is I create an image an save it to certain directory and copy it to clipboard.
but before I do that I delete every file that exist in the directory, but now I cant since, the image is being used by clipboard.
here's my code.
public override void OnClick()
        {
            //base.OnClick();
            DeleteOldCopiedJPG();
            System.Windows.Forms.Clipboard.Clear();
            string fileName = System.Windows.Forms.Application.ExecutablePath.Substring(0, System.Windows.Forms.Application.ExecutablePath.LastIndexOf("\\") + 1) + Guid.NewGuid() + ".jpg";
            //System.Windows.Forms.Cursor.Current = Cursors.Wait;
            //if (System.IO.File.Exists(fileName))
            //    System.IO.File.Delete(fileName);
            IExport objExport = (IExport)new ExportJPEG();
            objExport.ExportFileName = fileName;
#if Debug || Release
            ESRI.ArcGIS.Display.tagRECT objExportRECT = default( ESRI.ArcGIS.Display.tagRECT);
#else
            tagRECT objExportRECT = default(tagRECT);
#endif
            var _with1 = objExportRECT;
            _with1.left = mapControl.ActiveView.ExportFrame.left;
            _with1.top = mapControl.ActiveView.ExportFrame.top;
            _with1.right = mapControl.ActiveView.ExportFrame.right;
            _with1.bottom = mapControl.ActiveView.ExportFrame.bottom;

            IEnvelope envelope = new EnvelopeClass();
            envelope.PutCoords(mapControl.ActiveView.ExportFrame.left, mapControl.ActiveView.ExportFrame.top,
                mapControl.ActiveView.ExportFrame.right, mapControl.ActiveView.ExportFrame.bottom);
            objExport.PixelBounds = envelope;

            System.Int32 intHDC = objExport.StartExporting();
            mapControl.ActiveView.Output(intHDC, Convert.ToInt16(objExport.Resolution), objExportRECT, null, null);
            objExport.FinishExporting();
            objExport.Cleanup();

            System.Drawing.Image objImage = System.Drawing.Bitmap.FromFile(fileName);
            System.Windows.Forms.Clipboard.SetImage(objImage);

            //RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
            //renderTargetBitmap.Render((Visual)mapControl.ActiveView.ScreenDisplay);
            //Clipboard.SetImage(renderTargetBitmap);
        }

private void DeleteOldCopiedJPG(string Path)
        {
            string[] filePaths = Directory.GetFiles(System.Windows.Forms.Application.ExecutablePath.Substring(0, System.Windows.Forms.Application.ExecutablePath.LastIndexOf("\\") + 1));
            foreach (string filepath in filePaths)
                if (filepath.Substring(filepath.Length - 4) == ".jpg")
                    try{ File.Delete(filepath); } catch {}
        }

A: You need to dispose the image after inserting it into the clipboard:
using (System.Drawing.Image objImage = System.Drawing.Bitmap.FromFile(fileName))
{
    System.Windows.Forms.Clipboard.SetImage(objImage);
}

Otherwise it will remain open until the garbage collector calls the finalizer for objImage.


text:
Q: jquery calculate percentage with a max of 100% Simple progress bar that shows the percent the user has scrolled down a particular section of the page, in this case the main body of an article page (.post), reaches 100% when the end of the article/beginning of the comments are reached.
$(window).scroll(function() {
    var conheight = $('.post').height();
    var startDistance = 0;
    var scrollTop = $(document).scrollTop();
    var scrollAmount = $(window).scrollTop();
    var scrollArea = $('.commentswrapper').offset().top - $('.post').offset().top;

    // calculate the percentage the user has scrolled down the page and substract comment section
    var scrollPercent = 100 * $(window).scrollTop() / (scrollArea);

    if (scrollTop > 0) {
        $('.progress-bar').css('width', scrollPercent +"%"  );
    } else {
        $('.progress-bar').css('width', startDistance);
    }

});

The problem is that although it reaches 100% when the end of .post is reached, it keeps expanding as the comment section is scrolled.
How do I limit scrollPercent to 100% as an maximum?

A: // calculate the percentage the user has scrolled down the page and substract comment section
var scrollPercent = 100 * $(window).scrollTop() / (scrollArea);

if (scrollPercent > 100) {
    scrollPercent = 100;
}


text:
Q: how to use listagg operator so that the query should fetch comma separated values SELECT (SELECT STRING_VALUE
        FROM EMP_NODE_PROPERTIES
        WHERE NODE_ID=AN.ID ) containedWithin
FROM EMP_NODE AN
WHERE AN.STORE_ID = ALS.ID
AND an.TYPE_QNAME_ID=(SELECT ID
                      FROM EMP_QNAME
                      where LOCAL_NAME = 'document')
AND
AND AN.UUID='13456677';

from the above query I am getting below error.
ORA-01427: single-row subquery returns more than one row
so how to change the above query so that it should fetch comma separated values

A: This query won't return error you mentioned because

*

*there are two ANDs and

*there's no ALS table (or its alias).

I suggest you post something that is correctly written, then we can discuss other errors.

Basically, it is either select string_value ... or select id ... (or even both of them) that return more than a single value.

*

*The most obvious "solution" is to use select DISTINCT

*another one is to include where rownum = 1

*or, use aggregate functions, e.g. select max(string_value) ...
while the most appropriate option would be to join all tables involved and decide which row (value) is correct and adjust query (i.e. its WHERE clause) to make sure that desired value will be returned.

A: You would seem to want something like this:
SELECT LISTAGG(NP.STRING_VALUE, ',') WITHIN GROUP(ORDER BY NP.STRING_VALUE)
       as containedWithin
  FROM EMP_NODE N
  JOIN EMP_QNAME Q
    ON N.TYPE_QNAME_ID = Q.ID
  LEFT JOIN EMP_NODE_PROPERTIES NP
    ON NP.NODE_ID = N.ID
 WHERE Q.LOCAL_NAME = 'document'
   AND AN.UUID = '13456677';

This is a bit speculative because your original query would not run for the reason explained by Littlefoot.