text:
Q: Reading/writing files line-by-line reporting position I wish to read and write some files line-by-line.
My first thoughts were to use BufferedReader and BufferedWriter but my gotcha is that I need to know how far through the files I am.
When reading I would like to who how far through processing the file I am and I would like it to be accurate, so after every readLine() I am expecting the position to update, this is complicated by the fact that there is a buffer involved.
Same applies to writing, I need to get the position accurately before and after writing a line. I'm guessing this isn't as difficult as my understanding is that a BufferedWriter flushes after every newline char anyways, so given that I am writing lines, I could just write straight to the channel.
Before I reinvent the wheel here, or use some dodgy reflection, is there anything in the JDK that can help me out here?
EDIT: Just to clear things up, I am looking for byte positions.

A: It wasn't entirely clear based on your question what you mean by "how far through processing the file I am". Does that mean line number or byte position?
If it means line number, there are really two options:
A) Keep a track of the line numbers manually. Shouldn't be that hard. Just increment a counter for every line.
B) Use java.io.LineNumberReader as suggested by @Jesper
If it means byte position, increment the byte position counter by each line length and don't forget to include the newlines in the byte position as well.
When writing, there is no LineNumberWriter so you need to keep track of the counters manually. Shouldn't be hard.

A: see below example for reading file using RandomAccessFile
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Timer;
import java.util.TimerTask;

public class ConsoleReader {

   /**
    * @param args
    */
    public static void main(String[] args) {
    File file = new File("fileName");
       try {
           RandomAccessFile r = new RandomAccessFile(file, "r");
           //First time read
           String str = null;
           while((str = r.readLine()) != null) {
            System.out.println(str);
           }
           r.seek(r.getFilePointer());
           startTimer(r);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }

    private static void startTimer(final RandomAccessFile r) {
     Timer timer = new Timer();
     timer.scheduleAtFixedRate(new TimerTask() {
     @Override
     public void run() {
     String str = null;
     try {
          while((str = r.readLine()) != null) {
           System.out.println(str);
          }
          r.seek(r.getFilePointer());
     } catch (IOException e) {
         e.printStackTrace();
     }
      }
 }, 0, 1000);
    }
}


text:
Q: Type I Vacuum fluctuations Type one Parapositronium borrow energy from the vacuum to pop into existence, returning it after annihilation. Halfway through reading this eye opening paper about Vacuum fluctuations this one (probably silly) question arrised: Does Parapositronium only exist under complete vacuum circumstances or does it, for example, also form in the atmosphere?[answered] And if so: Does all space possess a ground state energy such as the one observed in complete Vacuum?
EDIT: After finding papers (1, 2) answering my first question, I have a followup: Where from do the Positronium borrow their energy while on a medium?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to connect a database which is on a VMware virtual machine with ASP ? I want to connect a sql database which is on a Vmware virtual machine.
And I have a class which includes this code rows :
 public SqlConnection baglan()
{
    SqlConnection baglanti = new SqlConnection("Data Source=192.168.13.128; Initial Catalog=DbFilm; Integrated Security=true;");
    baglanti.Open();
    return (baglanti);
}

and I cannot connect to this database i think i need to tell the machine the password and username too right ?

A: You are using Integrated Security=true in your connection string, so application is using your windows login to authenticate to database.
You have to configure the database to accept such authentication or use some sql server login and password in connection string.
Here you have a link describing all options in connection string
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.110%29.aspx


text:
Q: Does connecting your laptop to TV via HDMI decrease gaming performance? I have a laptop I use to game, its not a high-end one. My resolution is 1366x768, I'm thinking of getting a HDMI cable to try out gaming on the TV.
My card is an ATI Mobility Radeon 5470 HD, and it supports eyefinity, when I use dual monitors to game it reduces the framerate by 3-5 FPS. Since my TV is a 46-Inch 1080p 120Hz LED HDTV, I'm wondering if it would take a major hit on my laptop?

A: Outputting your display to a TV does not inherently decrease gaming performance. If your laptop screen supports a maximum resolution of 1366 x 768 and you try playing anything at 1080p (1920 x 1080) you're naturally going to experience a degradation in refresh rate (regardless of whether it's a TV or a regular monitor) as compared to your usual 1366x768 display.
That said, I'll try to answer your question because it's not very clear. If you are using the TV as the only display your laptop is showing at the native resolution of 1366 x 768, it should be updating at the same rate as if it were on the screen of the laptop. If you're duplicating screens or extending display across your screen and TV, you will of course experience a bit of decrease of performance. Any time your computer has to draw more pixels every refresh, you will of course be using more GPU power to draw it all.

A: In your situation I would connect the TV to the lappy and use just the TV as a screen; here's why:

*

*The 100Hz refresh rate combined with the LED is going to make the
refresh rate the same (or comparable) as the lappy.

*The resolution is higher.

*And you don't say the size of the laptop screen, but I assume it's
less than 46 inches. So it'll be probably double or triple the
screen size.

It's going to look bigger and higher res on the TV and the refresh rate shouldn't be noticeable to human eyes.
I have a similar set up: 27" FHD screen with 14" lappy. I recommend external keyboard and gaming grade mouse (preferably wireless).

A: I have a laptop with dual display, Intel 4000 and Nvidia 620M...On Nvidia I have selected to use 620 GPU for 3D, also the HDMI seems to use Intel 4000 for HDMI OUTPUT... The boost in 3D performance was noticeable after manual selection of Nvidia GPU in Nvidia Control Panel... (was AUTO). I have played Tomb Raider 3 with all settings at Maximum, but without one setting (some like P.....something). FSAA, Anti-Al 8X, and so on.
My TV is 3D LG 46", Full HD.
Laptop is Fujitsu LH532/G22, i3, 8Gb ram, 5400rpm hdd 500Gb.


text:
Q: Bootchart and how to optimize boot time I have spent some time researching how to decrease my boot time. I made several changes to my grub boot parameters.  However I could really use some help to understanding what else I could do. I spent some time looking at other treads on this site about this topic and make some tweaks they suggested but it made it worse. HERE is the direct link for my bootchart.

A: Fifteen seconds?  15secs?  That is really impressive!
And you actually want to optimise that??? :-O
I would say: take a system back-up now (You're definitely user type 4!) and don't touch anything!!!  (except maybe remove bootchart as that takes time as well)
Your boot is faster then 99.75% of all users on this site and faster then 99.999% of all user on this planet!
Congratulations!


text:
Q: How to make a div move on the HTML page and not go to the next level I have a created divs on a row and now when I zoom them, the following divs move down the page. I don't want them to move to next level, instead I want the HTML width should increase and they should stay at the same level. I have found a jsfiddle for something that I have created for my practice stuff. If you click on the image, they get zoomed and after some zooms, the right hand side image moves down the next level. For me, this should not happen. How to do this?
The link to jsFiddle is: http://jsfiddle.net/bq6Ju/14/
The below code is written by one of the stack overflow scholar, and this is something what I have a similar in my test application
              .flower {
display: block;
float: left;
margin: 10px;
width: 100px;
height: 100px;
overflow: hidden;
border: 1px solid red;
}

.flower img {
width: 100%;
height: 100%;
}
.flower div {
width: 200px;
height: 200px;
position: relative;
}

.chunk2 div {
left: -100px;
}
.chunk3 div {
top: -100px;
}
.chunk4 div {
top: -100px;
left: -100px;
}

The HTML code is

Javascript/Jquery code is
$('div.flower').click(function(){

var resize = 1.30;

var $this = $(this);
var $inner = $this.find('div');

$this.animate({
    'width': $this.width() * resize,
    'height': $this.width() * resize,
});

var p = {
    top: parseInt($inner.css('top')),
    left: parseInt($inner.css('left'))
}
console.log(p);
$inner.animate({
    'width': $inner.width() * resize,
    'height': $inner.width() * resize,
    'top': p.top*resize,
    'left': p.left*resize,
});

});

A: You could add a container around the images and prevent wrapping and add scrollbars by the overflow proprty:
.container { overflow: auto; white-space: nowrap; }

Not that in order to get this working I've removed the float, because that prevents you AFAIK from doing what you want. And I have changed the display property to inline-block. I've also added the vertical-align property to make sure the images are always top aligned.
.flower {
    display: inline-block;
    margin: 10px;
    width: 100px;
    height: 100px;
    overflow: hidden;
    border: 1px solid red;
    vertical-align: top;
}

You can see the demo here: http://jsfiddle.net/bq6Ju/18/

A: Adding a floated container with nowrap works too.
http://jsfiddle.net/bq6Ju/19/
.container {
    float: left;
    white-space: nowrap;
}

A: Demo: http://jsfiddle.net/bq6Ju/26/
HTML:

CSS:
.row {
  overflow-x: scroll;
}

.row_wrapper {
  width: 500px; /* initial width */
}

/* other your css */

JavaScript
// in click handler

var total_width = 0;
var cur_outer = $(this).outerWidth(true) - $(this).width();
var cur_inner = resize * $(this).width();
var total_width = cur_outer + cur_inner;

$(this).parent().children('.flower').not(this).each(function () {
  total_width += $(this).outerWidth(true);
});

$(this).parent().width(total_width + 10);


text:
Q: How to copy file/folder beginning with dot from Mac to PC without hidden attribute? I have Mac (OSX Lion) and PC (Windows 7) with a shared folder. To mount Windows shared folder I use "Connect to Server" in Finder. All files and folders are copied ok except for the files that begin with dot (e.g .htaccess). In Windows these files are created with hidden attribute.
How to copy file/folder beginning with dot without hidden attribute?

A: Let's assume for this example that your ".htaccess" file is located in the root directory of your mounted Windows share. Let's also say the Windows volume is called "WindowsShare". Finally, let's say you want to copy this file to your Desktop.
Open Terminal. Type in cd /Volumes/WindowsShare. Then type in cp .htaccess ~/Desktop. You can modify this as needed based on your file locations and file names.

A: So here is the answer:

*

*Navigate to /etc/

*Use any text editor to open smb.conf for editing. You will have to use administrator credentials e.g.,
sudo vi smb.conf

*Under the [global] section of this file, add the following
hide dot files = no

*Save the file. Your problem should be solved from there.


text:
Q: Advice for running an MQTT server I want to run Mosquitto MQTT broker on my server.
And I want to have for example 10 million users/clients connected.
I want to know a few things first:

*

*Can Mosquitto handle 10 million alive connections?

*If I want to have i.e. 8 Topics and categories for each client, can the broker handle 80 million topics?!

*If 100 thousand clients publish a message at the same time, what happens? can the broker handle it?

*If the answer to all above is yes, then what hardware specifications is needed for that to run without problem under Windows Server 2008 R2?(CPU,RAM,HDD,...)

*Is there any better broker than Mosquitto?(in performance, supporting user/pass, supporting ssl/tls)

*If it's not possible at all, then how are big companies/apps like Whatsapp/Viber/Wechat/others handling push notifications for their apps?

A: *

*Not at the moment, and on Windows it is currently limited to 1000 clients.

*Probably, but it will most likely depend on the arrangement of these topics.

*"Can the broker handle it?" - it depends what you mean by handle it. There will definitely be a good chunk of latency added.

*As above, Windows currently only supports 1000 clients.

*There are plenty of vendors who will sell you a solution.

*I imagine that the lightweight protocols are mostly restricted to the edge of their network, with other messaging used internally, and lots of servers.


text:
Q: Text copy or cut fails with error 0x80004005 in VIsual Studio 2017 Type library exporter encountered an error while processing 'CopyAsHtml.CopyAsHtmlPackage, CopyAsHtml'. Error: Type library exporter encountered an error while processing 'Microsoft.VisualStudio.Shell.Interop.SVsSolutionObject, Microsoft.VisualStudio.Shell.Interop'. Error: Type 'SVsSolutionObject' and type 'SVsSolution' both have the same UUID.
After that first error dialog, every use of cut or copy produces the E_FAIL, Unspecified Error dialog.

A: Go to Tools -> Manage Extensions -> Installed (left top corner) -> Search for CopyAsHtml and disable that extension. This worked for me :)


