text:
Q: Prevent Dialog form from closing in Smart Mobile Studio application I have a modalDialog with a W3EditBox where the user enters a string that ultimately gets added to a W3ListBox on the main form
I am trying to prevent the modalDialog from closing if one of these conditions exist
1.) W3EditBox text is nil
2.) if W3EditBox text already exists in the W3ListBox list
Here is the code for calling the dialog form (has just a label, edit box, and ok and cancel buttons)
procedure TfrmMain.HandleAddClick(Sender: TObject);
begin
  Application.ShowModal('frmGoal', 'W3Panel1', 'edtTitle', InitDialog, OkResponse, nil);
end;

Here is the code for handling the OK response
procedure TfrmMain.OkResponse(AForm: TW3CustomForm);
begin
 //code here to prevent if title is nil or already exists in listbox
 W3Listbox1.Add(TfrmGoal(AForm).Title);
end;

On another note, I don't understand how the W3ListBox's IndexOf method works.
I am use to search for a string – and it looks like it wants a control
Thanks
Shane

A: Let's say we have a visual project with main form MainForm and dialog AddDialog. The main form contains a listbox lbItems and the dialog contains a wrapper panel W3Panel1 with three child objects - an edit box inpItem and two buttons - btnOK and btnCancel. The AddDialog dialog is registered with a name AddDialog.
FAddDialog := TAddDialog.Create(Display.View);
FAddDialog.Name := 'AddDialog';
RegisterFormInstance(FAddDialog, False);

The dialog is then displayed with a simple ShowModal call.
btnAdd.OnClick := lambda
  Application.ShowModal('AddDialog', 'W3Panel1', 'inpItem', InitDialog, OkResponse);
end;

The simplest way to access the main form's listbox from the dialog is to provide the dialog with the reference to the main form's component. To do so, add a property to the dialog
property Items: TW3ListBox;

and then assign its value in the InitDialog.
procedure TMainForm.InitDialog(dialog: TW3CustomForm);
begin
  (dialog as TAddDialog).Items := lbItems;
end;

In the dialog itself you can then set up button click handlers.
btnCancel.OnClick := lambda Application.HideModal(mrCancel); end;
btnOK.OnClick := lambda CloseDialog; end;

The CloseDialog method will check whether the edit box is empty or equal to an already existing item in the listbox. You are correct that the IndexOf method is of no use in this case so just use a for loop to check all listbox items.
procedure TAddDialog.CloseDialog;
begin
  if inpItem.Text = '' then
    Exit;
  for var i := 0 to Items.Count - 1 do
    if Items.Text[i] = inpItem.Text then
      Exit;
  Application.HideModal(mrOK);
end;

BTW, the best way to access the dialog edit box from the main form is to expose it via a property in the dialog object:
property ItemText: string read (inpItem.Text) write (inpItem.Text);

The code in the main program can then access this property.
procedure TMainForm.OkResponse(dialog: TW3CustomForm);
begin
  lbItems.Add((dialog as TAddDialog).ItemText);
end;


text:
Q: Fancyhdr chapter and section titles overlap when titles are long I want to make a header using \usepackage{fancyhdr} and \pagestyle{fancy}. But when chapter and section names are long they overlap. Is there an option to force line breaks in the header so that they do not overlap?
Here a minimal example:
\documentclass{report}

% specifying header
\usepackage{fancyhdr}
\pagestyle{fancy}

\begin{document}

\chapter{A very long chapter title that should be on the top right}
\section{A very long section title that should be on the top left}

\newpage
Here, the header looks messy.

\end{document}

I saw that this question was discussed here but I hope that this did not really help me.

A: Here is an example of setting headings this way, using \parboxes and \RaggedRight/\RaggedLeft from ragged2e:

\documentclass{report}

\usepackage{fancyhdr,ragged2e}
\fancyhead{}
\lhead{\parbox[t]{0.4\textwidth}{\RaggedRight\rightmark\strut}}
\rhead{\parbox[t]{0.4\textwidth}{\RaggedLeft\leftmark\strut}}
\setlength{\headheight}{5\baselineskip}
\pagestyle{fancy}

\begin{document}

\chapter{A very long chapter title that should be on the top right}
\section{A very long section title that should be on the top left}

\newpage
Some text to demonstrate the header. looks bet.

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: hostname and hostname -s differ My /etc/hostname has:
name.domain.net

Previously, it was:
old.domain2.net

If I do hostame I get name.domain.net. But doing hostname -s returns old.
According to the man page:
   -s, --short
          Display the short host name. This is the host name cut at the first dot.

Which is not what I get. I have even rebooted the server.
Any ideas?

A: Just happened to me on CentOS 5.7 and found out using strace. Btw what distro is it?
Your /etc/hosts probably still looks like:
127.0.0.1   old.domain2.net localhost localhost.localdomain

You should replace the FIRST entry there, which probably still points to the old name.
This might also be tuned by editing /etc/nsswitch.conf and /etc/host.conf, but probably not required.


text:
Q: Is there any utility like smartctl which gives identify data for an ATAPI device? I want to know the identify data for the ATAPI device(CD/DVD ROM) I am using.
I can get the same information using the smartctl --identify /dev/device for the ATA Hard Disk but the same is not available for the CD/DVD Drives.
Is there any other command/utility which can give me such information. I am looking for an output in the same format as smartctl --identify gives.
Thanks

A: hdparm --identify ( or -I ) /dev/device reads and interprets the ATA device IDENTIFY DEVICE data.


text:
Q: NFS directory is no longer mounted but throws an error in df -h? I have an NFS server (at say, 1.2.3.4), and several clients.
On the clients, I had mounted a local directory by executing:
sudo mount 1.2.3.4:/var/nfs/stuff /mnt/nfs/var/nfs

All was good until I decided to change the location on the clients to /mnt/nfs. I first unmounted the existing mount point and then remounted the new one:
sudo mount 1.2.3.4:/var/nfs/stuff /mnt/nfs

No problems with that. And the new mount works fine. But when I run df -h, I get the error:
df: '/mnt/nfs/var/nfs': No such file or directory

And then it prints the normal mount points. When I execute:
mount -t nfs

I still see the old (/mnt/nfs/var/nfs) mount point listed, along with the new one. How can I fix this?


text:
Q: What is the performance hit from using SWT_AWT Bridge in Eclipse RCP I am building an Eclipse RCP application that will eventually have section for NASA Worldwind AWT component.  I will be using the SWT_AWT bridge to get the worldwind component embedded in an RCP application.  I am trying to decide whether I should write other components using SWT, or use Swing all the way and embed everything using SWT_AWT bridge.  The latter would allow me to use Swing, but not sure what the performance implications are?

A: If you are going to write an RCP application then it is best to stick to the native concepts and use SWT.
When you are going to write everything in Swing then there will be a performance penalty. How much, as always, depends on the hardware you are using. With todays hardware, assuming NASA has the funds, it would not be all that relevant.
What would be more relevant is the difference in UI. SWT renders with native widgets, Swing does not.
A good read is this article on the Swing in RCP [1]
[1] http://www.eclipse.org/articles/Article-Swing-SWT-Integration/


text:
Q: Smooth Data and Find Maximum I have a dataset (see below) of two variables, x and y.  I want to find for which value of x, does a maximum in y occur.  My current approach is simply to look up the x which gives me the maximum y.  This is not ideal as my data is quite noisy, so I would like to perform some sort of smoothing first, and then find the max.
So far, I have tried to use R to smooth my data with npreg (kernel regression) from the np package to obtain this curve:

but I'm not sure how to find the max.
I would like a solution to the following in Python:
1) Smooth the data (doesn't to be kernel regression)
2) Find the value of x where the max in y occurs using the smoothed data
x   y
-20 0.006561733
-19 -4.48E-08
-18 -4.48E-08
-17 -4.48E-08
-16 0.003281305
-15 0.00164063
-14 0.003280565
-13 0.003282537
-12 -4.48E-08
-11 0.003281286
-10 0.004921239
-9  0.00491897
-8  -1.52E-06
-7  0.004925867
-6  -1.27E-06
-5  0.009839438
-4  0.001643726
-3  -4.48E-08
-2  2.09E-06
-1  -0.001640027
0   0.006559627
1   0.001636958
2   2.36E-06
3   0.003281469
4   0.011481469
5   0.004922279
6   0.018044207
7   0.011483134
8   0.014765087
9   0.008201379
10  0.00492497
11  0.006560482
12  0.009844796
13  0.011483199
14  0.008202129
15  0.001641621
16  0.004921645
17  0.006563377
18  0.006561068
19  0.008201004

A: I'd run a Gaussian filter over the data to smooth:
# first, make a function to linearly interpolate the data
f = scipy.interpolate.interp1d(x,y)

# resample with 1000 samples
xx = np.linspace(-20,19, 1000)

# compute the function on this finer interval
yy = f(xx)

# make a gaussian window
window = scipy.signal.gaussian(200, 60)

# convolve the arrays
smoothed = scipy.signal.convolve(yy, window/window.sum(), mode='same')

# get the maximum
xx[np.argmax(smoothed)]

Here's the smoothed result:

The max occurs at 6.93.
There are a whole bunch of other window functions and filtering options in scipy.signal. See the documentation for more.

A: You might be able to use the smooth spline functions:
import numpy as np
from scipy import interpolate
x = range(-20,20)
y = [0.006561733, -4.48e-08, -4.48e-08, -4.48e-08, 0.003281305, 0.00164063, 0.003280565, 0.003282537, -4.48e-08, 0.003281286, 0.004921239, 0.00491897, -1.52e-06, 0.004925867, -1.27e-06, 0.009839438, 0.001643726, -4.48e-08, 2.09e-06, -0.001640027, 0.006559627, 0.001636958, 2.36e-06, 0.003281469, 0.011481469, 0.004922279, 0.018044207, 0.011483134, 0.014765087, 0.008201379, 0.00492497, 0.006560482, 0.009844796, 0.011483199, 0.008202129, 0.001641621, 0.004921645, 0.006563377, 0.006561068, 0.008201004]

tck = interpolate.splrep(x,y) # pass in s= some value to change smoothing:
                              # higher = smoother, s=0 for no smoothing

xnew = np.arange(-20, 20, 0.1)
ynew = interpolate.splev(xnew,tck,der=0)

