text:
Q: Serialize a Static Class? What happens if we serialize a static class? Can more than one instance of the static class be created if we serialize it?
[Serializable]
public static class MyClass
{
    public static MyClass()
    {

    }

    public static bool IsTrue()
    {
       return true;
    }
}

Suppose I XmlSerialize the object to a XML file, and at a later time I de-serialize back to a object. Another copy exists in the memory (created when somone instintiated the static calss for the first time). Will, there be two copy of the of the object? If yes, can we stop that? Does it apply to any class which follows the singleton pattern?

A: Why not just use a temporary instance class that is a mirror of the static class?
[XmlRoot]
public class SerializeClass
{
    public int Number {
        get;
        set;
    }
}

public static class SerializedClass {

    public static int Number {
        get;
        set;
    }

    public static void Serialize(Stream stream) {

        SerializeClass obj = new SerializeClass();
        obj.Number = Number;

        XmlSerializer serializer = new XmlSerializer(typeof(SerializeClass));
        serializer.Serialize(stream, obj);
    }

    public static void Deserialize(Stream stream) {

        XmlSerializer serializer = new XmlSerializer(typeof(SerializeClass));
        SerializeClass obj = (SerializeClass)serializer.Deserialize(stream);

        Number = obj.Number;
    }
}

I know it's a bit of a hack, but it acheives the same purpose, while still allowing Refactor before runtime, and value validation during runtime.

A: There are never any instances of static classes: they are both abstract and sealed in the IL, so the CLR will prevent any instances being created. Therefore there is nothing to serialize. Static fields are never serialized, and that's the only sort of state that a static class can have.
Your question about XML serialization makes no sense, as no-one can ever have created an instance of the static class to start with.

A: You can't serialize static classes (or any class whatsoever) using built-in .NET serialization features. You can only serialize instances of classes.

A: You may create  the following class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Soap;
using System.Reflection;
using System.IO;

namespace SerializeStatic_NET
{
    public class SerializeStatic
    {
        public static bool Save(Type static_class, string filename)
        {
            try
            {
                FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public);
                object[,] a = new object[fields.Length,2];
                int i = 0;
                foreach (FieldInfo field in fields)
                {
                    a[i, 0] = field.Name;
                    a[i, 1] = field.GetValue(null);
                    i++;
                };
                Stream f = File.Open(filename, FileMode.Create);
                SoapFormatter formatter = new SoapFormatter();
                formatter.Serialize(f, a);
                f.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool Load(Type static_class, string filename)
        {
            try
            {
                FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public);
                object[,] a;
                Stream f = File.Open(filename, FileMode.Open);
                SoapFormatter formatter = new SoapFormatter();
                a = formatter.Deserialize(f) as object[,];
                f.Close();
                if (a.GetLength(0) != fields.Length) return false;
                int i = 0;
                foreach (FieldInfo field in fields)
                {
                    if (field.Name == (a[i, 0] as string))
                    {
                        field.SetValue(null, a[i,1]);
                    }
                    i++;
                };
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

You must define a reference to System.Runtime.Serialization.Formatters.Soap.
Say, in your program you want to save the following static class:
public static class A
{
    public static string s;
    public static int i;
    public static double z;
}

You may use the following code:
bool ok = SerializeStatic.Save(typeof(A), "c:\\tests\\a.dat");

If you want to load the saved data (in the same program or in another program), use the following code:
bool ok2 = SerializeStatic.Load(typeof(A), "c:\\tests\\a.dat");

The fields A.s, A.i, A.z will get the new, loaded values.

A: I found this answer realy useful for my setting class! 1000 thanks to you!
But i had to do some changes to make it working, due to a non-serializable object and change to BinaryFormatter due to servicepack compatiblity
public class SerializeStatic
{
    public static bool Save(Type static_class, string filename)
    {
        try
        {
            FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public);

            object[,] a = new object[fields.Length-1,2]; //one field can´t be serialized, so shouldn´t be counted
            int i = 0;
            foreach (FieldInfo field in fields)
            {
                if(field.Name == "db") continue; // db cant be serialized! so get away.. not very pretty but does its job :)
                a[i, 0] = field.Name;
                a[i, 1] = field.GetValue(null);
                i++;
            };
            Stream f = File.Open(filename, FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter(); //Soapformatter -> .NET 4.5 -> doesn´t run under xp!
            // SoapFormatter formatter = new SoapFormatter();
            formatter.Serialize(f, a);
            f.Close();
            return true;
        }
        catch(Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString()); //Better error messages
            return false;
        }
    }

    public static bool Load(Type static_class, string filename)
    {
        try
        {
            FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public );
            object[,] a;
            Stream f = File.Open(filename, FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();
            a = formatter.Deserialize(f) as object[,];
            f.Close();
            if (a.GetLength(0) != fields.Length-1) return false;

            foreach ( FieldInfo field in fields)
                for(int i=0;i< fields.Length-1;i++) //I ran into problems that some fields are dropped,now everyone is compared to everyone, problem fixed
                    if (field.Name == (a[i, 0] as string))
                        field.SetValue(null, a[i,1]);
            return true;
        }
        catch(Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());
            return false;
        }
    }
}

A: Another solution but one that reads and writes in xml. You can also use the [NonSerialized] attribute above a field to prevent it from being serialized.
public static class SerializeStatic
{
    public static bool Serialize(Type staticClass, string fileName)
    {
        XmlTextWriter xmlWriter = null;

        try
        {
            xmlWriter = new XmlTextWriter(fileName, null);

            xmlWriter.Formatting = Formatting.Indented;

            xmlWriter.WriteStartDocument();

            Serialize(staticClass, xmlWriter);

            xmlWriter.WriteEndDocument();

            return true;
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());

            return false;
        }
        finally
        {
            if (xmlWriter != null)
            {
                xmlWriter.Flush();
                xmlWriter.Close();
            }
        }
    }

    public static void Serialize(string name, object obj, XmlTextWriter xmlWriter)
    {
        Type type = obj.GetType();
        XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();
        XmlAttributes xmlAttributes = new XmlAttributes();
        xmlAttributes.XmlRoot = new XmlRootAttribute(name);
        xmlAttributeOverrides.Add(type, xmlAttributes);
        XmlSerializer xmlSerializer = new XmlSerializer(type, xmlAttributeOverrides);

        xmlSerializer.Serialize(xmlWriter, obj);
    }

    public static bool Serialize(Type staticClass, XmlTextWriter xmlWriter)
    {
        FieldInfo[] fieldArray = staticClass.GetFields(BindingFlags.Static | BindingFlags.Public);

        xmlWriter.WriteStartElement(staticClass.Name);

        foreach (FieldInfo fieldInfo in fieldArray)
        {
            if (fieldInfo.IsNotSerialized)
                continue;

            string fieldName = fieldInfo.Name;
            string fieldValue = null;
            Type fieldType = fieldInfo.FieldType;
            object fieldObject = fieldInfo.GetValue(fieldType);

            if (fieldObject != null)
            {
                if (fieldType.GetInterface("IDictionary") != null || fieldType.GetInterface("IList") != null)
                {
                    Serialize(fieldName, fieldObject, xmlWriter);
                }
                else
                {
                    TypeConverter typeConverter = TypeDescriptor.GetConverter(fieldInfo.FieldType);
                    fieldValue = typeConverter.ConvertToString(fieldObject);

                    xmlWriter.WriteStartElement(fieldName);
                    xmlWriter.WriteString(fieldValue);
                    xmlWriter.WriteEndElement();
                }
            }
        }

        xmlWriter.WriteEndElement();

        return true;
    }

    public static bool Deserialize(Type staticClass, string fileName)
    {
        XmlReader xmlReader = null;

        try
        {
            xmlReader = new XmlTextReader(fileName);

            Deserialize(staticClass, xmlReader);

            return true;
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());

            return false;
        }
        finally
        {
            if (xmlReader != null)
            {
                xmlReader.Close();
                xmlReader = null;
            }
        }
    }

    public static object Deserialize(string name, Type type, XmlReader xmlReader)
    {
        XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();
        XmlAttributes xmlAttributes = new XmlAttributes();
        xmlAttributes.XmlRoot = new XmlRootAttribute(name);
        xmlAttributeOverrides.Add(type, xmlAttributes);
        XmlSerializer xmlSerializer = new XmlSerializer(type, xmlAttributeOverrides);

        return xmlSerializer.Deserialize(xmlReader);
    }

    public static bool Deserialize(Type staticClass, XmlReader xmlReader)
    {
        FieldInfo[] fieldArray = staticClass.GetFields(BindingFlags.Static | BindingFlags.Public);
        string currentElement = null;

        while (xmlReader.Read())
        {
            if (xmlReader.NodeType == XmlNodeType.EndElement)
                continue;

            if (xmlReader.NodeType == XmlNodeType.Element)
            {
                currentElement = xmlReader.Name;
            }

            foreach (FieldInfo fieldInfo in fieldArray)
            {
                string fieldName = fieldInfo.Name;
                Type fieldType = fieldInfo.FieldType;
                object fieldObject = fieldInfo.GetValue(fieldType);

                if (fieldInfo.IsNotSerialized)
                    continue;

                if (fieldInfo.Name == currentElement)
                {
                    if (typeof(IDictionary).IsAssignableFrom(fieldType) || typeof(IList).IsAssignableFrom(fieldType))
                    {
                        fieldObject = Deserialize(fieldName, fieldType, xmlReader);

                        fieldInfo.SetValueDirect(__makeref(fieldObject), fieldObject);
                    }
                    else if (xmlReader.NodeType == XmlNodeType.Text)
                    {
                        TypeConverter typeConverter = TypeDescriptor.GetConverter(fieldType);
                        object value = typeConverter.ConvertFromString(xmlReader.Value);

                        fieldInfo.SetValue(fieldObject, value);
                    }
                }
            }
        }

        return true;
    }
}

A: I found an interesting hack to keep a static class and enable it to make it readable by the xml serializer.
Keep your class non-static but put it in another class which is static
namespace Example
{
    static public class C
    {
        public static MyClass myClass = new MyClass();
    }
}