text:
Q: Using jQuery to manipulate a composed HTML page? I am working on a data scraping application.  The pages I want to scrape have already been collected by server-to-server requests, and are currently stored in my database.  I use an axios request to retrieve them from my database, and I now want to traverse/manipulate the pages using my VueJS application.
Here's what I have so far...
import $ from 'jquery'
...
...
axios.get('/mydomain/fetch_page/1')
    .then(function (response) {
        console.log(response.data.body); // log point #1
        let $page = $(response.data.body);
        // let $heading = $page('h2');
        console.log($page); // log point #2
    })

At log point #1 the page looks fine.  It includes the entire page: DOCTYPE, html, head, body, etc
At log point #2, it is an object where each property represents a DOM node, including text nodes.
If I un-comment the line that queries the $page for a $heading, I get an error telling me that $page is not a function.  What am I doing wrong?

A: $page is a jQuery object, not a function. Just as when you're writing web applications using jQuery, you call methods on it, you don't call it as a function.
To get the h2 elements, use the .find() method:
let $heading = $page.find("h2");


text:
Q: How to identify QEvent sender I have reimplemented QWidget::event() handler, where I am handling windowStateChange event. I was wondering if there is any way to identify which widget sends this event.

A: No, there's no way to do that, because posting or sending a QEvent does not require a QObject instance. When you post an event, it's done via a static QCoreApplication method, and it doesn't ask who's sending the event. Heck, it'd be counterproductive, because a useful way of interoperation between Qt and other event-driven code is to do event translation and post the events to the Qt side of things. The posting code may be an extern "C" function.

A: That event is generated when a window is minimized, maximized or full-screened so you should only see it from within the widget to which it applies.


text:
Q: How to convert from C# ref type to CLI\C++ ^% type I am writing an application in Managed C++ (CLI\C++). In which I am using a library (.dll file) which is written in C#.
In a file I am encountering a problem.
I am implementing functions of an interface which is written in the library.
The declaration of a function in the library is as given below:
COMWORKSPACELib.IWorkspaceEvents.WorkspaceMessage(int, string, COMWORKSPACELib.EnumNotificationCode, COMWORKSPACELib.EnumNotificationType, string, ref COMWORKSPACELib.EnumNotificationReply);

When I write the same code in CLI\C++ the declaration is like:
WorkspaceMessage(int workspaceToken, String ^description, EnumNotificationCode ^code, EnumNotificationType ^type, String ^source, EnumNotificationReply ^%action);

Here, the compiler is giving me error that the "class must provide an implementation for the interface method". Because the parameters passed in both function declarations are syntactically different.
Is there any alternative way to match the library declaration?
If I remove the "^' & '%' to match the library declaration then it gives further errors in the code.

A: Are EnumNotifcationCode, EnumNotificationType, and EnumNotficationReply all enums?  That is, are they value types?  If so, then it should be declared as follows:
WorkspaceMessage(int workspaceToken,
                 String^ description,
                 EnumNotificationCode code,
                 EnumNotificationType type,
                 String^ source,
                 EnumNotificationReply% action);


text:
Q: Datagrid Command Binding to buttom, don't select row I have a command bound to a button on my datagrid (e.g. button shows for everyrow).
Basically the command is wired to an object which shows children of that row in a pop up window.
Problem is the customers wants it to display the chid data but not actually select that row in the datagrid.

A: you have some options:

*

*you can use a style

*you can the UnSelectAll() method
and if you google you will find some more
EDIT:
did you try to handle the PrevievMouseDown Event? you can set e.Handled=true if the user click on the button.


text:
Q: How can I use sql to select records of students who have grade value less than or equal to 6 in both mathematics and Engish Language I have 3 tables and their columns as follows.
Table: Studenttable (StudentID)
Table: Subjecttable (SubjectID)
Table: SubjectName  (Gradetable,gradevalue).

I want to use sql to select only records of students who have got gradevalue <= 6 in both Mathematics and English Language.
But whenever i run the query, I have some students with  gradevalue <= 6 in either Mathematics or English Language as part of my record.
This is the look of the table relationshi.Relationship
This is the sample output which has some records with candidates with either Mathematics or English. (Which I want to exclude from the recordset) OutputSample
This is the sql I used
SELECT tblCandidates.CandidateID, tblCandidates.CandidateName, tblSubject.Subject, tblGrade.GradeValue
FROM tblSubject INNER JOIN (tblGrade INNER JOIN (tblCandidates INNER JOIN tblStudentGradeDetails ON (tblCandidates.CandidateID = tblStudentGradeDetails.CandidateIDFK) AND (tblCandidates.YearIDFK = tblStudentGradeDetails.YearIDFK) AND (tblCandidates.SchoolCodeIDFK = tblStudentGradeDetails.SchoolCodeIDFK)) ON tblGrade.GradeID = tblStudentGradeDetails.Grade) ON tblSubject.SubjectID = tblStudentGradeDetails.Subject
WHERE (((tblSubject.Subject) In ("Mathematics (Core)","English Language")) AND ((tblGrade.GradeValue)<=6));

A: You should really change tblStudentGradeDetails to have the SubjectId and GradeId from its' corresponding tables instead of the Subject(name) and Grade(name).
SELECT
    c.CandidateID
,   c.CandidateName
,   s.Subject
,   tblGrade.GradeValue
FROM tblCandidates c
JOIN tblStudentGradeDetails sg
    ON sg.SchoolCodeIDFK = c.SchoolCodeIDFK
JOIN tblSubject s
    ON s.Subject = sg.Subject
JOIN tblGrade g
    ON g.Grade = sg.Grade
WHERE   s.Subject IN ('Mathematics (Core)', 'English Language')
    AND g.gradeValue >= 6


text:
Q: Android Uncaught Exception when creating a SimpleDateFormat object I am getting an uncaught exception when trying to call
SimpleDateFormat constructor:
String test = "Thu Feb 02 00:00:00 EST 2017";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss Z yyyy");

The stack trace is:

02-15 15:55:31.999 27669-27669/com.clackityclack.parseproject
  W/dalvikvm: threadid=1: thread exiting with uncaught exception
  (group=0x40e76300) 02-15 15:55:32.077
  27669-27669/com.clackityclack.parseproject E/AndroidRuntime: FATAL
  EXCEPTION: main
                                                                                java.lang.IllegalStateException: Could not execute method for
  android:onClick
                                                                                at
  android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                                at android.view.View.performClick(View.java:4084)
                                                                                at android.view.View$PerformClick.run(View.java:16966)
                                                                                at android.os.Handler.handleCallback(Handler.java:615)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at
  android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:4084)
                                                                                at android.view.View$PerformClick.run(View.java:16966)
                                                                                at android.os.Handler.handleCallback(Handler.java:615)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.NoClassDefFoundError:
  android.icu.text.SimpleDateFormat
                                                                                at
  com.clackityclack.parseproject.childAddActivity.done(childAddActivity.java:69)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at
  android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:4084)
                                                                                at android.view.View$PerformClick.run(View.java:16966)
                                                                                at android.os.Handler.handleCallback(Handler.java:615)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                                                at dalvik.system.NativeStart.main(Native Method)