now xnew and ynew contain a finely sampled version of the fit, and you get the max with
max_index = np.argmax(ynew)
max_value = ynew[max_index]
max_x = xnew[max_index]

Sorry I was not able to test this; computer I am using right now doesn't have scipy etc. loaded... Should give you some ideas though.
Reference: http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html

A: I am not completely sure what is the main problem to solve? Better smoothing, finding the minimum or doing it all in Python? Why are you changing to Python if you have promising progress in R? I have found that in R the built in supsmu function usually does very good non-parametric smoothing. This is how I would do this in R.
smooth <- do.call(supsmu, data)
min.idx <- which.min(smooth$y)
min.point <- c(smooth$x[min.idx], smooth$y[min.idx])


text:
Q: How to actually get email DELIVERED past spam filters After hosting my own email server for 2 years I feel like it has come time to admit defeat. I can't get my email delivered past spam filters on Microsoft and Google despite following every protocol, every instruction, and building a clean reputation for my IP and domain over 2 years' worth of time. I am the only user on this domain and I only send personal email, so obviously Microsoft and Google should be marking all of my email as non-spam.
Anyway, I just want my email delivered. My question is how to actually do this in practice? In particular, is there a large corporation that I could pay to deliver my emails from my personal domain? I know many places advertise these services, but which of them are actually able to deliver email? Or if someone wants to fix deliverability on my mail server, I'm open towards rechecking everything one more time.

A: There are several ways to improve your mail server.
You can use this service : https://www.mail-tester.com/. Send an email, and it will shows you a report with all the problems and some clues to fix them.
If you have already done all possible security improvements, like DKIM, DMARC, reverse DNS and so, maybe you are still grey or black-listed by some antispam lists. I already hadthis issue myself : some companies were using their own mail server with an old antispam blacklist were I was still listed. Some antispam lists grey-lists by default large range of IP just because they are reserved to regular people use and may be used by spammers.


text:
Q: 'Database Error: Unable to connect to the database:Could not connect to MySQL' in Joomla I am using joomla 1.5, and my site was running fine, but suddenly couple of days back I got the error Database Error: Unable to connect to the database:Could not connect to MySQL
Its not always, the error is coming. Sometimes the error is coming, and sometimes not. If I have wrong database connection values, then why, is the site coming perfect sometimes. I double checked my database connection values, and are completely fine.
Try http://www.scholarsmarket.com/beta/top-ranked-students this link. Refresh this couple of times. You will get the problem
I am stuck with this error. Can't get out of this.

A: It a very common issue to tell exact reason, I think you should start from asking your hosting support about any limitations e.g. Database connections?
then take a look at the logs and statistics - probably you site suddenly got too much visitors at that time?

A: If this error seems to pop up 'randomly' it's usually because either persistent connections are used (or another reason why the connection goes into sleep mode for some time). Persistent connections are generally not a good idea on medium- to high-traffic sites, since it clogs up your database with 'sleeping' connections. Once those connections hit the maximum connection account for your database user, the MySQL server will reject any new connections and throw the error you are seeing.
So, in order to fix this problem, make sure your db config is not set to use persistent connections. You can also verify if this is the problem by running this query on your database (given that you have the proper permissions to do so):
SHOW PROCESSLIST;


text:
Q: Modifying shape colour based on cell value Am looking to modify the shape colour based on a linked cell value ...
The shape is 'test' and the cell value "X11". I'm getting the error that the object does not support this property or method ...
Sub CChange()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet

   With ws.Shapes.Range(Array("test"))
        If .Range("X11") = 1 Then
            .Fill.ForeColor.RGB = RGB(18, 38, 43)
        ElseIf .Range("X11") = 2 Then
            .Fill.ForeColor.RGB = 0
        End If
    End With
End Sub

A: Change your code to this , your with statement is wrong.
You are not working with worksheet hence you cannot access range with .Range.
Sub CChange()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet

   With ws.Shapes.Range(Array("test"))
        If ws.Range("X11") = 1 Then
            .Fill.ForeColor.RGB = RGB(18, 38, 43)
        ElseIf ws.Range("X11") = 2 Then
            .Fill.ForeColor.RGB = 0
        End If
    End With
End Sub


text:
Q: How to get rid of this code duplication while still maintaining elegant events? Ok so let's say I have two classes, class A and class B. They both need to perform a common operation but it wouldn't make sense to have them both derive from the same object so instead we go with composition. Basically, "has a" makes sense where "is a" doesn't.
Now each of the two classes instantiate this object and use it to perform the common operation and all is good. Everything is fine, now.
The problem arises when each of these two classes have to expose an event that the common routine must raise. Uh oh. Now what?
Well, we could do something like this in each of the two classes:
public event EventHandler CommonEvent
{
    add { theCommonObject.CommonEvent += value; }
    remove { theCommonObject.CommonEvent -= value; }
}

But now this code needs to be duplicated in each of the two classes and readers of the code may be somewhat confused by this code as well. add and remove are not very commonly seen keywords, at least.
Still, there is duplicate code in both of the two classes and not only that, but this solution will not always work!
For example, what if theCommonObject is locally instantiated in a single method and its scope is only within that one method.
Well then, in that case we cannot even use the shortcut code posted earlier and we have to completely duplicate the code in both classes. Not only that but it just screams inelegance because we're basically just re-raising a copy of the event to clients.
Example code that would have to be duplicated in each class in this case:
public event EventHandler SomeCommonEvent;

private void SomeMethod()
{
    theCommonObject = new theCommonObject();

    theCommonObject.DoSomething();

    theCommonObject.SomeCommonEvent += thisClass_SomeCommonEvent;
}

private void thisClass_SomeCommonEvent(object sender, EventArgs e)
{
    var handler = SomeCommonEvent;

    if (handler != null)
    {
        handler(this, e);
    }
}

As you can see, in both cases there is duplicate code but in the second there is even more because the object is local to a method rather than a member variable.
I cannot really think of a way around this, other than using inheritance but I don't think it makes semantic sense to do so, and many often claim that composition is superior to inheritance in terms of complexity-reduction, ease-of-understanding, et cetera.

A: You say you have a "has-a" relationship. From that, and based on your proposed solution that duplicates code, I assume your class A looks something like:
public class A
{
    private SomeCommonObject theCommonObject;
    public event EventHandler CommonEvent
    {
        add { theCommonObject.CommonEvent += value; }
        remove { theCommonObject.CommonEvent -= value; }
    }

    public A()
    {
        theCommonObject = new SomeCommonObject();
    }
}

Where's the problem? theCommonObject can never be "locally instantiated in a single method and its scope is only within that one method."
Yes, add and remove are not commonly used. So what? Clients of the class never see the add and remove. They still subscribe to the event using the traditional += syntax. The add and remove syntax is a non-issue as far as clients are concerned. And you, the developer, who is creating the class, are expected to know about these things.

A: You could use static helper to get code one time but it's also 'bad'
Problem is implementation can be written one time with derived, you decided not to derive.


text:
Q: Logistic Regression Model building (dropping p-values) I'm researching factors that influence how bookable a certain room is with data similar to that of Airbnb. The idea is to look at what has been filled out in a listing of a room (i.e. utilities included, kitchen shared/private, toilet shared/private...) to make a prediction on the probability of booking for a room, as opposed to just taking the average booking. A secondary (and more applied goal) would be to say that certain criteria can be made mandatory as they make the room x-times more bookable. So by including x,y,z the room would be i.e. double as likely to get booked. I have experience with regression but am fairly new to logistic regression, so I'm not 100% sure if this is the most sensible use of this method to get to the above mentioned outcome.
To establish the probability of a booking I have ca. 40 possible criteria that could be predictors in the model which are taken from the listing process of roughly 7000 rooms (I can 'zoom' into different cities and compare to adjust for confounding factors), and after analyzing them and basing it on previous knowledge I came up with around 7-8 that should have the largest effect size.
I figured I would use logistic regression to build the model as I have both continuous predictors and categorical ones, and of course my categorical dependent (booking: either 0 no booking, or 1 booking). My problem is that if I test the significance of those individual predictors on the dependent (booking) they are all significant, but once I start fitting them into a model together the significance drops and only 2 or 3 (and not even the ones with the largest effect size) remain. I assume this is often due to multicollinearity (i.e. bed & desk in a room are usually both filled out together if they happen to be filled out). Another issue is that the data varies a bit across datasets, so some predictors are significant in one dataset (e.g. London), and then they are insignificant when looking at the world dataset. I suppose as this is not an experimental setting it makes it all a bit more complicating.
My questions are:

*

*Is logistic regression the most appropriate method?