Then you can use the xml serializer to serialize/deserialize like this
Method :
public void WriteMyClass (string savepath, MyClass myClass)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyClass));
        XmlWriter xml_Writer;
        XmlWriterSettings xml_Settings = new XmlWriterSettings();

        xml_Settings.NewLineOnAttributes = true;
        xml_Settings.Indent = true;

        xml_Writer = XmlWriter.Create(savepath, xml_Settings);
        xmlSerializer.Serialize(xml_Writer, myClass);
        xml_Writer.Close();
    }

Use :
WriteMyClass(savepath, C.myClass);

I know it may not be the cleaner way, but this may combine XML Serializer and static class, but MyClass can be instantiated in other parts of your code, so be carefull about that.
Hope this may help.


text:
Q: How to calculate free available time from the json output? I have this kind of json with start and end time properties in the objects.
var meetings = [
  {
    id: '1',
    start_time: "2020-11-15T08:30:00+00:00",
    end_time: "2020-11-15T14:15:00+00:00"
  },
  {
    id: '2',
    start_time: "2020-11-15T19:30:00+00:00",
    end_time: "2020-11-15T20:30:00+00:00"
  },
];

So two meetings first one: 08:30 - 14:15 second: 19:30-20:30
There are 24 availavable hours for working so:
start_time = '00:00:00';
end_time = '23:59:00';

but in the format that i need would be
var start_time = '2020-11-15T00:00:00+00:00';
var end_time = '2020-11-15T23:59:00+00:00';

How can i calculate the avalavable hours depening on the already maked  meetings?
So because the first meeting is from 08:30 - 14:15 and the second 19:30-20:30 i will need json with the following result with the available hours:

[
  {
    start_time:'2020-11-15T00:00:00+00:00',
    end_time:'2020-11-15T08:30:00+00:00'
  },

  {
    start_time:'2020-11-15T14:15:00+00:00',
    end_time:'2020-11-15T19:30:00+00:00'
  },

  {
    start_time:'2020-11-15T20:30:00+00:00',
    end_time:'2020-11-15T23:59:00+00:00'
  }
]

A: You can do something like this:

var meetings = [
  {
    id: '1',
    start_time: "2020-11-15T08:30:00+00:00",
    end_time: "2020-11-15T14:15:00+00:00"
  },
  {
    id: '2',
    start_time: "2020-11-15T19:30:00+00:00",
    end_time: "2020-11-15T20:30:00+00:00"
  },
  {
    id: '3',
    start_time: "2020-11-15T20:50:00+00:00",
    end_time: "2020-11-15T21:30:00+00:00"
  },
  {
    id: '4',
    start_time: "2020-11-15T22:30:00+00:00",
    end_time: "2020-11-15T22:40:00+00:00"
  },

];

var startTime = '2020-11-15T00:00:00+00:00';
var endTime = '2020-11-15T23:59:00+00:00';

let availableHours = [];

for(let index in meetings){
    if(index != meetings.length - 1){
        index == 0 ? availableHours.push({start_time: startTime, end_time: meetings[index]['start_time'] }) : 0;
        availableHours.push({start_time: meetings[index].end_time, end_time: meetings[+index + 1]['start_time'] });
    } else {
        availableHours.push({start_time: meetings[index].end_time, end_time: endTime })
    }
}

