text:
Q: Grouping django objects using QuerySet API by shared text tags using two models with ForeignKey relationship Hi I am trying to write a django webapp that sits on top of a legacy database and so I cannot control too much my model fields and achieve functionality using new models.
I have many Documents with user given comma-separated-tags . I want to group "related" documents based on shared tags.
# Model to express legacy table
class Document(models.Model):
    id = models.BigIntegerField(primary_key= True)
    metadata_id = models.CharField(max_length=384)
    tags_as_csv = models.TextField()

# Created new Model tag_text extracted from tags_as_csv
class Tagdb(models.Model):
    tagid = models.BigIntegerField(primary_key=True)
    referencing_document = models.ForeignKey(Document)
    tag_text = models.TextField(blank=True)

So a Document would contain:
Document :
id = 1 ,
metadata_id = "a1ee3df3600c6f77a6e851781f7e70c6" ,
tags_as_csv = "raw-data , high temperature , important"

The Tagdb would have entries such as
id , referencing_document , tag_text
1  , 1 , "raw-data"
2  , 1 , "high temperature"
3  , 1 , "important"
4  , 2 , "important"
5  , 2 , "processed-data"
6  , 3 , "important"
7  , 4 , "processed-data"

Now I want to extract all the Document objects that match tags corresponding to a parent document. Which I am doing using the following get_queryset method.
   def get_queryset(self, **kwargs):
        parent_document = Document.objects.get(id=self.kwargs['slug'])
        tags_in_parent_document = [x.tag_text for x in Tagdb.objects.filter(referencing_document=parent_document.id)]
        # This will contain all the Document ids that match all the tags
        queryset_with_duplicates = []
        for tag in tags_in_parent_document:
            queryset_with_duplicates.extend([x.referencing_document.id for x in Tagdb.objects.filter(tagtext__icontains=tag)])

        # Make sure we have only unique ids
        queryset_unique = set(queryset_with_duplicates)

        # Get all the Document objects
        queryset = Document.objects.filter(id__in=queryset_unique)

        return queryset

My question is : is there a better way . Can I somehow get all the Documents that contain all the tags in the parent document and filter out the duplicates ( since multiple documents contain the same tag).

A: You'd better create two additional models: one for Tag and one for link between Tag and Document. If it's somewhy unacceptable, you can use something like:
Document.objects.filter(tagdb__tag_text__in=doc.tags_as_csv.split(' , ')).distinct()

Plus, add model method for getting/setting tags, it will ease any possible refactoring.


text:
Q: Class or type name not found - type Object I am a beginner in LotusScript, I have the following error in my agent:

My goal is to be able to connect to the server with the following code:
Option Public
Option Declare

Sub Initialize
    Dim myServer As String
    Dim myMailfile As String
    myServer = "server"
    myMailfile = "mailfile"

    Dim filePath As String
    Dim intErgebnis As Integer
    Dim objNotes As Object
    Dim LNdb As Object
    Dim LNView As Object
    Dim LNDoc As Object
    Dim LNItem As Object
    Dim strSubject As String
    Dim LNWorkspace As Object
    Dim LNAttachment As Variant
    intErgebnis = 0
    Set objNotes = GetObject("", "Notes.NotesSession")
    Set LNdb = objNotes.GETDATABASE(myServer, myMailfile)
    Set LNWorkspace = CreateObject("notes.notesuiworkspace")
    LNWorkspace.OpenDatabase myServer, myMailfile
End Sub

Does anyone have any idea how to solve this? Thank you for your help

A: There is no data type called Object in Lotusscript.
You need to declare those variables with their proper object types, e.g. NotesDatabase, NotesView, NotesDocument, etc.
Also, you should declare and initialize a NotesSession object, not use GetObject() in Lotusscript.  It looks like you are trying to write COM code, not Lotusscript.
Another suggestion is to use variable names that are conforming to the de-facto (established) naming convention. If you look at other Lotusscript code, you will notice that the variables generally are named the same way, making it much easier to read other developer's code. Yet another recommendation is to declare all Notes objects/classes first, grouped/sorted in the order they are being used, followed by the rest of the variables, before any of them are assigned values.
Your code should look more like this:
Sub Initialize
    Dim session As New NotesSession
    Dim db As NotesDatabase
    Dim view As NotesView
    Dim doc As NotesDocument
    Dim item As NotesItem
    Dim ws As New NotesUIWorkspace
    Dim uidoc as NotesUIDocument

    Dim mailServer As String
    Dim mailFileName As String
    Dim filePath As String
    Dim resultCount As Integer
    Dim subject As String

    mailServer = "server"
    mailFileName = "mailfile.nsf"
    resultCount = 0
    ' *** Open the specified mail file using back-end classes
    Set db = new NotesDatabase(mailServer, mailFileName)
    ' *** Get the document currently open in the Notes client using front-end classes
    Set uidoc = ws.CurrentDocument

End Sub

You see how much easier this is to read, not to mention it is both shorter and working.
I also recommend to always use variable names in English. If you ever need to ask someone for help, for example here on Stack Overflow, it is much easier for them to understand your code if you use variable names that are easy to understand. This is also the reason why you should use the standardized names for Notes objects/classes.
I wrote a series of articles about how to write better Lotusscript code, I think they may help you: http://blog.texasswede.com/how-to-write-better-code-in-notesdomino/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exception in thread "main" java.lang.Error: Invalid memory access with JNA and OpenCV I have an application with two parts. One part is a c++ program for opencv calculation. The other part is a Java part. I control a camera with JNA und edit the pictures from this camera with OpenCV.
I can call my function with JNA.
My Funtion in C++
extern "C" __declspec(dllexport) int createScript(char* imagePath)

In This function i call the function
void BladeCutter::calcMeanValues(cv::Mat image)
{
    std::vector<cv::Mat> bgr_planes;
    cv::split(image, bgr_planes);
    cv::Scalar blue = cv::mean(bgr_planes[0]);
    cv::Scalar green = cv::mean(bgr_planes[1]);
    cv::Scalar red = cv::mean(bgr_planes[2]);
    meanValues.scalar = cv::Scalar(blue[0], green[0], red[0]);
    meanValues.brightness = calcBrightness(image);
}

and get a Invalid memory access at cv::split(image, bgr_planes);
If i call the program without jna the program works fine.
Exception in thread "main" java.lang.Error: Invalid memory access
  at com.sun.jna.Native.invokePointer(Native Method)
  at com.sun.jna.Function.invokePointer(Function.java:477)
  at com.sun.jna.Function.invokeString(Function.java:658)
  at com.sun.jna.Function.invoke(Function.java:402)
  at com.sun.jna.Function.invoke(Function.java:323)
  at com.sun.jna.Library$Handler.invoke(Library.java:236)
  at com.sun.proxy.$Proxy0.createScript(Unknown Source)
  at de.test.BladeTileLocator.main(BladeTileLocator.java:14)

BladeTileLocator is the Java-Class.
package de.test;

import com.sun.jna.Native;

import de.interfaces.IBladeTileLocator;

public class BladeTileLocator {

    public static void main(String[] args) {

        final byte[] ba = new byte[50];
        final IBladeTileLocator bladeTileLocator = (IBladeTileLocator) Native.loadLibrary("BladeTileLocator", IBladeTileLocator.class);
        final String path = "C:\\Users\\bak\\Pictures\\Bildanalyse\\Bild.JPG";
        bladeTileLocator.createScript(path);
    }
}

My JNA Interface to call the function:
package de.interfaces;

import com.sun.jna.Library;

public interface IBladeTileLocator extends Library {
    int createScript(String imagePath);
}


text:
Q: How separate by grouping variable of word cloud in R? I want to make a wordcloud separated by grouping of autor variable and I did it:
# Create a dataframe that save freq of each word

tw <- tw_token %>% count(autor, word, sort=TRUE)

# head of data
dput(head(tw))
structure(list(autor = c("Mayoredlee", "Mayoredlee", "Elonmusk",
"Mayoredlee", "Mayoredlee", "Elonmusk"), word = c("sf", "city",
"tesla", "residents", "housing", "model"), n = c(775L, 320L,
263L, 260L, 180L, 163L)), row.names = c(NA, 6L), class = "data.frame")

# Make wordcloud

wordcloud(words = tw$word, freq = tw$n, min.freq = 1,
          max.words=200, random.order=FALSE, rot.per=0.45,
          colors=brewer.pal(8, "Dark2"))

The output of wordcloud

A: I think something like this might be what you are looking for:
par(mfrow = c(2, 2)) # output wordclouds on a 2 x 2 grid, adjust if necessary

tw %>%
  split(~ autor) %>%
  purrr::walk(~ with(., wordcloud(words        = word,
                                  freq         = n,
                                  min.freq     = 1,
                                  max.words    = 200,
                                  random.order = FALSE,
                                  rot.per      = 0.45)))


text:
Q: How to edit "MathJax equation" with jQuery-Tooltip or similar? How can I edit the text with a "tooltip" as in this screencast, please?
I would like to be able to the same with a "mathjax equation" (with Jquery or similar).

A: Not a direct answer, but the screencast seems to be a demo of the Aloha-based wysiwhat editor which is available on github, including a live demo.


text:
Q: Java singleton deserialization values keep default I have a simple singleton:
class Test1 implements Serializable {
    private static Test1 instance;

    public String a = "a";
    public String b = "b";
    public String c = null;
    public String d = null;
    public String e;
    public String f;

    private Test1() {
        e = "e";
    }

    public static Test1 getInstance() {
        if (instance == null) {
            instance = new Test1();
        }
        return instance;
    }

