Q:

Show message dialog

Is it possible to display a QML dialog when the user hits a button in a QML window?
Example:
When the user clicks in the menu bar on Help -> About the About dialog should be displayed:
import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

import "components"

ApplicationWindow {
    id: window
    visible: true
    width: 1040
    height: 480

    aboutDlg: aboutDialog {}  // does not work...

    menuBar: MenuBar {
        Menu {
            title: qsTr("Help")
            MenuItem {
                text: qsTr("About")
                onTriggered: aboutDlg.open();
        }
    }
    ...

components/AboutDialog.qml
import QtQuick 2.2
import QtQuick.Dialogs 1.1

MessageDialog {
    id: aboutDialog
    title: "May I have your attention please"
    text: "It's so cool that you are using Qt Quick."
    onAccepted: {
        console.log("And of course you could only agree.")
        Qt.quit()
    }
}

When I remove the line boutDlg: aboutDialog {}  // does not work... the following error is reported when clicking on the About menu item:

qrc:/main.qml:61: ReferenceError: aboutDlg is not defined

How can I achieve this?

A:

You called "aboutDialog" which is an ID in the AboutDialog.
Think of it like you add an object, like adding a Rectangle...which has its own file...and you can "instantiate" it by adding an object like so:
...

ApplicationWindow {

...

    AboutDialog {
        id: aboutDlg
    }

...
}

You can find example HERE
You might also optimize a bit and put the AboutDialog in a Loader.


Q:

Face authentication to unlock my app programmatically

I am developing an android app which uses fingerprint/face recognition for unlocking the app.
I have successfully integrated fingerprint authentication using BiometricPrompt. But didn't know where to start for Face authentication. Any headsup will be really helpful.
Also, Since BiometricPrompt comes with face, fingerprint, and iris, I don't want to use either MLKIT or any third party libraries.
Below is the piece of code I used for Fingerprint authentication.
new BiometricPrompt
    .Builder(context)
    .setTitle(title)
    .setSubtitle(subtitle)
    .setDescription(description)
    .setNegativeButton(negativeButtonText, context.getMainExecutor(),
                        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            biometricCallback.onAuthenticationCancelled();
        }
    })
    .build()
    .authenticate(new CancellationSignal(), context.getMainExecutor(),
            new BiometricCallbackV28(biometricCallback));

A:

Android 10: Will allow both finger print and Face ID as currently in Samsung s10.
Android 9: Will allow only Fingerprint authentication (irrespective of face Id unlock exist or not )
reference link
https://source.android.com/security/biometric/#source
Edit1:
However the Samsung is not following google's ritual.
Samsung will still have different behaviours .
1.Samsung - Android 9 - you can choose preferred biometrics and this applicable for the apps well.
But there is a bug. If you disable the finger print authentication for device level unlock you will get prompted for the fingerprint authentication in the app level.

Samsung - Android 10 - you can keep all the authentications active at same time. In biometric prompt you can choose authentication.

Short summary :


Q:

Is it possible to draw these charts with nvd3 or similar?

In a project I'm working on right now, which requires showing lots of charts, we've been using nvd3 javascript library quite successfully so far.
One of the new features we are adding now requires us to render this kind of chart:

Which is supposed to be a distribution chart (A + B + C + D = 100%). I don't know how to call that kind of chart.
As far as I know there's no way to draw that chart using nvd3, but I may be wrong.
Does anyone know a way to draw that kind of chart using nvd3 or any other library?
Thanks in advance.
UPDATE: I've learned that this kind of chart is called "rose chart", "polar area chart" or "coxcomb chart".

A:

Here is a few samples similar to you requirement that might help get and idea. It uses the d3.js framework

D3 Pie charts with grid lines
Creating a Polar Area Diagram (Radial Bar Chart)
Smooth Transitioning of Polar Area Diagram

And here's a The Big List of D3.js Examples
Hope it helps


Q:

Google maps API get GPS coordinates

I try to get GPS coordinates of some places via Google Map API but it doesn't work.
Here an example:
http://maps.google.com/maps/geo?q=Hungary,%20Szeged&hl=en&key=MY_API_KEY
Where is MY_API_KEY gets from the Google APIs Console. I have also switched on the Google Maps API v2, Google Maps API v3 and Google Maps Coordinate API.
When I load the URL I get this:
{
  "Status": {
    "code": 610,
    "request": "geocode"
  }
}

610 means wrong API key.
What am I doing wrong?

A:

Don't use the deprecated v2 API, use the current Google Maps Geocoding API v3


Q:

Need help shortening this query by either using a type of "for" or "while" loop

I would like to know if there is any way in which I can alter this SQL query so that I don't have to perform the UNION every time for a new field ("FieldName") from which I have to extract data.
I have about 30 fields with the name "Waybill1 up to "Waybill30".
I would like to perform the below query without having to use the UNION for every single field ID.
Here is the query, using only 3 of the "FieldName" values:
SELECT `FieldValue`, `SubmissionID` FROM `jos_rsform_submission_values` WHERE `FieldName` = "Waybill1" AND `FieldValue` != ""
UNION
SELECT `FieldValue`, `SubmissionID` FROM `jos_rsform_submission_values` WHERE `FieldName` = "Waybill2" AND `FieldValue` != ""
UNION
SELECT `FieldValue`, `SubmissionID` FROM `jos_rsform_submission_values` WHERE `FieldName` = "Waybill3" AND `FieldValue` != "" ORDER BY `SubmissionId` ASC

It should basically perform the same task as a "for" loop in PHP/Javascript etc.
I am not that familiar with SQL, so any help/guidance would be appreciated.

A:

You don't need to use UNION here, you can just use the IN operator
The IN operator allows you to specify multiple values in a WHERE clause.
SELECT FieldValue,
       SubmissionID
FROM   jos_rsform_submission_values
WHERE  FieldName IN ('Waybill1', 'Waybill2', 'Waybill3', 'Waybill4', etc...)
   AND FieldValue != ""
ORDER BY SubmissionId ASC


Q:

Java RMI : how InitialContext.lookup() works

In a distributed client server application, i am using java RMI to invoke server side method from client machine. At server side EJB is being used and application server is Glassfish. I have a SampleFacade Class at server end which is a java session bean and SampleFacadeRemote is a Remote interface exposed to client (@Remote has been used with it). SampleFacade implements SampleFacadeRemote Interface .
Please look at the following code snippet :
        private static SampleFacadeRemote lookupSampleFacade()
        {
            Context c = new InitialContext();
            return (SampleFacadeRemote)c.lookup("java:comp/env/SampleFacade");
        }
        catch (NamingException ne)
       {
          throw new RuntimeException(ne);
       }

Here, with the returned object, remote method can be successfully executed.
I am curious to know how it works. Does lookup method return SampleFacade object to client in order to execute its method? But SampleFacade's method is suppose to be run at server side/Remote JVM. then what type of object is being returned by lookup() method? Please explain the underlying mechanism.

A:

It returns a stub: a client-side object that implements the same remote interface and knows how to communicate with the actual remote object.
In fact you should note that it isn't the lookup() method that performs this magic: it is ultimately the bind() method concerned, or even the object itself, that translates the remote object to its stub, unless the stub is what was passed to bind(). In other words the stub is already in the Registry or LDAP or whatever you're looking up, and lookup() just gives you whatever was found.


Q:

Is there a name for 'markup'?

I've been trying to formulate a question for quite some time, and I haven't been able to come up with a better way to describe it. I hope it's not too confusing.
There are a number of ways to use markup languages to convey information like emphasis in text files. Stack exchange uses 'Markdown' for example. In this case, adding * (in Markdown) or <emph> (in HTML) is simply called 'markup' I suppose, but is there a name for this? That is, making something stand out in the text, be it logically like "emphasis" or explicitly like "bold" or "underline", etc. The only thing that comes to mind is to emphasize, but (to me at least) that implies stressing the word, not what you're doing with the text to achieve that result.
This has been bugging me for quite a while, I hope someone can help me out here.

A:

How about simply to format? You are formatting the text with Markdown. Or how about to style? CSS is called like that for a reason, it's all about styling.

A:

Dictionary.com defines markup, amongst other things, as

detailed instructions, usually written on a manuscript to be typeset,
  concerning style of type, makeup of pages, and the like.

So I would say that the best word for this is "markup".

A:

"Markup" is the generic noun for annotations added to a text, whether done with a pencil or with various electronic means, and whether or not they have anything to do with formatting. Even readers' underlines can be called "markup".
The corresponding verb is "to mark up".
"Formatting" refers specifically to arranging parts of a document into pages or screens. When you make your window narrower, the document gets "reformatted", but none of the "markup" changes at all.
"Markup" originally involved annotating several kinds of things on paper:  spelling or other corrections; things like breaking a paragraph in half or adding a heading; and giving formatting instructions such as to set a portion in italics.
In modern publishing those tasks are commonly separated:

An author or "encoder" identifies parts of a document by "what they are" (this bit is a footnote, 2nd-level heading, bibliography entry,
list item, command name, etc). This is called "descriptive" or
"declarative" markup.
Someone decides how each kind of thing should be formatted in a print or online edition. Publishers call this their "house style" or similar names.
Some person or program then applies the design to the objects, via "formatting" and "typesetting".