console.log(meetings)
console.log(availableHours)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Formattedtextfield and DateTime in JAVA How can i automatically write current system date as "YYYY-MM-DD HH:MM:SS" to formatted text field after program is launched in JAVA?
Actually i have two formatted text field. One of must be shown current system date - 5 Min  second must be shown current system date after program is launched.
When i run this program Jpanel comes. Ihave these 2 formattedtextfield in this panel.
Left one: must be show current system date - 5min (2013-12-22 21:00:00.000)
Right one: must be show current system date (2013-12-22 21:05:00.000)
How can i code it for automaticly appear this values to fields?
P.S: sorry i dont attach image because i dont have 10 rep yet :(

A: For setting the current system date you need:
JFormattedTextField ftf = ...;
ftf.setValue(new Date());

For setting the right format you need a DefaultFormatterFactory and the DateFormatter:
DateFormatter df = new DateFormatter(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
DefaultFormatterFactory factory = new DefaultFormatterFactory(); // other ctors possible
factory.setDefaultFormatter(df); // here simple default solution
ftf.setFormatterFactory(factory);

Note: You should read the javadoc. There are several variations for edit and display mode. So in your scenario you need two fields (and therefore two dates):
JFormattedTextField ftfLeft = ...; // create and set the format
JFormattedTextField ftfRight = ...; // create and set the format
Date now = new Date();
Date nowMinusFiveSeconds = new Date(now.getTime() - 5 *1000);
ftfLeft.setValue(nowMinusFiveSeconds);
ftfRight.setValue(now);

A: You can use a SimpleDateFormat the set the text of the textfield with the current time
    Date date = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(date);
    formatText = new JFormattedTextField(createFormatter("####-##-## ##:##:##"));
    formatText.setColumns(20);
    formatText.setText(dateString);

If you need to get the date value of the input text, just parse it.
   Date date;
   try {
       date = formatter.parse(formatText.getText());
   } catch (ParseException ex) {
       ...
   }

And to set the field editable with the desired format, you can use a MaskFormatter. See my example. It runs
import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

public class MaskFormatterTest1 extends JPanel {

    private JFormattedTextField formatText;

    public MaskFormatterTest1() {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateString = formatter.format(date);
        formatText = new JFormattedTextField(createFormatter("####-##-## ##:##:##"));
        formatText.setColumns(20);
        formatText.setText(dateString);

        setLayout(new BorderLayout());
        add(new JLabel("Enter Date and Time in YYYY-MM-DD HH:MM:SS format"), BorderLayout.NORTH);
        add(formatText, BorderLayout.CENTER);
    }

    private MaskFormatter createFormatter(String s) {
        MaskFormatter formatter = null;
        try {
            formatter = new MaskFormatter(s);
        } catch (java.text.ParseException exc) {
            System.err.println("formatter is bad: " + exc.getMessage());
            System.exit(-1);
        }
        return formatter;
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("MaskFormatter example");
                frame.add(new MaskFormatterTest1());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationByPlatform(true);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}


text:
Q: Zend Framework installed. Wordpress being installed in sub-folder. How do I carry over Zend user authentication to WP pages? I am working on a website with the Zend framework installed. Zend controls the user authentication (logged in, logged out, who they are, etc.).
I want to install Wordpress into a sub-folder and access the proper user data (username, logged in/out status, etc.) when viewing the pages/posts created by Wordpress.
What steps would I need to take to do this?
NOTE: The programmer before me installed and used Zend, I am familiar with Zend, but not so much the details so you might need to explain in more laymen terms. I've used Wordpress lots of times and know it quite well.

A: Somewhere in Wordpress (you likely know where since you are familiar with Wordpress), you will use the following Zend Framework code:
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
  // Identity exists; get it
  $identity = $auth->getIdentity();
}

The above code is checking the session namespace and determining if an identity has been stored. If there is an identity stored, someone has authenticated and you can retrieve that authorized identity.
The above code assumes that you can load classes with the Zend_ namespace prefix from wordpress (autoload, include_path, etc.).


text:
Q: Jenkins SVN Tag Parameter from CLI I recently attempted to use Jenkins-CLI with an SVN tag parameter. I received this error message.

CLI parameter submission is not supported for the class hudson.scm.listtagsparameter.ListSubversionTagsParameterDefinition type. Please file a bug report for this.

My command
java -jar jenkins-cli.jar -s [JENKINS_URL] build [BUILD] -s -p VERSION=trunk

Does anyone know a way around this?

A: This error usually occurs when plugin (in this case the subversion-plugin) does not support CLI parameter submission.
And really, if you take a look in the source code of the class specified in error, there is only support for parameter submission from GET and POST HTTP requests, and from "Build" button in Jenkins GUI.
The best thing to do would be to submit a bug report for this issue.
You can see similar bug report for another plugin here


text:
Q: Speed up animation of TitlePane in Dojo I'm trying to speed up or remove the wipeIn and wipeOut animation of a title pane in Dojo. The content should appear immediately after clicking on the title bar. In other frameworks, I would modify the animation speed or duration but I had no luck with this in dojo so far. I've also tried to overwrite the animation without too much success.
This is (simplified) how I create the TitlePane:
require(["dijit/TitlePane", "dojo/dom-construct"], function(TitlePane, domConstruct){
    var titlePaneOptions = {};
    titlePaneOptions.title = "Some Title";
    titlePaneOptions.open = true;
    titlePaneOptions.content = "Content";

    this._titlePane = new TitlePane(titlePaneOptions);
    domConstruct.place(this._titlePane.domNode, this.context.element, "only");

    this._titlePane.startup();
});

A: Check the API docs for TitlePane, under Property Summary, there is a duration:

duration - Time in milliseconds to fade in/fade out

So for example:
var titlePaneOptions = {};
titlePaneOptions.title = "Some Title";
titlePaneOptions.open = true;
titlePaneOptions.content = "Content";
titlePaneOptions.duration = 0;

.. should make it appear/disappear immediately.


text:
Q: beyond compare with `git difftool --dir-diff` -- Hitting an issue with sym-links Setup a new git repo and add some files:
[Feb-09 18:35][Desktop]$ mkdir exampleForStackOverflow
[Feb-09 18:35][Desktop]$ cd exampleForStackOverflow/

[Feb-09 18:35][exampleForStackOverflow]$ git init
Initialized empty Git repository in ~/Desktop/exampleForStackOverflow/.git/

[Feb-09 18:35][exampleForStackOverflow]$ touch foo.txt
[Feb-09 18:35][exampleForStackOverflow]$ touch bar.txt
[Feb-09 18:35][exampleForStackOverflow]$ touch baz.txt

[Feb-09 18:36][exampleForStackOverflow]$ git add *

[Feb-09 18:36][exampleForStackOverflow]$ git commit -m "Create files"
[master (root-commit) 42bfa60] Create files
 3 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 bar.txt
 create mode 100644 baz.txt
 create mode 100644 foo.txt

Modify the files:
[Feb-09 18:37][exampleForStackOverflow]$ echo "Foo" > foo.txt
[Feb-09 18:37][exampleForStackOverflow]$ echo "Bar" > bar.txt
[Feb-09 18:37][exampleForStackOverflow]$ echo "Baz" > baz.txt

Current status:
[Feb-09 18:38][exampleForStackOverflow]$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   bar.txt
    modified:   baz.txt
    modified:   foo.txt

no changes added to commit (use "git add" and/or "git commit -a")

Current diff:
[Feb-09 18:38][exampleForStackOverflow]$ git diff
diff --git a/bar.txt b/bar.txt
index e69de29..ebd7525 100644
--- a/bar.txt
+++ b/bar.txt
@@ -0,0 +1 @@
+Bar
diff --git a/baz.txt b/baz.txt
index e69de29..a688182 100644
--- a/baz.txt
+++ b/baz.txt
@@ -0,0 +1 @@
+Baz
diff --git a/foo.txt b/foo.txt
index e69de29..bc56c4d 100644
--- a/foo.txt
+++ b/foo.txt
@@ -0,0 +1 @@
+Foo

Now with bcompare I get the following:
[Feb-09 18:38][exampleForStackOverflow]$ git difftool --dir-diff

This is clearly not the expected behaviour.  The files do not align so differences cannot be seen.

I am running:
[Feb-09 18:44][exampleForStackOverflow]$ git --version
git version 2.7.1

[Feb-09 18:44][exampleForStackOverflow]$ cat /etc/redhat-release
CentOS release 6.6 (Final)

Beyond Compare: Version 4.1.3 (build 20814)
git config:
[Feb-09 18:45][exampleForStackOverflow]$ git config --list
color.ui=true
user.name=FOO
user.email=BAR@BAZ.com
log.decorate=full
diff.tool=bc3
difftool.bc3=trustExitCode
merge.tool=bc3
mergetool.bc3=trustExitCode
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true

Question: (From Ismail Badawi) What does this have to do with symlinks?
Answer: Sorry the screenshot isn't extremely clear but the files on the right hand side are symlinks.  See below:
[Feb-09 18:52][exampleForStackOverflow]$ cd /tmp/git-difftool.RWDqE/right
[Feb-09 18:52][right]$ ll
total 0
lrwxrwxrwx 1 BAZ BAZ_g 54 Feb  9 18:51 bar.txt -> /home/BAZ/Desktop/exampleForStackOverflow/bar.txt
lrwxrwxrwx 1 BAZ BAZ_g 54 Feb  9 18:51 baz.txt -> /home/BAZ/Desktop/exampleForStackOverflow/baz.txt
lrwxrwxrwx 1 BAZ BAZ_g 54 Feb  9 18:51 foo.txt -> /home/BAZ/Desktop/exampleForStackOverflow/foo.txt

A: In addition to sixtyfootersdude's suggestion, another option is to make Beyond Compare follow symbolic links. This will align symlinks with files of the same name.
In the Folder Compare, click the Rules toolbar button (referee icon).
Go to the Handling tab.
Check Follow symbolic links.
To make this affect all new sessions, change the dropdown at the bottom of the dialog from Use for this view only to Also update session defaults before you click OK.

Snapshots:

A: Using this will work:
git difftool --dir-diff --no-symlinks

From the git doc:

--[no-]symlinks
git difftool's default behavior is create symlinks to the working tree
  when run in --dir-diff mode and the right-hand side of the comparison
  yields the same content as the file in the working tree.
Specifying --no-symlinks instructs git difftool to create copies
  instead. --no-symlinks is the default on Windows.


text:
Q: Two sequence Session.set cause one rerun? In Chrome console,
> Tracker.autorun(function() {console.log(Session.get('show'))});

> Session.set('show',2);
2
> Session.set('show',3);
3
> Session.set('show',4);Session.set('show',5);
5

Two sequence Session.set cause one rerun?
How can I make it run twice?

A: You can use Tracker.flush() to immediately rerun the computation after the first reactive data source update :
> Session.set("show",4);Tracker.flush();Session.set("show",5);


text:
Q: MySQL Replication failing on `mysql`.`user` changes I have a simple master - slave setup with MySQL 5.6 that keeps failing whenever I make changes to the mysql.user table. The master is set to replicate two databases, neither of which are the mysql database. The binlog_format is set to ROW.
I have a selection of MySQL users set up on the master for various colleagues to make changes to the database on, but on the slave I only have one user, which is the web server.
When I tried to delete a redundant user from the master, the slave failed with the following message:
Error 'Operation DROP USER failed for 'mysql_user'@'localhost'' on query. Default database: ''. Query: 'DROP USER 'mysql_user'@'localhost''

I don't want to have to keep skipping the errors, because every now and again I'll make changes to the mysql.user table and it's easy to forget to check the replication is still going. I don't have any monitoring setup for the replication, so a couple of times I've made changes to the mysql table and no one has noticed for a couple of hours, which impacts our production web server.
Any help much appreciated.

A: Pay attention to the part of your error message: 'mysql_user'@'localhost''
There are two quotes after localhost word. When this statement replicates, a slave database server cannot find a user and replication stops. MySQL 5.7 has DROP USER IF EXISTS user form, but in MySQL 5.6 you better do not make such mistakes or prefer direct edits of mysql database.
UPDATE: When you are not interested in replicating MySQL accounts from a master server to slaves, you may want to add replicate-ignore-db=mysql to [mysqld] sections on each slave. I prefer filtering at slaves because having changes in binary logs of a master have potential value for troubleshooting in the future.


text:
Q: Universal Windows App fails to launch, "AppxDeploymentFailureBlue" I've installed my own Universal Windows App for all users on a PC, using the DISM tool while being logged-in in Audit Mode.
After doing so, I reboot into OOBE (using sysprep command), create a new user and try to launch this app.
The result is that nothing happens - the app doesn't launch (also checked in Task Manager).
In Windows' Event Viewer, I found an entry about AppxDeploymentFailureBlue, which appears there every time I try to launch that app - but it doesn't supply any further information about the problem or its cause.
I tried to look for this error code online, but all I could find is some discussions about a corrupted version of the Windows Store app or Windows' built-in apps - which isn't the case here.
Further more, this app has a StartupTask, and its failure to properly launch seems to be blocking other apps from registering themselves in the Startup tasks/apps list (if the app isn't installed, then they are registered successfully).

A: The solution turned out to be simple in hindsight, but not easy to track down:
Turns out one of the app's dependencies wasn't installed. Seems like installing a Universal App with DISM in Audit Mode (as opposed to when installing as regular local user) doesn't give any indication about missing pre-requisites.
In order to figure out which dependency was missing, I went over the App's AppxManifest.xml's <Dependencies> section. In order to check which are installed and which aren't, I used the following command: Dism /Online /Get-ProvisionedAppxPackages.
After installing the missing package (in my case, that was Microsoft.VCLibs.140.00.UWPDesktop), everything went back to normal.


text:
Q: NSDictionary - List all In a NSMutableDictionary like this:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithString:firstName], @"NAME",
[NSNumber numberWithFloat:familyName], @"SURNAME",
nil];

How can all of its elements be converted to the NSString? with the requirement that names and surnames are arranged in string like this: "name, surname, name, surname..."?
This gives a string with all the names but not surnames:
NSString * result = [[urlArray valueForKey:@"NAME"] componentsJoinedByString:@", "];

Is there a way similar to the one above to create a string with all the values of NSMutableDictionary?

A: Try something like this:
NSString *result = [NSString stringWithFormat:@"%@, %@", [urlArray valueForKey:@"SURNAME"], [urlArray valueForKey:@"NAME"]];

The %@ represents an objective-c object for more details see the Apple docs

A: The code to make a NSString from an NSDictionary may look like (if you're trying to print out everything in the NSDictionary)
NSMutableString* mutableString = [NSMutableString string];
NSDictionary* dictionary;

for(NSString* key in [dictionary allKeys])
{
    [mutableString appendString:[[dictionary objectForKey:key] description]];
}


text:
Q: set dimension of svd algorithm in python svd formular:  A ≈ UΣV*
I use numpy.linalg.svd to run svd algorithm.
And I want to set dimension of matrix.
For example: A=3*5 dimension, after running numpy.linalg.svd, U=3*3 dimension, Σ=3*1 dimension, V*=5*5 dimension.
I need to set specific dimension like U=3*64 dimension, V*=64*5 dimension. But it seems there is no optional dimension parameter can be set in numpy.linalg.svd.

A: If A is a 3 x 5 matrix then it has rank at most 3. Therefore the SVD of A contains at most 3 singular values. Note that in your example above, the singular values are stored as a vector instead of a diagonal matrix. Trivially this means that you can pad your matrices with zeroes at the bottom. Since the full S matrix contains of 3 values on the diagonal followed by the rest 0's (in your case it would be 64x64 with 3 nonzero values), the bottom rows of V and the right rows of U don't interact at all and can be set to anything you want.
Keep in mind that this isn't the SVD of A anymore, but instead the condensed SVD of the matrix augmented with a lot of 0's.


text:
Q: Build a jar file from project folder in a specific location of git repository using azure devops I am having a git repository for my project with a structure as shown below.

The structuring is based on the source, all the codes, scripts related to a source is kept under the respective source folder.
The scripts and code consists of sql, scala, pyhton...all kind of files used for that source.
Now for one of the source, I have to create a jar file.

*

*For that I have created a project in IntelliJ using sbt build and create jar file.

*Create a folder under respective source and copy the entire project into the created folder as below.

I have to use azure devops for creating jar file and store it in a dbfs location. There are two things i have to get clarity on.

*

*How to create a jar file from this location of repository using sbt build file from devops?
I tried with devOps, but could not see any agent job to create jar file from sbt file.

*If I could convert this sbt file into pom.xml, how could i create a jar file from this location of repository using devops?

A: You should have sbt available on Ubuntu host agent. Here you have an example YAML code:
name: sbt

trigger:
- master

variables:
  sbtFileDirectory: '<pass your folder where sbt file is>'
pool:
  vmImage: 'ubuntu-latest'
steps:
- script: sbt clean
  displayName: 'Running $ sbt clean'
  workingDirectory: $(sbtFileDirectory)
- script: sbt update
  displayName: 'Running $ sbt update'
  workingDirectory: $(sbtFileDirectory)
- script: sbt compile
  displayName: 'Running $ sbt compile'
  workingDirectory: $(sbtFileDirectory)
- script: sbt test
  displayName: 'Running $ sbt test'
  workingDirectory: $(sbtFileDirectory)

With classic/release pipelines it would be similar:

You can also monitor this topic on developer community - Scala and SBT builder

A: According to your description, you want to add build output (from Azure DevOps) into Source Control (GitHub). It's not recommended to update source control from a build, If you have special reason to do this, you can run git commands in the Powershell Task to do the commit and push. Check the answer in this case: Send specific files from Azure DevOps pipeline to Github
    #Clone repo to your workspace
    git clone https://github.com/repo

    #assuming master is your branch
    git checkout master

    #Refresh repo if is already in your workspace
    git pull -q 2>&1 | Write-Host

    #Copy file to the worspace
    XCOPY "File current location" "Git workspace location"

    #Add files to the local repo
    git add -A

    #Commits the file to local repo:
    git commit -m "Files commited."

    #Pushes the changes to Git repo
    git -c http.extraheader='AUTHORIZATION: bearer $env:System_AccessToken' push -q -f


text:
Q: Why is python list comprehension sometimes frowned upon? Many developers I have met suggest it's best practice to go with simple loops and if conditions instead of one line list comprehension statements.
I have always found them very powerful as I can fit a lot of code in a single line and it saves a lot of variables from being created. Why is it still considered a bad practice?
(Is it slow?)

A: It's not considered bad.
However, list comprehensions that either

*

*Have side effects, or

*Are more readable as a multi-line for loop

are generally frowned upon.
In other words, readability is important.
As an overly contrived example of the first bad example:
x = range(10)
[x.append(5) for _ in xrange(5)]

Basically, if you're not storing the result, and/or it modifies some other object, then a list comprehension is probably a bad idea.
As an example of the second, have a look at pretty much any code golf entry written in python. Once your list comprehension starts to become something that isn't readable at a glance, consider using a for loop.

A: There is no performance hit (even if there were, I would not worry about it; if performance were so important, you've got the wrong language). Some frown upon list comprehensions because they're a bit too terse for some, that's a matter of personal preference. Generally, I find simple list comprehensions to be much more readable than their loop/condition equivalents, but when they start to get long (e.g. you start to go past 80 characters), they might be better replaced with a loop.

A: List comprehensions are used for creating lists, for example:
squares = [item ** 2 for item in some_list]

For loops are better for doing something with the elements of a list (or other objects):
for item in some_list:
    print(item)

Using a comprehension for its side effects, or a for-loop for creating a list, is generally frowned upon.

Some of the other answers here advocate turning a comprehension into a loop once it becomes too long. I don't think that's good style: the append calls required for creating a list are still ugly. Instead, refactor into a function:
def polynomial(x):
    return x ** 4 + 7 * x ** 3 - 2 * x ** 2 + 3 * x - 4
result = [polynomial(x) for x in some_list]

Only if you're concerned about speed – and you've done your profiling! – you should keep the long, unreadable list comprehension.


text:
Q: Returning all strings from an array after a specific index I have made a command that does something to a player. One of the optional arguments for this is to add a reason and when executed, it would be sent to the user.
The problem is, I have created the command and the reason works however, the reason has to be written with no spaces. (e.g YouWereGreifing!). This is because in the code I have only told it to use the argument with the index of a number.
My question is, how would I combine an array into a string, but only take the values after a certain index in that array.
Code
Here is the method I am calling:
Main.demotePlayer(player, targetPlayer, "Guest", args[1])

and the args[] is being created with
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String [] args){

A: Try the Arrays.copyOfRange method?
newarray[] = Arrays.copyOfRange(oldArray, start, oldArray.length);


text:
Q: Alternative for XAMP on windows7 I'm currently doing a project which needs storage of data(dynamic website).But project is local project(local host).I have been using XAMP now days but which is not supporting now.Xamp installation problem -  no fix is availableWhich is the best local server side program that can I use for this project.I'm tied of searching on google because I don't get any useful information,please help me.

A: I suggest you could use WAMP as a local server. It is the best alternative for XAMP and you will get lots of support available on internet as well.
It is easy to use so go for WAMP as an alternative for your local server.
Here is the link from where you can download it-
http://www.wampserver.com/en/


text:
Q: SetTimeOut Property causes pop up blocker instead of new window I am making a synchronous post to a page and in the meanwhile while I am getting the response back I am showing an loading (wait) image. In order to show the image, I am using SetTimeout property and showing the response in a new window. Now since I am using the SetTimeout property the browser thinks this window as a pop up and blocking it. I am using window.open.
I have tried removing the wait image and it works fine.
When I remove the loading image it all works fine.
Any suggestion on how to fool the browser?
Thanks

A: There is a way to trick browser. Instead of using setTimeout, you can create a simple while loop which will do the delay. Something like this:
var d1 = new Date(),
    d2 = new Date(),
    timer = 500; //Milliseconds

while (d2.valueOf() < d1.valueOf() + timer) {
    d2 = new Date();
}

window.open('new_location.html', '_blank');

Its not pretty solution but it does the job :)


text:
Q: Exclude Subnets From Master List Using ipaddress module? I have a Python script that gets all of the network ranges we have deployed within the Google Cloud Platform. Whenever we create a new network, we need to ensure the network is unique and doesn't overlap with anything we've set up already. This is what I have so far:
from googleapiclient import discovery
from oauth2client.service_account
import ServiceAccountCredentials
from ipaddress import IPv4Network

credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceaccount.json')
compute = discovery.build('compute', 'v1', credentials=credentials) cloudresman = discovery.build('cloudresourcemanager', 'v1', credentials=credentials)
projects = [] projectdicts = cloudresman.projects().list().execute() projectdicts = projectdicts.get('projects')
for projectdict in projectdicts:
    if "sandbox" not in projectdict['name']:
        if projectdict['lifecycleState'] == "ACTIVE":
            projects.append(projectdict['projectId'])
        else:
            print(projectdict['projectId'] + " is not active")

ipranges = []
for project in projects:
    regiondicts = compute.regions().list(project=project).execute() regiondicts =
    regiondicts.get('items')
    for regiondict in regiondicts:
        region = regiondict['name']
        subnetworkdicts = compute.subnetworks().list(project=project,region=region).execute()
        subnetworkdicts = subnetworkdicts.get('items')
        if subnetworkdicts:
            for subnetworkdict in subnetworkdicts:
                ipranges.append(IPv4Network(subnetworkdict['ipCidrRange']))
                if "secondaryIpRanges" in subnetworkdict:
                    secondaryranges = subnetworkdict['secondaryIpRanges']
                    for secondaryrange in secondaryranges:
                        if secondaryrange['ipCidrRange'] not in ipranges:
                            ipranges.append(IPv4Network(secondaryrange['ipCidrRange']))

All of the subnets we use are within the 10.0.0.0/8 range.
But my question is: how can I exclude the list of subnets from a 'master list'?
I've tried the following:
masterranges = IPv4Network("10.0.0.0/8")
for iprange in ipranges:
    masterranges = masterranges.address_exclude(iprange)

However, that returns: 'generator' object has no attribute 'address_exclude'.
This makes sense because the 'generator' object is a list of subnets after the exclusion. I've also tried:
masterranges = IPv4Network("10.0.0.0/8")
for iprange in ipranges:
    masterranges = list(masterranges.address_exclude(iprange))

But of course, that then returns: 'list' object has no attribute 'address_exclude'.
The problem is that whenever I exclude one iprange from the master range, address_exclude produces a list of subnets, which I then need to iterate through with each iprange, which then, if successful, would produce a whole new list of subnets.
I'm struggling with the logic of how to make this work, so any help with this would be appreciated.

A: In your approach -
masterranges = IPv4Network("10.0.0.0/8")
for iprange in ipranges:
     masterranges = list(masterranges.address_exclude(iprange))

Inside the for loop, 'masterranges' is being assigned as an object of list data type and on the very next iteration 'address_exclude' is being performed on it, which is creating a problem.
'address_exclude' works on objects of data type ip_address, not on objects of data type list.
I suggest you use another variable in line 3 to store the list, then run another loop to append those data out of the list into your masterranges.


text:
Q: Bar chart using c sharp i had developed a windows app, which is is giving ouput in 4 textboexs,now i want these 4 values in to a Bar Grapg in another window, i had download wd MS chart but not able to understanad how to use it to make a window which displays these texeboxes values into bar chat in 1 click

A: Creating chart of any kind takes at least some amount of work. And it depends upon the charting library you are using. I would recommend NPlot as it is free, small and very easy to work with.

A: Not real sure of the question but I would look at http://code.msdn.microsoft.com/mschart. There is plenty of documentation and even some sample code.
I have used MsCharts for a previous project and found the examples rather sufficient.


text:
Q: LocalSettings Variables in windows store app not persisting? I am trying to configure an option to change the fontsize and created a setting but not able to persist. The setting is a select control. Default settings for font size are coming from default.css but I would like to override based on the user selection. This is a html/js app in windows 8 store. Any working example would be great. Thank you.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Preferences</title>

    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />

    <link href="/css/default.css" rel="stylesheet" />

        <button type="button" onclick="WinJS.UI.SettingsFlyout.show()" class="win-backbutton"></button>

Preferences

            Font Size:
            <select id="fontSize">
                <option>18px</option>
                <option>24px</option>
                <option>32px</option>
                <option>36px</option>
                <option>42px</option>
                <option>54px</option>
            </select>

JS:
(function() {
    "use strict";

    var appData = Windows.Storage.ApplicationData.current.localSettings;

    WinJS.UI.Pages.define("/settings/preferences.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {

            // Get DOM Elements
            var fontSize = document.getElementById("fontSize");

            //Wire up event handlers
            fontSize.addEventListener("change", fontSizeLeave);

           function fontSizeLeave() {
                appData.values["fontSize"] = fontSize.value;
            };

            // Get data
            // Set settings to existing values
           if (appData.values.size > 0) {
               fontSize.value = appData.values["fontSize"];

           }

        },

        checkpoint: function () {
            // Save data
            appData.values["fontSize"] = fontSize.value;

        },

        unload: function() {
            // Respond to navigations away from this page.
        },

        updateLayout: function(element, viewState, lastViewState) {
            // Respond to changes in viewState.
        }
    });
})();