The imports are:

import android.app.DatePickerDialog; import
  android.app.DialogFragment; import android.content.Context; import
  android.content.Intent; import android.icu.text.SimpleDateFormat;
  import android.os.Build; import
  android.support.annotation.RequiresApi; import
  android.support.v4.app.Fragment; import
  android.support.v4.app.FragmentActivity; import
  android.support.v4.app.FragmentManager; import
  android.support.v7.app.AppCompatActivity; import android.os.Bundle;
  import android.util.Log; import android.view.KeyEvent; import
  android.view.View; import android.view.inputmethod.InputMethodManager;
  import android.widget.DatePicker; import android.widget.EditText;
  import android.widget.TextView; import android.widget.Toast;
import com.parse.ParseException; import com.parse.ParseObject; import
  com.parse.SaveCallback;
import java.io.IOException; import java.sql.SQLException; import
  java.util.Date;
  */
import android.app.DatePickerDialog; import
  android.app.DialogFragment; import android.content.Context; import
  android.content.Intent; import android.icu.text.SimpleDateFormat;
  import android.os.Build; import
  android.support.annotation.RequiresApi; import
  android.support.v4.app.Fragment; import
  android.support.v4.app.FragmentActivity; import
  android.support.v4.app.FragmentManager; import
  android.support.v7.app.AppCompatActivity; import android.os.Bundle;
  import android.util.Log; import android.view.KeyEvent; import
  android.view.View; import android.view.inputmethod.InputMethodManager;
  import android.widget.DatePicker; import android.widget.EditText;
  import android.widget.TextView; import android.widget.Toast;
import com.parse.ParseException; import com.parse.ParseObject; import
  com.parse.SaveCallback;
import java.io.IOException; import java.sql.SQLException; import
  java.util.Date;

A: Remove this import import android.icu.text.SimpleDateFormat;
And use import java.text.SimpleDateFormat; instead.


text:
Q: Best way to communicate with Python script from command line? I apologize if this is a duplicate but my search terms didn't find me what I was looking for.
I only ever 'kill' my python script using its linux process id.
This has served me well but now I need to pickle certain things right before terminating.
What is the best practice for communicating with a running Python script from the linux command line? Is there a library I should know about?
Example action would be sending a terminate command to the running script, but also can see uses in the near future for modifying config variables etc.

A: One way would be to install signal handlers: https://docs.python.org/3/library/signal.html, for example, for SIGHUP (the hang up signal)

A: kill command in linux/unix sends signal to the process and process handles signal (except SIGSTP and SIGKILL). So by saying killing process you are just sending SIGKILL signal.
So for better terminating the script you should use other signal (for example SIGINT this acts like pressing CTRL+C in terminal) and handling this signal by assigning signal handler in your script. For more info about signal handlers use this link.
By assigning signal handlers you can ignore signal or use your own custom action like: clean up process and exit or something else.

A: There is no single best way. Depending on your requirements, you might choose between

*

*Signals. A single signal can communicate a few bits of information (with one signal, one bit; with two signals, two bits, because you can choose which one yon send, etc) and it's one-way; but it's reasonably real-time and asynchronous, so excellent for quick and easy one-way communications, perhaps as out-of-band information in addition to, or on top of, something more complex.

*Shared memory is quick and efficient two-way communications but nontrivial to use in practice, and obviously constrained to processes running on the same host.

*Sockets are very versatile and reasonably efficient for communication over a network, and reasonable for moderate amounts of data even on the same host.

This is pretty U*x-centric; Windows programmers tend to use threading and thus shared memory IPC a lot more.