Computer-based document systems progressed similarly: Many early ones had commands only for formatting effects: "change font", "shift left margin", "switch to bold", "skip a line", etc. Of course, similar combinations are used over and over again, so systems soon provided named sets of instructions for the common kinds of things.
Eventually (starting with Brian Reid's "Scribe" system), systems began to allow authors to ignore the "how" of formatting almost completely, by just picking "kinds" (often called "styles"). Many authors just do this, while many others do manual formatting, especially for short documents.
"Markup" is ubiquitous, but "formatting" isn't always part of the picture at all. Visually impaired readers may use a screen reader, and objects such as "heading", "footnote" etc. are communicated in entirely different ways. Similarly, a search engine cares little about fonts, but may care a great deal about which parts are the document title, author name, or bibliography.


Q:

Random number seed targeting the same version of the .NET framework

Does every CPU return the same random sequence based on the same seed if my application targets .NET framework 3.5?  I am checking if you get the same result as me. I am also hoping that everyone who I distribute my application to will get the same result. Thanks!
Random a = new Random(44448);
int i1 = a.Next(65, 90);
MessageBox.Show(i1.ToString());

A:

For a specific framework version your program should give the same result each time you run it, because of the fixed seed.
But it can give different results on different versions of the .NET framework.
For example, on .NET 4.0 I get 77. But putting the code into ideone (which uses Mono) gives 67.
The reason for this difference is because the precise algorithm used by Random is not part of the specification. The documentation has this information about the algorithm:

The current implementation of the Random class is based on a modified version of Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.
...
The implementation of the random number generator in the Random class is not guaranteed to remain the same across major versions of the .NET Framework. As a result, your application code should not assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework.

Emphasis mine. There are no guarantees that future implementations will use the same algorithm.


Q:

f.read coming up empty

I'm doing all this in the interpreter..
loc1 = '/council/council1'
file1 = open(loc1, 'r')

at this point i can do file1.read() and it prints the file's contents as a string to standard output
but if i add this..
string1 = file1.read()

string 1 comes back empty.. i have no idea what i could be doing wrong.  this seems like the most basic thing!
if I go on to type file1.read() again, the output to standard output is just an empty string.  so, somehow i am losing my file when i try to create a string with file1.read()

A:

You can only read a file once. After that, the current read-position is at the end of the file.
If you add file1.seek(0) before you re-read it, you should be able to read the contents again. A better approach, however, is to read into a string the first time and then keep it in memory:
loc1 = '/council/council1'
file1 = open(loc1, 'r')
string1 = file1.read()
print string1


Q:

Cisco ISE Wlan user authentication fails for users with umlaut

We have setup a Cisco Identity Services Engine to manage WLAN access for our users.
Access should be granted to users from a specific Windows Active Directory group.
This works fine for users having a username consisting only of ASCII letters. However, user names having e.g. an umlaut fail. The live authentication log shows an error "22056 Subject not found in the applicable identity store(s)".
Any idea what could be wrong? (And, no, renaming all non-ASCII users is not an option)

A:

The solution is surprisingly simple:
Users with Umlauts in ther name automatically can login with their usual login name with umlauts replaced (e.g. "Müller" becomes "Muller"). So renaming users in AD is not necessary, they just have to be informed to type the modified username in the WLAN login. (They could also do the same in any normal windows login, which may come in handy when they need to do a remote login from abroad where they don't have umlauts available on the keyboard).


Q:

Make figure with minipages wider than text

I have a lot of figures I want to present, and I try to line them up three in a row to save space, using the code below.
The figures become a bit too small, so I wanted to make the outer figure 1.25 of textwidth by putting {1.25\textwidth} after \begin{figure}, but that gives me a "Missing number, treated as zero." error.
How can I make the figure wider?
\begin{figure}[h]
\centering
    \begin{minipage}{.33\textwidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q1.eps}
    \end{minipage}\hfill
    \begin{minipage}{.33\textwidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q2.eps}
    \end{minipage}\hfill
    \begin{minipage}{.33\textwidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q3.eps}
    \end{minipage}
    \caption{Answers to questions 1, 2, and 3.}
    \label{fig:survey-ans-1-2-3}
\end{figure}

A:

Here I use nested \makeboxes around the minipages.  The outer one set to \textwidth, so that it centers properly, the inner to 1.25\textwidth to allow the \hfills to operate.
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{lipsum}
\begin{document}
\begin{figure}[h]
\centering
    \makebox[\textwidth]{\makebox[1.25\textwidth]{%
    \begin{minipage}{.4\textwidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q1.eps}
    \end{minipage}\hfill
    \begin{minipage}{.4\textwidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q2.eps}
    \end{minipage}\hfill
    \begin{minipage}{.4\textwidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q3.eps}
    \end{minipage}}}
    \caption{Answers to questions 1, 2, and 3.}
    \label{fig:survey-ans-1-2-3}
\end{figure}
\lipsum[1]
\end{document}

A:

You can use the adjustwidth environment from changepage, in this way:
\usepackage{changepage}
      .......
\begin{document}
      .......
\begin{adjustwidth}{-0.125\textwidth}{-0.125\textwidth}
\begin{figure}[h]
\centering
    \begin{minipage}{.33\linewidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q1.eps}
    \end{minipage}\hfill
    \begin{minipage}{.33\linewidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q2.eps}
    \end{minipage}\hfill
    \begin{minipage}{.33\linewidth}
        \centering
        \includegraphics[width=1\textwidth]{survey-q3.eps}
    \end{minipage}
    \caption{Answers to questions 1, 2, and 3.}
    \label{fig:survey-ans-1-2-3}
\end{figure}
\end{adjustwidth}
  .......

Don't forget to replace \textwidth with \linewidth for the minipages.


Q:

Is it normal to be stopped from doing experiments for months due to "equipment malfunctioning" during masters?

I am currently doing a medical science research masters with a difficult supervisor. Due to two incidents of equipment malfunctions (equipment that I am using), I was stopped from doing any experiments for more than three months in total. During the three months I did almost nothing. Over the entire 6 months that I have been here, I have only had one month during which I was able to generate any sufficient results (the other months I was learning the technique).  My supervisor rejected my proposal to switch to a new technique or use a different equipment set-up. What worries me is that I won't be able to gather sufficient results to write my thesis by July (which is the deadline), and I haven't even started my masters project.
I am wondering whether anybody else has similarly experienced this situation before and whether this is normal during your PhD i.e. doing absolutely nothing for 3 months or more due to the excuse of "equipment faults"? Do you just switch to a different experiment or part of the project which utilize different techniques? Could somebody please help me understand why my supervisor is doing this - is this normal for labs which lack funding?
What should I do? Should I make a formal complaint to the university about my masters supervisor? If I do so, I am afraid that the animosity between me and my supervisor will be beyond repair and he will not support me at all in finishing in time for the deadline. If it keeps on like this, I won't get enough results to sufficiently write the project thesis.

A:

In experimental sciences, such incidents are unfortunately common.  I do a lot of work in synthetic biology, for example, and it's not unusual to have a lab run into serious equipment or materials problems that significantly delay the work of the lab.  For example, one lab I was working with had a critical machine start producing strange results and it took a couple of months, several corrupted experiments, more than one technician visit, and also a change of protocols in order to debug it.
If the lab you are in is actively working to fix the equipment issues, and it is just taking a long time, that would not be unusual.  If they are not but are just neglecting it, then that is a very bad sign and you need to talk to the people who run your program to find out what to do.
In either case, you should make arrangements, either with your advisor or with the program heads, about how to adjust expectations given the equipment problems. Equipment issues should not be your problem or delay your graduation at a Masters level (Ph.D. is a different matter).


Q:

Entity Framework and inconsistent performance with processing the results of a query

Just setup New Relic on our site and we noticed some odd spikes in one of our webapi calls.
At this point I have the problem boiled down to a single EF query that I moved out to its own method so I could use New Relic to instrument it..
The only thing the method does is
//I changed this from ToListAsync to ToList to see if it would help
var result = Context.Data.Where(x=> x.id = id).ToList();
return result;

That's it..
Using New Relic and also logging out all the SQL queries I'm fairly positive the issue isn't with the query being slow. New Relic says the method is only spending an average of 339 ms running against the DB and I see similar numbers from the trace data coming from EF. But the methods average execution time is 16 seconds.
Normally this method executes in under 2 seconds but every so often EF just seems to go off into lala land and it takes 60 or 70 seconds to finish whatever it's doing. But I've never seen the DB query itself take longer then 500 ms. And the query is retrieving pretty much the exact same dataset every time it runs..
I noticed in the logs that the long wait time was always between executing the query and closing the connection.. Here's an example output from the logs

Application: 2015-02-17T10:04:11  PID[3556] Information -- Completed in 6 ms with result: SqlDataReader Application:  Application:
2015-02-17T10:04:11  PID[3556] Information  Application:  Application:
2015-02-17T10:04:22  PID[3556] Information Closed connection at 2/17/2015 10:04:22 AM +00:00

Notice the completion time is 6 ms but then there's a 11 second lag before getting to close connection

I've tried removing async for this call but it doesn't help
I tried using ConfigureAwait(false) on everything to see if it's some issue with trying to return to the original context
I've tried manually managing the connection myself.. So opening at the very beginning then closing at the very end

This can't be from load because right now there's literally 2 users beta testing the Azure site... So the load is pretty much non existent.
I've tried to recreate this locally but haven't been able to... And I'm not really sure where to go from here debugging the issue besides slowly gutting the EF parts for something simpler like Dapper to see if that behaves more consistently.
Technology Stack:

Sql Azure
Azure websites scaled up to two instances
EF 6 Async features
web api

A:

Which version of Sql Azure are you using?
We had a similar problem with Sql Azure Web (the one that will be retired soon)
We had a query using Entity Framework 6, agsint a table with about 700,000 rows. On my local sql server it took a second - on Sql Azure it took over 1 min!, worse still sometimes it even timed out
My guess is that Sql azure web is a shared sql server and that resources are limited.


Q:

Twitter Storm's Testing API won't initialize

I discovered backtype.storm.Testing while reading this SO question and got excited, but I haven't been able to get it to work because when I actually go to run the tests (from Java), the testing class won't load.
I wanted to use the functions from Testing exhibited in xumingming's TestingApiDemo, but when I actually run the tests I'm getting an ExceptionInInitializerError followed by a bunch of NoClassDefFoundErrors because it couldn't initialize backtype.storm.Testing.
What's going wrong with Testing? There's no problem at compile-time. My best guess is that it needs something from Clojure which is being dynamically loaded at runtime. Has anyone else seen this?
Here's most of the relevant stack trace:
java.lang.ExceptionInInitializerError: null
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:171)
        at backtype.storm.zookeeper$loading__4784__auto__.invoke(zookeeper.clj:1
)
        at backtype.storm.zookeeper__init.load(Unknown Source)
        at backtype.storm.zookeeper__init.<clinit>(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:249)
        at clojure.lang.RT.loadClassForName(RT.java:2056)
        at clojure.lang.RT.load(RT.java:419)
        at clojure.lang.RT.load(RT.java:400)
        at clojure.core$load$fn__4890.invoke(core.clj:5415)
        at clojure.core$load.doInvoke(core.clj:5414)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.core$load_one.invoke(core.clj:5227)
        at clojure.core$load_lib.doInvoke(core.clj:5264)
        at clojure.lang.RestFn.applyTo(RestFn.java:142)
        at clojure.core$apply.invoke(core.clj:603)
        at clojure.core$load_libs.doInvoke(core.clj:5302)
        at clojure.lang.RestFn.applyTo(RestFn.java:137)
        at clojure.core$apply.invoke(core.clj:603)
        at clojure.core$require.doInvoke(core.clj:5381)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at backtype.storm.cluster$loading__4784__auto__.invoke(cluster.clj:1)
        at backtype.storm.cluster__init.load(Unknown Source)
        at backtype.storm.cluster__init.<clinit>(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:249)
        at clojure.lang.RT.loadClassForName(RT.java:2056)
        at clojure.lang.RT.load(RT.java:419)
        at clojure.lang.RT.load(RT.java:400)
        at clojure.core$load$fn__4890.invoke(core.clj:5415)
        at clojure.core$load.doInvoke(core.clj:5414)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.core$load_one.invoke(core.clj:5227)
        at clojure.core$load_lib.doInvoke(core.clj:5264)
        at clojure.lang.RestFn.applyTo(RestFn.java:142)
        at clojure.core$apply.invoke(core.clj:603)
        at clojure.core$load_libs.doInvoke(core.clj:5302)
        at clojure.lang.RestFn.applyTo(RestFn.java:137)
        at clojure.core$apply.invoke(core.clj:603)
        at clojure.core$require.doInvoke(core.clj:5381)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at backtype.storm.daemon.nimbus__init.load(Unknown Source)
        at backtype.storm.daemon.nimbus__init.<clinit>(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:249)
        at clojure.lang.RT.loadClassForName(RT.java:2056)
        at clojure.lang.RT.load(RT.java:419)
        at clojure.lang.RT.load(RT.java:400)
        at clojure.core$load$fn__4890.invoke(core.clj:5415)
        at clojure.core$load.doInvoke(core.clj:5414)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.core$load_one.invoke(core.clj:5227)
        at clojure.core$load_lib.doInvoke(core.clj:5264)
        at clojure.lang.RestFn.applyTo(RestFn.java:142)
        at clojure.core$apply.invoke(core.clj:603)
        at clojure.core$load_libs.doInvoke(core.clj:5302)
        at clojure.lang.RestFn.applyTo(RestFn.java:137)
        at clojure.core$apply.invoke(core.clj:603)
        at clojure.core$require.doInvoke(core.clj:5381)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at backtype.storm.testing$loading__4784__auto__.invoke(testing.clj:1)
        at backtype.storm.testing__init.load(Unknown Source)
        at backtype.storm.testing__init.<clinit>(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:249)
        at clojure.lang.RT.loadClassForName(RT.java:2056)
        at clojure.lang.RT.load(RT.java:419)
        at clojure.lang.RT.load(RT.java:400)
        at clojure.core$load$fn__4890.invoke(core.clj:5415)
        at clojure.core$load.doInvoke(core.clj:5414)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.core$load_one.invoke(core.clj:5227)
        at clojure.core$load_lib.doInvoke(core.clj:5264)
        at clojure.lang.RestFn.applyTo(RestFn.java:142)
        at clojure.core$apply.invoke(core.clj:603)
        at clojure.core$load_libs.doInvoke(core.clj:5302)
        at clojure.lang.RestFn.applyTo(RestFn.java:137)
        at clojure.core$apply.invoke(core.clj:605)
        at clojure.core$use.doInvoke(core.clj:5392)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at backtype.storm.LocalCluster$loading__4784__auto__.invoke(LocalCluster
.clj:1)
        at backtype.storm.LocalCluster__init.load(Unknown Source)
        at backtype.storm.LocalCluster__init.<clinit>(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:249)
        at clojure.lang.RT.loadClassForName(RT.java:2056)
        at clojure.lang.RT.load(RT.java:419)
        at clojure.lang.RT.load(RT.java:400)
        at clojure.core$load$fn__4890.invoke(core.clj:5415)
        at clojure.core$load.doInvoke(core.clj:5414)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.lang.Var.invoke(Var.java:415)
        at backtype.storm.LocalCluster.<clinit>(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:171)
        at backtype.storm.testing4j$loading__4784__auto__.invoke(testing4j.clj:1
)
        at backtype.storm.testing4j__init.load(Unknown Source)
        at backtype.storm.testing4j__init.<clinit>(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:249)
        at clojure.lang.RT.loadClassForName(RT.java:2056)
        at clojure.lang.RT.load(RT.java:419)
        at clojure.lang.RT.load(RT.java:400)
        at clojure.core$load$fn__4890.invoke(core.clj:5415)
        at clojure.core$load.doInvoke(core.clj:5414)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.lang.Var.invoke(Var.java:415)
        at backtype.storm.Testing.<clinit>(Unknown Source)
        at my.package.storm.bolts.MockTupleHelpers.testTuple(MockTupleHelpers.ja
va:69)

Update: I found the place where I think the Testing class is being generated using Clojure. Perhaps the version of the Clojure libraries being used by my project (1.4) don't supply some necessary type in here? I'm using Storm 0.8.2.
Thanks,
-Daniel

A:

When you see NoClassDefFoundErrors, you are either missing some jar file in your classpath or the class isn't initialized due to some missing dependency. Check which jar files contain the classes which are throwing NoClassDefFoundError and add that to classpath.


Q:

How to make python not to create/copy pyobject from boost::shared_ptr during iteration on std::vector via boost::python?

I have an object and std::vector of boost::shared_ptr-s of that objects in it which I want to transfer into python using boost::python.
The problem here is the fact that during iteration over the exposed vector in python I'm getting different addresses every time for the same object.
As I understand, python creates pyobject via my boost::shared_ptr on every iteration and after the iteration (actually after the second iteration) garbage collector frees that address, though the elements are boost::shared_ptr-s.
When the elements are in python's list, they have their unique addresses which are not changing during iterations. This is what I'm trying to achieve.
I tried to surf the internet by reaching different boost documentations and different QAs in stackoverflow but failed to get my issue resolved.
I've created a small example demonstrating this issue.
Here is the C++ code:
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/python.hpp>

namespace bp = boost::python;

class A {
    public:
        A() : m_int(0) { }
        A(int numb) : m_int(numb) { }
        int get_m() const { return m_int; }
    private:
        int m_int;
};

std::ostream& operator<<(std::ostream& out, const A& obj) {
    out << obj.get_m();
    return out;
}

using APtr = boost::shared_ptr<A>;
using ACont = std::vector<APtr>;
using AContPtr = boost::shared_ptr<ACont>;

APtr CreateA() {
    return boost::make_shared<A>();
}

APtr CreateAFromNumb(int numb) {
    return boost::make_shared<A>(numb);
}

AContPtr CreateEmptyACont() {
    return boost::make_shared<ACont>();
}

AContPtr CreateFullACont(int size) {
    ACont vec{};
    for (int i = 0; i < size; ++i) {
        vec.push_back(boost::make_shared<A>(i));
    }
    return boost::make_shared<ACont>(vec);
}

BOOST_PYTHON_MODULE(example) {
    bp::class_<A, APtr, boost::noncopyable>("A", bp::no_init)
        .def("__init__", bp::make_constructor(CreateA))
        .def("__init__", bp::make_constructor(CreateAFromNumb))
        .def(bp::self_ns::str(bp::self))
        ;
    bp::register_ptr_to_python<APtr>();

    bp::class_<ACont, AContPtr, boost::noncopyable>("ACont", bp::no_init)
        .def("__init__", bp::make_constructor(CreateEmptyACont))
        .def("__init__", bp::make_constructor(CreateFullACont))
        .def("__iter__", bp::iterator<ACont>())
        .def("__len__", &ACont::size)
        ;
    bp::register_ptr_to_python<AContPtr>();
}

Here is the usage of it in python:
#!/usr/bin/env python

from example import *

vec = ACont(4)

print len(vec)
print "VEC", vec
for x in vec:
    print x,
    print repr(x)

print "VEC", vec
for x in vec:
    print x,
    print repr(x)

l = [x for x in vec]

print "LIST"
for x in l:
    print x,
    print repr(x)
print "LIST"
for x in l:
    print x,
    print repr(x)

When iterating over the exposed std::vector/boost::shared_ptr<std::vector> I'm getting different addresses for the same elements during just two sequential iterations.

Python creates pyobject on first iteration for the first item and
shows it's address.
On the second iteration, python creates another pyobject for the second element on another address.
Garbage collector sees that the first address is no more usable and frees it.
On the third iteration, python creates another pyobject for the third element in the same address as the first one, since gc just freed it.
And so on.

But iteration over the list of the same elements is being done correctly, since python does not create/destruct pyobjects as they have references in the list itself.
Here is the output of python run:
4
VEC <example.ACont object at 0x7ffff7ea9578>
0 <example.A object at 0x7ffff7eb27d0>    # address 1
1 <example.A object at 0x7ffff7eb2848>    # address 2
2 <example.A object at 0x7ffff7eb27d0>    # address 1 since gc just have freed it
3 <example.A object at 0x7ffff7eb2848>    # so on
VEC <example.ACont object at 0x7ffff7ea9578>
0 <example.A object at 0x7ffff7eb27d0>
1 <example.A object at 0x7ffff7eb2848>
2 <example.A object at 0x7ffff7eb27d0>
3 <example.A object at 0x7ffff7eb2848>
LIST
0 <example.A object at 0x7ffff7eb27d0>    # address 1
1 <example.A object at 0x7ffff7eb2848>    # address 2
2 <example.A object at 0x7ffff7eb28c0>    # address 3
3 <example.A object at 0x7ffff7eb2938>    # address 4
LIST
0 <example.A object at 0x7ffff7eb27d0>
1 <example.A object at 0x7ffff7eb2848>
2 <example.A object at 0x7ffff7eb28c0>
3 <example.A object at 0x7ffff7eb2938>

Summarizing, I would like to know whether there is a way not to create pyobjects in python for each element created in C++ taking into account a fact that these objects are boost::shared_ptr-s of some object.
Thank you in advance.
P.S. I'm using boost version 1.60 and python 2.7 (anaconda package).

A:

So, after long investigations, I found out that the task I wanted to solve does not have a real solution. This is due to the fact that python must register each object (created elsewhere, not in python) that just appeared in its environment to be aware of it. So the rest of scenario, regarding garbage collector, goes like described in the question. Neither boost/python nor swig could handle this case.
But, as a manual solution to this, to solve addressing issues I've created some kind of address mapping functionality. Since my issue was connected with object addresses, I transferred C++ address to python in order to see real object's address instead of python's one.
Also, since I need hashing functionality working on addresses, I did the same thing there. Here is my update
// Same code as previously
std::string GetAddress(const APtr& a_ptr) {
    std::string repr{"<example.A object at "};
    std::stringstream sstream;
    sstream << std::hex << std::showbase << reinterpret_cast<std::uintptr_t>(a_ptr.get());
    repr += sstream.str() + ">";
    return repr;
}

static std::size_t Hash(const APtr& a_ptr) {
    std::hash<std::uintptr_t> hasher;
    return hasher(reinterpret_cast<std::uintptr_t>(a_ptr.get()));
}

BOOST_PYTHON_MODULE(example) {
    bp::class_<A, APtr, boost::noncopyable>("A", bp::no_init)
        .def("__init__", bp::make_constructor(CreateA))
        .def("__init__", bp::make_constructor(CreateAFromNumb))
        .def("__repr__", GetAddress)
        .def("__hash__", Hash)
        .def(bp::self_ns::str(bp::self))
        ;
    bp::register_ptr_to_python<APtr>();

    bp::class_<ACont, AContPtr, boost::noncopyable>("ACont", bp::no_init)
        .def("__init__", bp::make_constructor(CreateEmptyACont))
        .def("__init__", bp::make_constructor(CreateFullACont))
        .def("__iter__", bp::iterator<ACont>())
        .def("__len__", &ACont::size)
        ;
    bp::register_ptr_to_python<AContPtr>();
}

Anyway, thank you all for your effort trying to help. :)