A: From my testing with your code, there isn't any issue with the data persistence.
This line of code results in a value of empty string in fontSize.value, even though the appData.values content is correct.
fontSize.value = appData.values["fontSize"];

An easy fix is to supply values for each of the options in your select
<select id="fontSize">
   <option value="18px">18px</option>
   <option value="24px">24px</option>
   <option value="32px">32px</option>
   <option value="36px">36px</option>
   <option value="42px">42px</option>
   <option value="54px">54px</option>
</select>


text:
Q: Hilbert space version of the notion of conditionally weakly-mixing functions. $\newcommand{\norm}[1]{\|#1\|}$ $\newcommand{\ab}[1]{\langle #1\rangle}$ $\newcommand{\mr}{\mathscr}$ $\newcommand{\mc}{\mathcal}$ $\newcommand{\E}{\mathbb E}$ $\newcommand{\C}{\mathbf C}$
Background/Definitions
Let $(X, \mc X, \mu, T)$ be an invertible measure preserving system.
A function $f\in L^2$ is said to be weakly-mixing if
$$
\lim_{N\to \infty} \frac{1}{N} \sum_{n=0}^{N-1} |\ab{f, T^n f}|^2 = 0
$$
This definition can be given for a more abstract setting.
Let $H$ be a Hilbert space equipped with a unitary operator $U:H\to H$.
A point $x\in H$ is said to be weakly-mixing if
$$
\lim_{N\to \infty} \frac{1}{N} \sum_{n=0}^{N-1} |\ab{x, T^nx}|^2 = 0
$$
Now suppose $\mc D$ and $\mc A$ are $T$-invariant sub-$\sigma$-algebras of $\mc X$ with $\mc A\subseteq \mc D$.
Then we have a factor map $(X, \mc D, \mu, T)\to (X, \mc A, \mu, T)$ mapping $x$ to $x$.
Thus $(X, \mc D)$ is an extension of $(X, \mc A)$.
We define a conditional inner product on $L^2(\mc D)$ as
$$
\ab{f, g}_{(\mc D|\mc A)} = \E[f\bar g| \mc A]
$$
for all $f, g\in L^2(\mc D)$.
Note that the "inner product" is valued in $L^1(\mc A)$ and not in $\C$.
Let $L^2(\mc D|\mc A)$ be the subspace of $L^2(\mc D)$ consisting of all $f\in L^2(\mc D)$ such that
$$
\norm{f}_{(\mc D|\mc A)} := \sqrt{\E[|f|^2|\mc A]}
$$
is in $L^\infty(\mc A)$.
Definition.
A function $f\in L^2(\mc D| \mc A)$ is said to be conditionally weakly-mixing if for each $g\in L^2(\mc D|\mc A)$ we have
$$
\lim_{N\to \infty} \frac{1}{N}\sum_{n=0}^{N-1} \|\ab{T^nf, g}_{(\mc D|\mc A)}\|_{L^2(\mc A)}^2 = 0
$$
This is a natural conditional version of the non-conditional definition given above.
Question

Question. Is there a Hilbert space version of definition of conditionally weakly-mixing.

The first thing that comes to mind is to consider a Hilbert space $K$ equipped with a unitary operator $U$, and let $H$ be a $U$-invariant closed linear subspace of $K$.
Thus $K$ mimics $L^2(\mc D)$ and $H$ mimics $L^2(\mc A)$.
Since the adjoint of the inclusion $L^2(\mc A)\to L^2(\mc D)$ is the conditional expectation map $\E[\cdot|\mc A]:L^2(\mc D)\to L^2(\mc A)$, we may define the conditional inner product of $x$ and $y$ in $K$ as $\ab{x, y}_{(K|H)} = \ab{i^*x, i^*y}_H$, where $i:H\to K$ is the inclusion map and $i^*$ is the adjoint of $i$.
However, $\ab{x, y}_{(K|H)}$ is a complex number, unlike in the case of the conditional inner product.
So perhaps we need more structure on the Hilbert space to come up with a proper definition.


text:
Q: Do in-app purchasing providers like Zong, Paypal, and Boku violate iPhone and Android terms and conditions? I know there are questions posted elsewhere about how to implement in-app purchases on iPhone and Android, but none answer the legality of the solutions today.  At the time of release, there was some dispute over whether some of these solutions violate terms of service, but it's now several months later.  There are also now several exceptions like Amazon, which seem to circumvent iTunes for purchases.
Anyone have a definitive answer?

A: It seems that the App Store has two main rules when it comes to in-app purchases (IAP):

*

*Buying physical goods or services outside the app using the in-app purchase API is not allowed

*Using something other than the in-app purchase API to purchase content, functionality, or services in an app is not allowed

Amazon is Ok on both these, but I don't know enough about the Zong, Paypal or Boku apps.


text:
Q: Create a new variable by extracting text from another R I have a dataframe called "data":
data <-
            x                y
            green-dog        3
            blue-dog         4
            red-cat          5
            yellow-cat       6

I need to create a new variable called "type", like this:
data <-
                x                y      type
                green-dog        3      dog
                blue-dog         4      dog
                red-cat          5      cat
                yellow-cat       6      cat

A: There are many ways to do this but this is the simplest if there are only two categories:
data <- data.frame(
    x = c("green-dog", "blue-dog", "red-cat", "yellow-cat"),
    y = 3:6)

data$type <- ifelse(grepl("dog", data$x), "dog", "cat")

Note that as written, anything without a "dog" in it becomes cat, even if "cat" isn't there either.  Things  to consider:

*

*how to handle NAs?

*should you have an explicit check for "cat", or can it just be the default (not dog) option?

*what about upper/lower case?

*do you want to capture the colour too?

If you need something more complex, I'd suggest checking out the stringr package.

A: We can do this easily with sub
data$type <-  sub(".*-", "", data$x)
data$type
#[1] "dog" "dog" "cat" "cat"


text:
Q: Installing Broadcom Wireless Drivers for ubuntu 15.04 I just followed the instructions to install Broadcom Drivers,every thing is working but at last instruction sudo apt-get install <bcmwl-kernel-source>,it just say:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package bcmwl-kernel-source

And no thing happened after I rebooted my system.
I use Ibuntu 15.04 and pci id is [14e4:4365] (rev 01)

A: *

*Add restricted component repository
sudo add-apt-repository restricted

*Update packages list
sudo apt-get update

*Confirm that you have kernel headers installed and updated
sudo apt-get install linux-generic

*Then install it again
sudo apt-get install bcmwl-kernel-source


text:
Q: MongoTemplate : group by on multiple fields with condition clause Earlier I had below mentioned aggregation pipeline.
db.EXCEPTIONS.aggregate(
[{ $match : {
        $and : [
            {workflow_stage_current_assignee : {$ne:null}},
            {CreatedDate:{$gt:ISODate("2017-07-12")}},
            {CreatedDate:{$lt:ISODate("2018-07-12")}}
        ]}
 },
 {
     $group : {_id: {user : "$workflow_stage_current_assignee", cm:"$control_monitor"},
               exceptions:{$sum:1} }
 },
 { $project : {"user":1,"cm":1,"exceptions":1}},
 { $sort : {"exceptions":1}}

]);

And corresponding conversion in Mongo template is as below.
Calendar fromDate = Calendar.getInstance();
fromDate.set(2016, 7, 12, 0, 0, 0);

Calendar toDate = Calendar.getInstance();
toDate.set(2018, 7, 12, 23, 59, 59);

MatchOperation match = Aggregation.match(new Criteria("workflow_stage_current_assignee").ne(null)
        .andOperator(new Criteria("CreatedDate").gte(new Date(fromDate.getTimeInMillis()))
        .andOperator(new Criteria("CreatedDate").lte(new Date(toDate.getTimeInMillis())))));

GroupOperation group = Aggregation.group("workflow_stage_current_assignee","control_monitor").count().as("exceptions");

ProjectionOperation project = Aggregation.project("workflow_stage_current_assignee","control_monitor","exceptions");

SortOperation sort=Aggregation.sort(Sort.Direction.DESC,"exceptions");

Aggregation aggregation  = Aggregation.newAggregation(match,group,project,sort);

AggregationResults<ExceptionCount> output  = mongoTemplate.aggregate(aggregation, "EXCEPTIONS", ExceptionCount.class);

This worked fine. Then I modified original query as below and added additional grouping option as overdue.
$group : {_id: {user : "$workflow_stage_current_assignee", cm:"$control_monitor"},
               exceptions:{$sum:1},
               },
               overdue: {$sum : {$cond :[
                                    {$gt:["$CreatedDate",ISODate("2017-07-12")]},1,0
                                ]}
               }

But I am not aware how to achieve this additional group clause in Mongo Template queries. I searched on internet but most of the results use DBObject from older API. Can any one help me in this with Mongo Template?

A: Finally I found the answer!
Since I couldn't find a way to conditionally group the fields using Mongo template, I had to tweak the logic of aggregation pipeline itself.

*

*I used conditional projection to project an additional field.

*Performed projection operation first.

*Then performed grouping using this additional field.

So code changes required are as below.
Step 1
I modified my projection clause and added another conditional projection field as below.
Cond overdueCondition = ConditionalOperators.when(new Criteria("CreatedDate").gt(new Date())).then(1).otherwise(0);
ProjectionOperation project = Aggregation.project("workflow_stage_current_assignee","control_monitor","exceptions").and("overdue").applyCondition(overdueCondition);

The result of this operation would reduce my result set to something like this:
{
"workflow_stage_current_assignee" : "Yogesh",
"control_monitor" : "P005",
"exceptions":"",
"overdue" : 1
},
{
"workflow_stage_current_assignee" : "Yogesh",
"control_monitor" : "P005",
"exceptions":"",
"overdue" : 0
}...

After step 1, I got another field in projection called overdue, with value either 1 or 0 depending on if my condition is satisfied or not.
Step 2
Then in group clause I used Sum operator to add all such overdue fields.
GroupOperation group =  Aggregation.group("workflow_stage_current_assignee","control_monitor").count().as("exceptions").sum("overdue").as("overdue");

Step 3
And finally I modified my aggregation pipeline to perform Projection operation first and then group all the results.
Aggregation aggregation  = Aggregation.newAggregation(match,project,group,sort);

This gave me required results!


text:
Q: Backbone: Does Collection#get return a copy of the model or the model object itself? I've been having some difficulty understanding exactly what happens when a model is manipulated in Backbone.
1) When calling #get on a Collection to "grab" a model, is the model the same model as the Collection's model? (e.g., updating the model will update the Collection's model)
2) If a model is added to various collections, do all of those collections contain the actual model (or a "copy" of the model)? It seems to me that it's the "copy" because when I try to destroy a model that has been added to various collections, not all the models in the various collections are destroyed.
Thanks! Appreciate any insights.