text:
Q: How Can eval() in This Code Be Not Secure? I'm using the code below to automatically load and declare classes so that I only need to put class files in a folder named classes. The part in spl_autoload_regsister() may seem to be unnecessary for you but it is needed to work as a WordPress plugin without errors.
It uses eval() and I've seen so many web pages talking about using eval() is bad and can create a security hole. So how could this be dangerous?
$strDirPath = dirname(__FILE__) . '\\classes\\';
$arrClassFiles = array_map(create_function( '$a', 'return basename($a, ".php");' ), glob($strDirPath . '*.php'));
spl_autoload_register(
    create_function('$class_name', '
        global $arrClassFiles, $strDirPath;
        if (in_array($class_name, $arrClassFiles))
            include($strDirPath . $class_name . ".php");' )
);

foreach ($arrClassFiles as $strClassName) {
    $strClassName_alpha = $strClassName . "_Alpha";
    eval("class $strClassName_alpha extends $strClassName {};");
}

print_r(get_declared_classes());

Maybe, somebody can put a file name of php code in the folder? But I don't see it can compromise the system.

A: If they can name a class file something like randomclass {}; echo $db_password;//.php, then you could have a code execution attack.
I'm pretty sure that's not a valid file name, but there are people far wilier than me at crafting valid malicious inputs.
It's just usually not an attack surface you need to open yourself up to, given that it's practically always possible to avoid with better code structure.

A: If an error condition is handled, I don't see a problem here.
Just be sure that if someone tries to call a different class that does exist (i.e. code that would be valid here, but that you wouldn't want your hacker to run directly because it would bypass a restriction on your system), that it won't be a security problem - or that it wouldn't be possible to run that class at all from this context.
Just in case, deny any attempts to run code with the words "class," or other keywords, or any built in class names, or built in function names, other builtins, etc. and you should be fine, but even that probably isn't necessary in your particular case here because would probably result in an error.


text:
Q: Passing variable using localStorage to loaded page from iframe I have two pages. The parent page has an iframe that loads a page where I need to pass a variable to set the number of results in an array from xml. Below is the code for both pages. I am trying to use localStorage to pass the var to define the number of articles returned in the parse.
code on main page

Code on second page

A: Here is the error I found in your code-
var x=xmlDoc.getElementsByTagName("item");

In this line, you are trying to get an <item> tag in HTML page, whereas there is no
such valid element uptil now (HTML5). Try to replace this with something else that fits your needs.
Thank you!


text:
Q: Customize jQuery Validation's errorPlacement only for some fields I'd like to customize the errorPlacement only for certain fields, and defer to the plugin's default placement for the rest.  Something like:
errorPlacement : function(error, element) {
    if($(element).prop("id") === "mySpecialField") {
        $("#mySpecialErrorMessageHolder").append(error);
    }
    else {
        // this is not valid syntax but it's what I really want...
        super.errorPlacement(error, element);
    }
}

Is this possible?

A: Use error.insertAfter(element);, which is the default:
errorPlacement : function(error, element) {
    if($(element).prop("id") === "mySpecialField") {
        $("#mySpecialErrorMessageHolder").append(error);
    }
    else {
        error.insertAfter(element);
    }
}

A: errorPlacement : function(error, element) {
    if($(element).prop("id") === "mySpecialField") {
        $("#mySpecialErrorMessageHolder").append(error);
    }
    else {
        error.insertAfter(element); // default error placement.
    }
}

Looking at the source, the default behavior is to use insertAfter.


text:
Q: Where is the serialized user session stored with Memcache as a session handler? And how to read/write into the serialized data? i am trying to communicate with Memcache as a session handler for Joomla. Following the PHP docs bottom example i have registered memcache a session handler. As soon as a user loads the Joomla site its session id together with other user data is stored into the Joomla database. But now i don't know how to get hands on Memcache to read the serialized session data like can be done with XCache using xcache_get($sessionid) As soon as i create a new Memcache instance as can be seen in the docs top example the session entry is removed from the database. But the session yet exists. This is quite confusing to me. I required to access (read/write) the serialized user session. How can i fetch/set it from the PHP session handler?

A: I believe the equivalent you are looking for is something like this:
Getting the session:
$session = $memcache->get($sessionId);

Setting the session:
$memcache->set(
    'sessionprefix:'.$sessionId,    // the session id.
    $session,           // the actual session itself
    false,              // set to true to use compression
    $expire,            // expiration in second
);

I have not used memcache very much but I have read that people usually use a prefix in the key to separate the different types of objects (this is also a common practice with redis, a similar data store). I have used 'sessionprefix:' here but I am sure Joomla has their own specific prefix.


text:
Q: Matlab parsing at run-time of function handles My Question: Given a function handle, does matlab parse the string each time it needs to evaluate it, or just once and then it caches it?
Example
Consider the ingenious function
function [] = foo(func)
for j=1:1e4
    func(j);
end

and the script
func1 = @(x) 5*abs(x)^2
function foo(func1);

At run-time, Matlab needs to interpret @(x) 5*abs(x)^2 as a function. In this example, does it do it once, or a thousand times?

A: First of all @(x)cos(x) is not a string, it is an anonymous function declaration. When you create an anonymous function, MATLAB essentially creates a function object which contains all of the information it needs to run. This anonymous function can then be passed around to various functions or even saved to a file. As such, it is only constructed once and evaluated many times.
When evaluated, MATLAB does not do any caching, so calling the same anonymous function with the same inputs many times causes the contents of the anonymous function to be evaluated each time.
If you want to get more information about your anonymous function, including the local workspace of the function, you can use the functions function
f = @(x)cos(x);

functions(f)

%            function: '@(x)cos(x)'
%                type: 'anonymous'
%                file: ''
%           workspace: {[1x1 struct]}
%    within_file_path: '__base_function'

That being said, in your example, it could really be reduced to a function handle rather than an anonymous function since you pass all input arguments directly to cos without modifying them. As you can see, this has a different internal representation and from some preliminary benchmarks, it seems to be marginally faster.
f = @cos

functions(f)

%    function: 'cos'
%        type: 'simple'
%        file: ''

And a quick benchmark
function benchit
    fprintf('Anonymous function: %0.4f\n', timeit(@option1));
    fprintf('Function handle:    %0.4f\n', timeit(@option2));
end

function option2()
    f = @(x)cos(x);
    for k = 1:10000
        f(k);
    end
end

function option1()
    f = @cos;
    for k = 1:10000
        f(k);
    end
end

And the results (not really a huge difference)
Anonymous function: 0.0056
Function handle:    0.0049

A few more things

*

*When creating the anonymous function, the anonymous function declaration must still adhere to all of MATLAB's standard syntax rules otherwise it won't be created. For example, the following would throw an error during anonymous function creation since it is invalid syntax
func = @(x)thing]

Error: Unbalanced or unexpected parenthesis or bracket.

*When you evaluate an anonymous function (after it's successful creation), it's just like evaluating any other function in that the anonymous function can throw an error and the error depends upon the input.
func = @(x) x + [1 2];

func([3 4])
%   4   6

% Now we're going to pass an array that isn't 1 x 2
func([5 6 7])

Matrix dimensions must agree.
  Error in @(x)x+[1,2]


text:
Q: Conflict in the Key Values in Nested Tikz Enviroments I am developing some Tikz commands with pgfkeys, and I want to use the commands that I developed earlier in my new commands. This creates nested Tikz and Tikz math enviroments as shown in the MWE given below.
Without changing the variable names, how can I pass the correct value of \a in the second call to the \testing, which is 3, not 4? I think in the MWE, the name \b is passed to the command, not 3.
The reason I am asking this question is I do not want to know the key variables used in the command \testing for a better coding.
\documentclass[]{standalone}
\usepackage{tikz}
\usetikzlibrary{math}

\pgfkeys{
 /testing/.is family,
 /testing,
  b/.store in =\b,
  a/.store in =\a}

\newcommand{\testing}[1][]{\pgfkeys{/testing, #1}
\tikzmath{
real \a, \b;
print ($Out:$);
print ($a = \a,$);
print ($b = \b |$);
}}

\begin{document}
\begin{tikzpicture}
\tikzmath{\b = 3;}
\path(0,-0.5) -- (6,0.5);
\testing[a = 1, b = 2]     %Result: a = 1, b = 2
\testing[a = \b, b = 4]    %Result: a = 4, b = 4. Should be: a = 3, b = 4.
\end{tikzpicture}
\end{document}


text: Q: как натянуть слайдер bootstrap на opencart Первый раз натягиваю верстку магазина, на opencart. Подскажите как натянуть свой слайдер, что бы можно было менять и добавлять картинки с админки, т.е в вкладке "баннеры". В carousel.twig, поставить свой код?


text:
Q: SQL search query in relations tables I am trying to make an sql search query to return only ORDERS that match my search keyword. The issue is that i also need to search in every comments body for each order and if a result is found in that comment the order for that comment should be selected.  The tables looks like this in a simplified way:
ORDERS:

ID = 95
title = first order

COMMENT RELATIONS:
id = 1241
comment_id = 500
target_id = 95
type = order

COMMENTS:
id = 500
body = this is the first comment

So if i searched for "first comment" the order with id 95 should be selected.
My current attempt seems to select more then order but also their comments and relations? This is how my current attempt looks like.
$query = 'SELECT DISTINCT *
FROM orders as o
LEFT JOIN comment_relations as cr ON o.id = target_id
LEFT JOIN comments as c ON cr.comment_id = c.id
WHERE o.id LIKE :keyword OR o.title LIKE :keyword OR c.body LIKE :keyword';

A: Not sure which database you are using but in most databases you can use the table alias follow by * for selecting only one table.
'SELECT DISTINCT o.*
FROM orders as o
LEFT OUTER JOIN comment_relations as cr ON o.id = target_id
LEFT OUTER JOIN comments as c ON cr.comment_id = c.id
WHERE o.id LIKE :keyword OR o.title LIKE :keyword OR c.body LIKE :keyword';

A: As per your concept i create 3 demo tables in phpmyadmin which description is here.
1.orders have columns (id,title).
2.comment_relations have columns (id,comment_id,target_id,type).
3.comments have columns (id,body).
This is SQL Query for fetch records from order by match keyword from comments table.
select DISTINCT o.* from orders o LEFT JOIN comment_relations cr ON o.id=cr.target_id LEFT JOIN comments c ON c.id=cr.comment_id where body LIKE '%keyword%'

On applying this query by replace your keyword at place of keyword you get this result.

Here i match keyword "first comment"


text:
Q: django can't find views...page not found error I am trying to print a response from the view.. but django shows the page not found error(404)
My main project.urls are:-
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from . import views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'ultimatefinalblog.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^$',views.siteindex,name="siteindex"),
    url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^markdown/', include('django_markdown.urls')),

)

my blog's urls.py are:-
from django.conf.urls import patterns,  url
from blog import views

urlpatterns = patterns('',
    #url(r'^$', views.BlogIndex.as_view(), name="index"),
    #url(r'^(?P<slug>\S+)$', views.BlogDetail.as_view(), name="entry_detail"),
    #url(r'^$', views.testview, name="testview"),
    url(r'^$', views.index, name="index"),
    url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
    url(r'^testingpage/', views.testview, name='testview'),
    )

I have defined the testview function in my views.py
def testview(request):
    return HttpResponse("testing our view!")

When i try to run the url 127.0.0.1:8000/blog/testingpage in my development server it shows the page not found error...can somebody help me solve this problem?

A: Here is your issue:
In your URL patterns,
url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
url(r'^testingpage/', views.testview, name='testview'),

The testingpage is being matched with ?P<slug>\S+ (for views.detail), before views.testview, and you probably have a raise 404 or something similar line of code to match slug.
So, Change the order:
url(r'^testingpage/', views.testview, name='testview'),
url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),

And it should work for you.
Also, Slug is generally matched with (?P<slug>[\w-]+) and not \S+

A: So!
I succeded to make your code work.
I'll organize this answer in three parts (beware : It will be exhaustive!) :

*

*First :

I'll copy the code I made (almost the same as yours, plus the parts you didn't provide and I had to recode - these are very basic, just to fill the missing parts). I hope it will help you to find how to fix your problem by comparing. I'll also give an hypothesis about your problem.

*

*Second :

I'll talk about your code. There are good habits that could help you to build your django projects (but you don't seem to use these). Please note that your code can work without using these. But it may be more difficult without these habits.

*

*Third :

I will suggest a corrected version of your code with comments to illustrate the second part.
First - The code that works on my computer :
I make my own version of your project with django 1.7.5.
I organized the project like this :
.
├── blog
│   ├── __init__.py
│   ├── admin.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── main
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
└── manage.py

Where "main" is the project name and "blog" an app.
From a fresh project, the files I had to modify/add are :
blog/urls.py :
from django.conf.urls import patterns,  url
from blog import views

urlpatterns = patterns('',
                       #url(r'^$', views.BlogIndex.as_view(), name="index"),
                       #url(r'^(?P<slug>\S+)$', views.BlogDetail.as_view(), name="entry_detail"),
                       #url(r'^$', views.testview, name="testview"),
                       url(r'^$', views.index, name="index"),
                       url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
                       url(r'^testingpage/', views.testview, name='testview'),
)

blog/views.py :
from django.shortcuts import render, HttpResponse

# Create your views here.

def testview(request):
    return HttpResponse("testing our view!")

def index(request):
    return HttpResponse("Index.")

def detail(request, slug="test"):
    return HttpResponse("Detail : " + slug)

main/urls.py :
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from . import views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'main.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^$',views.siteindex,name="siteindex"),
    url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^markdown/', include('django_markdown.urls')),
)

main/views.py :
from django.shortcuts import render, HttpResponse

# Create your views here.

def siteindex(request):
    return HttpResponse("site index!")

Then I just do :
>>>python manage.py migrate
>>>python manage.py runserver

And I can access to http://127.0.0.1:8000/blog/testingpage/ and to other pages. I have no problem this way.
But I you do so, you will see that this URL matches with the r'^(?P<slug>\S+)$' pattern. And therefore /blog/testingpage does not trigger the view testview but the view detail.
So I think your problem may come from the detail view, could you add it to your question to check?
Second - How you could improve your code :

*

*apps and views imports

The way you imports your views is functionnal, but it could be impractible
You could add the app ("blog") containing your views to INSTALLED_APPS in your main/settings.py. And you will be able to use your views just by entering their names as strings.
edit :
This changed with the 1.8 release, now it's recommended to do like you did. My bad.

*

*Your project isn't an app.

Your /main/urls.py suggests that you've a views.py in your /main directory.
Using this directory this way isn't explicitly forbidden, but it's an app's purpose. the /main directory is meant to contain general settings.
I think you should make a second app for your views.py (and probably some url patterns) if you don't want to insert it in the "blog" app.

*

*urlpatterns order

