text:
Q: scrollTop not working automatically I know there are a couple of questions to scrollTop already out there but I haven't really seen anything resembling my problem.
Using jquery 1.7.2 on an IE9 we have a page with three Tabs (JqueryUI).
The Data is connected and that resulted in us only having the current tab on the page. Changing tabs will remove the unseen one and reload the one we jump into.
The Scroll-Positions are stored correctly in variables on the base page but trying to set that position in the document-ready-function does not work.
An alert shows the correct number, so the function is actually called but the scrollbar does not move.
Calling the same function with a button on the page afterwards however works perfectly.
The document-ready-function on the tab's jsp is quite simple:
<script type="text/javascript">
jQuery(document).ready(function(){
    setAhaScrollbar();
});

</script>

and the called function is quite simple as well:
function setAhaScrollbar() {
    var scrollWert = $('#scrollbarAnhaengeartikel').val();
    alert(scrollWert);
    $('#anhaengeGridScrollable').scrollTop(scrollWert);
}

Called from document-ready it does nothing. Called from a button later on it works fine.
The div where the scroll position is supposed to be set is defined with overflow: auto and a fixed height

A:
crollTop( value )
  Description: Set the current vertical position of the scroll bar for each of the set of matched elements.
  .scrollTop( value )
  value
  Type: Number
  An integer indicating the new position to set the scroll bar to.

More Information
As the documentationsaid value should be number.
Try
var scrollWert = Number($('#scrollbarAnhaengeartikel').val());

or
var scrollWert = parseInt($('#scrollbarAnhaengeartikel').val());

A: Apparently it was primarily a timing problem. Maybe there were still things going on when document ready fired.
Changing that function to
jQuery(document).ready(function(){
    setTimeout("setAhaScrollbar()", 500);
});

did the trick so my problem is solved.


text:
Q: How to extract a specific element from EXIF photographic metadata? It's now possible to import photographs into Mathematica and import the EXIF data at the same time:
i = Import["ExampleData/coneflower.jpg", "ImageWithExif"]

You can now look at all the metadata:
Options[i, MetaInformation]

