text:
Q: Add Mousedown event in new CheckBox() instance Briefly, my app adds checkboxes programmatically into a flowlayoutpanel named "fp".
fp.Controls.Add(new CheckBox() { Name = "cb1", Text = "New Checkbox", Checked = true, AutoSize = true, AllowDrop = true });

i'm stuck trying to add a mouseclick event inside that new Checkbox instance. I tried adding the line below into the code above.
this.MouseDown += new MouseEventHandler(cbox_MouseDown);

But I get Invalid initializer member declarator
I also tried to add this:
((CheckBox)(this.Controls.Find("cb1", false))[0]).MouseDown += new MouseEventHandler(cbox_MouseDown);

before adding the new checkbox instance but it does not work either.
I could highly appreciate a way to insert the event directly into the new CheckBox() instance .
Thank you guys <3

A: *

*C#'s Object-Initializer syntax does not support events.

*

*C#'s Object-Initializers have a lot of other shortcomings too, I'm not a fan of them (horrible debugging, broken line-numbers in stack-traces, it ignores IDisposable when an exception is thrown, you can't use it with an existing object, often takes up more lines-of-code than otherwise, etc).

*However, you can define a new extension-method for ControlsCollection which will add the event-handler for you.

Like so:
MyExtensions.cs:
public static class MyExtensions
{
    public static void AddWithClickHandler( this ControlsCollection ctrls, EventHandler onClickHandler, CheckBox newCheckBox )
    {
        newCheckBox.Click += onClickHandler;
        ctrls.Add( newCheckBox );
    }
}

MyForm.cs:
public partial class MyForm : Form
{
    private readonly EventHandler onClickHandler;

    public MyForm()
    {
        this.InitializeComponent();

        //

        this.onClickHandler = new EventHandler( this.cbox_MouseDown );
    }

    private void cbox_MouseDown( Object sender, EventArgs e )
    {
        //
    }

    private Int32 checkboxCount = 0;
    private String GetNewCheckboxName()
    {
        this.checkboxCount += 1;
        return "cb" + this.checkboxCount.ToString("d");
    }

    public void AddCheckboxes()
    {
        this.fp.Controls.AddWithClickHandler( onClickHandler, new CheckBox() { Name = this.GetNewCheckboxName(), Text = "New Checkbox", Checked = true, AutoSize = true, AllowDrop = true } );

        this.fp.Controls.AddWithClickHandler( onClickHandler, new CheckBox() { Name = this.GetNewCheckboxName(), Text = "New Checkbox", Checked = true, AutoSize = true, AllowDrop = true } );

        this.fp.Controls.AddWithClickHandler( onClickHandler, new CheckBox() { Name = this.GetNewCheckboxName(), Text = "New Checkbox", Checked = true, AutoSize = true, AllowDrop = true } );
    }
}

Note that:

*

*In my code, the MyForm class only ever creates a single EventHandler instance (using new EventHandler), this is important as you need to allow code to de-register (i.e. remove) event-handlers to prevent memory-leaks.

*

*Unfortunately you cannot remove event-handlers registered using the shorthand syntax like this: obj.Click += this.OnClickMethod;

*Nor can you remove event-handlers implemented as lambda-methods, e.g. obj.Click += ( obj, sender ) => this.DoSomething();

*Control Names need to be unique, so rather than hardcoding strings like "cb1" and "cb2", unique names for each and every checkbox is generated by the GetNewCheckboxName() method.


text:
Q: Why not make "supermen" on Krypton? As a scientist and a father, Jor El wouldn't send his son to a planet with an environment that could potentially kill him, so he had to test what the yellow Sun's rays would do to the Kryptonian body.  Jor El states that the yellow Sun of Earth will make Kal El a god.  This means he would have tested its effects on Kryptonians.
Why not make a "tanning bed" that emits the radiation needed to make a Kryptonian into a superman?  Yes a red Sun drains Superman of his powers, but radiation can be blocked.  It would be a medical cure-all at minimum and a race of supermen at best.

A: We don't know that he tested anything, and it seems unlikely that he could do so if he tried. We also don't know how one would go about making a false sun, or how effective it would be.
Basing my answer solely on Man of Steel, we don't know how long the effects of the yellow sun last after exposure ends. Maybe a month, maybe a day. If a Kryptonian got out of your tanning bed, then walked out into the light of a red sun, the tanning bed's effect might wear off immediately.
And in the short term, the experiences of (young) Clark and Zod suggest that being exposed to a yellow sun for the first time is a horrible ordeal. The powers it gives you are excruciating and very difficult to control - people would be shooting heat vision everywhere and cutting everything in half. They would accidentally crush everything they touched. Every noise would be painful to their ears and their eyes would burn from the slightest hint of light. Even if it had some medicinal effect, it would be like chemotherapy - so unpleasant that it would always be the last possible alternative.
And even if Jor-El discovered how a yellow sun would affect Kryptonians, he might have discovered it a week before he sent Kal-El away, in which case he didn't have time to try to build anything - he was too preoccupied with the imminent explosion of his planet.
And considering the fact that in the film, Kryptonians aren't even allowed to have babies the natural way, what makes you think they'd be allowed to make their children into Supermen?

A: Actually, we know from the movie that even spending an entire lifetime in the yellow sun wouldn't save you from a few minutes in the Kryptonian atmosphere (as shown by Superman's stint in the atmosphere replicated in the Kryptonians' spaceship). Superman became Relatively Fit Untrained Guy. Even without a red sun, he was unable to maintain his powers relative to other Kryptonians.
Essentially, in the movie, we're shown (and outright told by Jor-El in the scout ship) that the Kryptonians were held down not just by their sun but specifically by their actions which harmed their own world.
Note that Zod, exposed to the sun and the fresh air, also became an unbermensch in a relatively short time. With just the sun, he was only given super strength, and this strength dissipated while in the ship. Strong people is something -- but not something which could save the whole planet. That would require several full on supermen.

A: Culture, religion, philosophy, ethics, etc.
Even assuming they had the foreknowledge on the effects of a different sun and that knowledge was widespread and deemed reliable... that doesn't mean their society would adopt it.  Consider the fact that we could engage in eugenics, sterilization, and designer babies today if we wanted to.  We could outlaw people with genetic defects from reproducing, we could terminate any prospectively "defective" child before being born, we could modify all humans before being born to meet certain specifications... but that's an anathema to us.  Just like there is a ton we could learn from human experimentation and testing, but we don't for moral reasons.
Similarly, we have the technology to pump you full of steroids from birth or to amputate your limps and replace them with artificial ones which could supply a specific mechanical advantage... again, we don't for reasons that go beyond the inability to do so.
Perfection and strength are in the eye-of-the-beholder.
What little insight into Kryptonian culture we have, we know that they deemed their sun, Rao, a god.  Shielding one's self from his light and accepting the light from artificial sources may well amount to heresy.
There's support for the idea that Kryptonians would find a super-powered society an anathema.  Remember that's Zod's entire mission.  To replicate and recreate Krypton exactly as it existed before with the sole modification of himself as leader.  So did his plans include dropping all his men onto Earth so that they could ALL have super-powers?  Clearly not!  Zod went through every effort to put as few Kryptonians on Earth as possible.  He had every intention of creating a New Krypton where none of them would have powers.  Why was he (and Faora and Nam-Ek) an exception?  That's the role of a soldier!  Killing is an anathema!   However, the soldier is given limited authority and window to do so within the scope of war.  Here, Zod gave himself permission to have super-powers... only to be discarded as soon as Krypton was rebuilt.

redpajama_set_name: RedPajamaStackExchange


text:
Q: intellij idea logcat colors is there fix for logcat color miss match in Intellij Idea. It should be colored  according to Log level, but it mixes them. I am using 12.0.4 version. and there is the screenshot:
[1] http://imagebin.org/251551 "image".
I am using Ubuntu 12.10 and Oracle JDK java version "1.6.0_35".
Thank You!

A: Here is the solution, click in turn:

File > Settings >  [IDE Settings] Editor > Color & Fonts > Console
  Colors

you will see the options, e.g

Console standard output
Console error output
etc...

And then right click the icon like below to customize the color you like :)

A: I think NobodyElse means this path
File > Settings > [IDE Settings] Editor > Color & Fonts > Android logcat

A: Found the answer: http://devnet.jetbrains.com/message/5483068#5483068
This is apparently a bug. I have reported.


text:
Q: cv::Mat to QImage conversion results in odd display trying to convert local webcam stream from cv::Mat to QImage but the output is weird. I've tried a bunch of things and searched for hours; I'm officially stuck.
here is the code snippet in question
void AppName::SlotFrameReady(cv::Mat image, qint64 captureTime, qint64 processTime)
{
  //  cv::Mat imageholder;
  //  cv::cvtColor(image, imageholder, CV_BGRA2RGBA);

 //   QImage img((const unsigned char*)(image.data), image.cols, image.rows, QImage::Format_Grayscale8);
 //    QImage img((const unsigned char*)(imageholder.data), imageholder.cols, imageholder.rows, QImage::Format_RGB32);
     QImage img((const unsigned char*)(image.data), image.cols, image.rows, image.step, QImage::Format_RGB888);

    m_VideoView->Update(&img);

}