With your blog/urls.py file, your app will "works". But /blog/testingpage/ will trigger the detail view and not the testview view, I'm not sure that is what you want to do. Beware the patterns order!
Third - An other way to do this :
Here is my version of the code.
I have organized the project like this :
.
├── blog
│   ├── __init__.py
│   ├── admin.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── main
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── website
    ├── __init__.py
    ├── admin.py
    ├── models.py
    ├── tests.py
    ├── urls.py
    └── views.py

The new files are :
blog/urls.py
from django.conf.urls import patterns, url
# You don't need this anymore
# from blog import views

urlpatterns = patterns('blog.views',  # this first argument will be used as a prefix to locate your views.
                       url(r'^$', 'index' , name="index"),
                       # beware the order!
                       # url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
                       url(r'^testingpage/', 'testview', name='testview'),
                       url(r'^(?P<slug>\S+)$', 'detail', name="entry_detail"),
)

blog/views.py
from django.shortcuts import render, HttpResponse

# Create your views here.

def testview(request):
    return HttpResponse("testing our view!")

def index(request):
    return HttpResponse("Index.")

def detail(request, slug="test"):
    return HttpResponse("Detail : " + slug)

INSTALLED_APP in main/settings.py (/!\ Important /!\)
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'website',
)

main/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'main.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^blog/', include('blog.urls')),
    url(r'^markdown/', include('django_markdown.urls')),
    url(r'^$', include('website.urls')),
)

website/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
# If you add the app name to INSTALLED_APP you don't need this anymore.
# from . import views

urlpatterns = patterns('website.views', # This first argument will be used as a prefix to locate your views.
    url(r'^$', 'siteindex', name="siteindex"),
)

website/views.py
from django.shortcuts import render, HttpResponse

# Create your views here.

def siteindex(request):
    return HttpResponse("site index!")

I hope all of this will help.


text:
Q: How to take advantage of MVVM Light EventToCommand to bind a lot of same events in XAML? Let me explain my requirements:
I have a grid containing several check boxes like this:
<Grid>

    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <CheckBox>1</CheckBox>
    <CheckBox
        Grid.Column="1">2</CheckBox>
</Grid>

I know clearly how to use mvvm light EventToCommand to bind to a command (which is defined in my VM or anywhere else).
But, as we all know, I have more than 1 check box. So I have to do it like this:
    <CheckBox
        Content="1">
        <i:Interaction.Triggers>
            <i:EventTrigger
                EventName="Checked">
                <ml:EventToCommand
                    Command="{Binding SomeCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </CheckBox>
    <CheckBox
        Grid.Column="1"
        Content="2">
        <i:Interaction.Triggers>
            <i:EventTrigger
                EventName="Checked">
                <ml:EventToCommand
                    Command="{Binding SomeCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </CheckBox>

If I have more check boxes, I have to C+V again and again so as to make each check box have the same EventToCommand behaviors.
What's more annoying is that we also have another event named as Unchecked. Usually the callback for both Checked and Uncheck are totally the same. So I have to C+V again & again & again..........
And finally my XAML is long and complicated!
==============================================
I'm thinking of some workaround like this:
I looked into the source code of Checked as well as Unchecked event, and found that both of them were RoutedEvent with mode as Bubble, which means this routed event call bubble up to the grid which contains them.
So I wrote my XAML code like this:
<Grid>
    <i:Interaction.Triggers>
        <i:EventTrigger
            EventName="ToggleButton.Checked">
            <ml:EventToCommand
                Command="{Binding TestCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    ......several check boxes......
</Grid>

But the above codes won't work. Neither Checked nor Unchecked is ATTACHED event.
Then I deleted "ToggleButton.", like this:
        <i:EventTrigger
            EventName="Checked">
            <ml:EventToCommand
                Command="{Binding TestCommand}" />
        </i:EventTrigger>