A: Like every other object in Javascript, Backbone objects are 'passed by a copy of the reference'. The best way to think about this is that javascript has a piece of data in memory, and variables are nothing more than pointers to those bits of data. When you set one variable equal to another, what you really get is two copies of the pointer, both pointing at the same piece of data in memory. So, applying this to your question:

*

*Yes. When you 'get' the model, what you 'get' from backbone is a
pointer to the place in memory where the object is stored. Now you
have two pointers (one in the collection and one in your variable), and you can perform operations on either of them
and either will perform that operation on the same piece of data in
memory.

*Kind of. Each collection has, again, a pointer to the same
object/model. When you remove that pointer from a collection, the
other pointers remain pointing to the same piece of memory, and that
memory is not erased, because it's still being pointed at from other
collections. model.destroy() will trigger a destroy event on both
the model and the collection it is holding a pointer to in it's
collection attribute. However, the model can not hold pointers
to multiple collections if it is a part of more than one collection.
So on your destroy event, it is removed only from the collection it was last assigned to - the one it holds in the model.collection attribute. Ordinarily, when no variables are holding pointers to the piece of data in memory, that memory will be erased, however, in this case, because your other collections have pointers to the model, the model remains in memory as a part of those collections.


text:
Q: How to limit user registration How do i limit the user registration in the registration page? i want to limit the user that can register to only 2 users. and if another user want to register, they will have a notice "Registration is Full".
Help me, i dont know what to do now, im looking for the answer for the whole week.
here's the php code of the registration process,
<?php