*How much do p-values matter when assessing whether a predictor should be fit into the model (I read on some other posts that it shouldn't be your all-or-nothing criterion in selecting predictors, but rather that you should look at changes in pseudo R^2 and goodness of fit).
In the end even if the lower bound of the CI of the Odds is below 1 it shouldn't matter to much as in reality if I think about it I doubt adding useful information such as specifications of the kitchen will decrease the bookability of a room.

Btw I'm running it on SPSS
Thanks a lot in advance.

A: Question 1:
Logistic regression should certainly work here: you have a binary outcome (booked or not) and you have 40 predictors. You could consider adding quadratic terms (squaring all your continuous variables and adding them as extra predictors) or interaction terms (multiplying your predictors with each other).
If you feel like testing other methodologies and your focus is on creating a good prediction model, you could look into, e.g., support vector machines, decision trees, random forests. I would suggest the caret package for R (http://topepo.github.io/caret/index.html) for this. However, this will be some extra work but performance might increase. Also, some of these models might be harder to interpret. If you are really just looking into finding the predictors, logistic regression is already a good choice.
Question 2:
p-values give good indications for individual variables but, as you said, as soon as you have correlating predictors in a model, they are harder to interpret.
If you are looking into building a good prediction model: I would evaluate models by their performance in a cross-validation (not sure whether SPSS can do that?). Take something like 70% of your dataset and test multiple combinations of variables in a cross-validation. You can evaluate your models using different metrics: Area under the ROC-cure (AUC) for discrimination, mean-squared error for minimizing the prediction error, etc. Choose a metric and take the model with the best metric, test it on the 30% of 'unused' data - this is the estimate of how your final model performs.
On top of that, you can choose to use penalized logistic regression (logistic LASSO, elastic net) to select predictors for you (again, extra work to learn this but it might save you plenty of time in the future). In that case you would have to tune the penalization parameters in the cross-validation instead of trying different combinations of predictors.


text:
Q: Exception in the OptaPlanner NurseRostering Example Whenever I am trying to user NurseRostering Problem, OptaPlanner. Following is the error, Could you please suggest me a with a possible place of correction, or what needs to be done to rectify it. Please Note; I dont want to import the examples jar because I am trying to use the code for a different purpose.
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The solver configuration (/org/optaplanner/examples/nurserostering/solver/nurseRosteringSolverConfig.xml) does not exist.
    at org.optaplanner.core.config.solver.XmlSolverFactory.configure(XmlSolverFactory.java:65)
    at org.optaplanner.examples.nurserostering.app.NurseRosteringApp.createSolver(NurseRosteringApp.java:33)
    at com.nttdata.scheduling.app.CommonApp.createSolutionBusiness(CommonApp.java:101)
    at com.nttdata.scheduling.app.CommonApp.init(CommonApp.java:85)
    at com.nttdata.scheduling.app.MainApp$1.actionPerformed(MainApp.java:82)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

A: OptaPlanner uses getClass().getResource("/org/optaplanner/examples/nurserostering/solver/nurseRosteringSolverConfig.xml") to retrieve that classpath resource. If it's not found, that exception is thrown.
Check if optaplanner-examples/src/main/resources is properly marked as a (resources) source path in your IDE or build.


text:
Q: How can put what come after the decimal in a integer in java? For example if I had a (double 123.987) how can take what comes after the right of the decimal and make it A integer (987)?

A: Well you can use String and split to derive your output:
double number = 123.456;
String numberString = String.valueOf(number);
String[] digits2 = numberString.split("\\.");
System.out.println(digits2[1]);

After having this output, you can cast it to integer. Should not be that hard


text:
Q: Twitter search with Jquery and ajax Currently my code is:
<!DOCTYPE html>

    <title>Search Tweets</title>

        <input id="query" type="text" value="" />

        <input id="submit" type="button" value="Search" />

Tweets

Everything is working properly however when it recieves the code from the profile image url it only displays the URL and not the image itself.  How do i get the profile image to get displayed instead of just the code?
Thank you

A: Just wrap the image url in an img tag
tweets.append('
' + data['results'][res]['from_user'] + ' Said:
' + data['results'][res]['text'] + '

');


text:
Q: PostgreSQL database - only insert if the record doesn't exist
Possible Duplicate:
Cannot SELECT from UPDATE RETURNING clause in postgres

I am using a PostgreSQL database which has a "company" table and a "country" table which each have a uniqueID.
I want a setup where if I try to add a company to the database, it only adds the company to the database with a new unique ID if it doesn't already exist.

A: insert into company (unique_id, company_name)
select 42, 'New Company Name'
from company
where not exists (select 1 from company where unique_id = 42);

See also here for a more general solution: Insert, on duplicate update in PostgreSQL?


text:
Q: The type or namespace name 'Speech' does not exist in the namespace 'System' (are you missing an assembly reference?) [!][1]][1][]2подскажите пожалуйста что происходит вчера студия переваривала System.Speech.Recognition а сегодня ни в какую. Microsoft.Speech.dll загружен и подключен. работаю в консольном.

A: ответ прост: по невнимательности я использовал
using System.Speech.Recognition;   ....
а нужно было
using Microsoft.Speech.Recognition;


text: Q: cant we access Mysql server without setting class path to it in environment variables in windows? I have installed the mysql server in windows. do i need to set the class path in environmental variables, without which can't i access the mysql server, using the command prompt of windows or connecting to it from any other system? what is the purpose of setting the class path? i installed ms sequel server, that is also a database server. To this ms sequel server i did not set any class path i was able to connect to it without any issues.


text:
Q: Excel VBA get a range value from visible cells after applying autofilter Is it not possible to do something simple like this to get the range value of B2?
crdata.Range("B2").SpecialCells(xlCellTypeVisible).Value

I have applied the autofilter to filter out with the given criteria and trying to return the range of B2 as a function.

A: Set the .SpecialCells(xlCellTypeVisible) to a Range, then use Cells(row, column) on this range to pick out the value that you require.  If you are using headers in the result then you may also have to use Offset(1,0) to address your data.  So where 'MySheet' has been defined as a Worksheet object, smething like:
Set rsltRng = MySheet.Autofilter.Range.SpecialCells(xlCellTypeVisible)
msgbox rsltRng.cells(2,2)


text:
Q: Grails: how to handle java bean validation on Grails I'm using Java entity classes as domain objects in Grails application. These classes have JSR 303 validation annotations (@Size, @NotEmpty etc...)
Grails controllers and views work fine with these entity classes, but when I try "bean.validate()" its always true.

A: You might need JPA plugin to deal with JSR 303 annotations. Also have a look at this defect.


text:
Q: Find values of $n$ that yield a prime number
Let $n$ be a positive integer, and $\frac{n(n+1)}{2}-1$ is a prime number. Find all possible values of n.

What I have so far is this: $$\frac{n(n+1)}{2}-1=2, n=2$$
Also, $n^2+n-2\over2$ can be factorized to be $(n+2)(n-1)\over2$.
What other values of $n$ are there, and how do you compute them? This question was from my Math Challenge II Number Theory packet.

A: HINT: Have you tried putting this over a common denominator and factorising the numerator?
If you are flagging this as "contest math" and aspiring to compete you really need to work through the basics before getting more of a clue than that.

A: If you have $p={(n+2)(n-1)\over2}$, then $2p=(n+2)(n-1)$ and so there are only two possibilities:

*

*$n-1=2$ and $n+2=p$.

*$n-1=1$ and $n+2=2p$.

A: Hint: $\frac{(n)(n+1)}{2} - 1 = p$
$n^2 + n -2 = 2p$, can you take it from here?


text:
Q: How to prevent a user from registering multiple accounts to vote themselves up This question isn't about preventing a single user from registering multiple accounts. It is assuming that registering multiple accounts cannot be prevented, but what we want to avoid/detect is when the user is using the accounts to vote for himself. This would apply to  sites like SO or digg, where a user creates a 2nd account solely for the purpose of of voting up their 1st account.
Any ideas how gaming the system in that way can be prevented/detected? Any insights how SO does it? :)

A: Discourage user A from up-voting user B when user B last connected from the same terminal point as user A.  You can attempt to track terminal identity through IP address, cookies, or a combination of the two - all too easily defeatable by the determinate user (use of anonymizer proxies or of multiple wifi connections, cookie clearing or use of multiple browsers, etc.)  And, of course, the inevitable dislike of individuals accessing your site from behind (e.g. corporate) proxies.
Another complementary line of defense would be, if your voting model allows it, to lower the value of votes given by potential collusion e.g. if user A voted for user B and user B voted for user A then you can arbitrarily decide to split the vote between the two (0.5 points each); you can nuance this based on existing reputation (gradually stop penalizing users with high reputations), or not nuance this (assume that users with high reputation, even if rightfully voting for each other - or for themselves if dishonest - won't mind working harder for additional reputation), etc. etc.

A: The creators of the site wrote about Vote Fraud and You.

A: Seems like one obvious sign would be when one user account casts nearly all its upvotes for one other user account.
If I were writing an algorithm to look for vote fraud, I'd probably start like this: for each user account A, create a histogram showing, for each number N=1,2,3,... of votes, how many other accounts have received N votes from A? Offhand I'd guess it would be something like a decreasing exponential distribution, e.g. A has upvoted 100 accounts once, 50 accounts twice, 25 accounts 3 times, and so on... the point being, it drops down to zero after just a few counts (in this case after N~8). If account A is upvoting one particular account much too often, you'll see a count at some absurdly large N like 80 or 100, and you can have the system flag that for you to look at more closely.

A: An easier way to get yourself voted up is to post intelligent responses. One could also resort to some form of clickjack to encourage others to vote you up without them taking an explicit action to do so.

A: It is not lockable but we can show some stats to the public and can avoid users to do this. Here is my answer.

*

*If there are two persons on StackOverflow, 'A' and 'B'.

*If 'B' up-vote 'A' more than 25 times, then this should be displayed on A's profile.

*Now if 'B' have more than 500 reputation, it means its OK that 'B' is also participating in SO.

*If 'B' have less than 500 reputation and up-vote 'A' 25 times, it may be that 'B' is a fake profile.

*In case, if 'B' is deleted after up-votes, then this should be displayed on profiles after some particular such cases.
OR
their should be some stats on each user profile like this:
10 up-votes from profiles with above 10,000 rep
27 up-votes from profiles with above 5,000 rep
50 up-votes from profiles with above 3,000 rep
45 up-votes from profiles below 1,000 rep
10 up-votes from deleted profiles.
20 up-votes from inactive profiles.

OR
20 rep on one up-vote from a person with above 10,000 rep
15 rep on one up-vote from a person with above 5,000 rep
10 rep on one up-vote from a person with above 1,000 rep
05 rep on one up-vote from a person with above 500 rep
02 rep on one up-vote from a person with below 500 rep

OR some thing like above can help.
https://meta.stackexchange.com/questions/35989/how-to-detect-if-users-have-created-more-than-one-profile-to-support-himself-hers/35994#35994


text:
Q: c3.js chart data is loaded but graph does not render while page load and refresh I tried some examples of c3.js Followed this link. And i got success in that. But i have one problem when i'm trying to load graph first time in any browser, it doesn't show me the graph.
And if i reload page once or twice it shows graph but data is loaded.
I'm using latest version 0.6.1 library in my project, even though chart not shown.
I googled quite a lot but i couldn't found any correct solution.
If anything is there to fix this issue suggest me. Thanks in advance.


text:
Q: How to animate active layout change (Layout A -> Layout B) in Android? I have a problem with animating layout transision in my Android Application.
I've three layouts stacked on each others. I just change visible layout to decide what content is shown to user. So the lifecycle look like this A->B->C->A...
The problem is that I want to animate my layout changes and I don't have idea how to do that. I want to achive ebook's like sliding effect (or any other one, I just want to get how does it work).
Any ideas?

A: My code:
MainActivity:
public class MainActivity extends Activity implements View.OnTouchListener {
private ViewFlipper viewFlipper;
private float touchDownX;
private float touchUpX;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewFlipper = (ViewFlipper) findViewById(R.id.body_flipper);
    viewFlipper.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        touchDownX = event.getX();
        return true;
    } else if (event.getAction() == MotionEvent.ACTION_UP) {

        touchUpX = event.getX();

        if (touchUpX - touchDownX > 100) {

            viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_right_in));
            viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_right_out));

            viewFlipper.showPrevious();

        } else if (touchDownX - touchUpX > 100) {

            viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_left_in));
            viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_left_out));

            viewFlipper.showNext();
        }
        return true;
    }
    return false;
}

}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"     tools:context=".MainActivity">