Still not working! :(
Events should BUBBLE up to the grid, don't they?
So, anyone have some good ideas about this?
Thanks!

A: You could define an implicit Style for all CheckBoxes in the Grid:
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.Resources>
        <Style TargetType="CheckBox">
            <Setter Property="Command" Value="{Binding SomeCommand}" />
        </Style>
    </Grid.Resources>

    <CheckBox>1</CheckBox>
    <CheckBox Grid.Column="1">2</CheckBox>
</Grid>

And instead of handling the Checked and Unchecked events, you could bind to the IsChecked property of each CheckBox to a source property:
<CheckBox IsChecked="{Binding IsFirstChecked}">1</CheckBox>

A: Thank you for ur suggestion. It's really handy.
I have also found another solution which was post in this site:
link
In the above post, another solution was mentioned:
using System;
using System.Windows;
using System.Windows.Interactivity;

namespace NaiveMepUi.GuiCommon
{
public class RoutedEventTrigger : EventTriggerBase<DependencyObject>
{
    public RoutedEventTrigger() { }

    public RoutedEvent RoutedEvent { get; set; }

    protected override void OnAttached()
    {
        Behavior behavior = base.AssociatedObject as Behavior;
        FrameworkElement associatedElement =
            base.AssociatedObject as FrameworkElement;

        if (behavior != null)
        {
            associatedElement =
                ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;
        }
        if (associatedElement == null)
        {
            throw new ArgumentException
                ("RoutedEventTrigger.AssociatedObject is not FrameworkElement.");
        }
        if (RoutedEvent != null)
        {
            associatedElement.AddHandler(
                RoutedEvent,
                new RoutedEventHandler(this.OnRoutedEvent));
        }
    }

    /// <summary>
    /// 路由事件被引发,继而引发基类的事件回调;
    /// 但是这一步会丢弃<paramref name="sender"/>。
    /// 如果事件绑定到命令,则命令只能接收到<paramref name="args"/>;
    /// 作为在 ViewModel 中定义的命令,原则上不应该 View 中定义的元素。
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    void OnRoutedEvent(object sender, RoutedEventArgs args)
    {
        base.OnEvent(args);
    }

    protected override string GetEventName()
    {
        return RoutedEvent.Name;
    }
}
}

Then I can use it in XAML like this:
       <Grid>
            <i:Interaction.Triggers>
                <guicommon:RoutedEventTrigger
                    RoutedEvent="CheckBox.Checked">
                    <ml:EventToCommand
                        Command="{Binding }" />
                    <!--todo 测试一下这种设计模式是否可行-->
                </guicommon:RoutedEventTrigger>
            </i:Interaction.Triggers>
       </Grid>


text:
Q: Showing spash screen while loading .net framework I want to show a splash screen to user when user runs an application. It is possible to show a splash screen when loading windows form but, is there any i can show a splash screen when my application is being launched i mean when .net framework is loading in the memory.

A: Anything you write using the .NET framework needs the framework loaded, so not that I'm aware of, no.  I suppose you could create some sort of application that launches your .NET application.  That first app wouldn't be able to use the .NET framework, though, and it seems a bit convoluted anyway.

A: If you need to show something while main .NET application is not even started, you need an external launcher (written in WinAPI, maybe?)

A: In order to do that you would have to either use a process to launch you application or implement your own runtime host. There's an excellent book on how to do the latter, but I doubt that it will be worth the trouble just to show a splash screen.

A: If you are using WPF, and experiencing delays, you can try this:

http://tozon.info/blog/post/2008/08/11/Splash-Screen-in-WPF.aspx

It's a splash screen that is loaded/displayed as soon as possible, before the WPF components are loaded and initialised.


text:
Q: How does R check for system external dependencies when installing an R package? For instance, while trying to install the R package curl as a dependency of usethis:
* installing *source* package 'curl' ...
** package 'curl' successfully unpacked and MD5 sums checked
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lcurl
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'

R detects that I don't have libcurl installed. At what level is this external dep. specified? I know that external dependencies can be indicated in the DESCRIPTION file, and indeed curl's pkg DESCRIPTION file does contain:
SystemRequirements: libcurl: libcurl-devel (rpm) or libcurl4-openssl-dev (deb).

But is that line what allowed R to detect the missing dependency and print that error? Can't be, right? How could it? So, how is R doing it?

A: Briefly:

*

*This is all in Writing R Extension.

*In short, it doesn't i.e. R does not help you. See below.

*CRAN (and Bioconductor) package dependencies can be declared.

*For everything else you can only approximate via SystemRequirements in DESCRIPTION

*This is not a solved or solvable problem of all depends across all operating systems

*So no other language has it either.

*What one can get is a package manager in a 'vertical' stack -- say brew or apt.  That is pretty good, but it also does not work at the CRAN source level.

*So all one can do is, as you show, invoke something executable called configure to test if resources are present, and to abort with clear errors if not.

*For the package you show, that test code in configure is here.

*There is a sibbling Windows version too.


text:
Q: Testing Reachability with Network Link Conditioner on 100% packet loss: help me understand what's happening Help me understand what I am seeing when testing Reachability code using the Network link conditioner. Here is my vanilla Reachability code:
Reachability* wifiReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

switch (netStatus)
{
    case NotReachable:
    {
        NSLog(@"Access Not Available");
        break;
    }

    case ReachableViaWWAN:
    {
        NSLog(@"Reachable WWAN");
        break;
    }
    case ReachableViaWiFi:
    {
        NSLog(@"Reachable WiFi");
        break;
    }
}

Now, when I test this code using the Network Link Conditioner using the "100% Loss" preset - the value of netStatus is ReachableViaWWAN, which I wasn't expecting. I read a lot of complaints that Reachability doesn't really test connectivity, rather it tests the potential of connectivity. So here's my question:
Is the "100% Loss" preset allowing the DNS requests to the Apple server pass through, but not letting any packets through?

A: This might have to do with the fact, that Reachability doesn't guarantee that a packet can actually reach the target host. It is about the local network configuration (interface up / down) and if it can SEND a packet.
From Apple's SCNetworkReachability Reference:

A remote host is considered reachable when a data packet, sent by an application into the network stack, can leave the local device. Reachability does not guarantee that the data packet will actually be received by the host.

So if the interface is up and Reachability can send a package, it is satisfied and returns status reachable.
From Apple's developer guide Why Networking is hard:

Important: The SCNetworkReachability API is not intended for use as a preflight mechanism for determining network connectivity. You determine network connectivity by attempting to connect. If the connection fails, consult the SCNetworkReachability API to help diagnose the cause of the failure.


text:
Q: Can codecept see elements in RSS feeds (XML)? I have an RSS feed which should have only 1 'item' in it. I know that I can do I.see() to check that any number exists; but is it possible to check if exactly 1 exists?
I know for elements (in html) I have much more flexibility than simply I.see(). Is it possible to see xml as elements?

A: const DOMParser = require('xmldom').DOMParser;
let parser = new DOMParser();
let elementTagName = "rss"; // set tag of your element here
let xmlXpath = "//body/pre";

I.waitForElement(xmlXpath);
let innerText = await I.grabTextFrom(xmlXpath);
let documentCustom = parser.parseFromString(innerText, "text/xml");
let documentCustomGetElement = documentCustom.getElementsByTagName(elementTagName)[0].childNodes; // your element here

You can try it for this rss-feed.


text:
Q: RegEx for matching and extracting UL & DL speeds into variables I'm trying to monitor file transfers. Output is:
Status: Uploading UL: 0.0 KiB/s

Status: Paused

Status: Downloading DL: 358.9 KiB/s ETA: 1h 27m

Status: Stopped

Status: Uploading UL: 25.8 MiB/s ETA: 25m 30s

I'd like to use a perl regex to pull these into $dl_speed, $ul_speed and $eta.
Can you send me on the right way?

A: I'm not sure if this would be the correct direction. However, this RegEx might help you to match your UL and DL variables.
(UL:\s|DL:\s)([0-9\.]+)(\sKiB\/s|\sMiB\/s)

It has three capturing groups:

*

*The right one is where your units go, and you can simply add more with an |.

*The left boundary is similar to the right one.

*In the middle group, only numbers and . is allowed, without spaces.

You can also reduce boundaries and much simplify this RegEx, if you wish.
You may make sure, if there are other Perl-required checks to follow through.

In case, you had more spaces in between your float numbers and the units, you might work on this RegEx:
(UL:\s+|DL:|\s+)([0-9\.]+)(\s+KiB\/s|\s+MiB\/s)

If you wish to get the three variables, you might add one matching set for UL and DL, and another set for ETA, maybe similar to this RegEx
((UL:\s+|DL:\s+)([0-9\.]+)(\s+KiB\/s|\s+MiB\/s))|((ETA:\s+)([0-9hms]+\s[0-9hms]+))

I have added several boundaries, since I'm not really sure, how your possible inputs may look like. You can much simplify, if you wish so.


text:
Q: Get all infoWindows on a Google Map I am working on a map where I neet to plot multiple routes using the DirectionService, and each marker on the route has an infoWindow.
Instead of having to keep track of which infoWindow binds to which marker, is there a way for me to grab all infoWindows on a map?

A: Why not just have one infowindow, and set the content of it to be different for each marker?  Makes life much simpler (unless you ever need to display more than one infowindow open at the same time)

A: There are no way to do what you want.
The map does not know what markers it have or what infowindows those markers have. The Markers know what map they belong to, but that is it. So unfortunatly you will have to keep track of your markers and infowindows if you want to use them after they are created.


text:
Q: Similarity / distance between many pairs of matrices I want to quantify group similarity by computing the mean of the distance between all sets of (multidimensional) points in each pair.
I can do this easily enough manually for each pair of groups manually like so:
library(dplyr)
library(tibble)
library(proxy)

# dummy data
set.seed(123)
df1 <- data.frame(x = rnorm(100,0,4),
                  y = rnorm(100,1,5),
                  z = rbinom(100, 1, 0.1))
df2 <- data.frame(x = rnorm(100,-1,3),
                  y = rnorm(100,0,6),
                  z = rbinom(100, 1, 0.1))
df3 <- data.frame(x = rnorm(100,-30,4),
                  y = rnorm(100,10,2),
                  z = rbinom(100, 1, 0.9))

# compute distance (unscaled, uncentred data)
dist(df1, df2, method = "gower") %>% mean
dist(df1, df3, method = "gower") %>% mean
dist(df2, df3, method = "gower") %>% mean

But I'd like to somehow vectorise this as my actual data has 30+ groups. A simple for loop can achieve this like so:
# combine data and scale, centre
df <- rbind(df1, df2, df3) %>%
  mutate(id = rep(1:3, each = 100))
df <- df %>%
  select(-id) %>%
  transmute_all(scale) %>%
  add_column(id = df$id)

# create empty matrix for comparisons
n <- df$id %>% unique %>% length
m <- matrix(nrow = n, ncol = n)

# loop through each pair once
for(i in 1:n) {
  for(j in 1:i) { #omit top right corner
    if(i == j) {
      m[i,j] <- NA #omit diagonal
    } else {
      m[i,j] <- dist(df[df$id == i,1:3], df[df$id == j,1:3], method = "gower") %>% mean
    }
  }
}

m
          [,1]      [,2] [,3]
[1,]        NA        NA   NA
[2,] 0.2217443        NA   NA
[3,] 0.8446070 0.8233932   NA

However, this method scales predictably badly; a quick benchmark suggests this will take 90+ hours with my actual data which has 30+ groups with 1000+ rows per group.
Can anyone suggest a more efficient solution, or perhaps a fundamentally different way to frame the problem which I'm missing?

A: I'm not sure if this will do well but here's another approach. You use ls to obtain the names of matrices, combn to generate pairs of two, and then get to obtain the matrices for calculating dist
do.call(rbind,
        combn(ls(pattern = "df\\d+"), 2, FUN = function(x)
            data.frame(pair = toString(x),
                       dist = mean(dist(get(x[1]), get(x[2]), method = "gower")),
                       stringsAsFactors = FALSE),
            simplify = FALSE
        ))
#      pair      dist
#1 df1, df2 0.2139304
#2 df1, df3 0.8315169
#3 df2, df3 0.8320911

A: You could take each pair of groups, concatenate them, and then just calculate the dissimilarity matrix within that group. Obviously this means you're comparing a group to itself to an extent, but it may still work for your use case, and with daisy it is reasonably quick for your size of data.
library(cluster)

n <- 30
groups <- vector("list", 30)

# dummy data
set.seed(123)
for(i in 1:30) {
  groups[[i]] = data.frame(x = rnorm(1000,ceiling(runif(1, -10, 10)),ceiling(runif(1, 2, 4))),
                           y = rnorm(1000,ceiling(runif(1, -10, 10)),ceiling(runif(1, 2, 4))),
                           z = rbinom(1000,1,runif(1,0.1,0.9)))
}

m <- matrix(nrow = n, ncol = n)

# loop through each pair once
for(i in 1:n) {
  for(j in 1:i) { #omit top right corner
    if(i == j) {
      m[i,j] <- NA #omit diagonal
    } else {
      # concatenate groups
      dat <- rbind(df_list[[i]], df_list[[j]])

      # compute all distances (between groups and within groups), return matrix
      mm <- dat %>%
        daisy(metric = "gower") %>%
        as.matrix

      # retain only distances between groups
      mm <- mm[(nrow(df_list[[i]])+1):nrow(dat) , 1:nrow(df_list[[i]])]

      # write mean distance to global comparison matrix
      m[i,j] <- mean(mm)
    }
  }
}

A: proxy can work with lists of matrices as input,
you only need to define a wrapper function that does what you want:
nested_gower <- function(x, y, ...) {
  mean(proxy::dist(x, y, ..., method = "gower"))
}

proxy::pr_DB$set_entry(
  FUN = nested_gower,
  names = c("ngower"),
  distance = TRUE,
  loop = TRUE
)

df_list <- list(df1, df2, df3)
proxy::dist(df_list, df_list, method = "ngower")
     [,1]      [,2]      [,3]
[1,] 0.1978306 0.2139304 0.8315169
[2,] 0.2139304 0.2245903 0.8320911
[3,] 0.8315169 0.8320911 0.2139049

This will still be slow,
but it should be faster than for loops in plain R
(proxy uses C in the background).
Important: note that the diagonal of the resulting cross-distance matrix doesn't have zeros.
If you were to call dist like proxy::dist(df_list, method = "ngower"),
proxy will assume that distance(x, y) = distance(y, x) (symmetry),
and that distance(x, x) = 0,
the latter of which is not true in this case.
Passing two arguments to dist prevents this assumption.
If you really don't care about the diagonal,
pass only one argument to save some extra time by avoiding the calculations of the upper triangular.
Alternatively, if you do care about the diagonal but still want to avoid calculating the upper triangular,
call dist first with one argument and then call proxy::dist(df_list, df_list, method = "ngower", pairwise = TRUE).
Side note: if you want to imitate this behavior with the gower package (as suggested by d.b),
you could define the wrapper function as:
nested_gower <- function(x, y, ...) {
  distmat <- sapply(seq_len(nrow(y)), function(y_row) {
      gower::gower_dist(x, y[y_row, , drop = FALSE], ...)
  })

  mean(distmat)
}

However, the values returned seem to change depending on how many records are passed to the functions,
so it's hard to tell what would be the best approach.
*Use proxy::pr_DB$delete_entry("ngower") first if you want to redefine a function in proxy.

If you prefer proxy's version of the Gower cross-distance matrix,
it occurs to me that you could leverage some of the functionality of my dtwclust package to do the calculations in parallel:
library(dtwclust)
library(doParallel)

custom_dist <- new("tsclustFamily", dist = "ngower", control = list(symmetric = TRUE))@dist

workers <- makeCluster(detectCores())
registerDoParallel(workers)

distmat <- custom_dist(df_list)

stopCluster(workers); registerDoSEQ()

This might be faster for your actual use case
(not so much for the small sample data here).
Same caveat about the diagonal
(so use custom_dist(df_list, df_list) or custom_dist(df_list, pairwise = TRUE)).
See section 3.2 here and the documentation of tsclustFamily if you'd like more info.


text:
Q: How to overwrite a imported python class for all calls I create a python-packages /MyLibPackage which I will import in my projects.
MyLibPackage.____init____.py includes mymodiciation.py. Furthermore the MyLibPackage Folder contains another file :base_classes.py(=external project)
mymodiciation.py imports "from base_classes import *".
Goal:
I can import MyLibPackage which has all classes from base_classes (=external project).
And if I have need to modifiy some classes or functions, I can overwrite this in mymodiciation.py. It works but I got a problem. For example:
I overwrite this classes in mymodiciation.py:
class Bookcollection(Bookcollection):
   new_member = "lalala"

class user(user):
   def get_books(self):
      return Bookcollection()

if I do:
from MyLibPackage import *
x = user()
books = x.get_books()

then the object Bookcollection has the property "new_member". Good!
But if i will do this:
from MyLibPackage import *
x = shelf() #this class is not overwritten and used also the object "Bookcolelction"
books = x.get_books()

then the object Bookcollection has NOT the property "new_member" because he is instanced with MyLibPackage.base_classes.Bookcollection and not with my overwritten class MyLibPackage.mymodiciation.Bookcollection
How can I say: If I overwrite a class in mymodiciation then MyLibPackage has to use this although when the call cames from MyLibPackage.base_classes.shelf (get_books).

A: What you want to do is called "monkey patching", and has little to do with Object Orientation.
Python does support it, but you have control over all your classes, you should seriously review your project to check if you will really need it.
Maybe using a framework like Zope Component Architecture, which allows you to mark classes with interfaces, and provides adapter objects so that you can cleanly use one object as having some interface it was not designed to have in first place, will be a better idea.
That said, what you are asking for is to change the class, in the other module, where it is - so that the changes are visible to all the other modules.
You do just that: change the class in the module where it belongs. In Python it can be done simply attributing  your new class to the desired name, in the module of origin:
import base_classes

class Bookcollection(base_classes.Bookcollection):
   new_member = "lalala"

base_classes.Bookcollection = Bookcollection

(For things like this to work, you have to avoid "from x import *"  in any project larger than single script - in this case you had 2  variables with the same name, and different meanings throughout your code:the base class, and the inherited class, for example. Python namespaces allow you to avoid that).
So, this will change the Bookcollection class in the base_class module - BUT only for code that will reference it from this point and on  on your execution chain. If the "x" class in your example,is defined in the "base_classes" module, or otherwise is defined before the "MyModule" is imported, it will get a reference to the old "Bookcollection" class.
As you can see, it can quickly become a mess, and if you really choose this approach, the only way of keeping your project even usable, is to have unit tests to verify that all the classes that you want patched, are actually patched. Even the importing order of modules will make a difference, as you see. If you have tests place, they will break if you make imports in an order that breaks your monkey patching.
If you just need to add and replace things in an existing class, you can monkey patch the class itself to replace its components, instead of monkey patching the module it is in to replace the class. This way, the import order of modules won't matter much -- it will affect even existing instances of that class:
 import base_classes

 base_classes.Bookcollection.new_member = "lalala"

 def new_bookcol_method(self):
      pass

 # to replace or register a method in the other class:
 base_classes.Bookcollection.__dict__["old_bookcol_method"] = new_bookcol_method

This will give you a more consistent behaviour than trying to assign a new class (which is an object in itself) to the same name in the original module.
All in all, you should  either do as @jamesj suggests in his answer, and use distinct classes, or if you need the dynamic behaviour, use a maintainable framework for that, like Zope Component Architecture. And whatever approach you take, do write unit tests.

A: Having classes with the same name is generally a bad idea as you get namespace clashes. I would recommend changing your MyLibPackage.base_classes.Bookcollection to MyLibPackage.base_classes.BaseBookcollection or similar. This should then work as expected.


text:
Q: Photoshop Script - resize images in folder (dialog box) i would like to know if there is an easy way to write a simple script in Photoshop.
I would like it to pop a dialog box to let user select a folder. Then the scripts creates another folder ("web_ready") inside selected one and put resized images into it. I can handle the resizing part pretty easily (there is a lot of tutorials on the web) but i don't know how to write the part with dialog box pop-up. Can you help me? I am talking about *.jsx scripts.

A: Folder select dialog:
var inputFolder = Folder.selectDialog("Select a folder to process");

Get the files from the folder:
var fileList = inputFolder.getFiles("*.JPG"); //Use whatever extension you want or no extension to select all files

Do something with the files:
for(var i=0; i<fileList.length; i++) {
    //do something..
}


text:
Q: Using separate functions based on template class type I have a fairly simple assignment to review hash tables, and we have to create a template class and test it using floats, ints, and STL strings as key data types.
I have the class setup like so:
 template<class K, class T>
 class hashTable{
     public:
     private:
 };

When I call the class to test it, I use:
hashTable<float, data>
hashTable<int, data>

etc... I just am not sure how to make the class use the hash function I have for each data type based on what data type I use when I call the function.

A: I see at least three approaches:
First. Create an overloaded function hash for all your types:
hash_t hash(int);
hash_t hash(float);

and in hashTable just call hash().
Second. Create a separate templated class (or, well, a function) hash<T> and specialize it for int, float, etc. Then in hastTable refer to it in general way as hash<K>:
 template<class T> class hash;
 template<> class hash<int> { hash_t operator() {...} };
 template<> class hash<float> { hash_t operator() {...} };

Third. Supply the needed class or function via a template parameter to hashTable, just the way the standard std::sort received comparison function:
template<class K, class T, class Hash>
class hashTable...

A: I would suggest you do it like the standard does.  Add a template parameter for the hash function and then use the standard hash.  If you have a custom type that the standard hash does not work for then you can implement you own and include it in the template arguments.
template<class K, class T, class Hash = std::hash<K>>
class hashTable{
// stuff
};


text:
Q: Use a filter in facet.range query? solrQuery.set("rows", 0);
    solrQuery.set("facet", true);
    solrQuery.set("facet.range", "logtime");
    solrQuery.set("facet.range.start", from);
    solrQuery.set("facet.range.end", to);
    solrQuery.set("facet.range.gap", unit);
    solrQuery.set("facet.mincount", 0);

here logtime is a date type
I am thinking of using facet.range.method but I don't know the syntax of it.
Can anyone give example for facet.range.method.
Thanks in advance


text:
Q: stopwatch using drawables instead of text. How to optimize cpu usage? How can i optimize my stopwatch in my app to use less cpu?
I am running a stopwatch using an asynctask class in the mainActivity. The doInBackground() method increments the values for the hours, minutes, seconds and centiseconds(10th of a second). The onProgressUpdate() method is responsible for updating 4 imageViews that display the hrs, mins, sec, centisec.
The problem i have is that the stopwatch uses about on average 50%+ cpu usage according to android studio(50% user and 30% kernel usage) and a cpu monitoring app that i installed on the device (2013 HTC one m7). The default android operating system stopwatch uses only about 10% cpu usage. If i use textViews instead of image views the cpu usage drop to half (less than 25%). But it is still more than 10% and i also i want to keep the style of digits im using.

Would caching the images help in anyway? source
I have also considered using XML drawables for the digits instead of bitmaps, but i don't know how effective this will be or if its even possible to create xml drawables of the digits
Lend me your knowledge stackoverflow

main XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#763768"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.aroboius.stopwatch.MainActivity"
    tools:showIn="@layout/activity_main">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/hoursImage"
        android:layout_marginRight="20dp"
        android:src="@drawable/digit00" />

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/minutesImage"
        android:layout_marginRight="20dp"
        android:src="@drawable/digit00" />

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/secondsImage"
        android:layout_marginRight="20dp"
        android:src="@drawable/digit00" />

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/centiSecondsImage"
        android:src="@drawable/digit00" />

</LinearLayout>

MainActivity

public class MainActivity extends AppCompatActivity {

    ImageView hoursIMG, minutesIMG, secondsIMG, centiSecondsIMG;
    TextView hoursText, minutesText, secondsText, centicsecondsText;
    int centiseconds, seconds, minutes, hours ;
    long startMS , endMS , elapsed ;
    boolean timerRunning;

    String [] digit = {"digit00","digit01","digit02","digit03","digit04","digit05","digit06","digit07","digit08","digit09", "digit10", "digit11","digit12","digit13","digit14","digit15","digit16","digit17","digit18","digit19","digit20",   "digit21","digit22","digit23","digit24","digit25","digit26","digit27","digit28","digit29","digit30","digit31",
            "digit32","digit33","digit34","digit35","digit36","digit37","digit38","digit39","digit40","digit41","digit42","digit43","digit44","digit45","digit46","digit47","digit48","digit49","digit50","digit51","digit52","digit53",
            "digit54","digit55","digit56","digit57","digit58","digit59","digit60","digit61","digit62","digit63","digit64","digit65","digit66","digit67","digit68","digit69","digit70","digit71","digit72","digit73","digit74","digit75",
            "digit76","digit77","digit78","digit79","digit80","digit81","digit82","digit83","digit84","digit85","digit86","digit87","digit88","digit89", "digit90","digit91","digit92","digit93","digit94","digit95","digit96","digit97","digit98","digit99"} ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //initializing values
        centiseconds = 0; seconds = 0; minutes = 0; hours = 0;
        startMS = 0; endMS = 0; elapsed = 0;

        hoursIMG = (ImageView) findViewById(R.id.hoursImage);
        minutesIMG = (ImageView) findViewById(R.id.minutesImage);
        secondsIMG = (ImageView) findViewById(R.id.secondsImage);
        centiSecondsIMG = (ImageView) findViewById(R.id.centiSecondsImage);

        //start asynctask/stopwatch
        timerRunning = true; new asyncTask().execute();
    }

    class asyncTask extends AsyncTask<Void, Void, Void> {

        //initialize a variable to the current system time
        @Override
        protected void onPreExecute() {
            startMS = System.currentTimeMillis();
        }

        @Override
        protected Void doInBackground(Void... params) {

            //timerRunning a varible to stop/start the timer
            while (timerRunning) {

                //initialize a 2nd variable to the current system time
                endMS = System.currentTimeMillis();

                //get the difference between the 2 time variables
                elapsed = endMS - startMS;

                //once it is greater than or equal to 100ms increment the centis, mins, secs, hrs
                if (elapsed >= 100) {

                    //reset the starting variable to repeat the process. it also compensating if elapses is greater than 100ms
                    startMS = endMS - (elapsed - 100);

                    centiseconds++;

                    if (centiseconds > 9) {
                        centiseconds = 0;
                        seconds++;
                        if (seconds > 59) {
                            seconds = 0;
                            minutes++;
                            if (minutes > 59) {
                                minutes = 0;
                                hours++;
                            }
                        }
                    }

                    //call method to update the images
                    publishProgress();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

 //get resource IDs for images that represent the values of hrs, mins, secs using the string array created earlier

                int hourResID = getResources().getIdentifier(digit[hours], "drawable", getPackageName());
                int minResID= getResources().getIdentifier(digit[minutes], "drawable", getPackageName());
                int secResID= getResources().getIdentifier(digit [seconds], "drawable", getPackageName());
                int csecResID= getResources().getIdentifier(digit[centiseconds], "drawable", getPackageName());

//set images of imageViews
                centiSecondsIMG.setImageResource(csecResID);
                secondsIMG.setImageResource(secResID);
                minutesIMG.setImageResource(minResID);
                hoursIMG.setImageResource(hourResID);
        }
    }
}

1:

A: Instead of burning your CPU and battery with a loop, you should use a CountDownTimer
  new CountDownTimer(30000, 1000) { // 30sec, tick each second

     public void onTick(long millisUntilFinished) {
         publishProgress();
         // mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

Or you can use a Runnable that you delay every time by the desired amount of time, let's say 200ms:
final static long REFRESH_RATE = 200L;
Handler mHandler = new Handler();

private final Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        if (mStarted) {
            long seconds = (System.currentTimeMillis() - t) / 1000;
            statusBar.setText(String.format("%02d:%02d", seconds / 60, seconds % 60));

            // cancel previous messages if they exist
            handler.removeCallbacks(mRunnable);

            handler.postDelayed(runnable, REFRESH_RATE);
        }
    }
};

start it:
mHandler.postDealyed(runnable, 0);

You can use a Timer with fixed rate:
new Timer().scheduleAtFixedRate(new TimerTask(){
    @Override
    public void run(){
       publishProgress();
    }
},0,1000);

Or you can use a ScheduledExecutorService, that will fix most of the problems you mentioned. See here and here.
ScheduledExecutorService scheduledExecutorService =
        Executors.newScheduledThreadPool(1);
long lastSecondDisplayed = 0;

ScheduledFuture scheduledFuture =
    scheduledExecutorService.schedule(new Callable() {
        public Object call() throws Exception {
            long now = System.currentTimeMillis() / 1000;

            // add this optimisation, so you don't calculate and
            // for sure don't refresh your UI (even slower)
            // if it's not needed:
            if (lastSecondDisplayed != now) {
                lastSecondDisplayed = now;
                // calculate whatever you want
                publishProgress();
            }
            return "Called!";
        }
    }, 1, TimeUnit.SECONDS);

Optimisations:

*

*move the 4 getResources().getIdentifier(... lines out of onProgressUpdate and prepare the 10 digits only once in onCreate.

It is always good to reuse resources in java, because when you're creating and disposing them frequently, like here, you'll finish your memory quite fast and the GC will have to free some memory for you. Both creating the objects, and especially garbage-collecting them takes a fair amount of time. By creating them only once and reusing them you keep yourself far from all this trouble.

A: It seems it was a problem with continuously resetting the imageViews to different drawables. The  getResources().getIdentifier() function calls also somewhat contributed to extra cpu usage and GarbageCleaner(GC) problems.
Instead of creating an image resource array I created a drawable array that I can continually reference. I created it in onCreate().
 final Drawable[] drawable = {ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit00),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit01),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit02),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit03),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit04),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit05),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit06),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit07),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit08),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit09),
                ContextCompat.getDrawable(getApplicationContext(), R.drawable.digit10)}