This is what I've tried - adding image.step, tried every QImage format, tried img.invertPixels() and img.invertRGB/invertRGBA()
I've also tried creating a temporary image to run cvtColor and convert (tried CV_BGRA2RGB and BGRA2RGBA) and this gives the same result.
type() output is 24 which, if I am correct, is CV_8UC4.
If I use any sort of above I get the following (although some formats will show incorrect color instead of just grayscale. This is with RGB8888):
http://i.imgur.com/79k3q8U.png
if I output in grayscale everything works as it should:
removed link bc rep isn't enough
On mac 10.11 with QT creator 5 and opencv 3.1 if that makes a difference, thanks!
edit to clarify:
I have tried Ypnos' solution here but that makes the output a blank gray screen. The only other options I've found are variations of what I've explored above.
The one thing I haven't tried is writing the mat to a file and reading it into a qimage. My thinking is that this is very inelegant and will be too slow for my needs.
another thing to note that I stupidly forgot to include - the video view update function transforms the qimage into a qpixmap for display. could this be where the error is?
edit again: got Ypnos' solution working, was a stupid error on my part (using the mat3b/vec3b when it is a 4 channel image). However, output is still a mess.
here is updated code:
void AppName::SlotFrameReady(const cv::Mat4b &image, qint64 captureTime, qint64 processTime)
{

    QImage dest(image.cols, image.rows, QImage::Format_RGBA8888);
    for (int y = 0; y < image.rows; ++y) {
            const cv::Vec4b *srcrow = image[y];
            QRgb *destrow = (QRgb*)dest.scanLine(y);
            for (int x = 0; x < image.cols; ++x) {
                    destrow[x] = qRgba(srcrow[x][2], srcrow[x][1], srcrow[x][0], 255);
            }
         }

    m_VideoView->Update(&dest);

and the relevant section of VideoView where it is converted to PixMap and pushed to display
    QPixmap bitmap = QPixmap::fromImage(*image).transformed(transform, Qt::SmoothTransformation);
    setPixmap(bitmap);

AND the new but still messed up output
http://i.imgur.com/1jlmfRQ.png
using the FaceTime camera built into my macbook pro as well as with 2 other USB cams I've tried (logitech c270 and a no-name chinese garbage cam)
any ideas?


text:
Q: find the closed form of $\sum_{k=1}^\infty\left(\frac{\sec{kz}}{k^2}\right)^2$ How to evaluate $\displaystyle\sum_{k=1}^\infty\left(\frac{\sec{(k\pi\sqrt{5})}}{k^2}\right)^2$?
In general, how to find the closed form of infinite series $\displaystyle\sum_{k=1}^\infty\left(\frac{\sec{(kz)}}{k^2}\right)^2$ in term of variable $z$ ?  Thanks in advance.


text:
Q: How to setup Eclipse for Android I'm trying to get Eclipse setup for Android and have done the following steps. I'm using the book "Android 101" and basically following the steps.
(1) Installed Java SDK
(2) Installed Eclipse
(3) Installed Android SDK
I start Eclipse and go to Window->Preferences and expect to see Android in the list. I'm supposed to select Android then point it to where I installed the Android SDK. The problem is that I'm not seeing Android in the list.
I did not have any trouble with the Java or Android installs, and I didn't see any option in the Eclipse install specific to Android.
I've searched on Stack Overflow and Googled, and am not finding anything.

A: From inside Eclipse select Help->Install New Software then click NEW.
Install ADT from https://dl-ssl.google.com/android/eclipse
After that you point it to your Android SDK install location and the APIs all show up. Hit APPLY and OK, then ready to start working.

A: The best plan here is to follow the advice given on the Android Developers blog in June, 2015.

[…] we are ending development and official support for the Android Developer Tools (ADT) in Eclipse at the end of the year. This specifically includes the Eclipse ADT plugin and Android Ant build system. If you have not had the chance to migrate your projects to Android Studio, now is the time.

I'm a long-time Eclipse user, and I recently fired up Android Studio for some brief Android testing. There was definitely a learning curve, but it wasn't insurmountable.


text:
Q: Webpack - dont output a bundle for a certain entry point Im using a file-loader to automatically render a bunch of pug templates to static html files, but webpack is also outputting a pointless file based on the entry point
Eg this is in my webpack.config.js:
entry: {
    'js/build/bundle.js': './js/app.js',
    'this-shouldnt-emit': './pug/.pug.js' //pug entry point
},

output: {
    path: path.join(__dirname, '../'),
    filename: '[name]'
},

...
// pug loading module rule
        {
            test: /\.pug$/,
            include: path.resolve(__dirname, "../pug"),
            use: [
                "file-loader?name=[path][name].html&context=./pug",
                "pug-html-loader?pretty&exports=false"
            ]
        }

and Im getting a this-shouldnt-emit bundle file in the root build directory, which I dont want.
How can I stop the file-loader from emitting an output bundle, but not interfere with it generating all the static html files it currently is. Is there a plugin or some kind of null loader I can put at the end of the loader chain to kill the bundle emitting?

A: I am not sure of what you are really asking but if you want it include multiple files in one bundle, use an array. The whole point of using [name] in filename: '[name].bundle.js is for multiple entries. It is not necessary (but optional) for one entry key.
This will create two bundle files.
entry: {
   BUNDLE_KEY_ONE: 'path/file.js',
   BUNDLE_KEY_TWO: 'path/otherFile.js',
}

This is how you have multiple files one bundle.
entry: {
   SINGLE_BUNDLE_NAME: ['file/one.js', 'file/two.js']
}


text:
Q: Linear shooting method for Second Order BVP How can we use the linear shooting method to solve the boundary value problem $$y'' = 2y' - y, ~y(0) = 1, \text{and} ~~y(1) = 2?$$
I tried to convert it to a first order system, but didn't get what I needed.

A: Hints:
We are given:
$$\tag 1 \displaystyle y'' = 2y' - y, ~y(0) = 1, \text{and} ~~y(1) = 2$$
We know that if the linear boundary-value problem:
$y'' = p(x)y' + q(x)y+r(x), a \le x \le b, y(a) = \alpha, y(b) = \beta$, satisfies:
(i) $p(x), q(x)$, and $r(x)$ are continuous on $[a, b]$
(ii) $q(x) \gt 0$ on $[a, b].$
We can get a unique solution.
For this problem, we have:
$y_1(x): y'' = p(x) y' + q(x) y + r(x)$, and
$y_2(x): y'' = p(x) y' + q(x) y$
So,

*

*$p(x) = 2$

*$q(x) = -1$

*$r(x) = 0$

With the same BCs given in $(1)$.
For comparison purposes, $(1)$ has the exact solution:
$$\displaystyle y(x) = e^{x-1} \left(-e x+2 x+e\right)$$
Now, you just have to apply all of the above to the Linear Shooting Algorithm.
Note, did they provide an "N" for how many steps they wanted because $\displaystyle h = \frac{b-a}{N}$?
Also note, this algorithm is pretty involved and it is easier to code it up rather than manually cranking values.

A: Characteristic equation of
$$
y''-2y+y = 0
$$
is
$$
\lambda^2 - 2\lambda+1 = 0 \\
\lambda_{1,2} = 1
$$
so general solution can be found as
$$
y = e^x(C_1 + C_2 x)
$$
To find unknown coefficients one can use boundary conditions
$$
y(0) = C_1 = 1 \\
y(1) = e(1+C_2) = 2 \\
C_2 = \frac 2e-1
$$
And finally
$$
y(x) = e^x \left [1 + x \left( \frac 2e-1\right) \right ]
$$


text:
Q: How can I restrict an authenticated user from posting on behalf of someone else? If I am logged in as user1 and I am accessing a ViewSet called RecipeSubmissionViewSet, the POST takes a recipe_id of the recipe the user wants to submit.  How do I ensure that user1 does not submit user2's recipe, assuming the Recipe model has an owner field on it and I can just compare it to request.user? Should I use a permission class for this or is there a better way?  I'm speaking from an backend point of view and not taking into account that the front end would of course filter out the recipes that belong to the user and only show them their own recipes.

A: There can be two ways. You can filter out queryset or define permission class.
If you override get_queryset method like this.
class RecipeSubmissionViewSet(...):
    def get_queryset(self):
        return Recipe.objects.filter(owner=self.request.user)
        # you can also use filtration based on action name like this

        # if self.action == 'update':
        #      return Recipe.objects.filter(owner=self.request.user)
        # return Recipe.objects.all()

User will get 404 response and will never be able to access objects other than he owns.
Second choice is permission class. You can define custom permission class and check ownership explicitly like this.
from rest_framework.permissions import BasePermission

class RecipeSubmissionPermission(BasePermission):
    def has_object_permission(self, request, view, obj):
        # you can also check permission here based on action
        # if view.action == 'update':
        #    pass
        return request.user.is_authenticated and obj.owner == request.user

class RecipeSubmissionViewSet(...):
    permission_classes=[RecipeSubmissionPermission]

In this case user will get 403 permission error.
If you use both of these methods. 404 will be preferred.
You can use whichever method you want or both of these. Permission class looks more programmatic and structured way of doing it but user will know that object with this id exists but he did not have permission to update it. But if you override queryset, user is not even be able to know if object exists or not thus more secure.

A: Are you using the django authentication system? Then you should be able to access request.user in the views and set the owner field accordingly.
EDIT: I think I misunderstood the question.
But this could help and Nafees Anwar looks good.

A: Nafees answer is pretty much the way to go.
I have been developing microservices with multitenancy to users and the rules for them(as per my projecs spec) are:

*

*Users cannot create items on behalf of another company/user

*Users cannot view/edit items belonging to another company.

The way I do this is simple.
To prohibit viewing/editing of someone else's stuff
def get_queryset(self):
    return self.queryset.filter(user=request.user)

And to prohibit editing of someone else's stuff, this is done on a serializer
class SomeSerializer(...):
    def validate(self, data):
        data.pop('user', None)
        data['user'] = self.context['request'].user

With the above, the get_queryset in the viewset will always return a 404 if user1 requests user2 info.
And the validate function will prevent assignment. Ie. If user1 creates something assigned to user2, it will rather assign user1, this behaviour is what I needed in my application, you can always raise serializers.ValidationError("You cannot assign stuff to user2") instead if thats what you need instead of reassigning the user as I do in my use case. With having this logic in the validate you can be sure that any writable function will always carry the same behaviour for that serializer.
Hope that this helps.


text:
Q: Trouble with CreateNewSite() bindings -- WMI -- IIS6 I am successfully creating new IIS 6 websites using the CreateNewSite() function, but would like to add an additional two hostname bindings (see below).
Questions:

*

*Does the CreateNewSite() function support multiple hostname bindings?

*If so, what is the syntax?  In all the example code I've found out there, I only find copies of the original MS code, with no examples of additional bindings, or even examples of modification functions.
I have already reviewed this blog page...
http://stweet.wordpress.com/2010/03/15/creating-a-new-website-programmatically-on-iis-using-asp-net/
... and while I saw something that looked like multiple domains, the code format was different, and so I'm not sure how it relates to the VBS I am using.
Thanks,
Mik

`
    Bindings = Array(0)
Set Bindings(0) = providerObj.get("ServerBinding").SpawnInstance_()
Bindings(0).IP = myIPnumber
Bindings(0).Port = "80"
Bindings(0).Hostname = WScript.Arguments(0)

' Create the new Web site using the CreateNewSite method of the IIsWebService object.
Dim strSiteObjPath
strSiteObjPath = serviceObj.CreateNewSite("RF_" & WScript.Arguments(0), Bindings, "D:\websites\" & WScript.Arguments(0) & "\httpdocs", WScript.Arguments(2))

`
The WScript.Arguments(2) is a custom IIS service number.


text:
Q: macro to showcase newly defined macros I have the following MWE which takes an argument and prints it verbatim. I have obtained the code from this answer.
\documentclass{article}
\makeatletter
\newcommand{\myverb}{%
    \begingroup
    % deactivate special characters
    \let\do\@makeother
    \dospecials
    % change '{' and '}' back to normal
    \catcode`\{=1
    \catcode`\}=2
    \@myverb%
}
\def\@myverb#1{%
    \endgroup%
    \texttt{#1}%
}
\makeatother
\begin{document}
\myverb{$\alpha$}
\end{document}