    // http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples
    protected Object readResolve() {
        return getInstance();
    }

    public String toString() {
        return String.format("Test1{ a:%s, b:%s, c:%s, d:%s, e:%s, f:%s}", a, b, c, d, e, f);
    }
}

My main():
if ((new File("t1.obj").exists() == false)) {
    Test1 t1 = Test1.getInstance();
    t1.b = "bb";
    t1.d = "dd";
    t1.f = "ff";

    serialize("t1.obj", t1);
}

else {
    Test1 t2 = deserialize("t1.obj");
}

First run looks well
Serialized hu.fehergeri13.abptc.server.Test1 object to t1.obj file.
Test1{ a:a, b:bb, c:null, d:dd, e:e, f:ff}

after second run:
Deserialized hu.fehergeri13.abptc.server.Test1 object from t1.obj file.
Test1{ a:a, b:b, c:null, d:null, e:e, f:null}

My serialize/deserialize:
public static void serialize(String filePath, Object o) {
    try {
        FileOutputStream fos = new FileOutputStream(filePath);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(o);

        System.out.println(String.format("Serialized %s object to %s file.", o.getClass().getName(), filePath));
        oos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static <T> T deserialize(String filePath) {
    try {
        FileInputStream is = new FileInputStream(filePath);
        ObjectInputStream ois = new ObjectInputStream(is);
        T o = (T) ois.readObject();

        System.out.println(String.format("Deserialized %s object from %s file.", o.getClass().getName(), filePath));
        ois.close();
        is.close();
        return o;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Why are the values keep default and not bb,dd,ff?

A: My serializable singleton:
public class MySingleton implements Serializable {

    private static final long serialVersionUID = -5909418239300111453L;
    private static MySingleton instance = null;

    protected MySingleton() {

    }

    public static MySingleton getInstance() {
        if (instance == null) {
            instance = new MySingleton();
        }
        return instance;
    }

    protected Object readResolve() {
        return getInstance();
    }

    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        ois.defaultReadObject();
        instance = this;
    }

    private String attr;

    public String getAttr() {
        return attr;
    }

    public void setAttr(String attr) {
        this.attr = attr;
    }
}


text:
Q: Why does Logic Application not work except directly under sudo? I am trying to run Logic application to talk to my logic analyzer, and I observe the following behavior, after I install the rules under the driver.
./Logic
./Logic: cpp_libs/libc.so.6: version `GLIBC_2.18' not found (required by /usr/lib/x86_64-linux-gnu/libstdc++.so.6)

sudo bash
./Logic
./Logic: cpp_libs/libc.so.6: version `GLIBC_2.18' not found (required by /usr/lib/x86_64-linux-gnu/libstdc++.so.6)

sudo ./Logic
# Application runs

What is the cause for this strange behavior?
I am running Ubuntu 14.04.

A: A plausible explanation for the difference in behavior is that the working and non-working commands are loading different libraries because they have different settings for the library search path LD_LIBRARY_PATH. There are other environment variables that could matter but are less likely, such as LD_PRELOAD, PATH (if ./Logic is a script that depends on some executables — but the error message isn't consistent with that), etc.
A plausible explanation for why invoking the command from an interactive instance of bash doesn't work, but invoking the command directly from sudo works, is that you are setting this environment in .bashrc, the file that interactive instances of bash runs. Running sudo clears almost all environment variables, hence sudo ./Logic works; but sudo bash followed by ./Logic doesn't work because running bash sets those variables again.
You should set environment variables in .profile (which is executed when the session starts), not in .bashrc. Your symptoms are characteristic of one of the problems with changing environment variables in .bashrc.
The setting for LD_LIBRARY_PATH should probably not be present in your setup files at all. Adding a directory that shadows system libraries is likely to be a source of incompatibilities. If you need it to run a particular program, set LD_LIBRARY_PATH only when running that program (via a shell wrapper, if you want to automate it), don't set it globally.


text:
Q: How to draw a linear regression line in Chart.js I saw other libraries support this but there is very little data for Chart.js. Can anybody indicate me the way to start with a regression line for my graph? This is my code so far:
var datiedu3 = {"labels": ['ok'],
          "datasets": [{label: 'EEE',
                        data: datoa ,

                        backgroundColor: 'rgb(255, 99, 132)',
                        borderWidth: 1,
                        showLine: false}]
           };

function grafo2(dati, opzioni) {
  var grafoline = document.getElementById('Chartline').getContext('2d');
  new Chart(grafoline, {type: 'scatter',data: dati, options: opzioni});
};
// display the data used in dataset[0]:
console.log(datiedu3.datasets[0].data)
grafo2(datiedu3)

I figured I had to create another dataset with a line graph, and put my equation there, but I don't know how to do it and I'm a bit lost.
My whole code is here codepen

A: I typically use  the regression package.
First, add the package as an external script.
Second, clean your data. Just basic checks here:
const clean_data = datoa
    .filter(({ x, y }) => {
      return (
        typeof x === typeof y &&  // filter out one string & one number
        !isNaN(x) &&              // filter out `NaN`
        !isNaN(y) &&
        Math.abs(x) !== Infinity &&
        Math.abs(y) !== Infinity
      );
    })
    .map(({ x, y }) => {
      return [x, y];             // we need a list of [[x1, y1], [x2, y2], ...]
    });

Then run
const my_regression = regression.linear(
  clean_data
);

The result will be something like:
{
  'points': [[4,3.79],[4.75,3.83],[5.5,3.87],.....],
  'equation': [0.05,3.59],
  'r2': 0.26,
  'string': 'y = 0.05x + 3.59'
}

Done. We've got our [x,y] points. So transform the linear regression points into something that chartjs can render:
const useful_points = my_regression.points.map(([x, y]) => {
    return y;
    // or {x, y}, depending on whether you just want y-coords for a 'linear' plot
    // or x&y for a 'scatterplot'
})

You can add these points either as

*

*another line chart dataset

*or with an annotation plugin.


text:
Q: How to count registry key values using vb.net I am using vb.net and I want to count values in windows registry key under HKEY_CURRENT_USER\SOFTWARE\MYAPP. Using the code below:
Dim tempKey As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\MyApp")
Dim count As Integer = tempKey.ValueCount.ToString

but I'm getting an error on the second line saying:

Object reference not set to an instance of an object.

Please I need your help.


text:
Q: How to change maximum memory allowed for function in OpenWhisk I have an OpenWhisk deployment on a Kubernetees cluster that was done using [1]. I know I can change the memory limit for a function by adding --memory x when creating the function. However, if I try to set a value large than 512MB I get the following error.
requirement failed: memory 812 MB exceeds allowed threshold of 536870912 B (code 10543)

I assume this is a configuration set during the setup or within the code. Is there a way to increase this limit to a custom value? if so what is the configuration I need to perform in order to do this?
[1] https://github.com/apache/incubator-openwhisk-deploy-kube

A: The memory limits are configurable for your deployment as of this patch https://github.com/apache/incubator-openwhisk/pull/3148. You can set the max memory in your deployment to suite your purposes.

A: You have to set the environment variable CONFIG_whisk_memory_max=1073741824 on the invoker with a higher value for example 1GB
One way to edit the invoker deployment file
https://github.com/apache/incubator-openwhisk-deploy-kube/blob/master/kubernetes/invoker/invoker-dcf.yml#L74
- name: "CONFIG_whisk_memory_max"
  value: "1073741824"

A: With ansible-playbook, you can specify an option with -e limit_action_memory_max=1073741824 when you deploy openwhisk. The whole command might be like
ansible-playbook openwhisk.yml -e limit_action_memory_max=1073741824 # with other options like '-e invoker_user_memory=25600m'


text:
Q: Using a tcl proc to login to devices I have a tcl (expect) script to log into devices and transfer files. Unfortunately, the files are large, and during the transfer period the ssh connection ends (the files are still transferred though). So I basically have to login again before I can perform more actions on the device. Since the whole login process is long, I put it in a proc. The issue is that the proc logs into the device, but after the login, the script sends the commands to the terminal as, for some reason, the commands no longer reach the device. I cant figure out why the session I logged into in the proc does not carry over to the rest of the script.
proc login {} {
    #login code - it works because I took it from the main script (which works).
    # variables are all declared as global, no errors are thrown. Login is successful
}

login

send "show\r" ;# this command is not sent to the device,
#instead it prints to the terminal. When in the main script,
#these commands would not be printed to the terminal window.

Is there a command I am missing to maybe return the login session to the rest of the script? something similar to the interact command, but to the rest of the script.

A: This is a tricky one. The expect man page says this:

Expect  takes  a rather liberal view of scoping.  In particular, variables read by commands specific
         to the Expect program will be sought first from the local scope, and if not  found,  in  the  global
         scope.   For  example, this obviates the need to place "global timeout" in every procedure you write
         that uses expect.  On the other hand, variables written are always in  the  local  scope  (unless  a
         "global" command has been issued).  The most common problem this causes is when spawn is executed in
         a procedure.  Outside the procedure, spawn_id no longer exists, so the spawned process is no  longer
         accessible simply because of scoping.  Add a global spawn_id to such a procedure.

So, add global spawn_id as the first line of the login proc

A: To make a procedure that evaluates code in its caller's scope, you need to use the uplevel command inside it. This lets you do what is essentially a macro very easily:
proc login {} {
    uplevel {
        # Put your code in here, which might look like this
        spawn ssh user@host ...
        expect Password:
        send $thePassword\r
        expect "bash$"
    }
}

Then, when you use login it will work exactly like the commands you have inside the uplevel in the procedure, as if they'd been typed in place of the login call.
This isn't usually a particularly recommended approach, as it is very easy to make code that is inflexible and inclined to break unexpectedly, but in your case it is a very easy approach since you can easily guarantee to only call login at a sensible place in the overall program structure. (The uplevel command is more commonly used with scripts passed in with arguments — it's just like you're passing in a block — but that's not what you need.)


text:
Q: stdClass object and foreach loops - campaign monitor api I am currently working within the campaign monitor api.
Here is my code:
require_once '../../csrest_general.php';

$auth = array('api_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxx');
$wrap = new CS_REST_General($auth);

$result = $wrap->get_clients();

echo "Result of /api/v3/clients\n
";
if($result->was_successful()) {
    echo "Got clients\n

";
    var_dump($result->response);
} else {
    echo 'Failed with code '.$result->http_status_code."\n

";
    var_dump($result->response);
}
echo '
';

This outputs the following:
array(2) {
  [0]=>
  object(stdClass)#5 (2) {
    ["ClientID"]=>
    string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    ["Name"]=>
    string(12) "xxxxxxxxxxxx"
  }
  [1]=>
  object(stdClass)#6 (2) {
    ["ClientID"]=>
    string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    ["Name"]=>
    string(15) "xxxxxxxxxxxx"
  }

}

How do i go about putting this into a foreach loop? when i try the following:
foreach ($result as $result->response) {
     echo $result;
}

i get this error:

Catchable fatal error: Object of class CS_REST_Wrapper_Result could not be converted to string

A: Credit to Mark Butler for answering this, so I've added his solution:
foreach($result->response as $entry) { echo $entry->ClientID; }

In general terms, getting at the contents of Campaign Monitor results requires you to access the response->Results part of the object returned from the method. Unfortunately, this is not clear from the API or documentation which tends to just 'print_var' the objects returned from the method calls.
For example, listing subscribers in a list:
require_once '/csrest_lists.php';
$sList = new CS_REST_Lists(YOUR_CM_LIST_ID,YOUR_CM_ACCT_KEY);
$sSubscribers = $sList->get_active_subscribers()->response->Results; // return results
foreach($sSubscribers as $s) {
    echo $s->EmailAddress . "\t" . $s->Name . "\t" . $s->State . "\n";
}

Hope this is useful to people - thanks danyo for the question - there are few of these on SO at the moment.
Pete


text:
Q: Calling a query inside a JavaScript loop I am using Node js.
I am trying to call a query within a loop. But it doesn't work as you might think.
I want it to work sequentially. However, the request part is always executed last.
After the loop is complete, the query request is executed. But what I want is to stack sequentially in the log.
Script
try {
  console.log('updateData');
  mssql.connect(config, function(err) {
    console.log('Connect');
    var request = new mssql.Request();
    console.log(JSON.parse(req.body.data));
    var updateObj = JSON.parse(req.body.data);
    console.log(updateObj.length);
    var queryString = "";
    console.log('updateObj :', updateObj);
    for (i = 0; i < updateObj.length; i++) {
      var selectQueryString = "SELECT * FROM tBM WHERE BM_i = " + updateObj[i].c_BM_IDs;
      console.log("Query : " + selectQueryString);
      console.log('loop I :', i);
      request.query(selectQueryString, function(err, recordset) {
        console.log("BM_i : " + recordset.recordset[0].BM_i);
        //request I is Last value of loop I +1
        console.log('request I :', i);
        //org up, org lo is error
        console.log("org up : " + updateObj[i].orgUpIDs);
        console.log("org lo : " + updateObj[i].orgLoIDs);
      });
    }
  });
} catch (err) {
  console.log(err)
}

Log
if updateObj.length = 4

Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 0
Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 1
Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 2
Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 3
BM_i : data
i : 4
Uncaught TypeError: Cannot read property 'orgUpIDs' of undefined

But I want the result like below.
like this
if updateObj.length = 4

Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 0
BM_i : data
i : 0
Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 1
BM_i : data
i : 1
Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 2
BM_i : data
i : 2
Query : SELECT * FROM tBM WHERE BM_i = data
loop I : 3
BM_i : data
i : 3

How can I implement it?
Thanks for your answer


text:
Q: convert string array to integer php Question:
How the best to convert $p=' "'.implode('","', $person).'"'; $p to an integer?
What I have:
I am trying to use an if statement telling $person == false;
$x['date']; is the timestamp in my database.
I have worked out the time difference, now I am trying to make the person disappear if post over 3 seconds.
so I used $t > 3 seconds then the $p ==  false;
The difficulty for my was the $t was implode so it a single string. I was trying to use preg_match, but I don't think this is a good idea.
I am trying to use $difference = settype($t, "integer"); but I am getting a boolean rather than a number.
$diff = array();
$person = array();
foreach($stmt as $x)
{
 $person[] =   $x['names']. $x['ages'];

$posts[] = $x['date'];
$timePosted = new DateTime($posts[] = $x['date']);
echo 'Time Posted : '. $timePosted ->format("d-m-Y H:i:s");
echo "
";

date_default_timezone_set('Europe/London');
$today = date('d-m-Y H:i:s');
echo 'Current time is : '. $today;
echo "
";

$today = new DateTime(date('d-m-Y H:i:s'));
$interval = $timePosted->diff($today);
"Difference " . $interval->d. " days ". $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
echo "
";

$diff[] = $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
$diff[] = $interval->s;  //last array seconds
}
$p=' "'.implode('","', $person).'"';
echo $t= ' "'.implode('","', $diff).'"'."
";
$difference = settype($t, "integer");
echo gettype($difference);
echo "
";

if( $t >3){
  $p == false;
}else{
 echo "its okay, smaller than 3 seconds";
}

A: The problem is you're setting $difference = settype($t, "integer");
The settype function returns a boolean. The value $t should be set to an integer, so to test, use echo gettype($t); instead of echo gettype($difference);
also, you're using a comparison operator instead of the assignment in
if( $t >3){
  $p == false;

it should be
if( $t >3){
  $p = false;


text:
Q: Back up Windows 10 Active Directory machine password I am the (interim) administrator responsible for a number of shared workspaces. I need to do some extensive updates. I usually perform changes on one "source" system and then distribute the NTFS image to all other "target" machines. All machines are part of an Active Directory with roaming user profiles.
The Active Directory is much larger than the department I am responsible for. Management decided that the Active Directory is administrated by an external contractor. They must not be bothered to keep costs low. I do not have administrative rights on the Active Directory, only for the local machines.
As far as I understand, every machine has a distinct machine password randomly generated while joining the Active Directory and changed on a regular interval. I am looking for a way to back up this particular machine password so I can overwrite the installation with the generic image and then re-institute the specific password. Since all machines are already part of the Active Directory, I expect no other differences between the machines. This article says:

Computers store their domain password in their "secrets" storage portion of the registry.

So I assume I can access it somehow.
I could of course perform the upgrades on each machine individually, but that would take an insane amount of time.
This is a variation of Backing up Windows 7 Active Directory configuration, but without a complete re-install.


text:
Q: Is there a specification for bash? like other languages?
I googled it and came up with
https://www.google.com/?gws_rd=ssl#q=bash+specification
which did not list any specifications, just manuals and guides.
Thanks,

A: IEEE 1003.1 ("POSIX") defines a standard "Shell Command Language". You can find the 2016 edition here.
GNU Bash is an implementation of that language, with many extensions. The only specifications for the extended bash language are the bash reference manual and the bash source code.

A: I would consider the manual to be the spec. Bash Manual


text:
Q: What was the most important thing of all that Hari Seldon wished to tell Daneel? In Asimov's Forward the Foundation Hari Seldon's last encounter with the robot Daneel Olivaw is below:

Seldon stood there for a few minutes after Daneel had gone, lost in thought. Suddenly he began moving in the direction of the First Minister's apartment. Seldon had one more thing to tell Daneel–the most important thing of all. Seldon hesitated in the softly lit hallway before entering. But the room was empty. The dark robe was draped over a chair. The First Minister's chambers echoed Hari's last words to the robot: "Good-bye, my friend." Eto Demerzel was gone; R. Daneel Olivaw had vanished.

What did people interpret as the most important thing?

A: Spoiler alert, my answer has to do with Asimov's Foundation and Earth.  In that book, it's revealed at the end that there is a problem with Seldon's Psychohistory Laws in that they assume a human-only universe.  So even if Seldon's Foundation dream is successful, whose to say that aliens from another galaxy won't destroy our human civilization.  Trevize realizes this in Foundation and Earth (Daneel does not it seems), and when sharing this theory he compares it to the discovery of the Zeroth Law followed by Daneel.  The Zeroth Law is discovered last but is the most important law in the Laws of Robotics, just like this aliens theory.  So in Forward the Foundation, right before Daneel and Hari split for good, Daneel mentions the "Zeroth Law" and the word "humanity".  Then Daneel quickly changes the subject by telling Hari he still has Dors, and here Hari pauses for a moment before shaking Daneel's hand and saying goodbye.  That pause shows Hari is thinking something but he's not sure what, and the mention of Dors, who Hari loves, derails his thoughts.  Then Daneel leaves, Hari stands there for a few minutes lost in thought, and then he figures it out - "the most important thing of all", which we already know from Foundation and Earth is that Psychohistory assumes intelligence lies with humanity only.  If Hari had been able to tell this to Daneel, it may have helped Daneel in his following of the Zeroth Law.  That's why it was so important to tell Daneel.
So as I just said, I bet he figured out the same thing Trevize figured out.  It makes sense, and that way Hari remains the smartest figure in the series as he's not to be out-done by the always-one-step-ahead-always-right Trevize, which is how it should be.
I read somewhere that Asimov wrote the first three parts of Forward the Foundation completely, but the final part was in draft form, though largely done. Maybe he had planned to answer this riddle in that final part but never got the chance to.  Why whoever put the finishing touches on this part for him didn't put in the answer, who knows.  Maybe they didn't want to corrupt the work by putting in an answer not first verified by Asimov, so they just left the riddle unsolved.  I suppose it's possible that Asimov expected people to solve this riddle by themselves, but I don't think so.  That's not really his style I think.

A: "Good bye my friend." Hari has a friendship, in the deepest sense of that word, with a man-made being. (Heck, the love of his life is likewise a non-sentient being.) The notion comes to him, as he stands there, that this is significant. He needs say it out loud to R. Daneel, because it would matter to him. Alas, too late.
Yes of course this relates to the notion that R. Daneel & his mates could themselves be a threat to the zeroth law, never mind aliens. As with all real art, we get to incorporate our own notions after the fact. Interesting to speculate whether and when Hari might have consciously made this connection. And each of us gets to believe what we like.
But Asimov was not a coy writer. He says what he means and means what he says.

A: It's not aliens from distant galaxy. What Hari had to say to Daneel was that robot intelligence and the Zeroth law would be colliding at some point (seen in "End of Foundation")
As Daneel was actively involved he was also reponsible for the Mule, the psychohistory indirectly and Galaxia.
Psychohistory only involved Humans, is the key.

A: Surely it's just what he did say: goodbye, and that Daneel was his friend.

A: The top-voted and accepted answer in this thread says that "the most important thing" that Hari Seldon wanted to tell Daneel Olivaw was the basic psychohistorical assumption that "intelligence lies only with humanity".
However, there are a few flaws with that answer.
Firstly, at the time the scene in question takes place, when Daneel disappears as Eto Demerzel, Hari Seldon had not developed psychohistory. This is the first section of 'Forward the Foundation', when Seldon is still forty years old, and still working out psychohistory. He can't have worked out its basic assumptions yet.
Secondly, even if Seldon did already know this assumption that psychohistory assumes intelligence lies only with humanity, why didn't he tell anyone? According to this theory, Seldon knew this assumption at 40 years old. He hadn't created the Foundation yet, or the Second Foundation - they were thirty years in the future.
In the second chapter of '... And Now You Don't' (collected as "Search by the Foundation" in 'Second Foundation'), a Student tells the First Speaker of the Second Foundation that:

The laws of Psychohistory are statistical in nature and are rendered invalid if the actions of individual men are not random in nature. If a sizable group of human beings learned of key details of the Plan, their actions would be governed by that knowledge
  and would no longer be random in the meaning of the axioms of Psychohistory. In other words, they would no longer be perfectly predictable.

Later, in the fourth chapter of the same story, the First Speaker tells the Student that:

Psychostatistics by its very nature has no meaning when applied to less than planetary numbers.

These axioms were repeated by Golan Trevize a century later in 'Foundation and Earth':

I knew nothing about Seldon's Plan except for the two axioms on which it is based: one, that there be involved a large enough number of human beings to allow humanity to be treated
  statistically as a group of individuals interacting randomly; and second, that humanity not know the results of psychohistorical conclusions before the results are achieved.

The Second Foundationers, and even the First Foundationers, were fully aware of these two axioms, which they would have learned from Seldon's own work nearly four hundred years earlier. Why not the third? If Seldon had known of this assumption, why didn't he record it along with the other two? As Trevize says, "Maybe the third requirement is an assumption so taken for granted that no one ever thinks of mentioning it." It looks like Seldon himself never recognised this assumption.
Thirdly, that answer states that "Asimov wrote the first three parts of Forward the Foundation completely, but the final part was in draft form, though largely done" and then hypothesises that the person(s) who completed the book "didn't want to corrupt the work by putting in an answer not first verified by Asimov, so they just left the riddle unsolved". However, the section where Daneel/Demerzel leaves is the first section of 'Forward the Foundation', not the last. It was therefore written by Asimov, and is as Asimov intended. (He has himself written that he didn't like to go back and re-write his own works. He did a first draft, then corrected it for spelling and minor wording issues, and that's it.)
So:

*

*Seldon hadn't developed psychohistory at the time that Daneel/Demerzel left.

*Seldon didn't know this basic assumption about psychohistory applying only to humans.

*The text was written by Asimov himself, as he intended it to be: there's no unresolved mystery about what he might have been thinking.
What, then, was "the most important thing of all" that Hari wanted to tell Daneel?
I posit that Asimov told us what that most important thing was. It's what Hari said to the empty room: "Good-bye, my friend." Friendship is important. At the time Daneel left, he and Seldon had known each other for about a decade: a quarter of Seldon's life. Hari had said "Good-bye, Daneel", but he hadn't said that extra word: "friend".
Asimov did like mystery, but he also liked to reveal the solution to mystery. If he hinted at something, it was either extremely obvious or it would be revealed later. This mysterious "most important thing" to say to Daneel was both obvious and revealed later. The answer is right there in the text, staring us straight in the face.
The most important thing of all for Hari Seldon to tell Daneel was that he was Hari's friend.


text:
Q: Cannsandra Driver & jnr-Unixsocket - java.lang.UnsatisfiedLinkError: could not load FFI provider jnr.ffi.provider.jffi.Provider I am using cassandra and jnr-unix socket in my project and both uses jnr-ffi. Not getting any error in my local, but getting error in test env.
The versions are,
Cassandra version - 3.3.2
jnr-unixsocket - 0.12

Error happens on calling UnixSocketChannel.open() from my code.
Code from the hierarchy,
public ApacheUnixSocket() throws IOException {
        this.inner = UnixSocketChannel.open();
        this.addr = null;
    }

The complete trace is as follows. This error happens only when i call Unisocket, but rest all looks good. Service starts as expected and able to communicate with cassandra db using the driver. Still, i see cassandra trace also. Bit confusing ...
Error :-
java.lang.UnsatisfiedLinkError: could not load FFI provider jnr.ffi.provider.jffi.Provider
    at jnr.ffi.provider.InvalidProvider$1.loadLibrary(InvalidProvider.java:48)
    at jnr.ffi.LibraryLoader.load(LibraryLoader.java:290)
    at jnr.unixsocket.Native.<clinit>(Native.java:76)
    at jnr.unixsocket.UnixSocketChannel.<init>(UnixSocketChannel.java:94)
    at jnr.unixsocket.UnixSocketChannel.open(UnixSocketChannel.java:49)
    at com.test.service.docker.ApacheUnixSocket.<init>(ApacheUnixSocket.java:36)
    at com.test.service.docker.UnixConnectionSocketFactory.createSocket(UnixConnectionSocketFactory.java:42)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:118)
    at org.apache.http.impl.conn.BasicHttpClientConnectionManager.connect(BasicHttpClientConnectionManager.java:338)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at com.test.service.docker.DockerClient.getData(DockerClient.java:123)
    at com.test.service.docker.DockerClient.updateContainerMetrics(DockerClient.java:88)
    at com.test.service.docker.DockerContainerMetrics.refreshDockerStats(DockerContainerMetrics.java:109)
    at com.test.service.docker.DockerContainerMetrics.lambda$start$1(DockerContainerMetrics.java:78)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ExceptionInInitializerError: null
    at jnr.ffi.provider.jffi.NativeRuntime.getInstance(NativeRuntime.java:49)
    at jnr.ffi.provider.jffi.Provider.<init>(Provider.java:29)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.getInstance(FFIProvider.java:68)
    at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.<clinit>(FFIProvider.java:57)
    at jnr.ffi.provider.FFIProvider.getSystemProvider(FFIProvider.java:35)
    at jnr.ffi.LibraryLoader.create(LibraryLoader.java:73)
    at com.datastax.driver.core.Native$LibCLoader.<clinit>(Native.java:108)
    at com.datastax.driver.core.Native.isGettimeofdayAvailable(Native.java:190)
    at com.datastax.driver.core.ClockFactory.newInstance(Clock.java:51)
    at com.datastax.driver.core.AbstractMonotonicTimestampGenerator.<init>(AbstractMonotonicTimestampGenerator.java:43)
    at com.datastax.driver.core.LoggingMonotonicTimestampGenerator.<init>(LoggingMonotonicTimestampGenerator.java:49)
    at com.datastax.driver.core.AtomicMonotonicTimestampGenerator.<init>(AtomicMonotonicTimestampGenerator.java:50)
    at com.datastax.driver.core.AtomicMonotonicTimestampGenerator.<init>(AtomicMonotonicTimestampGenerator.java:37)
    at com.datastax.driver.core.policies.Policies.defaultTimestampGenerator(Policies.java:121)
    at com.datastax.driver.core.policies.Policies$Builder.build(Policies.java:286)
    at com.datastax.driver.core.Cluster$Builder.getConfiguration(Cluster.java:1317)
    at com.datastax.driver.core.Cluster.<init>(Cluster.java:113)
    at com.datastax.driver.core.Cluster.buildFrom(Cluster.java:178)
    at com.datastax.driver.core.Cluster$Builder.build(Cluster.java:1335)
    at com.test.data.cassandra.spring.boot.CassandraAutoConfiguration$CassandraBuilderFactory.buildCluster(CassandraAutoConfiguration.java:133)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1316)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1282)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1205)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1096)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory$OptionalDependencyFactory.createOptionalDependency(DefaultListableBeanFactory.java:1602)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1053)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at com.test.service.Application.main(Application.java:90)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
    at org.springframework.boot.loader.WarLauncher.main(WarLauncher.java:59)