Q:

How can padding be disambiguated from data, when encrypting using a block cipher?

How can padding be disambiguated from data, when encrypting using a block cipher?

I'm by no means an expert in cryptography, but rather a programmer with a keen interest.
Suppose, I've X bytes of data, message M, that I want to encrypt using an N-byte block cipher, where N >> X.
How can M be padded using N-X bytes of padding O, such that there would be no ambiguity between decrypting the padded message M´ and the (concatenated) message M|O?
How is this done in practice? Normally, when encrypting using a block cipher, I don't see a header being output describing the original length of the message M?

A:

The usual padding for block ciphers ("PKCS#7 padding") is not a sequence of zeroes, but a sequence of P = N - (X % N) bytes each with value P.
If the message is a multiple of the block size, then a full block of padding is added (where each byte value is the block size).
For example, is the message is 15-byte long and the block size is 16 bytes, than one byte of padding will be added, and the value of the byte is 1. If the message is 14-byte long, two bytes with value 2 will be added. If the message is 16-byte long, sixteen bytes with value 16 will be added.
With these rules, the padding is unambiguous.


Q:

Server-side validation localization differs from client-side

Whilst this may concern to other topics as well, I'm just heading the following trouble with validation:
Model Annotation, Controller and Action
I use validation attributes from System.ComponentModel.DataAnnotations. The model looks like
public class NewUserModel
{
    [Required]
    public string Username { get; set; }
}