yields $\alpha$ on the page.
I want to define a macro \showcase which will print the code that was used for the text, and the evaluation of that code, namely
\newcommand\showcase[1]{\myverb{#1} #1}
\showcase{$\alpha$}

I expected this to print
$\alpha$ <actual-letter-alpha>

but instead it prints
<actual-letter-alpha> <actual-letter-alpha>

because the argument is expanded before it is taken by \myverb (I think).
What should I do to make the macro behave the way I want?
Note: I want to use this macro either inside a table or minipages, so that I can showcase the macros I have defined. So I need to be able to play with it, like put the column delimiter & between, or separate them into two minipage environments.

A: You need \meaning, something like
\documentclass{article}

\def\foo#1>{}

\newcommand\showcase[1]{%
\def\tmp{#1}%
\texttt{\expandafter\foo\meaning\tmp} #1}

\begin{document}

\showcase{$\alpha$}

\end{document}


text:
Q: ANTLR4 no error messages while converting my grammar the last few days/weeks I wrote ANTLR4 grammar and used it in my Javascript-React project.
While using the javascript runtime ( see here ), my console (powershell) always gave me an error message when my grammar was false or something was missing.
Now I'm out of town for a few weeks and had to install ANTLR4 + runtime on my laptop ( scroll down to WINDOWS for the tutorial I used ). This CLASSPATH stuff didn't worked for me, so I ignored it and .bat script didn't  worked for me either, like when I installed it for the first time.
My file structure looks like this:

When I go into my powershell and switch to the right folder and hit
.\antlr-4.11.1-complete.jar -Dlanguage=JavaScript .\FunktionLexer.g4

everything works fine and I have my token for the parser. This is probably exact the same installation I had before going out of town.
But when I use wrong grammar and hit the command just nothing happens. Like nothing, no output on my command line what could be wrong. I tryed to add parameter like -Xlog, which gives me a log until the grammar crashes, but it doesn't really tell me where it crashed.
Thanks in advance!

A: Given the grammar (without lexer rules):
grammar FunktionLexer;

parse
 : .*? EOF
 ;

I can generate a lexer and parser just fine by running:
java -jar antlr-4.11.1-complete.jar -Dlanguage=JavaScript FunktionLexer.g4

You might want to edit your question and clearly indicate how someone can reproduce what you describe.


text:
Q: How could factordb apply the p-1-method on this number? The following partial factorization
http://factordb.com/index.php?id=1100000001285565404
was used by factordb to prove this number ($\ 32^{2133}+4^{2133}+1\ $) to be prime.
http://factordb.com/index.php?query=32%5E2133%2B4%5E2133%2B1
What confuses me : I only know a variant of the p-1-method , where $n-1=FG$ where $F$ is completely factored and we have $F>G$. This is apparently not the case in the given factorization.

So how could factordb prove the primality with the $p-1$-method ?


text:
Q: MariaDB: delete row by using table alias doesn´t work having a statement like this:

DELETE FROM ek_stockvalue lw WHERE lw.id_stockvalue = 6

seems to run in an error in MariaDB. If i remove the "lw"-tablealias, it works:

DELETE FROM ek_stockvalue WHERE id_stockvalue = 6

A: In MariaDB's documentation nothing is mentioned, see DELETE, however, in MySQL's documentation the following is indicated, see 13.2.2 DELETE Syntax:

Note
If you declare an alias for a table, you must use the alias when
  referring to the table:
DELETE t1 FROM test AS t1, test2 WHERE ...

Try:
DELETE `lw` FROM `ek_stockvalue` `lw`
WHERE `lw`.`id_stockvalue` = 6;

See dbfiddle.

A: Nest a select statement into your delete statement like this (where I assume that your table has an identifying column named 'id'). Then you can use alias within the select statement:
DELETE FROM ek_stockvalue WHERE id in (
    SELECT id FROM ek_stockvalue lw WHERE lw.id_stockvalue = 6
)


text:
Q: Setting up GATT server using bluetoothctl tool I'm able to set up GATT services and characteristics with the
latest bluetoothctl tool using the following commands:
register-service,
register-characteristic,
register-application
I was just wondering if there is a way to define GATT-based service
for use only over the BR/EDR transport or LE transport using the
bluetoothctl tool or any Bluez utility tool? Can anyone shed some
light on this?

A: Theoretically speaking, the GATT layer should be agnostic of whether BLE or BR/EDR is used. You can test this by disabling BLE through the following commands:-
#btmgmt power off
#btmgmt le off
#btmgmt power on

After that you can use something like gatttool from a remote device to check if you can see the services/characteristics that you have created using the bluetoothctl commands that you listed earlier.
I hope this helps.


text:
Q: How to get the count of element with non-empty-array-field when group in mongodb aggregate using Spring Data Mongo? I have the following documents in one collection named as mail_test. Some of them have a tags field which is an array:
/* 1 */
{
    "_id" : ObjectId("601a7c3a57c6eb4c1efb84ff"),
    "email" : "aaaa@bbb.com",
    "content" : "11111"
}

/* 2 */
{
    "_id" : ObjectId("601a7c5057c6eb4c1efb8590"),
    "email" : "aaaa@bbb.com",
    "content" : "22222"
}

/* 3 */
{
    "_id" : ObjectId("601a7c6d57c6eb4c1efb8675"),
    "email" : "aaaa@bbb.com",
    "content" : "33333",
    "tags" : [
        "x"
    ]
}

/* 4 */
{
    "_id" : ObjectId("601a7c8157c6eb4c1efb86f4"),
    "email" : "aaaa@bbb.com",
    "content" : "4444",
    "tags" : [
        "yyy",
        "zzz"
    ]
}

There are two documents with non-empty-tags, so I want the result to be 2.
I use the the following statement to aggregate and get the correct tag_count:
db.getCollection('mail_test').aggregate([{$group:{
    "_id":null,
    "all_count":{$sum:1},
    "tag_count":{"$sum":{$cond: [ { $ne: ["$tags", undefined] }, 1, 0]}}
    //if replace `undefined` with `null`, I got the tag_count as 4, that is not what I want
    //I also have tried `$exists`, but it cannot be used here.
}}])

and the result is:
{
    "_id" : null,
    "all_count" : 4.0,
    "tag_count" : 2.0
}

and I use spring data mongo in java to do this:
private void test(){
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(new Criteria()),//some condition here
                Aggregation.group(Fields.fields()).sum(ConditionalOperators.when(Criteria.where("tags").ne(null)).then(1).otherwise(0)).as("tag_count")
                //I need an `undefined` instead of `null`,or is there are any other solution?
        );
        AggregationResults<MailTestGroupResult> results = mongoTemplate.aggregate(agg, MailTest.class, MailTestGroupResult.class);
        List<MailTestGroupResult> mappedResults = results.getMappedResults();
        int tag_count = mappedResults.get(0).getTag_count();
        System.out.println(tag_count);//get 4,wrong
    }

I need an undefined instead of null but I don't know how to do  this,or is there are any other solution?

A: You can use Aggregation operators to check if the field tags exists or not with one of the following constructs in the $group stage of your query (to calculate the tag_count value):
"tag_count":{ "$sum": { $cond: [ { $gt: [ { $size: { $ifNull: ["$tags", [] ] }}, 0 ] }, 1, 0] }}

// - OR -

"tag_count":{ "$sum": { $cond: [ $eq: [ { $type: "$tags" }, "array" ] }, 1, 0] }

Both, return the same result (as you had posted).


text: Q: Как можно сэмулировать браузер сафари на виндовс Всем привет, хотел узнать , есть ли способы сэмулировать сафари браузер на виндовс? Порой бывает что занимаюсь версткой, и на винде во всех браузерах все хорошо, а на маках в Сафари браузере постоянно какая-то фигня происходит.


text:
Q: Checking for duplicate cron jobs We are deploying code to our application server environment, and part of that process is creating a number of cron jobs on the server. When code gets pushed, our deployment script creates the required cron jobs without a problem using the following:
CRON_FILE=$SCRIPT_DIR/cron.txt
if [[ ! -f "$CRON_FILE" ]]; then
        printf "Cron template file missing!\n\n"
        exit 1
fi
while read LINE || [[ -n "$LINE" ]]; do
        printf "\n> Adding cron job \"$LINE\"\n"
        crontab -l | { cat; echo "$LINE"; } | crontab -
done < $CRON_FILE

The issue is that after the initial deployment, additional deployments are creating duplicate cron jobs.
Any pointers on how to detect if a cron job already exists?

A: When you add your cron job, include a comment with a unique label. Later you can use that unique label to determine if the cron job exists or not, and also to "uninstall" the cron job.
I do this all the time. I have a reusable script for this:
#!/bin/sh
#
# Usage:
# 1. Put this script somewhere in your project
# 2. Edit "$0".crontab file, it should look like this,
#    but without the # in front of the lines
#0  *   *   *   *   stuff_you_want_to_do
#15 */5 *   *   *   stuff_you_want_to_do
#*  *   1,2 *   *   and_so_on
# 3. To install the crontab, simply run the script
# 4. To remove the crontab, run ./crontab.sh --remove
#

cd $(dirname "$0")

test "$1" = --remove && mode=remove || mode=add

cron_unique_label="# $PWD"

crontab="$0".crontab
crontab_bak=$crontab.bak
test -f $crontab || cp $crontab.sample $crontab

crontab_exists() {
    crontab -l 2>/dev/null | grep -x "$cron_unique_label" >/dev/null 2>/dev/null
}

# if crontab is executable
if type crontab >/dev/null 2>/dev/null; then
    if test $mode = add; then
        if ! crontab_exists; then
            crontab -l > $crontab_bak
            echo 'Appending to crontab:'
            cat $crontab
            crontab -l 2>/dev/null | { cat; echo; echo $cron_unique_label; cat $crontab; echo; } | crontab -
        else
            echo 'Crontab entry already exists, skipping ...'
            echo
        fi
        echo "To remove previously added crontab entry, run: $0 --remove"
        echo
    elif test $mode = remove; then
        if crontab_exists; then
            echo Removing crontab entry ...
            crontab -l 2>/dev/null | sed -e "\?^$cron_unique_label\$?,/^\$/ d" | crontab -
        else
            echo Crontab entry does not exist, nothing to do.
        fi
    fi
fi

Save the script as crontab.sh in your project directory, and create a crontab.sh.crontab with your cron job definitions, for example:
0 0 * * * echo hello world
0 0 * * * date

*

*To install your cron jobs, simply run ./crontab.sh

*The script is safe to run multiple times: it will detect if the unique label already exists and skip adding your cron jobs again

*To uninstall the cron jobs, run ./crontab.sh --remove
I put this on GitHub too: https://github.com/janosgyerik/crontab-script
Explanation of sed -e "\?^$cron_unique_label\$?,/^\$/ d":

*

*In its simplest form the expression is basically: sed -e '/start/,/end/ d'

*It means: delete the content between the lines matching the start pattern and the end pattern, including the lines containing the patterns

*The script quotes the sed command with double-quotes instead of single quotes, because it needs to expand the value of the $cron_unique_label shell variable

*The start pattern \?^$cron_unique_label\$? uses a pair of ? instead of / to enclose the pattern, because $cron_unique_label contains /, which would cause problems

*The starting ? must be escaped with a backslash, but to be honest I don't know why.

*The ^ matches start of the line and $ end of the line, and the $ must be escaped, otherwise the shell would expand the value of the $? shell variable

*The end pattern /^\$/ is relatively simple, it matches a start of line followed by end of line, in other words an empty line, and again the $ must be escaped

*The d at the end is the sed command, to delete the matched lines, effectively removing it from the content of crontab -l, which we can pipe to crontab -

A: Weird, but very thorough answers. IMO overly complex.
Here's a decent one liner for anyone coming to this for a 2017 answer:
crontab -l | grep 'match-your-cronjob-search' || (crontab -l 2>/dev/null; echo "* * * * * /bin/cronjobCommandYouWant >> /dev/null 2>&1") | crontab -

Works great for us to not have dupe crons.
And here's the edited script from the original poster:
    CRON_FILE=$SCRIPT_DIR/cron.txt
if [[ ! -f "$CRON_FILE" ]]; then
        printf "Cron template file missing!\n\n"
        exit 1
fi
while read LINE || [[ -n "$LINE" ]]; do
        printf "\n> Adding cron job \"$LINE\"\n"
        crontab -l | grep "$LINE" || (crontab -l 2>/dev/null; echo "$LINE") | crontab -
done < $CRON_FILE

A: Your script janos is awesome, works perfectly and was exactly what i was looking for with one little glitch.
I couldnt manage multiple xxx.crontab templates.
Your script worked fine and i added it to my bootstrapping routines with a little modification so i can pass a first parameter $1 of the xx.crontab filename and second parameter $2 can be the removal.
I have parent shell scripts which then conditional decide, which, all or combination of crontab files i want to add/remove.
Here the script with my modifications included:
#!/bin/sh
#
# Usage:
# 1. Put this script somewhere in your project
# 2. Edit "$1".crontab file, it should look like this,
#    but without the # in front of the lines
#0  *   *   *   *   stuff_you_want_to_do
#15 */5 *   *   *   stuff_you_want_to_do
#*  *   1,2 *   *   and_so_on
# 3. To install the crontab, run ./crontab.sh <nameOfCronTabfile>
# 4. To remove the crontab, run ./crontab.sh <nameOfCronTabfile> --remove

cd $(dirname "$0")

test "$2" = --remove && mode=remove || mode=add

cron_unique_label="# cmID:$PWD|$1#"

crontab="$1".crontab
crontab_bak=$crontab.bak
test -f $crontab || cp $crontab.sample $crontab

crontab_exists() {
    crontab -l 2>/dev/null | grep -x "$cron_unique_label" >/dev/null 2>/dev/null
}

# if crontab is executable
if type crontab >/dev/null 2>/dev/null; then
    if test $mode = add; then
        if ! crontab_exists; then
            crontab -l > $crontab_bak
            echo 'Appending to crontab:'
            echo '-----------------------------------------------'
            cat $crontab
            crontab -l 2>/dev/null | { cat; echo; echo $cron_unique_label; cat $crontab; echo "# cm #"; } | crontab -
        else
            echo 'Crontab entry already exists, skipping ...'
            echo
        fi
        echo '-----------------------------------------------'
        echo "To remove previously added crontab entry, run: $0 $1 --remove"
        echo
    elif test $mode = remove; then
        if crontab_exists; then
            echo 'Removing crontab entry ...'
            crontab -l 2>/dev/null | sed -e "\?^$cron_unique_label\$?,/^# cm #\$/ d" | crontab -
        else
            echo 'Crontab entry does not exist, nothing to do.'
        fi
    fi
fi

UPDATE:
Sry, didnt noticed the weak empty line pattern for removing a crontab. Simply would delete everything after the found crontab id, including manually added crontabs.
Changed the empty line end pattern to a little end tag.
So it will add crontabs with:
crontab -l 2>/dev/null | { cat; echo; echo $cron_unique_label; cat $crontab; echo "# cm #"; } | crontab -

.. and removing exactly only this cron with:
crontab -l 2>/dev/null | sed -e "\?^$cron_unique_label\$?,/^# cm #\$/ d" | crontab -

A: We can also do it in code:
first in bash, check the manual:  man 2 open:
int fd = open('/tmp/1.txt', O_CREAT|O_EXCL)
if (fd === -1) {
   print "job exist"
   exit(1)
}
//unlink()
// your code

Js version:
const fs = require('fs')
try {
const fd = fs.openSync('/tmp/1.txt', 'wx')
} catch(err) {
  console.log('job exist')
  process.exit(0)
}

fs.unlinkSync('/tmp/1.txt')
fs.appendFileSync(fd, 'pid', 'utf8');


text:
Q: How to pass information between spring-integration components? In spring-batch, data can be passed between various steps via ExecutionContext. You can set the details in one step and retrieve in the next. Do we have anything of this sort in spring-integration ?
My use case is that I have to pick up a file from ftp location, then split it based on certain business logic and then process them. Depending on the file names client id would be derived. This client id would be used in splitter, service activator and aggregator components.
From my newbie level of expertise I have in spring, I could not find anything which help me share state for a particular run.I wanted to know if spring-integration provides this state sharing context in some way.
Please let me know if there is a way to do in spring-context.

A: In Spring Integration applications there is no single ExecutionContext for state sharing. Instead, as Gary Russel mentioned, each message carries all the information within its payload or its headers.
If you use Spring Integration Java DSL and want to transport the clientId by message header you can use enrichHeader transformer. Being supplied with a HeaderEnricherSpec, it can accept a function which returns dynamically determined value for the specified header. As of your use case this might look like:
return IntegrationFlows
    .from(/*ftp source*/)
    .enrichHeaders(e -> e.headerFunction("clientId", this::deriveClientId))
    ./*split, aggregate, etc the file according to clientId*/

, where deriveClientId method might be a sort of:
private String deriveClientId(Message<File> fileMessage) {
  String fileName = fileMessage.getHeaders().get(FileHeaders.FILENAME, String.class);
  String clientId = /*some other logic for deriving clientId from*/fileName;
  return clientId;
}

(FILENAME header is provided by FTP message source)
When you need to access the clientId header somewhere in the downstream flow you can do it the same way as file name mentioned above:
String clientId = message.getHeaders().get("clientId", String.class);

But make sure that the message still contains such header as it could have been lost somewhere among intermediate flow items. This is likely to happen if at some point you construct a message manually and send it further. In order not to loose any headers from the preceding message you can copy them during the building:
  Message<PayloadType> newMessage = MessageBuilder
      .withPayload(payloadValue)
      .copyHeaders(precedingMessage.getHeaders())
      .build();

Please note that message headers are immutable in Spring Integration. It means you can't just add or change a header of the existing message. You should create a new message or use HeaderEnricher for that purpose. Examples of both approaches are presented above.

A: Typically you convey information between components in the message payload itself, or often via message headers - see Message Construction and Header Enricher


text:
Q: OnSharedPreferenceChangeListener implementation I have a listView activity and need to apply and save some preferences made by user.
Each row of my ListView contains of two TextViews (year and country).
I handle onSharedPreferenceChanged event this way:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.
        OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs,
            String key) {
        TextView year = (TextView) findViewById(R.id.year);
        year.setTextSize(Float.parseFloat(prefs.getString(key, null)));
        TextView country = (TextView) findViewById(R.id.country);
        country.setTextSize(Float.parseFloat(prefs.getString(key, null)));
    }
});