<ViewFlipper
    android:id="@+id/body_flipper"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f0f0f0" >

    <include
        android:id="@+id/layout01"
        layout="@layout/page1" />
    <include
        android:id="@+id/layout02"
        layout="@layout/page2" />
    <include
        android:id="@+id/layout02"
        layout="@layout/page3" />

</ViewFlipper>

</RelativeLayout>

push_right_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
    android:duration="400"
    android:fromXDelta="-100.0%p"
    android:toXDelta="0.0" />
<alpha
    android:duration="400"
    android:fromAlpha="0.1"
    android:toAlpha="1.0" />
</set>

push_right_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
    android:duration="400"
    android:fromXDelta="0.0"
    android:toXDelta="100.0%p" />
<alpha
    android:duration="400"
    android:fromAlpha="1.0"
    android:toAlpha="0.1" />
</set>

push_left_in.xml and  push_left_out.xml are similar to the above ones.

A: use ObjectAnimator class and implement fade/translation animations that fit your needs.

A: Try to use ViewFlipper to flip between views. http://developer.android.com/reference/android/widget/ViewFlipper.html


text:
Q: Integration between Amazon S3 and QGIS Does anyone know an easy way to integrate QGIS and S3 buckets? To read the files from the bucket in gis platforms directly, without download?
I was looking for the same thing for R, and I found the package flyio (https://cran.r-project.org/web/packages/flyio/flyio.pdf) which is absolutely amazing, but still with the issue to integrate S3 and QGIS.
If it's possible so we can move from an internal server to S3 storage for the spatial data, instead of only raw/table-based data.
Thanks all in advance for ideas and feedback.

A: I don't know if this question is still of interest, but our approach was using PostgreSQL with the PostGIS extension in Amazon RDS to serve spatial data. Instead of storing your files in S3 storage, upload them to PostgreSQL tables. By doing so, you will also get daily snapshots of your data, better performance, the ability to query data with SQL and even set up authorization rules to match your exact needs.
It may seem a little more expensive at first, but if you find an alternate way to use S3 storage you will be using some kind of additional server which will also cost as much. Maybe some kind of software that adds S3 storage as a network attached drive works, but you will run into concurrency problems and sync issues if the files are used simultaneously by many people.
Let me know if you find a different approach. I am unaware of how you could do it.

A: S3 is specifically supported as a remote protocol, but others have shown that if the data is public, then using HTTP(S) to access the bucket may be easiest.
Open a layer in the Data Source Manager (the red, yellow, and blue squares icon), then change to Protocol: HTTP(S), cloud, etc. and enter the URL (documentation).
Example URL:
https://example-bucket.s3.us-east-1.amazonaws.com/sweet-layer.tif

To instead use S3 via vsis3 (public or private) or vsicurl (public; maybe private but complicated if so):

*

*general documentation

*vsicurl

*vsis3
The basics are that the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required and the "bucket" is the URL with the bucket path and the "object key" is the file or folder of the layer.


text:
Q: How do I handle projects in which my project manager is the same as the client? I am a freelance worker taking on a new project with a company I'm already familiar with. My boss (the company owner) previously gave me a website project to work at while he also assigns a project manager to review the progress. But with my latest project, the setup here is a little different.
My boss assigned to me this project as well. He's only in the office two days out of a week. After the first meeting with the client, I wondered who was the PM since I wasn't introduced to him/her. When I told my boss that in most cases, I'd rather report to the PM because it's easier and more accessible, that's when he informed me there that my PM is the same person as the client! I was a bit shocked. I didn't want to tell him right out that I find something very wrong with that arrangement, but I'm stuck with this project for now.
So I end up being in direct contact with the client once a week, which is good in a few cases, but am responsible for meeting him for extended periods while my boss only sits in for a few minutes. Especially for a project of a scope which will last for a few months, I feel like I'm doing the job of both a project manager and programmer.
I didn't quote him for the project- the PM/client sent the quote to my boss, and my boss is handling my payouts based on that.** He also controls the schedule for the project. So I'm trying to tread carefully with completing the goals so I don't get short-changed.
My biggest concern, though, is the lack of good communication. The PM/client is not very technically inclined, sometimes states goals that are subtly different from what I perceive, and asks for things that are beyond the means of the tools I'm working with. My boss is better at explaining the situation in a broad sense, but like I said he's not always available, and pretty slow at responding online.
Basically, there's a lack of a dedicated PM and there is sparse communication among me, my boss and the PM/client. How would I track my own progress and ensure better performance, and avoid misinterpreting the tasks for the project? I want to stay on a good pace with the communication I receive without feeling stuck or overwhelmed.
I prefer face to face contact. Everyone else in the office updates their progress by discussing with PMs working in the office on a daily basis, and their projects go more smoothly. My boss isn't interested in having one of them work on this project because he says it'll take a lot of time away from their current work. I want to force in more communication in this project but my boss isn't doing much to help.
[Edit] Well, here's an update. What ended up happening is that our client was demanding other features that turned out to be out of scope, and the CMS that we had to use didn't permit addition of these features so easily. My boss and I struck out some of his demands in the essence of time and budget, and last week the client/PM ended up being dissatisfied and cancelled the project indefinitely.
In the future I will stay away from such arrangements with the client doubling as a PM. I think it gives someone far too much control over the direction of a project.

A: You should create a list of tasks to be completed for this project and manage it in a project management system such as Redmine. You should then give all necessary parties access to the project management system and have them add/edit tasks as necessary. With this, they can track your progress and ensure that all requirements for the project are listed and completed.
It's not the face-to-face contact you would prefer, but you definitely need to have something written down and able to be tracked. Otherwise, expectations will not be addressed from all sides and your project will likely suffer.

A: The fact your client and PM are the same person is actually pretty nice.
There is no middle man so nothing get's lost in translation which is a real danger as you are already having trouble with just you and him... imagine if there are more people in between?
As Bernard already points you should use this time with the customer to flesh out what you will do in the upcoming week. Identify the features that are the most value and which you can tackle in that timespan and focus on them.
Focus on the details from his point of view. He's non technical and he shouldn't be. You cover the technical part and can tell him what is possible and what's not.
Then make sure you have your requirements written down in a verifiable manner. An issue tracker can be nice for this. Personally I like automated tests but business is not often willing to look at those even in business oriented tools like FitNesse or Twist.
As we're talking about weekly time boxed iterations you'll find you'll have to keep your tasks small as well.


text:
Q: change mysql table storage engine upon import We have some customers sending us mysql database sql files where some times the tables engines are myISAM and when or before importing it into our database we would need to convert the tables to InnoDB. Is this possible?
cheers,
Peter

A: If you are fortunate enough to be on linux
sed -i 's/engine=myisam/engine=innodb/gi' userfile.sql

This does assume that the data itself does not contain the exact text engine=myisam you can make it a bit more rigorous like this:
sed -i 's/) ENGINE=InnoDB/) ENGINE=MyISAM/g' junk.sql

A table creation statement looks like this:
CREATE TABLE `Table1` (
  `user_id` int(11) DEFAULT NULL,
  `user_name` varchar(5) DEFAULT NULL,
  `user_rating` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

And in the second usage of sed we have made it case sensitive and it also looks out for the ) and ' ' characters that preceded the ENGINE keyword


text:
Q: how to play youtube video with sound in wxpython window? I am making a simple youtube player and downloader app accessible for blind people with screenreaders, but also usable by sighted people.
I chose wxpython because it has best accessibility ever.
How to play a youtube video in the wx window? Do I need to use wx.media.MediaCtrl and how to correctly use it?
can I play youtube video without downloading it right in the wxpython window?
I tried using wx.media.MediaCtrl, but I downloaded the video from youtube and then made it to show the video.

A: wx.media will play direct from a URL, although I have no idea if it can access a YouTube url directly (I'm not a fan).
Here's a very bare bones player accessing a url rather than a file.
I would suggest that you test the media link to see if it is a url or a file, then use LoadURI or Load depending on the outcome.
import wx
import wx.media

class TestPanel(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title='Media Player')
        panel = wx.Panel(self, -1, size=(500, 700))
        self.player = wx.media.MediaCtrl(panel, style=wx.SIMPLE_BORDER)
        self.stop = wx.Button(panel, -1, "Stop")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.player, 1, flag=wx.ALL, border=5)
        sizer.Add(self.stop, 0, wx.ALL, 5)
        panel.SetSizer(sizer)

        self.media = 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4'
        self.player.Bind(wx.media.EVT_MEDIA_LOADED, self.play)
        self.player.Bind(wx.media.EVT_MEDIA_FINISHED, self.quit)
        self.Bind(wx.media.EVT_MEDIA_STOP, self.quit)
        self.Bind(wx.EVT_BUTTON, self.quit, self.stop)
        self.Bind(wx.EVT_CLOSE, self.quit)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.timer.Start(250)
        if self.player.LoadURI(self.media):
            pass
        else:
            print("Media not found")
            self.quit(None)
        self.Show()

    def OnTimer(self, event):
        if self.player.GetState() == wx.media.MEDIASTATE_PLAYING:
            print("Progress:",self.player.Tell())

    def play(self, event):
        self.player.Play()

    def quit(self, event):
        self.timer.Stop()
        if self.player.GetState() == wx.media.MEDIASTATE_PLAYING:
            self.player.Stop()
        self.Destroy()

if __name__ == '__main__':
    app = wx.App()
    Frame = TestPanel()
    app.MainLoop()

Worthy of note, you may have to choose your backend player via the szBackend parameter.
Available options are:

*

*MEDIABACKEND_DIRECTSHOW

*MEDIABACKEND_QUICKTIME

*MEDIABACKEND_GSTREAMER

*MEDIABACKEND_WMP10

If you want something more complicated than wx.media offers, you will have to roll your own.
Gstreamer and Vlc both work well on Linux, on other operating systems, I have no idea.
Edit:
If you must stream direct from youtube, use something like pafy to isolate the url.
For the above code:
add import pafy
instead of specifying the url to self.media replace
self.media = 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4'
with the following:
#       youtube url via pafy
        url = "https://www.youtube.com/watch?v=iL-jC7XyLeo"
        video = pafy.new(url)
        best = video.getbest()
        playurl = best.url
        self.media = playurl

Then continue as above


text:
Q: Transforming the array of object for Highcharts input? I am really struggling with the Object transformation. I have an array of Object and want to transform it into Highcharts multi line chart input. I want to get the unique dates first sorted from low to high, which will go into x axis and then transform the Original based on ID and date. The length for each ID.data is going to remain same (for whatever date count is not available for that date it will come as null)
Original:
 [
            {
                "date": "1997-09-29",
                "Count": 100,
                "ID": "AB12-R"
            },
            {
                "date": "1997-12-30",
                "Count": 104.7,
                "ID": "AB13-R"
            },
            {
                "date": "1998-03-30",
                "Count": 981,
                "ID": "BA12-R"
            },
            {
                "date": "1998-06-01",
                "Count": 341,
                "ID": "BA12-R"
            }
        ]

Transformed:
[{
Identiy : 'AB12-R',
data : [100,null,null,null]
},
{
Identiy : 'AB13-R',
data : [null,104.7,null,null]
},{
Identiy : 'BA12-R',
data : [null,null,981,341]
}]

I have tried with reduce but nothing is working it seems. I am able to group it by ID but not able to handle the null and missing count, Can someone please help me here ?
This is what i have tried:
  const result = Original.reduce(function (r, a) {
    r[a.ID] = r[a.ID] || [];
    r[a.ID].push(a);
    return r;
  }, Object.create(null));
  console.log({'Transformed':result})

A: Take a look at this solution:
const hcData = [];

data.forEach((d, i) => {

  const checkIfExist = hcData.find(data => data.id === d["ID"])

  if (checkIfExist) {
    checkIfExist.data[i] = d["Count"];
  } else {
    const initialData = [...Array(data.length)]
    initialData.fill(null, 0, data.length)

    initialData[i] = d["Count"];
    hcData.push({
      data: initialData,
      id: d["ID"]
    })
  }
})

Demo: https://jsfiddle.net/BlackLabel/k2dg1wns/


text:
Q: How to reduce the size of svg in d3.js? I'm using a template I found online for overlaying my data on a SVG (rendered by a geoJSON using d3.js).
I've included those variables too, as they are as I just wanted to test it.
Using this part of code, I'm able to get my map perfectly, without any cuts on the sides
Dimensions (650 x 650):
var w = 650;
var h = 650;
var proj = d3.geo.mercator();
var path = d3.geo.path().projection(proj);
var t = proj.translate();
var s = proj.scale();

var map = d3.select("#chart")
    .append("svg:svg")
    .attr("width", w)
    .attr("height", h)
    .call(initialize);

function initialize() {
    proj.scale(6700);
    proj.translate([-1240, 750]);
}

But when I change w or h to lower values, say 400 x 400 then it gets trimmed on the sides, when I leave the arguments in proj.scale() and proj.translate() as they are. Can someone please help how I can scale the size to lower dimensions like 400 x 400? (By changing anything in those arguments for scale() or translate())?
Any quick reference link which explains those changes brief and clear is also appreciated.


text:
Q: Printing multiple exceptions of method called I am implementing a compiler type checker in Java. My typeChecking class consists of methods that throw RuntimeExceptions if the given input file (program) is semantically wrong.
What happens now is when my program finds an error, it throws the exception and the program terminates. The functionality I want is to keep somewhere all the exception messages and print them at my Main class if an exception occurred at the typeChecking class.
Pseudocode example:
// Main class part of code
public static void main(String[] args){

    call typeChecking method

    if an exception (or more) occurred in the typeChecking class
        then print all the exception messages
    else no semantic errors found
        then do something else
}

What I thought is to create a static String array and add all the exception messages in it. Then at my Main class I am going to check if the array's size is 0. If it is not, this means exceptions occurred else not.
Is there any better way to do this?

A: Just use try-catch block to catch exceptions and do whatever you want with caught exception. I.e.
// Main class part of code
public static void main(String[] args){
    boolean exceptionOccured = false;
    try{
        call typeChecking method
    }catch(RuntimeException e){
        exceptionOccured = true;
        ...print it or put in an array or whatever.
    }
    if(exceptionOccured)
        do something else
}


text:
Q: Determine target of NTFS reparse point I have a Windows 2012 R2 server running as a VM (on top of KVM/Libvirt). It has an extra "internal" disk defined as F:
If I snapshot the Linux-based host's logical volume representing F: and mount it on the host I get many files tagged as being an unsupported reparse point.
What I want to do is to backup the filesystem from the host, which is why I've started from here.

Here is an example from the host's perspective
lvcreate --name shares-snap --size 10G --snapshot /dev/crypt_md3/shares
mount -o ro,offset=$((129*1024*1024)) /dev/crypt_md3/shares-snap /mnt/dsk
ls -l /mnt/dsk/mfc70.dll
lrwxrwxrwx 1 root root 26 Jan  5  2002 /mnt/dsk/mfc70.dll -> unsupported reparse point

Within the Windows guest, the file properties dialog shows its size to be 952KB but with the size on the disk as 0 bytes. This is classic for a reparse point. The advanced attributes are APL, with the L confirming that the file is indeed a reparse point.
Copying the file removes the P and L attributes from the copy.
Searching around lead me to How do you find the target of a symlink created with mklink and its accepted answer. I've downloaded both junction 1.06 and NTFSLinksView.
Running junction gets me nothing useful:
F:\> c:\local\bin\junction mfc70.dll

Junction v1.06 - Windows junction creator and reparse point viewer
Copyright (C) 2000-2010 Mark Russinovich
Sysinternals - www.sysinternals.com

F:\mfc70.dll: UNKNOWN MICROSOFT REPARSE POINT

Running dir /L gets me nothing useful either:
F:\>dir /L mfc70.dll
 Volume in drive F is Folder shares
 Volume Serial Number is B600-69DE

 Directory of F:\

05/01/2002  04:48           974,848 mfc70.dll
               1 File(s)        974,848 bytes
               0 Dir(s)  233,785,053,184 bytes free

Running dir /A:L does include the file, so it's definitely a reparse point of some sort.
NTFSLinksView simply doesn't list the file.

After all this background information, the question is really rather simple:

*

*How do I find out details of the reparse point?

*What do I tell ntfs-3g on the host to remap the junction points so they resolve?

A: These are probably de-duped files. They are implemented with junctions on disk and the file system driver handles reassembly. I doubt you will find a Linux tool that can deal with them. And other Windows utilities for junctions won't understand them because they were designed for regular junctions, not de-dupe junctions.


text:
Q: LINQ: How can i query a string? How can i query the following string, to extract information from it?
<Glyphs
Fill="#ff000000"
FontUri="\Documents\1\Resources\Fonts\547B9B52-1992-40E2-BBAA-0D815B2C6215.odttf" FontRenderingEmSize="10"
StyleSimulations="BoldItalicSimulation"
OriginX="20"
OriginY="1094.96"
UnicodeString="SomeString" />

For example, how can i read the OriginY value with LINQ?

A: The string you got looks a lot like XML. You might therefore want to try LINQ to XML. For instance, use the XDocument class:
var doc = XDocument.Parse(@"<Glyphs
    Fill=""#ff000000""
    FontUri=""...."" FontRenderingEmSize=""10""
    StyleSimulations=""BoldItalicSimulation""
    OriginX=""20""
    OriginY=""1094.96""
    UnicodeString=""SomeString"" />");

var fill = doc.Root.Attribute("Fill");

A:             string s = @"<Glyphs
Fill=""#ff000000""
FontUri=""\Documents\1\Resources\Fonts\547B9B52-1992-40E2-BBAA-0D815B2C6215.odttf"" FontRenderingEmSize=""10""
StyleSimulations=""BoldItalicSimulation""
OriginX=""20""
OriginY=""1094.96""
UnicodeString=""SomeString"" />";

            double val = (double)XElement.Parse(s).Attribute("OriginY");
            Console.WriteLine(val);


text:
Q: how to use GCP Client python API Call to start/stop VM across projects? I am trying to use the 'compute_v1' client library to START/STOP VMs in GCP. I need to do this across 'PROJECTS' so I am planning to use the IAM , RBAC approach for Service Accounts created with the "Service Account Token Creator Role" assigned.
How do I go about setting up the Credentials in my client.?
right now I just use my 'login' related json key file as follows:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/xxxxxx.json"

The scope of this application is to STOP/START a list of VMs based on a project and do this on demand.
All is well , now I want to use this in production across multiple projects.!
Any direction of how to Authenticate and impersonate the RBAC for each Service Account is much appreciated.


text:
Q: Save image blob-object to local filesystem Javascript I have a blob object that I get from a canvas containing image. I change this blob to objectURL.

let myBlob = canvas.toBlob(function(blob) {...}, 'image/jpeg', 0.95);
let myUrl = URL.createObjectURL(myBlob);

I get a blob object url like: blob:file:///d324f-3fd4....
To get the location the file is saved, I try to request the filesystem at first before calling getDirectory method of DirectoryEntry object. However, I get the generic File not found in the directory error.

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
webkitRequestFileSystem(window.TEMPORARY, 2048*2048, resolve, errorHandler);
// doesn't resolve to any value

I searched everywhere in the AppData folder in Windows 10 but no temporary files were found there. My guess is that the blob exists only inside browser-memory and not actually saved in the temporary root folder of electron.

A: URL.createObjectURL doesn't save your file on the disk, it only creates a symlink.
In case of Blobs stored in memory (like your case), the symlink points to the memory, and holds the file in memory for as long as the session that created the symlink is alive.
In case of Files (gotten from user's input), the symlink points directly to the user's disk.
So in your case you can't access its location, because it only exists in memory.
Now, you can always store the Blob on fileSystem, but I'm not an Electron ninja, so I'll let you check others' answers : Save video blob to filesystem electron/node js


text:
Q: Can we store files on the django framework? I was wondering on how to store some files in the django framework, and how to access them for editing and updating them? I wanted to upload a few excel files and a few python scripts which automate the excel files. Everything is working fine locally for me, but just wanted to know on how to do it for webpage which can be accessed by anyone?
Thanks

A: There are two ways to solve this problem:

*

*Copy the python automation code under your app directory, import it as a module in your django view.py file and call the function that performs the specified task. (preferred)

<your_app>/
├── admin.py
├── ...
├── <your_automation_script>.py
└── views.py

# views.py
from .<your_automation_script> import <edit_xlsx>

def view_function(req):
    # ... do before xls edition ...
    <edit_xlsx>()
    # ... do after xls edition ...
    return "something"

*Create a subprocess of the python automation code in the django view. (not preferred)

# views.py
import subprocess

def view_function(req):
    # ... do before xls edition ...
    process = subprocess.run(['/path/to/automation_script.py','<args_if_any>'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

    output = process.stdout
    errors = process.stderr
    # ... do after xls edition ...
    return "something"


text:
Q: Nan in pd.DataFrame (simmetrical matrix) I've got a dataframe like this one. I'd like to remove the nans and shift up the cells. Then add a date column and set it as index.
                ciao      google    microsoft
Search Volume   368000    NaN       NaN
Search Volume   368000    NaN       NaN
Search Volume   450000    NaN       NaN
Search Volume   450000    NaN       NaN
Search Volume   450000    NaN       NaN
Search Volume   450000    NaN       NaN
Search Volume   NaN       37200000  NaN
Search Volume   NaN       37200000  NaN
Search Volume   NaN       37200000  NaN
Search Volume   NaN       37200000  NaN
Search Volume   NaN       37200000  NaN
Search Volume   NaN       37200000  NaN
Search Volume   NaN       NaN       135000
Search Volume   NaN       NaN       135000
Search Volume   NaN       NaN       110000
Search Volume   NaN       NaN       110000
Search Volume   NaN       NaN       110000
Search Volume   NaN       NaN       110000

The output should be like:
date = ['20140115', '20140215', '20140315', '20140415', '20140515', '20140615']

date        ciao    google      microsoft
20140115    368000  37200000    135000
20140215    368000  37200000    135000
20140315    450000  37200000    110000
20140415    450000  37200000    110000
20140515    450000  37200000    110000
20140615    450000  37200000    110000

Looks simple but I don't know how to do it. Thanks

A: This should work:
denulled = {col: df.loc[df[col].notnull(),col].values for col in df.columns}

df_out = pd.DataFrame(denulled, index=date)

A: You can also use dropna on the columns as series
df1=pd.DataFrame(data=[df[i].dropna().values for i in df.columns]).T
df1.index=dates

A: My proposition is:
pd.DataFrame(data={ colName: df[colName].dropna().values for colName in df.columns },
    index=['20140115', '20140215', '20140315', '20140415', '20140515', '20140615'])

The main point is a dictionary comprehension, executed for each column.
dropna removes NaN items and values allows to free oneself from
index values.

A: One tricky solution cause by you have duplicate index
pd.concat([df[x].dropna() for x in df.columns],1)
Out[24]:
                  ciao      google  microsoft
SearchVolume  368000.0  37200000.0   135000.0
SearchVolume  368000.0  37200000.0   135000.0
SearchVolume  450000.0  37200000.0   110000.0
SearchVolume  450000.0  37200000.0   110000.0
SearchVolume  450000.0  37200000.0   110000.0
SearchVolume  450000.0  37200000.0   110000.0

A: you could use apply with dropna:
df = df.apply(lambda x: pd.Series(x.dropna().values)).fillna('')
df['date'] = date
print(df)

output:
     ciao      google   microsoft  date
 368000.0  37200000.0   135000.0   20140115
 368000.0  37200000.0   135000.0   20140215
 450000.0  37200000.0   110000.0   20140315
 450000.0  37200000.0   110000.0   20140415
 450000.0  37200000.0   110000.0   20140515
 450000.0  37200000.0   110000.0   20140615


text: Q: Deployement Strategy Type when pod in already up then dont deploy otherwise deploy I am doing CI CD with gitlab and openshift using custom templates. I just want to know Is there any deployment strategy which will not recreate the pod everytime. I just want that if my pod is up then dont deploy again and if the pod is not present there then only it will deploy.


text:
Q: Is Telegram logo available as a character in Unicode? I have developed a Telegram bot. I want to send a text message with the bot.
In that message I want to insert Telegram logo besides my Telegram address but in a text message you cannot insert both image and text like in an html page.
I am constrained to use Unicode characters in my message. There are characters for phone, email, etc. in Unicode character set but I didn't find a character for Telegram logo. Is there such a character in Unicode or not?
The best possible character I found is Black Rightwards Arrowhead with code U+27A4.

A: No any organization icon added to Unicode for now, even is Google or Facebook.
If you see web pages use those icon, most of them use Font Awesome, likes fa-telegram, fa-stack-overflow icon.


text:
Q: Meteor/NodeJS with MongoDB Replica Sets - Multiple Datacenter Secondaries I am running Meteor (NodeJS) and planning to point to to multiple copies of MongoDB running in separate datacenters.  I plan to use:
MONGO_URL="mongodb://server1:27017,server2:27017,server3:27017,server4:27017/dbname?replicaSet=rs1&readPreference=nearest&w=majority"
Two questions.
1) Does anyone know if this will tell Node/Meteor to get its database read requests from the MongoDB that is CLOSEST (quickest ping times)? I think it should, according to the MongoDB docs, "nearest" readPreference https://docs.mongodb.com/manual/core/read-preference/ but I can't find the answer for sure in the Meteor and Node docs.
2) If the closest MongoDB disappears or times-out, will it automatically failover the database read requests to the next-closest Mongo?


text:
Q: How to perform p4 submit operation ONLY on files which has diff? I would like to know if there's a built-in function in P4 or a way to basically only allow the p4 submit to commit ONLY when the file has a diff. Let said I have rev 1, and I want to update the file with rev 2. But I should be only allow to make this change if rev 2 is actually diff from rev 1.
I checked P4 Manual on "p4 submit" , but I don't see much about this type of scenarios. The P4V GUI has one of these options, but how do we get this accomplish in command-line?  Thanks.
p4 submit  -d "Update new drop $now" file.txt

A: You need the -f reventunchanged or -f leaveunchanged options.  See here under the options section for various options that are available to you.  The former will automatically revert the unchanged files, the latter will leave them alone.  In both cases changed files will be submitted.

A: There are a few options.

*

*Add either the -f revertunchanged or -f leaveunchanged options on the p4 submit command (p4 help submit).

*Perform a p4 revert -a command before submitting (p4 help revert)

*Change the SubmitOptions on your client (a.k.a your workspace) so that it will always revert unchanged files before submitting (p4 help client).

P4V can be considered a wrapper of the p4 command line, i.e. it performs the exact same commands.
Tips:

*

*If you want to see what you commands P4V is performing, go to your preferences and change the log settings to output more detail.

*Did you notice the way I formatted the help links? If you type that (e.g. p4 help submit) into your command prompt / terminal, it will display the help for that command. If you want to see what other commands are available type p4 help commands.

A: I think 'p4 submit -f revertunchanged -d "my description" file.txt' might be useful to you.


text:
Q: Search rectangle (hard disk) in the image Task: Find the hard disk in the image to determine its angle and contours
Problem: It is not always possible to find the correct contour of the disc.
In the code, I make images gray, blur, find the difference between them and define the contours, but the solution is not exact. I would like your help.
Second question:
Maybe I can detect my disk from this image? Can you help me with algorithm.
Background image:

Source image:

firstFrame = cv2.imread(bg_im)  # background image
frame_img = cv2.imread(frame)   # source image

gray = cv2.cvtColor(frame_img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
firstFrame = cv2.cvtColor(firstFrame, cv2.COLOR_BGR2GRAY)
firstFrame = cv2.GaussianBlur(firstFrame, (21, 21), 0)

frameDelta = cv2.absdiff(firstFrame, gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]

rect = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(rect)

x1 = box[0][0]
x2 = box[1][0]
x4 = box[3][0]

y1 = box[0][1]
y2 = box[1][1]
y4 = box[3][1]

perimeter_1_4 = sqrt((x4 - x1)**2 + (y1 - y4)**2)
perimeter_1_2 = sqrt((x2 - x1)**2 + (y1 - y2)**2)

box = np.int0(box)
corner = list(rect)[2]

if perimeter_1_4 > perimeter_1_2:
    corner = -(90 - corner)

cv2.drawContours(frame_img,[box],0,(0,0,255),2)


text:
Q: Artifacts in ARC GIS aspect raster I am trying to make a set of raster layers of the Earth's magnetic field using point data collected over 21x31km at regular 300m intervals. I have tried 150 different combinations of kriging variables and ended up using Universal with a second order trend removal, default settings for the rest. This gave the most accurate predictions and the smoothest contours.
Problem occurs with the conversion of the intensity a raster (at 10m resolution) to aspect raster to get the magnetic direction. I get these artifacts between the locations of the original data points resulting in a whole series of X's. The magnetic field direction jumps 20 degrees over 5-6 pixels and then drops down 20 degrees for no apparent reason.
Why is it doing this?
Any ideas on a better kriging method for this sort of data?

A: The solution I came to after talking to the GIS ninja's across the road was to generate a coarser raster than I was after and then resample it. Method as follows:
1) Make the first raster with whatever kringing method you wish to use.
2) Output the cell size in some regular interval that does not cause the Artifacts, I would recommend getting 2-3 new data points between each  observed. Make certain that the output cell size is divisible for your final resolution. e.g 300m -> 100m ->  50m  -> 10m
3) In data management use the "raster to point" tool to get a new set of points for next Kriging.
4) If required use the clipping tool to remove any points outside of the orginal raster size.