Caused by: java.lang.IllegalStateException: Can't overwrite cause with java.lang.UnsatisfiedLinkError: java.lang.UnsatisfiedLinkError: No such file or directory
    at com.kenai.jffi.internal.StubLoader.loadFromJar(StubLoader.java:364)
    at com.kenai.jffi.internal.StubLoader.load(StubLoader.java:254)
    at com.kenai.jffi.internal.StubLoader.<clinit>(StubLoader.java:434)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.kenai.jffi.Init.load(Init.java:68)
    at com.kenai.jffi.Foreign$InstanceHolder.getInstanceHolder(Foreign.java:49)
    at com.kenai.jffi.Foreign$InstanceHolder.<clinit>(Foreign.java:45)
    at com.kenai.jffi.Foreign.getInstance(Foreign.java:103)
    at com.kenai.jffi.Type$Builtin.lookupTypeInfo(Type.java:242)
    at com.kenai.jffi.Type$Builtin.getTypeInfo(Type.java:237)
    at com.kenai.jffi.Type.resolveSize(Type.java:155)
    at com.kenai.jffi.Type.size(Type.java:138)
    at jnr.ffi.provider.jffi.NativeRuntime$TypeDelegate.size(NativeRuntime.java:178)
    at jnr.ffi.provider.AbstractRuntime.<init>(AbstractRuntime.java:48)
    at jnr.ffi.provider.jffi.NativeRuntime.<init>(NativeRuntime.java:57)
    at jnr.ffi.provider.jffi.NativeRuntime.<init>(NativeRuntime.java:41)
    at jnr.ffi.provider.jffi.NativeRuntime$SingletonHolder.<clinit>(NativeRuntime.java:53)
    at jnr.ffi.provider.jffi.NativeRuntime.getInstance(NativeRuntime.java:49)
    at jnr.ffi.provider.jffi.Provider.<init>(Provider.java:29)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.getInstance(FFIProvider.java:68)
    at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.<clinit>(FFIProvider.java:57)
    at jnr.ffi.provider.FFIProvider.getSystemProvider(FFIProvider.java:35)
    at jnr.ffi.LibraryLoader.create(LibraryLoader.java:73)
    at com.datastax.driver.core.Native$LibCLoader.<clinit>(Native.java:108)
    at com.datastax.driver.core.Native.isGettimeofdayAvailable(Native.java:190)
    at com.datastax.driver.core.ClockFactory.newInstance(Clock.java:51)
    at com.datastax.driver.core.AbstractMonotonicTimestampGenerator.<init>(AbstractMonotonicTimestampGenerator.java:43)
    at com.datastax.driver.core.LoggingMonotonicTimestampGenerator.<init>(LoggingMonotonicTimestampGenerator.java:49)
    at com.datastax.driver.core.AtomicMonotonicTimestampGenerator.<init>(AtomicMonotonicTimestampGenerator.java:50)
    at com.datastax.driver.core.AtomicMonotonicTimestampGenerator.<init>(AtomicMonotonicTimestampGenerator.java:37)
    at com.datastax.driver.core.policies.Policies.defaultTimestampGenerator(Policies.java:121)
    at com.datastax.driver.core.policies.Policies$Builder.build(Policies.java:286)
    at com.datastax.driver.core.Cluster$Builder.getConfiguration(Cluster.java:1317)
    at com.datastax.driver.core.Cluster.<init>(Cluster.java:113)
    at com.datastax.driver.core.Cluster.buildFrom(Cluster.java:178)
    at com.datastax.driver.core.Cluster$Builder.build(Cluster.java:1335)
    at com.test.cassandra.spring.boot.autoconfigure.CassandraAutoConfiguration$CassandraBuilderFactory.buildCluster(CassandraAutoConfiguration.java:133)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1316)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1282)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1205)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1096)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory$OptionalDependencyFactory.createOptionalDependency(DefaultListableBeanFactory.java:1602)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1053)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at com.test.service.Application.main(Application.java:90)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
    at org.springframework.boot.loader.WarLauncher.main(WarLauncher.java:59)