But the changes are applied only for the first row, the others stay the same as before.
What should I do to apply new settings for each row of the list? Thanks for your answers.

A: Change your code to :
OnSharedPreferenceChangeListener listener; // class field

// in onResume()
SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(this);
listener = new SharedPreferences.
        OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs,
            String key) {
        TextView year = (TextView) findViewById(R.id.year);
        year.setTextSize(Float.parseFloat(prefs.getString(key, null)));
        TextView country = (TextView) findViewById(R.id.country);
        country.setTextSize(Float.parseFloat(prefs.getString(key, null)));
    }
};
prefs.registerOnSharedPreferenceChangeListener(listener);
// unregister in onPause()

For an explanation see here


text:
Q: Rails active_model_serializers on polymorphic nested association after setup the gem i've tried to get a deep nested polymorphic  associated data.
but the gem just render the 1 level associated data.
the serializer
class CommentsSerializer < ActiveModel::Serializer
  attributes :id, :title, :body, :user_id, :parent_id, :commentable_id, :commentable_type

  belongs_to :user
  belongs_to :commentable, :polymorphic => true
end

After some research
on the active_model_serializers github doc page
i've tried this solution, and did not worked either
has_many :commentable

def commentable
  commentable = []
  object.commentable.each do |comment|
    commentable << { body: comment.body }
  end
end

please someone can spare a tip on this issue?
and for some that should i use
ActiveModel::Serializer.config.default_includes = '**'

i've tried already this config too
The screeshot below illustrate this case

this comment has many reply's by commentable, but just render one. i would like to render the rest of comments of this comment.

A: You need to properly define your serializers and be careful not to render everything recursively. I have setup these 2 models:
class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

And these serializers:
class CommentSerializer < ActiveModel::Serializer
  attributes :id, :body

  belongs_to :commentable, serializer: CommentableSerializer
end

class CommentableSerializer < ActiveModel::Serializer
  attributes :id, :body

  has_many :comments, serializer: ShallowCommentSerializer
end

class ShallowCommentSerializer < ActiveModel::Serializer
  attributes :id, :body
end

You need another serializer for all comments of a post, so that the comments don't try to render the post, which would try to render the comments, etc...
Keep your
ActiveModel::Serializer.config.default_includes = '**'

config option turned on.
Calling http://localhost:3000/comments/1 yields:
{
  "id": 1,
  "body": "comment",
  "commentable": {
    "id": 1,
    "body": "post",
    "comments": [
      {
        "id": 1,
        "body": "comment"
      },
      {
        "id": 2,
        "body": "Reply comment"
      }
    ]
  }
}

which, I believe, is what you were trying to achieve.


text:
Q: Tor not working after update Yesterday I updated my Ubuntu 14.04 LTS and after that Tor stopped working :
When I try to run Tor using command
sudo service tor start it gives an error
aa-exec: ERROR: profile 'system_tor' does not exist

prior to the update everything was working fine.