{MetaInformation -> {"Exif" -> {"ImageDescription" -> "          ",
      "Make" -> "NIKON", "Model" -> "E950", "Orientation" -> 1,
      "XResolution" -> 300, "YResolution" -> 300,
       "ResolutionUnit" -> 2,
       "Software" -> "Adobe Photoshop CS3 Macintosh",
       "DateTime" -> "2008:08:19 11:29:05", etc...

So how would I extract - say - the exposure time ("ExposureTime")? I was trying something like this:
"ExposureTime" /. Options[i, MetaInformation] ...

but I don't know enough about the structure of the stored metainformation. Can you do this without knowing that structure?

A: Here is something based on FilterRules and using your post of Exif metadata format.
FilterRules
FilterRules["Exif" /. (MetaInformation /. Options[i, MetaInformation]), "XResolution"]

{"XResolution" -> 300}

There may be more elegant ways to extract the rules which form part of MetaInformation, I await them with interest.
This unpacks nested sets of rules:
FilterRules[ Options[i, MetaInformation] //. {_ -> z_} -> z, "XResolution"]

{"XResolution" -> 300}

OptionValue
Here is an interesting alternative which does require some knowledge of the structure of the MetaInformation but is otherwise nicely concise.
OptionValue[Options[i, MetaInformation], MetaInformation -> "Exif" -> "XResolution"]

300

A: Does this do want you want?
Cases[Options[i, MetaInformation],
 HoldPattern["ExposureTime" -> ___], Infinity]

or even simpler because it is Rules all the way down:
Cases[Options[i], HoldPattern["ExposureTime" -> ___], Infinity]

{"ExposureTime" -> 1/65}

All-in-one:
With[{wanted = "ExposureTime"},
  wanted /. Cases[Options[i], HoldPattern[wanted -> ___], Infinity]] //
  N

A: The earlier answers stopped working for Mathematica 11+. In Mathematica 10 and earlier, the MetaInformation was a nested list of rules:
$VersionNumber
i = Import["ExampleData/coneflower.jpg","ImageWithExif"];
Options[i, MetaInformation] //Short

10.3
{MetaInformation->{Exif->{ImageDescription->          ,<<37>>,SceneType->1}}}

In Mathematica 11+, the MetaInformation is now an Association. This means that the previous approaches no longer work:
$VersionNumber
 i = Import["ExampleData/coneflower.jpg","ImageWithExif"];
 Quiet @ Check[
  OptionValue[Options[i], MetaInformation -> "Exif" -> "ExposureTime"],
  $Failed
]

Cases[Options[i], HoldPattern["ExposureTime" -> ___], Infinity]

11.3
$Failed
{}

Instead, you will need to extract information from an association. If you don't know the structure of the association you can use Keys to investigate:
meta = OptionValue[Options[i], MetaInformation];
meta //Keys

{"Exif"}

Then:
meta["Exif"] //Keys

{"Make", "Model", "Orientation", "XResolution", "YResolution",
  "ResolutionUnit", "Software", "DateTime", "YCbCrPositioning", "ExposureTime", "FNumber", "ExposureProgram", "ISOSpeedRatings", "ExifVersion",
  "DateTimeOriginal", "DateTimeDigitized", "ComponentsConfiguration",
  "CompressedBitsPerPixel", "ExposureBiasValue", "MaxApertureValue",
  "MeteringMode", "LightSource", "FlashInfo", "FocalLength", "FlashpixVersion",
  "ColorSpace", "PixelXDimension", "PixelYDimension", "InteroperabilityIndex",
  "InteroperabilityVersion", "FileSource", "SceneType"}

Now we see "ExposureTime". So:
meta["Exif", "ExposureTime"]

Quantity[1/65, "Seconds"]

A: Just a note that Mathematica has since made the importing of Exif metadata easier:
Import["ExampleData/coneflower.jpg", "ExposureTime"]

Quantity[Rational[1,65],"Seconds"]

(This displays nicely as 1/65 s in the front-end.)
This is a bit confusing because "ExposureTime" isn't listed in the list of possible things to import:
Import["ExampleData/coneflower.jpg","Elements"]

{BitDepth, CameraTopOrientation, Channels, ColorMap, ColorProfileData, ColorSpace, Data, DateTime, Exif, FlashUsed, GeoPosition, GPSDateTime, Graphics, Image, ImageSize, IPTC, RawData, RawExif, RawIPTC, RawXMP, RedEyeCorrection, Summary, Thumbnail, XMP}

However, in the docs for JPEG, under "Scope", it says that any Exif tags can be directly imported.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count characters in two specific lines in all files and printing the sum with corresponding filename Following is the case: there are multiple *.txt files each containing below lines with different values of var or lab.
For example:
abc.txt:
var^ABCDEFG
lab^ABCDEFGH

def.txt:
var^ABCDEFGHI
lab^ABCDEFGHIJ

I need a command or script which will print sum of number of characters in (var^ or lab^) for each .txt file.
Sample output:
abc.txt: Total Characters in (Var and Lab) are 15.        (counting character after the caret ^ sign)
def.txt: Total Characters in (Var and Lab) are 19.

A: Something like this should work:
for file in *.txt; do \
  echo -n "$file: Total Characters in (Var and Lab) are ";
  cut -d "^" -f 2 < $file | tr -d '\n' | wc -c;
done

Output:
abc.txt: Total Characters in (Var and Lab) are 15
def.txt: Total Characters in (Var and Lab) are 15

A: You could do it like this with GNU awk:
gawk -F^ '
  BEGINFILE{count=0}
  $1 == "var" || $1 == "lab" {count += length($2)}
  ENDFILE{printf("%s: Total Characters in (Var and Lab) are %d\n", FILENAME, count)}
' ???.txt
abc.txt: Total Characters in (Var and Lab) are 15
def.txt: Total Characters in (Var and Lab) are 19

A: Expanding @steeldriver's answer to other awk implementations without BEGINFILE and ENDFILE makes it a bit messier, but portable:
awk -F'^' 'FNR==1{if (NR>FNR) printf("%s : Total characters in (Var) and (Lab) are %d\n",lastfile,sum); sum=0; lastfile=FILENAME} \
 NF==2 && ($1=="var" || $1=="lab") {sum+=length($2)} \
 END{printf "%s: Total characters in (Var) and (Lab) are %d\n", FILENAME, sum}' abc.txt def.txt

To explain:

*

*At beginning of file, (i.e. FNR, the per-file-line counter, is 1), we store the filename in a temporary variable lastfile and set the counter variable to 0.

*If this is not the first file (i.e. NR, the global line-counter, is larger than FNR), we output the statistics from the previous file.

*Since this rule would not catch the last file on awk's argument list, we have to replicate the logic also in the global END block.

A: Python
#!/usr/bin/python
import re
import sys
co=0
k=open(sys.argv[1],'r')
t=re.compile(r'var\^|lab\^')
for i in k:
    m=re.sub(t,"",i)
    co=co+len(m.strip())
print "{0}: Total Characters in (Var and Lab) are {1}".format(sys.argv[1],co)

$ python test.py abc.txt
abc.txt: Total Characters in (Var and Lab) are 15

$ python test.py def.txt
def.txt: Total Characters in (Var and Lab) are 19

Awk method
    #!/bin/bash
    awk -F "var|lab" 'BEGIN{sum=0}{gsub(/\^/,"",$2)}{sum=sum+length($2)}END{print FILENAME ": Total Characters in (Var and Lab) are "sum}' $1

 sh test.sh abc.txt
abc.txt: Total Characters in (Var and Lab) are 15

sh tes.sh def.txt
def.txt: Total Characters in (Var and Lab) are 19

A: Using grep and wc:
for i in *.txt; do
  printf '%s: Total Characters in (Var and Lab) are %d.\n'\
    "$i"\
    "$(( $(grep -E '^(var|lab)' "$i" | wc -c) - 10 ))"
done


text:
Q: How to prove that $\sum_{i,j,k,l=1}^n a^{ij} a^{kl} v_{x_i x_k} v_{x_j x_l} \geq \theta^2|D^2v|^2$?
This problem is taken from Partial Differential Equations (Evans) $\S$6.4.3.

Consider the operator
$$Lu = -\sum_{i,j=1}^n a^{ij}u_{x_ix_j} +\sum_{i=1}^n b^i u_{x_i} + cu \quad\text{in }\Omega,$$
where $\Omega\subset\mathbb{R}^n$ is a bounded open set, $(a^{ij})$ is uniformly elliptic, i.e., there exists some $\theta>0$ such that
$$\sum_{i,j=1}^n a^{ij}(x)\xi_i\xi_j\geq \theta|\xi|^2$$
for any $x\in\Omega$ and $\xi\in\mathbb{R}^n$.
Given a smooth function $v$. How to prove that
$$\sum_{i,j,k,l=1}^n a^{ij} a^{kl} v_{x_i x_k} v_{x_j x_l} \geq \theta^2|D^2v|^2.$$

A: Here is a solution, I think it's right.
Use the method as in Page 347. Fix any $x_0\in \Omega$. Since the matrix $A=(a^{ij}(x_0))$
is symmetric and positive definite, there exists an orthogonal matrix
$O=(o_{ij})$ such that
$$OAO^T = \mathrm{diag}(\lambda_1, \ldots, \lambda_n),$$
with $\lambda_i\geq \theta$ for $i=1,\ldots,n$. Write $y = x_0 + O(x-x_0)$, then
$$u_{x_ix_j} = \sum_{k,l=1}^n u_{y_ky_l} o_{ki} o_{lj}.$$
Therefore
$$\begin{align*}
  \bigstar:
  & =\sum_{i,j,k,l=1}^n a^{ij} a^{kl} v_{x_ix_k} v_{x_jx_l} \\
  & = \sum_{i,j,k,l=1}^n a^{ij} a^{kl}
      \biggl(\sum_{r,s=1}^n v_{y_ry_s} o_{ri} o_{sk}\biggr)
      \biggl(\sum_{p,q=1}^n v_{y_py_q} o_{pj} o_{ql}\biggr) \\
  & = \sum_{i,j,k,l,r,s,p,q=1}^n a^{ij} a^{kl} o_{ri} o_{sk} o_{pj} o_{ql}
      v_{y_ry_s} v_{y_py_q}.
\end{align*}$$
Note that
$$\sum_{i,j=1}^n a^{ij} o_{ri} o_{pj} = \delta_{rp} \lambda_r,$$
and
$$\sum_{k,l=1}^n a^{kl} o_{sk} o_{ql} = \delta_{sq} \lambda_s.$$
Hence
$$\begin{align*}
\bigstar
& = \sum \delta_{rp} \lambda_r \delta_{sq} \lambda_s v_{y_ry_s} v_{y_py_q} \\
& = \sum_{p,q=1}^n \lambda_p \lambda_q v_{y_py_q}^2 \\
& \geq \theta^2 |D^2 v|^2.
  \end{align*}$$


text:
Q: Does anyone know the default font for Python IDLE on Macs? I've searched everywhere for the default font for the Python IDLE app when it was first downloaded. I changed it to Courier New because it was the default Windows font but then I can't remember what the original font was.

A: It is always  Courier New but I'm using Jetbrain Mono NL. I highly recommended that or Monaco.


text:
Q: Gui simulation for smart home application im looking for suggestion in which GUI tool is most appropriate for me to use in implementing my study. im using java language. i would like the graphics to simulate a house in which graphical changes apply without user inputs from mouse or keyboards. my user input is in the form of sms. thanks in advance guys. im hoping to animate it or simulate a smart home through the conditions i had set in my program. thnaks!

A: Your questions is very underspecified. I will assume that you are at the early stages of producing a hand-rolled home automation programs, you probably need:

*

*an environment to let you test the core logic of the system (i.e. "If the system is in state X and I issue command Y, what does it actually do, and will I lose the contents of my freezer?")

*an environment to let you test the SMS communications module

*you may need a demo mode to show prospecitve customers what it does (this is my best guess at what is being requested here)

Now (3) could fill in for (1), but is a lot more programming effort, so from the start you probably want a simple text interface to do (1).
In general, you almost certainly want a modular system: a core logic system supported by at least two input models (SMS and keyboard), three output models (text debug, graphical demo, and control-line/wireless signals for the actual hardware), and various ancillary stuff (configuration reading, saved state handling). Come to think of it, since you probably need a way to probe the current state of the system, you should make the saved state and condition probe code share a single framework as well.


text:
Q: Why is my program slow when looping over exactly 8192 elements? Here is the extract from the program in question. The matrix img[][] has the size SIZE×SIZE, and is initialized at:
img[j][i] = 2 * j + i
Then, you make a matrix res[][], and each field in here is made to be the average of the 9 fields around it in the img matrix. The border is left at 0 for simplicity.
for(i=1;i<SIZE-1;i++)
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        for(k=-1;k<2;k++)
            for(l=-1;l<2;l++)
                res[j][i] += img[j+l][i+k];
        res[j][i] /= 9;
}

That's all there's to the program. For completeness' sake, here is what comes before. No code comes after. As you can see, it's just initialization.
#define SIZE 8192
float img[SIZE][SIZE]; // input image
float res[SIZE][SIZE]; //result of mean filter
int i,j,k,l;
for(i=0;i<SIZE;i++)
    for(j=0;j<SIZE;j++)
        img[j][i] = (2*j+i)%8196;

Basically, this program is slow when SIZE is a multiple of 2048, e.g. the execution times:
SIZE = 8191: 3.44 secs
SIZE = 8192: 7.20 secs
SIZE = 8193: 3.18 secs

The compiler is GCC.
From what I know, this is because of memory management, but I don't really know too much about that subject, which is why I'm asking here.
Also how to fix this would be nice, but if someone could explain these execution times I'd already be happy enough.
I already know of malloc/free, but the problem is not amount of memory used, it's merely execution time, so I don't know how that would help.

A: The following tests have been done with Visual C++ compiler as it is used by the default Qt Creator install (I guess with no optimization flag). When using GCC, there is no big difference between Mystical's version and my "optimized" code. So the conclusion is that compiler optimizations take care off micro optimization better than humans (me at last). I leave the rest of my answer for reference.

It's not efficient to process images this way. It's better to use single dimension arrays. Processing all pixels is the done in one loop. Random access to points could be done using:
pointer + (x + y*width)*(sizeOfOnePixel)

In this particular case, it's better to compute and cache the sum of three pixels groups horizontally because they are used three times each.
I've done some tests and I think it's worth sharing. Each result is an average of five tests.
Original code by user1615209:
8193: 4392 ms
8192: 9570 ms

Mystical's version:
8193: 2393 ms
8192: 2190 ms

Two pass using a 1D array: first pass for horizontal sums, second for vertical sum and average.
Two pass addressing with three pointers and only increments like this:
imgPointer1 = &avg1[0][0];
imgPointer2 = &avg1[0][SIZE];
imgPointer3 = &avg1[0][SIZE+SIZE];

for(i=SIZE;i<totalSize-SIZE;i++){
    resPointer[i]=(*(imgPointer1++)+*(imgPointer2++)+*(imgPointer3++))/9;
}

8193: 938 ms
8192: 974 ms

Two pass using a 1D array and addressing like this:
for(i=SIZE;i<totalSize-SIZE;i++){
    resPointer[i]=(hsumPointer[i-SIZE]+hsumPointer[i]+hsumPointer[i+SIZE])/9;
}

8193: 932 ms
8192: 925 ms

One pass caching horizontal sums just one row ahead so they stay in cache:
// Horizontal sums for the first two lines
for(i=1;i<SIZE*2;i++){
    hsumPointer[i]=imgPointer[i-1]+imgPointer[i]+imgPointer[i+1];
}
// Rest of the computation
for(;i<totalSize;i++){
    // Compute horizontal sum for next line
    hsumPointer[i]=imgPointer[i-1]+imgPointer[i]+imgPointer[i+1];
    // Final result
    resPointer[i-SIZE]=(hsumPointer[i-SIZE-SIZE]+hsumPointer[i-SIZE]+hsumPointer[i])/9;
}

8193: 599 ms
8192: 652 ms

Conclusion:

*

*No benefits of using several pointers and just increments (I thought it would have been faster)

*Caching horizontal sums is better than computing them several time.

*Two pass is not three times faster, two times only.

*It's possible to achieve 3.6 times faster using both a single pass and caching an intermediary result

I'm sure it's possible to do much better.
NOTE
Please, note that I wrote this answer to target general performance issues rather than the cache problem explained in Mystical's excellent answer. At the beginning it was just pseudo code. I was asked to do tests in the comments... Here is a completely refactored version with tests.

A: The difference is caused by the same super-alignment issue from the following related questions:

*

*Why is transposing a matrix of 512x512 much slower than transposing a matrix of 513x513?

*Matrix multiplication: Small difference in matrix size, large difference in timings
But that's only because there's one other problem with the code.
Starting from the original loop:
for(i=1;i<SIZE-1;i++)
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        for(k=-1;k<2;k++)
            for(l=-1;l<2;l++)
                res[j][i] += img[j+l][i+k];
        res[j][i] /= 9;
}

First notice that the two inner loops are trivial. They can be unrolled as follows:
for(i=1;i<SIZE-1;i++) {
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

So that leaves the two outer-loops that we're interested in.
Now we can see the problem is the same in this question: Why does the order of the loops affect performance when iterating over a 2D array?
You are iterating the matrix column-wise instead of row-wise.

To solve this problem, you should interchange the two loops.
for(j=1;j<SIZE-1;j++) {
    for(i=1;i<SIZE-1;i++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

This eliminates all the non-sequential access completely so you no longer get random slow-downs on large powers-of-two.

Core i7 920 @ 3.5 GHz
Original code:
8191: 1.499 seconds
8192: 2.122 seconds
8193: 1.582 seconds

Interchanged Outer-Loops:
8191: 0.376 seconds
8192: 0.357 seconds
8193: 0.351 seconds


text:
Q: "Factory Method is a specialization of Template Method". How? Similarities and differences between the two:
Template Method

*

*Relies on inheritance.

*Defines the steps of an algorithm, and leaves the task of implementing them to subclasses.

Factory Method

*

*Relies on inheritance.

*A superclass defines an interface to create an object. Subclasses decide which concrete class to instantiate.

The two side by side:

I'm not sure what the phrase "Factory Method is a specialization of Template Method" means (it's in the Head First Design Patterns book). In Beverage we have the method prepare which is final and defines a series of steps. In PizzaStore we have a method which is abstract, and subclasses redefine it. How is the latter a specialization of the former?

A: In Beverage we have the ("template") method prepare which calls some abstract methods like boilWater, brew etc. which are implemented in the subclasses. It is not essentially for the pattern to have the template method located in the base class, it could be anywhere else, assumed the abstract methods are public. But it is essentially that there are the abstract methods which must be overriden and will fill the gaps in the "algorithm template".
The factory method is also about a class where abstract methods are overwritten, a core point is the caller of that method does not need to know the exact type of the created object. Note that in PizzaStore, the abstract method createPizza must be called somewhere from - lets say a method createLotsOfPizza.
This makes the latter a template method, where the specific steps of the "algorithm to create pizzas" are the gaps to be filled. Now it is probably just an imprecise use of words by saying "the factory method pattern" is a special case of the "template method" pattern. Especially the "factory methods" are not "template methods", however they might be called from a template method. So to be more precise, we might say

"the factory method pattern is typically used in conjunction with a special case of the template method pattern"

and I guess that is what the authors of that book wanted to express.

A: I think "Factory Method is a specialization of Template Method" is a mis-characterization.  I believe that it would be more accurate to say that the Template Method pattern is merely a variation on the Factory Method pattern.
Further, I claim that the Template Method pattern isn't really a pattern at all (in the Gang of Four sense), since it arises naturally through inheritance and method overriding.  You can see that, in the diagram above for the Template Pattern, the descendant classes merely override methods in the base class with their own behavior.
On the whole, Software Patterns (of the Gang of Four variety) are really just workarounds for deficiencies in programming languages, and the Template Pattern only restates what object-oriented languages are already natively capable of.

A: I would say Head First is simply wrong in this characterization.
Wikipedia defines Template Method as:

In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses.

(It references GoF for that.)
And Factory Method is defined as:

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.

There is no overlap between the two, except that in C++, inheritance is a key part of both. However, in languages that make a distinction between implementation inheritance (extends in Java) and interface implementation (implements in Java), even this commonality doesn't exist, since interface implementation is sufficient for factory method, but not template method. And in C++, pure implementation inheritance (without the interface inheritance, i.e. private inheritance or CRTP) can be used for the former, but not for the latter.
And aside from that? One is a behavioral design pattern, the other a creational pattern. One describes an outline of an operation, with some key parts left out to be filled in by specialized subclasses; the other specifies a very simple contract, leaving the entire implementation to the concrete instances. They are completely distinct.
In my opinion, the line as quoted is simply wrong. Either it is a glaring error in the book, or (less likely) it is out of context and should be interpreted differently.

A: "In my opinion, the line as quoted is simply wrong. " >> I cannot agree the GoF probably talked about similarities:

*

*In template method the methods called inside the body are implemented in subclasses. In factory method implementation is provided in subclass.
So if brew() had returned an object it would be also a factory method.
Most likely PizzaStore::createPizza will be called from the some template method when handling the order.

An argument about extends/implements is totally irrelevant as someone mentioned design patterns are concepts not linked to any language syntax. esp. in JAVA where there is a 'default' method in interface so you can achieve it also using interface.
So it depends on the view if someone is biased to see just some minor differences.
But if you are keen to find the common features then yes both patterns defer implementation to the subclass. In first case it is a step's implementation, in second case it is the implementation of and object. Both implementations are then used in super classes.


text:
Q: Very peculiar - submit once the first time, twice the 2nd time, trice the 3rd time .. and so on .. what I did wrong? Working with a modal form that submits edited information via ajax post. The thing is, it submitted once the first time .. fire up the modal form again, then submit, and twice it goes and so on and so forth. Does anyone had this sort of experience before? Please help.
$("#editInfo").click(function () {
    valform = ["realname","email"];
    valneed = 2;
    $('#smallModal .modal-body').empty();
    $('#smallModal .modal-body').load('/profile.php?action=profile_edit_info');
    $('#smallModal .modal-title').text('Edit Personal Information');
    $('#smallModal').modal('show')

    $('#smallModal').on('shown.bs.modal', function () {
        $("#smallModal #profileeditinfoform").keydown(function(event){
        if(event.keyCode == 13 && event.target.nodeName!='TEXTAREA')
            {
                event.preventDefault();
                return false;
            }
        });

        $("#realname_comment").hide();
        $("#email_comment").hide();

        $('#realname').bind("change", function() {
            $('#realname').addClass("spinner");
            var v_realname = verifyVar($('#realname').val(),'name');
            displayVerify(v_realname,'realname');
        });

        $('#email').bind("change", function() {
            $('#email').addClass("spinner");
            var v_email = verifyVar($('#email').val(),'email');
            displayVerify(v_email,'email');
        });

        $("#editinfo_submit_btn").click(function(event) {
            event.preventDefault();
            $('#loader').fadeIn();

            formData = $("#profileeditinfoform").serialize();
            var v_submit = submitEditInfo(formData);
            verifySubmitEditInfo(v_submit);

            $('#loader').fadeOut();
        });
    });
});

function submitEditInfo(data) {
    var alldata = data + '&action=profileeditinfo';
    return $.ajax({
        type: 'POST',
        cache: false,
        data: alldata,
        url: '/ajax/submit.php'
    });
}

function verifySubmitEditInfo(ajaxCall) {
        ajaxCall.success(function(realData) {
                response = JSON.parse(realData)
                if (!response.success) {
                    $.gritter.add({
                        title: response.title,
                        image: '/img/custom/fail.png',
                        sticky: false,
                        text: response.message
                    });
                } else {
                    valform = [];
                    $("#submitdiv").hide();
                    $("#profileeditinfoform").find("input:text").val('');
                    $('#infodiv').slideUp(200).load('/divloader.php?req=profile_info').slideDown(200);
                    $.gritter.add({
                        title: response.title,
                        image: '/img/custom/success.png',
                        sticky: false,
                        text: response.message
                    });
                    $("#smallModal").modal('hide');
                }
        });
}

A: Every time you click, you're adding a new event handler:
$('#smallModal').on('shown.bs.modal' //...

Are you sure you want to do this on "click", or might it be better to set this up outside of the click handler?
In fact, you're binding event handlers as a response to other events all over this code. That's probably not a great idea, unless you unbind them once you're done.

A: You need to pull out your binders, you bind a new time every time the button  is clicked! Only bind on load, not under button click event.


text:
Q: How can I pass a preprocessor to TfidfVectorizer? - sklearn - python How can I pass a preprocessor to TfidfVectorizer?
I made a function that takes a string and returns a preprocessed string
then I set processor parameter to that function "preprocessor=preprocess", but it doesn't work.
I've searched so many times, but I didn't found any example as if no one use it.
I have another question.
Does it (preprocessor parameter) override removing stopwords and lowereing case that could be done using stop_words and lowercase parameters?

A: You simply define a function that takes a string as input and retuns what is to be preprocessed. So for example a trivial function to uppercase strings would look like this:
def preProcess(s):
    return s.upper()

Once you have your function made then you just pass it into your TfidfVectorizer object. For example:
from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
     'This is the first document.',
     'This is the second second document.',
     'And the third one.',
     'Is this the first document?'
     ]

X = TfidfVectorizer(preprocessor=preProcess)
X.fit(corpus)
X.get_feature_names()

Results in:
[u'AND', u'DOCUMENT', u'FIRST', u'IS', u'ONE', u'SECOND', u'THE', u'THIRD', u'THIS']

This indirectly answers your follow-up question since despite lowercase being set to true, the preprocess function to uppercase overrides it. This is also mentioned in the documentation:

preprocessor : callable or None (default) Override the preprocessing
  (string transformation) stage while preserving the tokenizing and
  n-grams generation steps.


text:
Q: Widget not changing on Tap in Flutter So I am trying to build an Instagram like image editor with all the functionality. I wanted to switch between a text field and a simple Text Widget on tapping on either of them. I found an example online but it does not work in my case.
class _StateTextFieldState extends State<StateTextField> {
  FocusNode focusNode;
  GlobalKey key = GlobalKey();
  TextEditingController controller;
  Offset offset = Offset(1, 1);
  Color textColor;
  double fontSize;
  bool highlighted;
  final ValueNotifier<Matrix4> notifier = ValueNotifier(Matrix4.identity());
  Color pickerColor = Color(0xffffffff);
  Color currentColor = Color(0xffffffff);

  void changeColor(Color color) {
    setState(() => pickerColor = color);
  }

  @override
  void initState() {
    highlighted = widget.highlighted;
    focusNode = widget.focusNode;
    focusNode.addListener(() {
      setState(() {
        highlighted = true;
      });
    });
    controller = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double fontSize = 24;
    String text = "Enter Text!";
    bool isEditing = false;
    double textWidth = MediaQuery.of(context).size.width * 0.6;
    return Container(
      key: key,
      height: MediaQuery.of(context).size.height * 0.6,
      child: MatrixGestureDetector(
          onMatrixUpdate: (Matrix4 m, Matrix4 tm, Matrix4 sm, Matrix4 rm) {
            setState(() {
              notifier.value = m;
            });
          },
          child: Transform(
            transform: notifier.value,
            child: Row(
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    border: highlighted
                        ? Border.all(color: Colors.black, width: 2)
                        : Border.all(color: Colors.transparent),
                  ),

                  // color: Colors.redAccent,
                  width: textWidth,
                  child:
                      //_editTitleTextField(controller)
                      isEditing
                          ? TextField(
                              textAlign: TextAlign.center,
                              autofocus: true,
                              onEditingComplete: () {
                                setState(() {
                                  text = controller.text;
                                  isEditing = false;
                                  focusNode.unfocus();
                                  print(isEditing);
                                  highlighted = false;
                                });
                              },
                              style: TextStyle(
                                  color: currentColor, fontSize: fontSize),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide:
                                        BorderSide(color: Colors.transparent),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.blue),
                                  ),
                                  fillColor: Colors.red,
                                  hintText: "Enter text",
                                  hintStyle: TextStyle(color: Colors.red)),
                              maxLines: 1,
                              focusNode: focusNode,
                              //  maxLength: 100,
                            )
                          : Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                  text,
                                  style: TextStyle(fontSize: 18),
                                ),
                                IconButton(
                                    icon: Icon(Icons.edit, color: Colors.white),
                                    onPressed: () {
                                      setState(() {
                                        print(widget);
                                        isEditing = true;
                                        print(isEditing);
                                      });
                                    })
                              ],
                            ),
                ),
              ],
            ),
          )
          //         ),
          ),
    );
  }