Then I set the images on the imageViews using the Drawable
MainActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    centiSecondsIMG.setImageDrawable(drawable[centiseconds]);
                                    secondsIMG.setImageDrawable(drawable[seconds]);
                                    minutesIMG.setImageDrawable(drawable[minutes]);
                                    hoursIMG.setImageDrawable(drawable[hours]);

                                }
                            });

Memory and cpu are now all perfectly fine and working normally.
i sitll dont know why changing the imageViews images rapidly using setImageResource() caused problems with cpu,memory and GC.


text:
Q: Is it possible to implement method-level access checks with annotations? Consider some basic authorization framework with Users and Groups where access to methods should be guarded by checks which make sure that the user or the group have the necessary PriviledgeLevel to execute the method and fails otherwise.
What I imagine is something like this:
@AccessCheck(PriviledgeLevel.ADMINISTRATOR)
public static void secureMethod(){ ... }

Where the code checking basically does
if(currentUser.getPriviledgeLevel >= PriviledgeLevel.ADMINISTRATOR ||
   currentUser.getGroup.priviledgeLevel >= PriviledgeLevel.ADMINISTRATOR)
  // Allow access
else
  // Deny access

Would it be possible to implement it this way?
I did a bit of research which points to some existing things based on AspectJ, mostly on the Security Annotation Framework (SAF) and on Spring Security.
I'm a bit concerned because SAF doesn't seem very active anymore and the documentation isn't that great.
I'm not sure about Spring Security but it seems to be more focused on security problems in web-related topics.
The Java Authentication and Authorization Service seems to be related, but doesn't use the annotation approach.
Does it make sense trying to define these security requirements with this declarative approach?
Is there another library/framework I'm missing, which already implements what I want or some techonology which would be relevant here?
Or is there a completely different solution (like implementing my own ClassLoader, ...) which is superior to what I imagine (in terms of conciseness and readability for the library user)?