A: First of all, check if the file /etc/apparmor.d/system_tor exists.
I suppose it does not, because it was removed somehow and therefore the warning that it does not exist anymore.
/etc/apparmor.d/system_tor is provided by package tor in ubuntu.
(see http://packages.ubuntu.com/trusty/amd64/tor/filelist)
So simply reinstall tor from the official software sources and everything should be fine.

A: I have the same issue but I just checked and /etc/apparmor.d/system_tor is present in my system.
What it looks to be the cause of the problem is the init script /etc/init.d/tor that is calling aa-exec in a wrong way ( at least it is not working ):
Solution:

*

*Edit /etc/init.d/tor

*At line 159 you should have this:
AA_EXEC_ARGS="--profile=system_tor -- $DAEMON"
Change it with
AA_EXEC_ARGS="-f system_tor -- $DAEMON"
Now the service load fine for me but I have to say I don't know the difference between -f and --profile option.


text:
Q: Where do I put my snaplets? I'm new to Haskell and Snap and I want to write a simple bug-tracking application. I set up a Snap project using $ snap init and it works. The problem is that I don't know how to go any further.
I want to create a snaplet Tickets that uses a database to store bug reports, and use that snaplet in my main web application.
I read the documentation about snaplets but I couldn't figure out where to put their source code (in the /snaplets directory, I suppose? If so, how do I load them?). Could anybody point me in the right direction?

A: Are you sure you need to create a separate snaplet for Tickets? The snaplet infrasructure is meant for reusable components such as session management, authentication, database access, admin panels, user management, etc.
Are you going to be using your Tickets self-contained module across multiple web applications? If so, then by all means go ahead and create a snaplet.
In any case, it sounds to me like you are at least in part asking how to organize a project with multiple "modules" or "parts" while using snap. I'll try to address this below. Please let me know if you feel I have missed the mark.
Assuming you don't need to create a separate snaplet for Tickets:
For functionality specific to a single site, I think you would be better off creating a few modules and developing the code for the functionality right inside your current application's package and module hierarchy. Here are a few points on how I have been organizing my snap projects of late:

*

*I put my database-related code under modules in MyApp.DB.
namespace. You could have a MyApp.DB.Tickets that contains all
database calls needed for operation on your Tickets module.

*I put all UI-related functionality under MyApp.UI. namespace. You
could put a MyApp.UI.Tickets module that contains your Handlers,
your Splices, your Forms and so on.

*To handle forms, I use the excellent digestive-functors library. You may find this blog post helpful if you don't know them already.

*I usually have a shared UI helper library under MyApp.UI.Helpers where I place common code used across all/most UI modules.

*I usually have a shared Form helper library under MyApp.UI.Forms

*Any code tangential to the fact that my application exposes a Web UI goes outside the MyApp.UI. namespace. So if my application needs to perform some offline analyses, I may put them under the MyApp.Analysis. namespace.
Once you define and export your Handlers under MyApp.UI.Tickets, you can go to your Site.hs file and wire them into your application at specific routes.
For inspiration on how to handle database connections, you can check out the postgresql-simple snaplet.
However, if you do need to create a snaplet:
A snaplet is simply a stand-alone application that uses the Snap.Snaplet infrastructure,  (typically) has its own .cabal file and (typically) is its own Haskell package. Snap then gives you a way to embed or nest this re-usable, self-contained application in yet another snap application. Think a hierarchy of Russian dolls.
Assuming you performed something similar to what I described in the section above, you are now 95% ready to convert to a snaplet. Just name your application snaplet-tickets, expose a SnapletInit using makeSnaplet and use nestSnaplet in another snap application to include this reusable piece of functionality right there.


text:
Q: Rspec Devise Sign in I trying to sign in my admin so as to test the controller specs in rspec
I did my best  to follow the instruction mention over here but it seem that I missed something because of which the admin is still not able to login resulting in my controller spec to fail
Here my code
## spec/spec_helper.rb
RSpec.configure do |config|
   config.include Devise::TestHelpers, :type => :controller
   config.extend ControllerMacros, :type => :controller
end

## spec/support/controller_macros.rb
module ControllerMacros
  def login_admin
    before(:each) do
      @request.env['devise.mapping'] = Devise.mappings[:admin]
      admin = Admin.create(first_name: 'Admin',
        last_name: 'User',
        email: 'admin@poaster.me',
        password: 'admin1234',
        password_confirmation: 'admin1234',
        active: true
      )
      admin.confirmed_at = Time.now
      admin.confirm!
      sign_in admin
      ## Did an idependent test over here using binding.pry not sure why
      # binding.pry
      # session  => {"warden.user.admin.key"=>[[27], "$2a$04$6KicZPZUvYxOBiMadVyIqe"]}
      # request['env'].warden.user => nil
      # request['env'].warden.authenticated? => false
    end
  end
end

The output that see in session inside my controller spec
{"flash"=>
  #<ActionDispatch::Flash::FlashHash:0x007f9bee570738
   @closed=false,
   @flashes={:alert=>"You have to confirm your account before continuing."},
   @now=nil,
   @used=#<Set: {}>>}

Controller Spec
   ## spec/controllers/users_controller_spec.rb
   login_admin
   describe UsersController do
     context 'GET users/index' do
       it 'render users index pages' do
         get :index
         #binding.pry
         #session =>  {"flash"=> #<ActionDispatch::Flash::FlashHash:0x007f9bee570738 @closed=false,@flashes={:alert=>"You have to confirm your account before continuing."},@now=nil,@used=#<Set: {}>>}

         expect(response).to render_template('index')
        end
      end
    end

Controller Code
## app/controllers/users_controller.rb
class UsersController < ApplicationController
  before_filter :authenticate_admin!
  before_filter :require_admin?, :only => [:deactivate, :activate, :index]
  def index
    page = params[:page] || 1
    @users  = User.includes(:company).where(roles_mask: 1) params[:page])
    @users = @users.page(page).per(10)
  end
end

A: Found it seem the issue was because I was doing this
admin.confirmed_at = Time.now
I turn using only
admin.confirm! plainly work out of box


text:
Q: Simple controller functional test failing This is my first Controller unit test for Symfony2. Copying as fully as I can from the Docs, I'm simply asserting the inclusion of some text.
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class AdviseeControllerTest extends WebTestCase
{
    public function testCreatePageContainsContent()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/create/adviseeSet');

        $this->assertGreaterThan(
            0,
            $crawler->filter('html:contains("Name")')->count()
        );

    }
}

My route is as follows:
advisee_set_create:
    pattern: /create/adviseeSet
    defaults: { _controller: AcademicsBundle:Advisee:create }

This test fails, along with any other test that asserts the inclusion of any kind of content. is there something I'm ignorant about how $client->request() or $crawler->filter() works that copying from the Default example is not passing? My Test lives in AcademicsBundle > Tests > AdviseeControllerTest.php
Outputted message(with both --verbose and -debug) is:
...\AcademicsBundle\Tests\Controller\AdviseeControllerTest::testCreatePageContainsContent
Failed asserting that 0 is greater than 0.

A: My crawler needed to follow redirects, so I added:
    $client->followRedirect();

By testing
    $content = $client->getResponse()->getContent();
    $this->assertEquals('shmee', $content);

I was able to get a much more helpful failure message
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'shmee'
+'<!DOCTYPE html>
+
+
+        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+        <meta http-equiv="refresh" content="1;url=http://localhost/create/adviseeSet" />
+
+        <title>Redirecting to http://localhost/create/adviseeSet</title>
+
+
+        Redirecting to http://localhost/create/adviseeSet.
+
+'

And I saw the shortened path in the attempted redirect.


text:
Q: How to select elements like question1, question2, question3,... in JQuery form validation plug-in? I am using jQuery and the jQuery Validation plugin to validate inputs. Below is the code. Now there are many inputs named like question1, question2, question3, question4,... How can I place validation on them? I mean how to select them all together?
$(document).ready(function() {
    $("#item").validate({
        rules: {
            title: {
                required: true,
                minlength:40
            },
            content: {
                required: true,
                minlength:100,
                maxlength:2000
            }
        },
        messages: {
        }
    });
});

The code:
 $("input[name^='question']"): {
            required: true,
             minlength:40

        }

does not work.

A: Several ways. You can use the comma separator:
$("#question1, #question2, #question3")...

You can use add():
$("#question1").add("#question2").add("#question3")..

If question1 is a name and not an ID, use an attribute selector:
$(":input[name^=question]")...

But I would recommend using a class:
<input type="text" name="question1" class="question">
<input type="text" name="question2" class="question">
<input type="text" name="question3" class="question">

with:
$(":input.question")...

A: Assuming you mean <input type="text" name="question1" />, then try the following jquery selector:
$("input[name^='question']");

It will return a list of all of those elements.
This is how to do it (assuming the code you posted works for one element):
$(document).ready(function() {
    $("input[name^='question']").validate({
        rules: {
            title: {
                required: true,
                minlength:40
            },
            content: {
                required: true,
                minlength:100,
                maxlength:2000
            }
        },
        messages: {
        }
    });
});