include('connection.php');

$name=$_POST['name'];
$username=$_POST['username'];
$password=$_POST['password'];
$password2=$_POST['password2'];

$sql=mysqli_query($conn,"INSERT INTO admin (name,username,password,password2) VALUES ('$name','$username','$password','$password2')");

if($sql == TRUE)
{
    echo '<script language="javascript">';
    echo 'alert("Register Successfully");';
    echo 'window.location.href="index_admin.php";';
    echo'</script>';
}

else
{
    echo "Error: ".$sql."<br>".$conn -> error;
}
    $conn -> close();

?>

A: Answer to your question: before inserting into database do a select count like

select count(*) from admin;

if returned rows are <=1 , do insert , otherwise do not insert.
you can also use different query and PHP mysqli_num_rows()
this might Help you PHP Manual
Now. advise.
you are not checking several thing before inserting

*

*always check data received should not be empty

*always check duplicate username

*always check escape characters

so please think what else can break your code.

A: If I understand your question correctly.....
You should do a query to select everything from your table then do a count of the result.
Then wrap your entire query inside an if() condition.
if($num_results < 2){
    // your code here
}else{
    // there are already two entries in your db
}


text:
Q: Class not found in dynamic web project using maven in eclipse I'm trying to connect to a JDBC database in my maven project, however the provider class path could not be found in the project. When I try the same code in a normal java project it works. Does anyone know how to include the classpath or something to solve this problem?
Class.forName("com.amazonaws.athena.jdbc.AthenaDriver");

Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("aws_credentials_provider_class", "athena.AmazonCredentialsProvider");

connection = DriverManager.getConnection("jdbc:awsathena://athena.us-east-1.amazonaws.com:443", properties);

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>PSRCore.Graph2</groupId>
    <artifactId>PSRCore.Graph2</artifactId>
    <version>1.0.3</version>
    <packaging>war</packaging>
    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>redshift</id>
            <url>http://redshift-maven-repository.s3-website-us-east-1.amazonaws.com/release</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.26</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.26</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.26</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>2.26</version>
        </dependency>
        <dependency>
            <groupId>com.amazon.redshift</groupId>
            <artifactId>redshift-jdbc42</artifactId>
            <version>1.2.1.1001</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.11</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.datastax.spark</groupId>
            <artifactId>spark-cassandra-connector_2.11</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.4.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>PSRCore.Graph2</finalName>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Caused by: java.lang.ClassNotFoundException:
  psrcore/graph2/athena/AmazonCredentialsProvider
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at
  com.amazonaws.athena.jdbc.AthenaDriverPropertiesFactory.lambda$parseProperties$2 (AthenaDriverPropertiesFactory.java:44)
... 31 more


text:
Q: While statement and def function I'm learning the def function and wrote this code:
def thirdpower(number):
    n=number**3
    print "%d to the 3rd power is %d" % (number,n)
thirdpower(input("Enter a number"))

But now, I want to add in a conditional statement (perhaps using the while statement) so that if a user leaves the input blank, it will print out an error, and will re-ask the user.
So far, I can't figure it out:
def thirdpower(number):
        n=number**3
while True:
    if len(thirdpower())==0:
        print "%d to the 3rd power is %d" % (number,n)
        thirdpower(input("Enter a number"))
    break
else:
    print "you entered a blank, please try again."

Any input is apreciated!! :)

A: Not sure I know exactly what you are up to, but this might help:
def thirdpower(n):
    return n**3
number = None
while not number:
    try:
        number = float(raw_input("Enter a number "))
    except:
        number = None
print "%d to the 3rd power is %d" % (number, thirdpower(number))

A: first of all, having a break statement in your while loop is a bad practice(not to mention while True), you should always focus on
having a condition that will quit itself
you can do something like this
user_input = input("enter a number")
while user_input == "" : #or other conditions you want to put
    print("error message")
    user_input = input("enter a number")

A: If your number is going to be raw_input from the user, then you could assign what number is before entering the while loop, or have the parameter passed to the function handle that.

A: What you want is this:
while True:
    try:
        number = int(input('Enter a number: '))
        break
    except ValueError:
        print('Please enter an integer.')

print('%d to the 3rd power is %d' % (number, thirdpower(number)))

In a try statement, if something goes wrong it looks for an except block. So in your case, when a user enters something that cannot be converted to an integer such as a non-number string or whitespace, it will fail and produce a ValueError. It will then look for the corresponding except block, and execute the statements nested within.
As it is in a while loop, this will keep happening until the input is found to be valid (by no exceptions occurring) and the while loop is broken, with number being the last entered value.

A: Python functions are recursive, use this functionnality :
def thirdpower():
    try:
        number = int(raw_input("Enter a number : "))
        n=number**3
        print "%d to the 3rd power is %d" % (number,n)
    except ValueError:
        print "You must enter an integer, please try again."
        thirdpower()

thirdpower()

The try: ... except:... blocks is used to determine if the value is an integer or not.

A: Try breaking up the problem in to multiple parts, getting the value and calculating the "thirdpower".
You will also want to make sure to convert your user input into an integer.
while True:
    try:
        user_val = int(raw_input("Enter a number: "))
        break
    except ValueError:
        print "You didn't enter a valid integer"
thirdpower(user_val)

If you want float values just change "int" to "float". You may also want to return the value from thirdpower:
def thirdpower(number):
    n = number**3
    print "%d to the 3rd power is %d" % (number, n)
    return n


text:
Q: Double precision in parentheses in C Working with a double, I can set
double x = 216/22            //Output's 9.818181...

However, when I try:
double x = (216/22)          //Outputs 9.00000...
double x = ((double)216/22)  //Outputs 9.0000...
double x = (216/(double)22)  //Outputs 9.818181...

Why does (216/22) return 9 and not 9.8181...?

A:
Why does (216/22) return 9 and not 9.8181...?

Because both 216 and 22 are int - and the result is an int.
(216.0/22) would return double as expected.

A: #include <stdio.h>

int main ( void )
{
    double w = 216/22;
    double x = (216/22);
    double y = ((double)216/22);
    double z = (216/(double)22);

    printf("w %lf\n",w);
    printf("x %lf\n",x);
    printf("y %lf\n",y);
    printf("z %lf\n",z);
    return(0);
}

output exactly as expected
w 9.000000
x 9.000000
y 9.818182
z 9.818182

Two integer divisions converted to double, then two double divisions.  If you didnt get that then something is wrong with your compiler or your code or pilot error handling the experiment.  Then after you solve your compiler/code issue then consult C tutorial documentation on typecasting.  You told the compiler to do an integer division, which means there is no fractional remainder, then you converted that integer 9 to a double 9.0.  For the other two you asked the compiler to convert the integers to double first then do a double divide, which means you get to keep the fractional remainder.
then if you do this
#include <stdio.h>

union
{
    unsigned int ui[2];
    double d;
} myun;

int main ( void )
{
    double w = 216/22;
    double x = (216/22);
    double y = ((double)216/22);
    double z = (216/(double)22);
    unsigned int r = (1/10)*10;
    unsigned int s = ((double)1/10)*10;
    unsigned int t = (1/10.0)*10;

    printf("w %lf\n",w);
    printf("x %lf\n",x);
    printf("y %lf\n",y);
    printf("z %lf\n",z);
    printf("r %u\n",r);
    printf("s %u\n",s);
    printf("t %u\n",t);
    return(0);
}

you get
w 9.000000
x 9.000000
y 9.818182
z 9.818182
r 0
s 1
t 1

exactly as expected.
this doesnt change the output for this test
unsigned int t = (1/10.0F)*10;

but it is doing something different than without the F in there.

A: double x = (216/22)
Is interpreted as two integers, then the result is casted to a double. If you want to do this without casting, and keep precision, do:
double x = (216.0/22.0) // outputs 9.818181...