My problem is that even though isEditing changes on clicking the Iconbutton, the widget does not rebuild and remains the same. Where am I going wrong?

A: you have to move your variables from build method to class method. Currently each time you rebuild your widget ( for example by taping on a button ) your variables will be get default values
class _StateTextFieldState extends State<StateTextField> {
 ... your code...
 double fontSize = 24;
 String text = "Enter Text!";
 bool isEditing = false;

 @override
 Widget build(BuildContext context) {
   ... your code ...
  }
}

A: The problem here is that , you are using setState and functionality of setState is to rebuild the UI again by calling the build function.
@override
Widget build(BuildContext context) {
   double fontSize = 24;
   String text = "Enter Text!";
   bool isEditing = false;

   return Container(
   .. . ..
   . . .
}

So whenever you call setState ,each time this function is called and your variables are getting re-initialized , hence ,you need to make these variables as class members, instead of making them local variable of build function.
class _StateTextFieldState extends State<StateTextField> {
bool isEditing =false;
. . .
. . .
@override
Widget build(BuildContext context) {
   return Container( . . );
}

Hope this helps!


text:
Q: How to get the return code of RTP from the shell in Vxworks? In Linux, there are very convenient mechanisms for retrieving the return code of a program from the shell.  In particular, the shell provides the $? variable and the if construct.
Is there any way to also get the return codes (i.e. the return value of main) of RTPs spawned interactively from the vxworks shell?  I'd be interested in doing this from either the standard "c interpreter shell" ("->"), or the RTP command shell.

A: As far as I know it's not possible to grab the return value (from kernel space, which is where CMD shell and C shell live) of an RTP. You can obviously achieve what you want with kernel tasks, but that entails first getting your symbols into the kernel either directly, or by a DKM (downloadable kernel module).


text:
Q: Possible to access an AWS public dataset using Cyberduck? Cyberduck version: Version 7.9.2
Cyberduck is designed to access non-public AWS buckets. It asks for:

*

*Server

*Port

*Access Key ID

*Secret Access Key

The Registry of Open Data on AWS provides this information for an open dataset (using the example at https://registry.opendata.aws/target/):

*

*Resource type: S3 Bucket

*Amazon Resource Name (ARN): arn:aws:s3:::gdc-target-phs000218-2-open

*AWS Region: us-east-1

*AWS CLI Access (No AWS account required): aws s3 ls s3://gdc-target-phs000218-2-open/ --no-sign-request

Is there a version of s3://gdc-target-phs000218-2-open that can be used in Cyberduck to connect to the data?

A: If the bucket is public, any AWS credentials will suffice. So as long as you can create an AWS account, you only need to create an IAM user for yourself with programmatic access, and you are all set.
No doubt, it's a pain because creating an AWS account needs your credit (or debit) card! But see https://stackoverflow.com/a/44825406/1094109 and https://stackoverflow.com/a/44825406/1094109
I tried this with s3://gdc-target-phs000218-2-open and it worked:

For RODA buckets that provide public access to specific prefixes, you'd need to edit the path to suit. E.g. s3://cellpainting-gallery/cpg0000-jump-pilot/source_4/ (this is a RODA bucket maintained by us, yet to be released fully)
NOTE: The screenshots below show a different URL that's no longer operational. The correct URL is s3://cellpainting-gallery/cpg0000-jump-pilot/source_4/

A: No, it's explicitly stated in the documentation that

You must obtain the login credentials [in order to connect to Amazon S3 in Cyberduck]


text:
Q: How strong can tidal forces get? I am imagining a planet the size of Earth being in close proximity to something of high mass such as a gas giant or a star, but ultimately I'd be more interested in how to figure this out myself.
So (as it states in the title), I am trying to find out how strong, realistically tidal forces could be, before a planet is destroyed.
One way of stating this question would be: ignoring other factors, how close could the earth get to the sun before it would be destroyed by tidal forces? Would the tidal forces be strong enough to be noticed directly by anything on the surface?
I am honestly not sure which quantities are relevant. Is the important quantity the yield strength of rock? Or does the molten core make this slightly irrelevant?
My other guess would be that it has something to do with the gravitational binding energy. It seems like if the tidal potential energy was on the order of the gravitational binding energy, then bad things would happen, but that seems rather subjective. I guess it depends on what I mean by destroyed, but at least that is an upper bound though, right?


text:
Q: Can I make Ubuntu 18.04 switch between multiple windows of the program by just clicking the icon? I just want a Windows 7 behavior where clinking the icon cycles through all the windows. I know about Alt+` (Tilde) and Alt+Tab clicking the icon is just more intuitive.

A: If you mean Enabling Click to Minimize (minimize the window when clicking on the icon) as shown in the gif photo:

It is simple, you can do that by running the following command in your terminal:
gsettings set org.gnome.shell.extensions.dash-to-dock click-action 'minimize'

If you do not like 'click to minimize' behavior, you can set it back to default using the command below:
gsettings reset org.gnome.shell.extensions.dash-to-dock click-action

A: You can do
gsettings set org.gnome.shell.extensions.dash-to-dock click-action 'cycle-windows'

A: I know the question is tagged ubuntu-dock* but if you are using the Dash to Panel extension you can find a similar setting in Tweaks > Extensions > Dash to panel > Behaviour > Click Action > Set to Cycle through windows.
* the title is broad and Google may pick this up as a search

A: Install dconf-editor by
sudo apt install dconf-editor

Goto /org/gnome/shell/extensions/dash-to-dock and change click-action to cycle-windows


text:
Q: How do you check if a DateTime is Midsummer eve- or day in C#? How do you check if a DateTime is Midsummer eve- or day in C#? I'm working on a solution in C# for creating schedulings. It has to check if a DateTime is Midsummer eve- or day in Sweden. Do I have to hard code it in a table? Do I have to implement my own function for this? What is the formula in that case?
Thanks.

A:
It has to check if a DateTime is Midsummer eve- or day in Sweden

In Sweden the Midsummer's day is a Saturday between June 20 and June 26:
public static bool IsSwedishMidsummerDay(DateTime dt)
{
    return dt.DayOfWeek == DayOfWeek.Saturday
        && dt.Month == 6 && dt.Day >= 20 && dt.Day <= 26);
}

Here you find a list of midsummer-dates which show that the rule applies.


text:
Q: How to get the Path of my export-csv file powershell I want get the Path of my exported CSV file and store it in a variable.
Here's my PowerShell code:
Get-ADUser -identity $sam | Select  @{ expression={$_.GivenName}; label='FirstName' }, @{ expression={$_.Surname}; label='LastName' }, SamAccountName, UserPrincipalName | export-csv -Path "NotMigratedUsers_$($DateofExport.Invoke()).csv" -Append -Force

I am looking for to get the path of NotMigratedUsers_$($DateofExport.Invoke()).csv

A: Export-Csv creates the file in the current working directory, so you can construct the path like this if the file doesn't exist yet:
Join-Path $PWD.Path "NotMigratedUsers_$($DateofExport.Invoke()).csv"

If the file already exists you can resolve the path like this:
(Resolve-Path "NotMigratedUsers_$($DateofExport.Invoke()).csv").Path

or like this:
(Get-Item "NotMigratedUsers_$($DateofExport.Invoke()).csv").FullName

A: This should be a simple case of:
$Path = "NotMigratedUsers_$($DateofExport.Invoke()).csv"

But obviously I don't know (based on the code provided) what $DateofExport contains or whether it actually has an Invoke() method.


text:
Q: codeigniter update database with "TRUE" for checked items and "FALSE" for remaining unchecked items I am new to php/codeignitor and trying to post changes on form checkboxes to my db. The row to modify is assigned by the gl_id below.
I am not sure how to use my update_checked function in the model to
post TRUE to each of these fields where gl_id =x and FALSE using to the remaining fields not in the array. I can create and view the array of checked values using $_POST['checked'] in the controller
and passing it to the model. Now I need to use this array to post to the db where gl_id = the value from the form in the view.
In View

Update GL id <?php echo $gl_field['gl_id'];?>

        Stat
            <input type="checkbox" <?php if ($gl_field['stat'] == "TRUE") {echo "checked = checked";} ?>
            name = "checked[]" id="stat" value= "stat"  />

        Exclude
            <input type="checkbox" <?php if ($gl_field['exclude'] == "TRUE") {echo "checked = checked";} ?>
            name="checked[]" id="exclude" value= "exclude">

        Override
            <input type="checkbox" <?php if ($gl_field['override'] == "TRUE") {echo "checked = checked";} ?>
            name= "checked[]" id= "override" value = "override"/>

In Controller
            public function update_table(){
               $this->load->helper('form');
               $this->page_nav_model->update_table();
               $checked_array = $_POST['checked'];
               $this->page_nav_model->update_checked($checked_array);
               $this->load->view('pages/success');
            }

In Model
    foreach($checked_array as $true){
            echo $true;
        }

To clarify when I pull the information into the form in the example above all of the checkboxes are set to "TRUE" in the db so they are checked. If I uncheck stat and click submit I am able to see an array with the values (exclude, override).
I appreciate any help that sets me in the right direction.

A: If a checkbox is unchecked in the HTML, the value does not get sent via $_POST. This is not accounted for in CodeIgniter. This is how I deal with this issue. In the controller:
/**
 * Set post values for unchecked boxes.
 *
 * @access private
 * @return void
 */
private function _section_checkboxes()
{
    if (!$this->input->post('is_active')) {$_POST['is_active'] = 0;}
    // other checkboxes here...
}

/**
 * if form validation passes, run this to edit a section
 *
 * @access public
 * @return void
 */
public function do_edit_section()
{
    $this->_section_checkboxes();
    if ($this->section_model->edit_section($this->input->post()))
    {
        redirect('success_page');
    }
}

And in the model:
/**
 * updates a section with active record, returns success.
 *
 * @access public
 * @param array $data
 * @return bool
 */
public function edit_section(array $data)
{
    $this->db->where('id', $data['id']);
    return $this->db->update('sections', $data);
}

And in the view, using the form helper:
<?=form_checkbox(array('name' => 'is_active', 'id' => 'is_active_field', 'value' => '1', 'checked' => (bool)$item->is_active))?>

Now your unchecked checkboxes are set as 0 when unchecked, 1 when checked. I hope this answers your question.

A: To update your table with CI all at once, you need an array like this:
    $data = array(
        'column_1_name' => 'value_to_insert'
        'column_2_name' => 'value_to_insert'
        'column_2_name' => 'value_to_insert'
    );

Right now, you have an array like this $checked_array = ('stat', 'exclude', 'override') - with more or fewer members.
To create the array that you can use in your update statement (like $data above), what you need to do is create another array with the name of each column and a value equal to 1 if it is in $checked_array or 0 if it was not in $checked array.
The function add_values() below can do that for you. You have to supply two arguments:

*

*$all_possibilities is an array of each column name that you will want to update to either 1 or 0. In this case, it should look like $all_possibilities = array('stat', 'exclude', 'override');

*$selected: this is an array with the names of the boxes that were actually selected - it is a subset of $all_possibilities (or it is the same if all the boxes were checked).

This function goes in your controller.
    function add_values($all_possibilities, $selected) {

        $array_for_query = array();
        // this goes through each possible box that can be checked to see if that possibility was actually selected
        foreach($all_possibilities as $array_member) {
            // this checks to see if the current member of $all_possibilities is found in the $selected array
            if (in_array($array_member, $selected)) {
                    // if it is, it adds that as a member of a new query $array_for_query and gives it a value of 1 (true)
                    $array_for_query[$array_member] = 1;
                } else {
                    // if it is not, same as above, but gives it a value of 0
                    $array_for_query[$array_member] = 0;
                }
        }

        // once all the possibilities have been checked and added to the query array, that array is returned
        return $array_for_query;
    }

Now you can call the function and pass the two arguments in. The returned array is assigned to $checked_and_unchecked.
    $data['checked_and_unchecked'] = add_values($possibilities, $checked_array);

Make sure you also grab the gl_id from the form. You can do that with a hidden field in your view:
    <input type="hidden" name="gl_id" value="<?php echo $gl_field['gl_id'];?>" />

In the controller, grab that value with
    $data['gl_id'] = $this->input->post('gl_id');

Then you can pass the information to your model and update your table passing in the name of the table and the array you created.
    $this->model_name->model_method($data);

This will then go in the model:
    $this->db->update('table_name', $checked_and_unchecked);
    $this->db->where('gl_id', $gl_id);

A: So I still needed help getting the final touches on the overall project so I wanted to post the final results here for anyone as green as I looking to control checkboxes from the db and the db from checkboxes.
Controller:
    [function from Tayler and]
    $all_checkbox_fields = array('stat','exclude','override');
        $checked_array = $_POST['checkbox'];
        $data['checkbox'] = $this->add_values($all_checkbox_fields, $checked_array);
        $data['gl_id'] = $this->input->post('gl_id');
        $this->page_nav_model->update_checked($data);
        $this->load->view('pages/success');

Model:
    public function update_checked($data){
        $this->default_db->where('gl_id', $data['gl_id']);
        $this->default_db->update('oracle_table', $data['checkbox']);
    }

View:
    Stat
        <input type="checkbox" <?php if ($gl_field['stat'] == "1") {echo "checked = checked";} ?>
        name = "checkbox[]" id="stat" value= "stat"/>

    Exclude
        <input type="checkbox" <?php if ($gl_field['exclude'] == "1") {echo "checked = checked";} ?>
        name="checkbox[]" id="exclude" value= "exclude"/>

    Override
        <input type="checkbox" <?php if ($gl_field['override'] == "1") {echo "checked = checked";} ?>
        name= "checkbox[]" id= "override" value = "override" >


text:
Q: Return DataTable based on boolean param I have a table that has a field, "IsActive," that indicates whether a record has been "deleted" or not.
Currently, I retrieve this info like so:
    public DataTable GetContractors(bool IsActive)
    {
        SqlParameter paramIsActive = new SqlParameter("@IsActive", SqlDbType.Bit);
        paramIsActive.Value = IsActive;
        DataSet ds = this.SQLDataAccess.ExecSProcReturnDataset(this.AppConfig.ConnectString, "p_selContractors", paramIsActive);
        return ds.Tables[0];
    }

The code for my DAL and stored procedure is irrelevant, so I'll omit that for now.
Here is my question: this code works fine if I want to return records that ARE active or ARE NOT active... but, how would I modify this to return ALL records (active AND inactive)?
Right now, I have two methods and two stored procs (one with the IsActive parameter and the other without the param), but I know there must be an easier way.
Any suggestions?

A: Pass a NULL (assign DBNull.Value to the parameter) and modify your stored procedure to check for that and not care what type of record it is in that circumstance.  Some thing like:
.... WHERE MyTable.IsActive = COALESCE(@IsActive, MyTable.IsActive)

A: Make @IsActive nullable and tweak your SQL code like this:
select ... from ... t
where ...
and (@IsActive is null or t.IsActive = @IsActive)

Plus, refactor your code a tad so that it's more explicit:
public DataTable GetContractors(bool isActive)
{
    return GetContractors((bool?)isActive);
}

public DataTable GetAllContractors()
{
    return GetContractors(null);
}

private DataTable GetContractors(bool? isActive)
{
    SqlParameter paramIsActive = new SqlParameter("@IsActive", SqlDbType.Bit);
    paramIsActive.Value = isActive == null ? DBNull.Value : (object)isActive.Value;

    DataSet ds = this.SQLDataAccess.ExecSProcReturnDataset(
        this.AppConfig.ConnectString, "p_selContractors", paramIsActive);

    return ds.Tables[0];
}

A: change your stored procedure.  Have it check if the parameter is null.  if it's null, return both active and not active.  if it's not null, return the data depending on the parameter.
then in your code, make the parameter nullable, and pass a null when you want to return all records.

A: In your sproc, make the @isActive parameter nullable
ALTER PROCEDURE p_selContractors ( @isActive bit = null )

Then in your WHERE clause, use the following :-
WHERE
  ( @isActive IS NULL OR Active = @isActive )

And in your C# code, don't set the @isActive parameter value, and you should be cool.

A: A quick and easy hack would be to call both procedures seperately and merge the results.
(I'm not saying this is the best option, just one that no-one has suggested yet)
i.e.
var dt = this.SQLDataAccess.ExecSProcReturnDataset(this.AppConfig.ConnectString, "p_selContractors", true).Tables[0];
var dt2 = this.SQLDataAccess.ExecSProcReturnDataset(this.AppConfig.ConnectString, "p_selContractors", false).Tables[0];
dt.Merge(dt2, false);


text:
Q: Performance issues with a stored proc - closing a connection too slow I have previously asked a question about a stored proc that was executing too slowly on a sql server box, however, if I ran the sproc in Query Analyzer, it would return under one second.  The client is a .NET 1.1 winforms app.
I was able to VNC into the user's box and, of course, they did not have SQL tools installed, so I cranked up Excel, went into VBA and wrote a quick function to call the sproc with exact same params.
It turns out that the sproc does return subsecond and I can loop through all the rows in no time at all.  However, closing the connection is what takes a really long time, ranging from 5 seconds to 30.
Why would closing a connection take that long?

A: The symptoms you describe are almost always due to an 'incorrect' cached query plan. While this is an large topic (see parameter sniffing here on SO), you can often (but not always) alleviate the problem by rebuilding a database's indexes andensuring that all statistics are up to date.

A: If you're using a SqlDataReader, one thing you can try is once you have all the data you need, call Cancel on the SqlCommand before calling Close on the SqkDataReader.  This will prevent the out parameters and return values from being filled in which might be the cause of the slowness to close the connection.  Do it in a try catch block because it can throw a cancelled by user exception.

A: Connection pooling?
That, or I'd check for any service packs or KB articles for the client library.


text:
Q: Compile typescript namespaces with less code duplication I'm using gulp-typescript to transpile my typescript files into JS. And it all works fine, except I'm surprised that namespaces are duplicated for every file in the resulting .js file.
Take this example:
LettersOnlyValidator.ts:
namespace Validation {
    const lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }
}

ZipCodeValidator.ts:
namespace Validation {
    const numberRegexp = /^[0-9]+$/;
    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

Compiles into app.js:
var Validation;
(function (Validation) {
    const lettersRegexp = /^[A-Za-z]+$/;
    class LettersOnlyValidator {
        isAcceptable(s) {
            return lettersRegexp.test(s);
        }
    }
    Validation.LettersOnlyValidator = LettersOnlyValidator;
})(Validation || (Validation = {}));
var Validation;
(function (Validation) {
    const numberRegexp = /^[0-9]+$/;
    class ZipCodeValidator {
        isAcceptable(s) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
    Validation.ZipCodeValidator = ZipCodeValidator;
})(Validation || (Validation = {}));

This is my expected outcome:
var Validation;
(function (Validation) {
    const lettersRegexp = /^[A-Za-z]+$/;
    class LettersOnlyValidator {
        isAcceptable(s) {
            return lettersRegexp.test(s);
        }
    }
    const numberRegexp = /^[0-9]+$/;
    class ZipCodeValidator {
        isAcceptable(s) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
    Validation.LettersOnlyValidator = LettersOnlyValidator;
})(Validation || (Validation = {}));

Is there any compile options to optimize that? I couldn't find anything in the documentation: https://www.typescriptlang.org/docs/handbook/compiler-options.html
Or is there a technical reason. e.g. scope conflict for it?


text:
Q: Do we know this homogeneous space by another name? Consider the homogeneous space $GL(3)/GL(2) = GL(3,\mathbb{R})/GL(2,\mathbb{R})$ where $GL(2)$ fixes the first coordinate axis (so can be identified with the subgroup of $2\times 2$ blocks sitting in the 'bottom right' corner of matrices in $GL(3)$).
Is there any 'explicitly known' other homogeneous space which is isomorphic to this one? Say by using orthogonal groups? Is it some sort of Grasmannian/Stiefel manifold?
Am I correct in guessing that $GL(3)/GL(2)$ has dimension 5?

A: As a bundle it fibers over $\mathbb RP^2$ with fiber $\mathbb R^3 \setminus \mathbb R^2$.
I think the most natural way to describe this space would be to consider two bundles over $\mathbb RP^2$: (1) $\mathbb RP^2 \times \mathbb R^3$ and (2) $\{(L,v) : L \in \mathbb RP^2, v \in \mathbb R^3, v \perp L \}$ for this purpose $\mathbb RP^2$ is considered the space of lines in $\mathbb R^3$.
So the total space of bundle (2) is a subspace of the total space of bundle (1).  The bundle you're interested in, is the complement of (2) in (1).
So another way to say what this space is, is it's all pairs $(L, v)$ such that $L$ is in $\mathbb RP^2$ and $v$ projects to a non-zero vector in $L$ (using orthogonal projection).
So another way to describe it would be the tangent bundle of $\mathbb RP^2$ fiber-product with a certain bundle over $\mathbb RP^2$ -- as a bundle over $\mathbb RP^2$ this "certain bundle" is the map $\mathbb R \times S^2 \to \mathbb RP^2$ where $(p,q) \longmapsto \pi(q)$ where $\pi : S^2 \to \mathbb RP^2$ is the 2:1 covering map.
Even simpler, as a space it's diffeomorphic to $S^2 \times \mathbb R^3$.  You can make this equivarient with respect to the left $GL(3)$ action as well -- $GL(3)$ has its standard (projectivized) action on $S^2$, similarly it acts on $\mathbb R^3$.

A: More of a comment than an answer (I know you tagged this as "differential-geometry" and not "homotopy-theory"):
By using simultaneous continuous Gram-Schmidt orthonormalization, this deformation retracts onto $O(3)/(GL(2)\cap O(3))=O(3)/O(2)$.  Note that $O(3)/(O(2)\times O(1))=:Gr_2(\mathbb{R}^3)\cong Gr_1(\mathbb{R}^3)=\mathbb{RP}^2$, so taking an $O(1)$-quotient yields $\mathbb{RP}^2$.  As $O(3)/O(2)$ is connected (the coset of any $A\in O(3)$ contains an element of $SO(3)$), it must be that $O(3)/O(2)\cong S^2$.  (In fact, the fiber bundle $O(2)\rightarrow O(3)\rightarrow S^2$ is just the circle bundle $S(TS^2)$, i.e. the sphere bundle of $TS^2$.)  So, your space is homotopy equivalent to $S^2$.
The fact that you're quotienting by an embedded Lie subgroup means that the dimensions do indeed subtract: $\dim(GL(3)/GL(2))=3^2-2^2=5$.  So this isn't just $TS^2$ or anything like that.  I'd nevertheless be willing to bet that it's some sort of fiber bundle over $S^2$, but I couldn't prove it...


text:
Q: Lisp: Need help getting correct behaviour from SBCL when converting octet stream to EUC-JP with malformed bytes The following does not work in this particular case, complaining that whatever you give it is not a character.
(handler-bind ((sb-int:character-coding-error
                 #'(lambda (c)
                      (invoke-restart 'use-value #\?))))
    (sb-ext:octets-to-string *euc-jp* :external-format :euc-jp))
Where *euc-jp* is a variable containing binary of EUC-JP encoded text.
I have tried #\KATAKANA_LETTER_NI as well, instead of #\? and also just "". Nothing has worked so far.
Any help would be greatly appreciated!
EDIT: To reproduce *EUC-JP*, fetch http://blogs.yahoo.co.jp/akira_w0325/27287392.html using drakma.

A: There's an expression in SBCL 1.0.18's mb-util.lisp that looks like this:
(if code
    (code-char code)
    (decoding-error array pos (+ pos bytes) ,format
                    ',malformed pos))

I'm not very familiar with SBCL's internals, but this looks like a bug.  The consequent returns a character, while the alternative returns a string (no matter what you give to it via USE-VALUE, it's always converted into a string by way of the STRING function; see the definition of DECODING-ERROR in octets.lisp).

A: It works for me:
CL-USER> (handler-bind ((sb-int:character-coding-error
                         #'(lambda (c)
                             (declare (ignore c))
                             (invoke-restart 'use-value #\?))))
           (sb-ext:octets-to-string (make-array '(16)
                                                :element-type '(unsigned-byte 8)
                                                :initial-contents '#(181 65 217 66 164 67 181 217 164 223 164 222 164 185 161 163))
                                    :external-format :euc-jp))
"?A?B?C休みます。"

Might *euc-jp* be something other than a (vector (unsigned-byte 8))?


text:
Q: How to SHA hash in cocoa/iOS Given the message and the salt how can I encode it returning the hashed string?
I need reproduce the php function:
hash_hmac('sha256','message','salt');

Thanks

A: Found the answer:
#import <CommonCrypto/CommonHMAC.h>

-(NSString *) hashString :(NSString *) data withSalt: (NSString *) salt {

   const char *cKey  = [salt cStringUsingEncoding:NSUTF8StringEncoding];
   const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
   unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
   CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

   NSString *hash;

   NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];

   for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
       [output appendFormat:@"%02x", cHMAC[i]];
   hash = output;
   return hash;

}


text:
Q: Javascript XMLHttpRequest Puzzler: Asynchronous vs. Synchronous In building a Firefox extension, I have a dialog that calls a Javascript function when the user hits the "OK" button.  That function looks like this:
var acceptSubscribeHttpReq = null;
function acceptSubscribe(url) {
    acceptSubscribeHttpReq = new XMLHttpRequest();
    acceptSubscribeHttpReq.onload = httpLoadedSubscribe;
    acceptSubscribeHttpReq.onerror = httpErrorSubscribe;
    try {
        acceptSubscribeHttpReq.open("GET", url, true);
        acceptSubscribeHttpReq.send(null);
    } catch(e) {
        acceptSubscribeHttpReq.abort();
        return false;
    }
    // alert("request.status = "+acceptSubscribeHttpReq.status);
    return true;
 }

Interestingly, this works fine if I use a synchronous send (by setting the third argument of open to false), or if I uncomment the alert at the end of the function.  But if I use asynchronous without uncommenting the alert, then this fails silently -- I return from this function as expected, but the onload handler never fires.
This seems to indicate that the XMLHttpRequest object is being destroyed when the function exits.  Is that correct?   Is that happening because this is being called from a button?  And if so, what are the possible solutions?  If that's not the case, any idea why this would be happening?
Here is the XUL for the dialog:
<dialog id="winMain" title="&settingWindow.title;" style="min-width:400px;"
    onload="initSubscribe();" ondialogaccept="return acceptSubscribe();"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">

Any and all help appreciated!

A: The field status of the request only exists after the request has finished (onload / onerror). If you try to access this field before the request has been finalized, you will have an error because such a field does not exists.


text:
Q: Build error with map_view, flutter & gradle I get a build error using flutter version 1.2.2 and map_view version 0.0.14.
I tried to use this code in build.gradle
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2-4'

I followed all the steps here https://pub.dartlang.org/packages/map_view#-readme-tab-
I have an api-key but get the following build error
 Error running Gradle: ProcessException: Process "C:UsersAlmoit PCDesktopMyAppMapflutter_app2androidgradlew.bat" exited
abnormally:

Configure project :map_view
WARNING: The specified Android SDK Build Tools version (27.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.2.1.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '27.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

FAILURE: Build failed with an exception.

What went wrong: The Android Gradle plugin supports only Kotlin Gradle plugin version 1.2.51 and higher. Project 'android' is using
version 1.1.2-4.

Try: Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output. Run with –scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 10s Command: C:UsersAlmoit
PCDesktopMyAppMapflutter_app2androidgradlew.bat app:properties

With flutter doctor, everything seems fine.
flutter doctor -v

[√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [Version 10.0.17763.437], locale en-AI)
    • Flutter version 1.2.1 at C:flutter
    • Framework revision 8661d8aecd (10 weeks ago), 2019-02-14 19:19:53 -0800
    • Engine revision 3757390fa4
    • Dart version 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at C:Sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = C:Sdk
    • Java binary at: C:Program FilesAndroidAndroid Studiojrebinjava
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[√] Android Studio (version 3.3)
    • Android Studio at C:Program FilesAndroidAndroid Studio
    • Flutter plugin version 33.4.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[√] Connected device (1 available)
    • SPH L520 • 2d81b4cf • android-arm • Android 4.4.2 (API 19)

• No issues found!

I searched it everywhere but can't find the answer. Please help me regarding this.

A: In your /android/build.gradle try increasing the version of the kotlin gradle plugin like so:
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.0'

I read somewhere that flutter now only support version 1.3+.
I just tried it and now I can at least build my app for android.
PS: Since you are using an older version of flutter maybe the kotlin plugin will work with an older version as mentioned in the error messages:
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51'


text:
Q: How to GROUP BY CASE with aggregate function I am attempting to get the count of a.clmNo based on the a.stat value displayed on one row.  I am currently getting 3 rows returned since I have a count of 5 a.clmNo over 3 different a.stat values, which makes sense since I am grouping by s.stat.  How can I change my query so that I don't have to group by s.stat and instead get the results returned on one row?
Current results:
+-------------+--------------+-----------------+-----------+---------------+
| pend_claims | assnd_claims | qa_ready_claims | qa_claims | closed_claims |
+-------------+--------------+-----------------+-----------+---------------+
|       0     |       3      |        0        |     0     |       0       |
+-------------+--------------+-----------------+-----------+---------------+
|       0     |       0      |        0        |     1     |       0       |
+-------------+--------------+-----------------+-----------+---------------+
|       1     |       0      |        0        |     0     |       0       |
+-------------+--------------+-----------------+-----------+---------------+

Desired results:
+------------+--------------+-----------------+-----------+--------------+
|pend_claims | assnd_claims | qa_ready_claims | qa_claims | closed_claims|
+------------+--------------+-----------------+-----------+--------------+
|       1    |       3      |        0        |      1    |      0       |
+------------+--------------+-----------------+-----------+--------------+

Current query:
SELECT  ISNULL(case when s.stat = 'Pending Assignment' then count(a.clmNo) end,0) as pend_claims,
    ISNULL(case when s.stat = 'Assigned' then count(a.clmNo) end,0) as assnd_claims,
    ISNULL(case when s.stat = 'QA Ready' then count(a.clmNo) end,0) as qa_ready_claims,
    ISNULL(case when s.stat = 'In QA' then count(a.clmNo) end,0) as qa_claims,
    ISNULL(case when s.stat = 'Closed' then count(a.clmNo) end,0) as closed_claims
FROM assnmts a
inner join assnmtStats astats
    on a.assnmtIdPk = astats.assnmtIdFk
inner join stats s
    on astats.aStatId = s.statIdPk
inner join repAssnmts ra
    on a.assnmtIdPk = ra.assnmtIdFk
inner join aspnetusers anu
    on ra.repId = anu.Id
inner join clients c
    on a.clientIdFk = c.clientIdPk
inner join carrs
    on a.carrierId = carrs.carrIdPk
inner join (SELECT a2.assnmtIdPk, MAX(astats2.asCrtdDt) as MaxDate
            FROM assnmts a2
                INNER JOIN assnmtStats astats2
                    on a2.assnmtIdPk = astats2.assnmtIdFk
            GROUP BY a2.assnmtIdPk
            ) mdt
    on a.assnmtIdPk = mdt.assnmtIdPk
    and astats.asCrtdDt = mdt.MaxDate
inner join (select a3.assnmtIdPk, MAX(ra2.raCrtdDt) as MaxRepDate
            from assnmts a3
            inner join repAssnmts ra2
                on a3.assnmtIdPk = ra2.assnmtIdFk
            group by a3.assnmtIdPk
            ) mrepdt
on a.assnmtIdPk = mrepdt.assnmtIdPk
and ra.raCrtdDt = mrepdt.MaxRepDate
group by s.stat

A: You want conditional aggregation.  Remove the GROUP BY and rephrase the SELECT:
SELECT SUM(case when s.stat = 'Pending Assignment' then 1 else 0 end) as pend_claims,
       SUM(case when s.stat = 'Assigned' then 1 else 0 end) as assnd_claims,
       SUM(case when s.stat = 'QA Ready' then 1 else 0 end) as qa_ready_claims,
       SUM(case when s.stat = 'In QA' then 1 else 0 end) as qa_claims,
       SUM(case when s.stat = 'Closed' then 1 else 0 end) as closed_claims


text:
Q: Action after window.close() I have some troubles with javascript. I would like to do an action after closing a popup window
    <script type="text/javascript">
        window.close()
        window.opener.document.getElementById("login").modal('hide');
    </script>

"window.opener.document.getElementById("login")" this part is
  recognize in the console, but not the modal function : "Uncaught
  TypeError: window.opener.document.getElementById(...).modal is not a
  function(…)"

I was thinking it's because jquery is not called before my code, so I added before juste in case :
<%= javascript_include_tag "application" %>
<script type="text/javascript">
  window.opener.document.getElementById("login").modal('hide');
  window.close();
</script>

but it's still not working. Can you see where is the problem ?


text:
Q: Javascript - capture repeated sequence? Let's say I have a string,
"Testing   éééé     123"

I want to strip out all the occurrences of
é

and all the spaces that come before and after, and just replace it with one space so it ends up like:
"Testing 123"

How do you capture recurrence of a sequence of characters i.e. the repeating
é

, for a Javascript regular expression?

A: Backreferences are your friend for this kind of thing.
A backreference is allowed in regular expressions, allowing you to match the same repeated pattern as a first one. For instance, let's match your char entities:
/(&#x[0-9a-f]+;)\1+/i

This will match the first char entity it finds, then proceeds to chain any number of identical entities after it.
If you want to remove repeated characters, you can even extend it further to this:
/(.+)\1+/i

Which will match any sequence of repeated characters (including spaces) and compounded patterns. Do note, however, that this will get rid of repeated letters in text if there are any.

A: Put the sequence in a group and repeat that group with + - then, you can replace that (and surrounding spaces) with a single space:

const input = "Testing   éééé     123";
const output = input.replace(/ *(?:é)+ */, ' ');
console.log(output);

If there may be additional repeated sequences, eg
"Testing   éééé     123 foobar éé baz";

Then use the global flag as well:
.replace(/ *(?:é)+ */g, ' ');
//                        ^


text:
Q: how to install Tableau in ubuntu 22.04? Is there any sudo-alike magic spell to install Tableau or the only solution is by using it via the web app?
Somehow, didn't find the installation pack for Tableau. Any other Tableau-alike solution for ubuntu recommended is also welcome!

A: Tableau Desktop is only available for PC or MAC. Tableau Server is available for linux https://www.tableau.com/products/linux


text:
Q: Nodejs - Another installation is in progress System - Win 7 64 bit.
Nodejs - node-v6.9.4-x64.msi
Installation error - Another installation is in progress. You must complete that installation before continuing this one.
Solutions that did NOT work - Run as admin, Run via commandline as admin, log had same error i saw in installer, don't install online docs option,
Please help me to fix this. Thank you !

A: This will not be an issue with your NodeJs installation, it might be because of your previous installation (might be any other software) which might be still in progress or not exit properly.
To solve your issue, please try restarting your machine once and install. This will indirectly kill your previous unstable installation and allow you to install NodeJs

A: I had this issue with '2017-03-21, Version 6.10.1 'Boron' (LTS)'. Restarting my PC solved the issue.
P.S. However, this issue seems to be specific to the NodeJs installer. I tried installing other programs after the NodeJs installation threw up this error and they installed fine (even before the restart).


text:
Q: Click event on button doesn't seem to fire I'm not new to HTML or JavaScript, though I don't use them often. I am, however, very new to PHP, and am currently facing a weird issue when trying to get a click event on a button in my HTML which is imbedded in PHP:

<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="function() { alert('Moo!'); }">Some button</button>
</body>

</html>

Nothing happens when I click on the button. Yes, there's of course more markup in the original, but it's not relevant to my question. The W3C markup validation service says there are no errors, and when I alert moo from a script at the bottom of the body tag it works fine as well. It looks like the click event doesn't fire... Any idea why?

A: It is because you define a function and do not execute it. Do not wrap it in a function.
onclick="alert('Moo!');"

If you wrap it in a function. you would need to execute it.
onclick="(function() { alert('Moo!'); })()"

A: The issue is your anonymous function syntax. You're using a function definition, but you're not immediately invoking it, or giving it a name, so the browser doesn't have anything to do with it.
If you want it immediately invoked when clicked you might try rewriting the button section like this:
<button type="button" onclick="(function() { alert('Moo!'); })();">Some button</button>

But my personal preference would be to write it into a named function and call it as the handler instead.

A: You can't have anonymous functions in the inline event handler - use alert("Moo")

<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="alert('Moo!')">Some button</button>
</body>

</html>

You could also use a named function:

function moo() {
  alert("Moo!");
}

<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="moo()">Some button</button>
</body>

</html>

And even an IIFE:

<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="(function() { alert('Moo!'); })()">Some button</button>
</body>

</html>

A: You can bind actions in onclick attribute in 3 ways:

*

*<button type="button" onclick="alert('Moo!');">Some button</button>

*Make a function in JS code. <button type="button" onclick="someFunc()">Some button</button>

*Using closures: <button type="button" onclick="(function() { alert('Moo!'); })()">Some button</button>
`


text:
Q: extract columns according to a list I have a table df, which lists the frequency of 2000 words in 1000 document
id   happy so  today    cut  song dad  may
 1    2      4     3     2    1    0    2
 2    1      2     1     4    0    2    2
 3    0      2     1     1    2    0    3

I want to extract some columns (words) from the table according to a list like this:
     Topic 1   Topic 2
[1,] "cut"     "one"
[2,] "may"     "day"
[3,] "song"    "job"
[4,] "act"     "start"
[5,] "control" "check"

extracting one column from a table is df$col, here the column names in df are the names in the list. The outcome would be like this:
id    cut  may song
 1     2     2   1
 2     4     2   0
 3     1     3   2

A: We can use match.  To extract the columns in "df1" based on the first column of "m2"
df1[c(1, match(m2[,"Topic1"], names(df1), nomatch=0))]
#   id cut may song
#1  1   2   2    1
#2  2   4   2    0
#3  3   1   3    2

As 'm2' is matrix, we can also do this for all the columns in the same step
df1[c(1, match(m2, names(df1), nomatch=0))]

If we need to subset the initial dataset based on each of the columns in "m2" (matrix),
lapply(seq_len(ncol(m2)), function(i)
        df1[c(1, match(m2[,i], names(df1), nomatch=0))]
        )
#[[1]]
#  id cut may song
#1  1   2   2    1
#2  2   4   2    0
#3  3   1   3    2

#[[2]]
#  id
#1  1
#2  2
#3  3

NOTE: In the second column of "m2", there is no element that matches with the column names of 'df1'.


text:
Q: wxPython - implementing wx.EVT_TEXT_PASTE i'm creating a wx.PyValidator for my textboxes:
class IPValidator(wx.PyValidator):
    "Validator for validating IP addresses"

    def __init__(self):
        super(IPValidator, self).__init__()
        self.Bind(wx.EVT_TEXT_PASTE, self.OnPaste)

    def Clone(self):
        """Cloning the validator"""
        return self.__class__()

    def Validate(self, win):
        """the validate function"""
        return self.OnValidate(self.GetWindow().GetValue())

    def OnValidate(self, text):
        """returns True or False about the given text"""
        return re.match(text, ip_pattern)

    def OnPaste(self, event): #######
        text = event.GetString()
        if self.OnValidate(text):
            event.Skip()

    def TransferToWindow(self):
        return True

    def TransferFromWindow(self):
        return True

I have a problem in my OnPaste method. How can I get the string that is pasted before it is being pasted and make sure it is valid? event.GetString returns an empty string

A: you need to interface the clipboard directly
def get_clipboard_text():
    if not wx.TheClipboard.IsOpened(): wx.TheClipboard.Open()
    do = wx.TextDataObject()
    success = wx.TheClipboard.GetData(do)
    if success:
        return do.GetText()
    return ""

class MyWidget(...):
    ....
    def OnPaste(self, event): #######
        text = get_clipboard_text()
        if self.OnValidate(text):
            event.Skip()

is how you can do it with just wx ... but I recommend using something like pyperclip as it is much easier to deal with


text:
Q: Connect to Google App Engine shared memcached from python3.7 runtime Google App Engine supports a Python 3.7 runtime on a beta basis, but I cannot figure out how to connect to the appengine memcache from that runtime. The documentation is strangely silent on the issue.
Here are the docs for python2.7: https://cloud.google.com/appengine/docs/standard/python/memcache/ However, note that python3.7 is grayed out. Does anyone know how to connect to this service in python3.7?

A: My sense from exploring further is that the memcache API is not going to be supported going forward. Instead, they're expecting people to transition to standard backends hosted in the cloud. For example, it's possible to get a free Redis instance with 30MB of storage turned on in the cloud. You can use that as a cache the same way you would use memcached. I tested this and found performance acceptable:
2018-10-16 21:03:09.733 PDT
Took 1.3084499999999935 ms to get result OK (from set)
2018-10-16 21:03:09.735 PDT
Took 1.1954209999998966 ms to get result bar (from get)
2018-10-16 21:03:09.736 PDT
Took 1.0369539999999233 ms to get result null (from get)

This was using the nodejs8 runtime, but I assume the Python 3.7 runtime would be no different. The tutorial on how to set this up is here.

A: Memcache is documented as being unavailable for the Python3.7 runtime:

The Memcache service is not available in Python 3. If you need access to a hosted caching service, you can use a third party memcache service like Redis Labs Cloud.

Update:
The documentation has been updated, and now recommends using Google's Cloud MemoryStore [for Redis] to create an application cache.

To build an application cache, create a Cloud Memorystore instance and connect it to your app using Serverless VPC Access.

Note that unlike Memcache, Cloud Memorystore is not free.


text:
Q: Send Data from render process to renderer process in Electron I am developing desktop application using Electron,
Scenario is I have 2 BrowserWindow, From FirstBrwoserWindow, I am going to SecondBrowserWindow after button click. i have instantiated SecondBrowserWindow on FirstBrwoserWindow's button click to avoid Object has been destroyed Exception.
As per Electron, if we want to send data between processes we have to use IPC. So actual problem starts here, I am creating SecondBrowserWindow object in FirstBrwoserWindow's renderer file, and for IPC i need to get SecondBrowserWindow object in main process.
How do i get SecondBrowserWindow Object in main.js and use IPC.on there????

A: The way I've solved this is to pass the data with ipcRenderer from the first window to the main process and then pass it with ipcMain to the second window using BrowserWindow.webContents.send().
It looks kinda like this.
Window 1
...
// Emit an ipc message with your data
ipcRenderer('your-message', { foo: 'bar' });
...

Main process
...
let window1 = new BrowserWindow(...);
let window2 = new BrowserWindow(...);
...
// when ipc message received pass it on to second window object with webContents
ipcMain.on('your-message', (event, payload) => {
  window2.webContents.send('your-relayed-message', payload);
});
...

Window 2
...
// when ipc messaged received in second window do what you want with the data
ipcRenderer.on('your-relayed-message', (event, payload) => {
  console.log(payload);
});
...

A: You can do it in more ways but what I recommend you to:
1) when you receive the input to open the 2nd BrowserWindow in the renderer, send a message to main.js
2) from main.js open the 2nd BrowserWindow so you can control it and send message to it in a cleaner way.
In this way, you can close the previous BrowserWindow without errors in communication and you have a more scalable and readable logic for N BrowserWindows.


text:
Q: Rotate PDF in Safari In Safari if I open a misoriented PDF is there a way to rotate it so that I can read it without having to rotate my head and end up dizzy?

A: If it's mis-oriented in Safari that means the original is formatted that way.  Safari only provides a "quick viewer" of sorts for PDF files and is only rendering what was provided.
What you need to do is open it in Preview.

Simply right click anywhere on the PDF in Safari and select "Open With Preview."  Once you're in Preview, you can rotate the PDF with ⌘ CommandL or ⌘ CommandR to rotate left and right respectively.

A: Using Preview is a terrific alternative as mentioned above.
Preview can even save the PDF with the new rotation. Later, if you want to view in Safari, you can do so without difficulty (or dizziness).


text:
Q: Is there a print_r or var_dump equivalent in PHP that does not echo the result by default? I often use print_r($value, true) to dump some variables in log statements, and sometimes I forget to set the second parameter to true, which then might result in instead of the result being in the log statement, in most cases it just gets lost, but sometimes it is even rendered to the users browser.
This just happened to me, and within the object graph where some credentials, and other things that you normally would not like the end user to see. The problem was that instead of passing true as the second parameter, for some reason I passed null 1 year ago. And now there was some system failure that made the wrong output show.
What do you do to avoid having stacktraces output by programmer error? Why do all PHP dumping functions just echo the output by default? Searching though our codebase, I found quite a lot of invocations of print_r without the second parameter set to true.
I also use json_encode() for debug output sometimes, because the output is sometimes more concise and friendly to read. Any drawbacks with that approach?
We normally use some sort of output buffering, but not everywhere.

A: Why not create a custom function that will wrap all your print_r calls? I use something like this:
function good_print() {
    $log = '';
    foreach(func_get_args() as $arg) $log .= print_r($arg, true);
    return $log;
}

It saves time, gives me better functionality, plus I don't have to worry about "did I use the right call this time?"

A: var_export() returns a string if the second argument is true; but it's up to you to remember to set that second argument

A:
What do you do to avoid having stacktraces output by programmer error?

Simple, non production code is not allowed on production (var_dump, print_r, et al. are never useful in production). Enforce by in order of preference either build / testing system, source control, enforcing using only wrapper functions which can easily be disabled centrally, or if you really must, production server configuration.

Why do all PHP dumping functions just echo the output by default?

Because it's easiest during development.

Searching though our codebase, I found quite a lot of invocations of print_r without the second parameter set to true

And you also found a lot of or die('some errormessage); statements, also not a good idea in production for obvious reasons. Manual code is illustration, never production code, but alas treated as such by many a programmer.

I also use json_encode() for debug output sometimes, because the output is sometimes more concise and friendly to read. Any drawbacks with that approach?

Some extra load maybe, and no clear indicator it is for debugging (as mentioned earlier, var_dump is a red flag, json_encode isn't).

We normally use some sort of output buffering, but not everywhere.

I only use it when strictly needed, so, almost nowhere.

A: As per the PHP manual docs on print_rdocs, you can tell print_r to return the results instead of outputting them with the second, optional bool parameter:
$test = array('var1', 'var2');
$val = print_r($test, TRUE); // won't output anything
echo $val; // output the normal print_r goodness you know and love

UPDATE
After actually reading the question I would suggest @davethegr8's solution, so you and others should probably vote for that over this answer. Another implementation:
function _print_r($val, $return=TRUE)
{
  print_r($val, $return);
}

Finally, a funny thing happens when you use test-driven development: You don't litter your source code with test debug statements because you've already handled it in your unit tests:

A:
What do you do to avoid having stacktraces output by programmer error?

You can set a custom method that prints errors only if the DEBUG option is set.
define('DEBUG', "DEBUG");

function print_log($input) {
    if (defined("DEBUG")) {
        print_r($input, true);
    }
}

and instead of calling print_r just call print_log.
You may also want to take a look at Krumo, which is an amazing replacement for var_dump and print_r for displaying PHP variables in a structured way.


text:
Q: Matlab nested parfor loops inside functions, will all workers be used if the outer loop is small? If I understand the documentation correctly I can have a parfor loop inside another parfor loop as long as the inner loop is in a separate function call, which is true in my case.
My question is simply this:
In some instances my outer loop only uses 2 threads/workers. I have 6 workers in my parallel pool.
Will the inner parfor loop take advantage of the 4 unused workers?

A: From MATLAB's own documentation (http://www.mathworks.com/help/distcomp/nesting-and-flow-in-parfor-loops.html):

The body of a parfor-loop cannot contain another parfor-loop. But it
  can call a function that contains another parfor-loop.
However, because a worker cannot open a parallel pool, a worker cannot
  run the inner nested parfor-loop in parallel. This means that only one
  level of nested parfor-loops can run in parallel. If the outer loop
  runs in parallel on a parallel pool, the inner loop runs serially on
  each worker. If the outer loop runs serially in the client (e.g.,
  parfor specifying zero workers), the function that contains the inner
  loop can run the inner loop in parallel on workers in a pool.

As a worker cannot itself open a pool, the inner parfor loop will work in a serial manner.


text:
Q: When should os.File.Close() be called explicitly? I seems that whether f.Close() is commented out or not in the following program, the result is the same. Does anybody know when f.Close() should be explicitly called?
package main

import (
    "os"
    "log"
    "strconv"
)

func main() {
    f, err := os.OpenFile(os.Args[1], os.O_RDWR|os.O_CREATE, 0666)
    if err != nil { log.Fatal(err) }
    defer f.Close()

    off, err := strconv.ParseInt(os.Args[3], 0, 64)
    if err != nil { log.Fatal(err) }

    _, err = f.WriteAt([]byte(os.Args[2]), off)
    if err != nil { log.Fatal(err) }
}

$ go run main.go output.txt abc 10
$ xxd < output.txt
00000000: 0000 0000 0000 0000 0000 6162 63         ..........abc

A: You should call File.Close() when the File object is no longer needed.
The actual implementation is OS specific, but will close the file descriptor, prevent any further I/O, and free the resources for garbage collection (at the Go level), or reuse (at the kernel level).
One pathological consequence of not calling Close on a long running program with many open files would be running out of open file descriptors, blocking all I/O for that user (or even the entire system).
In general, skipping File.Close() means you cannot be guaranteed that the write succeeded. In all OSes writes are not committed to disk upon return of the Write(...) call but are buffered. Calling File.Sync() or File.Close() tends to be the only way to surface errors encountered when flushing all buffers. This is the same reason defer f.Close() should not be used when you actually care about catching errors.
In your particular code sample, you're not checking the error returned by f.WriteAt so any problem will be ignored. In this very specific scenario, calling f.Close really doesn't matter as you already have no guarantee that the file was written successfully.


text:
Q: What would you call a pleading before a judge or God Is there a noun or adjective for the following or similar:

*

*a pleading before a judge for clemency

*a prayer before God begging for mercy

Is there a better word than "begging", "pleading", "petitioning", etc.?

A: Perhaps entreaty

An earnest or humble request:
  the king turned a deaf ear to his entreaties

Oxford Dictionaries Online

A: The noun imploration might be suitable to your needs.

An act of begging someone to do something:
earnest implorations for divine forgiveness and mercy

From the verb implore Etymonline tells us

v.
c.1500, from Middle French implorer and directly from Latin implorare "call for help, beseech," originally "invoke with weeping," from assimilated form of in- "on, upon" + plorare "to weep, cry out." Related: Implored ; imploring ; imploringly.

A:
Judge or God, clemency or mercy..

Supplication, a noun, can logically be applied to any situation in which you plead to someone in power for help or a favor.
Supplication:  comes from the Latin verb supplicare, which means "to plead humbly."
(etymonline.com)

Supplication (also known as petitioning) is a form of prayer, wherein
  one party humbly or earnestly asks another party to provide something,
  either for the party who is doing the supplicating (e.g., "Please
  spare my life.") or on behalf of someone else (e.g., "Please spare my
  child's life.").
  (wiki)

A: Prayer may be best because it is actually a legal term of art.  E.g., I'm looking at a court order that reads "... it is hereby ORDERED and DECREED that the prayer of the Petition is DENIED...."

A: In the English criminal courts the defence, between conviction and sentencing, may make a plea in mitigation.

A: In the case of religion I would use the word "prostrate" or "prostration". This is when you kneel down with your body flat before a God or religious icon. I have used the word in non religious instances too but this may not be correct.


text:
Q: How I make this jquery slide show? I am trying to make a slide show as my home page banner. Here I use jquery localscroll.js and scrollTo.js plugins.
This is my Javascript -
$(document).ready(function() {
    $("#slideshow").css("overflow", "hidden");
    $("#slideshow-nav").css("visibility", "visible");
    $("#slideshow-nav a[href=#oron5]").addClass("active");

    $("#slideshow-nav").localScroll({
        target:'#slideshow', axis: 'x'
    });

    $("#slideshow-nav a").click(function(){
        $("#slideshow-nav a").removeClass("active");
        $(this).addClass("active");
    });
});

Here I need to click navigation button to view images. So Can I know, how do I make this to change images automatically after some times?
This is my FIDDLE so far.
Can anybody help me to figure this out.
Thank you.

A: One simple way is to set an interval and use jQuery's .click() function. For example, try adding this code to the end of your $(document).ready() function:
var count = 2;
var interval = setInterval(function() {
    if(count > 5) {
        clearInterval(interval);
    }
    $("#slideshow-nav li:nth-child(" + count + ") a").click();
    ++count;
}, 1000);


text:
Q: Find user by authentication token in Rails? So for a certain project I'm thinking it may possibly be useful for me to be able to take an authentication token and figure out which user it is for. I'm not sure if it's even possible or not. Anyone happen to know?

A: Authlogic (example app linked) uses 'persistence tokens'.
    t.string    :login,               :null => false                # optional, you can use email instead, or both
    t.string    :email,               :null => false                # optional, you can use login instead, or both
    t.string    :crypted_password,    :null => false                # optional, see below
    t.string    :password_salt,       :null => false                # optional, but highly recommended
    t.string    :persistence_token,   :null => false                # required
    t.string    :single_access_token, :null => false                # optional, see Authlogic::Session::Params
    t.string    :perishable_token,    :null => false                # optional, see Authlogic::Session::Perishability

    # Magic columns, just like ActiveRecord's created_at and updated_at. These are automatically maintained by Authlogic if they are present.
    t.integer   :login_count,         :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
    t.integer   :failed_login_count,  :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
    t.datetime  :last_request_at                                    # optional, see Authlogic::Session::MagicColumns
    t.datetime  :current_login_at                                   # optional, see Authlogic::Session::MagicColumns
    t.datetime  :last_login_at                                      # optional, see Authlogic::Session::MagicColumns
    t.string    :current_login_ip                                   # optional, see Authlogic::Session::MagicColumns
    t.string    :last_login_ip                                      # optional, see Authlogic::Session::MagicColumns

It may not be exactly what you want, but I think you can make it work. The real question is, why do you want to do this?


text:
Q: Something went wrong while saving the category. Notice: getimagesize(): I'm facing the following error when I try to change category name :
Something went wrong while saving the category.
Notice: getimagesize(): read of 8192 bytes failed with errno=21 Is a directory in /home/nectarksa/public_html/vendor/magento/framework/Filesystem/Driver/File/Mime.php on line 115

I've tried to increase php memory limit it's didn't fixed.

A: This error means that the path give is the path to a directory/folder and not an image file.  So you need to do some debugging to see why.
if (function_exists('mime_content_type')) {
   $result = $this->getNativeMimeType($path);
} else {
   $imageInfo = getimagesize($path); // Line 115
   $result = $imageInfo['mime'];
}

A: It's solved finally, the problem was because of one extension called auto cache flush.