Q: unable to itherate through the array perl I have this perl script:
my %perMpPerMercHash;

foreach my $sheet () {   #proper ranges specified
    foreach my $row ( ) {    #proper ranges specified
        #required variables declared.
        push(@{$perMpPerMercHash{join("-", $mercId, $mpId)}}, $mSku);
    }
}

#Finally 'perMpPerMercHash' will be a hash of array`
foreach my $perMpPerMerc ( keys %perMpPerMercHash ) {
    &genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
}

sub genFile {
    my ( $outFileName, @skuArr ) = @_;
    my $output = new IO::File(">$outFileName");
    my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
 #mpId is generated.
    &prepareMessage($writer, $mpId, @skuArr);
}

sub prepareMessage {
    my ( $writer,  $mpId, @skuArr ) = @_;
    my $count = 1;
    print Dumper \@skuArr;    #Printing correctly, 8-10 values.
    foreach my $sku ( @skuArr ) {   #not iterating.
        print "loop run" , $sku, "\n";   #printed only once.
    }
}

Can somebody please help why this is happening. I am new to perl and could not understand this anomaly.
EDIT:
output of Dumper:
$VAR1 = [
          'A',
          'B',
          'C',
        ];

A: When you do
&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});

You're passing a reference to an array.
So in
sub genFile {
    my ( $outFileName, @skuArr ) = @_;

You have to do :
sub genFile {
    my ( $outFileName, $skuArr ) = @_;

and then use @$skuArr.
Have a look at references
The modified genFile sub will be:
sub genFile {
    my ( $outFileName, $skuArr ) = @_;
    my $output = new IO::File(">$outFileName");
    my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
 #mpId is generated.
    &prepareMessage($writer, $mpId, @$skuArr);
}

And the other sub don't need to be modified.
Or you can pass always skuArr  by reference:
&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
...
sub genFile {
    my ( $outFileName, $skuArr ) = @_;
    ...
    &prepareMessage($writer, $mpId, $skuArr);
}

sub prepareMessage {
    my ( $writer,  $mpId, $skuArr ) = @_;
    my $count = 1;
    print Dumper $skuArr;
    foreach my $sku ( @$skuArr ) {
        print "loop run" , $sku, "\n";
    }
}


Q: mootools accordion styling problem I just built my first mootools accordion, but it is adding a lot of inline styles which is just ruining my UI. I can set up a inline style with !important keyword but it will just make my css maintenance a nightmare. any ideas how to get rid of the inline styles
It is just this
<script language="javascript">
   window.addEvent('domready', function() {

 //create our Accordion instance
 var myAccordion = new Accordion($('accordion'), 'div.subTreeHeader', 'div.accordionElement', {
 opacity: false, fixedHeight:400

 });

});

</script>

A: Well this is quite old question, I answer it because I run to it when looking for the same problem.
Actually Mootools Acordion adds this much inline CSS:
padding-top: 0px; border-top-style:
none; padding-bottom: 0px; border-bottom-style: none;
overflow: hidden; opacity: 1;

The solutions I found for this are fixes that have to be applied after calling the new Fx.Accordion. I also agree that feels wrong to fix with !important CSS fixing. So I also looked for other options.
Option 1, set back the css as you want:
$$('.acordion3_content').setStyles({
    border: '3px solid #0F0',
    'overflow-y': 'auto',
});

Option 2, create one more div inside or outside it. I did this option to get a scroll div I could have events connected to. Like this I could have a scroll inside the accordion's content without it being affected of Fx.Acordion's CSS.


Q: Updating the Jpanel of a class After some advice on using jpanel - I'm new to java and playing around with the GUI elements.
Bascially what I'm curious about is if I can set up a Jpanel in one class, then somehow add labels etc to the that container, but from another class.
Is this possible ? or do i have to set the entire GUI up in one class, but then I guess I would have the same issue, if I wanted to update those fields I had set up in the main class from another class?
Apologies I don't really have any code that's usefull to demostrate here - I'm just trying to get the idea going, working out if its possible before I go ahead. And I'm not even sure if this is possible. Any advice would be greatly appreciated.
Thanks

A: As long as you have a reference to the JPanel, you can add whatever GUI-element you want, by calling add(JComponent comp) on the JPanel.
So, you can do something like this:
class Panel extends JPanel{

    ...

}

class Main{

    public Main(JPanel thePanel){
        thePanel.add(new JButton("Hello"));
    }
}

Was this what you were looking for?
You can also update the fields added to the panel from another class, if you have a public  accessor-method set up, in the class. So in your panel class, you have a method:
public JButton getButton(){
    return button;
}

Then you can access the button from whatever class with a reference to your panel class, like this:
panel.getButton().setText("Some text");

Note that the button could just as well be public, then you could simply call the method directly: panel.button.setText("Some text"); but this is not considered good code, as it violates some general good OOP practices, not relevant to mention here.


Q: F# Split list into sublists based on comparison of adjacent elements I've found this question on hubFS, but that handles a splitting criteria based on individual elements. I'd like to split based on a comparison of adjacent elements, so the type would look like this:
val split = ('T -> 'T -> bool) -> 'T list -> 'T list list

Currently, I am trying to start from Don's imperative solution, but I can't work out how to initialize and use a 'prev' value for comparison. Is fold a better way to go?
//Don's solution for single criteria, copied from hubFS
let SequencesStartingWith n (s:seq<_>) =
    seq { use ie = s.GetEnumerator()
          let acc = new ResizeArray<_>()
          while ie.MoveNext() do
             let x = ie.Current
             if x = n && acc.Count > 0 then
                 yield ResizeArray.to_list acc
                 acc.Clear()
             acc.Add x
          if acc.Count > 0 then
              yield  ResizeArray.to_list acc }

A: This is an interesting problem! I needed to implement exactly this in C# just recently for my article about grouping (because the type signature of the function is pretty similar to groupBy, so it can be used in LINQ query as the group by clause). The C# implementation was quite ugly though.
Anyway, there must be a way to express this function using some simple primitives. It just seems that the F# library doesn't provide any functions that fit for this purpose. I was able to come up with two functions that seem to be generally useful and can be combined together to solve this problem, so here they are:
// Splits a list into two lists using the specified function
// The list is split between two elements for which 'f' returns 'true'
let splitAt f list =
  let rec splitAtAux acc list =
    match list with
    | x::y::ys when f x y -> List.rev (x::acc), y::ys
    | x::xs -> splitAtAux (x::acc) xs
    | [] -> (List.rev acc), []
  splitAtAux [] list

val splitAt : ('a -> 'a -> bool) -> 'a list -> 'a list * 'a list

This is similar to what we want to achieve, but it splits the list only in two pieces (which is a simpler case than splitting the list multiple times). Then we'll need to repeat this operation, which can be done using this function:
// Repeatedly uses 'f' to take several elements of the input list and
// aggregate them into value of type 'b until the remaining list
// (second value returned by 'f') is empty
let foldUntilEmpty f list =
  let rec foldUntilEmptyAux acc list =
    match f list with
    | l, [] -> l::acc |> List.rev
    | l, rest -> foldUntilEmptyAux (l::acc) rest
  foldUntilEmptyAux [] list

val foldUntilEmpty : ('a list -> 'b * 'a list) -> 'a list -> 'b list

Now we can repeatedly apply splitAt (with some predicate specified as the first argument) on the input list using foldUntilEmpty, which gives us the function we wanted:
let splitAtEvery f list = foldUntilEmpty (splitAt f) list

splitAtEvery (<>) [ 1; 1; 1; 2; 2; 3; 3; 3; 3 ];;
val it : int list list = [[1; 1; 1]; [2; 2]; [3; 3; 3; 3]]

I think that the last step is really nice :-). The first two functions are quite straightforward and may be useful for other things, although they are not as general as functions from the F# core library.

A: How about:
let splitOn test lst =
    List.foldBack (fun el lst ->
            match lst with
            | [] -> [[el]]
            | (x::xs)::ys when not (test el x) -> (el::(x::xs))::ys
            | _ -> [el]::lst
         )  lst []

the foldBack removes the need to reverse the list.

A: Having thought about this a bit further, I've come up with this solution. I'm not sure that it's very readable (except for me who wrote it).
UPDATE Building on the better matching example in Tomas's answer, here's an improved version which removes the 'code smell' (see edits for previous version), and is slightly more readable (says me).
It still breaks on this (splitOn (<>) []), because of the dreaded value restriction error, but I think that might be inevitable.
(EDIT: Corrected bug spotted by Johan Kullbom, now works correctly for [1;1;2;3]. The problem was eating two elements directly in the first match, this meant I missed a comparison/check.)
//Function for splitting list into list of lists based on comparison of adjacent elements
let splitOn test lst =
    let rec loop lst inner outer = //inner=current sublist, outer=list of sublists
        match lst with
        | x::y::ys when test x y -> loop (y::ys) [] (List.rev (x::inner) :: outer)
        | x::xs ->                  loop xs (x::inner) outer
        | _ ->                      List.rev ((List.rev inner) :: outer)
    loop lst [] []

splitOn (fun a b -> b - a > 1) [1]
> val it : [[1]]

splitOn (fun a b -> b - a > 1) [1;3]
> val it : [[1]; [3]]

splitOn (fun a b -> b - a > 1) [1;2;3;4;6;7;8;9;11;12;13;14;15;16;18;19;21]
> val it : [[1; 2; 3; 4]; [6; 7; 8; 9]; [11; 12; 13; 14; 15; 16]; [18; 19]; [21]]

Any thoughts on this, or the partial solution in my question?

A: "adjacent" immediately makes me think of Seq.pairwise.
let splitAt pred xs =
    if Seq.isEmpty xs then
        []
    else
        xs
        |> Seq.pairwise
        |> Seq.fold (fun (curr :: rest as lists) (i, j) -> if pred i j then [j] :: lists else (j :: curr) :: rest) [[Seq.head xs]]
        |> List.rev
        |> List.map List.rev

Example:
[1;1;2;3;3;3;2;1;2;2]
|> splitAt (>)

Gives:
[[1; 1; 2; 3; 3; 3]; [2]; [1; 2; 2]]

A: I would prefer using List.fold over explicit recursion.
let splitOn pred = function
    | []       -> []
    | hd :: tl ->
        let (outer, inner, _) =
            List.fold (fun (outer, inner, prev) curr ->
                            if pred prev curr
                            then (List.rev inner) :: outer, [curr], curr
                            else outer, curr :: inner, curr)
                      ([], [hd], hd)
                      tl
        List.rev ((List.rev inner) :: outer)

A: I like answers provided by @Joh and @Johan as these solutions seem to be most idiomatic and straightforward. I also like an idea suggested by @Shooton. However, each solution had their own drawbacks.
I was trying to avoid:

*

*Reversing lists

*Unsplitting and joining back the temporary results

*Complex match instructions

*Even Seq.pairwise appeared to be redundant

*Checking list for emptiness can be removed in cost of using Unchecked.defaultof<_> below

Here's my version:
let splitWhen f src =
    if List.isEmpty src then [] else
    src
    |> List.foldBack
        (fun el (prev, current, rest) ->
            if f el prev
            then el , [el]          , current :: rest
            else el , el :: current , rest
        )
        <| (List.head src, [], [])               // Initial value does not matter, dislike using Unchecked.defaultof<_>
    |> fun (_, current, rest) -> current :: rest // Merge temporary lists
    |> List.filter (not << List.isEmpty)         // Drop tail element


Q: invoking functions defined by flet in another function I have a collection of functions defined in foo that I want to also want to use in bar. I have these functions defined in foo because I want foo to be self-contained -- otherwise I know that I can define these functions externally (globally) to be accessible to foo and bar and other functions, or define both foo and bar within a labels construct in which these functions are defined only for foo and bar. In any case, I would like for foo to be distributable without the external functions or the labels structure. Hence the challenge.
This is what I have so far (I am using Emacs Lisp in this case), but what I have now ends up defining the local functions in foo globally when I invoke bar. Any suggestions how to define local variables/functions in bar "on the fly"?
(defun foo (x)
  (flet ((addone (x) (1+ x))
     (addtwo (x) (+ 2 x)))
    (addtwo x)))

(defun bar (x)
  (let* ((fnlist (car (cdaddr (symbol-function 'foo))))
     (nfn (length fnlist))
     (ifn nil)
     (bar-body '(addone x))
     (i 0))
    (eval (append
       ;; local symbol names
       ;; to which function definitions will be set
       (list 'let (mapcar 'car fnlist))
       ;; set function definitions
       (list '(while (< i nfn)
            (setq ifn (nth i fnlist))
            (eval `(fset ',(car ifn) ,(append (list 'lambda) (cdr ifn))))
            (setq i (1+ i))))
       ;; function invocation
       (list bar-body)))))

Function application:
(foo 1) ;;=> 3

(bar 1) ;;=> 2

(addone 1) ;;=> 2 ?should not be defined outside of bar?

A: This isn't self-contained, so it's not really an answer; but it's different to the other options you mentioned, so I'll add it anyway.
(defmacro with-foo-functions (&rest forms)
  `(flet ((addone (x) (1+ x))
          (addtwo (x) (+ 2 x)))
     ,@forms))

(defun foo (x)
  (with-foo-functions
   (addtwo x)))

(defun bar (x)
  (with-foo-functions
   (addone x)))

A: Emacs Lisp has dynamic binding. This is different from the lexical binding used by pretty much all other Lisps. For example, if you try to do the following in Common Lisp, you will get an error message saying that FOO is not defined:
(defun bar ()
  (foo 10))

(flet ((foo (x) (1+ x)))
  (bar))

In Emacs Lisp, however, since FOO is dynamically bound this will return 11 as the binding of FOO is available in BAR.
Emacs Lisp does not provide lexical bindings for functions, so in order to achieve the same thing in Emacs Lisp you'll have to fake it by binding a lambda to a lexical variable and then use a macro to hide the FUNCALL:
(lexical-let ((foo #'(lambda (x) (1+ x))))
  (macrolet ((foo (x) `(funcall foo ,x)))
    (foo 10)))

The other answer to this question suggests the use of a macro instead of the flet. This works, but it results in unnecessary code duplication. My solution prevents this at the expense of having to either write the macrolet part, or using funcall every time you want to call the function. One could write a macro to wrap all of this inside a lexical flet version if this is something that is needed often.


Q: What are the Newton groupoids from Drinfeld's paper on the Grinberg-Kazhdan theorem? The paper the Grinberg-Kazhdan formal arc theorem and the Newton groupoids by Drinfeld seems to contain many interesting things which are beyond me. For now, I am trying to get some intuition for the Newton groupoids. From the introduction:

The proof is based on the ideas that go back to the 17th century (namely, the implicit function theorem or equivalently, Newton's method for finding roots) and the 19th century (the Weierstrass division theorem).
The goal of the rest of the article is to clarify the geometric ideas behind the proof from §2. In particular, we introduce Newton groupoids. These are certain groupoids in the category of schemes, which are related to Newton's method for finding roots. They are associated to any generically étale morphism from a locally complete intersection to a smooth variety (both schemes are assumed separated).

The actual setting for the definition of Newton groupoids seems to me rather involved, so instead of writing down, I risk assuming many people read what Drinfeld writes.
Question. What is the geometric intuition behind Newton groupoids, and how are they related to the implicit function theorem/Newton's method of finding roots?


Q: Why does HashSet not implement ICollection? I am going to write a library to traverse an object graph (like some kind of serialization).
You will need to judge if an object is a collection in the traverse, so the ICollection came out of my mind. (string has also implemented IEnumerable)
But it is really weird that almost all containers in Collections have implemented ICollection except HashSet only implemented ICollection<T>...
I have checked out almost all common containers in System.Collections namespace:
ArrayList : IList, ICollection, IEnumerable, ICloneable
BitArray : ICollection, IEnumerable, ICloneable
Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable
Queue : ICollection, IEnumerable, ICloneable
SortedList : IDictionary, ICollection, IEnumerable, ICloneable
Stack : ICollection, IEnumerable, ICloneable
Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, IDeserializationCallback
HashSet<T> : ISerializable, IDeserializationCallback, ISet<T>, ICollection<T>, IEnumerable<T>, IEnumerable
LinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
Queue<T> : IEnumerable<T>, ICollection, IEnumerable
SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
SortedSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
Stack<T> : IEnumerable<T>, ICollection, IEnumerable

Is this a bug? Or there are some reason behind?

A: ICollection isn't anywhere near as useful now as it was with .NET 1.1 when there was no ICollection<T> offering greater type safety. There's very little one can usefully do with ICollection that one can't do with ICollection<T>, often with greater efficiency and/or type safety, especially if one writes generic methods for those cases where one might want to do something with collections of different element types.
This though begs the question of why the likes of List<T> did implement ICollection. But when List<T> was introduced with .NET 2.0 all legacy code was using ICollection and ArrayList, not ICollection<T> and List<T>. Upgrading code to use List<T> rather than ArrayList can be a pain, especially if it means having to either immediately change all uses of ICollection it would hit to use ICollection<T> or, even worse, double up because a method was being hit with the List<T> that was also being hit with other non-generic collections and so versions of the method would be needed for each. Implementing ICollection eased the upgrade path by allowing people to be more piecemeal in how they took advantage of generic collections.
When HashSet<T> came out generics had been in use for three years already, and there was not a previous non-generic hash-set type provided by the framework, so there was less of an upgrade pain, and hence less of a motivation for supporting ICollection.


Q: Why are (Pre)sheaves more important than Co(pre)sheaves? I'm learning Sheaf Theory,  and this is an issue that's been bothering me.
Fix a small category $\mathcal{C}$.
A $\mathcal{V}$-valued presheaf on the small category $\mathcal{C}$ is a functor $F:\mathcal{C}^{\text{op}}\rightarrow \mathcal{V}$. This determines a category $[\mathcal{C}^{\text{op}},\mathcal{V}]$ where objects are $\mathcal{V}$-valued presheaves, and morphisms are natural transformations between them.
If we impose certain gluing conditions (namely a Grothendieck Topology $J$), we can form the full subcategory $\text{Sh}_{\mathcal{V}}(\mathcal{C},J)$ of $[\mathcal{C}^{\text{op}},\mathcal{V}]$ called the category of $\mathcal{V}$-valued sheaves on the category $\mathcal{C}$.
There is also a dual notion called a copresheaf, which is a functor $F:\mathcal{C}\rightarrow \mathcal{V}$, determining a category $[\mathcal{C},\mathcal{V}]$ of copresheaves similar to earlier. Cosheaves form a category (which I'll denote $\textbf{CoSh}_{\mathcal{V}}(\mathcal{C},J)$) by a similar construction. (One can also view co(pre)sheaves $\mathcal{C}$ as (pre)sheaves on $\mathcal{C}^{\text{op}}$)
If $\mathcal{V}$ is an abelian category, then studying $\text{Sh}_{\mathcal{V}}(\mathcal{C},J)$ gives rise to Sheaf Cohomology. Also, if $\mathcal{V} = \textbf{Set}$, then $\text{Sh}_{\textbf{Set}}(\mathcal{C},J)$ is a very important example of a topos.
My question is why are (pre)sheaves more studied/important than co(pre)sheaves, when
$\mathcal{C}$ and $\mathcal{C}^{\text{op}}$ are both small categories? Do (pre)sheaves give more important information about the category $\mathcal{C}$ (depending on what one is studying)?


Q: Why mangled names found within an exe? I have an MS C/C++ statically linked release exe (no debug info on it), that does not export any symbol, but when browsing it with a hex viewer I see things like
.?AVElxInterface@@
.?AV?$CBufferRefT@H@@
.?AV?$CBufferT@H@@
.?AV?$CBufferRefT@PAVElxInterface@@@@

of course they are the mangled names of certain classes/members provided by the internal C++ modules.
why are they there? how can avoid exposing them?

A: Personally, I don't see any reason to over-hide this data, as it supplies no clue to people who view it on how to utilize these symbols to do something "bad". However, if that's really a huge problem for you, i.e. you are afraid of being sort of reverse-engineered somehow, then you may opt to code obfuscation. For example, Semantic Designs offer a product for these purposes and claim that it's of high quality. I've never had a chance to try that stuff myself. Keep in mind that it's commercial.


Q: EF Core: Column with ValueGeneratedOnAdd trows "Cannot insert explicit value for identity column..." I have ASP.NET MVC 5 application that uses Entity Framework 6.2. This app creates some records in MS SQL server.
I have to process this records in AWS lambda function. For this purpose, I created c# .NET Core v2.0 lambda function. There I generate models from existed DB as described in the next article - Getting Started with EF Core on ASP.NET Core with an Existing Database.
Generated models look like:
public partial class Request
{
    public int EntityId { get; set; }
    public Result Result { get; set; }
}
public partial class Result
{
    public int EntityId { get; set; }
    public Request Entity { get; set; }
}

And OnModelCreating:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Request>(entity =>
    {
        entity.HasKey(e => e.EntityId);
        entity.ToTable("Request", "mySchema");
    });

    modelBuilder.Entity<Result>(entity =>
    {
        entity.HasKey(e => e.EntityId);
        entity.ToTable("Result", "mySchema");
        entity.HasIndex(e => e.EntityId).HasName("IX_EntityId");
        entity.Property(e => e.EntityId).ValueGeneratedOnAdd();
        entity.HasOne(d => d.Entity)
            .WithOne(p => p.Result)
            .HasForeignKey<Result>(d => d.EntityId)
            .OnDelete(DeleteBehavior.ClientSetNull)
            .HasConstraintName("FK_mySchema.Result_mySchema.Request_EntityId");
    });
}

In the lambda function, I am processing a request and  setting result:
using (var db = new DataContext(connection))
{
    var request = db.Request.First();
    request.Result = new Result();
    db.SaveChanges();
}

On the save operation I got the exception:
Cannot insert explicit value for identity column in table 'Result' when IDENTITY_INSERT is set to OFF.
I checked different way to solve this issue. But there are already set ValueGeneratedOnAdd function in model creating method.
Also, I tried to add [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to Result.EntityId  - without any success.
What did I miss in my implementation?

A: You are trying to initialize request.Result with new Result() which has no values.  That may cause this error.


Q: Win32 ToolTip disappears never to re-appear with Commctl 6 I'm creating a ToolTip window and adding tools to it using the flags
TTF_IDISHWND | TTF_SUBCLASS. (c++, win32)
I have a manifest file such that my program uses the new WindowsXP themes
(comctrl32 version 6).
When I hover over a registered tool, the tip appears.
Good.
When I click the mouse, the tip disappears.
Ok.
However, moving away from the tool and back
again does not make the tip re-appear. I need to hover over a different tool
and then come back to my tool to get the tip to come back.
When I remove my manifest file (to use the older non-XP comctrl32), the
problem goes away.
After doing some experimentation, I discovered the following differences
between ToolTips in Comctl32 version 5 (old) and Comctl32 version 6 (new):

*

*New TTF_TRANSPARENT ToolTips (when used In-Place) actually return
HTCLIENT from WM_NCITTEST if a mouse button is down, thus getting
WM_LBUTTONDOWN and stealing focus for a moment before vanishing. This causes
the application's border to flash.

*Old TTF_TRANSPARENT ToolTips always return HTTRANSPARENT from WM_NCHITTEST,
and thus never get WM_LBUTTONDOWN themselves and never steal focus. (This seems to be just aesthetic, but may impact the next point...)

*New ToolTips seem not to get WM_TIMER events after a mouse-click, and
only resume getting (a bunch of) timer events after being de-activated and
re-activated. Thus, they do not re-display their tip window after a mouse
click and release.

*Old ToolTips get a WM_TIMER message as soon as the mouse is moved again
after click/release, so they are ready to re-display their tip.
Thus, as a comctl32 workaround, I had to:

*

*subclass the TOOLTIPS_CLASS window and always return HTTRANSPARENT from
WM_NCHITTEST if the tool asked for transparency.

*avoid using TTF_SUBCLASS and rather process the mouse messages myself so
I could de-activate/re-activate upon receiving WM_xBUTTONUP.
I assume that the change in internal behavior was to accommodate the new "clickable" features in ToolTips like hyperlinks, but the hover behavior appears to be thus broken.
Does anyone know of a better solution than my subclass workaround? Am I missing some other point?

A: You're not the only one who has hit compatablity issues with tooltips between these DLLS.
I too have had nothing but trouble with the new tooltips in the themable common controls. We have already been monkeying with mouse messages and active/deactivating the tips before adding the manifest and theming our application - so it sounds like what your doing isn't too crazy.
We're still living with problems with TTN_NEEDTEXT messages being send constantly as the mouse moves (not just when hovering), positioning problems with large tips (maybe not something new), and odd unicode messages being sent instead of the ANSI versions (which I plan to post as a question at some point).

A: I don't know, but this sounds like a really "hard" problem (in the sense that all real-world) problems are really hard. I bet the underlying problem is something to do with the setting of the focus. Windows that manually do that are evil and generally suffer from all manner of bugs.


Q: Can't import modules I've searched for this problem and tried different solutions but can't fix it.
In my Django project I have different apps and a non-app directory called 'testing_utils' with modules which serve for a testing purposes. In particular I want to import all available models to file dummy_factory.py. However when I simply import modules from my apps like so:
from abc import ABC
from datetime import date
from users.models import User

I get the error message

ModuleNotFoundError: No module named 'users'

Which is strange since I definetley can import models to some_app.views.py and access them.
Here's an example of my project's directory:
/home/user/dev/project/
▸ project/
▾ testing_utils/
    dummy_factory.py
▾ users/
  ▸ __pycache__/
  ▸ migrations/
  ▸ templates/
  ▸ tests/
    __init__.py
    admin.py
    apps.py
    models.py
    views.py
  manage.py*

A: /home/user/dev/project/ needs to be in your PYTHONPATH to be able to be imported.
If your testing_utils is meant to be local only, the easiest way to accomplish this is to add:
import sys
sys.path.append('/home/user/dev/project/')

... in dummy_factory.py before importing the module.
Solutions that would be more proper would be to install users (how exactly you'd make your package installable depends on your system and what version of Python and Pip you need to support), or to use a virtualenv that automatically adds the right directories to PYTHONPATH.


Q: How to call specific method of portlet.java class rather then overide serveResource method? I want some help in liferay with ajax.
Right now I am calling the ajax method from my view.jsp page to submit some data.
Here is sample code I am using in view.jsp:
<%@ include file="/init.jsp"%>

<portlet:actionURL name="AddTest" var="add1" />
<portlet:resourceURL id="AddTest" var="AddTest"></portlet:resourceURL>

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

    <script type="text/javascript">
    function addToDo(addToDo){
        var todo =document.getElementById('toDo').value;
        $.ajax({
            url :addToDo,
              data: {"todo":todo,"CMD":"addToDo"},
              type: "GET",
              dataType: "text",
            success: function(data) {
                  $("#toDoList").html(data);
            }
        });
    }
    </script>
</head>

<body>

    <portlet:resourceURL var="addToDo" id="addToDo"></portlet:resourceURL>

    <form>
        <input type="text" name="toDo" id="toDo">
        <button name="Add" type="button" onclick="addToDo('<%=addToDo%>')">Add</button>
        <div id="toDoList">

        </div>
    </form>
</body>
</html>

and in my portlet.java class there is one method which is called by this ajax call:
@Override
public void serveResource(ResourceRequest request, ResourceResponse response){
    if(request.getParameter("CMD").equals("addToDo")) {

        System.out.println("came here for add");

        mediatype userToDo = new mediatypeImpl();
        //userToDo.setMediaId(12345);
        try {
            userToDo.setPrimaryKey((CounterLocalServiceUtil.increment()));
            userToDo.setMedianame(request.getParameter("todo"));
            mediatypeLocalServiceUtil.addmediatype(userToDo);
        }
        catch (SystemException e) {
            e.printStackTrace();
        }
    }
}

So my question is that right now it is just caling by default @override method from any ajax class.
But how can I call specific method of portlet.java class on ajax call?
I am new bee in ajax. So please guide me anyways u can.....
I got following error when calling ajax with url of following
<portlet:actionURL name="ajax_AddAdvertise" var="addToDo" windowState="<%= LiferayWindowState.EXCLUSIVE.toString()%>"> </portlet:actionURL>

06:47:03,705 ERROR [http-bio-8080-exec-23][render_portlet_jsp:154] java.lang.NoSuchMethodException: emenu.advertise.portlet.RestaurantPortlet.ajax_AddAdvertise(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
    at java.lang.Class.getMethod(Class.java:1605)

my process action method as follows
 @ProcessAction(name = "ajax_AddAdvertise")
    public void ajax_AddAdvertise(ResourceRequest request,ResourceResponse response) {

}

A:
how can I call specific method of portlet.java class on ajax call?

I think we can't have two different versions of serveResource methods like we do for action methods atleast not with the default implementation.
If you want different methods you would have to go the Spring MVC (@ResourceMapping) way to have that.
Still, you can define different logic in your serveResource method using the resourceId as follows (a full example):
In the JSP:
<portlet:resourceURL var="myResourceURL" id="myResourceID01" />

In the portlet class the serveResource method will contain the following code:
String resourceID = request.getResourceID();

if(resoureID.equals("myResourceID01")) {
   // do myResourceID01 specific logic
} else {
   // else do whatever you want
}

Please keep in mind [Important]
In a portlet you should not use <html>, <head>, <body> tags since portlets generate fragment of the page and not the whole page. Even if it is allowed your resultant page will not be well-formed and will behave differently on different browsers. And moreover the javascript which modifies DOM element will be totally useless.
Edit after this comment:
You can also use ajax with action methods:
People use <portlet:actionURL> with ajax generally for <form>-POST.
For this the actionURL is generated in a slightly different way in your jsp like this:
<portlet:actionURL name="ajax_AddAdvertise" var="addToDo" windowState="<%= LiferayWindowState.EXCLUSIVE.toString()%>">
</portlet:actionURL>

And in your portlet you can have (as in the question):
@ProcessAction(name = "ajax_AddAdvertise")
public void ajax_AddAdvertise(ActionRequest request, ActionResponse response) {
// ... your code
}


Q: Vue Material - Triggering MdTableAlternateHeader visibility I'm looking for a way to trigger the MdAlternateHeader visibility - or maybe to reset its count state.
The app in question has this multi-selection MdTable in which I implemented a delete function per row. But on data erasing, the alternate header still hold the md-selected class set to true (refeered to the deleted and previously selected element/row). As well as the related computed props (isInSelectedItems and isMultipleSelected).
How can I change these state? I was thinking about to trigger a "selected" or "clicked" event on the row befote its deletion, but I'm missing something on the way.
Thanks in advance for the help.

A: Ok, I got it.
I inspected the framework data and noticed this md-selected-value prop, contained in MdTable component. After declaring the prop in my component:
props: [
    // ...
        'mdSelectedValue'
    ],

I update its value through a second array, delegated to track what elements are being selected for deletion:
data: () => ({
    selezionato = []
})

then I listen for any change in selection:
<md-table v-model="cercato" @md-selected="onSelezionato" md-sort="codice" md-sort-order="asc" md-card md-fixed-header :md-selected-value="selezionato">

In my delete function, after every deletion I reset the the new selezionato value, in order to disable the alternate header:
this.selezionato = []

That's it.


Q: Item not showing in list view after added to database After I add the items in database they show only after I restart the app. How to fix this? I have tried using notifyDataSetChanged() but not sure if i did good.
Fragment showing ListView and Button which calls Add Item Activity:
    @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v =inflater.inflate(R.layout.tab_1,container,false);

    Button button = (Button)v.findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), NewData.class);
            startActivityForResult(intent, 0);}});

    listView = (ListView)v.findViewById(R.id.listView);
    listDataAdapter = new ListDataAdapter(getActivity().getApplicationContext(),R.layout.row_layout);
    listView.setAdapter(listDataAdapter);

    userDbHelper = new UserDbHelper (getActivity().getApplicationContext());
    sqLiteDatabase = userDbHelper.getReadableDatabase();
    cursor = userDbHelper.getInformations(sqLiteDatabase);
    if(cursor.moveToFirst()){
        do {
            String nr1, nr2, nr3;
            nr1 = cursor.getString(0);
            nr2 = cursor.getString(1);
            nr3 = cursor.getString(2);
            DataProvider dataProvider = new DataProvider(nr1, nr2, nr3);
            listDataAdapter.add(dataProvider);}
        while (cursor.moveToNext());}

Add item Activity:
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.additemactivity);
    number_1 = (EditText)findViewById(R.id.number11);
    number_2 = (EditText)findViewById(R.id.number12);
    number_3 = (EditText)findViewById(R.id.number13);

    Button button1=(Button)findViewById(R.id.shtobtn);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String number1 = number_1.getText().toString();
            String number2 = number_2.getText().toString();
            String number3 = number_3.getText().toString();

            userDbHelper = new UserDbHelper(context);
            sqLiteDatabase = userDbHelper.getWritableDatabase();
            userDbHelper.addInformations(number1, number2, number3, sqLiteDatabase);
            Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_SHORT).show();
            userDbHelper.close();
            Intent intent=new Intent();
            setResult(RESULT_OK, intent);
            finish();}});

List Data Adapter:
   @Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    LayoutHandler layoutHandler;
        if (row == null){
            LayoutInflater layoutInflater =(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.row_layout,parent,false);
            layoutHandler = new LayoutHandler();
            layoutHandler.NUMER1=(TextView)row.findViewById(R.id.number11);
            layoutHandler.NUMER2=(TextView)row.findViewById(R.id.number12);
            layoutHandler.NUMER3=(TextView)row.findViewById(R.id.number13);
            row.setTag(layoutHandler);}
    else { layoutHandler = (LayoutHandler)row.getTag();}
    DataProvider dataProvider = (DataProvider)this.getItem(position);
    layoutHandler.NUMER1.setText(dataProvider.getNum1());
    layoutHandler.NUMER2.setText(dataProvider.getNum2());
    layoutHandler.NUMER3.setText(dataProvider.getNum3()); return row;

A: Add listView.notifyDataSetChanged(); after list is updated.

A: Create one public method in adapter class which is notifyDataSetChanged()

A: If you are using SQLite DB then to automatically populated the updated database values into your list view, you should extend your custom adapter with CursorAdapter. Once you fetch data in cursor it will automatically show you the updated values;
    public class CustomAdapter extends CursorAdapter {

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.your_list_item, parent, false);
       // return null;
    }

    @Override
    public Object getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

    }
 }

A: In your Fragment
private SharedPreferences.Editor editor;
private SharedPreferences sharedpreferences;
UpdatingReceiver updatingReceiver;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup  container, @Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context);
    editor = sharedpreferences.edit();
    editor.putString("some unique key", name);
    String name = "Inside";
}
  @Override
protected void onPause() {
    super.onPause();
    editor = sharedpreferences.edit();
    String name = "Outside";
    editor.putString("some unique key", name);
    editor.commit();
}
@Override
protected void onStart() {
    super.onStart();
    updatingReceiver = new UpdatingReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("updating receiver unique key");
    registerReceiver(updatingReceiver, intentFilter);

}

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(updatingReceiver);
}
class UpdatingReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //list all the data
        //set adapter
        //notifyDataSetChanged
    }
}

So you can come to know if you are in inside the fragment or outside the fragment. Based on that you should trigger from your activity.
In your Activity, after you added the code in db just call the receiver based on inside or outside. So it will update immediately.
private SharedPreferences.Editor editor;
private SharedPreferences sharedpreferences;
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
String prefsString = sharedpreferences.getString("some unique key", "");
if (prefsString=="Inside")
{
   Intent broadCast = new Intent();
                broadCast.setAction("updating receiver unique key");
                sendBroadcast(broadCast);
}

A: The solution:
    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {adapter.notifyDataSetChanged();}


Q: Django App - Ajax Auto-complete After 2 Characters and 1s Delay I have this piece of code in my Django app to create simple auto-complete search suggestion box. How do I limit the Ajax to at least 2 characters and how can I add lets say 1sec delay for the Ajax to execute the search query?
$(function(){

$('#search').keyup(function() {

    $.ajax({
        type: "POST",
        url: "/search/",
        data: {
            'search_text' : $('#search').val(),
            'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
        },
        success: searchSuccess,
        dataType: 'html'
    });

});

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}

A: Assuming that #search is probably a text input field, you can add the following code right before your ajax request:
// get the value that the user has typed
var v = $(this).val();
// don\'t go on if less than 3 chars or
// some other key was pressed that did not change the data
if (v.length < 3 || v == $(this).data('prev-val')) return;
// set the old value as the new one
$(this).data('prev-val', v);
// now call ajax

Following a comment in the question, this does not deal with any time delay. A timer could easily be used to trigger the ajax request, and cancel any previous timer before setting a new one. But this would probably make matters more complicated for no good reason.


Q: a conjecture of certain q-continued fractions Given the squared nome $q=e^{2i\pi\tau}$ with $|q|\lt1$, define,
$$\begin{aligned}F(q)=\cfrac{1-q^2}{1-q^3+\cfrac{q^3(1-q)(1-q^5)}{1-q^9+\cfrac{q^6(1-q^4)(1-q^8)}{1-q^{15}+\cfrac{q^9(1-q^7)(1-q^{11})}{1-q^{21}+\ddots}}}}\overset{\color{red}{?}}=\prod_{n=1}^\infty\frac{(1-q^{12n-2})(1-q^{12n-10})}{(1-q^{12n-4})(1-q^{12n-8})}\\[1.5mm]&\end{aligned}$$
and
$$\begin{aligned}G(q)=\cfrac{1-q^4}{1-q^3+\cfrac{q^3(1-\frac{1}{q})(1-q^7)}{1-q^9+\cfrac{q^6(1-q^2)(1-q^{10})}{1-q^{15}+\cfrac{q^9(1-q^5)(1-q^{13})}{1-q^{21}+\ddots}}}}\overset{\color{red}{?}}=\prod_{n=1}^\infty\frac{(1-q^{12n-4})(1-q^{12n-8})}{(1-q^{12n-2})(1-q^{12n-10})}\\[1.5mm]&\end{aligned}$$
Q: How do we prove rigorously that the two q-continued fractions are equal to the q-series?
(if true, then the two q-continued fractions are reciprocals such that their product is unity, $F(q)\,G(q)=1$.)

A: (A half-answer.) Let $|q|<1$ and,
$$p = q^m,\quad \alpha = \pm q^{-n},\quad \beta = \pm q^n,\quad \alpha\beta = 1$$
We propose that,
$$\small C_{m,n}(q)=\prod_{k=1}^\infty\frac{(1-\alpha\, p^{4k})(1-\beta\, p^{4k-4})}{(1-\alpha\, p^{4k-2})(1-\beta\, p^{4k-2})} \overset{\color{red}{?}}=\cfrac{(1-\beta\,p^0)}{ 1-p+\cfrac{p(1-\alpha\, p)(1-\beta\, p)}{1-p^3+\cfrac{p^2(1-\alpha\, p^2)(1-\beta\, p^2)}{1-p^{5}+\cfrac{p^3(1-\alpha\, p^3)(1-\beta\, p^3)}{1-p^{7}+\ddots}}}}\tag1 $$
It takes only some algebraic manipulation to show that given,
$$\alpha_1 = \pm q^{\large -n_1},\quad \beta_1 = \pm q^{\large n_1},\quad \alpha\beta = 1$$
then the two products are reciprocals,
$$\frac{(1-\alpha_1\, p^{4k})(1-\beta_1\, p^{4k-4})}{(1-\alpha_1\, p^{4k-2})(1-\beta_1\, p^{4k-2})} \times \frac{(1-\alpha_2\, p^{4k})(1-\beta_2\, p^{4k-4})}{(1-\alpha_2\, p^{4k-2})(1-\beta_2\, p^{4k-2})}=1$$
if,
$$m =\frac{n_1+n_2}{2}\tag2$$
For example, let $m,\,n_1,\,n_2 = 3,\,2,\, 4$, and using $(1)$ and the positive case of $\pm$, we get,
$$C_{3,2}(q) = \prod_{n=1}^\infty\frac{(1-q^{12n-2})(1-q^{12n-10})}{(1-q^{12n-4})(1-q^{12n-8})} = \small\cfrac{1-q^2}{1-q^3+\cfrac{q^3(1-q)(1-q^5)}{1-q^9+\cfrac{q^6(1-q^4)(1-q^8)}{1-q^{15}+\cfrac{q^9(1-q^7)(1-q^{11})}{1-q^{21}+\ddots}}}}$$
$$C_{3,4}(q) = \prod_{n=1}^\infty\frac{(1-q^{12n-4})(1-q^{12n-8})}{(1-q^{12n-2})(1-q^{12n-10})} = \small\cfrac{1-q^4}{1-q^3+\cfrac{q^3(1-q^{-1})(1-q^7)}{1-q^9+\cfrac{q^6(1-q^2)(1-q^{10})}{1-q^{15}+\cfrac{q^9(1-q^5)(1-q^{13})}{1+q^{21}+\ddots}}}}$$
the same as in the post and,
$$C_{3,2}(q)\,C_{3,4}(q) = 1$$
The reciprocality is true for general $m,n_1,n_2$ that obey $(2)$. However, what remains is to show that the cfrac is indeed equal to the infinite product $(1)$.

A: I write $q_n = \exp\frac{2\pi\mathrm{i}\tau}{n}$, thus $q_n^n=q$.
In a related answer
and another one,
I used a formula by Ramanujan, proved by Adiga et al. (1985):
$$\small\frac{(-a;q)_\infty\,(-b;q)_\infty - (a;q)_\infty\,(b;q)_\infty}
{(-a;q)_\infty\,(-b;q)_\infty + (a;q)_\infty\,(b;q)_\infty}
= \cfrac{a+b}{1-q+\cfrac{(a+bq)(aq+b)}{1-q^3+\cfrac{q\,(a+bq^2)(aq^2+b)}
{1-q^5+\cfrac{q^2(a+bq^3)(aq^3+b)}{1-q^7+\cdots}}}}\tag{1}$$
In both cases, we had been able to simplify the result to a quotient of
Jacobi thetanulls, which implies that it is an eta quotient.
We will encounter that pattern again, so let us work it out in general.
Let me recall some two-variable Jacobi theta functions.
For $z\in\mathbb{C}$, let $w=\exp(\mathrm{i}z)$, so that expressions with
$w$ can be considered functions of $z$. Similarly, expressions with some $q_n$
can be considered functions of $\tau$.
I will need the following Theta functions:
$$\begin{align}
 \vartheta_3(z\mid\tau) = \vartheta_3(z,q_2)
 &= \sum_{k\in\mathbb{Z}} q_2^{k^2}\,w^{2k}
\\  &= (-w^2q_2;q)_\infty\,(-w^{-2}q_2;q)_\infty\,(q;q)_\infty
\\ \vartheta_4(z\mid\tau) = \vartheta_4(z,q_2)
 &= \sum_{k\in\mathbb{Z}} (-1)^k\,q_2^{k^2}\,w^{2k}
\\  &= (w^2q_2;q)_\infty\,(w^{-2}q_2;q)_\infty\,(q;q)_\infty
\\  \vartheta_2(z\mid\tau) = \vartheta_2(z,q_2)
 &= \sum_{k\in\mathbb{Z}} q_8^{(2k+1)^2}\,w^{2k+1}
 = q_8 w \sum_{k\in\mathbb{Z}} q^{k\,(k+1)/2}\,w^{2k}
\\  &= q_8 w\,(-w^2q;q)_\infty\,(-w^{-2};q)_\infty\,(q;q)_\infty
\end{align}$$
where the $q$-Pochhammer representations are due to the
triple product identity.
There is another Theta function, known as $\vartheta_1$,
but we will not need it.
If you split the series for $\vartheta_3$ and $\vartheta_4$ in parts
with even resp. odd summation index $k$, you get
$$\begin{align}
 \vartheta_3(z\mid\tau)
 &= \vartheta_3(2z\mid4\tau) + \vartheta_2(2z\mid4\tau)
\\  \vartheta_4(z\mid\tau)
 &= \vartheta_3(2z\mid4\tau) - \vartheta_2(2z\mid4\tau)
\end{align}$$
and therefore
$$\frac{\vartheta_3(z\mid\tau) - \vartheta_4(z\mid\tau)}
{\vartheta_3(z\mid\tau) + \vartheta_4(z\mid\tau)}
= \frac{\vartheta_2(2z\mid4\tau)}{\vartheta_3(2z\mid4\tau)}$$
Plugging in the product representations, we get
$$\frac{(-w^2q_2;q)_\infty\,(-w^{-2}q_2;q)_\infty
- (w^2q_2;q)_\infty\,(w^{-2}q_2;q)_\infty}
{(-w^2q_2;q)_\infty\,(-w^{-2}q_2;q)_\infty
+ (w^2q_2;q)_\infty\,(w^{-2}q_2;q)_\infty}
\\= w^2q_2\,\frac{(-w^4q^4;q^4)_\infty\,(-w^{-4};q^4)_\infty}
{(-w^4q^2;q^4)_\infty\,(-w^{-4}q^2;q^4)_\infty}$$
Suppose we are given $a,b\in\mathbb{C}$ with $ab=q$.
Then we can set $w^2=a/q_2=q_2/b$ or as well $w^2=b/q_2=q_2/a$,
so the above identity takes the form
$$\begin{align}
    \frac{(-a;q)_\infty\,(-b;q)_\infty
    - (a;q)_\infty\,(b;q)_\infty}
    {(-a;q)_\infty\,(-b;q)_\infty
    + (a;q)_\infty\,(b;q)_\infty}
    &= a\,\frac{(-a^2q^3;q^4)_\infty\,(-b^2q^{-1};q^4)_\infty}
    {(-a^2q;q^4)_\infty\,(-b^2q;q^4)_\infty}
\\  &= b\,\frac{(-a^2q^{-1};q^4)_\infty\,(-b^2q^3;q^4)_\infty}
    {(-a^2q;q^4)_\infty\,(-b^2q;q^4)_\infty}
    \tag{2}
\end{align}$$
Applying the above to your question:

*

*For $F(q)$: In $(1)$ and $(2)$, replace $q$ with $q^3$.
So $(2)$ requires $ab=q^3$ now.
Now set $a=-\mathrm{i}q_2^5$, $b=\mathrm{i}q_2$.
Thus $ab = q^3$ and $a/b = -q^2$. This yields
$$\begin{align}
\mathrm{i}q_2\,F(q) &= \mathrm{i}q_2\,\cfrac{1-q^2}
{1-q^3+\cfrac{q^3(1-q)(1-q^5)}
{1-q^9+\cfrac{q^6(1-q^4)(1-q^8)}
{1-q^{15}+\cfrac{q^9(1-q^7)(1-q^{11})}{1-q^{21}+\cdots}}}}
\\&\stackrel{(1)}{=}
\frac{(\mathrm{i}q_2^5;q^3)_\infty\,(-\mathrm{i}q_2;q^3)_\infty
- (-\mathrm{i}q_2^5;q^3)_\infty\,(\mathrm{i}q_2;q^3)_\infty}
{(\mathrm{i}q_2^5;q^3)_\infty\,(-\mathrm{i}q_2;q^3)_\infty
+ (-\mathrm{i}q_2^5;q^3)_\infty\,(\mathrm{i}q_2;q^3)_\infty}
\\&\stackrel{(2)}{=}
\mathrm{i}q_2\,\frac{(q^{2};q^{12})_\infty\,(q^{10};q^{12})_\infty}
{(q^8;q^{12})_\infty\,(q^4;q^{12})_\infty}
\end{align}$$
which confirms the claim for $F(q)$.

*For $G(q)$: Again, use $(1)$ and $(2)$ with $q$ replaced by $q^3$.
Now set $a=-\mathrm{i}q_2^7$, $b=\mathrm{i}q_2^{-1}$.
Thus $ab = q^3$ and $a/b = -q^4$. This yields
$$\begin{align}
\mathrm{i}q_2^{-1}\,G(q) &= \mathrm{i}q_2^{-1}\,\cfrac{1-q^4}
{1-q^3+\cfrac{q^3(1-q^{-1})(1-q^7)}
{1-q^9+\cfrac{q^6(1-q^2)(1-q^{10})}
{1-q^{15}+\cfrac{q^9(1-q^5)(1-q^{13})}{1-q^{21}+\cdots}}}}
\\&\stackrel{(1)}{=}
\frac{(\mathrm{i}q_2^7;q^3)_\infty\,(-\mathrm{i}q_2^{-1};q^3)_\infty
- (-\mathrm{i}q_2^7;q^3)_\infty\,(\mathrm{i}q_2^{-1};q^3)_\infty}
{(\mathrm{i}q_2^7;q^3)_\infty\,(-\mathrm{i}q_2^{-1};q^3)_\infty
+ (-\mathrm{i}q_2^7;q^3)_\infty\,(\mathrm{i}q_2^{-1};q^3)_\infty}
\\&\stackrel{(2)}{=}
\mathrm{i}q_2^{-1}\,\frac{(q^4;q^{12})_\infty\,(q^8;q^{12})_\infty}
{(q^{10};q^{12})_\infty\,(q^2;q^{12})_\infty}
\end{align}$$
which confirms the claim for $G(q)$.
Have fun applying the above formulae to more such continued fractions.


Q: $.each is looping over each character in my json and displaying undefined i need to loop over the below json but the below code is looping over each character in my json and displaying "undefined": (is there anything wrong with the below json??? Any help is appreciated)
{"news_id":"1","news_title":"News Title One","news_date":"2012-03-20","news_pic":"album-bb[6].jpg","news_desc":"Here goes the news title one Here goes the news title one Here goes the news title one Here goes the news title one.","gallid":"3"}
{"news_id":"2","news_title":"News Title Two","news_date":"2012-04-14","news_pic":"174863_163190093755777_2032987021_q.jpg","news_desc":"News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two.","gallid":"0"}

This is my code which is being fired on click event:
var phpNews;
var NewsObject;

$(document).ready(function () {

    $("#btnNewsPage").click(function()
    {
        $.post("server/news.php",null,function(e){
            NewsObject = e;
            $.mobile.changePage("#NewsPage");
        });
    });

    $('#NewsPage').live('pagebeforeshow',function(event, ui){
        var list;
        $.each(NewsObject, function(k,v){
            list = v.news_title;
        });

        $("#displayNews").html(list);
    });

})

A: Looks like, your NewsObject isn't a JSON object but string. It could happen because JQuery can't guess the response type, so you, probably, need to specify dataType for your $.post request (documentation):
$.post("server/news.php", null, function(e){ ... }, 'json');

P.S. Also your JSON not looks valid, i expect to see something like {'a':'b'}, but you have {'a':'b'} {'c':'d'}.
Updated. Based on the comments below, i would suggest you to use next PHP code for your server/news.php:
<?php

require "../includes/config.php";
require "../includes/h.conn.php";
require "../includes/admin.id.php";

$strSQL = "select * from news where admin_id=" .$admin_id;
$objRS = mysql_query($strSQL);
$News_Obj = array();

while ($row = mysql_fetch_assoc($objRS)) {
    $record = array (
               "news_id" => $row['news_id'],
               "news_title" => $row['news_title'],
               "news_date" => $row['news_date']
    );
    $News_Obj[] = $record;
}

// don't forget to clear after yourself: mysql_free_result, disconnect

header("Content-type: application/json");
echo json_encode($News_Obj);
?>

Also you can use Firebug to see what exactly returns the script and which HTTP or Javascript errors happen when you do a request.


Q: WCF Site Blocked by McAfee, how to unblock without turning off firewall McAfee's firewall was blocking me from using a WCF client I made in C# .NET over a local network until I disabled it.  How can I keep the firewall up and add an exception or something for my stie hosted in IIS?  Like when the firewall is up, navigating to http://mark-pc from the other computers comes up with nothing but if you turn off the firewall it comes up with my locally hosted IIS site (which is what I want).  I dont want to turn off the whole firewall so how can I just let that connection go out?
Even when I allow Port 80 though McAfee, it doesn't work.  They can view it in a browser but trying to ping mark-pc fails.


Q: Xamarin.Forms navigation stack flow I'm trying to work out the correct way of structuring the navigation for my Xamarin.Forms application.
Please note the LoginPage is currently set as the application's MainPage.
The intended (visual) structure is as follows:
CheckPermissionsPage ➜ LoginPage ➜ HomePage
I am following a MVVM structure, so my LoginPageViewModel is displaying a modal of CheckPermissionsPage within it's constructor as so:
await Application.Current.MainPage.Navigation.PushModalAsync(new CheckPermissionsPage());
The idea is that the check permissions page validates the application has permissions to specific services and if it does, the page automatically closes. The user must then login to the application, after which the HomePage is displayed.
How would I structure the LoginPage so that the CheckPermissionsPage modal can be displayed/hidden based on permissions state. Consequently, after a successful login, the HomePage is displayed (without an option to return to the LoginPage). Thanks!

A: I ended up changing the application MainPage to navigate throughout the pages. So my initial application main page is now the CheckPermissionsPage. Should permissions be granted I then run Application.Current.MainPage = new NavigationPage(new LoginPage());. After logging in, the HomePage is displayed with Application.Current.MainPage = new NavigationPage(new HomePage());. This probably isn't the most ideal solution, but it does allow me to prevent back navigation for my LoginPage.


Q: Delaying events in a game loop with Android? If you have a game loop thread in Android that draws to a surfaceview and you require a couple of seconds delay to perform animation, how do you go about doing this?


Q: Why is the clone army so...small? In Attack of the Clones, Lama Su says that 200,000 clone units were ready, and a million were on the way. Now I am assuming one unit means one clone trooper. Considering that there were a million planets in the Republic, these numbers are too small to make a difference. A million troops can't even overwhelm a single Earth-sized planet. Did the Republic use other troops or droid or something?

A: The military term "unit" does not mean one individual. In fact, a single unit can contain several hundred soldiers. The relevant factor is the number of people in command.
For instance,

A company is a military unit, typically consisting of 80–250 soldiers and usually commanded by a major or a captain. Most companies are formed of three to six platoons, although the exact number may vary by country, unit type, and structure.
Source: Wikipedia.

If we go by these numbers, we could be talking about 40,000,000 soldiers ready and 200,000,000 on the way. However,
considering that clones are quickly produced, better trained, and far more easily controlled, we can assume that clone units can potentially contain much larger numbers of soldiers.

A: The Kaminoans wasn't selling individual soldiers, so the soldier wasn't the unit.  If it was, all you would have would be clones, and likely their armor and weapons.  But when Yoda deployed them on Geonosis within hours of receiving them, they already had assault vehicles which they were piloting, implying that they were trained to do so.  It's also unlikely that Yoda swung by Crazy Eddie's Correlian Cruisers en route to Kamino, swiped his Galactic Express card, and bought those vehicles on the spot.
The clones were delivered with the vehicles, which implies that they came with all sorts of other equipment, maybe even the interstellar transports themselves.    So a "unit" was likely similar to a military unit, consisting of a group of clones and their heavy equipment.

A: The Clones were the elite assault force of the Republic, a military arm concentrated entirely on the purpose of fighting.
Obviously each member planet had it's own military, because they're well, planets. Each one has billions of people at least and they'd need militaries to regulate their own planetary scale conflicts. Imagine a planet is a planet..like ours. Just like we have towns-cities-states-countries and accompanying levels of conflict. For Star Wars, they add on top of that "Systems" and then "Galaxy."
The GAR and the Seperatists were Galactic scale armies, a fighting force that could fight all across the galaxy. As you'd imagine, moving a whole army across the galaxy would consume far more resources than just having 10 armies sit on a planet somewhere. I mean, think about it, every country in the world has an army, only about a dozen have an honest to god space program.
These forces were capable of subjugating whole planets because of orbital support. Think about it, all they'd need to do is pinpoint weak points in the enemy defenses, target it with a highly advanced strikeforce, and then mop up the incoming reinforcements with turbolaser or even asteroid strikes. A single space crusier could destroy many armies by just throwing a giant space rock near them.

A: Lama Su was likely referring to the number of units that could be deployed immediately.
Here is Lama Su's original dialogue to Obi-Wan Kenobi from Attack of the Clones.

And now to business. You will be delighted to hear we are on schedule. Two hundred thousand units are ready, with another million well on the way.

Given that clones can be fully grown in nearly half of the time when compared to normal humans and that the order was placed nearly ten years ago, it is very likely that Obi-Wan Kenobi was looking only at the first "batch" of clones.
What we are not provided is the number of "batches" or "generations" that had been ordered, only that a million more units were well under way.

Please tell your Master Sifo-Dyas
              that we have every confidence his
              order will be met on time and in
              full. He is well, I hope?

This is reinforced through Lama Su's reference to the order. She implies that it has yet to be fulfilled and that it will be in the future. Thus, both figures provided are only initial estimates.

We are also shown clone troopers in all stages of life, indicating that the clone army is still being developed and that the final numbers are likely far greater than what is provided by Lama Su.

A: The number of Republic and/or Separatist planets isn't what's important -- it's the number of droids faced by the clone army. If there was no Separatist Droid Army then 200,000 clones would be more than enough for the Republic to force its will upon the Separatists. Conversely, had the Senate continued to be deadlocked over the Military Creation Act and the clone army hadn't already existed, the Separatists could have have easily defeated the Republic with its droid army. Imposing its will across the entire galaxy would be difficult for either the Republic or Separatists (the Republic struggled to control the outer regions of the galaxy even in peacetime) but whichever side had an unopposed army would have been able to depose its opponent's seat of government (e.g. Coruscant).
Wookieepedia's Legends article claims that there were 1 million B1 battle droids, 100,000 B2 battle droids, and 3,000 droidekas at the first Battle of Geonosis, but these figures are not well sourced. Assuming they are true, however, that puts the clone army at about a 5-to-1 disadvantage. Nonetheless, the clones had the element of surprise and over two hundred Jedi on their side. Furthermore, the clones are touted as much better than droids:

They're immensely superior to droids, capable of independent thought and action.
Lama Su, Star Wars: Episode II Attack of the Clones

These advantages were apparently enough to overcome the clone army's numerical disadvantage since the clone army literally routed the droid army at the first Battle of Geonosis (in that the Separatists fled in disorder).
Building droids takes less time than growing clones, so one would think that the Separatists' numerical advantage would increase over time. However, the Separatists were not prepared for full-scale production at the beginning of the Clone Wars since the Separatists didn't even know of the existence of the clone army. Furthermore, the clones are age-accelerated so that they only take half the normal time to reach adulthood. And, again, don't forget the huge advantage offered by the Jedi.

A: According to star wars wiki there are about 1,000,000,000 clones since a unit is about 500 troops and they get 3 more million


Q: Control the iterations of triple nested loop in list comprehension, Python I have 2 lists which I need to iterate through:
hits_idx2 = [ 0, 1, 2]
common_b = [ [835,1234,2345] , [223,544] , [423,1234]  ]

in order to produce the following output:

0, 835
  0, 1234
  0, 2345
  1, 223
  1, 544
  2, 423
  2, 1234

I created a nested loop using list comprehensions and a check to see if the element returned at the each iteration if the last element in each sublist, if it not the loop should continue, if it is it should go to the next element of hits_idx2 and iterate through the second sublist in common_b:
for x,y in [(x,y) for x in hits_idx2 for ind in hits_idx2 for y in common_b[ind] if y!=common_b[ind][-1]]:
    print (x,y)

but unfortunately I am getting the following:

0 835
  0 1234
  0 223
  0 423
  1 835
  1 1234
  1 223
  1 423
  2 835
  2 1234
  2 223
  2 423

I am kinda stuck, any help more than welcome. thanks!
I solved it as follows:
for h,y in [ (h,common) for h, common in [(h, common) for h, commons in zip(hits_idx2, common_b) for common in commons] ]:
    print(h,y)


Q: How do I run a single test in Scala? I'm going through the scala labs and I can't seem to figure out how to run a single test.
I run test in sbt and I get 23 failing tests for me to fix. I want to run just the HelloWorldExercise.scala. How would I do this?

A: sbt "testOnly HelloWorldExercise"


Q: Angular2 input data getting lost on button click I have created Angular2 code like this to get the data on button click

             <input #newData [(ngModel)]="data.id" type="text" >
             <select #newCategory [(ngModel)]="i.index" class="input-bars">
              <option *ngFor="let data of field" [value]="data.value">{{data.value}}</option>
            </select>

        <button class="btn btn-success (click)="addData(newData.value, newCategory.value)">ADD</button>

    addData(value, dropValue){

        this.Data[index] = value;
    }

But when the button is clicked the data on the input field is getting lost in ui. How to keep it when the button is clicked and display on the ui as well??

A: I'll hazard a guess that you're working in a form, so add type="button" to the button <button class="btn btn-success" (click)="addData(newData.value)">ADD</button>. That should prevent it from thinking the form is submitting and clearing the data.


Q: reading lines of text in a nonblocking way In a C program I want to read text lines from stdin.
At the same time I want to handle data coming from another file descriptor.
I tried to use poll to wait for any of the two source to become readable and handle them accordingly. However poll needs bare file descriptors and for reading whole lines with something like fgets I need a FILE handle.
I can use fileno or fdopen to "convert" them, but using both in a mixed way does not seem to be a good idea.
Therefore, is there a good way to wait for lines of text without blocking or threading?

A: You can use whatever you want for multiplexing (select(), poll(), epoll_wait()). But you shouldn't read from stdin with fgets() because multiplexing knows nothing about if we've got complete line or no. So it may block in some cases. You should write custom line reading function, that will indicate that there is no complete line yet and return immediately.


Q: Decimal Module in Python Why does this code output 25 although I used the decimal module. I tried it on the calculator and it outputted 26.28.
from decimal import *
getcontext().prec = 2

targetPrice = 40
currentPrice = 56.5
winChance = 0.9
stopLoss = 23
lossChance = 0.1

expectancy =100 * abs(((Decimal(targetPrice) -  Decimal(currentPrice)) / Decimal( currentPrice))) *  Decimal(winChance)
print(expectancy)

A: You're getting inexact results because you're rounding down to two decimal places after every calculation.  Your calculator isn't doing that.
With no rounding.
>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.2920353982300884955752212389')

With rounding:
>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.28')

It only gets worse after that.


Q: Unable to build c++ application using nw-gyp build. Error: error MSB6006: "CL.exe" exited with code -1073741515 I have tried to set up nw-gyp on Windows 8.1 x64 by following the following link:
nw-gyp installation guide
For this I installed:

*

*Python v2.7

*Node v4.2.2 (Setted its path too in environment variable)

*npm v2.14.7

*node-webkit v0.12.3

*Microsoft Visual Studio C++ 2012 for Windows Desktop Express version From Here
after this I installed nw-gyp using the following command.

*

*npm install -g nw-gyp

Now I tried to run the demo app provided here nw-gyp Example
Now I configure the app using command:

*

*nw-gyp configure --target=0.12.3

0.12.3 is my node webkit version. The configuration is successful and I am able to get the build folder. But further when I try to build the addon using command

*

*nw-gyp build

I get the following error
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x64.targets(146,5): error MSB6006: "CL.exe" exited with code -1073741515. [E:\PacificCX\testSecond\build\binding.vcxproj]

Here is the full log:
E:\PacificCX\testSecond>nw-gyp build
gyp info it worked if it ends with ok
gyp info using nw-gyp@0.12.4
gyp info using node@4.2.2 | win32 | x64
(node) child_process: options.customFds option is deprecated. Use options.stdio
instead.
gyp info spawn C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
gyp info spawn args [ 'build/binding.sln',
gyp info spawn args   '/clp:Verbosity=minimal',
gyp info spawn args   '/nologo',
gyp info spawn args   '/p:Configuration=Release;Platform=x64' ]
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppBuild.targets(29
7,5): warning MSB8003: Could not find WindowsSDKDir variable from the registry.
  TargetFrameworkVersion or PlatformToolset may be set to an invalid version nu
mber. [E:\PacificCX\testSecond\build\binding.vcxproj]
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x
64.targets(146,5): error MSB6006: "CL.exe" exited with code -1073741515. [E:\Pa
cificCX\testSecond\build\binding.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Users\kamaldeep.singh\AppData\Roam
ing\npm\node_modules\nw-gyp\lib\build.js:267:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:200:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\kamaldeep.sin
gh\\AppData\\Roaming\\npm\\node_modules\\nw-gyp\\bin\\nw-gyp.js" "build"
gyp ERR! cwd E:\PacificCX\testSecond
gyp ERR! node -v v4.2.2
gyp ERR! nw-gyp -v v0.12.4
gyp ERR! not ok

Someone please help me solve this out. Thanks in advance.
Here is the link to my complete sample program. Download Sample

A: solved this problem by updating Visual Studio 2012.


Q: Getting text after URL in asp.net / URL Rewriting (sort of!) My app is a very simple "one page" type app-
It has Default.aspx
I'm basically trying to get, for example:

www.myappurl.com/this is my text

I want to get hold of "this is my text" from the above example.
This will be displayed on the page (for now)
I didn't really want to have to use any complext url rewriting things for this...
(My hosting provider uses IIS6)
I tried using a 404 handler, but this is a bit long winded, and i'm using shared hosting, that can't set the "execute url" on custom 404 pages.
Any other ideas?

A: You can add a mapping for all requests with the * extension to the ASP.NET isapi dll (GET/POST) verbs. You will need to uncheck the "verify file is on disk" checkbox when mapping the extension in IIS. (In IIS7 integrated mode, you map the extension in the web.config as well). Note that this will caause everything to be served by asp.net, even images and script files, which can slow things down.
Then create a handler mapping in your web.config to a http handler you create.
From there, in the ProcessRequest() method of the handler, you have access to the HttpContext that spawned the request and can manipulate the URL from there.
That is the easiest option, you could also create a HttpModule, or have the default page at root redirect to http://www.domain.com/default.aspx/this is my text, in the code-behind of default.aspx, you will be able to get the text following the page and slash.


Q: docker push to nexus 3 - invalid checksum digest format Though I am able to successfully push a newly pulled docker image to Nexus 3 docker hosted repo, an error like "invalid checksum digest format" is thrown at the end. I pulled "jenkins:latest" from dockerhub, then tagged it and then pushed it to a nexus docker hosted repo.
f3e4e0468545: Pushed
656120ad8c56: Pushed
30f9a83f20f3: Pushed
78dbfa5b7cbc: Pushed
invalid checksum digest format

I know Nexus 3 is not LTS yet, but want to be sure that its not my environment settings. I have an insecure docker registry on 18443

docker info
Containers: 1
 Running: 0
 Paused: 0
 Stopped: 1
Images: 53
Server Version: 1.10.1
Storage Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 89
 Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
 Volume: local
 Network: bridge null host
Kernel Version: 3.16.0-53-generic
Operating System: Ubuntu 14.04.3 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 3.86 GiB

Client:
 Version:      1.10.1
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   9e83765
 Built:        Thu Feb 11 19:27:08 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.10.1
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   9e83765
 Built:        Thu Feb 11 19:27:08 2016
 OS/Arch:      linux/amd64

A: Docker version 1.10 was not out when Nexus 3.0m7 was released.  We are working on adding support for it now.  This specific issue is being tracked here:
https://issues.sonatype.org/browse/NEXUS-9766
UPDATE: This issue/ticket is resolved now in Nexus Repository Manager 3.0.0-03.  For upgrade instructions see https://support.sonatype.com/hc/en-us/articles/217967608-How-to-Upgrade-Nexus-3-Milestone-m7-to-3-0-0-Final.


Q: iPhone didreceivememorywarning strategy If i have a array of employees for example in my viewcontroller. Then I get the notification of low memory and the app is also not the active one.
At this point I should save the list of employees in a DB right ? so that when the user reactivate the app again, it will go through the viewDidLoad and from here I can reload the data from the DB?
Is this a good strategy?
I'm fairly new into iPhone dev.

A: You should save any unsaved changes as soon as your app enters the background. Your app could be terminated at any point in the background without ever receiving any notifications of any kind. If your data isn't saved, it will be lost when the user restarts the app.
With regard to memory warnings, these are more likely to happen in the foreground. Once your app is in the background, it is suspended and won't get any notifications. If your app is running under iOS 5 or earlier then a memory warning could result in a view controller's viewWillUnload method being called. When that view controller needs to be displayed again, its viewDidLoad will be called again. Under iOS 6, this doesn't happen anymore. viewWillUnload is deprecated.


Q: Eigen::SparseTriangularView I am trying to switch some code from Eigen 3.2.10 to 3.3. I am running into compile errors with this method declaration
/// \brief Returns template expression for the lower triangular part of A.
Eigen::SparseTriangularView < SystemMatrixType, Eigen::Lower >
    getLowerTriangular() const;

producing error C2143: syntax error : missing ';' before '<'.
It looks like SparseTriangularView has been renamed or replaced. What should SparseTriangularView or this whole declaration be replaced by?

A: Just use TriangularView < SystemMatrixType, Eigen::Lower >. Triangular and Selfadjoint views of dense and sparse expressions have been unified in 3.3.


Q: How do I get the body in a SOAP response when I have a ClientTransportException In SoapUI/Postman I am sending this request

Notice how I am getting a 401 Unauthorized, but I am getting a response body. The 401 is expected.
Now I am trying to send this message with jax-ws. I intercept the messageresponse with a handler.
My handler looks like this:
public class SHandler implements SOAPHandler<SOAPMessageContext> {
    @Override
    public Set<QName> getHeaders() {
        System.out.println(">>>>>>>>>>> GetHeaders");
        return null;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext soapMessageContext) {
        boolean isRequest = (Boolean) soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (!isRequest) {
            try {
                System.out.println(soapMessageContext.getMessage().getSOAPBody().getValue(););
            } catch (SOAPException e) {
                e.printStackTrace();
            }
        }
        System.out.println(">>>>>>>>> Message");
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext soapMessageContext) {
        try {
            System.out.println(soapMessageContext.getMessage().getSOAPBody().getValue());
        } catch (SOAPException e) {
            e.printStackTrace();
        }
        System.out.println(">>>>>>>>>>> HandleFault");
        return true;
    }

    @Override
    public void close(MessageContext messageContext) {
        System.out.println(">>>>>>>>>>> Close");
    }
}

I would expect to get a return value from the request, but I get null. I only see this response in my console:
com.sun.xml.ws.client.ClientTransportException: The server sent HTTP status code 401: Unauthorized
How do I get the body that is shown in the Postman request?
 Some more context information:
The jax-ws service that makes requests to the blurred out endpoint
@WebServiceClient(
        name = "LIReceiveMessageService",
        targetNamespace = "http://uic.cc.org/UICMessage",
        wsdlLocation = "src/main/java/nl/rls/ci/soapinterface/UICCCMessageProcessingInboundWS.wsdl"
)
public class LIReceiveMessageService
        extends Service {
    ....
}

The messageResolver I added using this oracle guide.
LIReceiveMessageService service = new LIReceiveMessageService();
service.setHandlerResolver(new MyHandlerResolver());


Q: Write to MySQL on mouseover After months of testing, I'm not succeeding to create a script that writes a logtext to the MySQL when a div gets a mouseover.
I think I have to use $.ajax, the only problem is, is that ajax (still) is the language which I'm not very good at.
One of the 100 things i've tried:
<?
echo "
Some dynamic text
";
?>

Who can help?

A: Ok, there's a much better way to do this, but since I'm on a phone that's dying and you have been waiting a year...
var info = $("#div0").html();
// if Js in a php file you can do var info = <?php echo $logtext ?>; To bring it to JS
$.get("phpfilehere.php", {info:info}, function(data){
alert(data);
});

The mouseover function...
$("#div0").on("mouseover", function(){
// my JS code above goes here
 });

PHP file:
if(isset($_GET['info'])){
$log = $_GET['info'];
// Put ur stuff here, make sure u only echo when u want ur php script to stop and be sent back to Ajax function as data var.
// insert $log
echo "test";
} else {
echo "no get info supplied":
}

And here is a tool I made to teach people how to write prepared statements for SQL queries :) if you need it...
http://wbr.bz/QueryPro/index.php?query_type=prepared_insert


Q: Basic Javascript Variable Scoping So I'm trying to make an app that would return whether each of these twich users
  ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx",      "RobotCaleb", "noobs2ninjas"]

is streaming. This is my code:
var users= ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var progress =0;
var streaming = [];
$(document).ready( function() {
console.log(window.progress);
while (window.progress<8) {

var url = 'https://api.twitch.tv/kraken/streams/' + window.users[window.progress] + '?callback=?';
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
if (data.stream) {

window.streaming[window.progress]="streaming";

}
//if closed
else {
window.streaming[window.progress]="not streaming";
};
//else closed

console.log(window.progress);
console.log(window.users[window.progress]);
var html = "
 "+window.users[window.progress]+ " is currently " +window.streaming[window.progress] + "
";
$("body").append(html);
}});
// getjson closed
        window.progress +=1;
        };
// for loop closed

});

//document ready closed

and this is what I'm getting:
"undefined is currently streaming"
so it doesn't seem to pull the users. Thanks

A: Your streaming array isn't initialized, so this can't be done due there's no 0,1,... element on it
window.streaming[window.progress]="streaming"; //streaming.length == 0, streaming[0] == 'undefined'

maybe you would like to clone the users.length on it to have a index
streaming = []; // length == 0
streaming.length = users.length; // length == users.length


Q: How to properly plot a ratio I am trying to plot a ratio but my problem is that when the dividend is larger than the divisor my quotient can be as high as possible.  When the divisor is larger than the dividend the quotient is between 0 and 1.  That is fine, but when I plot out the results the ratios with the larger dividend take up a huge portion of the plot and the smaller dividend ratios are limited to a much smaller area.  Is there a way to show ratios on a plot (hopefully using base plots) where the dividend is five times greater than the divisor will take up the same amount of space as when the divisor is five times greater than the dividend.
Here is some sample data:
x=1:10
y=10:1
ratioxy=x/y

The data is:
x
[1]  1  2  3  4  5  6  7  8  9 10
y
[1] 10  9  8  7  6  5  4  3  2  1
ratioxy
[1]  0.1000000  0.2222222  0.3750000  0.5714286  0.8333333  1.2000000  1.7500000  2.6666667
[9]  4.5000000 10.0000000

When I do this:
plot(ratioxy,type='l',col='blue')
abline(h=1)

I get this:

All I can think of is somehow playing around with the quotients in ratioxy that are less than one, but nothing is coming to me right now.

A: Try using a logarithmic scale.
plot(ratioxy,type='l',col='blue')


Q: Getting False with my Def, What is wrong with my code? def richNumber(n):
    nb = []
    n = int(n)
    sum1 = 0
    for i in range(n, n+1):
        if n % i ==0:
            nb.append(i)
    sum1 = sum(nb) - nb[-1]
    if sum1 > n:
        return True
    else:
        return False

n = int(input("n:"))

print(richNumber(n))

I have 5 Test Cases:
n = 4
n = 12
n = 6
n = 20
n = 100

With n = 4 and 6 the output is false ,with n = 12,20,100 is supposed to be true but its showing false.
This function used to get all divisor of n in a list, if the sum of all divisor of n (not N) is larger than N is true, smaller is False

A: for i in (n, n+1)

Iterates over two numbers, n and n + 1, not all divisors. You need to use range to iterate from 1 to n
for i in range(1, n + 1)

A: Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
    nb = []
    n = int(n)
    sum1 = 0
    for i in range(1, n):
        if n % i == 0:
            nb.append(i)
    sum1 = sum(nb)
    if sum1 > n:
        return True
    else:
        return False


Q: Prove that the solution belong to ${L^2}\left( {0,T;{L^2}\left( \Omega \right)} \right)$ Let $k \in {L^\infty }\left( {0,T} \right)$ and we assume that
$$\phi :t \mapsto u\left( t \right) + \int_0^t {k\left( s \right)u\left( s \right)ds}  \in {L^\infty }\left( {0,T;{L^2}\left( \Omega  \right)} \right).$$
Can we prove that $u \in {L^\infty }\left( {0,T;{L^2}\left( \Omega  \right)} \right)$.
My approach is here.
We have
$$\left\| {u\left( t \right)} \right\| = \left\| {\phi \left( t \right) + \int_0^t {k\left( s \right)u\left( s \right)ds} } \right\| \leqslant \left\| {\phi \left( t \right)} \right\| + \int_0^t {\left| {k\left( s \right)} \right|\left\| {u\left( s \right)} \right\|ds}  \leqslant {\left\| \phi  \right\|_{{L^\infty }\left( {0,T;{L^2}} \right)}} + {\left\| k \right\|_{{L^\infty }\left( {0,T} \right)}}\int_0^t {\left\| {u\left( s \right)} \right\|ds} .$$
Use Gronwall inequality, we get $\left\| {u\left( t \right)} \right\| \leqslant {\left\| \phi  \right\|_{{L^\infty }\left( {0,T;{L^2}} \right)}}\exp \left( {{{\left\| k \right\|}_{{L^\infty }\left( {0,T} \right)}}T} \right)$. Then we have $u \in {L^\infty }\left( {0,T;{L^2}} \right)$.
But i cant prove $u\left( t \right) \in {L^2}$.


Q: Why does the lower bound on the Hardy-Littlewood maximal function make it non-integrable? We have that $$Hf(x) \geq \frac{c}{|x|^n}$$ for some $c>0$ whenever $|x| \geq 1$. How does this lower bound show that that the maximal function is non-integrable? Perhaps if we could show that $\frac{c}{|x|^n}$ isn't integrable outside the unit ball we could show this. However, I am not sure how to do this. Similar questions seem to imply that it is obvious given the inequality.

A: Hint: Observe
\begin{align}
\int_{\mathbb{R}^n} \frac{dx}{|x|^n} =\int^\infty_0 \int_{|x|=r} \frac{1}{|x|^n}\ dS(x)dr
\end{align}


Q: how to make display to console text I am beginner at C# and I am trying like welcome message like as
 Console.WriteLine(" Enter Your Name:");
 Console.Write(new string(' ', Console.WindowWidth));
 Console.Write("first name:");
 string name = Console.ReadLine();

I need after entering the first name to clear the window and go for next output like:
 Console.Write("last name:");
 string lastname = Console.ReadLine();

How do I do this?

A: You can clear the console window with
Console.Clear()

If you put this in between your two blocks of code you should have what you need.
You can also make a blank line by doing
Console.Writeline();

Instead of
Console.Write(new string(' ', Console.WindowWidth));

A: Did you try this...
Console.WriteLine(" Enter Your Name:");

Console.WriteLine("first name:");
string firstName = Console.ReadLine();

Console.WriteLine("last name:");
string lastName = Console.ReadLine();

Please feel free to use Console.Clear() to clear the console.
You may further print/see the values using
Consile.WriteLine("Your First Name is " + firstName + " and last name is " + lastName);


Q: Match and replace string in text using regular expressions I have a large string and it might have the following:

How can I replace values in the string from anything above to:

this is what I came up with, but it does not work:
        string source = "bunch of text";
        string regex = "
";
        string regexReplaceTo = "
";
        string output = Regex.Replace(source, regex, regexReplaceTo);

A: What about...

*

*Regex to match : class=\"[A-Za-z0-9_\-]+\"

*Replace with   : class=\"\"
This way, we ignore the first part (id="Specs", etc) and
just replace the class name... with nothing.

A: Looks like another case of http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html.  What happens to the following valid tags with a Regex?

I don't see a how using Linq2Xml wouldn't work with any combination:
XElement root = XElement.Parse(xml); // XDocument.Load(xmlFile).Root
var specsDivs = root.Descendants()
                    .Where(e => e.Name == "div"
                           && e.Attributes.Any(a => a.Name == "id")
                           && e.Attributes.First(a => a.Name == "id").Value == "Specs"
                           && e.Attributes.Any(a => a.Name == "class"));
foreach(var div in specsDivs)
{
  div.Attributes.First(a => a.Name == "class").value = string.Empty;
}
string newXml = root.ToString()

A: If your input isn't XML compliant, which most HTML isn't, then you can use the HTML Agility Pack to parse the HTML and manipulate the contents. With the HTML Agility PAck, combined with Linq or Xpath, the order of your attributes no longer matters (which it does when you use Regex) and the overall stability of your solution increases a lot.
Using the HTML Agility Pack (project page, nuget), this does the trick:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("your html here");
// or doc.Load(stream);

var nodes = doc.DocumentNode.DescendantNodes("div").Where(div => div.Id == "Specs");

foreach (var node in nodes)
{
    var classAttribute = node.Attributes["class"];
    if (classAttribute != null)
    {
        classAttribute.Value = string.Empty;
    }
}

var fixedText = doc.DocumentNode.OuterHtml;
//doc.Save(/* stream */);


Q: Testing Exceptions in Nunit 3.0 and above I am trying to test an exception, NUnit 3.11 is giving me the error, and the unit test is failing. I want Nunit to green pass if it receives this exception, not error out. How would I resolve this?
Feel free to improve code if you want, just started learning programming few months ago.
When running it gives the exception itself, does not pass.
Test errors out- Message: System.ArgumentException : Too much data
public class ParseVendorSupply
{
    public VendorSupply FromCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        if (values.Length > 3)
        {
            throw new System.ArgumentException("Too much data");
        }
        VendorSupply vendorsupply = new VendorSupply();
        vendorsupply.VendorId = Convert.ToInt16(values[0]);
        vendorsupply.ProductId = Convert.ToInt16(values[1]);
        vendorsupply.Quantity = Convert.ToInt16(values[2]);
        return vendorsupply;
    }
}

Test:
public class ParseVendorSupplyNunit
{

    ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();

    [Test]
    public void FromCsv_ParseCorrectly_Extradata()
    {
        string csvLineTest = "5,8,3,9,5";
        //VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
        Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
    }

A: You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:
Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));

There is also an async version if you are using async/await
Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));

A: The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.
Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.
Defining an Action avoids this problem because it specifies a method call that won't be made immediately.
However, a more colloquial way to specify this in NUnit is by using a lambda directly...
Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);

A: Wrap method you are testing into an Action
Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
Assert.That(parseFromCsv, Throws.ArgumentException)

And when testing for common exceptions, such as ArgumentException, always test for exception message as well.
Because common exception can occur in some other places and test will pass for a wrong reason.
I prefer to use FluentAssertions, which I found little bid more readable.
Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");


Q: Count number of records in lmdb databse with python I open a lmdb database using this code:
    lmdb_env = lmdb.open(source_path, readonly=True)

How can I count the number of records in this database?

A: I think it should be like this:
lmdb_env = lmdb.open(lmdb_file_name, readonly=True)
print lmdb_env.stat()

Then it prints the directory that Jaco pasted here.

A:     env = lmdb.open('db file path', max_dbs = ' > 0')
    with env.begin() as tx:
        db = env.open_db(b'db name', txn=tx)
        print(env.stat())
        print(tx.stat(db)) # this gives stats about one specific db

env.stat() gives entries of the main database. tx.stat(db) gives entries of one named database.

A: You can use event.stat(). It will return the following dictionary with entries detailing the number of records in this database:
{'branch_pages': 1040L,
'depth': 4L,
 'entries': 3761848L,
 'leaf_pages': 73658L,
 'overflow_pages': 0L,
 'psize': 4096L}

A: I found a simple solution using for loop. Here it is:
count = 0
for key, value in lmdb_env.cursor():
        count = count + 1

However, I think there should be a better way using pre-defined function.


Q: Encontrar numero faltante en el array Tengo que encontrar que números del 1 al 10 faltan en el array llamado _valores, hice otro array para comparar, pero no logro hacer que diga cuales faltan.
public static void main(String[] args) {

    int [] _valores = {5, 8, 4, 6, 2, 9};

    int [] _total = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int numerosfaltantes = 0;

    for (int i = 0; i < _valores.length; i++) {

        numerosfaltantes = _valores[i];

        for (int j = 0; j < _total.length; j++) {

            if (numerosfaltantes != _total[j] ) {

                numerosfaltantes = _valores[i];

                System.out.println(""+numerosfaltantes);
            }
        }
    }
}

A: Te dejo una solución espero que te sirva!
public class NumerosFaltantes {

    public static int [] domain = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public static void printNumerosFaltantes(int[] values) {
        for (int i = 0; i < domain.length; i++) {
            boolean isNumeroFaltante = true;

            for (int j = 0; j < values.length; j++) {
                if (values[j] == domain[i]) {
                    isNumeroFaltante = false;
                }
            }

            if (isNumeroFaltante) {
                System.out.println("Falta el número " + domain[i]);
            }
        }
    }

    public static void main(String[] args) {
        // TODO code application logic here
        int[] values = {5, 8, 4, 6, 2, 9};
        NumerosFaltantes.printNumerosFaltantes(values);
    }
}

Debes recorrer todo el dominio de valores contra el array a buscar los numeros faltantes. Es decir, cada valor posible entre 1 y 10 debes buscarlo en tu array _valores por lo tanto los for deben ser al reves. la variable booleana isNumeroFaltante asume que el numero no se encuentra en el array y en caso de encontrarlo setea el valor en falso. Cuando se termina de recorrer el array de valores si no se encontro el numero se imprime el numero faltante.
Espero que se entienda y que te sirva.
Saludos!


Q: Why am I getting Interceptor attempted to ‘Proceed’ for a method without a target error? In my case I have main project and test project. I was getting proper results on the test project where I have only one Installer class and register everything in one place. In my main project I had several installers (one for service, one for interceptors, one for common libraries, one for data persistence). For the main project I was getting the error specified:
This is a DynamicProxy2 error: the interceptor attempted to ‘Proceed’ for a method without a target, for example, an interface method or an abstract method
I was struggling to find out what was wrong. I plugged into my constructor that accepts interface of a data persistence layer and saw that it only receives a proxy object.

A: Also, see here: Manually Loading the Factory Extension into the Ninject Kernel
Under some circumstances it may be necessary to manually load the extension. The solution in my case was to add the following code during kernel construction:
if (!kernel.HasModule("Ninject.Extensions.Factory.FuncModule"))
{
    kernel.Load(new FuncModule());
}

A: Why this was happening is specified here: http://kozmic.net/2009/03/20/castle-dynamic-proxy-tutorial-part-viii-interface-proxy-without-target/
Krzysztof explains that you Castle can resolve even an interface, and Windsor will create a class for you. However if you want to use an interceptor and call a invocation.Proceed() method you need to specify what happens inside that method (for ex. using lambda expression)
Solution:
In my case solution was to put all installers into one, except of the interceptor installer. That one could stay alone, and eveything was fine.

A: If you have this problem by Update method so change it like this :
 var myObj = _dbContext.Set<T>().Find(entity.Id);
 _dbContext.Entry(myObj).CurrentValues.SetValues(entity);
_dbContext.SaveChanges();


Q: Generic class factory or method of hierarchy objects I have hierarchy  class and generic class:
       public class Form
       {
           public string Name { get; set; }
           public string Producer { get; set; }
       }

       public class Book : Form
       {
           public string Topic { get; set; }
           public string Autor { get; set; }
       }

       public class Copybook : Form
       {
           public string Topic { get; set; }
           public int CountPages { get; set; }
       }

       public class Notebook : Form
       {
           public int Cost { get; set; }
       }

       public class Request<T> where T : Form
       {
           public T Form { get; set; }
       }

I want to make factory or method, which will create objects of generic class in depend of logic and params. How it make? I tried to do this, but the code did not work:
        public enum FormParams
        {
            Book,
            Copybook,
            Notebook
        }

        public static class RequestFactory
        {
            public static Request<Form> Create(FormParams formParams)
            {
                if (formParams == FormParams.Book)
                {
                    return new Request<Book>();
                }

                if (formParams == FormParams.Copybook)
                {
                    return new Request<Copybook>();
                }

                return new Request<Notebook>();
            }
        }

A: If you think carefully, what you're asking for doesn't really make sense. What if you did this?
var request = RequestFactory.Create(FormParams.CopyBook);
request.Form = new Book();

If the underlying type of request was Request<CopyBook>, then its Form property would have the type of CopyBook, and trying to set its value to a Book wouldn't make sense.
If you determine that the above use-case should never happen, you can formalize that fact by using an interface that doesn't allow the Form property to be set. Then you can make that interface covariant.
public class Request<T> : IRequest<T>
    where T : Form
{
    public T Form { get; set; }
}

public interface IRequest<out T> where T : Form
{
    T Form { get; }
}

...
    public static IRequest<Form> Create(FormParams formParams)

But in that case you may find there's no reason to have IRequest be generic at all.
public class Request<T> : IRequest
    where T : Form
{
    public T Form { get; set; }

    Form IRequest.Form => this.Form;
}

public interface IRequest
{
    Form Form { get; }
}

...
    public static IRequest Create(FormParams formParams)

A: You need to add an Interface to your hierarchy so you can flag the generic parameter as covariant.
public class Request<T> : IRequest<T> where T : Form
{
    public T Form { get; set; }
}

public interface IRequest<out T>
{
    public T Form
    {
        get;
    }
}

And then you need to change the return type of your Create method to an IRequest<Form>.
public static class RequestFactory
{
    public static IRequest<Form> Create(FormParams formParams)
    {

        if (formParams == FormParams.Book)
        {
            return new Request<Book>();
        }

        if (formParams == FormParams.Copybook)
        {
            return new Request<Copybook>();
        }

        return new Request<Notebook>();
    }
}