java.lang.UnsatisfiedLinkError: Can't load library: /usr/lib/libjffi-1.2.so
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1827)
    at java.lang.Runtime.load0(Runtime.java:809)
    at java.lang.System.load(System.java:1086)
    at com.kenai.jffi.internal.StubLoader.loadFromBootPath(StubLoader.java:316)
    at com.kenai.jffi.internal.StubLoader.load(StubLoader.java:249)
    at com.kenai.jffi.internal.StubLoader.<clinit>(StubLoader.java:434)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.kenai.jffi.Init.load(Init.java:68)
    at com.kenai.jffi.Foreign$InstanceHolder.getInstanceHolder(Foreign.java:49)
    at com.kenai.jffi.Foreign$InstanceHolder.<clinit>(Foreign.java:45)
    at com.kenai.jffi.Foreign.getInstance(Foreign.java:103)
    at com.kenai.jffi.Type$Builtin.lookupTypeInfo(Type.java:242)
    at com.kenai.jffi.Type$Builtin.getTypeInfo(Type.java:237)
    at com.kenai.jffi.Type.resolveSize(Type.java:155)
    at com.kenai.jffi.Type.size(Type.java:138)
    at jnr.ffi.provider.jffi.NativeRuntime$TypeDelegate.size(NativeRuntime.java:178)
    at jnr.ffi.provider.AbstractRuntime.<init>(AbstractRuntime.java:48)
    at jnr.ffi.provider.jffi.NativeRuntime.<init>(NativeRuntime.java:57)
    at jnr.ffi.provider.jffi.NativeRuntime.<init>(NativeRuntime.java:41)
    at jnr.ffi.provider.jffi.NativeRuntime$SingletonHolder.<clinit>(NativeRuntime.java:53)
    at jnr.ffi.provider.jffi.NativeRuntime.getInstance(NativeRuntime.java:49)
    at jnr.ffi.provider.jffi.Provider.<init>(Provider.java:29)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.getInstance(FFIProvider.java:68)
    at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.<clinit>(FFIProvider.java:57)
    at jnr.ffi.provider.FFIProvider.getSystemProvider(FFIProvider.java:35)
    at jnr.ffi.LibraryLoader.create(LibraryLoader.java:73)
    at com.datastax.driver.core.Native$LibCLoader.<clinit>(Native.java:108)
    at com.datastax.driver.core.Native.isGettimeofdayAvailable(Native.java:190)
    at com.datastax.driver.core.ClockFactory.newInstance(Clock.java:51)
    at com.datastax.driver.core.AbstractMonotonicTimestampGenerator.<init>(AbstractMonotonicTimestampGenerator.java:43)
    at com.datastax.driver.core.LoggingMonotonicTimestampGenerator.<init>(LoggingMonotonicTimestampGenerator.java:49)
    at com.datastax.driver.core.AtomicMonotonicTimestampGenerator.<init>(AtomicMonotonicTimestampGenerator.java:50)
    at com.datastax.driver.core.AtomicMonotonicTimestampGenerator.<init>(AtomicMonotonicTimestampGenerator.java:37)
    at com.datastax.driver.core.policies.Policies.defaultTimestampGenerator(Policies.java:121)
    at com.datastax.driver.core.policies.Policies$Builder.build(Policies.java:286)
    at com.datastax.driver.core.Cluster$Builder.getConfiguration(Cluster.java:1317)
    at com.datastax.driver.core.Cluster.<init>(Cluster.java:113)
    at com.datastax.driver.core.Cluster.buildFrom(Cluster.java:178)
    at com.datastax.driver.core.Cluster$Builder.build(Cluster.java:1335)
    at com.test.cassandra.spring.boot.autoconfigure.CassandraAutoConfiguration$CassandraBuilderFactory.buildCluster(CassandraAutoConfiguration.java:133)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)