text:
Q: What emails clients are being used out there? This is not "exactly" a programming question, but it's highly related.  We are writing an app that sends out email invitations for a client (no, it's not spam).  Their designer gave us an HTML and CSS template to use which is fine.  The problem is that it looks like crap in Outlook 2007 because Microsoft decided to use Word (of all things!) as the rendering engine for HTML in Outlook 2007.  I want the client to understand that they should design a "compatible" look and would love to be able to show some kind of statistics about what email clients are being used out there, namely that Outlook 2007 is growing in use.
Has anyone run across any white papers, web sites, studies that even come close to providing a view on this?  I don't expect census level accuracy, but something fairly credible would be good.  Thanks for any help.

A: My understanding of the generally perceived best-practise on this, is is to code for the lowest-common denominator. There are plenty of email clients with enough use in-the-wild that aren't great at rendering "modern" HTML.
Firstly, aim to send your mails as a 2-part multipart mime message. An HTML part AND a plain-text part.
Secondly, try to avoid using CSS or positioned divs where possible. Use table-based layouts and inlined-styles. Preferably specifying as much of the style in HTML where possible.
Try to keep images as inline IMG tags, or as table/row/cell background attributes only.
The email world just isn't anywhere near as up-to-date, and more importantly, far more diverse than the browser world. If you follow these simple rules, your life is going to be much easier than taking a more advanced approach and repeatedly tweaking it in order to get your content to render satisfactorally on enough of the common clients.