So, nothing special. According to that, a pretty much default controller action
public ActionResult New()
{
    return View(new NewUserModel());
}

and the view
@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.Username)
    @Html.EditorFor(m => m.Username)
    @Html.ValidationMessageFor(m => m.Username)
    <button type="submit">save</button>
}

Setting Culture With Filter
Based on user preferences, culture is set via following filter
public class CultureFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // simplified for this example
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de");
    }
}

which is registered in global.asax with
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new CultureFilter());
}

Default language is english, so the web.config contains
<globalization culture="en-US" uiCulture="en"/>

With that done, client-side validation works perfectly. Data attributes for unobtrusive jQuery validation are localized as you can see in the resulting HTML:
<input data-val="true"
       data-val-required="Das Feld Username ist erforderlich."
       id="Username" name="Username" type="text" value="" />

The Problem: Server-side Validation Without Localization
The trouble is, that forcing server-side validation by disabling JavaScript renders following unlocalized validation message, while the data attribute is still localized:
<input data-val="true"
       data-val-required="Das Feld Username ist erforderlich."
       id="Username" name="Username" type="text" value="" />
The Username field is required.

Looks pretty funny, doesn't it? ;-)
What Did I Try?
First, I checked if the server-side culture is set by web.config. Yes, it is. If I change the <globalization/> attributes to german cultures (or just remove the node as by system language is german), the server-side validation message is german too.
This let me believe there might be a difference in times when server-side and client-side take their messages from resources. And maybe the server-side does it prior to executing the action, which means CultureFilter.OnActionExecuting() is called after that, which of course is too late in this case.
So I tried to set the culture on begin request (global.asax):
protected void Application_BeginRequest()
{
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("de");
}

Well, that did the trick. But I really think this is an ugly solution. So...
The Question: Am I Right and Do I Have Any Other Options?
Is it true, that server-side validation takes the messages from resource before a filter could set the culture? If not, what am I doing wrong? If yes, is there another, cleaner option for setting the culture than the global.asax "hack"?
Thank you in advance.

A:

Thanks to Stephen Muecke's answer, who pushed me in the right direction, I realized there are more filter interfaces which I could implement. A great overview of the MVC lifecycle can be found in this article. It points out that IAuthenticationFilter and IAuthorizationFilter implementations are invoked before the model binding happens.
I decided to use these interfaces (IAuthorizationFilter in my case because IAuthenticationFilter is not available in MVC 3) for my CultureFilter:
// would use IAuthenticationFilter in MVC 5
public class CultureFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        // simplified for this example
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de");
    }
}

This might not be best practice, but in my opinion it's cleaner than using Application_BeginRequest in global.asax and I think, especially with IAuthenticationFilter, setting culture there is the better place than on model binding.


Q:

Passing UNC username and password within a UNC path

Is it possible to pass the UNC username and password within a UNC path?
Similar to how FTP and SMB support this:
smb://user:pass@destination.com/share
ftp://user:pass@destination.com/share

I am trying to get a (non domain PC) service access to a DFS path.
Is there another way around this? I could bind the PC to the domain and run the service as a domain user but what if I was using Linux?

A:

On Windows, you cannot put credentials in UNC paths. You must provide them using net use, runas /netonly, or when asked by Windows. (If you have some programming skills, you can store the SMB password as a "domain credential" using CredWrite(), which is equivalent to checking the "Remember password" box in Windows.)
On Linux, it depends on the program.

GNOME's Gvfs accepts the user@host syntax, but appears to completely ignore the password. (However, you can store it in GNOME Keyring beforehand.)
smbclient uses the same UNC syntax as Windows; however, it has an --authentication-file option from which credentials could be read.
Both programs above are using libsmbclient, and can use Kerberos authentication instead of passwords: run kinit user@YOUR.DOMAIN and use smbclient -k //host/share. This is more secure than password authentication.

Note that putting passwords into URIs is deprecated, and you should not rely on it being supported anywhere.

A:

You can map a "drive" to the UNC path using net use.  Future accesses should share the existing connection
Net Use \\yourUNC\path /user:uname password

Note: you do not need to specify a drive letter


Q:

theme.js and responsive.js not loading in custom theme in magento 2.1.9

I have created a custom theme,
   Thomson/
    └── book
        ├── composer.json
        ├── media
        │   └── image.png
        ├── registration.php
        └── theme.xml