text:
Q: How to display custom properties from ApplicationUser in view in asp.net mvc 4? I added custom properties to ApplicationUser like this:
public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Skype { get; set; }
        public string About { get; set; }
        public Photo Avatar { get; set; }
    }

I need to display all users with their custom properties in view. I used this  tutorial. But Index view works with only properties from IdentityUser.
How to get access to custom properties in Index view?

A: What you can do is in your controller pass the ApplicationUser to the view
return view(applicationUser)
However what you should do is create a new view model which is simply a class like so
public class ApplicationUserViewModel : ApplicationUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Skype { get; set; }
        public string About { get; set; }
        public Photo Avatar { get; set; }
    }

Then in your controller you would populate the new ApplicationUserViewModel and then pass that into your view.
Just make sure in your View it is expecting the correct ViewModel
@model ApplicationUserViewModel example


text:
Q: Ubuntu 13.04 Window Title Font How can I change the font for the window title in 13.04 Ubuntu?

Original text:
Wie kann ich die Schrift für den Fenstertitel bei Ubuntu 13.04 ändern?

A: Download Unity tweak tool in the software center. This app let's you adjust your fonts in appearance --> fonts.


text:
Q: How to use the Guava ListenableFuture and the Futures.chain() methods I have a homework task that requires me to learn how to use the Guava concurrency library.
In the task I have several thread pools, where each one is controlled by an individual object.
Each pool has several working threads that perform simple tasks (mostly emulating doing stuff by using Thread.sleep(long)) and all those simple tasks are stored in a container object that emulates a messageboard.
Each simple task has a dependency list of other tasks, and it cannot be executed until all of those tasks are completed.
How can I benefit from the Guava library using the ListenableFuture and the Futures.chain()?
I have searched everywhere for some extensive example code online, but didn't find anything that I understand how to use.

