text:
Q: using timer to send emails every minute I'm trying to use a timer to send an email every minute. The information for each email is taken from values for each row of components I have on a form. I can send the emails without using the timer, so I know the email method works. But when I try to implement the timer, the emails do not get sent. I read the docs on the timer class, and I believe this should work. But I'm not familiar with it enough to really know what to do. Here is the code:
Here is the email method:
//method to send email to outlook
public void sendEMailThroughOUTLOOK(string recipient,
    string subject, string body)
{
    try
    {
        // Create the Outlook application.
        Outlook.Application oApp = new Outlook.Application();
        // Create a new mail item.
        Outlook.MailItem oMsg =
            (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
        // Set HTMLBody.
        //add the body of the email
        oMsg.Body = body;

        oMsg.Subject = subject;
        // Add a recipient.
        Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
        // Change the recipient in the next line if necessary.
        Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
        oRecip.Resolve();
        // Send.
        oMsg.Send();
        // Clean up.
        oRecip = null;
        oRecips = null;
        oMsg = null;
        oApp = null;
    }//end of try block
    catch (Exception ex)
    {
    } //end of catch
} //end of Email Method

And here is the timer event:
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    foreach (rowClass row in this.rows)
    {
        string recipientAddress = "roomcheckstest@gmail.com";
        string subjectLine = "GPC " + (string)row.buildingComboBox.SelectedItem
            + " " + (string)row.roomComboBox.SelectedItem + "-Room Check";
        string senderline = "Sender=ctsstaff.ithelpcentral@ttu.edu" + "\t";
        string newlinespaces = Environment.NewLine + Environment.NewLine +
            Environment.NewLine + Environment.NewLine + Environment.NewLine;
        string legalLastName = "Legal Last Name=" +
            (string)row.buildingComboBox.SelectedItem;
        string legalFirstName = "Legal First Name=" +
            (string)row.roomComboBox.SelectedItem;
        string timeLine = "Time= 15m";
        string requestType = "Initial Request Type=Onsite";
        string classRoomMaintenace = "Classroom maintenance. " +
            "Regular Classroom weekly check.";
        string closingEmailSent = "Closing Email Sent=yes";
        string currentlyClosed = "Currently Closed=yes";
        string assignTo = "Assign To=ITHC CTS Staff";
        string typeLine = "Type=Hardware";
        string category = "Category=Internal Component";
        string subCategory = "Subcategory=Performance";
        string agentType = "Type (Agent)=Hardware";
        string agentCategory = "Type (Agent)=Hardware";
        string subCategoryAgent = "Subcategory (Agent)=Performance";
        string labelLine = "Label=Service Request";
        string status = "Status=Closed";
        string finalbody = senderline + newlinespaces + legalLastName
            + newlinespaces + legalFirstName + newlinespaces + timeLine
            + newlinespaces + requestType + newlinespaces + classRoomMaintenace
            + newlinespaces + closingEmailSent + newlinespaces
            + currentlyClosed + newlinespaces + assignTo + newlinespaces
            + typeLine + newlinespaces + category + newlinespaces
            + subCategory + newlinespaces + agentType + newlinespaces
            + agentCategory + newlinespaces + subCategoryAgent
            + newlinespaces + labelLine + newlinespaces + status;
        sendEMailThroughOUTLOOK(recipientAddress, subjectLine, finalbody);
        MessageBox.Show("email");
        //Thread.Sleep(60000);
        //sendEMailThroughOUTLOOK(recipientAddress, subjectLine, finalbody);
    }
}

Here is where the timer is created inside a send email button on the form, which should in theory call the email method:
private void submitButton_Click(object sender, EventArgs e)
{
    if (rows[0].buildingComboBox.SelectedIndex > -1)
    {
        System.Timers.Timer time = new System.Timers.Timer();
        time.Interval = 300000;
        time.Enabled = true;
        time.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        MessageBox.Show("Issues Sent");
    }
}

I send an email for each row of components on the form (the user adds rows as needed)
The email is sent through outlook (it has to be sent through outlook using exchange server)
I need to delay it because the server will not accept them all at once. My understanding of the timer class must be flawed. I cant figure out why this isn't working.

A: It looks like you need to call .Start() on the Timer.
Note that nothing will happen until the timer ticks, so the first e-mail won't go out immediately.
Also, your timer interval is set to 5 minutes (300,000ms) instead of 1 (60,000ms).

A: You should really use threads when trying to do things like this. Make a class and have it implement Runnable. Then in the implemented function run, make a while loop and then at the end add Thread.sleep(60000).


text:
Q: postgres - how to kill all long running queries that match a particular query? I have lots of background jobs that queue up the same query.
I've been having a situation where they get stuck, and I'd like to kill the really long running queries in some simple way, that won't take down the entire DB.
How can I do this using a query?
Let's assume my query is the following, and I want to kill any that have been running for over 60 minutes
select * from some_big_table;

A: This is the best I could come up with. Note I'm running on a mac
First I generated an MD5 of my query, at the command line. I did this so it'd simplify what the query looks like, to ensure I only matched my target query and to avoid "sql injecting" myself if I mistyped my query.
# on linux, use 'md5sum' instead.
$ echo -n 'select * from some_big_table;' | md5
65007f37ff78f1e66645105412430b7c

Then I just used a subselect to filter out any other queries that hadn't been running for > 60 minutes.
SELECT pg_cancel_backend(pid)
FROM   pg_stat_activity
WHERE
       now() - pg_stat_activity.query_start >= interval '60 minutes' AND
       md5(query) = '65007f37ff78f1e66645105412430b7c' AND
       state = 'active';

which seemed to work fine
 pg_cancel_backend
-------------------
 t
 t
(2 rows)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javamail gmail and OAuth2 I'm trying to use the latest javamail 1.6.0 api in a web app (java 1.8/tomcat8) to send email on behalf of client users of the app. Some clients use gmail.
I don't want to ask them to enable access to insecure apps in their google accounts as suggested by the javamail FAQ, and I'm willing to implement oauth2 if that's what it takes.
To do that, I did the following on google developer console:

*

*created an app

*created oauth2 credentials for the app (clientid,
clientsecret)

*granted the app access to gmail api

Then, I implemented the oauth2 flow in my app using the google oauth client
The authorization redirect is constructed:
String url =
        new GoogleAuthorizationCodeRequestUrl(clientId,
            redirectUrl,
            Collections.singleton(GmailScopes.GMAIL_SEND)
            ).setAccessType("offline").build();

That successfully redirects to the google site where I can authenticate and authorize my app to send mail on my behalf.  It successfully redirects back to my app after I authorize, and the app processes the authorization code:
GoogleTokenResponse response =
                new GoogleAuthorizationCodeTokenRequest(
                        new NetHttpTransport(),
                        new JacksonFactory(),
                      clientId,
                      clientSecret,
                      code,
                      redirectUrl)
                .execute();

(where code is the returned authorization code)
This seems to work, and returns an access token and refresh token.
(I can also go back to my google account settings and see that I have authorized the app to send email.
So now I want to try to use the access token to send mail through the javamail api using my gmail username (the one I logged in as to authorize the app), the access token, and the following settings:
host = "smtp.gmail.com";
port = 587;
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");

The javamail code works fine for other smtp servers.
I also turned on debug to trace the smtp flow
DEBUG: JavaMail version 1.6.0
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 smtp.gmail.com ESMTP c7sm3632131pfg.29 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO 10.0.0.5
250-smtp.gmail.com at your service, [216.165.225.194]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO 10.0.0.5
250-smtp.gmail.com at your service, [216.165.225.194]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.gmail.com, user=<myemail@gmail.com>, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
DEBUG SMTP: AUTH XOAUTH2 command trace suppressed
DEBUG SMTP: AUTH XOAUTH2 failed, THROW:

 javax.mail.AuthenticationFailedException: OAUTH2 asked for more
...
DEBUG SMTP: AUTH XOAUTH2 failed
ERROR 2017-08-06 18:39:57,443  - send: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==

decoding that last line I see that the error is a 400 status, that I interpret to mean that the token is not valid.
I also verified that the token is good using the google rest api:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<token>

I also tried using port 465 with ssl enabled, but got the same error.
what am I doing wrong here?

A: This is an addition to the answer of user2000974. The documentation of Google about using OAuth to authenticate to an IMAP or SMTP server Gmail > IMAP > OAuth 2.0 Mechanism clearly states the following

This document defines the SASL XOAUTH2 mechanism for use with the IMAP AUTHENTICATE and SMTP AUTH commands. This mechanism allows the use of OAuth 2.0 Access Tokens to authenticate to a user's Gmail account.
The scope for IMAP and SMTP access is https://mail.google.com/.

I hope this will direct people that stumble upon this question in the future to the right documentation page.

A: I tried playing with the requested scopes, and finally got it to work by requesting full access to the gmail account (scope = "https://mail.google.com/"). The limited documentation of the scopes suggests that the specific scope for sending mail SHOULD work, but apparently it doesn't. Requesting full access to the account works, but seems to defeat the purpose of having limited scopes.  It's starting to sound like the SMTP server just isn't respecting the limited scope.

A: Something important, beware from Gmail API and Gmail IMAP, because they're not the same when this problem occurs. Gmail API allows multiple and granular scopes to specific task, but when using Gmail IMAP it will require always the full scope.


text:
Q: Corner cases of codechef farmer feb.Code:POTATOES This question originates from codechef, the online contest website. It requires calculating prime numbers. The question is:

Farmer Feb has three fields with potatoes planted in them. He harvested x potatoes from the first field, y potatoes from the second field and is yet to harvest potatoes from the third field. Feb is very superstitious and believes that if the sum of potatoes he harvests from the three fields is a prime number , he'll make a huge profit. Please help him by calculating for him the minimum number of potatoes that if harvested from the third field will make the sum of potatoes prime. At least one potato should be harvested from the third field.
Input
  The first line of the input contains an integer T denoting the number of test cases. Each of the next T lines contain 2 integers separated by single space: x and y.
Output
  For each test case, output a single line containing the answer.
Constraints
1 ≤ T ≤ 1000
1 ≤ x ≤ 1000
1 ≤ y ≤ 1000

Example
Input:
2
1 3
4 3

Output:
1
4

Explanation
In example case 1: the farmer harvested a potato from the first field and 3 potatoes from the second field. The sum is 4. If he is able to harvest a potato from the third field, that will make the sum 5, which is prime. Hence the answer is 1 (he needs one more potato to make the sum of harvested potatoes prime).

I solved it this way:
import java.io.*;
import java.util.StringTokenizer;

class java2s {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T=Integer.parseInt(br.readLine());
        while(T-->0) {
            StringTokenizer st=new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            int sum = x + y;
            for(int i=1; i<100; i++) {
                int res=sum+i;
                if(res==3 || res==5 || res==7) {
                    System.out.println(i);
                    break;
                }
                else if((res%2)!=0 && (res%3)!=0 && (res%5)!=0 && (res%7)!=0) {
                    System.out.println(i);
                    break;
                }
            }
        }
    }
}