After that I choose my custom theme via admin, my frontend not load correctly.
I tried, static-content deploy, clear cache, and remove <m2>/var/* files
css are calling but  theme.js and responsive.js is goes to 404.
Reference:
Error:

Frontend:

Suggest me, How to fix this..

A:

There are two solutions
Solution 1 -
You need to define parent in your theme.xml file, so the that responsive.js and theme.js file will access from the parent theme
theme.xml ( app/design/frontend/Thomson/Book/theme.xml )
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
   <title>Thomson Book</title>
   <parent>Magento/blank</parent> <!-- the parent theme -->
   <media>
        <preview_image>media/preview.jpg</preview_image>
   </media>
</theme

Solution 2 -
You need to add both the files responsive.js and theme.js in your custom theme.
Thomson/
    └── book
        ├── composer.json
        ├── media
        │   └── image.png
        ├── registration.php
        └── theme.xml
        |-- web
             |--js
                 |--responsive.js
                 |--theme.js


Q:

How to make DBconnection and Node.js Query file separately

I have question. How to connect dbconnection.js and demo_api_select.js I have a problem when declare variable on demo_api_select.js. It doesn't work and have error notification like this:
Error Notification
Please help

dbconnection.js:

var mysql=require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "test"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

module.exports = con;

demo_api_select.js

var db = require('./dbconnection');

db.connect(function(err) {
  if (err) throw err;
  //Select all customers and return the result object:
  con.query("SELECT * FROM profil" , function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

I want to make those code work as well as this code:
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "test"
});

con.connect(function(err) {
  if (err) throw err;
  //Select all customers and return the result object:
  con.query("SELECT * FROM profil" , function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

A:

Try this code.No need to connect twice to database
var db = require('./dbconnection');

db.query("SELECT * FROM profil" , function (err, result, fields) {
   if (err) throw err;
    console.log(result);
   });
});


Q:

PDO PHP Error , Now sure how to fix it?

I am getting the following errors:

Notice: Array to string conversion in line 371
Warning: PDOStatement::execute() [pdostatement.execute]:
  SQLSTATE[HY093]: Invalid parameter number: number of bound variables
  does not match number of tokens on line 371

The code which generate this error is below :
// update member file report...
$sql = 'UPDATE memberFileReports SET membersAdded =?, membersCanceled=?, errors=?, dateProcessed=?, totalProcessed=? WHERE id = ?';

$totalToProcess = $membersAdded + $membersCanceled + $totalErrorCount;

$userarray = array($membersAdded,$membersCanceled,$totalErrorCount,date("Y-m-d H:i:s"),$totalToProcess,$fileDataReportId);

$stmt = $this->db->prepare($sql);

$stmt->execute(array($userarray));

Please help ??

A:

Change $stmt->execute(array($userarray)); to $stmt->execute($userarray);.  Since $userarray is already an array, you don't need to wrap it in a new array.  By wrapping it in a new array like your code was, PDO gets sent 1 parameter when it expected all 6.  This is why the error generated said "number of bound variables does not match number of tokens".


Q:

Binding double property to AngleProperty

Is there a way to control rotation of rectangle via Binding ? I tried it this way but it does not work any idea ?
    // class Unit
    private double _rotation;
    public double rotation
    {
        get
        {
            return _rotation;
        }
        set
        {
            _rotation = value;
            OnPropertyChanged("rotation");
        }
    }
    public Binding rotationBinding { get; set; }

    // Controller class generating UI
    private Rectangle GenerateUnit(Unit u)
    {

        Rectangle c = new Rectangle() { Width = u.size, Height = u.size };

        c.Fill = new ImageBrush(new BitmapImage(new Uri(@"..\..\Images\tank\up.png", UriKind.Relative)));
        c.SetBinding(Canvas.LeftProperty, u.xBinding);
        c.SetBinding(Canvas.TopProperty, u.yBinding);

        RotateTransform rt = new RotateTransform();
        BindingOperations.SetBinding(rt, RotateTransform.AngleProperty, u.rotationBinding);
        c.LayoutTransform = rt;

        return c;
    }

X and Y bindings work fine so I guess that is implemented correctly.
I am just looking for a way to bind the angle property so when I change the rotation property it will rotate the rectangle in UI. (I dont need animation, switching the angle instantly is fine).
Thanks

A:

Problem seems to be in your rotationBinding. You should create binding in your Unit class:
rotationBinding = new Binding("rotation");
rotationBinding.Source = this;// or instance of o your Unit class if you create rotationBinding outside Unit class

It works for me...


Q:

PostgreSQL AFTER INSERT trigger, and referencing the inserted row

I have an INSERT trigger in PostgreSQL that I'm trying to have join the inserted row on another table, and then insert the result in a third table. Let's call the original table, that the INSERT trigger fires on, "A"; the table the cursor joins A on "B"; and the table the trigger function then inserts to "C".
My thinking was that an AFTER INSERT function should allow me to pass a value from the "NEW" row as a parameter in order to reference its corresponding row in Table A, like this:
myCursor CURSOR (insertedKey A.key%TYPE) FOR
  SELECT *
    FROM A
    INNER JOIN B
    ON A.key=B.key
  WHERE A.key=insertedKey;

...

OPEN myCursor (NEW.key);
FETCH NEXT FROM myCursor INTO row_C;
INSERT INTO C VALUES (row_C.*);

This gives me an empty cursor. If I trigger the trigger on AFTER UPDATE, it works, but with the old row from A. This leads me to think that PostgreSQL doesn't think AFTER INSERT/UPDATE means what I think it means.
Or maybe I'm just doing something wrong? Is there any way of doing what I'm trying to do?

A:

Not sure why it happens but you could do something along the line of
INSERT INTO C
  SELECT NEW.*, B.*
    FROM B
    WHERE B.key = NEW.key


Q:

Fisher Paykel Washing Machine Model

Anyone knows what model is this washing machine?
I'm trying to look for the part but can't find its model number.

A:

Model gw712; see the back of the top panel next to the serial number.  Go on their web page, put in the serial number and get the parts list for that machine.


Q:

Can hunting dogs be trained to hunt multiple animals?

Basically, I am wanting my dog to retrieve birds, but also hunt rabbits and foxes. I may also want to use him to smell for blood trails from deer, elk, etc. Would this be possible, or would it just confuse him?

A:

You can't teach an old dog new tricks.
Hunting dogs are trained from pups, you wouldn't necessarily confuse your dog, but you might discover that it doesn't do the best job of what you want it to do (rips your birds apart while retrieving them, isn't fast enough to catch rabbits and foxes, leads you to a steaming pile of poop instead of following a blood trail) Or you might find he isn't that smart, I have a labrador retriever, and he's pretty dumb, he loves to chase things but I've never seen him catch anything. Some cats will let him catch up, but that always results in my dog getting scratched in the face and running away crying (then he goes and pouts to mommy).
One of the reasons we have so many breeds is because certain breeds proved to be more effective than others for certain tasks. Pointers are great for letting you know where animals are hiding and flushing them out. Hounds proved to be excellent trackers and following trails with their extra keen sense of smell. Retrievers proved to be efficient at retrieving game birds without shredding them to bits. Greyhounds were fast enough to chase down and kill rabbits, foxes and coyotes. Irish Wolf Hounds are the reason that wolves are extinct in Ireland. Dachshunds with their powerful bodies and short legs were bred for digging into borrows and hunting badgers. Yorkies, believe it or not, were originally hunting dogs, used to eradicate small mammals like rats, mice, even skunks and other borrowing animals, those little ankle biters are mean for a reason-they're killing machines.
If you already have a dog, you're not going to have much luck training it to be effective at preforming the duties of all the other breeds, but if you started training him early, you could probably teach it how to do an okay job at at least some of them. If there was such a thing as a well-rounded hunting breed, then we'd probably hear about it more often, but as it is hunters prefer their job specific breeds.
According to this site the Pudelpointer is the best all-round hunting dog, so if you want one dog that can do it all, you should consider getting a Pudelpointer pup and start training it from a young age.


Q:

convert uiview to .png image

I am working on iphone and I take the subclass of UIView and in draw rect method I am making some design. I want to convert this view in .png format.
Thanks in advance.

A:

    UIGraphicsBeginImageContext(myView.frame.size);
    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data=UIImagePNGRepresentation(viewImage);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"];
    [data writeToFile:strPath atomically:YES];


Q:

Запятая перед союзом И в сложном предложении

Нужна ли запятая перед И в таком предложении: "Мы любим наш театр, наших зрителей(?) и надеемся, что лучшие спектакли у нас еще впереди."

A:

Любим и надеемся - однородные сказуемые, соединенные союзом и. Запятая не нужна (хотя там и слышится пауза):
Мы любим наш театр, наших зрителей и надеемся, что лучшие спектакли у нас еще впереди.


Q:

Feasability of Angular2 in Salesforce (through VF page)

I've used Angular 1.x in Salesforce with quite a bit of success, but I was wondering if anyone has been able to work with Angular2.
I was able to get a very simple hello world to load, but only if I don't include the SF header (otherwise there seem to be script name-spacing conflicts).
I still don't know much about the framework in general, but it seems like there are a lot more dependancies (which may be an issue).
Just want to know if anyone out there has actually used Angular 2 in a real project and if so:

what does the basic configuration looks? (structure, dependancies, VF
setup, etc)
what issues/concerns/challenges should be considered.

A:

If you're still interested in creating an Angular 2 app on the Salesforce platform I may have a solution for you. I myself love Angular 2 and everything it brings to the table. My company also works exclusively on Salesforce, so I wanted to figure out a way to marry the two.
What I ended up doing was create a boilerplate to make it easier to get started with Angular 2 on Salesforce. The boilerplate itself is available on Github at https://github.com/iDev0urer/salesforce-angular2-boilerplate and allows you to develop your application locally using the REST and SOAP API's to manipulate data. It also provides an easy way to deploy your app to Salesforce using gulp deploy.
Please check it out and give me feedback!


Q:

What is the difference between closed under intersections of finitely many subsets and closed under countable intersections?

It is given in definition, that $\sigma$ algebra is a type of algebra of sets. So if algebra of sets is defined as being closed under intersections with finitely many subsets, does that mean that being closed under countable intersections implies being closed under intersections with finitely many subsets? Countable set is a set which is bijective to a subset of natural numbers? If so, does finitely many mean that you can also have a bijective function with natural number set? And then, why is that important in probability?

A:

Being closed under arbitrary finite intersections does not imply being closed under countable intersections. For example, take the family of co-finite subsets of the natural numbers, that is, the family $F$ of sets whose complement is finite. So, e.g., $\{3,4,5,6,\ldots\}$, which omits the finite set {$0,1,2$}, is in $F$, but the set of even numbers is not (because it’s complement is infinite).
Now, any intersection of finitely many sets from $F$ is in $F$ because the complement of that intersection is the union of the complements, i.e. a finite union of finite sets, which is finite.
But if you look at the countably many sets $A_n = N - \{n\}$ for $n = 0, 1,2,3,\ldots$, each one is in $F$, but their intersection is empty, and the empty set is not in $F$. So $F$ is not closed under countable intersections.


Q:

xcode add embedded binary with buildscript

I have been given a dynamic framework from a third party which does not compile on X86_64 based archs at linker stage due missing symbols, I have asked them repeatedly bundle this architecture with their framework, but they haven't been able to do so until now.
Now my question is the following, I can't find anyway to add the stage embedded binary stage using the build settings, how are the embedded binaries linked to the app during the build/linker process?
I know that if they do so, i might have to strip the arch from the framework, but it beats to not being able to compile the framework.

A:

It turns out that the embedded binary stage is nothing more than xcode copying the .framework into the an target bundle Framework folder so to achieve my final intentions of creating a script that adds a framework completely manually.
Which resulted in two scripts, one that is added right after target dependencies in build phases, must be before compile sources:
if [[ $PLATFORM_NAME == 'iphoneos' ]]; then

    SOME_FRAMEWORK=$BUILT_PRODUCTS_DIR"/"$PRODUCT_NAME".app/Frameworks/someframework.framework/"
    export LIBRARY_SEARCH_PATHS=$LIBRARY_SEARCH_PATHS" "$SDKROOT"/someframework.framework"
fi

and Another script and link binary with Libraries, where i copy and sign the framework.
if [[ $PLATFORM_NAME == 'iphoneos' ]]; then
    MY_FRAMEWORK=$BUILT_PRODUCTS_DIR"/"$PRODUCT_NAME".app/Frameworks/someframework.framework/"
    mkdir -p $BUILT_PRODUCTS_DIR"/"$PRODUCT_NAME".app/Frameworks"
    cp -Rv $PROJECT_DIR"/someframework.framework" $MY_FRAMEWORK

    CODE_SIGN_IDENTITY_FOR_ITEMS="${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
    if [ "${CODE_SIGN_IDENTITY_FOR_ITEMS}" = "" ] ; then
        CODE_SIGN_IDENTITY_FOR_ITEMS="${CODE_SIGN_IDENTITY}"
    fi

    codesign --force --verbose --sign "${CODE_SIGN_IDENTITY_FOR_ITEMS}" $MY_FRAMEWORK"/<binary of framework>"
fi

this is just a quick rough script i created quickly to achieve this. I only allow this to happen i target is a device as this was my original intentions. but it can be removed.

A:

Thank you @RicardoDuarte;
There is my script for both iPhone & simulator.
Example_To=$BUILT_PRODUCTS_DIR"/"$PRODUCT_NAME".app/Frameworks/Example.framework/"
Example_From=$PROJECT_DIR"/../out/Build/Products/"$CONFIGURATION$EFFECTIVE_PLATFORM_NAME"/Example.framework"

mkdir -p $BUILT_PRODUCTS_DIR"/"$PRODUCT_NAME".app/Frameworks"
cp -Rv $Example_From $Example_To

if [[ $PLATFORM_NAME == 'iphoneos' ]]; then
    CODE_SIGN_IDENTITY_FOR_ITEMS="${EXPANDED_CODE_SIGN_IDENTITY_NAME}"

    if [ "${CODE_SIGN_IDENTITY_FOR_ITEMS}" = "" ] ; then
        CODE_SIGN_IDENTITY_FOR_ITEMS="${CODE_SIGN_IDENTITY}"
    fi

    codesign --force --verbose --sign "${CODE_SIGN_IDENTITY_FOR_ITEMS}" $Example_To
fi

I also added path to framework

$(PROJECT_DIR)/../out/Build/Products/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)

to "Framework Search Paths" and "Header Search Paths", your's path and framework name can be different of course.


Q:

some issue for Group by sum Trading report

Some Minor Issue in my query can you help for issue.
This Is my Query
declare @table table (
    groupname varchar(50),
    credit numeric(18,2),
    debit numeric(18,2),
    undergroup varchar(50)
)

insert into @table
values ('Sales', 1210.00, 0.00, 'Sales'),
       ('Sales Return', 0.00, 0.00, 'Sales'),
       ('Closing Stock', 1400.00, 0.00, 'Closing Stock')

SELECT ROW_NUMBER() OVER ( ORDER BY undergroup ) Cr_RN,
    groupname Cr_GroupName,
    ABS(Credit+Debit) Cr_Amount,
    ABS(LAG(Credit, 1, 0) OVER ( ORDER BY groupname ) -Debit ) AS Cr_Total
    FROM(
        SELECT
            GroupName GroupName,
            undergroup,
            SUM(ISNULL(Credit,0.00)) OVER (PARTITION BY groupname) AS Credit,
            SUM(ISNULL(Debit*-1,0.00)) OVER (PARTITION BY groupname) AS debit
        FROM @table
    ) X

My query Output

Some Hint for output

And I want this type of output

A:

Alpesh, can you check this query please? This should give the expected results.
SELECT ROW_NUMBER() OVER (ORDER BY undergroup ) Cr_RN,
    groupname Cr_GroupName,
    ABS(Credit+Debit) Cr_Amount,
    CASE WHEN LEAD(RID,1,0)OVER ( ORDER BY undergroup ) =RID+1 THEN 0 ELSE
    ABS(UG_Credit - UG_Debit ) END AS Cr_Total
    FROM(
        SELECT ROW_NUMBER() OVER (PARTITION BY undergroup ORDER BY undergroup ) RID,
            GroupName GroupName,
            undergroup,
            SUM(ISNULL(Credit,0.00)) OVER (PARTITION BY groupname) AS Credit,
            SUM(ISNULL(Debit*-1,0.00)) OVER (PARTITION BY groupname) AS debit,
            SUM(ISNULL(Credit,0.00)) OVER (PARTITION BY undergroup) AS UG_Credit,
            SUM(ISNULL(Debit*-1,0.00)) OVER (PARTITION BY undergroup) AS UG_Debit
        FROM @table
    ) X


Q:

Delete a row from a gridview outside the deleterow method

I want to delete a row outside the RowDeleting Method.
I'm trying to do that this way, but it asks for the sender and the row to delete, but I get a conversion error.
Can't convert type gridview row to gridview delete event args
here's my code, do you notice anything wrong?
grdContact_RowDeleting((object)grdContact, (GridViewDeleteEventArgs)grdContact.Rows[0]);

protected void grdContact_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    List<DettagliFattura> app = (List<DettagliFattura>)Session["lst_dettagli"];
    app.RemoveAt(e.RowIndex);

    Session["lst_dettagli"] = app;
    FillGrid();
    CalcolaTotale();
}

A:

use a empty template as show below by using tr and td
<EmptyDataTemplate>

                                                    <asp:TextBox runat="server" ID="coursetxt"></asp:TextBox>

                                                    <asp:Label ID="lbladd3" runat="server"></asp:Label>
                                                    <asp:TextBox runat="server" ID="Universitytxt"></asp:TextBox>

                                                    <asp:TextBox runat="server" ID="sdatetxt"></asp:TextBox>

                                                    <asp:TextBox runat="server" ID="endtxt"></asp:TextBox>

                                                    <asp:Button ID="btnInsertRecordedu" runat="server" CssClass="buttonpop" Text="Add" ValidationGroup="edu" CommandName="Insert_emptydatatemplate" />

                                        </EmptyDataTemplate>


Q:

PHP create JSON file from Twitter API

I've been reading more on PHP JSON and APIs I wanted to play around and pull a user's tweets so I wrote a function that requires the TwitterAPIExchange wrapper.
The code:
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
get_twitter_json();

function get_twitter_json() {
    $username       = 'foobar';
    $count          =   5;
    $json_folder    = 'json';
    $pull_time      =   1;

    $settings = array(
        'oauth_access_token'        => "",
        'oauth_access_token_secret' => "",
        'consumer_key'              => "",
        'consumer_secret'           => ""
    );

    if (is_dir($json_folder)) :
        echo "Directory $json_folder exists
";
    else :
        echo "Did NOT find directory $json_folder
";
        exit();
    endif;

    $file_loc   = "json/twitter.json";
    $cachetime  = @filemtime($file_loc);
    $diff       = time() - $cachetime;

    if ($diff <= 60 * $pull_time) :
        $results    = json_decode(file_get_contents($file_loc));
    else :
        $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
        $getfield = '?screen_name=' . $username . '&count=' . $count;
        $requestMethod = 'GET';
        $twitter = new TwitterAPIExchange($settings);
        $results = json_decode(
            $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest(), true
        );

        $i = 0;
        if (isset( $results['error'])) :
            echo 'Issue found in request';
            exit();
        else :
            foreach($results as $tweet) :
                $tweets[$i]['created']      = $tweet['created_at'];
                $tweets[$i]['text']         = $tweet['text'];
                $tweets[$i]['username']     = $tweet['user']['name'];
                $tweets[$i]['screenname']   = $tweet['user']['screen_name'];
                $tweets[$i]['url']          = $tweet['user']['url'];
                $i++;
            endforeach;
        endif;

        $jsonified = json_encode($tweets);
        $jsoncache = $file_loc;
        $fp = fopen($jsoncache, "w");
        fwrite($fp, $jsonified);
        fclose($fp);
    endif;

}

Are there any improvements I can make to my code?  Eventually I will implement this into a WordPress Plugin.  I am curious about any better approaches than fwrite and fclose so if there is a better way to write to a JSON file that would be helpful.

A:

This is a partial review.
$file_loc and $json_folder
Use $json_folder in the construction of $file_loc. If you decide to use a different folder, you need change two variables.
$file_loc = "{$json_folder}/twitter.json";

Naming of function
You named your function get_twitter_json()... which... does essentially nothing. It does not return json like the function name suggests. It doesn't even return the twitter result. Instead this seems a partial implementation of a processing function. If it is supposed to return tweets, then name at least something like get_tweets().
Whitespace
Use consistent whitespace. Trying to align all assignments to the same indentation will create problems sooner than later. Changing one assignment will mess up the rest. Multi-line assignments will look even weirder. I would recommend 1 space before the assignment operator (=) and one space after it.
$results and $tweets
The if-else-statement should have some code behind it. The if-statement loads the decoded json-file in $results, while the else-statement loads it in $tweets. Use one of them.
While you are at it, while php allows you to use $tweets undefined like that, it doesn't make for clear code.
foreach with a counter
You are using a foreach loop with a custom counter. That... defeats the purpose of a foreach loop. Either use a for loop and use the exposed counter from that, or use the append syntax to don't need a counter.
foreach($results as $tweet) :
    $new_tweet = array();
    $new_tweet['created']      = $tweet['created_at'];
    $new_tweet['text']         = $tweet['text'];
    $new_tweet['username']     = $tweet['user']['name'];
    $new_tweet['screenname']   = $tweet['user']['screen_name'];
    $new_tweet['url']          = $tweet['user']['url'];
    $tweets[] = $new_tweet;
endforeach;


Q:

socket select fails with operation in progress - Non blocking mode

Our application uses a non-blocking socket usage with connect and select operations (c code).
The pusedo code is as below
unsigned int ConnectToServer(struct sockaddr_in *pSelfAddr,struct sockaddr_in *pDestAddr)
{
    int sktConnect = -1;

    sktConnect = socket(AF_INET,SOCK_STREAM,0);
    if(sktConnect == INVALID_SOCKET)
        return -1;

    fcntl(sktConnect,F_SETFL,fcntl(sktConnect,F_GETFL) | O_NONBLOCK);
    if(pSelfAddr != 0)
    {
        if(bind(sktConnect,(const struct sockaddr*)(void *)pSelfAddr,sizeof(*pSelfAddr)) != 0)
        {
            closesocket(sktConnect);
            return -1;
        }
    }

    errno = 0;
    int nRc = connect(sktConnect,(const struct sockaddr*)(void *)pDestAddr, sizeof(*pDestAddr));
    if(nrC != -1)
    {
        return sktConnect;
    }

    if(errno != EINPROGRESS)
    {
        int savedError = errno;
        closesocket(sktConnect);
        return -1;
    }

    fd_set scanSet;
    FD_ZERO(&scanSet);
    FD_SET(sktConnect,&scanSet);

    struct timeval waitTime;
    waitTime.tv_sec = 2;
    waitTime.tv_usec = 0;

    int tmp;
    tmp = select(sktConnect +1, (fd_set*)0, &scanSet, (fd_set*)0,&waitTime);
    if(tmp == -1 || !FD_ISSET(sktConnect,&scanSet))
    {
        int savedErrorNo = errno;
        writeLog("Connect %s failed after select, cause %d, error %s",inet_ntoa(pDestAddr->sin_addr),savedErrorNo,strerror(savedErrorNo));
        closesocket(sktConnect);
        return -1;
    }

    .
    .
    .
    .
    .}

Problem statement
In the above code, the select fails with error code 115 which is "Operation in progress". I do not see any documentation on select failing with errno 115.
a. When does the select fails with error code 115 in non-blocking socket? Under what scenario?
b. Do we see any system logs which hints at this problem. Only concern for us me - I could not find any documented feature which describes such problem.

PS : We are using SUSE Linux 11 Enterprise Edition.

A:

Some thoughts on your code:
I think your condition below the select can be modified to check only to see, if select has returned a value greater than 0 and if that is the case, you can check output of getsockopt for the socket (for SOL_SOCKET and SO_ERROR) options (getsockopt(...,SOL_SOCKET, SO_ERROR,...,...)) to see if connect has not failed.
I am not very sure if the select will always return the socket as writable in case of a connection success. So, in your case, it may (only may) be the case that, the tmp variable is not -1 and the errno it is showing is the errno of the previous connect call.
Additional Reasons:
Another good reason is that, the destination address to which you are connecting is either not reachable, or doesn't have a server waiting at the specified address + port combination. In which case, you can try once with a blocking socket to see if that connects.


Q:

How can I find the word starting at a specific character position and not word postion in a string?

Str="I love chocolate pudding"
pos=7
def getWordatPos(pos):
    xxx

I need to return the word at the pos 7 which is chocolate. Is there anyway to do that? I know it is easy if chocolate is at index 2 but I need it at the character position.

A:

You can try.
Str="I love chocolate pudding"
pos=7

ans=Str[pos:].split()[0]

Output
"chocolate"

Str[pos:] return 'chocolate pudding', Then I split them using split which return ['chocolate','pudding'] and I extracted 1st-word using indexing.
If pos=8 the output would be 'hocolate'.


Q:

Pythagorean Triple finder

Would like some feedback on a code style exercise motivated by this PythagTriple algorihtm. I started with the Rosetta Code - "efficient C" solution  (not the naive one) and refactored it heavily into modern C++17.
It doesn't quite match their "Task spec". That that was not the focus. However, it could very easily be adopted to do so - just a few changes in main().Performance appears very similar to the C code I started with and the generated ASM seems reasonable.
But the main focus here is style, ease of readability, maintenance and correctness.
Specific feedback points I am looking for:

Use of the lambda to process each triple
Way of constraining the template to prevent unsuitable lambda's being passed. (C++20 concepts needed to do it cleanly?)
Use of initialisers for static data. Also is there a way to get away from the {{ .. {{ .. {},{},{} .. }} .. }}  craziness? 4 extra opening and closing braces.
Use of specific type for vec3 and a using alias for trans
Body of the transform() function. Is there a map() ... splat way?
General function signatures / use of const, constexpr, attributes etc
Use of "by value" vs "by ref" semantics for triples / tranforms etc. There are some "arguably redundant" const T&s in there which were just as fast as "by value" (probably copy elided).
More algorithmic question: The algorithm as implemented is constrained by max_perimeter and due to recursive DFS flow and the matrix transforms the triples come out in a (subjectively) "weird order". Several other constraints and orderings are conceivably possible. One idea is to implement several alternative .find_XX() methods to do that.

EDIT: There is updated code in a separate answer below, integrating the feedback.
#include <array>
#include <iostream>

namespace pythag {

class triple {
 public:
  const long _a;
  const long _b;
  const long _c;

  template <typename F>
  constexpr void find(long max_perim, F&& proc) {
    if (perimeter() > max_perim) return;
    proc(*this);
    for (auto& T : U) transform(T).find(max_perim, proc);
  }

  [[nodiscard]] constexpr long perimeter() const noexcept { return _a + _b + _c; }

  friend std::ostream& operator<<(std::ostream& stream, const triple t) noexcept {
    return stream << t._a << ", " << t._b << ", " << t._c;
  }

private:
  struct vec3 {  // a strong type to distinguish from triple
    const int _x;
    const int _y;
    const int _z;
  };

  using trans = std::array<vec3, 3>;

  [[nodiscard]] constexpr long dot(vec3 V) const noexcept {
    return V._x * _a + V._y * _b + V._z * _c;
  }

  [[nodiscard]] constexpr triple transform(const trans& T) const noexcept {
    return triple{dot(T[0]), dot(T[1]), dot(T[2])};
  }

  static constexpr auto U = std::array<trans, 3>{{
      // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships
      // clang-format off
      {{{  1, -2,  2},     // vec3 U[0][0]
        {  2, -1,  2},     // vec3 U[0][1]
        {  2, -2,  3}}},   // vec3 U[0][1]

      {{{  1,  2,  2},     // vec3 U[1][0]
        {  2,  1,  2},     // vec3 U[1][1]
        {  2,  2,  3}}},   // vec3 U[1][2]

      {{{ -1,  2,  2},     // vec3 U[2][0]
        { -2,  1,  2},     // vec3 U[2][1]
        { -2,  2,  3}}},   // vec3 U[2][2]
      // clang-format on
  }};
};

} // namespace pythag

int main() {
  // basic usage demo
  long sum_peri = 0;
  long count = 0;

  pythag::triple{3, 4, 5}.find(
      100'000'000, // produces 7'023'027 "primitive" triples in <100ms on i7 2600
      // [](const auto& t) { std::cout << t << "\n"; });  // print option. slow obviously
      [&sum_peri, &count](const auto& t) { sum_peri += t.perimeter(); ++count; });

  std::cout << count << "\n";        // these 2 lines are just a way to prevent
  return (sum_peri ^ count) & 0xff;  // entire programme being optimised away
}

A:

Here are some comments on your revised code, many of which apply to your original code as well.
for (auto& T: U) transform(T).find(max_perim, proc);

You're using the names T and U to refer to things that are not template type parameters. In fact, U is a reference to a static data member of the enclosing class, whose only declaration appears many lines below this use. This is extremely surprising code. I might instead write
for (auto&& formula : this->child_formulas) {
    this->transform(formula).find(max_perim, proc);
}

Notice the use of braces around the loop body; the use of auto&&, Which Always Works; the use of this-> to clarify for the human reader what scope we're expecting to find these names in; and especially the descriptive name child_formulas for U. (child_formulas says what U is; this-> says whose it is. Both of those things were in question, in the old code.)

class triple : public std::array<long, 3> {

Don't inherit from standard types. It's legal C++, but it's bad practice.

If you (or your project, or your company) didn’t write class Foo, then class Foo should not be granted control over the API of your own class. And that’s what you’re doing when you inherit from a base class: you’re granting that class control over your API.

I like your original x, y, z data members much better.

template <typename F>
void find(long max_perim, F&& proc) {

You're passing proc by perfect-forwarding, but then when you use it, you're using it as a plain old lvalue. This is fine (in the wild-west anything-goes world of templates), but it doesn't express the meaning of proc quite as well as I'd like. proc is supposed to be a callback that gets called for each triple, right? Calling a callback doesn't modify the callback. So, we can and should require that proc be const-callable, and then we just write
template<class F>
void find(int max_perim, const F& proc) {

(Drive-by irrelevant style adjustments to save typing. long varies in size and is the same size as int on many platforms, so let's just use int until we're ready to step all the way up to a well-defined int64_t or __int128_t.)
If you really want to support non-const and/or rvalue-callable Fs, you can perfect-forward proc all over the place, but trust me, it's not worth it. (The std::forward<F>(proc)s will clutter your code, and all you're doing is enabling your users to write confusing and unintuitive client code.)
Vice versa, re your question about concepts: You can constrain this template to SFINAE away in C++17 (or C++11) like this:
template<class F, class = std::enable_if_t<std::is_invocable_v<const F&, triple&>>>
void find(int max_perim, const F& proc) {

This is not much more boilerplate than the C++2a concepts version:
template<class F> requires std::is_invocable<const F&, triple&>
void find(int max_perim, const F& proc) {

Notice that in C++2a you will also be able to write "simply"
void find(int max_perim, const std::invocable<triple&> auto& proc) {

but (A) this doesn't express exactly the same SFINAE-constraint as the other two, and (B) IMHO it looks more confusing and scary.
But should you constrain this function to SFINAE away when it's given a "bad" lambda type? IMHO, no, you shouldn't. There's no reason to SFINAE here. SFINAE is for when you need this version of find to drop out of the overload set so that some other more general version can pick up the call. That's not the situation that you have, here.
Compare the error messages you get from (A) (or the C++2a Concepts version (A2))
template<class F, class = std::enable_if_t<std::is_invocable_v<const F&, triple&>>>
void find(int max_perim, const F& proc) {
    proc(*this);
}

this->find(42, 7);

versus (B)
template<class F>
void find(int max_perim, const F& proc) {
    static_assert(std::is_invocable_v<const F&, triple&>);
    proc(*this);
}

this->find(42, 7);

versus (C)
template<class F>
void find(int max_perim, const F& proc) {
    proc(*this);
}

this->find(42, 7);

and see which version feels most "user-friendly" for the client programmer. (Remember that someone using find correctly will never see any of these error messages, so you should optimize to help the guy who doesn't know how to use it.)

  cnt_next_depth += U.size(); // always 3
  if (--cnt_this_depth == 0) {
    if (++depth > max_depth) return;
    cnt_this_depth = cnt_next_depth;
    cnt_next_depth = 0;
  }
  for (auto& T: U) q.push(t.transform(T));

Code comments are usually a red flag, at least on CodeReview. ;) It seems that this += corresponds to the three calls to q.push below; i.e., your algorithm requires that cnt_next_depth exactly track q.size(). But you can't use q.size() because you are reusing q to store both the elements at the current level and the elements at the next level.
It would make more sense to use two different queues:
std::vector<triple> this_level = ...;
std::vector<triple> next_level;
for (int i=0; i < max_depth; ++i) {
    for (auto&& t : this_level) {
        proc(t);
        for (auto&& formula : child_formulas) {
            next_level.push_back(t.transform(formula));
        }
    }
    this_level = std::move(next_level);
    next_level.clear();
}

As a bonus, it turns out that we don't even need them to be queues anymore; they can be plain old vectors, and we save a bunch of heap traffic.

friend std::ostream& operator<<(std::ostream& stream, const triple& t) noexcept {
  // Frustrating boiler plate. Any terse alternatives, that do it quickly and correctly?
  char comma[] = {'\0', ' ', '\0'}; // NOLINT
  for (auto d: t) {
    stream << comma << d;
    comma[0] = ',';
  }
  return stream;
}

No good answer. The idiomatic way would be
friend std::ostream& operator<<(std::ostream& stream, const triple& t) {
    bool first = true;
    for (auto&& d : t) {
        if (!first) stream << ", ";
        stream << d;
        first = false;
    }
    return stream;
}

Notice that this function is not noexcept, because any of these stream operations might throw. (For example, if you're writing to a stringstream and it throws bad_alloc.)
Also, in real life I'd write for (int d : t) to indicate exactly what type of "elements" I expect to be getting out of a triple. I'm using auto&& here only because I saw your comment that you want to stick with "Almost Always Auto" style.

  triple transform(const trans& T) const noexcept {
    auto res = triple{};
    std::transform(T.begin(), T.end(), res.begin(), [this](vec3 V) {
      return std::inner_product(V.begin(), V.end(), this->begin(), 0L);
    });
    return res;
  }

This is interesting use of STL algorithms, but algorithms are really meant for operating on big anonymous ranges of data elements, not for constant-size situations like we have here. In order to use STL algorithms, you've been forced to anonymize your formulas into faceless data ranges:
  static constexpr auto U = std::array<trans, 3>{{
      // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships
      {{{{{1, -2, 2}},    // vec3 U[0][0]
         {{2, -1, 2}},    // vec3 U[0][1]
         {{2, -2, 3}}}}}, // vec3 U[0][1]

      {{{{{1, 2, 2}},    // vec3 U[1][0]
         {{2, 1, 2}},    // vec3 U[1][1]
         {{2, 2, 3}}}}}, // vec3 U[1][2]

      {{{{{-1, 2, 2}},    // vec3 U[2][0]
         {{-2, 1, 2}},    // vec3 U[2][1]
         {{-2, 2, 3}}}}}, // vec3 U[2][2]
  }};

Compare that code to a more "code-driven" version:
triple transform(const Formula& f) const noexcept {
    return f(x, y, z);
}

auto formulas[] = {
    +[](int x, int y, int z){ return triple{ x - 2*y + 2*z, 2*x - y + 2*z, 2*x - 2*y + 3*z}; },
    +[](int x, int y, int z){ return triple{ x + 2*y + 2*z, 2*x + y + 2*z, 2*x + 2*y + 3*z}; },
    +[](int x, int y, int z){ return triple{ -x + 2*y + 2*z, -2*x + y + 2*z, -2*x + 2*y + 3*z}; },
};

In this version, trans is gone already, and t.transform(f) is hardly pulling its weight.

if (perimeter() > max_perim) return;

Consider what you'd do if you wanted to find all triples up to some maximum side length, or up to some maximum hypotenuse length. Does this approach generalize to
triple.find(callback_on_each_triple, stopping_condition);

?

A:

Use of the lambda to process each triple

Sure, why not. Nothing wrong with using a lambda in main() here instead of writing a normal function.

Way of constraining the template to prevent unsuitable lambda's being passed. (C++20 concepts needed to do it cleanly?)

If you could live with pythag::triple::find() not being constexpr, then you don't need C++20 for this at all. Just use std::function<> for the type of proc:
#include <functional>
...
void find(long max_perim, std::function<void(triple &)> proc) {
    ...
}

Use of initialisers for static data. Also is there a way to get away from the {{ .. {{ .. {},{},{} .. }} .. }} craziness? 4 extra opening and closing braces.

Yes, by not using std::array<>, but just declaring a multidimensional, "C-style" array:
  static constexpr vec3 U[3][3] {
      {{  1, -2,  2},     // vec3 U[0][0]
       {  2, -1,  2},     // vec3 U[0][1]
       {  2, -2,  3}},    // vec3 U[0][1]

      {{  1,  2,  2},     // vec3 U[1][0]
       {  2,  1,  2},     // vec3 U[1][1]
       {  2,  2,  3}},    // vec3 U[1][2]

      {{ -1,  2,  2},     // vec3 U[2][0]
       { -2,  1,  2},     // vec3 U[2][1]
       { -2,  2,  3}},    // vec3 U[2][2]
  };

You need to change transform() as well:
  [[nodiscard]] constexpr triple transform(const vec3 T[3]) const noexcept {
    return triple{dot(T[0]), dot(T[1]), dot(T[2])};
  }

Use of specific type for vec3 and a using alias for trans

I think you could've made vec3 an array as well, either std::array<> (at the cost of even more braces) or just int[3]. Since you use trans in multiple places, it's good to have made an alias for it. But what's weird is that you write:
static constexpr auto U = std::array<trans, 3>{...};

The auto is totally unnecessary here, you could've written it simply as:
static constexpr std::array<trans, 3> U{...};

Body of the transform() function. Is there a map() ... splat way?

There's std::inner_product which could replace dot(), and std::transform() could have replaced the body of transform(), if your triples and vectors were arrays. It would have looked like:
triple transform(const trans& T) const {
    triple result;
    return std::transform(T.begin(), T.end(), result.values.begin(),
        [this](vec3 V){
            return std::inner_product(V.begin(), V.end(), this->values.begin(), 0);}
        }
    );
}

Instead of const long _a, _b, _c you'd have to have something like std::array<long, 3> values to make it work.

General function signatures / use of const, constexpr, attributes etc

Does it really need to be constexpr? It is restricting you (you can't use std::function<> for find() for example), and I don't see any reason why you would ever need to know the number of Pythogorean triples up to some value at compile-time.
Of course, marking things const, constexpr, [[nodiscard]] and so on where possible is a good thing. Keep doing that.
I would however change the type of the components of vec3 to long, to match that of the triple itself. You could even think of making an alias for the value type, or make the whole class templated, so you can decide which value type to use.

Use of "by value" vs "by ref" semantics for triples / tranforms etc. There are some "arguably redundant" const T&s in there which were just as fast as "by value" (probably copy elided).

With optimization enabled, any decent compiler will probably generate the same assembly code here, regardless of whether you pass by value or by const reference.
You even missed the possibility to make operator<<() take a const reference.

More algorithmic question: The algorithm as implemented is constrained by max_perimeter and due to recursive DFS flow and the matrix transforms the triples come out in a (subjectively) "weird order". Several other constraints and orderings are conceivably possible. One idea is to implement several alternative .find_XX() methods to do that.

What algorithm is best depends on the application. Your recursive DFS algorithm is probably the most elegant one to implement, but apart from the weird output order, the main issue is that you can run out of stack space if the recursion goes too deep. So try to implement another algorithm that doesn't require recursive function calls.


Q:

$(this) vs this in jQuery

What is the difference between $(this) and this in jQuery ? Here are two different usage :
 $(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
     $(this).append( " BAM! " + i );
   });
 });

 $(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });

A:

The "this" variable refers (in such cases as the event handlers you've supplied) to a DOM element. Thus $(this) is a jQuery object containing just that one DOM element.
You should use plain "this" when the native DOM APIs suffice, and $(this) when you need the help of jQuery. Your second example is a good illustration; another might be when you just need the "id" or "name" of an element.

A:

The difference is that this by itself is a reference to the dom object that the event is acting upon. $(this) is creating a jquery object from that dom object.
EDIT: So with the DOM object you aren't going to have access to all the jquery added functionality but only what the dom allows. Basically you can think of the this by itself as the same as if you did document.getElementById(id)

A:

$(this) is a jquery object while this refers to native dom object


Q:

CSV file: newline in file

I have data in a database that needs to be exported to CSV. Some of the fields include addresses and such, which include newlines which MUST be preserved. The data is being exported like this (this is sample data of course):
"Bob Smith",38,"Fire Chief","1234 Obscure St.
Random Town, NA, 12345"

Which doesn't show up correctly in Excel, or import correctly with TextFieldParser class. Is it possible to export newlines in CSV files? How?

A:

Substitute the newline characters in the data with a unique combination of other characters (eg,"*#^$&@!").  Undo the substitution on the other end.


Q:

Perl Moose::Util::TypeConstraints bug ? what is this error about the name has invalid chars?

That has been hours i am tracking a Moose::Util::TypeConstraints exceptions, i don't understand where it gets to check a type and tells me that the name is incorrect. I tracked the error to a reduced example to try to locate the problem, and it just shows me that i do not get it.
Did i get to a Moose::Util::TypeConstraints bug ?
aoffice:new alex$ perl -c ../codesnippets/typeconstrainterror.pl
../codesnippets/typeconstrainterror.pl syntax OK
aoffice:new alex$ perl -d ../codesnippets/typeconstrainterror.pl
(...)
DB<1> r
Something::File::LocalFile=HASH(0x100d1bfa8) contains invalid characters for a type name. Names can contain alphanumeric character, ":", and "."
 at /opt/local/lib/perl5/vendor_perl/5.10.1/darwin-multi-2level/Moose/Util/TypeConstraints.pm line 508
    Moose::Util::TypeConstraints::_create_type_constraint('Something::File::LocalFile=HASH(0x100d1bfa8)', undef, undef, undef, undef) called at /opt/local/lib/perl5/vendor_perl/5.10.1/darwin-multi-2level/Moose/Util/TypeConstraints.pm line 285
    Moose::Util::TypeConstraints::type('Something::File::LocalFile=HASH(0x100d1bfa8)') called at ../codesnippets/typeconstrainterror.pl line 7
    Something::File::is_slink('Something::File::LocalFile=HASH(0x100d1bfa8)') called at ../codesnippets/typeconstrainterror.pl line 33
Debugged program terminated.  Use q to quit or R to restart,
  use o inhibit_exit to avoid stopping after program termination,
  h q, h R or h o to get additional info.

Below, the code that crashes:
package Something::File;
use Moose;
has 'type' =>(is=>'ro', isa=>'Str', writer=>'_set_type' );

sub is_slink {
    my $self = shift;
    return ( $self->type eq 'slink' );
}

no Moose;
__PACKAGE__->meta->make_immutable;
1;

package Something::File::LocalFile;
use Moose;
use Moose::Util::TypeConstraints;

extends 'Something::File';

subtype 'PositiveInt'
     => as 'Int'
     => where { $_ >0 }
     => message { 'Only positive greater than zero integers accepted' };

no Moose;
__PACKAGE__->meta->make_immutable;
1;

my $a = Something::File::LocalFile->new;
# $a->_set_type('slink');
print $a->is_slink ." end\n";

A:

Elevating this from a comment on hobb's answer.
What's happening is that your method name type that is inherited into Something::File::LocalFile via extends 'Something::File'; is colliding with the type function exported by Moose::Util::TypeConstraints.
I believe that if you use namespace::autoclean inside Something::File::LocalFile you'll see this problem go away. Alternatively if you limit the exports from Moose::Util::TypeConstraints to only the functions you need (ie use Moose::Util::TypeConstraints qw(subtype) the problem will also go away.


Q:

Display lines when the digits repeated in same line

I would like to display the lines on text if 3 digits repeated in same line
with a condition applied for 3 digits repeat.
Input
410202410
203103903
555710294473555

so 410 and 555 repeated
Output
410202410
555710294473555

how to handle this through sed or awk?
I would like also to apply the same only on digits before first comma.
such as 410202410,11,2017,109

A:

POSIXly:
grep '\([0-9]\{3\}\).*\1'

Would print the lines that contain 3 decimal digits followed by a sequence of 0 or more characters followed by the same 3 digits.
To restrict that pattern before the first comma:
grep '^[^,]*\([0-9]\{3\}\)[^,]*\1'


Q:

FileReader and BufferedReader

I have 3 methods

for open file
for read file
for return things read in method read

this my code :
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication56;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author x
 */