A: In absence of general statistics, collect your own.
Check out http://fingerprintapp.com/email-client-stats for a ready-made statistics collection tool, and see http://www.mattbrindley.com/fingerprint-email-client-usage-1/ for a write-up about it. Matt Brindley also offers this gem: "So far only Outlook has proved as popular as we expected, the iPhone was a notable surprise for our own list, with Lotus Notes making an unexpected appearance as well."
Of course, provide both text/html and text/plain mime types so that readers can choose which version to view, and keep your html extremely basic until your statistics indicate that you can get fancier.
If Fingerprint's fee is out of the question, you can collect your own statistics. Include hyperlinks in your HTML. When your CGI application receives requests from these hyperlinks, it can save the HTTP_USER_AGENT in a database for your statistical analysis. This method is not entirely reliable because some readers will stick to plain text, some will never click any of the hyperlinks, and some email clients will not include useful information in the user agent request header, but it may give you enough information to proceed.
Sitepoint, a well-respected source for W3 information, has an article, http://www.sitepoint.com/article/code-html-email-newsletters/, in which Tom Slavin points out:

*

*Use HTML tables to control the design layout and some presentation. You may be used to using pure CSS layouts for your web pages, but that approach just won't hold up in an email environment.

*Use inline CSS to control other presentation elements within your email, such as background colors and fonts.
Slavin also recommends templates from Campaign Monitor and MailChimp to get you started.