When I ran that code on my PC, it worked very well, but when I submitted it to the contest website, the grader indicated that my answer was incorrect.
Can you tell me which corner cases I am missing?

A: First and foremost, the way input is displayed is little misleading. I guess input should look like
input:
2
1 3
4 3
and the output should look like
1
4
The code you've submitted is checking very minimal number of cases.
Answering the below questions should help you elucidating the problem

*

*Why are you only comparing the variable result to 3,5,7 where the result can also be 101 which is a prime number.

*To check whether or not result is a prime, Why are you dividing the result only by 2,3,5,7?
example:169 is not a prime and is not divisible by any of 2,3,5,7.

*What is the maximum number of potatoes(in all the three fields) feb can harvest?

*How to check whether a number is prime or not.


text:
Q: How to export VECTORIZE image in PDF format as output of ListLinePlot? It seems that ListLinePlot is not generating VECTORIZE PDF file when using Export command.

*

*I use the command : Export["File1.pdf",File1]

*I also Right-Click then "Save Graphic As..." File2.pdf

The two files (grouped) are added for clarity. There are differences in the following :

*

*File size

*Image quality : points gets blurred at high resolution

*Gray Rectangle corner points are deformed

*Orange Polygon is moving out of the frame in file obtained via (1) approach.

Any solution to this will be helpful.
The complete code is :
test = ListLinePlot[iData,
  Mesh -> All, MeshStyle -> Directive[PointSize[0.006]],
  PlotRange -> {{1, 14}, {0, 2.8}},
  FrameLabel -> {"R (km)",
    "M (\!\(\*SubscriptBox[\(M\), \(\[CircleDot]\)]\))"},
  Epilog -> {
    {Black, PointSize[Large], Point[{10.97, 1.97}]},
    {Black, Dashed,
     Line[{{10.97, 1.97}, {10.97, 1.97}, {0, 1.97}, {10.97, 1.97}}]},
    Text[Rotate[Style["Causality", 15, Black], 48 Degree], {6, 2.3}],
    Text[Rotate[Style["P > \[Infinity]", 15, Black],
      56 Degree], {4.85, 2.3}],
    Text[Rotate[Style["GR Limit", 15, Black], 0 Degree], {2.6, 2.3}]},
  Prolog -> {Text[Style["PSRJ1614-2230", 16, Black], {10.2, 2.3}],
    {EdgeForm[Thin], RGBColor[1.00, 0.90, 0.80],
     Polygon[{{0, 0}, {10.97, 10.97/2.9}, {0, 10.97/2.9}}]},
    {EdgeForm[Thin], RGBColor[1.00, 0.78, 0.55],
     Polygon[{{0, 0}, {10.97, 4*10.97/9.0}, {0, 4*10.97/9.0}}]},
    {EdgeForm[Thin], RGBColor[1.00, 0.67, 0.33],
     Polygon[{{0, 0}, {10.97, 10.97/2.0}, {0, 10.97/2.0}}]},
    {EdgeForm[{Thick, GrayLevel[0.6]}],
     HatchFilling[45 Degree, 0.5, 3], GrayLevel[0.8],
     Rectangle[{8.3, 1.97 - 0.04}, {12, 1.97 + 0.04}]}}]

Dataset is available @ Here
Thanks & Regards,

A: HatchFilling* is implemented as a pixel shader. If pixel shaders are involved, the output will always be a raster.  There might be other reasons, but that is the one that jumped out while reading your code.
* This applies to all of the Filling and Shading directives, VertexColors, and Texture.


text:
Q: $.getJSON - ajax is sent but callback function is ignored - Internet Explorer So here is my function
function ajax(addr,loading, loadTo, json){
        addr = addr.replace(' ', '');
        if (loading){
                $("#"+loading).fadeIn();
        }

        if (json){
                $.getJSON(addr, function(data){
                        alert('whoooo working'); // <--- it never goes here
                        if (loading){
                                $("#"+loading).fadeOut();
                        }
                        procJSON(data);
                });
                return true;
        }
}

and I'm calling it with
var postid = $(this).attr('data-postid');
ajax(url+'tools/delete/'+postid, 'loading'+postid, false, true);

ajax is sent, image (loading image) is showed, but callback function is never called.
Isn't that just new reserved value from that IE's big list? Yes I know, IE is not a valid browser, but I can't blame my customers

A: As it fails in specific browsers, it's likely that it is a combination of unexpected headers in the response, and how the browser handles the data based on that.
If for example the response has the content type text/html instead of application/json, the browser might try to turn the response content into a HTML document (by adding pre tags around it), which would then cause the JSON parsing to fail.
If you use the $.ajax method, you can also catch any error message, which would give you a clue to what's going on:
$.ajax({
  url: addr,
  dataType: 'json',
  success: function(data){
    alert('whoooo working'); // <--- it never goes here
    if (loading){
      $("#"+loading).fadeOut();
    }
    procJSON(data);
  },
  error: function(o,c,m) { alert(m); }
});


text:
Q: Get ImagePlus objects from multiple ROIs using ImageJ I'm using ImageJ's Java API and need to calculate some data based on multiple selected ROIs (regions of interest).
First I get an instance of the current ROI Manager by using
RoiManager roiMng = RoiManager.getInstance();

Then, I get all ROIs in the manager by using Roi[] rois = roiMng.getRoisAsArray(); .
From here, I need to get the image in the ROI and get some data from it. However, I seem to only get Null back when calling getImage() on a ROI.
Doing something like,
Roi roi = rois[0];
ImagePlus foo = roi.getImage();
int height = foo.getHeight();

gives me 'java.lang.NullPointerException' at the foo.getHeight() line.
Anyone got any ideas as to what may be going here?
Thanks!

A: you need to set the roi on the ImagePlus . Then you can duplicate the part of the image defined by the active ROI by calling the duplicate() method.
ImagePlus imp = IJ.getImage(); // get the (current) image from the active/selected window
...
imp.setRoi(rois[0]);
ImagePlus roiImp = imp.duplicate();

This way you will get the image defined by the ROI's bounding box. The duplicate methods either creates a copy of the entire image or the roi-image, if a ROI is set.
In case you do not need the pixel data, but you need to get ROI based stats, you might want to have a look at https://imagej.nih.gov/ij/developer/api/ij/ImagePlus.html#getStatistics--
and
https://imagej.nih.gov/ij/developer/api/ij/gui/Roi.html#getStatistics--
hope that helps
Felix


text:
Q: How do I fix this dimenion error in keras / tensorflow? This is the code I am trying to run. X is an array of shape (1000,26) and Y is of shape (1000, 1). I am trying to fit a model that predicts a 1 or a 0 for each row of the X array. For whatever reason tf/keras doesn't seem to like my 2D array input. I have tried adjusting everything I can think of; layers and layer types, activation and loss functions, flattening, and switching from tensorflow.keras to keras, but I keep getting errors that go something like this:
InvalidArgumentError: Input shape axis 0 must equal 3, got shape [2]
     [[{{node dense_33_1/unstack}}]]

My code:
X = tf.constant(training)
Y = tf.constant(train_labels)

model = models.Sequential()

model.add(layers.Dense(46, activation='relu', input_shape=(1000,26)))
model.add(layers.Dense(46, activation='relu'))
model.add(layers.Dense(46, activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(2, activation='softmax'))

model.summary()

model.compile(optimizer='adam',
    loss=['binary_crossentropy'],
    metrics=['binary_accuracy'])

model.fit(X, Y, epochs=2, steps_per_epoch=100)

I am very new to building a model and I don't exactly understand the proper way to build a model around data yet, so all I can really gather from this error is that it wants a 3D array as input, but I don't really get how that even makes sense. Why would it need a 3D tensor and not a 2D?

A: As also stated in your model.summary(), the error message is telling you that your first layer is expecting a 3D X matrix with shape (None, 1000, 26), while you are passing a 2D X with shape (1000, 26).
This is because in this case Keras has already put the first dimension (batch size = None) for you, so you just need to specify the other one, i.e. the number of features. You need to change this
input_shape=(1000,26))

to this
input_dim=26

Other than this I suggest to review your choices of layers.Flatten() and X and Y as tf.constant.


text:
Q: Is push token gets ever updated nativescript-plugin-firebase I am creating nativescript angular app with push notifications. I cannot find information what heppens with push token when:

*

*App is restariting in dev mode i see that token is same - is it similar scenario when user closes and opens installed prod app on their phone?

*What happens with token when user uninstalls an app - is that token gone?

*What happens when user installs an app again - does he gets new push token or token is stored in the phone and is assigned to this device +app forever?

Reason why i am asking is because i do not know when to put token to DB and when to update and should i update at all.
Thanks


text:
Q: Why do materials obey Hooke's law? Why do materials extend proportionally to the force exerted on them (Hooke's law)? I thought that

*

*when materials are compressed or extended under force, their atoms become closer or further apart;

*the inter-atomic forces are essentially electrostatic;

*electrostatic forces (and indeed most other forces) follow an inverse-square law;

So I would naively conclude that springs should follow an inverse square law.
But clearly in most situations the law is linear.  Where is my logic flawed?

A: When one considers a relatively small segment of a curve, most appear approximately linear when one zooms in far enough. Most materials are not truly linear when stretched a considerable distance, but for small deviations about the equilibrium some are approximately linear. This can be seen when one considers Taylor Series expansions of functions.
The inverse square law for electrostatics can be expanded as a Taylor Series as well, and it contains a linear component as can be seen here:
$$\frac{1}{(r-r_0)^2}=\frac{1}{r_0^2}\left[1+2\left(\frac{r}{r_0}\right)+3\left(\frac{r}{r_0}\right)^2+4\left(\frac{r}{r_0}\right)^3+\cdots\right]\,.$$
For small deviations $\Delta r\approx0$, the inverse square law is approximately linear since the higher-order terms $\mathcal{O}[(\Delta r)^2]$ fall off very quickly. This can be seen using the Binomial approximation $(1+x)^n\approx1+nx$ where $x\approx0$. In this case we have:
$$(\Delta r-r_0)^{-2}=\frac{1}{r_0^2}\left(1-\frac{\Delta r}{r_0}\right)^{-2}\approx\frac{1}{r_0^2}\left[1-(-2)\left(\frac{\Delta r}{r_0}\right)\right]=\frac{1}{r_0^2}\left[1+\frac{2\Delta r}{r_0}\right]\,.$$
Of course this is far too simple to describe the more complex material effects of crystal lattices being stretched from equilibrium, but this is the general idea of how many materials can exhibit linear relationships between force and distance for small deviations from equilibrium.


text:
Q: IBOutlet variables in a Singleton Newbie Warning - I'm trying to create a method for updating displayed information from multiple methods across multiple files. I'm new to Obj-C, but in C this would be trivial - use a function call.
It seems that a singleton design pattern is the solution - create a singleton that updates the displayed information, and the singleton method's available "globally" and it updates the IBOutlet variables. There's one display object and it can be manipulated from any method in the system.
This doesn't seem to work. I suspect it's due to my misunderstanding of how a singleton deals with IBOutlet variables. Perhaps the connections made in IB don't work in singletons?
This must surely be a common problem - accessing the user interface from multiple objects? What's the elegant solution to  this problem?

A: IB doesn't deal with singleton. But you have some options:
You can call a singleton's method, for the connection IBAction method.
Or similar: in that IBAction method you can broadcast a notification via NSNotificationCenter.
To inform your UI from different classes, that a change has occurred, create a protocol for your view controller and create a delegate, that conforms to this.
And do yourself a favor: stick to the MVC pattern cocoa depends on. Otherwise you will fight the Framework, instead of using it.


text:
Q: Running script via subprocess.Popen with return value I have a simple script which is having the structure of:
if __name__ =='main':
    #do some logic
    #print to console the result

Now, I ran the script via the code using subprocess.Popen() method like this:
p = subprocess.Popen(
  ["python", path_of_script_to_run] + arguments_list,
  stdout=subprocess.PIPE,
  stderr=subprocess.PIPE)

My question is how can I return a value from the running script to the calling script using return value, or other method.
I cannot use return under the context of if __name__ =='main':
So does it mean I cannot pass a return value to be assigned in the calling script to the p variable?
I'm also want to try avoiding parsing the prints of the script run to the console..

A: Use communicate() to retrieve output of your script. And returncode to get the exit code.
p = subprocess.Popen(
  ["python", path_of_script_to_run] + arguments_list,
  stdout=subprocess.PIPE,
  stderr=subprocess.PIPE)

(stdoutdata, stderrdata) = p.communicate()
exit_code = p.returncode

For your other script to return an exit code, you should use sys.exit(code).
import sys
if __name__ =='main':
    try:
        # do stuff
        sys.exit(0)
    except Exception as err:
        print(err)
        sys.exit(1)

A: You can capture the output in the calling script using  subprocess.check_output():
from subprocess import check_output
result = check_output(args).decode()

To also capture standard error in the result, use stderr=subprocess.STDOUT.


text:
Q: Generate list with string keys? I have two vectors, v1 and v2
v1 <- c('one', 'two', 'three')
v2 <- c('two', 'three', 'four')

I would like to create a list that produces:
"two" : "two", "three" : "three"

Currently, I can only produce this code:
> l <- list()
> l <- c(l, subset(v1, v1 %in% v2)
> l
    [[1]]
    [1] "two"

    [[2]]
    [1] "three"

How can I make the keys be the actually values rather than an index? Thanks.

A: I'm not exactly sure what you mean by the 'keys' but am guessing you want the 'names' of the list nodes to be the same as the values:
l <- c(l, subset(v1, v1 %in% v2) )
names(l) <- unlist(l)
 l
$two
[1] "two"

$three
[1] "three"

(I opposed to naming lists 'l' since the l and 1 character are often confusingly similar in the serif fonts. Not to mention the ambiguity of l and I in non-serif fonts.)


text:
Q: Technique for building a Multiplayer Server I'm looking to write my own multiplayer game server (most likely in nodejs) and I was wondering what protocol I should be using to transfer data? Are Datagrams the norm to send information (i realize they don't confirm delivery like HTTP, that can written on top of the protocol)? Any suggestions of performant proven systems would be a real help.
I guess I'm looking for successful techniques in handling the data transfer quickly and effectively (maintaining state on the server and scaling are a separate issue that I have a solid understanding of).
I'm looking to initially support desktop/mobile games (MacOS, iOS, and Android).

A: For all your protocol needs take a look at socketIO.
Basically your best solution is to rely on websockets which are TCP sockets. socketIO is just a nice cross-browser compliant abstraction.
Either you use standard long pulling techniques or html5 websockets. There is no access to UDP for browser <-> server.

A: There is a technology that is called RTMFP that Adobe introduced in the latest version of Flash (Flash 10). It allows you to do P2P connection and transfer data directly from a client to an other client without passing by the server. On top of that, it's using UDP to transfer data. I believe that this was originally designed to do video and audio streaming, but you can use it to pass data around.
However the main downside on this technology is the mobile since most of them don't support Flash. In this case you can use Socket.IO and use the server as a router of information as a fallback.
If you want to build your application in Javascript, you can still use it by bridging the functionnality to Javascript. If you want to take a look at a simple version of a bridge, you can take a look at this github project (I am the author).

A: As a C++ developer of Massive Multiplayer games for 10 years, I can tell you that most of your more advanced games, such as ones in which I was involved (Legends Of Kesmai, Magic: The Gathering Online, Airwarrior II, AVP, NTN Triva) to name a few, TCP is used for most communication simply because you need an ACK / NACK to be sure the data was received from the client.  That is not to say UDP doesn't have it's place.  In Legends we wrote the the protocol code to use UDP for out of bandwidth delivery of data which wasn't imperative that it be received in proper packet order and complete.  Use UDP when you want to do things like update graphic files in the background while the user is playing, etc.  This type of delivery is often used for such purposes and allows your TCP packets to arrive as required by your server.


text:
Q: GWT popuPanel.hide() doesnt work I have simple view. There are uiBinder and class themselves:
public class NewNotePopupPanel extends Composite implements NewNoteView {
interface NewNotePopupPanelUiBinder extends UiBinder<PopupPanel, NewNotePopupPanel> {
}

private static NewNotePopupPanelUiBinder ourUiBinder = GWT.create(NewNotePopupPanelUiBinder.class);

@UiField
PopupPanel popupPanel;
@UiField
VerticalPanel newNoteMainPanel;
@UiField
HorizontalPanel newNoteHeader;
@UiField
Label storedNoteTitle;
@UiField
DateLabel noteCreatedDate;
@UiField
VerticalPanel contentPanel;
@UiField
TextBox currentNoteTitle;
@UiField
RichTextArea contentTextArea;
@UiField
HorizontalPanel newNoteFooter;
@UiField
CheckBox favorite;
@UiField
Button save;
@UiField
Button close;

private Presenter presenter;

static {
    Resources.INSTANCE.style().ensureInjected();
}

public NewNotePopupPanel() {
    initWidget(ourUiBinder.createAndBindUi(this));
}

@UiHandler("favorite")
void onFavoriteCheckBoxClicked(ClickEvent event) {
    if (presenter != null) {
        presenter.onFavoriteCheckBoxClicked();
    }
}

@UiHandler("save")
void onApplyButtonClicked(ClickEvent event) {
    if (presenter != null) {
        presenter.onApplyButtonClicked();
    }
}

@UiHandler("close")
void onCancelButtonClicked(ClickEvent event) {
    popupPanel.hide();
}
}

UiBinder:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
         xmlns:g='urn:import:com.google.gwt.user.client.ui'>