A: By the line:
double x = (216/22) //Outputs 9.00000..., you are performing an integer division to specify both values as double:
double x = 216.0/22.0  or double x = (double)216/(double)22
If either of the values were to have been of type double or casted to it then the resultant would be of type double.


text:
Q: RxJS 5 Observable and Angular2 http: Call ajax once, save the result, and subsequent ajax calls use cached result The code below is a simplified version of what I currently have:
name.service.ts
@Injectable()
export class NameService {

    const nameURL = "http://www.example.com/name";

    getName() {
        return this.http.get(nameURL);
    }
}

name1.component.ts
@Component({
    templateUrl: './name1.component.html',
    styleUrls: ['./name1.component.css']
})
export class Name1Component implmenets OnInit {

    private name1;

    constructor(
        private nameService: NameService
    ){}

    ngOnInit() {
        this.setupName();
    }

    private setupName() {

        this.nameService.getName()
            .subscribe(
                resp => this.name1 = resp,
                error => this.name1 = "unknown"
            );
    }
}

name2.component.ts
@Component({
    templateUrl: './name2.component.html',
    styleUrls: ['./name2.component.css']
})
export class Name2Component implmenets OnInit {

    private name2;

    constructor(
        private nameService: NameService
    ){}

    ngOnInit() {
        this.setupName();
    }

    private setupName() {

        this.nameService.getName()
            .subscribe(
                resp => this.name2 = resp,
                error => this.name2 = "unknown"
            );
    }
}

Here is what I want to do, name1.component.ts will first call the getName method of the NameService class. getName will then make an ajax call and return an observable.
Next, name2.component.ts will also call the same getName method of the NameService class, and getName will also perform the same ajax call and return an observable.
Is it possible using rxjs whereby when getName method in NameService makes its first ajax call, it then stores the result of the ajax call. Any subsequent function calls to the getName method will instead return the cache result of the first ajax call and not perform another redundant ajax.

A: You can subscribe to the Observable multiple times, so if all you want to do is save the second network request for data shared between two Components, you can cache it in your Service like this:
@Injectable()
export class NameService {

    const nameURL = "http://www.example.com/name";
    private cache: Observable<any>;

    getName() {
        return this.cache || this.cache = this.http.get(nameURL);
    }
}


text:
Q: scom 2012 You have specified the wrong server for this operation we are getting the following error in scom 2012.
The AD Health Set has detected a problem with mailbox.eu.domainname.com at 10/8/2013 5:41:37 AM. The Health Manager is reporting that ActiveDirectoryConnectivityConfigDCProbe/mailbox.eu.domainname.com Failed with Error message: Received a referral to eu.domainname.com when requesting DC=eu,DC=domainname,DC=com from dc1.us.domainname.com You have specified the wrong server for this operation
So we have the following AD set up
root: domainname.com
child domain: us (1 mailbox server used to keep mail contacts for Office365)+
child domain: eu  (all Exchange server are here but one mailbox server)
We get this error on 2 Exchange 2013 mailbox servers and 1 Exchange 2013 cas server
Here is a break down of our Exchange org. We are moving to Exchange 2013 from Exchange 2010
domain.com: has 2 HUB/CAS both Exchange 2010
us: 1 Mailbox Exchange 2013 and 1 mailbox Exchange 2010
eu: 3 Mailbox Exchange 2013 and 3 Mailbox Exchange 2010, 3 CAS Exchange 2013 and 3 CAS Exchange 2010
when we are done with Exchange 2010 we will have the following
domain.com: 0 Exchange servers
us: 1 Mailbox Exchange 2013
eu: 3 Mailbox Exchange 2013, 3 CAS Exchange 2013
Now that i have given some back ground you can see that the dc1 is in the wrong domain. The accounts in dc1.us.domainname.com don't exist on mailbox.eu.domainname.com

A: AD monitoring is buggy a lot, so first of all you should clear agents


text:
Q: What does 'const gchar *' mean, and does that memory need to be freed after use? I have the following code:
int main()
{

const gchar *wew = gtk_entry_get_text(GTK_ENTRY(gtkentrywidget));

return 0;
}

gtk_entry_get_text() returns a const gchar*, so does wew need to be deallocated or not, and why?

A: A gchar is just a typedef for the C type char.  You must not deallocate this specific pointer.  Per the documentation:

Returns : a pointer to the contents of the widget as a string. This string points to internally allocated storage in the widget and must not be freed, modified or stored.

A: gtk_entry_get_text returns a const gchar* instead of a gchar* to prevent you from trying to free the memory. The documentation of the function even tells you so. Of course if you cast the returned value to gchar*, you're able to free it, but that's just because the C language doesn't prevent you from doing silly things.
For exemple, as that memory chunk is internally used by your GtkEntry, if you free that memory chunk, and later call gtk_entry_set_text, your program  will crash. This is because the memory where it tries to write is unallocated...


text:
Q: How fibers can exist in Java I know that my question is more academic than a real issue. In most cases a thread implementation with Fiber-like logic would be OK. But is there any way to implement Fibers as they are described in the JVM?
Is there any framework that is missing me to achieve that?

A: There were/are Java EE frameworks, that enable to have a class with normal control flow like a Java SE application, and thus maintain state. To function over HTTP at specific points the classes instance is serialized, a response is made to the client, and on the next request the instance is deserialized and continues. This is not a general purpose coroutine solution, and I would certainly not call fibers.
Unfortunately its name slips my mind. But that was a specific case of running one single coroutine transfering control to the framework coroutine.
AOP offers another mean to switch control. Could maybe be used to implement fibers.


text:
Q: Misalignment of values in Python The following code should create a dictionary in which the keys are the words of the input sentence and the values, starting with the number 1, respectively, to represent the number of words in the sentence. Does the following code work correctly for you?The values are not in order for me and I am very confused.
sentence =input()
list_words=sentence.split()
for i in list_words:
    d = {word: i for i, word in enumerate(list_words, 1)}
print(d)

A: Try this.
sentence = str(input('Give your sentence: '))
list_words = sentence.split()
dict_word = {}
count=1
for i in list_words:
    dict_word[i] = count
    count += 1
print(dict_word)

My output with this code is this:
Give your sentence: The following code should create a dictionary of input sentence words and give the

{The': 1, 'following': 2, 'code': 3, 'should': 4, 'create': 5, 'a': 6, 'dictionary': 7, 'of': 8, 'input': 9, 'sentence': 10, 'words': 11, 'and': 12, 'give': 13, 'the': 14}


text:
Q: Multiple case statements in Impala I have one table with transaction_date,sal,name and age columns.
Query: If transactions is made in last 24 months. If this is Yes, then it should check the age whether age lies in between 18-54 or not. If this condition is yes it should display a string as success, failure on false condition. If the transactions is made in last 24 months. If this is false, then get the no. of transactions. If it is Yes, then average of salaries
I have given overview as below according to my requirement. This to be executed in impala as a query.
transaction made in last 24 months --Yes->Is Age in between 18-54 --Yes->success
                                                                  --No-->failure
                                --No-->get no.of transactions--Yes-->sal avg

Please share me the exact query in impala for the same


text:
Q: Mongoose populate documents I got 3 database models in mongoose that looks like this:
//profile.js
var ProfileSchema   = new Schema({
    username:    { type: String, required: true },
    password:    { type: String, required: true },
    matches:    [{ type: Schema.Types.ObjectId, ref: 'Match' }]
});

//match.js
var MatchSchema   = new Schema({
    scores:     [{ type: Schema.Types.ObjectId, ref: 'Score',  required: true }],
});

//score.js
var ScoreSchema   = new Schema({
    score:       {type: Number, required: true},
    achivement: [{type: String, required: true}],
});

And I try to populate a profile with
Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) })
            .populate('matches')
            .populate('matches.scores')
            .exec(function(err, profile) {
                if (err) {...}
                if (profile) {
                   console.log(profile);
                }
            });

The matches get populated but I dont get the scores in matches to populate. Is this not supported in mongoose or do I do something wrong? Populate gives me this:
{
    user_token: "539b07397c045fc00efc8b84"
    username: "username002"
    sex: 0
    country: "SE"
    friends: []
    -matches: [
        -{
            __v: 1
            _id: "539eddf9eac17bb8185b950c"
            -scores: [
                "539ee1c876f274701e17c068"
                "539ee1c876f274701e17c069"
                "539ee1c876f274701e17c06a"
            ]
        }
    ]
}

But I want to populate the score array in the match array. Can I do this?

A: Yes, you are right. I tried using Chaining of populate I got same output.
For your query please use async.js and then populate by the method mentioned below.
For more details please have a look at this code snippet. It is a working, tested, sample code according to your query. Please go through the commented code for better understanding in the code below and the link of the snippet provided.
//Find the profile and populate all matches related to that profile
Profile.findOne({
    _id: mongoose.Types.ObjectId(profile_id)
})
.populate('matches')
.exec(function(err, profile) {
    if (err) throw err;

    //We got the profile and populated matches in Array Form
    if (profile) {
        // Now there are multiple Matches
        // We want to fetch score of each Match
        // for that particular profile

        // For each match related to that profile
        async.forEach(profile.matches, function(match) {
            console.log(match, 'match')
            // For each match related to that profile
            // Populate score achieved by that person
            Match.find({
                _id:match.id
            })
            .populate('scores', 'score')
            .exec(function (err, score) {
                if (err) throw err;

                // here is score of all the matches
                // played by the person whose profile id
                // is passed
                console.log(score);
            })
        })
    }
});

A: Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) })
        .populate('matches.scores')
        .exec(function(err, profile) {
            if (err) {...}
            if (profile) {
               console.log(profile);
            }
        });


text:
Q: HTTP Error 414 - Requested URI is too long / base64 image I am trying to pull an base64 encoded image from a hosted XML file into my jQuery mobile app, but I get this error.

Failed to load resource: the server responded with a status of 414
  (Request-URI Too Long)

I know that for URLs, shortening them fixes the error but I can't shorten a base64 string.
Any ways around this?

A: I know this is an old question so I hope someone can benefit form my answer.
I just experienced this problem myself. I have gone through a few posts elsewhere and most of of what I read suggested you make sure your 64base string in your img src starts with data:image/;base64...

Unfortunately that was not my issue. I was getting the (Request-URI Too Long) because my base64 had been JSON stringified so it looked something like this.