A: As Louis mentions, I think that Futures.allAsList etc. could be useful for you. However, I think that Futures.chain does seem useful and appropriate for the situation you describe. Since this is an assignment meant to challenge you, I'm not going to say any more than this: Futures.chain allows you to submit a task for execution upon completion of another task, and it returns a new ListenableFuture representing the result of that task. How does that apply to what you're trying to do?

A: You might be interested in reading the presentation slides on Guava util.concurrent, linked on the Guava homepage (slide 11 and onward). They really helped me crystallize my understanding of ListenableFuture and why it's so useful.
My guess is that the goal of your assignment is to understand how Futures work, and how Guava's ListenableFuture and Futures.chain() simplifies their use when coordinating multiple tasks.
The only open source code that comes to mind that uses ListenableFuture is sitebricks-mail:

*

*MailClient interface

*NettyImapClient implementation
I don't know if it uses Futures.chain(), though.

A: I don't think Futures.chain() is the answer here, if the primary issue is dealing with task dependency lists.  More likely is Futures.allAsList or Futures.successfulAsList, which take multiple futures, and return a future that returns only after all of the input futures have succeeded or failed.


text:
Q: Exception safety in C++ when adding to multiple std containers I have some code that adds to a std::vector and a std::map after creating an object.
v.push_back(object);     // std::vector
m[object->id] = object;  // std::map

I want to make this have a strong exception guarantee. Normally, to make operations like these atomic, I would implement a swap method for each container, and call all of the functions that could throw on temporary copies of the container:
vector temp_v(v);
map temp_map(m);

temp_v.push_back(object);
temp_m[object->id] = object;

// The swap operations are no-throw
swap(temp_v, v)
swap(temp_m, m)

However, making temporary copies of the entire vector and map seems very expensive. Is there any way to implement a strong exception guarantee for this function without the expensive copies?

A: General Case
Technically, only one copy is required:

*

*Copy the vector

*Update the copy

*Update the map

*Swap the copy and the original vector

Another option is catch-roll-back-and-rethrow:
  v.push_back(object);
  try
  {
    m.insert(object->id, object); // Assuming it cannot be present yet
  }
  catch(..)
  {
    v.pop_back();
    throw;
  }

Or the other way around. I picked this order because the vector::pop_back() is guaranteed not to fail.
UPDATE: If object->id could be present, see Grizzly's answer for a solution.

Specific Case for Pointers
However, as you are using object->, you might be storing pointers. The copy-constructor of a pointer cannot throw, and we can use that fact to simplify the code:
v.reserve(v.size() + 1);
m[object->id] = object; // can throw, but not during the assignment
v.push_back(object); // will not throw: capacity is available, copy constructor does not throw

And if you are really worried about frequent resizing:
if (v.capacity() == v.size()) v.resize(v.size()*2); // or any other growth strategy
m[object->id] = object;
v.push_back(object);

A: I think this is a situation where using try-catch is the correct manner of handling it. If the access to the map throws you undo the operation on the vector and rethrow:
v.push_back(object);
try
{
  m[object->id] = object;
}
catch(...)
{
  v.pop_back();
  throw;
}

However this will still not give you a strong guarantee, since operator[] on maps is a problematic instruction for exception safety (if the element is not in the map an object is default constructed, which will stay in the map, if the operator= throws (very unlikely in this case, since you seem to be storing pointers, but still).
Therefore I would rewrite it as
try
{
  auto iter = m.find(object->id);//used auto for shorter code,
  if(iter == m.end())
    m.insert(std::make_pair(object->id, object);
 else
   iter->second = object;
}

A: You can use a scopeguard object that rolls back the operations when destroyed unless it is told not to. This approach is outlined in Generic: Change the Way You Write Exception-Safe Code — Forever.
E.g. something like:
container1.push_back(a);
Guard g(bind(&ContainerType::pop_back, &container1));
container2.push_back(a);
// ...
g.dismiss();

A: I suppose you could roll your own RAII-type object:
template<typename T>
class reversible_vector_pusher
{
  private:
    std::vector<T> * const ptrV;
    bool committed = false;
  public:
    reversible_vector_pusher(std::vector<T> & v, const T & obj) : ptrV(&v)
        { v.push_back(obj); }
    void commit()
        { committed = true; }
    ~reversible_vector_pusher()
    {
        if(! committed)
             ptrV->pop_back();
    }
};

reversible_vector_pusher<...> rvp(v, object); // replace ... with object's type
m[object->id] = object;
rvp.commit();

(I chose to reverse the vector-push because it's always reversible, whereas with a map you might have overwritten another element that you'd have to try to get back.)


text:
Q: Webpage stops reciving FastAPI websocket events So I'm transfering from node into FastAPI (Because it's more convinient for me)
And I have a webpage (full code here), which was working in node, but when transferred to FastAPI only starting websocket messages get through, the one in loop get lost (though problem is only with this particular page, other pages in project receives them). Here's FastAPI code:
@app.websocket("/websocket")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_json({"event": "infobar", "content": info_bar})
    await websocket.send_json({"event": "show_emblem", "value": emblem_visible})
    await websocket.send_json({"event": "predefs", "content": predefs})
    await websocket.send_json({"event": "candidates", "content": candidates})
    await websocket.send_json({"event": "timer_state", "state": timer.__dict__()})
    while True:
        data = await websocket.receive_json()
        print(data)
        if data["event"] == "timer":
            if data["type"] == "start" and not timer.running:
                timer.running = True
                timer.started_at = datetime.datetime.now()
                await websocket.send_json({"event": "timer_state", "state": timer.__dict__()})
            elif data["type"] == "stop":
                UpdateTimer()
                timer.running = False
                await websocket.send_json({"event": "timer_state", "state": timer.__dict__()})

            elif["type"] == "set":
                timer.running = False
                timer.time = int(data["time"])
                await websocket.send_json({"event": "timer_state", "state": timer.__dict__()})
        else:
            print(data)
            await websocket.send_json({"event": "Test_event", "content": "Missing"})
            print("Dispatching")


text:
Q: Probability Mass Function of a Binomial Distribution in Python I am using Python3 to compute the Probability Mass Function (PMF) of this wikipedia example:

I tried to follow this scipy documentation:
https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.stats.binom.html
The documentation clearly says:
Notes

The probability mass function for binom is:

binom.pmf(k) = choose(n, k) * p**k * (1-p)**(n-k)

for k in {0, 1,..., n}.

binom takes n and p as shape parameters.

Well, I tried to implement this having the wikipedia example in mind. This is my code:
from scipy.stats import binom

n = 6

p = 0.3

binom.pmf(k) = choose(n, k) * p**k * (1-p)**(n-k)

print  (binom.pmf(1))

However, I get this error's message:
  File "binomial-oab.py", line 7
    binom.pmf(k) = choose(n, k) * p**k * (1-p)**(n-k)
    ^
SyntaxError: can't assign to function call

How can I solve this?

A: You can use scipy.stats.binom.pmf(k) for this. For example:
n = 10
p = 0.3
k = np.arange(0,21)
binomial = scipy.stats.binom.pmf(k,n,p)
print(binomial)

A: Just call binom.pmf(1, n, p) to get your result for k=1. The expression in the documentation is just showing you how the PMF is mathematically defined and is not an actual code snippet that you are expected to execute.


text:
Q: How to set bottom_margin equal to its height? I want to set bottom margin equal to view's/layout's height.
 <FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
    //Main layout
    <LinearLayout
        android:id="@+id/content_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        .
        .
        .
    </LinearLayout>

    //Bottom drawer layout
    <LinearLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        .
        .
        .
    </LinearLayout>
</FrameLayout>

How to add bottom margin to second child exactly of its height so that it goes out of the screen?
Is it possible through xml attribute?

A: You cant get height of a view in xml.
You can get height of a view dynamically by using ViewTreeObserver, then you can set the margin for that View.
Below is a way you can do dynamically:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.layoutid);

final ViewTreeObserver vto = linearLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {
            //get LayoutWidth and height here
            int layoutWidth = linearLayout.getWidth();
            int layoutHeight = linearLayout.getHeight();

            //set layout margin here
            LinearLayout.LayoutParams llp = linearLayout.getLayoutParams();
            llp.bottomMargin = layoutHeight;
            linearLayout.setLayoutParams(llp);

            //Then remove layoutChange Listener
            ViewTreeObserver vto = linearLayout.getViewTreeObserver();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                vto.removeOnGlobalLayoutListener(this);
            } else {
                vto.removeGlobalOnLayoutListener(this);
            }
        }
    });


text:
Q: Search processes by executable name, excluding those without a TTY? I'm trying to search for processes that have a given executable name and have an associated TTY.
My use-case is an attempt to identify running abduco client processes. Since abduco runs client processes with an associated TTY and server processes without one, I can use that to distinguish between them.
So far, I've come up with two approaches. I could run:
ps ao pid,comm | grep abduco

which by default (without adding the x option) only considers processes with an associated TTY.
Or I could leverage ps -C to select processes by executable name, rather than having to pipe to grep for that part. But that will include processes that have no associated TTY, and it doesn't look like ps provides an option to change that. So I'd have to do some post-processing to filter out processes that reported a TTY of ?:
ps -C abduco o pid,tty

Is there a cleaner solution?

A: Note that each system will have their own ps command, each with their own syntax and features.
POSIX does specify a ps command though with many of the options optional.
None of the options you used are standard. ps ao is BSD-style syntax, ps -C is a HP/UX option. You must be using the ps implementation from procps as that one did try and merge features from many different ps implementations.
Even with that one, I'm not aware that it can be told to report processes with a given name and with a controlling tty.
So you'd be left with post-processing:
ps -o pid= -o tty= -C abduco | awk '$2 != "?" {print $1}'