public class RemoteFileObjectImpl extends java.rmi.server.UnicastRemoteObject  implements RemoteFileObject
{
    public RemoteFileObjectImpl() throws java.rmi.RemoteException {
        super();
    }

    File f = null;
    FileReader r = null;
    BufferedReader bfr = null;

    String output = "";
    public void open(String fileName) {
        //To read file passWord
        f = new File(fileName);
    }
    public String readLine() {
        try {
            String temp = "";
            String newLine = System.getProperty("line.separator");
            r = new FileReader(f);
            while ((temp = bfr.readLine()) != null) {
                output += temp + newLine;
                bfr.close();
            }
        }
        catch (IOException ex) {
           ex.printStackTrace();
        }

        return output;
    }

    public void close() {
        try {
            bfr.close();
        } catch (IOException ex) {
        }
    }

    public static void main(String[]args) throws RemoteException{
        RemoteFileObjectImpl m = new RemoteFileObjectImpl();
        m.open("C:\\Users\\x\\Documents\\txt.txt");
        m.readLine();
        m.close();
    }
}

But it does not work.

A:

What do you expect it to do, you are not doing anything with the line you read, just
m.readLine();

Instead:
String result = m.readLine();

or use the output variable that you saved.
Do you want to save it to a variable, print it, write it to another file?
Update: after your update in the comments:
Your variable bfr is never created/initialized. You are only doing this:
r = new FileReader(f);