A: You could do this fairly trivially yourself by using dynamic proxies.
public interface MyInterface {
           @AccessCheck(Privilege.ADMIN)
           public void doSomething();
}

The proxy would be created on the class that implements your interface and you would annotate your interface with your custom annotation.
 MyInterface aInterface = (MyInterface) java.lang.reflect.Proxy.newProxyInstance(obj.getClass()
                .getClassLoader(), obj.getClass().getInterfaces(),
                new YourProxy(new Implementation());

In the invoke() method of your proxy, you can check if your method has the annotation and throw a SecurityException if the privileges are not met.
public YourProxy implements InvocationHandler {
         ....
         public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {

              if ( method.isAnnotationPresent(AccessCheck.class) {
                    ....// do access check here and throw SecurityException()
         }
 }

A: I think AspectJ will do what you want it to do. We have a whole bunch of methods which you need certain access rights for and we've created an AspectJ aspect which will check that and error out if the user does not have those permissions.
As a plus, because AspectJ is "woven" into the classes at compile time it cannot be disabled by configuration.
We also use Spring Security, it is possible to use both in harmony!

A: With Spring Security, you just have to add:
@Secured("ADMINISTRATOR")
public static void secureMethod(){ ... }

And configure it properly, by:

*

*use JdbcDaoImpl as your UserDetailsService

*enable group support

*customize the queries (if you are using database credential storage)

If you are not using database credential storage, just configure your preferred UserDetailsService to add both user and group credentials to the authorities of the generated UserDetails.
Of couse, it is hard to understand it without checking the concepts at the documentation, but method level access checks is perfectly possible with spring security and it's my prefered technology for it.

A: In Spring Security, as the docs state, both @Secured and @PreAuthorize can be used at method level.
To enable @PreAuthorize (if you haven't already...), you need to put <global-method-security pre-post-annotations="enabled" />
in your configuration XML;
For @Secured use <global-method-security secured-annotations="enabled" />.
For more details, refer to this article.