A: Raw market share figures will not help you much. When designing HTML email, the only thing that matters is what client your particular target population uses. This depends on geographical area, industry, B2B/B2C -- variations are huge in practice. In some industries (journalism...) you'll even have to reckon with a sizeable population using clients like Lotus Notes, which is notorious for supporting HTML barely more than nominally (shudder).
Outlook 2007 can certainly not be neglected any more, in particular if you send to business addresses, but with Vista on new PCs it's also got a noticeable presence for private accounts.
Return Path indeed have data according to industry.
However, in practice, a good approach is to follow "save" guidelines, in a lowest common denominator style. Outlook 2007 is not the only problematic client -- Gmail is also quite notorious for lacking support for a number of design elements others display just fine. You'll find that a surprising number of web designers do run a sideline with HTML email design (there is demand and it helps pay the rent). If you just start out, Campaign Monitor (an email marketing provider) has a wealth of good resources. You could start with their 2008 Email Design Guidelines. They're also one of those behind the Email Standards Project.
Oh, personally I use Thunderbird with IMAP, Gmail, and RoundCube.
(Disclaimer/full disclosure: I actually work for a competitor, in the loose sense, of Campaing Monitor.)

A: you should look at ReturnPath - they somewhat specialize in that.
Clients you likely need to consider (aside from Outlook):

*

*AOL

*Gmail (Google)

*Yahoo Mail (Yahoo)

*Hotmail/Live/MSN/Outlook (Microsoft)

*Lotus Notes (IBM)

*Thunderbird (Mozilla)

A: I have outlook and gmail, but also a blackberry Curve...
The curve is HORRIBLE at dealing with anything other than plain/text emails. Please have a link near the top to view the email on a website, and consider sending a multipart email that also has a text only section for clients that don't support HTML and such.

A: If you expect to hit many business customers, remember that a very large potion of them will be using MS Office and Exchange Server and therefore also Outlook. If you're more aiming for home users most of them will either be using some webmail or a mail client that uses a regular HTML engine, like Windows Mail, Thunderbird, Opera Mail, Mac OS X Mail.app.

A: I use KMail, you should also look at Thunderbird, Outlook, Evolution, Lotus and Opera Mail.
Also keep in mind many people use webmail such as GMail, Hotmail, Yahoo Mail etc. And some web mail (and mail-clients) work only in plain-text for security reasons.
Personally I think that plain text emails are best, many people prefer not to allow HTML mails due to security reason and thus would just be viewing a badly formatted plain text mail anyway, regardless of what you send, so in my opinion it would be better to just use plain text.

A: Gmail - personal mail
Lotus Notes - forced to use it for corporate mail :(
Lotus Notes sucks at rendering any HTML message correctly (we're running 6.5), and has only partial support for CSS. The best HTML messages for it are simple table-based layouts.

A: At work we have 3 x KMail and 4 x mac OSX' mail.
Further webmail as fail-over (squirrelmail on mail server) in Firefox, Camino, Safari.
We put the words in the mail, the rest in attachments.
Words (pure text messages) can simply be copy/pasted, forwarded etc without formatting problems.
Separate attachments lets user choose to view, download, save etc.
This is the most universal way to use mail.

A: I faced this issue some time back.. most of the clients (including web) block HTML! We just created a web version of the email and added this to the footer of the email "If you are not able to view the message click here (link to web version). It was simply because some people think that its not safe to display images ;-) so a better way to make them open and read beautiful html emails

A: I run M2 (Opera's built-in mail client) and always have it set to "prefer plain text" for mail bodies. I also have "Block external elements"  turned on.

A: Also, I think if you send as both text/plain and text/html, Gmail users (of the webmail UI) have no choice but to view the text/html version.

A: I ran across this report / data that clearly shows Outlook 2007 gaining in popularity and  heading in an upward curve.  Currently this site reports the following top 4 clients (percentage out of 100% of course) but also that Outlook 2007 is on the rise.  Hope this helps.
http://www.campaignmonitor.com/stats/email-clients/#most_popular
27.77%  Outlook 2000, 2003, Express  /
16.23%  Hotmail /
14.14%  Yahoo! Mail /
8.94%  Outlook 2007

A: I'm using gmail


text:
Q: Scrolling back to last position on site My site uses this javascript function to scroll to anchors on the page;
        function scrollToAnchor(aid){
            var aTag = $("a[name='"+ aid +"']");
            $('html,body').animate({scrollTop: aTag.offset().top},'slow');
        }

This does as intended,
        $( window ).ready(function() {
            <?php
                if (isset($_GET['track'])) {
                    echo 'scrollToAnchor("viewTrack");';
                }
            ?>
        });

I integrated a jQuery function in with PHP, not sure if that is okay to do but it seems to work.
My problem. When the page is loading it scrolls to where i need it to, but then it snaps back to the last known scrolling position of the site once everything has loaded. How can i prevent this?


text:
Q: Full Motion Video over Wireless Projection I'm looking for a solution to get graphics from a tablet to a projector wirelessly.  The idea is to have the professor connect to the the solution and then connect to a network share, load their powerpoint/video/content and then output their screen to the projector while being able to walk around the room during class.
We have been using a solution called 'AirProjector' which went out of business several years back.  Major downfall of of the AirProjector was video is very choppy.  The more screen the device had to update the slower and poorer the display was to the point where animation was taboo.
Any suggestions on a solution to the above?  Even if we dont' gain full motion video maintaning the level of service would be nice.  This change is required as we are moving from an open wireless network to requireing WPA2 Personal(we don't have the time to dedicate to getting WPA2 Enterprise up right now) and the device only supports WEP at best.

A: What about using wireless VGA?
http://www.iogear.com/product/GUW2015VKIT/


text:
Q: PHP/SQL error which executing <?php
$dbhost="host";
$dbusername="user";
$dbpassword="pass";
$dbname="db";

try {
  # MySQL with PDO_MYSQL
  $DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
  echo "Connected Successfully";
}
catch(PDOException $e) {
    echo $e->getMessage();
}

#  close the connection
$DBH = null;
?>

When running it in my server, i get the following error:
Parse error: parse error, unexpected '{' in /home/web/i/htdocs/search/pdo.php on line 7

I am trying to do a test to use PDO to save variable to a database and was advised PDO was the way to securely store variable to a database. Please let me know why I am receiving the error and how to resolve it.

A: I've run your code and do not get a parse error. It looks all fine.
Maybe you did not run the same as you posted here.


text:
Q: python - How Popen stdout can return object I have a python script (test.py) and it will call another python script (x.py) to do something and I would like the x.py can return the object "Person" to test.py.
test.py:
cmd= "python /usr/example/x.py"
command= Popen(cmd, shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE)

x.py:
--The following coding is used to assign a name to object "person"
person = people.name("Peter")
printAreeter

Is there any ways that can archive my goals?
Thanks a lot.

A: solution:
1 use json return and read it back to the object
2 is it possible to try import the function or class in x.py and u can run the func as native func or classes
3 if not i suppose u r running on another machine, i strongly recommend paramiko library

A: quote:
this is how to dump to json
class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

this is how to read it back:
class Foo(object):
    def __init__(self,*kwags):
        if kwags == None:
            self.x = 1
            self.y = 2
        else:
            self.x = kwags.get("x")
            self.y = kwags.get("y")
foo = Foo(json.loads("{"x":1, "y":2}"))

from:class serieslization


text:
Q: How do I force python's datetime.strftime to output in UTC? I have two separate machines (local development and server) accessing the same datetime from a database. The datetime objects have the same value (including timezone) on both machines:
Local
print ts
> datetime.datetime(2017, 1, 13, 7, 18, 9, 209000, tzinfo=<UTC>)

Server
print ts
> datetime.datetime(2017, 1, 13, 7, 18, 9, 209000, tzinfo=<UTC>)

However, the output of strftime is different on both machines:
Local
print ts.strftime('%s')
> 1484320689

Server
print ts.strftime('%s')
> 1484291889

What's going on here? How can I get both the client and server to output the same timestamp string in UTC?

A: In case anyone comes across this post, I found the solution.
It turns out that strftime always tries to convert to local time and there isn't much you can do about it.
The solution was to use calendar:
return calendar.timegm(datetime.utcnow().timetuple())

If you need your milliseconds:
return calendar.timegm(self.timestamp.timetuple()) * 1000 + self.timestamp.microsecond / 1000

Or similar for microseconds.


text:
Q: Unit test Angular router event on Activationstart Need some help regarding writing test case for the below mentioned code. The problem is, I am not able to mock ActivationStart. I am using angular 10.
this.router.events
  .pipe(
    filter((event) => event instanceof ActivationStart)
  )
  .subscribe((event) => {
    this.breadCrumb = this.getBreadCrumb(event);
    // other logics here
  });

A: I think you can take advantage of RouterTestingModule
Try this:
@Component({
  selector: 'dummy',
  template: '
Hello
,
  styleUrls: [],
})
class DummyComponent {}
describe('YourComponent', () => {
  let router: Router;

  // waitForAsync is async in older versions of Angular
  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        DummyComponent,
        // your other declarations here
      ],
      imports: [
        RouterTestingModule.withRoutes([
          { path: 'dummy', component: DummyComponent },
        ]),
      ]
    }).compileComponents();

     router = TestBed.inject(Router); // TestBed.inject should be TestBed.get in older versions of Angular
     // wait for the initialNavigation of the router
     // I think this should be enough to trigger that event you require
     router.initialNavigation();
  }));

  it('should trigger the event', async () => {
     // this explicit navigation should trigger the event
     await router.navigate('dummy');
     // assert the breadcrumb
     expect(component.breadCrumb).toBe(...);

  });

});