text:
Q: Make base class variant over base classes I have two (non-trivial) classes like this:
class MyClass(Base):
    def __init__(self, etc, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.etc = etc

    def do_something(self, arg1, arg2):
        # not actually a function call, just to make this as minimal as possible
        output = computation_with_a_bunch_of_code(arg1, arg2)
        return super().do_something(output)

Don't get too attached to the exact format, the super call may be in the really long computation (possibly multiple times), but the only difference is the super delegated to.
I've tried looking at related questions and none quite did what I wanted. For instance, This recommended one with multiple inheritance doesn't rely on super calls the way mine does.
While I'd love to just instantiate base like an object like so:
class MyFakeBaseClass:
    def __init__(self, etc, base):
        self.base = base
        self.etc = etc

    def do_something(self, arg1, arg2):
        output = computation_with_a_bunch_of_code(arg1, arg2)
        return self.base.do_something(output)

The library I'm using requires the ultimate base class of whatever I pass in to be one of its base classes (I think it uses metaclass subtyping magic to do things to your overridden methods, because duck typing doesn't generally work). While I could use the API's lowest level abstract class as my base, I'd have to do a lot of legwork to manually override a ton of methods with self.base.method() which would end up being about as much boilerplate code as normal code I'm replacing anyway, and a nightmare to read.
My ideal solution would look something like:
class _BaseClass(???):
    def __init__(self, etc, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.etc = etc

    def do_something(self, arguments):
        arguments = computation_with_a_bunch_of_code()
        return super().do_something(arguments)

class RealOne(_BaseClass(SuperOne)): pass

class RealTwo(_BaseClass(SuperTwo)): pass

I've tried typing.Generic since on the surface it seemed similar from examples, but given a Generic[T], it doesn't seem to use T as a real concrete super class when calling super. And on further research, it appears you can't really use it this way anyway, due to when the relevant values are set if nothing else.
Currently I've settled on:
def _actually_do_something(base, obj, arg1, arg2):
    output = computation_with_a_bunch_of_code(arg1, arg2)
    return base.do_something(output)

class MyClass(Base):
    # ... etc ...
    def do_something(self, arg1, arg2):
        base = super()
        return _actually_do_something(base, self, arg1, arg2)

Which is fine, but with multiple methods doing this it's a lot of boilerplate, and a frustrating amount of indirection, somewhat to me, but definitely to other people working on this who I've shown it to. It's not completely unmaintainable, but if one exists I'd like a cleaner solution.
It seems to me that the only other solution within my (unfortunate) constraints is metaclasses, but I couldn't find anything that quite did what I wanted. Most examples were either trivial (setting an attribute), or didn't specify how to use a dynamic base class. I'd welcome a simpler solution even more, but as far as I can tell decorators and the like can't quite do this. PEP 638 (Syntactic Macros) seems like it'd be an easy avenue to what I want, but as far as I can tell it's not implemented yet, and I'm unfortunately tied to environments that don't have 3.9 available yet anyway if it is (I'm stuck on 3.6, specifically). It's possible the answer is "just do what you're doing now and update to that whenever it comes out," but again, if there's something relatively simple, compact, and nice looking I'm missing I'd like to know.


text:
Q: Group By Linq ASP.NET I currently display a list of errors from a database. As you can see from the image below, there are a number of errors that share the same Application Name.
I am wanting to group all the errors with the same name together and just show the one error with that application name instead of all of them.
I have looked at other questions on here related to what I am doing but none of them have given me the answer I require.
This is my current code.
Controller
public ActionResult Index(string sortOrder, string searchString, string currentFilter, int? page)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

        if (searchString != null)
        {
            page = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        ViewBag.CurrentFilter = searchString;

        var applications = from s in db.ElmahErrors
                     select s;

        if (!String.IsNullOrEmpty(searchString))
        {
            applications = applications.Where(s => s.Application.Contains(searchString));
        }

        switch (sortOrder)
        {
            default:
                applications = applications.OrderBy(x => x.Application).ThenByDescending(s => s.TimeUtc);
                break;
        }

        int pageSize = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultPageSize"]);
        int pageNumber = (page ?? 1);
        return View(applications.ToPagedList(pageNumber, pageSize));
    }

View
@model PagedList.IPagedList<DataIntelligence.Models.ElmahError>
@using PagedList.Mvc;
<link href="Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "Application Error Dashboard";
}

Application Error Dashboard

@using (Html.BeginForm("Index", "Application", FormMethod.Get))
{

        Find by Application: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />

}

            Application

            Host

            Type

           Date

            Message

@foreach (var item in Model) {

             @Html.DisplayFor(modelItem => item.Application)

            @Html.DisplayFor(modelItem => item.Host)

            @Html.DisplayFor(modelItem => item.Type)

            @Html.DisplayFor(modelItem => item.TimeUtc)

            @Html.DisplayFor(modelItem => item.Message)

}

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of     @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

How would I go about changing this code in order to achieve what I am wanting?
Thanks in advance.

A: If you replace:
var applications = from s in db.ElmahErrors
                 select s;

With:
var applications = db.ElmahErrors
  .GroupBy(s => s.Application)
  .Select(grp => grp.FirstOrDefault());

Then the query will only deal with one element for each application.
You might also wish to do this grouping at a later state, if there were elements in ElmahErrors you wanted to filter out, on some other criteria, to make sure you didn't happen to filter out the distinct item chosen when there was another item with the same Application that wouldn't have been filtered.

A: You should take a look at 'MoreLinq', perhaps their DistinctBy provides the answer you need. It is available in NuGet.
MoreLINQ's DistinctBy for C#
Should work something like this:
List<ElmahErrors> distinctByError = db.ElmahErrors.DistinctBy(x => x.Message).ToList();

A: Try this query
var applications = from s in db.ElmahErrors
 group c by new
    {
        s.Application,
        s.Host,
        s.Type,
        s.Date,
        s.Message
    } into gcs
    select new ElmahErrors()
    {
        gcs.key.Application,
        gcs.key.Host,
        gcs.key.Type,
        gcs.key.Date,
        gcs.key.Message
    };

A: var results = from a in applications
              group a by a.Application into g
              select new { Application = g.Key, Count = g.Count(), LastDate = g.Max(d=>d.Date) };

Or if you want to group by more coulms:
 var results = from a in applications
                  group a by new {a.Application, a.Message} into g
                  select new { Application = g.Key.Application, Message = g.Key.Message, Count = g.Count(), LastDate = g.Max(d=>d.Date) };


text:
Q: Разница между row_number, limit или rownum в разных базах данных Разные базы данных предлагают разные варианты ограничения результата выборки по количеству записей.
Например, в PostgreSQL это limit, в Oracle может использоваться rownum. Но при этом есть row_number теоретически поддерживаемый всеми базами данных.
Есть ли разница между использованием специфичного варианта на каждой базе данных или же использованием общего row_number для всех, не задумываясь о типе базы данных?
То есть, возможно, под капотом базы реализуют эти варианты одинаково или же какие-то из вариантов заметно лучше, какие-то заметно хуже.


text:
Q: Can I embed a twitter feed in my email? I'm about to send out an email campaign to my clients. The email will be sent in HTML format, and I wanted to embed a twitter feed in my email, similar to the twitter widgets you see embedded in blogs and websites everywhere. When I copy and paste the code generated through the twitter website, my email doesn't render anything :(
Any ideas if this is possible? Thanks! Here's the code twitter generated:
<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'faves',
  rpp: 5,
  interval: 6000,
  title: 'The best of Twitter according to',
  subject: 'My Tweets',
  width: 250,
  height: 300,
  theme: {
    shell: {
      background: '#8540c2',
      color: '#ffffff'
    },
    tweets: {
      background: '#ffffff',
      color: '#444444',
      links: '#43c43f'
    }
  },
  features: {
    scrollbar: true,
    loop: false,
    live: true,
    hashtags: true,
    timestamp: true,
    avatars: true,
    behavior: 'all'
  }
}).render().setUser('maryamKE').start();
</script>

A: There is no standard for HTML email, and most email clients sensibly reject JavaScript.  I recommend you link to a page on your web site.

A: There is no good way to accomplish this with the embeds provided directly from Twitter.
This was a need I also had and created a service that makes it extremely easy: https://www.widgmail.com/


text:
Q: Does MS T-SQL include a data type called varchar2? and if so, what's the difference between it and between varchar? Had this question in an interview.