so bfr is still null.
You should do something like this instead:
bfr = new BufferedReader(new FileReader(f));


Q:

does lucene standardanalyzer remove stopwords and have stemming function?

i have tested standardanalyzer with indexWriter and found that it automatically removes stopwords, however, i did not add stopwords list as following code is what i used
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
        IndexWriterConfig config =new IndexWriterConfig(Version.LUCENE_35, analyzer);

where is default stopwords list?
also, does this analyzer automatically stem words too??

A:

According to the API docs, there exists a default set of stopwords (taken from English language), stored in StandardAnalyzer.STOP_WORDS_SET. It is used if you create the analyzer with the constructor public StandardAnalyzer(Version matchVersion), which is exactly what you do. The set is exactly the same as StopAnalyzer.ENGLISH_STOP_WORDS_SET. You can use one of the other constructors to pass the analyzer another (possibly empty) set of stopwords.
StandardAnalyzer doesn't stem words. If you need stemming, use for example SnowballAnalyzer.


Q:

Meaning of phrase "rent full month"

What does "I only rent out full month" mean when said by a potential landlord?
At first I thought it means that the apartment can only be rented starting at the first day of a month, but now I think it might mean that it is only rented out for one month at a time. Is it a standard phrase in English or should I ask the person who said it to clarify?

A:

I would sugges you ask the person who said it, however its only logical to assume that he meant was the time frame of the rent, so you must rent for 1 full month (usually calendar month) and not less