<ui:with field="res" type="ru.beleychev.notes.client.ui.Resources"/>
<g:PopupPanel ui:field="popupPanel" width="600px" modal="true" title="Edit Note" addStyleNames="{res.style.mainPanel}">
    <g:VerticalPanel ui:field="newNoteMainPanel">
        <g:HorizontalPanel ui:field="newNoteHeader">
            <g:Label ui:field="storedNoteTitle" addStyleNames="{res.style.label}"/>
            <g:DateLabel ui:field="noteCreatedDate" customFormat="EEE, MMM d, yyyy"
                         addStyleNames="{res.style.label}"/>
        </g:HorizontalPanel>
        <g:VerticalPanel ui:field="contentPanel">
            <g:TextBox ui:field="currentNoteTitle" addStyleNames="{res.style.searchBox}"/>
            <g:RichTextArea ui:field="contentTextArea" focus="true"/>
        </g:VerticalPanel>
        <g:HorizontalPanel ui:field="newNoteFooter">
            <g:CheckBox ui:field="favorite"/>
            <g:Button ui:field="save" text="Save" addStyleNames="{res.style.button}"/>
            <g:Button ui:field="close" text="Close" addStyleNames="{res.style.button}"/>
        </g:HorizontalPanel>
    </g:VerticalPanel>
</g:PopupPanel>

This popup window opens from another view. And there is all ok.
I have no problems with interface. But, unfortunately, "Close" button doesn't close popup. It's simple (easy-peasy). What is the problem? ) Looking forward to your suggestions, guys. Thank you in advance.

A: from why can't i hide DialogBox in UiBinder in GWT?
DialogBox (and PopupPanels in general) does not work like any other widget when speaking about adding them to the DOM. You should never attach them directly to it (i.e., panel.add(yourDialogBox) or inside a UiBinder XML file) as you did. Instead you should create them, and simply call hide()/show(), and the like methods, to get it displayed/hidden (i.e., attached/detached at the end of/from the DOM)


text: Q: Time Exceed Alert in Excel I need to do time validation condition in excel. If my total time greater than 0:50, am getting text printed like "your have crossed your limit" else "you are good".I used this condition, but it's not working. =IF(K2>TIME(0,50,0),"You have crossed your limit","You are good"). Can anyone help me out on this !?


text:
Q: Save Selected Features in QGIS 3.4 Model I'm trying to build some models I have in QGIS 2.18. Each model uses the "Save Selected Features" geoalgorithm so that the model only runs on selected features in the source vector layer.
In 3.4 there is no "Save Selected Features". There is an "Extract Selected Features" but I am unable to get the "polygons to lines" algorithm to point to it as it does in 2.18.
This is the 2.18 model


text:
Q: Combining array values in pairs without pairing with previous elements in array i'm having trouble with combining array values. I have tried to combine them and make pairs something what i have done already but i want to erase some pairs that i do not want. Please some one to help me this happen .
// the Code I have now is:
$inputarray = array('Mussafiri', 'Fire', 'Ubungo', 'Mbezi');
$outputarray = array();
  $i = 0;
   foreach($inputarray as $values) {
      $j = 0;
      foreach($inputarray as $values2) {
        if($values != $values2){
            $outputarray[] = array($values => $values2);
        }
      $j++;
     }
 $i++;
}
print_r($outputarray);

//Output  array is:
       Array (   [0] => Array ( [Mussafiri] => Fire)
                 [1] => Array ( [Mussafiri] => Ubungo)
                 [2] => Array ( [Mussafiri] => Mbezi)
                 [3] => Array ( [Fire] => Mussafiri)
                 [4] => Array ( [Fire] => Ubungo)
                 [5] => Array ( [Fire] => Mbezi)
                 [6] => Array ( [Ubungo] => Mussafiri)
                 [7] => Array ( [Ubungo] => Fire)
                 [8] => Array ( [Ubungo] => Mbezi)
                 [9] => Array ( [Mbezi] => Mussafiri )
                 [10] => Array ( [Mbezi] => Fire)
                 [11] => Array ( [Mbezi] => Ubungo) )

NOTE: I DO NOT WANT THE FOLLOWING PAIRS TO APPEAR, I want element to pair with the next element and not pair with the previous element so i do not like index 3,6,7,8,9,10 and 11 to appear in the pair list i.e
                  [3] => Array ( [Fire] => Mussafiri)
                  [6] => Array ( [Ubungo] => Mussafiri)
                  [7] => Array ( [Ubungo] => Fire)
                  [8] => Array ( [Ubungo] => Mbezi)
                  [9] => Array ( [Mbezi] => Mussafiri)
                  [10] => Array ( [Mbezi] => Fire)
                  [11] => Array ( [Mbezi] => Ubungo)

A: If I understand correctly you're trying to create all unique pairs from the array, in which case something like this should work:
$pairs = array();
foreach ($inputarray as $key => $value) {
  for ($i = $key + 1; isset($inputarray[$i]); $i++) {
    $pairs[] = array($value => $inputarray[$i]);
  }
}

The for loop sets $i as the key of the current array element + 1, so it'll never be referencing itself, and will never reference any previous array members.

A: for($i=0; $i<$inputarray.length;$i++){
    $k=$i+1;
    for($j=$k; $j<$inputarray.length;$j++){
        $outputarray[] = array($inputarray[$i] => $inputarray[$j]);

    }
}


text:
Q: Vulkan dynamic rendering, nothing seems to be getting rasterized I am trying to render using the dynamic rendering extension, to this effect I am trying to render just a triangle with these 2 shaders:
#version 450

layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec3 inColor;

layout(location = 0) out vec3 fragColor;

void main() {
    gl_Position = vec4(inPosition, 0.5, 1.0);
    fragColor = inColor;
}

#version 450

layout(location = 0) in vec3 fragColor;

layout(location = 0) out vec4 outColor;

void main() {
    outColor = vec4(vec3(1), 1.0);
}

I am testing my first frame with renderdoc, the vertices seem fine:

So does the output of the vertex shader:

These are the rasterization settings:

As you can see there is no culling, so no matter what the triangle should be rasterized.
But when I go onto the FB both the swapchain image and depth attachment are unaffected. The depth is 1 everywhere and the color attachment is 0 everywhere.
I don't understand why this is not rendering.

A: In case someone runs into this problem in the future.
I was trying to render just a single frame (rather than on a loop) so I was not synchronizing objects because I thought it would not be necessary.
Turns out it very much is, so if you are rendering to the swacphain images even if just once, things won't work unless you use the appropriate fences and semaphores.


text:
Q: Date converter on Spring data Neo4j + Kotlin I'm switching from Java to Kotlin for a simple project but I'm figuring one conversion issue. I've on the database :
CREATE (:Meeting {on: '2018-10-09', location: "Oracle's offices"})

and in kotlin (with SpringBoot + Spring Data neo4J)
@NodeEntity
data class Meeting(
    @Id @GeneratedValue var id: Long?,
    @DateString("yyyy-MM-dd") var on: LocalDate?,
    var location: String?,
    @Relationship(value = "ON") var topics: List<Topic> = ArrayList(),
    @Relationship(value = "IN", direction = Relationship.INCOMING) var
participants: List<Person> = ArrayList(),
    @Relationship(value = "ON") var event: Event?
) : Comparable<Meeting> {
    override fun compareTo(other: Meeting): Int {
        return this.on!!.compareTo(other.on)
    }
}