A: No.  varchar2 is an Oracle datatype, equivalent to its (as well as TSQL's) own varchar.
CLARIFICATION
The differentiation between Oracle's varchar and varchar2 seems to have originated back when the ANSI SQL standard was still being formulated.  I cannot locate any definitive references as to what exactly the implementation differences, if any, were initially (pre-Oracle 7), as this remains a source of confusion.  Suffices to say that the two are practically treated as synonyms since Oracle 7.  Both suffered improvements (maximum size went from 2k to 4k) in release 8.  Note that TSQL's varchar can store 8k.

A: I've never heard Vlad's suggestion that the VARCHAR data type used to only support 2k of data.  Given that they are synonymous in every release since 8.1.7 (I haven't checked the documentation for earlier releases), that seems odd to me.  Vlad, do you have a reference for that?
From the SQL Reference section on the VARCHAR data type

The VARCHAR datatype is currently
  synonymous with the VARCHAR2 datatype.
  Oracle recommends that you use
  VARCHAR2 rather than VARCHAR. In the
  future, VARCHAR might be defined as a
  separate datatype used for
  variable-length character strings
  compared with different comparison
  semantics.

Since Oracle predates the SQL standard, certain comparison semantics in Oracle don't match the standard (such as comparing NULL and the empty string).  In theory, Oracle has the VARCHAR data type so that in the future they can change the VARCHAR data type's comparison semantics to match the SQL standard without affecting the backwards compatibility of applications using the VARCHAR2 data type.


text:
Q: How to make controlls for epub using HTML 5,JavaScript and CSS? Ok so we have to implement an online e-reader using HTML5, JS and CSS. So far I have a pretty good understanding of those 3 technologies. What basically needs to happen is that a user picks a book from a gallery of links which takes him to a page to read the book.
Apparently the the epub file should be loaded into memory on the clients computer, unpacked and then displayed on the webpage. Up untill this point I don't have too many problems, what really racks my brain is what comes next.
So all the chapters are divided into seperate xhtml pages aswell as the cover, title page, table of contents which makes creating navigatable dynamic links to them not too hard. But, we also have to provide controls to change the font, colour and navigate between pages.
How do I implement this?
Does the JS to do this come in the page that loads the epub files and if so, how do I write JS that changes properties of a page loaded in the page the JS is in?
I can't think of another way to do this except to put a small JS widget on every single chapter, but then the problem of "turning pages" still exists as I do not know where one page starts and the other ends as this isn't specified in the xhtml files.
I'm sorry if I'm unclear or did not provide enough information, although I have worked with JS, HTML5 and CSS alot the whole epub thing is pretty new to me.
Any help would be appreciated.

A: I would check out one of the few open source projects dedicated to epubs on the web to get you started. You seem to be asking many questions so rather than answer specifically, I recommend you look at how some others have tackled the problems.
First you should check out Readium: http://readium.org/ They have many of the functions you've described (changing the font, picking a book from a library, etc.)
Next I would look at my personal project https://github.com/fchasen/epub.js
We do things a little differently but again it be a good place to look at how we've handled some challenges so you can come back with more specific questions.


text:
Q: flutter : start app in background when the android or ios phones turned on I want to run my flutter app in the background when the phone turns on.
in other words, the app starts in the background in phone startup.
until now I didn't use packages, if this has a solution, please say.


text:
Q: Show that a set has zero measure with respect to two measures I have a measure $\nu$ defined in $(\mathbb{R}^p, \mathcal{B}^p)$ such that
$$\int_{\mathbb{R}^p} x'x \,  d\nu(x) < \infty$$
Given $\nu$ with this property, define the measure $\kappa$ as:
$$\kappa(E):= \int_E x'x \, d\nu(x)$$
I want to show that $\nu(E) = 0 $ if, only if, $\kappa (E)=0$.
This sounds very simple and straightforward, but I don't have the resources to prove it.
I tried to find an expression that involves both $\nu(E)$ and $\kappa(E)$, but I couldn't.
Help!

A: I think $\nu$ could be the point measure of the origin (i.e., $\nu(E)=1\iff 0\in E$). That would make $\kappa$ the zero measure.


text:
Q: How can I use an $n$-input neural network to predict some values for $n-1$ inputs? I have a fully-connected neural network whose input is a vector of $n$ (normalized) integers. Each of these integers is associated with an object. The output is similarly a vector of $n$ values each of which is the prediction of a metric corresponding to one of those objects. The network is trained using the data of all $n$ objects.
Now, I need to consider the prediction scenario above in a faulty manner, say, a fault just eliminates one of those objects. Now, I am wondering whether or not I can use the very neural network above to predict the features of the remaining $n-1$ objects. In particular, I don't who what I need to feed into the input associated with the eliminated object.
Any thoughts and ideas are welcome!

A: You could have an additional $n$ binary inputs which indicates whether each object is present or not.
Alternatively, you could have an architecture which can take in a variable number of inputs and produce a variable number of outputs. For example, given inputs $x_i$, embed them to $z_i = f(x_i)$, then let $z = \sum_i z_i$, and have output $y_i = g(x_i, z)$, where $f$ and $g$ are both neural networks. This scheme doesn't rely on there being any fixed number of objects.


text:
Q: Quantile functions in boost (C++) Judging from the documentation boost seems to offer quantile functions (inverse cdf functions) for both normal and gamma distributions, but its not clear for me how can I actually use them. Could someone paste an example please?

A: There is a workable example on QuantCorner.
// Édouard Tallent @ TaGoMa.Tech
// September 2012

#include<boost/math/distributions.hpp>
#include<iostream>
using std::cout;
using std::endl;

double inverseNormal(double prob, double mean, double sd){
        boost::math::normal_distribution<>myNormal (mean, sd);
        return quantile(myNormal, prob);
}

int main (int, char*[])
{
        try
        {
                double myProb = 0.1;    // the 10% quantile
                double myMean = 0.07;   // a 7% mean
                double myVol = 0.14;    // a 14% volatility

        cout << inverseNormal(myProb, myMean, myVol)  << endl;
        }

                catch(std::exception& e)
        {
                cout << "Error message: " << e.what() << endl;
        }
return 0;
}

A: The quantile calculation is implemented as a free function. Here's an example:
#include <boost/math/distributions/normal.hpp>

boost::math::normal dist(0.0, 1.0);

// 95% of distribution is below q:
double q = quantile(dist, 0.95);

You can also get the complement (quantile from the right) using:
// 95% of distribution is above qc:
double qc = quantile(complement(dist, 0.05));

There are some similar worked examples here:
http://www.boost.org/doc/libs/1_46_1/libs/math/doc/sf_and_dist/html/math_toolkit/dist/stat_tut/weg.html
Edit: don't need namespaces on the free functions thanks to ADL


text:
Q: Get a URI for a RawContact photo in Android I know I can get the URI of a contact's photo using:
Uri person = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(person, Contacts.Photo.CONTENT_DIRECTORY);

Is there a way to do the same for a RawContact?
I've tried:
Uri person = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
Uri photoUri = Uri.withAppendedPath(person, Contacts.Photo.CONTENT_DIRECTORY);

But it doesn't work...
The reason I need a URI instead of the actual blob is because the code is in an AppWidget and seems like there a very hard limit of a couple of megs when passing data from a widget to the launcher, so I need to use setImageViewUri and not setImageViewBitmap.
Thanks.

A: Here is the solution to your problem. Solution
I also had the very same problem and after digging around and reading Android's source code I got it. It's probably to late by now (for you) but here it is anyway.
public InputStream getBitmapFromUri(String rawContactId) throws FileNotFoundException {

    final Uri photoUri = Uri.withAppendedPath(
            ContentUris.withAppendedId(RawContacts.CONTENT_URI, Long.valueOf(rawContactId)), RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
    final InputStream imageStream = contentResolver.openInputStream(photoUri);

    return imageStream;
}

A: I think you need to directly access the 'data' table(ContactsContract.Data) to get the photo for raw contacts. The column 'data15' should store it.
Contacts.Photo.CONTENT_DIRECTORY is the contact's primary photo path, but no such path is provided for raw contacts in default.

A: If you are querying for RawContacts you can also add RawContacts.CONTACT_ID to the projection, then you can build the URI the same way:
long contactId = cursor.getLong(cursor.getColumnIndex(RawContacts.CONTACT_ID));
Uri person = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(person, Contacts.Photo.CONTENT_DIRECTORY);

A: A year later and no real answer, I guess it can't be done.
I ended up using setImageBitmap instead of setImageUri,
and used a scaling code for the bitmap to reduce memory consumption as much as possible (a loop that requests smaller and smaller sizes of the bitmap until the size is under a const limit).
this seemed to work well for almost all our users, some still complain about missing pics in the widget, but I'd say less then 2-3% of our users which is kinda acceptable.


text:
Q: The Red Book of Westmarch - Gold or Silver? A friend of mine is designing a box to look like the Red Book of Westmarch. We could use the movies as a reference, but I was wondering if it's ever mentioned anywhere in the text whether or not the star and 'BB' initials are inlaid with gold or silver. I've poured through the appendices, and some of Tolkien's notes, but I've not found anything. Personally I feel that Bilbo would have went with gold, but I'm not sure.
Any ideas?

A: In the text, there's no mention of a star or "BB" at all. In Book I, Chapter 1, "A Long-Expected Party", the book is simply described as "a leather-bound manuscript"; in Book VI, Chapter 6, "Many Partings", we're told that they have become

three books of lore that he had made at various times, written in his spidery hand, and labelled on their red backs...

Finally, in Book VI, Chapter 9, "The Grey Havens", it's described as "a big book with plain red leather covers" (emphasis added).
Based on this, the book seems to envision something with no decoration at all—no "BB" nor decorative star nor anything else.

A: The quote in Matt's answer is taken from the second (or later) edition. In the original edition, it read

...some books of lore that he had made at various times, written in his spidery hand, and labelled on their red backs: Translations from the Elvish, by B.B.

Still no mention of any inlay, but we do learn

the content [...] was preserved in that copy of the Red Book of Westmarch which was made in Gondor by the King's Writer Findegil [...].

This is a book that has copies found in royal libraries, so ornamentation is a possibility, but there is nothing definitive.


text:
Q: Question from Kline's Calculus: A physical and intuitive approach A train runs at a velocity of 66 ft/ sec along a straight track. When the brakes are applied, the deceleration is $4/3$  ft/$sec^2$. For how long and how far should the brakes be applied so that the train stops at the station?
(Please note that I have not yet even reached using the integration symbol in this book. It's the complete basics so please do try to explain steps that are simple to you. :-) )
Here's where I'm stuck.
We have initial velocity = 66.
Brake acceleration = - 4/3
Taking the antiderivative of acceleration we get:
v = $-4/3t + C$
When t = 0, v = 66. So, C = 66
v = $-4/3t + 66$
Taking the antiderivative of velocity, we get:
s = $-2/3 t^2 + 66t + C$
Suppose I consider the starting point as distance $0$, then I can say C = $0$ but then I don't know 's' which must be the distance to the station, which is not given.
Suppose I consider the station as distance $0$ then I do not know C as how far the train is from the station is not given.
How do I proceed with this?

A: Lets try this:
The equation for deceleration is:
d= (Vf-Vi)/t
Where Vf is the final velocity, which should be zero, having in mind that the train stops in the station.
Vi is the initial velocity, a value given to us by the condition as well as d.
so t= (Vf-Vi)/d= (0-66)/(-4/3)
giving you the time.


text:
Q: What is the best way/UX to handle logic show item's detail from ListView/RecyclerView I am working on a simple app with only two activity.

*

*The first activity(named as StudentListActivity) have a recyclerview show the list of student. Each item is a student and list student data will get from server.

*The second activity(named as StudentDetailActivity) is detail of specific student and be started when click on recyclerview's item in StudentListActivity.

And what I confuse is the way to get student detail data. I consider in two ways:

*

*When click on recyclerview's item in StudentListActivity, I will pass entire student object to StudentDetailActivity and show it regularly. This way will fast and alway available but come wrong in case of the student no longer exist but still show detail on StudentDetailActivity.

*I just pass only the student's id and call api to server in oder to get student info depend on that id. This way can avoid the case in the first way because we call to the server and ensure the student is existed on database. But it take time to call api, let user waiting for and maybe affect to user experience.

Any one tell me what is the best way/UX for that situation, or are there still other solutions. Suggest me, please!
Thanks,

A: From an UX perspective, I would do the following:
Let's say in your RecyclerView, each item consists of a name, and image. When you navigate over to a detail activity for a specific student, I would pass on (along the id) the name and the image URL to the other activity and implement Activity Transitions. Something along the lines of:

Source
And from then on, I would use the id to retrieve the rest of the information. I would advise against sending large data over intents, as they were not designed for that purpose. Also if you make your Activity to depend on an object instead of an ID to start, you will have a hard time enable direct app linking and allowing users to share pages from your app. Also consider the Activity lifecycle, and what happens on configuration change. See more here, and see the following diagram:

Source
From an architectural perspective, I would suggest the following:
Implement a local database, and ensure your network requests are cached properly. This will enable you more speedier results and an offline-ready application. Between your UI and data sources, implement a Repository pattern, along the lines of:

Source

A: Most of the application which i developed comes across this situation. What I always prefer to do is when user land on to student detail activity, load from cache if available and parallely trigger a Web service call. Once the server response available update the student details activity with latest info and store the same in cache. This way transition will be very smooth,  and user won't feel waiting...


text:
Q: Sort tenors in finance notation I have an array of tenors
Tenors = np.array(['10Y', '15Y', '1M', '1Y', '20Y', '2Y', '30Y', '3M', '5Y', '6M', '9M'])

where M stands for month and Y stands for years. The correctly sorted order (ascending) would then be
['1M', '3M', '6M', '9M', '1Y', '2Y', '5Y', '10Y', '15Y', '20Y', '30Y']

How do I achieve that using python with scipy/numpy? As the tenors originate from a pandas dataframe a solution based on pandas would be fine as well.

A: You can use str.extract for parsing numbers and values, then convert to int and categories by astype and last sort_values:
df = pd.DataFrame({'a':Tenors})
df[['b','c']] = df.a.str.extract("(\d+)([MY])", expand=True)
df.b = df.b.astype(int)
df.c = df.c.astype('category', ordered=True, categories=['M','Y'])
df = df.sort_values(['c','b'])
print (df)
      a   b  c
2    1M   1  M
7    3M   3  M
9    6M   6  M
10   9M   9  M
3    1Y   1  Y
5    2Y   2  Y
8    5Y   5  Y
0   10Y  10  Y
1   15Y  15  Y
4   20Y  20  Y
6   30Y  30  Y

print (df.a.tolist())
['1M', '3M', '6M', '9M', '1Y', '2Y', '5Y', '10Y', '15Y', '20Y', '30Y']

A: print sorted(Tenors, key=lambda Tenors: (Tenors[-1], int(Tenors[:-1])))

Sorts by the last character and then by the integer value up to the last character

A: Approach #1 Here's a NumPy based approach using np.core.defchararray.replace -
repl = np.core.defchararray.replace
out = Tenors[repl(repl(Tenors,'M','00'),'Y','0000').astype(int).argsort()]

Approach #2 If you are working with strings like '18M', we need to do a bit more of work, like so -
def generic_case_vectorized(Tenors):
    # Get shorter names for functions
    repl = np.core.defchararray.replace
    isalph = np.core.defchararray.isalpha

    # Get scaling values
    TS1 = Tenors.view('S1')
    scale = repl(repl(TS1[isalph(TS1)],'Y','12'),'M','1').astype(int)

    # Get the numeric values
    vals = repl(repl(Tenors,'M',''),'Y','').astype(int)

    # Finally scale numeric values and use sorted indices for sorting input arr
    return Tenors[(scale*vals).argsort()]

Approach #3 Here's another approach, though a loopy one to again handle generic cases -
def generic_case_loopy(Tenors):
    arr = np.array([[i[:-1],i[-1]] for i in Tenors])
    return Tenors[(arr[:,0].astype(int)*((arr[:,1]=='Y')*11+1)).argsort()]

Sample run -
In [84]: Tenors
Out[84]:
array(['10Y', '15Y', '1M', '1Y', '20Y', '2Y', '30Y', '3M', '25M', '5Y',
       '6M', '18M'],
      dtype='|S3')

In [85]: generic_case_vectorized(Tenors)
Out[85]:
array(['1M', '3M', '6M', '1Y', '18M', '2Y', '25M', '5Y', '10Y', '15Y',
       '20Y', '30Y'],
      dtype='|S3')

In [86]: generic_case_loopy(Tenors)
Out[86]:
array(['1M', '3M', '6M', '1Y', '18M', '2Y', '25M', '5Y', '10Y', '15Y',
       '20Y', '30Y'],
      dtype='|S3')

A: I opted for the long solution since I needed convert_tenors anyway. This also solves Jim's objection.
import scipy

def convert_tenors(tenors):
    #convert tenors to years
    new_tenors = scipy.zeros_like(tenors,dtype=float)
    for i,o in enumerate(tenors):
        if(o[-1]=='M'):
            new_tenors[i] = int(o[:-1])/12
        else:
            new_tenors[i] = int(o[:-1])
    return new_tenors

def sort_tenors(tenors):
    #sort tenors in ascending order
    idx = scipy.argsort(convert_tenors(tenors))
    return tenors[idx]

Tenors = scipy.array(['10Y', '15Y', '1M', '1Y', '20Y', '18M', '2Y', '30Y', '3M', '5Y', '6M', '9M'])
print(sort_tenors(Tenors))

returns
['1M' '3M' '6M' '9M' '1Y' '18M' '2Y' '5Y' '10Y' '15Y' '20Y' '30Y']

A: A straightforward solution — convert the tenors their day equivalent, then sort based on that:
def tenorToDays(tenor):
    unit = tenor[-1:].lower()
    value = int(tenor[0:-1])
    if unit == 'w':
        return 7*value
    elif unit == 'm':
        return 30*value
    elif unit == 'y':
        return 365*value
    else:
        raise ValueError(f'Unrecognised tenor unit: ({unit})')

tenors = ['10Y', '15Y', '1M', '1Y', '20Y', '2Y', '30Y', '3M', '5Y', '6M', '9M', '18M']
sorted(tenors, key=lambda tenor: tenorToDays(tenor))
# ['1M', '3M', '6M', '9M', '1Y', '18M', '2Y', '5Y', '10Y', '15Y', '20Y', '30Y']


text:
Q: How to update a specific data of a table? I am making a likes/dislikes thing in php & html. So, since it uses likes for each blog, I use the blog ID. I would like to know how I could update the "likes" in the table, but only update the "likes" of the specific row using it's id. Here is the php script:
<?php

require 'init.php';

$rating = $_GET['rating'];
$postid = $_GET['id'];

if ($rating = "like") {
    $sql = "

    ";
}

if ($rating = "dislike") {
    $sql = "
        UPDATE
            posts
        SET
            dislikes = dislikes+1
        WHERE
            id = $postid
    ";
}
?>

A: The update query does not seem to be the problem here, the main problem is your if statement, where you are not using comparison operator but are using assignment operator.
The statement: if ($rating = "like") assigns value "like" to the variable $rating, it does not compare $rating against value "like", which is what I think you want it to do.
There are few other "major" issues to note is that you are wide open for SQL Injection attacks.  Since you mentioned that you are using mysql_ functions in your comment, you at least want to make use of mysql_real_escape_string function.  e.g.
$rating = mysql_real_escape_string($_GET['rating'], $con); // assuming $con is your MySQL Connection
$postid = mysql_real_escape_string($_GET['id'], $con);

Another equally important point to note is that mysql_ functions are deprecated.  You definitely should consider using either mysqli or pdo.
Third and final point to note is that if your rating is "like" then the query is empty.  Hopefully you are checking for emptyness before calling mysql_query, which is not shown here.


text:
Q: Problem with Simple dialog box in jquery? I am using simple dialog for showing some custom popup having a iframe in it whose source is a VF page. Below is the code i am using for it in Javascript.
 function openDialog(var1,var2){
  if (var1 != null && var2 !=''){

   var pageURL = '/apex/myVFPage?id='+var1 +'&name='+var2;

    var sd = new SimpleDialog("Test", true);

    sd.setTitle("Message From Webpage");

    sd.createDialog();
     window.parent.sd = sd;
     sd.setWidth("50%");

   //Specify the iFrame and give URL of VF page
    sd.setContentInnerHTML("");

     if ($j(sd.dialog).find('#InlineEditDialogX').size() == 0) {
     var close = $j("Close");

    close.mouseover(function() {

       this.className = 'dialogCloseOn';
        }).mouseout(function() {
          this.className = 'dialogClose';
          }).click(function() {

       // finally our on click handler which closes the dialog
        sd.hide();
       });
      // insert the new generated close button before the h2 tag so it'll show up on   the top right corner
    close.insertBefore($j(sd.dialog).find('.topLeft h2'));
     } sd.show();

    }

}

I am calling this javascript function from my VF page button.
How can i close the dialog box from my iframe's VF page.  And re-render my parent VF page to new href from the child VF page(i.e. in the iFrame).

A: You can use the postMessage function from within the iframe to tell the parent to close the dialog, see: http://davidwalsh.name/window-iframe
So in your function you would listen for a message from the iframe e.g. "closeMe" then remove the dialog.
Mark


text:
Q: XAMPP setup to use name instead of IP address I have an internal network for our company and in one of the server I have XAMPP/Apache setup and have my own website.
I access that page from a browser anywhere within a network by entering the following address:
http://10.10.239.306/MyPage/testpage.php
I am trying to change so that instead of the IP (which is hard to remember) the user can enter, say for example:
http://hweb/MyPage/testpage.php
I followed the online instruction and did the following update on the server hosting the pages:
in the C:\Windows\system32\driver\etc\host file I added:
127.0.0.1  hweb
in the C:\xampp\apache\conf\extra\httpd-vhosts.conf file I added:
<VirtualHost *:80>
    ServerName hweb
    ServerAlias myname
    DocumentRoot c:/xampp/htdocs/MyPage
</VirtualHost>

When I enter http://hweb/MyPage/testpage.php in my browser, I get a Internet Name Resolution Error (dns_server_failure) error
I did restart the Apache server twice.
Does anyone know what I am doing wrong and how to fix it?

A: try to change the listen
127.0.0.1 hweb,
check following link;
http://sustainablewebdesign.com/book/resources/xampp/

A: Internet Name Resolution Indicates that your browser does not know the IP of hweb. I.e. you did not edit the hosts file on the client machine (the one which tries to access)
Please verify you have 10.10.239.306 hweb in C:\Windows\system32\driver\etc\host on Client machine.


text:
Q: How to convert DM-script files (*.s) into a plugin file (*.gtk) I have written some DM-script files (.s), and thus I would like to convert (compile?) them into plugin files (.gtk). In this case, should I prepare some kind of compiler and Gatan Software Development Kit (SDK) package, or others? If there is a good way, please teach the procedure in detail. I will be really grateful, if you share some wisdom to create *.gtk files.

A: .GTK files are not compiled - you will not gain any speed benefit of having them in a .gtk (or .gt1, .gt2 ) file. They are only packed into those files for convenience of sharing and distributing them easily without sharing source code.
That said, the way to "pack" scripts into those files is to use a script-command itself, i.e. write a script which build these files from a set of .s files on the hard drive.

The command to add a script-file to a script package is AddScriptFileToPackage with the syntax:

void AddScriptFileToPackage( String file_path, String packageName, Number packageLevel, String packageLocation, String command_name, String menu_name, String sub_menu_name, Boolean isLibrary )
void AddScriptFileToPackage( String file_path, String packageName, Number packageLevel, String command_name, String menu_name, String sub_menu_name, Boolean isLibrary )

The command to add a script (string) to a script package is AddScriptToPackage with the syntax:

void AddScriptToPackage( String script, String packageName, Number packageLevel, String packageLocation, String command_name, String menu_name, String sub_menu_name, Boolean isLibrary )
void AddScriptToPackage( String script, String packageName, Number packageLevel, String command_name, String menu_name, String sub_menu_name, Boolean isLibrary )

The paramters in the two commands are:

Note, that the created plugin-file will by default appear in the user_plugin location:
C:\Users\USERNAME\AppData\Local\Gatan\Plugins
The second syntax allows specifying the path, where the packageLocation parameter might be any of the names also accepted in the command GetApplicationDirectory, most often either being user_plugin (see above) or just plugin referring to the current run DigitalMicrograph.exe relative plugin folder, i.e.
.\Plugins relative to where the DigitalMicrograph.exe sits, typically
C:\Program Files\Gatan\Plugins\
Note, that one can append scripts to an existing file, but can not "unistall" one from it. In that case, one has to delete the file and re-create it anew.
Also, if an error occurs in the to-be-added scripts, they will not install correctly and you might need to start over.
The F1 help documentation (of later GMS versions) has an example script showing how to typically use the command:

The difference between libary and command install is the same as when using the File-Menu command to "install a script". A library usually is a set of methods (or classes) which, when installed, remain available and in memory. The command installs a script as a menu-command to the UI. i.e. selecting the menu executes the scirpt (once).
While the "File/Install Script" install things into the general prefereces-file of DigitalMicrograph, the commands above create separate .gtk files which load on startup if found in the plugins-folder. Any code that is installed as "library" is run once on startup.


text:
Q: Adding a text with spacing in math mode I have a text inside mathmode in latex and I would like the text to be separated from the equation with some spaces. How can I do this? Example code below
\begin{gather*}
A^2 = B^2 + C^2  \text{[Pythagaros theorem]}
\end{gather*}