In any case, note that -C "$string" matches on process names, not really executable name. On Linux the process name is a string of up to 15 bytes that is an attribute of a process. It's inherited from the parent process and changed every time a process does a execve() system call, in which case the process name is changed to the first 15 bytes of the base name of the file path passed to execve() (so in that sense, that's an executable name), or with a prctl(PR_SET_NAME) call (though that's rarer).
To match on the executable whose code the process is running, you'd need to look at the /proc/<pid>/exe symlink (on Linux).
For instance, with zsh:
print -rC1 -- /proc/*/exe(e['[[ $REPLY -ef =bzip2 ]]']:h:t)

Would report the pids of the processes running the bzip2 command (whose /proc/pid/exe, after symlink resolution is the same file as the first occurrence of a bzip2 in $PATH).
And to restrict to the ones with tty:
() {
  print -rC1 -- /proc/$^@/exe(e['[[ $REPLY -ef =bzip2 ]]']:h:t)
} $(ps ao pid=)

However, since the bzip2, bunzip2, bzcat are all the same file, matching on executable is actually less useful than matching on process name, as that command wouldn't differentiate between processes that had invoked bzip2 or bunzip2 or bzcat.
The bzcat aka bzip2 aka bunzip2 looks at the basename of its argv[0] to decide whether to compress / uncompress / bzcat, so strictly speaking that should be what we would want to match on (found in /proc/pid/cmdline on Linux), but that's likely not worth the effort as over 99% of the time, the basename of that argv[0] is the same (though not truncated) as that of the executable passed to execve().


text:
Q: Sqrt and Pow in Cassandra NoSQL (Nearest neighbor) Is there any way to use this Math functions in Cassandra NoSQL? I found the function below while looking for a way to get the nearest row given a latitude and longitude.
SELECT latitude, longitude, sqrt(
    pow(69.1 * (latitude - [startlat]), 2) +
    pow(69.1 * ([startlng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < 25 ORDER BY distance;

A: Math functions are not built in to CQL, but there is a new feature in Cassandra 2.2 called user defined functions which allow you to create math functions.  I'm not sure if you can use the result of the math operation to restrict the rows returned.
Here is an example:
cqlsh> CREATE OR REPLACE FUNCTION fLog (input double) CALLED ON NULL INPUT RETURNS double LANGUAGE java AS 'return Double.valueOf(Math.log(input.doubleValue()));';

See more details here.
Probably the more common way to do this is outside of CQL where you would do a map/reduce type operation to map rows to distances and reduce it to the distances less than 25.  That could be done using Spark or programmatically with a Cassandra java client, etc.


text:
Q: How do packets know which device to go to? My level of knowledge is really basic, but as I understand when you search up say a website you send a server a request for the information of that webpage, then the server sends back packets which contain all that information. I was told these packets know where to go by the IP address you gave to the server upon the request, but that IP only gets the packets to your router, how does the router then know which device in the network requested those packets? I understand that each device has a MAC address but since you did not send the Mac address in the original request, the packets being sent back can't contain it surely? I tried looking online but really couldn't find any explanation for this. If someone could simply explain it to me I would be very grateful :)

A: IP packets work very much like the U.S. Postal Service. Consider each packet an envelope with a TO: and FROM: address. When you mail the letter, it goes to your local post office. The local post office looks at the TO: address's zip code. The local post office then routes it to the next nearest post office to that zip code, and then the next, and the next, etc, until the letter arrives at the local post office of the recipient.
When your computer sends an IP packet, say an HTTP GET request to google.com, the packet first leaves your network interface, whether its WiFi or Ethernet, and arrives at your router. Well, actually, first your computer has to resolve google.com to an IP address via DNS, but that's another discussion... Your router then consults it's ARP (address resolution protocol) table to see if it's a local device connected to WiFi or the router's switch. If not, then it's sent up-stream to the router's assigned gateway IP address (which is assigned by your ISP).
The packet arrives at your local ISP's edge router. That router consults its routing tables to determine if it's an up-stream, peer, or down-stream route. It's up-stream, so the edge router sends the packet to the next router upsteam, and again, and again, until it gets to your ISP's main router, which is likely connected to a high-capacity fiber-optic backbone.
The packet then travels to Google's nearest geographical datacenter and the whole routing process is reversed until it gets to one of many Google HTTP servers.
Each time the packet stops at a router to determine the next port to go out on, we call that a "hop". You can actually see these hops in action by using the traceroute utility built in to most operating systems.
In Windows: tracert google.com
In Linux/MacOS: traceroute google.com
BTW, you're correct that every device on any network has a unique MAC (media access control) address. These IP address to MAC address conversions are stored in ARP tables. They are cleared when a switch or router is reset. In order to discover a device's MAC address for a given IP address, your network card sends out a WHOIS packet to the network broadcast address. The switch knows to send these packets to every port and if the device that has this MAC address is connected, it will respond "right here!" :-)


text:
Q: Issue after Spark Installation on Windows 10 This is a cmd log that I see after running spark-shell command (C:\Spark>spark-shell). As I understand, it's mainly an issue with Hadoop. I use Windows 10. Can somehow please with the below issue?
C:\Users\mac>cd c:\
c:\>winutils\bin\winutils.exe chmod 777 \tmp\hive
c:\>cd c:\spark
c:\Spark>spark-shell

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/05/14 13:21:25 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/05/14 13:21:34 WARN General: Plugin (Bundle) "org.datanucleus.store.rdbms" is already registered. Ensure you dont have multiple JAR versions of the same plugin in the classpath. The URL "file:/c:/Spark/bin/../jars/datanucleus-rdbms-3.2.9.jar" is already registered, and you are trying to register an identical plugin located at URL "file:/C:/Spark/jars/datanucleus-rdbms-3.2.9.jar."
17/05/14 13:21:34 WARN General: Plugin (Bundle) "org.datanucleus" is already registered. Ensure you dont have multiple JAR versions of the same plugin in the classpath. The URL "file:/c:/Spark/bin/../jars/datanucleus-core-3.2.10.jar" is already registered, and you are trying to register an identical plugin located at URL "file:/C:/Spark/jars/datanucleus-core-3.2.10.jar."
17/05/14 13:21:34 WARN General: Plugin (Bundle) "org.datanucleus.api.jdo" is already registered. Ensure you dont have multiple JAR versions of the same plugin in the classpath. The URL "file:/c:/Spark/bin/../jars/datanucleus-api-jdo-3.2.6.jar" is already registered, and you are trying to register an identical plugin located at URL "file:/C:/Spark/jars/datanucleus-api-jdo-3.2.6.jar."
17/05/14 13:21:48 WARN ObjectStore: Failed to get database global_temp, returning NoSuchObjectException
Spark context Web UI available at http://192.168.1.9:4040
Spark context available as 'sc' (master = local[*], app id = local-1494764489031).
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.1.1
      /_/

Using Scala version 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131)
Type in expressions to have them evaluated.
Type :help for more information.

A: There's no issue in your output. These WARN messages can simply be ignored.
In other words, it looks like you've installed Spark 2.1.1 on Windows 10 properly.
To make sure you installed it properly (so I could remove looks from above sentence) is to do the following:
spark.range(1).show

That by default will trigger loading Hive classes that may or may not end up with exceptions on Windows due to Hadoop's requirements (and hence the need for winutils.exe to work them around).


text:
Q: How to get a list of all domains? I'm trying to get all domains that are available in the Windows Login dialog (in the Domain dropdown).
I've tried the following code but it only returns the domain I am logged into.  Am I missing something?
StringCollection domainList = new StringCollection();
try
{
    DirectoryEntry en = new DirectoryEntry();
    // Search for objectCategory type "Domain"
    DirectorySearcher srch = new DirectorySearcher(en, "objectCategory=Domain");
    SearchResultCollection coll = srch.FindAll();
    // Enumerate over each returned domain.
    foreach (SearchResult rs in coll)
    {
        ResultPropertyCollection resultPropColl = rs.Properties;
        foreach( object domainName in resultPropColl["name"])
        {
            domainList.Add(domainName.ToString());
        }
    }
}
catch (Exception ex)
{
    Trace.Write(ex.Message);
}
return domainList;

A: Add a reference to System.DirectoryServices.dll
using (var forest = Forest.GetCurrentForest())
{
    foreach (Domain domain in forest.Domains)
    {
        Debug.WriteLine(domain.Name);
        domain.Dispose();
    }
}

A: Take a look at this CodeProject article. You'll find a simple code snippet to enumerate domains in the current forest.


text:
Q: Why we create mock for interfaces in Unit testing Why we mock interfaces while performing unit testing in .NET? Why not mock classes. Correct me if the question is silly.

A: You don't create mock interfaces. You create interfaces which your production classes implement, and then you either create a test double manually, or you use a mocking framework to "pretend" to implement the interface in a programmable way. Those test doubles (manual or mocks) are then used when you're testing other production classes which have a dependency on the interface.
Some frameworks will let you mock classes to some extent, but usually they don't allow sealed classes to be mocked, or the behaviour of non-virtual methods to be specified with mock behaviour.
I'm not entirely sure this answers your question - if you could clarify the question, I'll try to clarify my answer accordingly...

A: You mean mock objects. There is no such thing as a mock interface, there is a mock of an interface (or class).
They are used so you can concentrate on testing a class without also testing its dependencies.
Since unit tests are about testing the smallest unit of code (normally a class in .NET), you don't want your tests to execute code that does is not part of the class, this is where mocks come in.
The idea is that you use mocks instead of any implementation of a dependency of the class under test, thus ensuring that the code tested is only that of the class under test.

A: Testing concerns the behaviour of a certain unit. Since other parties are present when testing some cases, you would need a way to safely bypass them. In a way that your test is not affected. Mocks and stubs provide that ability.


text:
Q: Notepad++: how to get filename / path of current file and put it into the clipboard in notepad plus plus Editing files with VIM I can easily copy & paste the name ( or the full path ) of the file
I'm working on ( to understand what I mean about VIM you can see: this question or wiki );
Is there an  equivalent solution by using Notepad++ ?, how can I do?

A: There is no default shortcut key to copy file name or path but you can create one.
Go to Settings->Shortcut mapper
scroll down and look for "Current File path to Clipboard"
click on the empty cell next to it and provide the shortcut of your choice.

A: Notepad++ has no default shortcut to do that, but:
open menu: "Edit" (Alt-E) then select: "Copy to clipboard" and you have different options to
copy the fully qualified file name for current document or parts of it.
See this wiki for exhaustive reference.

A: Another solution is to right-click on the tab, which will let you get the file name/path from there. However, I have tabs disabled, so I have to go with Franco's solution.


text:
Q: Why am I not able to grab from the url? import requests
from bs4 import BeautifulSoup

web = requests.get("http://minewind.com/forums", allow_redirects=False)

mems = BeautifulSoup(web.text)
mems.prettify()

for links in mems.find_all('a'):
    print (links.get("href"))

I'm trying to grab links from a certain webpage, but no matter what I do it won't grab from the /forums but only from minewind.com home page. No matter which url I ask to grab. I'm using a requests py library similar to urllib, I have tried this with urllib and it does something similar.

A: The URL you are trying to access claims it doesn't exist:
>>> import requests
>>> r = requests.get("http://minewind.com/forums")
>>> r.status_code
404

This is probably due to user agent detection; if I set the User-Agent header to something resembling a real browser you do get a response:
>>> r = requests.get("http://minewind.com/forums",
...     headers={'User-Agent': 'Mozilla'})
>>> r.status_code
200
>>> r.url
u'http://minewind.com/forums/'
>>> r.history
(<Response [301]>,)

You can see that you are redirected to a URL with the / at the end.


text:
Q: Validating Tkinter Entry Box I am trying to validate my entry box, that only accepts floats, digits, and operators (+×÷-, %). But my program only accepts numbers not symbols.
I think it is a problem with my conditions or Python Regex.
Here's the code:
from tkinter import *
import re

root = Tk()
def correct(inp):
    pattern = re.compile(r'^(\d*\.?\d*)$')
    if pattern.match(inp) is not None:
        return True
    elif inp is "":
        return True
    else:
        return False

a = Entry(root)
e = root.register(correct)
a.config(validate='key', validatecommand=(e, '%P'))
a.pack()

root.mainloop()

A: Your regexp only matches floats: \d*.?\d* matches digits followed optionally by a dot and more digits. If what you want to match is a pattern like [float][operator][float], then you can use (just add the operators you want in the square brackets):
pattern = re.compile(r'^\d*\.?\d*[+*/\-%]?\d*\.?\d*$')