text:
Q: How can I determine the subject of an rspec controller test? So I don't have a great reason for needing to know this other than curiosity - the BEST reason - but I'm not sure what's going on here.
Background:
I'm working through the RSpec book and updating the examples.
On Chapter 24 - Rails Controllers there's a test for a messages controller.
## spec/controllers/messages_controller_spec.rb ##

require 'spec_helper'

describe MessagesController do
  describe "POST create" do
    let(:message) { mock_model(Message).as_null_object }

    before do
      Message.stub(:new).and_return(message)
    end

  # Then a bunch of Tests...

    context "when the message fails to save" do
      before do
        message.stub(:save).and_return(false)
        post :create
      end

      it "assigns @message" do
        assigns[:message].should eq(message)
      end

      it "renders the new template" do
        response.should render_template("new")
      end
    end
  end
end

This goes along with the messages controller:
## app/controllers/messages_controller.rb ##

class MessagesController < ApplicationController
  def create
    @message = Message.new(params[:message])

    if @message.save
      flash[:notice] = "The message was saved successfully"
      redirect_to action: "index"
    else
      render "new"
    end
  end
end

When I run the tests:
The test passes with response.
it "renders the new template" do
  response.should render_template("new")
end

The test also passes with subject.
it "renders the new template" do
  subject.should render_template("new")
end

The test Also passes with page
it "renders the new template" do
  page.should render_template("new")
end

The test ALSO passes with NOTHING
it "renders the new template" do
 should render_template("new")
end

In case it helps anyone make heads or tails of this, the config/routes.rb just has  resources :messages

Why do all those tests pass? What am I actually testing? Are 'page', 'subject', and ' ' just synonyms for response?
Does it matter as long as my tests pass?

A: By default, the subject would be referencing the class, which is the MessagesController.
Not defining a subject in the last test example, will implicitly set the subject to be MessagesController.

A: From a binding.pry, it appears that subject is an instance of the controller class:
[2] pry(#<RSpec::ExampleGroups::MyController::DescribeString::ContextString>)> subject.is_a? Class
=> false
[3] pry(#<RSpec::ExampleGroups::MyController::DescribeString::ContextString>)> subject.is_a? Users::SessionsController
=> true


text:
Q: Corporate client oauth request returns HTTP 401 code To login to my corporate client Salesforce GUI, I have to use the following link:
https://theCompany.force.com/partner

This link works and logs me in, if I want to log in manually. But when I try to integrate OAuth 2.0 with Salesforce into my application, I, logically, send a request to the following link:
https://theCompany.force.com/partner/services/oauth2/authorize?response_type=code&client_id=<your_client_id>&redirect_uri=<your_redirect_uri>
This generates a valid link, and I am able to log in with it, but along with the response body I receive HTTP code 401. The workflow of my application is strictly set -- all 4xx and 5xx responses are failing. Therefore I cannot proceed with the response from Salesforce. Moreover, a valid auth link and 401 code looks like unexpected behaviour on Salesforce side.
And since I use GuzzleHttp library to process data, it throws ClientException...
Is this a Salesforce bug? Or am I missing something in my implementation? Maybe, I should send an authorization request to some other link?
For instance, https://theCompany.force.com/services/oauth2/authorize?arguments (without /partner) does not work and sends 503 as expected.

A: As I said, I use GuzzleHttp library to process data, and it throws ClientException whenever I try to send a request to get partner login link.
Since I did not get any adequate response from Salesforce support or developer community,I decided to simply catch the exception:
try
{
    return $this->httpClient->get('https://theCompany.force.com/services/oauth2/authorize?' . $arguments)->getEffectiveUrl();
}
catch (GuzzleHttp\Exception\ClientException $e)
{
    return $e->getResponse()->getEffectiveUrl();
}

Once called $e->getResponse()->getEffectiveUrl(), it returns the valid login link.


text:
Q: C: Multiple input from keyboard I'm trying to read multiple input from keyboard and store the input in variables.
A snipet of my code:
char answer = 'N';
int artnr;
char artname [27];
int stock;
double price;

while (answer != 'Y') {
printf("%s\n", "Enter article number:");
scanf("%d" , &artnr);
printf("%s\n", "Enter article name:");
scanf("%c" , &artname);
printf("%s\n", "Enter stock balance:");
scanf("%d" , &stock);
printf("%s\n", "Enter a price");
scanf("%f" , &price);
printf("%s\n", "Do you want to quit? (Y/N)");
scanf("%c" , &answer);
}

Output:
Enter article number:
1
Enter article name:
Enter stock balance:
25
Enter a price
4
Do you want to quit? (Y/N)
Enter article number:
Something seems to go wrong with my scanning. I guess it has to with the '/o' in the article name or when I press enter in order to confirm my input.

A: artname is a char array and "Enter article name:" suggests you actually wanted to scan a string.
So, this
scanf("%c" , &artname);

probably should be
scanf("%s", artname);

scanf() leaves the trailing newline when you scan with %c in the input buffer. You can ignore it by adding a whitespace in the format string:
scanf("%c" , &answer);

to
scanf(" %c" , &answer); // Notice the space in " %c"

A whitepsace in the format string tells scanf() to ignore any number of whitespaces in the input.
and change this
scanf("%f" , &price);

to
scanf("%lf" , &price);

in order to match the format string with the type.


text:
Q: Spark 2.4.6 + JDBC Reader: When predicate pushdown set to false, is data read in parallel by spark from the engine? I am trying to extract data from a big table in SAP HANA, which is around 1.5tb in size, and the best way is to run in parallel across nodes and threads. Spark JDBC is the perfect candidate for the task, but in order to actually extract in parallel it requires partition column, lower/upper bound and number of partitions option to be set. To make the operation of the extraction easier, I considered adding an added partition column which would be the row_number() function and use MIN(), MAX() as lower/upper bounds respectively. And then the operations team just would be required to provide the number of partitions to have.
The problem is that HANA runs out of memory and it is very likely that row_number() is too costly on the engine. I can only imagine that over 100 threads run the same query during every fetch to apply the where filters and retrieve the corresponding chunk.
So my question is, if I disable the predicate pushdown option, how does spark behave? is it only read by one executor and then the filters are applied on spark side? Or does it do some magic to split the fetching part from the DB?
What could you suggest for extracting such a big table using the available JDBC reader?
Thanks in advance.

A: Before executing your primary query from Spark, run pre-ingestion query to fetch the size of the Dataset being loaded, i.e. as you have mentioned Min(), Max() etc.
Expecting that the data is uniformly distributed between Min and Max keys, you can partition across executors in Spark by providing Min/Max/Number of Executors.
You don't need(want) to change your primary datasource by adding additional columns to support data ingestion in this case.


text:
Q: xsl How do I total the sum of one particular type of element based on an attribute from a different element Given the following xml:
<orders>
    <order>
        <productName quantity="10">Blender</productName>
        <total price="20">200</total>
    </order>
    <order>
        <productName quantity="2">Computer</productName>
        <total price="1000">2000</total>
    </order>
    <order>
        <productName quantity="3">Scanner</productName>
        <total price="800">2400</total>
    </order>
</orders>

I would like to calculate the sum of all orders where quantity is greater than 2.  After hours and hours of trying, I finally give up. This is one of the solutions I have come up with (which is of course not working, returns 0):
xsl:value-of select="sum(order/productName[@quantity>2]/total)"
Please help!

A: Use sum(order[productName[@quantity>2]]/total).


text:
Q: Plots won't show up in qtconsole I have read tons of questions on this, but I am still baffled. I'm running Anaconda in Scientific Linux. I launche a console a type ipython qtconsole.
My script.py is something like
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5,6,7,8,9,10])
plt.show()

I type run script.py from the qtconsole, and the program just sits and does nothing. What am I doing wrong? I have been using the qtconsole for running my scripts, maybe it's better for really being interactive with and I should be running my scripts some other way?
Any general advice on workflow would be very helpful here. When should I use python script.py, when should I use ipython script.py, and when should I use the qtconsole, etc...?

A: This seems like a Magic Function problem
More specifically %matplotlib. %matplotlib inline will show it within the browser, or you can replace inline with whatever you feel better for your use.