but when I execute a simple meetingRepository.findAll(), I have that exception
java.time.format.DateTimeParseException: Text '2018-10-09' could not be parsed at index 4
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) ~[na:1.8.0_171]
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ~[na:1.8.0_171]
at java.time.LocalDate.parse(LocalDate.java:400) ~[na:1.8.0_171]
at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:69) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:46) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.format.support.FormattingConversionService$ParserConverter.convert(FormattingConversionService.java:200) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41) ~[spring-core-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191) ~[spring-core-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174) ~[spring-core-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.data.neo4j.conversion.Neo4jOgmEntityInstantiatorAdapter$Neo4jPropertyValueProvider.getParameterValue(Neo4jOgmEntityInstantiatorAdapter.java:89) ~[spring-data-neo4j-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.data.convert.KotlinClassGeneratingEntityInstantiator$DefaultingKotlinClassInstantiatorAdapter.extractInvocationArguments(KotlinClassGeneratingEntityInstantiator.java:230) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.data.convert.KotlinClassGeneratingEntityInstantiator$DefaultingKotlinClassInstantiatorAdapter.createInstance(KotlinClassGeneratingEntityInstantiator.java:204) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.data.convert.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:84) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.data.neo4j.conversion.Neo4jOgmEntityInstantiatorAdapter.createInstance(Neo4jOgmEntityInstantiatorAdapter.java:61) ~[spring-data-neo4j-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.neo4j.ogm.metadata.reflect.EntityFactory.instantiate(EntityFactory.java:126) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.metadata.reflect.EntityFactory.newObject(EntityFactory.java:95) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.context.GraphEntityMapper.mapNodes(GraphEntityMapper.java:237) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.context.GraphEntityMapper.mapEntities(GraphEntityMapper.java:212) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.context.GraphEntityMapper.map(GraphEntityMapper.java:138) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.context.GraphEntityMapper.map(GraphEntityMapper.java:94) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.lambda$loadAll$0(LoadByTypeDelegate.java:107) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:574) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:558) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:94) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:118) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at org.neo4j.ogm.session.Neo4jSession.loadAll(Neo4jSession.java:192) ~[neo4j-ogm-core-3.1.9.jar:3.1.9]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:282) ~[spring-core-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.lambda$invoke$0(SharedSessionCreator.java:108) ~[spring-data-neo4j-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invokeInTransaction(SharedSessionCreator.java:139) ~[spring-data-neo4j-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invoke(SharedSessionCreator.java:110) ~[spring-data-neo4j-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at com.sun.proxy.$Proxy101.loadAll(Unknown Source) ~[na:na]
at org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findAll(SimpleNeo4jRepository.java:154) ~[spring-data-neo4j-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findAll(SimpleNeo4jRepository.java:149) ~[spring-data-neo4j-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.data.repository.core.support.MethodInvocationValidator.invoke(MethodInvocationValidator.java:99) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at com.sun.proxy.$Proxy105.findAll(Unknown Source) ~[na:na]
at be.namuco.dynanetwork.manager.InfoManager.getAllMeetings(InfoManager.kt:80) ~[classes/:na]
at be.namuco.dynanetwork.controller.InfoController.getAllMeetings(InfoController.kt:51) ~[classes/:na]

I've then tried with the annotation @Converter with a custom converter like that
class LocalDateParser : AttributeConverter<LocalDate, String> {

    val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")

    override fun toGraphProperty(value: LocalDate): String? {
        return formatter.format(value)
    }

    override fun toEntityAttribute(value: String?): LocalDate {
        return LocalDate.parse(value);
    }
}

without any success

------------------EDIT------------------------
Thx @Xavier

------------------EDIT------------------------
when I look with the debugger I can see that the parser is looking for a pattern
MM/dd/yy

Can someone help me ?
config :
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
     <groupId>org.neo4j</groupId>
     <artifactId>neo4j-ogm-http-driver</artifactId>
     <version>3.1.11</version>
 </dependency>
 <dependency>
     <groupId>org.neo4j</groupId>
     <artifactId>neo4j-ogm-bolt-driver</artifactId>
     <version>3.1.11</version>
 </dependency>

A: Just try to add the following Formatter bean to your project:
@Component
class LocalDateFormatter : Formatter<LocalDate> {
    override fun parse(text: String, locale: Locale): LocalDate {
        return LocalDate.parse(text, DateTimeFormatter.ISO_LOCAL_DATE)
    }

    override fun print(obj: LocalDate, locale: Locale): String {
        return DateTimeFormatter.ISO_LOCAL_DATE.format(obj)
    }
}

UPDATE
The above code works if you have spring-boot-starter-web dependency in your project. But if you don't - you can add FormattingConversionServiceFactoryBean to the project and register your Formatter manually (then you can remove @Component annotation from it):
@Bean
fun formattingConversionServiceFactoryBean(): FormattingConversionServiceFactoryBean {
    val factoryBean = FormattingConversionServiceFactoryBean()
    factoryBean.setFormatters(setOf(LocalDateFormatter()))
    return factoryBean
}

Working demo in Java.


text:
Q: How to get one specific field of my data with IBM Cloudant and Postman? I have a database in IBM Cloudant and I use his API url in postman to get data. I have three data (temperature, humidity, sound level) in a JSON file.
How to get one specific field of my data such as Humidity for example?

A: In order to retrieve data from CouchDB/Cloudant, you probably want to create a view and then access it.  Try the docs here http://guide.couchdb.org/draft/views.html - you can create views using the cloudant web interface, and you probably want to write a map function that emits the document ID as the key, and the field you're interested in (humidity) as the value.


text:
Q: MySQL multiple tables problem? I want to be able to check my email if it equals $e but my email is in another table called info how can I can I fix this problem?
Here is my MySQL query so far.
"SELECT password, salt FROM users WHERE (email = '" . $e . "' OR username = '" . $e . "') AND active IS NULL"

A: Use a JOIN:
SELECT users.password, users.salt
FROM users
JOIN info
ON info.id = users.info_id
WHERE (users.email = $e OR info.username = $e)
AND users.active IS NULL

Note: you may need to modify the line starting ON depending on how you have structured your schema. If you are unsure of what modification to make, update your question to include the output of SHOW CREATE TABLE users and SHOW CREATE TABLE info.
Also you might want to double-check that there isn't an SQL injection vulnerability in your code. It is good practice to use parameters, or at least make sure that the strings are properly escaped. It is not clear from your code extract if you are escaping correctly or not.


text:
Q: Wordpress | adding a blog link to the navigation menu I have this wordpress website, and it contains some articles, i need to create a button to the navigation menu that is labelled "Blog" that leads to all the articles, how to do that?

A: *

*You should have a page named "Blog".

*Go to your "Settings" tab, then "Reading" and set your "Posts page"
to the "Blog" page.

*Add your "Blog" page to your menu under "Appearance" then "Menus"

Source for Blog info: http://www.wpbeginner.com/wp-tutorials/how-to-create-a-separate-page-for-blog-posts-in-wordpress/
Source for Menu info: https://codex.wordpress.org/WordPress_Menu_User_Guide


text:
Q: How to remove new Notifications from banner? Is there any way to handle remote notification payloads before they're delivered and display in notification centre?

A: With push notifications of default type there is no way to filter out notifications if the app is not in foreground.
The possible solution to this is to use VoIP push notifications in conjunction with PushKit.
VoIP pushes are always waking up the application, however they are not presented to the user and don't modify app badge value, so it's up to the developer to show a local notification upon the received VoIP push and to deal with app badge.
There is a technique with additional silent push that for example Facebook is using, to delete notification on iOS device when the message has been read on desktop web site. It's described here: https://www.pushwoosh.com/docs/deletable-ios-push


text:
Q: Turn a Block into a Scope I have a block in a view:
<% current_user.friends.each do |friend| %>
  <% friend.courses.each do |course| %>
    <%= course.course_name%>
  <% end %>
<% end %>

and I was reading through the Rails Guides and API because it seemed to me that this was the sort of thing that I could bring into a model via a scope. I have two questions:

*

*Is this the sort of thing I can bring into the model via a scope?

*How would I go about doing that?

The relationships are as follows:
class User
  has_many :friends, through: friendships
  has_many :friendships, conditions: "status = 'accepted'"
  has_many :courses

class Course
  belongs_to :user

I have tried a few different variations of scope, particularly in the Course model. The one I tried most recently was:
scope :friend_courses, joins(:user => :friends)

but that didn't return courses belonging to a user's friends.
The code I have in the block works, so if I have to use that, I will. But it seems like there's a way to user eager loading here...

A: class User < ActiveRecord::Base
  has_many :friend_courses, :through => :friends, :source => :courses
  has_many :friends, :through => :friendships
  has_many :friendships, :conditions => {:status => 'accepted'}
  has_many :courses
end

user.friend_courses


text:
Q: How to format using content from Ng-Repeat taken from Angular JS? This is probably a really simple question (I am a bit new to AngularJS), but I have the following code:

    ...

For instance, after it fetches 4 result, I want the results to display on the next line.
Is there a way to keep a counter for the results fetched by ng-repeat? Or some indication to make the next result display on the next line?

A: You could use $index inside it.

A: To add a break each fourth row (the plus 1 is since index starts at 0)

A: $index is built-in counter in ng-repeat, you can use it with ng-if directive:

A: You need to change the div tags to the span tags as otherwise by default it will be on a different line. Apart from that you can use the ng-if inorder to place a br tag
HTML Code:

        {{result}}

Working Fiddle


text:
Q: Replace a value in a column in R I have a data like this:
     x                       y         Dec
0,526315789473684   4,32808638960238    1
0,407407407407407   5,61296415952669    1
0,285714285714286   4,80940239482732    2
0,129032258064516   7,31517603835356    1
0,370370370370370   6,82876196429676    2
.........................................

I would like it to be :
   x                       y            Dec
0,526315789473684   4,32808638960238    yes
0,407407407407407   5,61296415952669    yes
0,285714285714286   4,80940239482732    no
0,129032258064516   7,31517603835356    yes
0,370370370370370   6,82876196429676    no
.........................................

I would like to change the "1" as "yes" and "2" as "no" in the "Dec" column.
How can I do this?

A: Did you try:
levels(df$Dec) <- c(2,1)

Replace "df" with your dataframe name


text:
Q: Format Specifier: %u vs %d in C #include<stdio.h>

int main(){
    int a = 3;
    printf("%u\n",&a);
    printf("%d\n",&a);
    return 0;
}

I was trying to print address of Variable, "a". Now with usage of two different format specifier, "%u" and "%d", two different memory address is printed which I find it wierd.
So My Question is what difference between two format specifier?

A: Using the both conversion specifiers to output an address invokes undefined behavior.
From the C Standard (7.21.6.1 The fprintf function)

9 If a conversion specification is invalid, the behavior is
undefined.275) If any argument is not the correct type for the
corresponding conversion specification, the behavior is undefined.

Instead you should use the conversion specifier p as for example
printf( "%p\n", ( void * )&a );

Another approach is to use integer types intptr_t or uintptr_t declared in the header <stdint.h> and to use specifiers PRIdPTR or PRIuPTR or, for example, PRIxPTR declared in the header <inttypes.h> to output assigned values of pointers of the type void *.
Here is a demonstration program.
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main( void )
{
    int a = 3;
    intptr_t p1 = ( intptr_t )( void * )&a;
    uintptr_t p2 = ( uintptr_t )( void * )&a;

    printf( "&a = %p\n", ( void * )&a );
    printf( "&a = %"PRIdPTR "\n", p1 );
    printf( "&a = %"PRIuPTR "\n", p2 );
    printf( "&a = %#"PRIxPTR "\n", p2 );
}

The program output is
&a = 0x7ffc220b16ec
&a = 140720879638252
&a = 140720879638252
&a = 0x7ffc220b16ec

A: %d is for signed integers, %u is for unsigned integers.
So, when you print the same value out with %d and with %u, you may get different values, since the bytes you're printing out are being interpreted differently. (Once as a signed integer, once as an unsigned integer.)
Final note, you should use %p ("p" for "pointer") to print out addresses.

A: Well of course "%u\n" has different address than "%d\n" because these are different values created one after another. Look at ASM:

RDX register will have the same value for both printf calls because of LEA instruction is putting the same address into it.
But what you probably see are the values of RCX register which contains different printf format value address for each printf call.
Now the answer:
%d is signed decimal integer.
%u is unsigned decimal integer.
The problem occurs when there is a printf call. This function changes the value of RDX register which is the memory address of a variable.


text:
Q: Can i use netoffice package to automate outlook application from a web application. Is there any disadvantages Can i use netoffice package to automate outlook application from a web application. I need to open outlook window to create meetings and send from a web application.Is there any disadvantages in using netoffice for the same?

A: Nope. It is not a supported way of automating Office applications.
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
Read more about that in the Considerations for server-side Automation of Office article.
If you deal with Exchange profiles you may consider using EWS, see Get started with EWS Managed API client applications for more information.


text:
Q: How do you share your git repository with other developers? I have a central git repository that everyone pushes to for testing and integration, but it only is pushed to when features are 'ready'.  While in the middle of a big task, developers frequently have many commits that stay on their hard drives.
Sometimes in the middle of these projects I'd like to either see what another developer is doing, or show him how I've done something.  I'd like to be able to tell another developer to just "pull my working copy".
The only way I can think of is having everyone run SSH on their development machines and adding accounts or SSH keys for everyone, but this is a huge privacy and permissions nightmare, and seems like a lot of work to maintain.
Should we just be pushing to that central repository in these cases? Should we be pushing after every local commit?

A: Two common approaches:

*

*developers have their own public repos (for example mpd and associated programs).

*developers push to refs in their own namespace on a central repo (dev1/master, dev2/master). Depending on your exact situation, you might want some access control in the form of hooks to make sure no one does anything silly.

A: We use branches for code that isn't "ready" yet, and the branches get pushed to a central repo (which is backed up!).  When a new feature becomes "ready" it gets merged into the master branch.
One of the benefits of using git is that it is very, very easy to create and merge branches, plus you can visualize what's happening using gitk.  Recommended!


text:
Q: Confusion about Rust modules I'm trying to create a Rust library to decode an OTF and in order to test this, I'm writing a CLI application so that I can verify its behavior from time to time.
Here are the contents of the Cargo.toml file.
# OTFDecode - A library to decode Open Type Fonts (OTF's).
[package]
name = "otfdecode"
version = "1.0.0"
edition = "2021"

I then have the lib.rs file with the following contents:
//! OTFDecode - A library to decode Open Type Fonts (OTF's).
mod reader;

/// Represents an Open Type Font (OTF).
pub struct OpenTypeFont {
    pub sfnt_version: u32,
    pub num_tables: u16,
}

/// Decode data as an Open Type Font (OTF).
pub fn decode(data: &[u8]) -> OpenTypeFont {
    let mut reader = reader::OpenTypeFontReader::new(data);
    let sfnt_version = reader.read_u32();
    let num_tables = reader.read_u16();

    OpenTypeFont {
        sfnt_version,
        num_tables,
    }
}

And I do have the reader.rs file:
//! A simple reader for reading an Open Type Font (OTF).

/// Represents a mechanism for reading an Open Type Font (OTF).
pub struct OpenTypeFontReader<'a> {
    buffer: &'a [u8],
    position: usize,
}

//# The basic implementation of the `OpenTypeFontReader` struct.
impl<'a> OpenTypeFontReader<'a> {
    //# Defines the constants which are required in this `impl` block.
    const U32_SIZE: usize = 4; // The amount of bytes in a `u32`.
    const U16_SIZE: usize = 2; // The amount of bytes in a `u16`.

    /// Creates a new OpenTypeFontReader.
    pub fn new(buffer: &'a [u8]) -> Self {
        OpenTypeFontReader {
            buffer,
            position: 0,
        }
    }

    /// Read an `u32` from the underlying buffer and increase the reader's position by 4.
    pub fn read_u32(&mut self) -> u32 {
        let bytes = self.buffer[self.position..self.position + OpenTypeFontReader::U32_SIZE]
            .try_into()
            .unwrap();

        self.position += OpenTypeFontReader::U32_SIZE;

        u32::from_be_bytes(bytes)
    }

    /// Read an `u16` from the underlying buffer and increase the reader's position by 2.
    pub fn read_u16(&mut self) -> u16 {
        let bytes = self.buffer[self.position..self.position + OpenTypeFontReader::U16_SIZE]
            .try_into()
            .unwrap();

        self.position += OpenTypeFontReader::U16_SIZE;

        u16::from_be_bytes(bytes)
    }
}

I then have the main.rs file, which is the entry point to the CLI:
//! OTFDecode - A CLI application to verify that the `OTFDecode` library is correctly implemented.
mod lib;

/// Represents the `main` entry point for the application.
/// This function is executed when the application is started.
fn main() {
    let data: [u8; 6] = [
        // OTF Header.
        /* - SFNT Version.     */ 0x00, 0x01, 0x00, 0x00,
        /* - Number of tables. */ 0x00, 0x19,
    ];

    let decoded_otf = lib::decode(&data);

    println!("OTF Font inspection.");
    println!("- SFNT Version: {:?}", decoded_otf.sfnt_version);
    println!("- Number of: {:?}", decoded_otf.num_tables);
}

NOTE: All files are at the same level (inside the src/ folder).
Cargo is however giving me the following error:
error[E0583]: file not found for module `reader`
  --> src\lib.rs:26:1
   |
26 | mod reader;
   | ^^^^^^^^^^^
   |
   = help: to create the module `reader`, create file "src\lib\reader.rs" or "src\lib\reader\mod.rs"

error[E0433]: failed to resolve: could not find `OpenTypeFontReader` in `reader`
  --> src\lib.rs:36:30
   |
36 |     let mut reader = reader::OpenTypeFontReader::new(data);
   |                              ^^^^^^^^^^^^^^^^^^ could not find `OpenTypeFontReader` in `reader`

Some errors have detailed explanations: E0433, E0583.
For more information about an error, try `rustc --explain E0433`.

Why can't I use the contents of the reader.rs file? What am I doing wrong?

A: Cargo does not understand your usage of lib.rs as the entry point to your library but as a normal rust file. That's why when you declare the module reader in lib.rs cargo expects that you have a source file in a subdirectory lib.
You can fix the problem by changing main.rs:

*

*Remove mod lib

*change let decoded_otf = lib::decode(&data); to let decoded_otf = otfdecode::decode(&data);
Now cargo understands lib.rs correctly as the entry point to your library (because you don't have mod lib) and you are able to use your library as any other crate you included.
Probably this is not the best explanation, I would recommend reading the part in the book about modules.
I found this about using code from lib.rs in main.rs

A: You essentially need both main.rs - containing the manual testing code (binary) and lib.rs - entry point to your library in the same project. To do this, your binary needs to treat your library as an external crate and use it with crate name:
use otfdecode;

// Then use otfdecode::reader::OpenTypeFont somewhere.


text:
Q: Convergence of sequence of functions $\sum_{n\ge1 }ne^{-nx^2}$ How to show that the series $$\sum_{n\ge1 }ne^{-nx^2}$$ is not uniformly convergent for $x\in (0,\infty)$ whereas converges uniformly when $x\in (a,\infty),\ a>0$?
What I observed is, for $x>a$, $$ ne^{-nx^2}\le ne^{-na^2}. $$  Since $$\sum_{n\ge 1}ne^{-na^2}\le \infty\implies \sum_{n\ge 1}f_n\ \text{converges uniformly when}\ x\in (a,\infty). $$ But, how to do the first case?

A: Note that$$\sum_{n=1}^\infty ne^{-nx^2}=\sum_{n=1}^\infty n\left(e^{-x^2}\right)^n=\frac{e^{-x^2}}{\left(1-e^{-x^2}\right)^2},$$which is an unbounded function on $(0,+\infty)$. Since each function $\sum_{n=1}^Nne^{-nx^2}$ is bounded there, the convergence cannot be uniform.


text:
Q: How to pass a state's value into props in React class component I am getting geocode locations into the latt,lngg variables through axios and setState , i want to use this variables inside google-map-react package center How can i pass these state values into props .
Rest API
then(res => {
  console.log(res.data.results[0].geometry.location.lat);
  console.log(res.data.results[0].geometry.location.lng);
  // console.log(res.data[0]);

  this.setState({latt:res.data.results[0].geometry.location.lat})
  this.setState({lngg:res.data.results[0].geometry.location.lng})
})

static defaultProps = {
  center: {
    lat: 32,
    lng: 56
  },
  zoom: 5.7
};

<GoogleMapReact bootstrapURLKeys={{ key:API-KEY}} defaultCenter={this.props.center} defaultZoom={this.props.zoom}>

A: For referencing state values, you'd use this.state.center and this.state.zoom rather than this.props. which is for the props of the current component.


text:
Q: Adding a progress bar to copy file script $destinationFolder = "C:\Users\Jimmy\Desktop\Saves"
$rootFolder = "C:\Users\Jimmy\Desktop\test"
$subFolder = "\sales"
$fileName = "hello.txt"

$Dir = get-childitem $rootFolder |
       select -first 10 |
       ?{ $_.PSIsContainer } |
       Sort-Object { [regex]::Replace($_.Name, '\d+', { $args[0].Value.PadLeft(20) }) }

[array]::Reverse($Dir)

$Dir | format-table FullName

Foreach ($i in $Dir){
  if(Test-Path $($i.FullName + $subFolder + "\" + $fileName)){
    #echo $($i.FullName + $subFolder)
    get-childitem $($i.FullName + $subFolder) |
      where {$_.Name.ToLower() -eq $fileName.ToLower()} |
      Copy-Item -Destination $destinationFolder
    echo $("just copied " + $fileName + " from " + $i.FullName.Trim())
    break;
  }else{
    echo $("Could not find " + $fileName + " in " + $i.FullName.Trim())
  }
}

I usually use this script to copy large files from one location to another. I want to add a progress bar so I have some indication of the file being copied etc.
I would like to add a write-progress [ooooo     ] type of thing, but I'm unsure how to do it.

A: replace your foreach statement with this :
$i=1
$dir| %{
    [int]$percent = $i / $dir.count * 100
    Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
    copy $_.fullName -Destination $destinationFolder
    $i++
}


text:
Q: custom module to have an admin form I want to create a module with a form when clicking on menu tab, I have tried to exactly create it like what we have under System->MyAccount,
but when I click on Example the menu is empty.I started with this example and changed it.
here is my effort:

config.xml:
<?xml version="1.0"?>
<config>
    <modules>
        <Custom_Adminhello>
            <version>1.0.0</version>
        </Custom_Adminhello>
    </modules>
        <admin>
        <routers>
            <adminhello>
                <use>admin</use>
                <args>
                    <module>Custom_Adminhello</module>
                    <frontName>admin</frontName>
                </args>
            </adminhello>
        </routers>
    </admin>

    <global>
        <helpers>
            <custom_adminhello>
                <class>Custom_Adminhello_Helper</class>
            </custom_adminhello>
        </helpers>
         <blocks>
            <custom_adminhello>
                <class>Custom_Adminhello_Block</class>
            </custom_adminhello>
        </blocks>
    </global>
</config>

adminhtml.xml:
<config>
    <menu>
        <custom translate="title" module="custom_adminhello">
            <title>Custom Module</title>
            <sort_order>1</sort_order>
            <children>
                <example>
                    <title>Example</title>
                    <sort_order>1</sort_order>
                    <action>adminhello/system_account</action>
                </example>
            </children>
        </custom>
    </menu>
    <acl>
        <resources>
            <admin>
                <children>
                    <custom translate="title" module="custom_adminhello">
                        <title>Example Menu Item</title>
                        <sort_order>1</sort_order>
                        <children>
                            <example>
                                <title>Example Menu Item</title>
                            </example>
                        </children>
                    </custom>
                </children>
            </admin>
        </resources>
    </acl>

</config>

AccountController.php
class Custom_Adminhello_System_AccountController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    {
        $this->_title($this->__('System'))->_title($this->__('My Account'));

        $this->loadLayout();
        $this->_setActiveMenu('system/account');
        $this->_addContent($this->getLayout()->createBlock('adminhello/system_account_edit'));
        $this->renderLayout();
    }

}

Data.php:
class Custom_Adminhello_Helper_Data extends Mage_Core_Helper_Abstract
{
}

Edit.php:
class Custom_Adminhello_Block_System_Account_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();

        $this->_controller = 'system_account';
        $this->_updateButton('save', 'label', Mage::helper('adminhello')->__('Save Account'));
        $this->_removeButton('delete');
        $this->_removeButton('back');
    }

    public function getHeaderText()
    {
        return Mage::helper('adminhello')->__('My Account');
    }
}

Form.php
class Custom_Adminhello_Block_System_Account_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
        $userId = Mage::getSingleton('admin/session')->getUser()->getId();
        $user = Mage::getModel('admin/user')
            ->load($userId);
        $user->unsetData('password');

        $form = new Varien_Data_Form();

        $fieldset = $form->addFieldset('base_fieldset', array('legend'=>Mage::helper('adminhtml')->__('Account Information')));

        $fieldset->addField('username', 'text', array(
                'name'  => 'username',
                'label' => Mage::helper('adminhtml')->__('User Name'),
                'title' => Mage::helper('adminhtml')->__('User Name'),
                'required' => true,
            )
        );

        $fieldset->addField('firstname', 'text', array(
                'name'  => 'firstname',
                'label' => Mage::helper('adminhtml')->__('First Name'),
                'title' => Mage::helper('adminhtml')->__('First Name'),
                'required' => true,
            )
        );

        $fieldset->addField('lastname', 'text', array(
                'name'  => 'lastname',
                'label' => Mage::helper('adminhtml')->__('Last Name'),
                'title' => Mage::helper('adminhtml')->__('Last Name'),
                'required' => true,
            )
        );

        $fieldset->addField('user_id', 'hidden', array(
                'name'  => 'user_id',
            )
        );

        $fieldset->addField('email', 'text', array(
                'name'  => 'email',
                'label' => Mage::helper('adminhtml')->__('Email'),
                'title' => Mage::helper('adminhtml')->__('User Email'),
                'required' => true,
            )
        );

        $fieldset->addField('current_password', 'obscure', array(
                'name'  => 'current_password',
                'label' => Mage::helper('adminhtml')->__('Current Admin Password'),
                'title' => Mage::helper('adminhtml')->__('Current Admin Password'),
                'required' => true,
            )
        );

        $fieldset->addField('password', 'password', array(
                'name'  => 'new_password',
                'label' => Mage::helper('adminhtml')->__('New Password'),
                'title' => Mage::helper('adminhtml')->__('New Password'),
                'class' => 'input-text validate-admin-password',
            )
        );

        $fieldset->addField('confirmation', 'password', array(
                'name'  => 'password_confirmation',
                'label' => Mage::helper('adminhtml')->__('Password Confirmation'),
                'class' => 'input-text validate-cpassword',
            )
        );

        $form->setValues($user->getData());
        $form->setAction($this->getUrl('*/system_account/save'));
        $form->setMethod('post');
        $form->setUseContainer(true);
        $form->setId('edit_form');

        $this->setForm($form);

        return parent::_prepareForm();
    }
}

A: You can use https://www.magentocommerce.com/magento-connect/ultimate-module-creator.html  extension its free and simple. Try and mark ans as correct.


text:
Q: QT - Unknown debugger type "No engine" Recently I have re-installed QT (5.5.1 MSVC 2013, 32 bit, rev. b52c2f91f5) on my PC and installed the debugging tools of Microsoft.
QT (QT Creator) can auto-detect these just fine.

When trying to start the debugger with either the default shortcut F5 or clicking it manually, it throws an error that the debugger could not be run. (Compiling works fine, debugging not at all)

No debugger-engine of type "No engine" could be created.

(Running Windows 8.1 with VS2013/VS2015 installed - QT working with VS2013 32&64 bit).
On my work PC I did the same process a few weeks ago and had no problems at all.
What could cause this problem ? Yet I have only found questions with the same problem related to other compilers.

A: *

*Close Qt Creator.

*In the folder where your .pro file resides, there will be some .pro.user and .pro.user.x files. Delete them all. Keep only your .pro file.

*Start Qt Creator and open your .pro file. Qt Creator will ask you to reconfigure your project. Accept that.

*Now you can debug again, or at least I could; the problem happened to me when I had just updated Qt Creator.

A: It may point to a missing component in your installation process or an actual defect in Qt:
Option #1
Install a debugger.

If you are installing 5.5.1 for Visual Studio 2013 64 or 32bit, 2012
  32bit, 201032bit.  Then install windows Debuggers.
Qt will detect automatically the compiler and Debugger.
To set manually Tools->options->build&run->kits->set one of auto detected , then
  you can see all.

Source: https://forum.qt.io/topic/59974/unknown-debugger-type-no-engine/11
Option #2

Unable to create a debugger engine of the type "No engine"

in the past pointed to a bug in the Qt Creator, if you'll update it may be fixed.
I'm also aware that alternatively, it may be solved by updating to Python 2.7.1.

A: I had a problem in windows 7 but I've solved it:

*

*Download Windows driver kit
https://www.microsoft.com/en-us/download/details.aspx?id=11800

*Add your debugger

*Change auto-detected kit debugger to your added debugger

A: I installed Debugging Tools for Windows and the debugger appeared under Manage Kits > Build & Run > Debuggers but it didn't added in the kits so I had to go to Manage Kits > Build & Run > Kits then select the desired kit and under Debugger I had to select the debugger. Initially the debugger is set to "None".

A: Answering the title of this question, not the person asking it.
I had the exact same error message on arch linux 64 trying to compile for arm android.
First I ran the gdb debugger in the command line to get the root issue:
~/tools/android/android-ndk-r12/prebuilt/linux-x86_64/bin/gdb-orig:
error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory

libncurses is the issue!  (As of 6/24/2016) Arch linux is on ncurses 6.0-4.  Later you'll also find libtinfo.so.5 is missing.
At this point, the method for fixing the problem is up to you; I don't like using a bunch of AUR repos, so I executed a simple hack.  We're forcing the library linkage that was in libncurses 5x to point at 6x.
Please ensure you don't overwrite anything before running these commands
cd /usr/lib
sudo ln -s libncursesw.so.6.0 libncurses.so.5
sudo ln -s libncursesw.so.6.0 libtinfo.so.5

Re-run your arm gdb, and it should work.


text:
Q: Setting and getting global variable in JavaScript using jQuery I am trying to work out why I am getting undefined data type on printName(). So how we can update a global variable trough a function (like a Setter) function and get access the updated value via other functions if needed.
$(function () {
    var name;

    function setName() {
        name = "TestName";
    }

    function printName() {
        alert(name);
    }
    printName();
});

A: Because you haven't set the name using setName(). function. in other words you never called setName()

A: $(function () {
    var name;

function setName() {
    name = "TestName";
}

function printName() {
    alert(name);
}
    setName();
    printName();
});


text:
Q: How to show $x\in(0,1]$? Problem is to show $(0,1]$ is subset of $\cup [\frac{1}{n},1]$.
What I have so far is:
Let $x$ be in $(0,1]$. And I want to show $x\in[\frac{1}{n}, 1]$

A: For each given $x$, try to find a $n$ such that $x$ is in the interval $[1/n,1]$.
Can you find a $n$ for every $x$? Then you have proven your theorem.

A: Take $x\in (0,1)$. There exists $n>0$ such that $0<1/n<x$ ( because the sequence $(1/n$ goes to 0, as $n\to\infty$). Then $x$ is in $[1/n,1]$.


text:
Q: delay including of html files in angularjs ng-include I have a series of html files I am including into my main controller. These html files are not actually being used for atleast 4 seconds while one html file does its stuff. How would I define to delay loading of rest of the files to improve startup performance of the app.

A: Another solution(less elegant) could be:

In your controller initialize template with
$scope.template = '';

And do
$scope.template = 'somefile.html';

when you need the template to be loaded.

A: Load these asynchron with promises. This covers the idea:
var promise = $http.get('someFile.html').success(function (data) {
        htmlContent = data.response;
    });

promise.then(function(result) {
    $scope.model = result;
});


text:
Q: EditText is hidden on Samsung Galaxy i have the following layout
<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
        <ListView
            android:id="@+id/displaysms_listView1"
            android:layout_width="fill_parent"
            android:layout_height="319dp" />
        <EditText
            android:id="@+id/displaysms_textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Write Message"
            android:inputType="textVisiblePassword" />
        <RelativeLayout
            android:id="@+id/displaysms_relativeLayout2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
            <Button
                android:id="@+id/displaysms_btn_send"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:gravity="fill_vertical"
                android:text="Send"
                android:textSize="12sp" />
            <Button
                android:id="@+id/displaysms_btn_clear"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:gravity="fill_vertical"
                android:text="Clear"
                android:textSize="12sp" />
      </RelativeLayout>
</LinearLayout>

i have done adjustPan in the manifest file and it works fine on devices except samsung galaxy the EditText hides under the soft keyboard, any suggestions, i just want a EditText and buttons at the bottom of my list view
my Activity looks like
<activity
            android:name="com.SMSActivity"
             android:windowSoftInputMode="adjustPan|adjustResize"

A: u can do something like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="100" >

    <ListView
        android:id="@+id/displaysms_listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="20" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="80"
        android:focusableInTouchMode="true"
        android:padding="5dp"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/displaysms_textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Write Message"
            android:inputType="textVisiblePassword" />

        <FrameLayout
           android:id="@+id/FrameLayout1"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content" >

           <Button
               android:id="@+id/displaysms_btn_send"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_gravity="left|center_vertical"
               android:padding="5dp"
               android:text="Send"
               android:textAppearance="?android:attr/textAppearanceMedium" />

           <Button
               android:id="@+id/displaysms_btn_clear"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_gravity="right|center_vertical"
               android:padding="5dp"
               android:text="Clear"
               android:textAppearance="?android:attr/textAppearanceMedium" />
      </FrameLayout>
    </LinearLayout>

</LinearLayout>

in ur manifest file
<activity
    android:name="com.SMSActivity"
    android:windowSoftInputMode="adjustResize" />

Take a look for ref

A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<RelativeLayout
    android:id="@+id/displaysms_relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" >

    <ListView
        android:id="@+id/displaysms_listView1"
        android:layout_width="fill_parent"
        android:layout_height="319dp"
        android:layout_margin="5dp" />

    <EditText
        android:id="@+id/displaysms_textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/displaysms_listView1"
        android:layout_margin="5dp"
        android:hint="Write Message"
        android:inputType="textVisiblePassword" />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/displaysms_relativeLayout2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_below="@+id/displaysms_relativeLayout1" >

    <Button
        android:id="@+id/displaysms_btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="Send"
        android:textSize="12sp" />

    <Button
        android:id="@+id/displaysms_btn_clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Clear"
        android:textSize="12sp" />
</RelativeLayout>

A: try doing editText.requestFocus()


text:
Q: Does the use #ifndef and #define change the memory allocation? I recently saw a header file with such defines:
#ifndef DEFINE_ME
#define DEFINE_ME     1
     char abc[10];
#endif

but I also found that DEFINE_ME was never defined in any other header file of the project so why was #ifndef used? does it have to do any thing with memory?

A: It's called an include guard.
The purpose of DEFINE_ME is to prevent the particular (where it's defined) header file being included multiple times accidentally.

To understand how it works, try without include guard:
header.h:
int x = 5;

file.c:
#include "header.h"
#include "header.h"

int main() {
   printf("%d\n", x);
}

and then try with an include guard:
header.h:
#ifndef DEFINE_ME
#define DEFINE_ME 1

int x = 5;

#endif

file.c:
#include "header.h"
#include "header.h"

int main() {
   printf("%d\n", x);
}

When you have DEFINE_ME, the header will be included the first time in fil.c, the header.h is included as DEFINE_ME wasn't defined before. But the next #include "header.h" wouldn't include the contents of the guard as DEFINE_ME has already been defined by the previous inclusion.

A: It's include guard.
The purpose of This is to prevent multiple declaration of variable.
ifndef = if not defined.
then define it..
if defined then use the previous declaration ..
suppose u have two header files
header1:
#ifndef DEFINE_ME
#define DEFINE_ME     1
#endif

header 2:
#ifndef DEFINE_ME
#define DEFINE_ME     1

#endif

now if in c file header 2 is included first then it will include the value from header 2 not from header 1.. as it is already defined in header 2
You can have header file guard also as explained below:
Header1.h
#ifndef _header1
#define _header1
#ifndef VAR1
#ifdef VAR1   5
#endif
#endif

Header2.h
#ifndef _header2
#define _header2
#ifndef VAR1
#ifdef VAR1   5
#endif
#endif

Now you have used a guard so that u by mistake include same header in different files of same project then also u will be safe.


text:
Q: uwp app and unhandled exception I created a Universal Windows Platform app for Windows 10 desktop. I'm using HockeyApp for logging my events and exceptions. I uploaded pdb symbols to my HockeyApp account.
I got an unhandled exception, this is the log:
MyApp!<BaseAddress>+0xe6890f
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x699af7
MyApp!<BaseAddress>+0xb41a69
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x699af7
MyApp!<BaseAddress>+0xb3c820
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x699af7
MyApp!<BaseAddress>+0xb3810a
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x699af7
MyApp!<BaseAddress>+0xbc7a30
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x699af7
MyApp!<BaseAddress>+0xbd4dc3
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x699af7
MyApp!<BaseAddress>+0xe68fc9
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x4ba96e
MyApp!<BaseAddress>+0xf22ade
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x4511ee
MyLibrary!<BaseAddress>+0x451168
MyLibrary!<BaseAddress>+0x50c81a
MyApp!<BaseAddress>+0x10227bb
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
MyLibrary!<BaseAddress>+0x69993e
MyLibrary!<BaseAddress>+0x497d7c
MyApp!<BaseAddress>+0xb1c72c
MyApp!<BaseAddress>+0xb1c6e6
MyApp!<BaseAddress>+0xb1c614
         Microsoft.HockeyApp.Extensibility.Windows.UnhandledExceptionTelemetryModule.CoreApplication_UnhandledErrorDetected(Object sender, ApplicationModel.Core.UnhandledErrorDetectedEventArgs e)

How can I use this information? How do I find the real reason for this exception? Any ideas?


text:
Q: Intentional border or padding overlap halfway for responsive tile view I'm working with a responsive layout where the container has any number of "tiles" that automatically adjust their percentage based width depending on the screen size using media queries.
Each tile has a 10px border and I'm looking a reliable way to ensure there's always that 10px border. If I set the border to 10px then adjacent tiles end up having 20px between them. If I see it to 5px, the edge tiles end up having the thinner border than the rest, and etc.
What's a good method to style the tile to make borders overlap halfway without having to constantly adjust the edge tiles with javascript?
Note: I use a technique using width: % for width and padding-bottom: % for height of the tiles. It's a technique that works because padding bottom is based on the width. If you see to the same value it will be perfect square.

A: The answer was the following:
ul#container{
     border: 5px solid white; /*Half border*/
}

ul#container li.tile {
     outline: 10px solid white;  /*Full border*/
     outline-offset: -5px solid white;  /*Negative Half border*/
}

An alternative way I found that worked a bit better in my case (decided to use isotope.js for responsive tiles) was the following:
li.tile {
    border: 10px solid white;
    margin-right: -10px;
    margin-bottom: -10px;
}


text:
Q: How to rewrite all the current page with Ajax? I have created a simple page with a button on the center.
Now I want that when I click the button then the current page is completly rewritten with new HTML and Javascript code loaded from the server.
How can I do this with ajax ?

A: Suggestion: post with a normal form and reload the page.  If you're reloading the entire page anyway, you're doing away with all the benefits of AJAX anyway, best to reload the entire page, for example:
<form action="otherpagr.html">
  <input type="submit" value="Click me" />
</form>

AJAX is for replacing part of a page to reduce the overhead...but if you're replacing say the entire <body> it's easier to just load the page you're going to.

A: Nick is right with what he says, but if there's no other way:
$('a').click(function() {
  $('body').load("test.html");
});

EDIT: Making sure load only fetches content inside the <body> Tag from the remote adress. For me it didn't work to fetch only the <body> tag by defining body => load('test.html body')

To animate the page you could do something like this:
$('a').click(function() {
  $('body').load("test.html", function() {
    $(this).hide().fadeIn(2000);
  });
});

but then I suggest to implement at least one wrapper-element.