Anyways, that's the two places I'd look for an error.


text:
Q: TypeError: this.props.clickitem is not a function I have created RoundedButton component as a child component. I am sending click button value into parent component using
  _handleButtonClick(item) {
    this.props.clickitem(item.buttonText);
  }

Compiler throws an error
TypeError: this.props.clickitem is not a function
RoundedButton._handleButtonClick
D:\ReactJS\xxx\src\RoundedButton.js:8
   5 |  state = {};
   6 |
   7 |  _handleButtonClick(item) {
>  8 |    this.props.clickitem(item.buttonText);
   9 |  }
  10 |
  11 |  render() {
View compiled

RoundedButton.js
import React, { Component } from "react";
import "./App.css";

class RoundedButton extends Component {
  state = {};

  _handleButtonClick(item) {
    this.props.clickitem(item.buttonText);
  }

  render() {
    let buttonText = this.props.text;
    return (
      <button
        type="button"
        className="Button"
        onClick={this._handleButtonClick.bind(this, { buttonText })}
      >
        {buttonText}
      </button>
    );
  }
}

export default RoundedButton;

App.js
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.clickitem = this.clickitem.bind(this);
  }

  clickitem(buttonText) {
    console.log(buttonText);
  }

  render() {
    return (

        Score:

          <RoundedButton text="Rock" clickitem={this.clickitem} />
          <RoundedButton text="Paper" />
          <RoundedButton text="Scissors" />

    );
  }
}

export default App;

Can anyone help me what I am doing wrong ?

A: Your code works. However for the RoundedButton with the text set to "rocks". However you might have forgotten to put clickitem props on the other two RoundedButton components

class RoundedButton extends React.Component {
  state = {};

  _handleButtonClick(item) {
    this.props.clickitem(item.buttonText);
  }

  render() {
    let buttonText = this.props.text;
    return (
      <button
        type="button"
        className="Button"
        onClick={this._handleButtonClick.bind(this, { buttonText })}
      >
        {buttonText}
      </button>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.clickitem = this.clickitem.bind(this);
  }

  clickitem(buttonText) {
    console.log(buttonText);
  }

  render() {
    return (

        Score:

          <RoundedButton text="Rock" clickitem={this.clickitem} />
          <RoundedButton text="Paper" clickitem={this.clickitem}/>
          <RoundedButton text="Scissors" clickitem={this.clickitem}/>

    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));


text:
Q: Complex filtering in rails app. Not sure complex sql is the answer? I have an application that allows users to filter applicants based on very large set of criteria. The criteria are each represented by boolean columns spanning multiple tables in the database. Instead of using active record models I thought it was best to use pure sql and put the bulk of the work in the database. In order to do this I have to construct a rather complex sql query based on the criteria that the users selected and then run it through AR on the db. Is there a better way to do this? I want to maximize performance while also having maintainable and non brittle code at the same time? Any help would be greatly appreciated.

A: It is hard to answer this question fully without knowing more details, but I'll try anyway.
While databases are bad at quite a few things, they are very good at filtering data, especially when it comes to a high volumes.
If you do the filtering in Ruby on Rails (or just about any other programming language), the system will have to retrieve all of the unfiltered data from the database, which will cause tons of disk I/O and network (or interprocess) traffic. It then has to go through all those unfiltered results in memory, which may be quite a burdon on RAM and CPU.
If you do the filtering in the database, there is a pretty good chance that most of the records will never be actually retrieved from disk, won't be handed over to RoR and won't then be filtered. The main reason for indexes to even exist is for the sole purpose of avoiding expensive operations in order to speed things up. (Yes, they also help maintain data integrity)
To make this work, however, you may need to help the database a bit to do its job efficiently. You will have to create indexes matching your filtering criteria, and you may have to look into performance issues with certain types of queries (how to avoid temporary tables and such). However, it is definately worth it.
Having that said, there actually are a few types of queries that a given database is not good at doing. Those are few and far between, but they do exist. In those cases, an implementation in RoR might be the better way to go. Even without knowing more about your scenario, I'd say it's a pretty safe bet that your queries are not among those.

A: As @hazzit said, it is difficult to answer without much details, but here's my two cents on this. Raw SQL is usually needed to perform complex operations like aggregates, calculations, etc. However, when it comes to search / filtering features, I often find using raw SQL overkill and not quite maintainable.
The key question here is : can you break down your problem in multiple independent filters ?
If the answer is yes, then you should leverage the power of ActiveRecord and Arel. I often find myself implementing something like this in my model :
scope :a_scope, ->{ where something: true }
scope :another_scope, ->( option ){ where an_option: option }
scope :using_arel, ->{ joins(:assoc).where Assoc.arel_table[:some_field].not_eq "foo" }
# cue a bunch of scopes

def self.search( options = {} )
  output   = relation
  relation = relation.a_scope if options[:an_option]
  relation = relation.another_scope( options[:another_option] ) unless options[:flag]
  # add logic as you need it
end

The beauty of this solution is that you declare a clean interface in which you can directly pour all the params from your checkboxes and fields, and that returns a relation. Breaking the query into multiple, reusable scopes helps keeping the thing readable and maintainable ; using a search class method ties it all together and allows thorough documentation... And all in all, using Arel helps securing the app against injections.
As a side note, this does not prevent you from using raw SQL, as long as the query can be isolated inside a scope.
If this method is not suitable to your needs, there's another option : use a full-fledged search / filtering solution like Sunspot. This uses another store, separate from your db, that indexes defined parts of your data for easy and performant search.


text:
Q: Align image representing horizontal content border between two elements representing navigation elements I'm trying to horizontally align three elements; navigation back button, horizontal content border and navigation next button.

  back

 continue

Example: https://jsfiddle.net/qd6uens0/1/
The problem is, border has to be responsive. So it has to adapt to the space left between navigation buttons and all three elements have to stay in the same line.
My border has only 1 pixel height, unlike the one in the jsfiddle example.
Thank you!

A: You can do this with CSS table and :before

.form-navigation {
  display: table;
  width: 100%;
  vertical-align: middle;
}

.form-bottom-border-wrapper {
  width: 100%;
  display: table-cell;
  vertical-align: middle;
  position: relative;
}

.form-bottom-border-wrapper:before {
  position: absolute;
  top: 50%;
  height: 1px;
  border-bottom: 1px solid black;
  width: 100%;
  content: "";
}

.form-back, .form-continue {
  display: table-cell;
  vertical-align: middle;
}

  back

  continue


text:
Q: How to run subtitles in video using video.js for Opera, Chrome? I wrote code to insert subtitles in the video
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8"/>
        <title>name</title>

    <link rel = "stylesheet" href = "skript/video-js.min.css" />
    <script src = "skript/video.min.js"> </script>

    </head>
<body>
<video
  class="video-js"
  controls
  preload="auto"
  width="640"
  height="264"
  data-setup='{}'>
  <source src="1.mp4" type="video/mp4">

    <track label="rus" kind="subtitles" srclang="ru" src="sub/rus.vtt"/>
    <track label="eng" kind="subtitles" srclang="en" src="sub/eng.vtt"/>

  </video>
</body>

</html>

But it does not work with browsers Opera, Chrome
Is there any way to fix this?

A: Did you try to embed vtt/subtitles files in m3u8 package? It works with all browsers.


text:
Q: System.QueryException unexpected token Trying to return all fields in object

System.QueryException: unexpected token: '('

when I run the Invocable class at the parents = assignment
public with sharing class AuditReportBulkifyClass {

    @InvocableMethod(label='Collect Bulkified Records')
    public static List<List<hdone__AuditReport__c>> gatherRequests(Request[] requests) {

        // Gather bulkified records from Flow
        Map<Id, hdone__AuditReport__c> parents = new Map<Id, hdone__AuditReport__c>();

        // Want to get all fields from object for use in Flows
        Map<String, Schema.SobjectField> fieldMap = hdone__AuditReport__c.SobjectType.getDescribe().fields.getMap();
        Set<String> fieldNames = fieldMap.keySet();
        String myset_Joined = string.join(new List<String>(fieldNames), ',');
        String theQuery = 'SELECT ' + myset_Joined + ' FROM hdone__AuditReport__c WHERE Id IN :parents.keySet()';

        for(Request request : requests) {
            parents.put(request.recordId, null);
        }

        parents = new Map<Id, hdone__AuditReport__c>(
            (List<hdone__AuditReport__c>)Database.query(theQuery)
        );

        // Flows must return List<List> for Sobject Collections. This is returned as Sobject Collection to Flow
        List<List<hdone__AuditReport__c>> responseColl = new List<List<hdone__AuditReport__c>>();

        // Add all of the values to an initial List
        List<hdone__AuditReport__c> responseList = new List<hdone__AuditReport__c>();
        responseList.addAll(parents.values());

        System.debug('Size of ResponseList ' + responseList.size());

        // Adds actual values we will use to the List of List
        responseColl.add(responseList);
        System.debug('Return responseColl size ' + responseColl.size());

        // Initialize a new list which will return empty to ensure return same number of interviews back to Flow
        List<hdone__AuditReport__c> emptyList = new List<hdone__AuditReport__c>();

        // Iterate through number of interviews - 1 and assign to empty list
        for (Integer i=0; i<responseList.size()-1; i++){
            responseColl.add(emptyList);
            }
        return responseColl;
    }

    public with sharing class Request {
        @InvocableVariable(label='Record ID' required=true)
        public Id recordId;

        @InvocableVariable(label='Object API Name' required=false)
        public String objectName;

        @InvocableVariable(label='Parent ID' required=false)
        public Id parentId;
    }
}

A: There are some variable bindings that "normal" SOQL can resolve, but Dynamic SOQL cannot.
It's probably not a perfect rule, but if your variable binding includes a period/dot/full-stop like you have in parents.keySet(), then chances are that it won't work with Dynamic SOQL.
See the "Dynamic SOQL Considerations" section of the documentation on dynamic SOQL for a better idea of what, precisely, is and is not allowed.
The solution here is to store your parents.keySet() in a dedicated variable of type Set<Id> sometime prior to when you need it in your dynamic query. You could probably use String.format() somehow as well.