If you don't care about the order and just want to allow any sequence of numbers and operators:
pattern = re.compile(r'^[\d.+*/\-%]*$')


text:
Q: How to make my discord.js bot show how many servers it is in as it's status I'd like to have my bot have a status that says how many servers it's in.
For example, in 6753421 guilds. I figure you'd make a separate section of code and add ${} to the status with the name of the function in it.

A: You need to use client.setActivity() and then use the client.guilds.cache.size value.
For example:
client.setActivity(`serving ${client.guilds.cache.size} servers`);


text:
Q: Quicksort parallel arrays with respect to both arrays at the same time I have two parallel arrays, a double a[] and an int b[], that I am trying to sort using quicksort.
I want to sort the first array a[] in descending order and at the same time swap the values of b[].
Simultaneously, for elements of a[] with the same value, the elements of b[] must be sorted in ascending order.
I have adjusted the following code, but I can't figure out how to achieve the last part.
void qsort1(double a[], int b[], int lo, int hi) {
 int h, l, p, t1;
 double t;

 if (lo < hi) {
   l = lo;
   h = hi;
   p = a[hi];

   do {
     while ((l < h) && (a[l] <= p))
        l = l+1;
     while ((h > l) && (a[h] >= p))
        h = h-1;
     if (l < h) {
        t = a[l];
        a[l] = a[h];
        a[h] = t;
        t1 = b[l];
        b[l] = b[h];
        b[h] = t1;
      }
   } while (l < h);

   a[hi] = a[l];
   a[l] = p;

   qsort1( a, b, lo, l-1 );
   qsort1( a, b, l+1, hi );
 }
}

For example:
Arrays at the beginning:
a[1] = 10   b[1] = 1
a[2] = 15   b[2] = 2
a[3] = 20   b[3] = 3
a[4] = 15   b[4] = 4
Arrays in the end:
a[1] = 20   b[1] = 3
a[2] = 15   b[2] = 2
a[3] = 15   b[3] = 4
a[4] = 10   b[4] = 1

A: I would avoid two independent arrays. Instead I would make a struct that contained one double and one integer and make an array of that struct. The benefit is two things:
1) The array can be sorted by standar qsort
2) The requirement about sorting on the double first and sort on the integer in case of equal double values, can easily be implemented by the compare function.
It can look something like this:
typedef struct
{
  double a;
  int b;
} SomeDataType;

int compar(const void * a, const void * b)
{
  SomeDataType* pa = (SomeDataType*)a;
  SomeDataType* pb = (SomeDataType*)b;
  if (pa->a > pb->a) return -1;
  if (pa->a < pb->a) return 1;
  if (pa->b > pb->b) return 1;
  if (pa->b < pb->b) return -1;
  return 0;
}

void pd(SomeDataType* p, int n)
{
  for(int i=0; i<n; ++i)
  {
    printf("%f - %d\n", p[i].a, p[i].b);
  }
}
int main()
{
  SomeDataType arr[] = {{10.0, 1}, {15.0, 2}, {20.0, 3}, {15.0, 4}};
  pd(arr, 4);
  qsort(arr, 4, sizeof(SomeDataType), compar);
  printf("-------------------------\n");
  pd(arr, 4);
  return 0;
}

Output:
10.000000 - 1
15.000000 - 2
20.000000 - 3
15.000000 - 4
-------------------------
20.000000 - 3
15.000000 - 2
15.000000 - 4
10.000000 - 1

If it's important to have two individual arrays in the program, I would still use qsort and an array of structs. I would do the sorting in 3 steps.
1) Copy data from the individual arrays to an array of structs
2) Sort the array of structs using qsort
3) Copy the sorted data in the array of structs back to the individual arrays
That could look like:
typedef struct
{
  double a;
  int b;
} SomeDataType;

int compar(const void * a, const void * b)
{
  SomeDataType* pa = (SomeDataType*)a;
  SomeDataType* pb = (SomeDataType*)b;
  if (pa->a > pb->a) return -1;
  if (pa->a < pb->a) return 1;
  if (pa->b > pb->b) return 1;
  if (pa->b < pb->b) return -1;
  return 0;
}

void qsort1(double a[], int b[], int lo, int hi)
{
 if (lo < hi)
 {
   int num_elements = hi - lo + 1;
   SomeDataType* p = malloc(num_elements * sizeof *p);

   // Copy from individual arrays to array of structs
   for(int i=0; i<num_elements; ++i)
   {
     p[i].a = a[lo+i];
     p[i].b = b[lo+i];
   }

   // Sort array of structs
   qsort(p, num_elements, sizeof *p, compar);

   // Copy from array of structs  back to individual arrays
   for(int i=0; i<num_elements; ++i)
   {
     a[lo+i] = p[i].a;
     b[lo+i] = p[i].b;
   }

   free(p);
 }
}

void pa(double a[], int b[], int n)
{
   for(int i=0; i<n; ++i)
   {
     printf("a[%d] = %f b[%d] = %d\n", i, a[i], i, b[i]);
   }
}

int main()
{
  double a[] = {10.0, 15.0, 20.0, 15.0};
  int b[] = {1, 2, 3, 4};
  pa(a, b, 4);
  qsort1(a, b, 0, 3);
  printf("-------------------------\n");
  pa(a, b, 4);

  return 0;
}

Output:
a[0] = 10.000000 b[0] = 1
a[1] = 15.000000 b[1] = 2
a[2] = 20.000000 b[2] = 3
a[3] = 15.000000 b[3] = 4
-------------------------
a[0] = 20.000000 b[0] = 3
a[1] = 15.000000 b[1] = 2
a[2] = 15.000000 b[2] = 4
a[3] = 10.000000 b[3] = 1


text:
Q: Is there a way to get a custom control to display the correct language in the VS Editor when a different language is selected I know this sounds knit picky but I have several custom controls that have been translated. When I use those controls on a Form and then change the language they still display the default language. When the application is running, the correct language is shown, but this gives the impression that parts of the form are not translated, plus in some circumstances it affects the layout of the form that can not be seen until run time.

A: One way is overriding the OnPaint event of the Custom Control. Or you will have to translate the resx by using a proper resx Editor like this or this.
For example...
    protected override void OnPaint(PaintEventArgs pevent)
    {
        base.OnPaint(pevent);
        this.Text = CustomGlobalResources.GetItem(this.Tag.ToString());
    }

Here is an interesting addin for visual studio.