text:
Q: Add user to remote windows share using WMI I have a share on the root of C:\ on a remote computer IMPC-1111, and I'm trying to add a user /w access masks:
FullControl = 2032127
Change = 1245631
[ReadOnly] = 1179817

I've figured out how to read them....but cannot figure out how to write/change them. This is the code I use to read them.
Private Function GetSharedFolderAccessRule() As DataTable

    Dim DT As DataTable = New DataTable()

    Try

        DT.Columns.Add("ShareName")
        DT.Columns.Add("Caption")
        DT.Columns.Add("Path")
        DT.Columns.Add("Domain")
        DT.Columns.Add("User")
        DT.Columns.Add("AccessMask")
        DT.Columns.Add("AceType")

        Dim Con As ConnectionOptions = New ConnectionOptions
        Con.Username = "Username"
        Con.Password = "Password"

        'Dim Scope As ManagementScope = New ManagementScope("\\.\root\cimv2", Con)
        Dim Scope As ManagementScope = New ManagementScope("\\IMPC-1111\root\cimv2", Con)
        Scope.Connect()

        Dim Query As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_LogicalShareSecuritySetting")
        Dim Searcher As ManagementObjectSearcher = New ManagementObjectSearcher(Scope, Query)
        Dim QueryCollection As ManagementObjectCollection = Searcher.[Get]()

        For Each SharedFolder As ManagementObject In QueryCollection

            If True Then
                Dim ShareName As String = CType(SharedFolder("Name"), String)
                Dim Caption As String = CType(SharedFolder("Caption"), String)
                Dim LocalPath As String = String.Empty
                Dim Win32Share As ManagementObjectSearcher = New ManagementObjectSearcher("SELECT Path FROM Win32_share WHERE Name = '" & ShareName & "'")

                For Each ShareData As ManagementObject In Win32Share.[Get]()
                    LocalPath = CType(ShareData("Path"), String)
                Next

                Dim Method As ManagementBaseObject = SharedFolder.InvokeMethod("GetSecurityDescriptor", Nothing, New InvokeMethodOptions())
                Dim Descriptor As ManagementBaseObject = CType(Method("Descriptor"), ManagementBaseObject)
                Dim DACL As ManagementBaseObject() = CType(Descriptor("DACL"), ManagementBaseObject())

                For Each ACE As ManagementBaseObject In DACL
                    Dim Trustee As ManagementBaseObject = CType(ACE("Trustee"), ManagementBaseObject)
                    Dim Row As DataRow = DT.NewRow()
                    Row("ShareName") = ShareName
                    Row("Caption") = Caption
                    Row("Path") = LocalPath
                    Row("Domain") = CType(Trustee("Domain"), String)
                    Row("User") = CType(Trustee("Name"), String)
                    Row("AccessMask") = CType(ACE("AccessMask"), UInt32)
                    Row("AceType") = CType(ACE("AceType"), UInt32)
                    DT.Rows.Add(Row)
                    DT.AcceptChanges()
                Next
            End If
        Next

    Catch ex As Exception
        MessageBox.Show(ex.StackTrace, ex.Message)
    End Try

    Return DT

End Function

Can anyone point me in the right direction? Is this even possible to write using WMI?
Thanks!

A: You can use the Win32_LogicalShareSecuritySetting.SetSecurityDescriptor() method to modify the share permissions.  Modifying the existing permissions works as follows...

*

*Get the desired Win32_LogicalShareSecuritySetting instance.

*Call GetSecurityDescriptor() to get the share's security descriptor as a Win32_SecurityDescriptor instance.

*Get the security descriptor's discretionary access control list through its DACL property.

*Create a new access control entry.

*

*Get a reference to the Win32_ACE class.

*Create an instance of the Win32_ACE class.

*Set the AccessMask, AceFlags, AceType, and Trustee properties of the access control entry.

*

*Get a reference to the Win32_Trustee class.

*Create an instance of the Win32_Trustee class.

*Specify the principal for the entry by setting the SIDString or Name (and Domain) property of the trustee.

*

*Querying instances of the Win32_Account class or its derivatives would be one way to get these values.

*Create a new access control list combining the existing entries and the new entry.

*

*Per Order of ACEs in a DACL, ensure Deny entries are ordered before Allow entries.

*Set the DACL property of the security descriptor to the new access control list.

*Call SetSecurityDescriptor() to save the share's security descriptor.

The following class contains methods to get the properties of a share and, in particular, add a new access control entry via the AddAccessControlEntry() method...
Imports System.Management
Imports System.Security.AccessControl

Friend Class ShareSecurity
    Private ReadOnly Property ShareName As String

    Private ReadOnly Property GetOptions As ObjectGetOptions

    Private ReadOnly Property Scope As ManagementScope

    Public Sub New(host As String, shareName As String, username As String, password As String)
        Me.ShareName = shareName
        GetOptions = New ObjectGetOptions()
        Scope = New ManagementScope(
            New ManagementPath() With {
                .NamespacePath = "root\cimv2",
                .Server = host
            },
            New ConnectionOptions() With {
 _ ' ***** For demonstration purposes only! *****
 _ 'TODO: Find a secure way to store the remote password
                .Password = password,
                .Username = username
            }
        )
    End Sub

    Public Function GetShareProperties() As IDictionary(Of String, Object)
        Dim sharePath As New ManagementPath($"Win32_Share.Name=""{ShareName}""")

        Using share As New ManagementObject(Scope, sharePath, GetOptions)
            Return GetPropertyDictionary(share)
        End Using
    End Function

    Public Function GetShareSecurityDescriptorProperties() As IDictionary(Of String, Object)
        Using shareSecurity As ManagementObject = GetShareSecurity()
            Using securityDescriptor As ManagementBaseObject = GetShareSecurityDescriptor(shareSecurity)
                Return GetPropertyDictionary(securityDescriptor)
            End Using
        End Using
    End Function

    Public Sub AddAccessControlEntry(entryType As AceType, entryRights As FileSystemRights, securityIdentifier As String)
        AddAccessControlEntry(
            entryType,
            entryRights,
            Sub(trustee)
                trustee("SIDString") = securityIdentifier
            End Sub
        )
    End Sub

    Public Sub AddAccessControlEntry(entryType As AceType, entryRights As FileSystemRights, domain As String, account As String)
        AddAccessControlEntry(
            entryType,
            entryRights,
            Sub(trustee)
                trustee("Domain") = domain
                trustee("Name") = account
            End Sub
        )
    End Sub

    ''' <param name="trusteeInitializer">Initializes the Win32_Trustee instance for the access control entry to be added.</param>
    Public Sub AddAccessControlEntry(entryType As AceType, entryRights As FileSystemRights, trusteeInitializer As Action(Of ManagementObject))
        Using shareSecurity As ManagementObject = GetShareSecurity()
            Using securityDescriptor As ManagementBaseObject = GetShareSecurityDescriptor(shareSecurity)
                Dim accessControlEntries As ManagementBaseObject() = DirectCast(securityDescriptor("DACL"), ManagementBaseObject())

                ' The class must not be created in the remote scope otherwise CreateInstance()
                ' throws "System.UnauthorizedAccessException: 'Access is denied'."
                Using accessControlEntryClass As New ManagementClass("Win32_ACE")
                    Using accessControlEntry As ManagementObject = accessControlEntryClass.CreateInstance()
                        accessControlEntry("AccessMask") = CUInt(entryRights)
                        accessControlEntry("AceFlags") = CUInt(AceFlags.None)
                        accessControlEntry("AceType") = CUInt(entryType)

                        ' The class must not be created in the remote scope otherwise CreateInstance()
                        ' throws "System.UnauthorizedAccessException: 'Access is denied'."
                        Using trusteeClass As New ManagementClass("Win32_Trustee")
                            Using trustee As ManagementObject = trusteeClass.CreateInstance()
                                trusteeInitializer.Invoke(trustee)
                                accessControlEntry("Trustee") = trustee

                                ' Create a new access control list including the new access control
                                ' entry, sorted with Deny entries first (true sorts after false)
                                ' https://learn.microsoft.com/windows/win32/secauthz/order-of-aces-in-a-dacl
                                securityDescriptor("DACL") = accessControlEntries _
                                    .Append(accessControlEntry) _
                                    .OrderByDescending(Function(entry) CType(entry("AceType"), AceType)) _
                                    .ToArray()

                                SetShareSecurityDescriptor(shareSecurity, securityDescriptor)
                            End Using
                        End Using
                    End Using
                End Using
            End Using
        End Using
    End Sub

    Private Function GetShareSecurity() As ManagementObject
        Dim shareSecurityPath As New ManagementPath($"Win32_LogicalShareSecuritySetting.Name=""{ShareName}""")

        Return New ManagementObject(Scope, shareSecurityPath, GetOptions)
    End Function

    Private Function GetShareSecurityDescriptor(shareSecurity As ManagementObject) As ManagementBaseObject
        ' Create an array to store the output parameter
        Dim invokeParameters(0) As ManagementBaseObject
        Dim invokeResult As UInteger = shareSecurity.InvokeMethod("GetSecurityDescriptor", invokeParameters)

        If invokeResult = 0 Then
            Return invokeParameters(0)
        Else
            'TODO: Handle failure of GetSecurityDescriptor()...
            Return Nothing
        End If
    End Function

    Private Sub SetShareSecurityDescriptor(shareSecurity As ManagementObject, securityDescriptor As ManagementBaseObject)
        ' Create an array to store the input parameter
        Dim invokeParameters() As ManagementBaseObject = {securityDescriptor}
        Dim invokeResult As UInteger = shareSecurity.InvokeMethod("SetSecurityDescriptor", invokeParameters)

        If invokeResult <> 0 Then
            'TODO: Handle failure of SetSecurityDescriptor()...
        End If
    End Sub

    Private Shared Function GetPropertyDictionary(obj As ManagementBaseObject) As IDictionary(Of String, Object)
        Return obj.Properties _
            .Cast(Of PropertyData)() _
            .ToDictionary(
                Function([property]) [property].Name,
                Function([property])
                    ' Recursively create dictionaries in place of management objects
                    Dim baseObjectArray As ManagementBaseObject() = TryCast([property].Value, ManagementBaseObject())

                    If baseObjectArray IsNot Nothing Then
                        Return baseObjectArray.Select(AddressOf GetPropertyDictionary).ToArray()
                    Else
                        Dim baseObject As ManagementBaseObject = TryCast([property].Value, ManagementBaseObject)

                        If baseObject IsNot Nothing Then
                            Return GetPropertyDictionary(baseObject)
                        Else
                            Return [property].Value
                        End If
                    End If
                End Function
            )
    End Function
End Class

The following program uses the above ShareSecurity class to display the properties of a remote share and, optionally, add a new access control entry to it...
Imports System.Security.AccessControl

Public Class Program
    Public Shared Sub Main(args As String())
        If args Is Nothing OrElse args.Length = 0 Then
            DisplayUsage()
        ElseIf args.Length < 4 Then
            DisplayError("Too few arguments.")
        Else
            Dim host As String = args(0)
            Dim shareName As String = args(1)
            Dim username As String = args(2)
            ' ***** For demonstration purposes only! *****
            'TODO: Find a secure way to store the remote password
            Dim password As String = args(3)
            Dim shareSecurity As New ShareSecurity(host, shareName, username, password)

            DisplayShareProperties(shareSecurity)
            DisplaySecurityDescriptor(shareSecurity)

            If args.Length > 4 Then
                If args.Length <> 7 AndAlso args.Length <> 8 Then
                    DisplayError("Argument count mismatch.")
                Else
                    Dim entryType As AceType

                    If Not [Enum].TryParse(args(4), True, entryType) Then
                        DisplayError($"Invalid <type> value ""{args(4)}"".")
                    Else
                        Dim entryRights As FileSystemRights

                        If Not [Enum].TryParse(args(5), True, entryRights) Then
                            DisplayError($"Invalid <rights> value ""{args(5)}"".")
                        Else
                            DisplayTextWithSeparator("New access control entry")
                            Console.WriteLine($"   Type: {entryType}")
                            Console.WriteLine($" Rights: {entryRights}")

                            If args.Length = 7 Then
                                Dim securityIdentifier As String = args(6)

                                Console.WriteLine($"    SID: {securityIdentifier}")
                                shareSecurity.AddAccessControlEntry(entryType, entryRights, securityIdentifier)
                            Else ' args.Length = 8
                                Dim domain As String = args(6)
                                Dim account As String = args(7)

                                Console.WriteLine($" Domain: {domain}")
                                Console.WriteLine($"Account: {account}")
                                shareSecurity.AddAccessControlEntry(entryType, entryRights, domain, account)
                            End If
                            Console.WriteLine()
                            DisplaySecurityDescriptor(shareSecurity)
                        End If
                    End If
                End If
            End If
        End If
    End Sub

    Private Shared Sub DisplayUsage()
        Dim entryAssemblyPath As String = System.Reflection.Assembly.GetEntryAssembly().Location
        Dim entryAssemblyName As String = System.IO.Path.GetFileName(entryAssemblyPath)

        Console.WriteLine("Display share properties:")
        Console.WriteLine()
        Console.WriteLine($"{entryAssemblyName} <host> <share> <username> <password>")
        Console.WriteLine()
        Console.WriteLine("Add access control entry:")
        Console.WriteLine()
        Console.WriteLine($"{entryAssemblyName} <host> <share> <username> <password> <type> <rights> <sid>")
        Console.WriteLine($"{entryAssemblyName} <host> <share> <username> <password> <type> <rights> <domain> <account>")
        Console.WriteLine()
        Console.WriteLine(vbTab & $"  <type> - A {GetType(AceType).FullName} enumeration value.")
        Console.WriteLine(vbTab & $"<rights> - A {GetType(FileSystemRights).FullName} enumeration value.")
        Console.WriteLine(vbTab & "   <sid> - An account security identifier.")
        Console.WriteLine()
    End Sub

    Private Shared Sub DisplayError(message As String)
        Console.WriteLine($"ERROR: {message}")
        Console.WriteLine()
        DisplayUsage()
    End Sub

    Private Shared Sub DisplayTextWithSeparator(text As String)
        Console.WriteLine(text)
        Console.WriteLine(New String("-"c, text.Length))
    End Sub

    Private Shared Sub DisplayShareProperties(shareSecurity As ShareSecurity)
        Dim shareProperties As IDictionary(Of String, Object) = shareSecurity.GetShareProperties()

        DisplayTextWithSeparator("Share properties")
        For Each propertyName As String In New String() {"Description", "Name", "Path"}
            DisplayProperty(shareProperties, propertyName)
        Next
        Console.WriteLine()
    End Sub

    Private Shared Sub DisplaySecurityDescriptor(shareSecurity As ShareSecurity)
        Dim securityDescriptorProperties As IDictionary(Of String, Object) = shareSecurity.GetShareSecurityDescriptorProperties()

        DisplayTextWithSeparator("Share security descriptor")
        DisplayProperty(securityDescriptorProperties, "ControlFlags", Function(value) CType(value, ControlFlags))
        Console.WriteLine()

        Dim accessControlList As IDictionary(Of String, Object)() = securityDescriptorProperties("DACL")
        For i As Integer = 0 To accessControlList.Length - 1
            Dim accessControlEntryProperties As IDictionary(Of String, Object) = accessControlList(i)

            DisplayTextWithSeparator($"Access control entry #{i}")
            DisplayProperty(accessControlEntryProperties, "AccessMask", Function(value) CType(value, FileSystemRights))
            DisplayProperty(accessControlEntryProperties, "AceFlags", Function(value) CType(value, AceFlags))
            DisplayProperty(accessControlEntryProperties, "AceType", Function(value) CType(value, AceType))
            DisplayProperty(accessControlEntryProperties, "Trustee", Function(value) DirectCast(value, IDictionary(Of String, Object))("Name"))
            Console.WriteLine()
        Next
    End Sub

    Private Shared Sub DisplayProperty(properties As IDictionary(Of String, Object), propertyName As String)
        DisplayProperty(properties, propertyName, Nothing)
    End Sub

    Private Shared Sub DisplayProperty(properties As IDictionary(Of String, Object), propertyName As String, selector As Func(Of Object, Object))
        Dim propertyValue As Object = properties(propertyName)
        Dim displayValue As Object = If(
            selector IsNot Nothing,
            selector.Invoke(propertyValue),
            If(propertyValue, "<null>")
        )

        Console.WriteLine($"{propertyName}: {displayValue}")
    End Sub
End Class

Given a share like this...

...with Full Control granted to Administrators and Read granted to Everyone, calling the program like this...
SO60271689.exe MyComputer "My Share" MyUser MyPassword AccessDenied "Modify, Synchronize" S-1-5-32-546

...or like this...
SO60271689.exe MyComputer "My Share" MyUser MyPassword AccessDenied "Modify, Synchronize" BUILTIN Guests

...produces output like this...
Share properties
----------------
Description: This is the share description.
Name: My Share
Path: C:\My Share

Share security descriptor
-------------------------
ControlFlags: DiscretionaryAclPresent, SelfRelative

Access control entry #0
-----------------------
AccessMask: ReadAndExecute, Synchronize
AceFlags: None
AceType: AccessAllowed
Trustee: Everyone

Access control entry #1
-----------------------
AccessMask: FullControl
AceFlags: None
AceType: AccessAllowed
Trustee: Administrators

New access control entry
------------------------
   Type: AccessDenied
 Rights: Modify, Synchronize
    SID: S-1-5-32-546

Share security descriptor
-------------------------
ControlFlags: DiscretionaryAclPresent, SelfRelative

Access control entry #0
-----------------------
AccessMask: Modify, Synchronize
AceFlags: None
AceType: AccessDenied
Trustee: Guests

Access control entry #1
-----------------------
AccessMask: ReadAndExecute, Synchronize
AceFlags: None
AceType: AccessAllowed
Trustee: Everyone

Access control entry #2
-----------------------
AccessMask: FullControl
AceFlags: None
AceType: AccessAllowed
Trustee: Administrators

Since VB.NET is not my native tongue, here's the equivalent C# code I started with to get things working...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Security.AccessControl;

namespace SO60271689.CSharp
{
    internal class ShareSecurity
    {
        private string ShareName
        {
            get;
        }

        private ObjectGetOptions GetOptions
        {
            get;
        }

        private ManagementScope Scope
        {
            get;
        }

        public ShareSecurity(string host, string shareName, string username, string password)
        {
            ShareName = shareName;
            GetOptions = new ObjectGetOptions();
            Scope = new ManagementScope(
                new ManagementPath() {
                    NamespacePath = @"root\cimv2",
                    Server = host
                },
                new ConnectionOptions() {
                    // ***** For demonstration purposes only! *****
                    //TODO: Find a secure way to store the remote password
                    Password = password,
                    Username = username
                }
            );
        }

        public IDictionary<string, object> GetShareProperties()
        {
            ManagementPath sharePath = new ManagementPath($"Win32_Share.Name=\"{ShareName}\"");

            using (ManagementObject share = new ManagementObject(Scope, sharePath, GetOptions))
                return GetPropertyDictionary(share);
        }

        public IDictionary<string, object> GetShareSecurityDescriptorProperties()
        {
            using (ManagementObject shareSecurity = GetShareSecurity())
            using (ManagementBaseObject securityDescriptor = GetShareSecurityDescriptor(shareSecurity))
                return GetPropertyDictionary(securityDescriptor);
        }

        public void AddAccessControlEntry(AceType entryType, FileSystemRights entryRights, string securityIdentifier)
        {
            AddAccessControlEntry(
                entryType,
                entryRights,
                trustee => trustee["SIDString"] = securityIdentifier
            );
        }

        public void AddAccessControlEntry(AceType entryType, FileSystemRights entryRights, string domain, string account)
        {
            AddAccessControlEntry(
                entryType,
                entryRights,
                trustee => {
                    trustee["Domain"] = domain;
                    trustee["Name"] = account;
                }
            );
        }

        /// <param name="trusteeInitializer">Initializes the Win32_Trustee instance for the access control entry to be added.</param>
        private void AddAccessControlEntry(AceType entryType, FileSystemRights entryRights, Action<ManagementObject> trusteeInitializer)
        {
            using (ManagementObject shareSecurity = GetShareSecurity())
            using (ManagementBaseObject securityDescriptor = GetShareSecurityDescriptor(shareSecurity))
            {
                ManagementBaseObject[] accessControlEntries = (ManagementBaseObject[]) securityDescriptor["DACL"];

                // The class must not be created in the remote scope otherwise CreateInstance()
                // throws "System.UnauthorizedAccessException: 'Access is denied'."
                using (ManagementClass accessControlEntryClass = new ManagementClass("Win32_ACE"))
                using (ManagementObject accessControlEntry = accessControlEntryClass.CreateInstance())
                {
                    accessControlEntry["AccessMask"] = (uint) entryRights;
                    accessControlEntry["AceFlags"] = (uint) AceFlags.None;
                    accessControlEntry["AceType"] = (uint) entryType;

                    // The class must not be created in the remote scope otherwise CreateInstance()
                    // throws "System.UnauthorizedAccessException: 'Access is denied'."
                    using (ManagementClass trusteeClass = new ManagementClass("Win32_Trustee"))
                    using (ManagementObject trustee = trusteeClass.CreateInstance())
                    {
                        trusteeInitializer.Invoke(trustee);
                        accessControlEntry["Trustee"] = trustee;

                        // Create a new access control list including the new access control
                        // entry, sorted with Deny entries first (true sorts after false)
                        // https://learn.microsoft.com/windows/win32/secauthz/order-of-aces-in-a-dacl
                        securityDescriptor["DACL"] = accessControlEntries
                            .Append(accessControlEntry)
                            .OrderByDescending(entry => (AceType) (uint) entry["AceType"] == AceType.AccessDenied)
                            .ToArray();

                        SetShareSecurityDescriptor(shareSecurity, securityDescriptor);
                    }
                }
            }
        }

        private ManagementObject GetShareSecurity()
        {
            ManagementPath shareSecurityPath = new ManagementPath($"Win32_LogicalShareSecuritySetting.Name=\"{ShareName}\"");

            return new ManagementObject(Scope, shareSecurityPath, GetOptions);
        }

        private ManagementBaseObject GetShareSecurityDescriptor(ManagementObject shareSecurity)
        {
            // Create an array to store the output parameter
            ManagementBaseObject[] invokeParameters = new ManagementBaseObject[1];
            uint invokeResult = (uint) shareSecurity.InvokeMethod("GetSecurityDescriptor", invokeParameters);

            if (invokeResult == 0)
                return invokeParameters[0];
            else
            {
                //TODO: Handle failure of GetSecurityDescriptor()...
                return null;
            }
        }

        private void SetShareSecurityDescriptor(ManagementObject shareSecurity, ManagementBaseObject securityDescriptor)
        {
            // Create an array to store the input parameter
            ManagementBaseObject[] invokeParameters = new ManagementBaseObject[1] { securityDescriptor };
            uint invokeResult = (uint) shareSecurity.InvokeMethod("SetSecurityDescriptor", invokeParameters);

            if (invokeResult != 0)
            {
                //TODO: Handle failure of SetSecurityDescriptor()...
            }
        }

        private static IDictionary<string, object> GetPropertyDictionary(ManagementBaseObject obj)
        {
            return obj.Properties
                .Cast<PropertyData>()
                .ToDictionary(
                    property => property.Name,
                    // Recursively create dictionaries in place of management objects
                    property => property.Value is ManagementBaseObject[] baseObjectArray
                        ? baseObjectArray.Select(GetPropertyDictionary).ToArray()
                        : property.Value is ManagementBaseObject baseObject
                        ? GetPropertyDictionary(baseObject)
                        : property.Value
                );
        }
    }
}

using System;
using System.Collections.Generic;
using System.Security.AccessControl;

namespace SO60271689.CSharp
{
    class Program
    {
        public static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
                DisplayUsage();
            else if (args.Length < 4)
                DisplayError("Too few arguments.");
            else
            {
                string host = args[0];
                string shareName = args[1];
                string username = args[2];
                // ***** For demonstration purposes only! *****
                //TODO: Find a secure way to store the remote password
                string password = args[3];
                ShareSecurity shareSecurity = new ShareSecurity(host, shareName, username, password);

                DisplayShareProperties(shareSecurity);
                DisplaySecurityDescriptor(shareSecurity);

                if (args.Length > 4)
                {
                    if (args.Length != 7 && args.Length != 8)
                        DisplayError("Argument count mismatch.");
                    else
                    {
                        if (!Enum.TryParse(args[4], true, out AceType entryType))
                            DisplayError($"Invalid <type> value \"{args[4]}\".");
                        else if (!Enum.TryParse<FileSystemRights>(args[5], true, out FileSystemRights entryRights))
                            DisplayError($"Invalid <rights> value \"{args[5]}\".");
                        else
                        {
                            DisplayTextWithSeparator("New access control entry");
                            Console.WriteLine($"   Type: {entryType}");
                            Console.WriteLine($" Rights: {entryRights}");

                            if (args.Length == 7)
                            {
                                string securityIdentifier = args[6];

                                Console.WriteLine($"    SID: {securityIdentifier}");
                                shareSecurity.AddAccessControlEntry(entryType, entryRights, securityIdentifier);
                            }
                            else // args.Length == 8
                            {
                                string domain = args[6];
                                string account = args[7];

                                Console.WriteLine($" Domain: {domain}");
                                Console.WriteLine($"Account: {account}");
                                shareSecurity.AddAccessControlEntry(entryType, entryRights, domain, account);
                            }
                            Console.WriteLine();
                            DisplaySecurityDescriptor(shareSecurity);
                        }
                    }
                }
            }
        }

        private static void DisplayUsage()
        {
            string entryAssemblyPath = System.Reflection.Assembly.GetEntryAssembly().Location;
            string entryAssemblyName = System.IO.Path.GetFileName(entryAssemblyPath);

            Console.WriteLine("Display share properties:");
            Console.WriteLine();
            Console.WriteLine($"{entryAssemblyName} <host> <share> <username> <password>");
            Console.WriteLine();
            Console.WriteLine("Add access control entry:");
            Console.WriteLine();
            Console.WriteLine($"{entryAssemblyName} <host> <share> <username> <password> <type> <rights> <sid>");
            Console.WriteLine($"{entryAssemblyName} <host> <share> <username> <password> <type> <rights> <domain> <account>");
            Console.WriteLine();
            Console.WriteLine($"\t  <type> - A {typeof(AceType).FullName} enumeration value.");
            Console.WriteLine($"\t<rights> - A {typeof(FileSystemRights).FullName} enumeration value.");
            Console.WriteLine("\t   <sid> - An account security identifier.");
            Console.WriteLine();
        }

        private static void DisplayError(string message)
        {
            Console.WriteLine($"ERROR: {message}");
            Console.WriteLine();
            DisplayUsage();
        }

        private static void DisplayTextWithSeparator(string text)
        {
            Console.WriteLine(text);
            Console.WriteLine(new string('=', text.Length));
        }

        private static void DisplayShareProperties(ShareSecurity shareSecurity)
        {
            IDictionary<string, object> shareProperties = shareSecurity.GetShareProperties();

            DisplayTextWithSeparator("Share properties");
            foreach (string propertyName in new string[] { "Description", "Name", "Path" })
                DisplayProperty(shareProperties, propertyName);
            Console.WriteLine();
        }

        private static void DisplaySecurityDescriptor(ShareSecurity shareSecurity)
        {
            IDictionary<string, object> securityDescriptorProperties = shareSecurity.GetShareSecurityDescriptorProperties();

            DisplayTextWithSeparator("Share security descriptor");
            DisplayProperty(securityDescriptorProperties, "ControlFlags", value => (ControlFlags) (uint) value);
            Console.WriteLine();

            IDictionary<string, object>[] accessControlList = (IDictionary<string, object>[]) securityDescriptorProperties["DACL"];
            for (int i = 0; i < accessControlList.Length; i++)
            {
                IDictionary<string, object> accessControlEntryProperties = accessControlList[i];

                DisplayTextWithSeparator($"Access control entry #{i}");
                DisplayProperty(accessControlEntryProperties, "AccessMask", value => (FileSystemRights) (uint) value);
                DisplayProperty(accessControlEntryProperties, "AceFlags", value => (AceFlags) (uint) value);
                DisplayProperty(accessControlEntryProperties, "AceType", value => (AceType) (uint) value);
                DisplayProperty(accessControlEntryProperties, "Trustee", value => ((IDictionary<string, object>) value)["Name"]);
                Console.WriteLine();
            }
        }

        private static void DisplayProperty(IDictionary<string, object> properties, string propertyName)
        {
            DisplayProperty(properties, propertyName, null);
        }

        private static void DisplayProperty(IDictionary<string, object> properties, string propertyName, Func<object, object> selector)
        {
            object propertyValue = properties[propertyName];
            object displayValue = selector != null
                ? selector.Invoke(propertyValue)
                : propertyValue ?? "<null>";

            Console.WriteLine($"{propertyName}: {displayValue}");
        }
    }
}


text:
Q: Centering a div inside a li I have the following piece of HTML:

© 2011. All rights reserved.

And the following piece of CSS:
#downmenu {
    font-size:14px;
    border-top: 1px solid #666;
    clear: both;
    list-style-type: none;
    margin: 20px 0;
    overflow: hidden;
    padding: 11px 0 11px 34px;
    width: 870px;
}

#downmenu li {
    float:left;
}

#downmenu li.copyright {
    margin-right:540px;
    height:36px;
}

#downmenu li.copyright div{
    margin: auto 0;
}

(I think) #downmenu li.copyright is set to 36px tall, and I want to centre vertically the div inside it. To achieve that I've used margin: auto 0;. But it isn't centered.
Any clue?

A: Remove the div altogether and use line-height to center your text.
Setting the line height equal to the height of the li will center it vertically.
    #downmenu li.copyright {
    margin-right:540px;
    height:36px;
    line-height:36px;
}

A: Try this:
#downmenu li.copyright {
    margin-right:540px;
    height:36px;
    display: table-cell;
    vertical-align: middle;
}

A: You will need to have line-height to be the same as the li height.
height: 36px;
line-height: 36px;
I see you have paddings, this might change how you see the div. Use something like Chrome Developer Console or firebug to see how your CSS is applied.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel Filter works badly Helo Everyone,
I have a problem with filter, please help me.
I used filters before and everything was ok.
Today, I imported data from a text file. After importing data, I used a filter as in the attachment and rows don't meet criteria still appear.
Can you help me?

A: Looks like the filter was not applied to the whole range of cells.  Since there is a line there that appears to be all blank (row 211), the filter may have stopped at that spot instead of covering all the data.
If you select all the cells (really columns A:C) and apply the filter again, it should probably work.


text:
Q: Bulk MIgration from MongoDB to PostgreSQL using MoSql Hi I need to migrate my MongoDB into PostgreSQL.I used MoSql tool for that purpose. I created a collection map as following and saved in test.yaml file.
  test_db:
  check_collection:
    :columns:
    - id:
      :source: _id
      :type: TEXT
    - user_name:
      :source: user_name
      :type: TEXT
    - action_time:
      :source: action_time
      :type: TIMESTAMP
    :meta:
      :table: check_collection
      :extra_props: true

where test_db is my MongoDB and check_collection is my collection..and execute this using mosql and its working fine.All my raws inside check_collection is copied to PostgreSQL.
My question is that how to convert my all collections in mongoDB into PostgreSQL using a single test.yaml file? I have around 50+ collections in my project, so creating 50 yaml independent file is not a good idea.


text:
Q: Client not communicating in a chat application I have created the multi chat application.
Current Problem
When I compile my class Chatinterface 2 times, 2 clients open up. Now When I am trying to communicate by typing a text message in the text area. The other client does not show the message and vice versa.
Can someone correct my code? and tell me what is happening.
Please don't be harsh I am only a beginner.
Please note I have provided the code of the server as well for a detailed explanation.
package stack;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;

class Chatinterface implements ActionListener,Runnable {

    private JFrame chatwindow;
    JTextArea typemsg;
    JTextArea displaymsg;
    JButton sendbutton;
    JButton logoutbutton;
    Socket client;
    BufferedReader read;
    PrintWriter write;
    String getmsg;
    String gettext;
    public Chatinterface(){

        try {
            client = new Socket("localhost",3420);
            write = new PrintWriter(client.getOutputStream());

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        displaygui();
    }

    private void displaygui() {
        chatwindow = new JFrame();
        chatwindow.setResizable(false);
        chatwindow.setBounds(100, 100, 450, 300);
        chatwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SpringLayout springLayout = new SpringLayout();
        chatwindow.getContentPane().setLayout(springLayout);

        typemsg = new JTextArea();
        springLayout.putConstraint(SpringLayout.NORTH, typemsg, 171, SpringLayout.NORTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.WEST, typemsg, 10, SpringLayout.WEST, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.SOUTH, typemsg, -10, SpringLayout.SOUTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.EAST, typemsg, 340, SpringLayout.WEST, chatwindow.getContentPane());
        chatwindow.getContentPane().add(typemsg);

        displaymsg = new JTextArea();
        displaymsg.setWrapStyleWord(true);
        displaymsg.setEditable(false);
        springLayout.putConstraint(SpringLayout.NORTH, displaymsg, 10, SpringLayout.NORTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.WEST, displaymsg, 0, SpringLayout.WEST, typemsg);
        springLayout.putConstraint(SpringLayout.SOUTH, displaymsg, 160, SpringLayout.NORTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.EAST, displaymsg, 0, SpringLayout.EAST, typemsg);
        chatwindow.getContentPane().add(displaymsg);

        sendbutton = new JButton("Send");
        springLayout.putConstraint(SpringLayout.NORTH, sendbutton, -76, SpringLayout.SOUTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.WEST, sendbutton, 5, SpringLayout.EAST, typemsg);
        springLayout.putConstraint(SpringLayout.SOUTH, sendbutton, -27, SpringLayout.SOUTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.EAST, sendbutton, 82, SpringLayout.EAST, typemsg);
        chatwindow.getContentPane().add(sendbutton);
        sendbutton.addActionListener(this);
        sendbutton.setActionCommand("S");

        logoutbutton = new JButton("Logout");
        springLayout.putConstraint(SpringLayout.NORTH, logoutbutton, 50, SpringLayout.NORTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.WEST, logoutbutton, -65, SpringLayout.EAST, sendbutton);
        springLayout.putConstraint(SpringLayout.SOUTH, logoutbutton, 108, SpringLayout.NORTH, chatwindow.getContentPane());
        springLayout.putConstraint(SpringLayout.EAST, logoutbutton, 0, SpringLayout.EAST, sendbutton);
        chatwindow.getContentPane().add(logoutbutton);
        logoutbutton.addActionListener(this);
        logoutbutton.setActionCommand("L");
        chatwindow.setVisible(true);

    }
    public static void main(String args[])
    {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Chatinterface method = new Chatinterface();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t1 = new Thread();
        t1.start();
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {

        if(arg0.getActionCommand().equals("S"))
        {
            String gettext2;
            gettext2 = typemsg.getText();
            write.println(gettext2);
            displaymsg.append(gettext2+"\n");
            typemsg.setText("");
        }

        if(arg0.getActionCommand().equals("L")){
            System.exit(0);
        }

    }
    @Override
    public void run() {
        String readmsg;

        try {
            read = new BufferedReader(new InputStreamReader(client.getInputStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            readmsg = read.readLine();

            while(readmsg!=null)
            {

                displaymsg.append(readmsg);

            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Here is the class handler that is invoked whenever a new client is connected.
package stack;

import java.io.*;
import java.net.*;

public class Handler implements Runnable {
    Socket s;

    String getmsg = null;
    String sendmsg;

    public Handler(Socket s) {
        this.s = s;

    }
    public void run() {
            BufferedReader reader1 = null;
            PrintWriter writer1 = null;

            try {
                reader1 = new BufferedReader(new InputStreamReader(
                        s.getInputStream()));
                writer1 = new PrintWriter(s.getOutputStream(), true);
                sendmsg = reader1.readLine();
                while (sendmsg!=null) {

                        writer1.println(sendmsg);

                }
                reader1.close();
                writer1.close();
                s.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }

    }
}

Here is the main server class
package stack;

import java.net.*;
public class Servera  {
    public static void main(String[] args) throws Exception {
        Socket s;
        ServerSocket server = new ServerSocket(3420);

        while(true)
        {
            s = server.accept();
            Handler handler1 = new Handler(s);
            Thread t1 = new Thread(handler1);
            t1.start();
        }

    }
}

A: Your server is not getting message sent by client.For that you need to flush the OutputStream in client using write.flush()
Following will be the code change:
   if(arg0.getActionCommand().equals("S"))
        {
            String gettext2;
            gettext2 = typemsg.getText();
            write.println(gettext2);
            write.flush()
            displaymsg.append(gettext2+"\n");
            typemsg.setText("");
        }

Also your logic for sending message from one client to another is not proper.As per your code the server will send message to same client from which it has received the message.FOr this you need to maintain the pool of client sockets and then broadcast the messages to all clients.Hope these answer your query.
Please accept the answer if it is right.


text:
Q: Centre contact clamping in coaxial barrel connectors Barrel connector plugs seem to have two different methods for keeping the centre contact under pressure.  Some plugs have a rigid circular inner contact which relies on the socket to have a split pin which can press outwards to maintain contact (eg., the non-yellow plugs below).  Others have a pair of clamps within the plug itself, which (I assume) press against a solid pin in the socket (eg., the yellow ones below).

I need plugs like those yellow ones, but with solder tags.  When searching, how do I refer to them in a way that distinguishes them from the plugs with a rigid inner contact?
They don't have to be yellow.


text:
Q: What sort of database design would I need to use in case I wanted users to save tags, and be able to call already used tags? I'm trying to implement a feature similar to StackOverflow's tag feature. That a user can create a new tag, or by typing pull up a list of similar tags already created.
This is such a wonderful feature on this site and I find it sad that most sites do not have something like this. It's both robust, and yet very very flexible and best of all: driven by the community.
So I have these two tables:
Company
    id
    email
    name
    companySize
    countryOfOrigin
    industryid

Industry
    id
    description

Every time a user writes a new tag, I want to create one with a unique ID, and also be able to search for existing tags.

Will this database design allow for an easy and efficient implementation of this feature?

If not, please give a little guidance. :)

A: Whilst there's not a tremendous amount of information to go on, what you've listed should be fine. (The 'tag' being the 'description' field in the industry table, etc.)
As you might imagine, all of the real work is done outside of SQL, where you'll need to...

*

*(Potentially) add new tag(s) that don't yet exist.

*Associate the industry with the supplied tag(s).

*(Potentially) prune previously used tags that may no longer be in use.

...every time you edit an industry.
That said, the key limitation of your proposed setup is that each company can only belong to a single industry. (i.e.: It can only have a single industry tag associated with it.)
As such, you might want to consider a schema along the lines of...
Company
    id
    ...
    countryOfOrigin

Industries
    id
    description

CompanyIndustriesLookup
    companyID
    industryID

...which would let you associate multiple industries/tags with a given company.
Update...
For example, under this setup, to get all of the tags associated with company ID 1, you'd use...
SELECT Industries.description FROM (CompanyIndustriesLookup, Industries)
WHERE companyID=1 AND industryID=Industries.ID
ORDER BY Industries.description ASC;

On a similar basis, to get all companies tagged with an industry of "testing", you'd use...
SELECT Company.name FROM (Company, Industries, CompanyIndustriesLookup)
WHERE Company.id=CompanyIndustriesLookup.companyID
AND Industries.id=CompanyIndustriesLookup.industryID
AND Industries.description="testing"
ORDER BY Company.name ASC

A: A very easy (if somewhat suboptimal, but it often does not matter) solution to use tags is to not have tag ids at all. So, you have:
Items
    ItemId
    Name
    Description
    ...

ItemTag
    ItemId
    Tag

Adding a tag to an item is just adding the tuple to the ItemTag table, whether the tag already exists or not. And you don't have to do any bookkeeping on removing tags either. Just keep an index on ItemTag.Tag, to be able to quickly display all unique tags.


text:
Q: jCarousel arrow disable if there are no more image in the left or right I use Sorgalla jcarousel.
Lets say that I have nine images and the script is set with scroll: 3, and i am watching image 1-3, then the arrow should be only on the right side, which means i can browse for more pics to the right. then, when i browse the the right and i am watching f.e. image 4,5,6, in this case the arrows should be on boths sides, because there are pics to the left and to the right. BUT, if i browse again to the right and get until image 7,8,9, the the arrow on right side should disappear because there is nothing more to browse to the right. only the left arrow should be shown in this case.
My script:
jQuery(document).ready(function($) {
    myCarousel = null; // This will be the carousel object

    function mycarousel_initCallback(carousel, state) {
        if (state == 'init') {
            myCarousel = carousel;
        }
        $('#arrows_gallery_next').bind('click', function() {
            carousel.next();
            return false;
        });
        $('#arrows_gallery_prev').bind('click', function() {
            carousel.prev();
            return false;
        });

        $('.product-view .product-img-box .more-views .jcarousel-skin-tango .jcarousel-item').width(<?php echo $thumbX;?>);

    };

    jQuery('#arrows_gallery_carousel').jcarousel({
        scroll: 1,
        visible:3,
        initCallback: mycarousel_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null,
            setupCallback:function(){
               jQuery('#arrows_gallery_carousel.jcarousel-list li').each(function(){
                    jQuery(this).width(103)
               })
            },
    });
});

A: Change your paging handlers to keep track of the page number and enable / disable the paging buttons once they reach the start or end.
function mycarousel_initCallback(carousel, state) {
    var page = 1;
    $('#arrows_gallery_prev').css('visibility', 'hidden');

    if (state == 'init') {
        myCarousel = carousel;
    }
    $('#arrows_gallery_next').bind('click', function() {
        carousel.next();
        page++;
        $('#arrows_gallery_prev').css('visibility', 'visible');
        $('#arrows_gallery_next').css('visibility', (page == 3) ? 'hidden' : 'visible');
        return false;
    });
    $('#arrows_gallery_prev').bind('click', function() {
        carousel.prev();
        page--;
        $('#arrows_gallery_next').css('visibility', 'visible');
        $('#arrows_gallery_prev').css('visibility', (page == 1) ? 'hidden' : 'visible');
        return false;
    });

    $('.product-view .product-img-box .more-views .jcarousel-skin-tango .jcarousel-item').width(<?php echo $thumbX;?>);

};

By the way, you mentioned that the scroll was set to 3, but your configuration has scroll as 1.


text:
Q: How to transform a shape in Snap.svg without applying the transformation to its mask? I want to transform a rectangle (position, scale, and angle) that has a mask.
I created a fiddle file to demonstrate my problem.
http://jsfiddle.net/MichaelSel/vgw3qxpg/2/
Click the green rectangle, and see how it moves in relationship to the circle on top of it. The rectangle is moving and the circle is stationary. This is how I want to objects to act.
But now click the button on top.
The circle is now a mask for the green rectangle, now when you press it, you can see that that the transformations are applied to the mask as well. (the circle doesn't stay stationary like when it wasn't a mask).
I know that more often then not, you want to treat a mask this way, but for my app I want the opposite.
I was able to overcome this problem by creating an opposite movement in the blue example.
With that, my demo is very simple and I am looking to implement this in a big app. Is there a way to achieve what I want without all the hassle?
This is the code for the green(bad) example:
  s = Snap("#player")
    rect = s.rect(100, 100, 100, 100).attr({"fill" : "green" })
    circle = s.circle(200, 200, 50).attr({"fill" : "white" })
    rect.attr("mask",circle)
    rect.click(function () {
        rect.transform("t20,10s1.1...")
    })

This is the code for the blue (good) example:
    rect2 = s.rect(300, 100, 100, 100).attr({ "fill": "blue" })
    circle2 = s.circle(400, 200, 50).attr({ "fill": "white" })
    rect2.attr("mask", circle2)
    rect2.click(function () {
        rect2.transform("t20,10s1.1...")
        circle2.transform("t-20,-10s"+1/1.1 + "...")
    })

Any suggestions?
Thank you.

A: If you put the rectangle in a group, and then apply the mask to the group, you can transform the rect any way you like without affecting the mask.
s = Snap("#player")
rect = s.rect(100, 100, 100, 100).attr({"fill" : "green" })
g = s.group(rect);
circle = s.circle(200, 200, 50).attr({"fill" : "white" })
rect.click(function () {
    rect.transform("t20,10s1.1...")
})

$("#myButton").click(function () {
    g.attr("mask",circle)
})

http://jsfiddle.net/vgw3qxpg/3/


text:
Q: How can I toggle the Fn key lock on an LG Gram running Linux? Most laptops allow toggling the Fn key lock (whether you have to press the Fn key or not to use the special functions of the f1-f12 keys like adjusting screen brightness or volume), with a shortcut like Fn+esc, or a setting in the BIOS or system preferences. On the LG Gram, there is a setting in the BIOS (press F2 while on startup to boot to the BIOS, then press Ctrl+Alt+F7 to show more options, and look for the setting under Advanced), but that setting doesn't seem to have any effect when booted into Linux. I always have to press Fn to use the special functions of f1-f12.

A: For WINDOWS 11 - The LG Gram has an app that allows changing the function key lock. Depending on your LG Gram model, use either LG Control Panel or LG Smart Assistant.
In LG Smart Assistant, choose Keyboard from the left navigation menu, then scroll down to Lock Fn Key and turn this ON to lock function keys in the mode that controls hardware features (volume, brightness, etc.)
In LG Control Panel, Go to System Settings and scroll to Hotkey mode setting and select USE - to eneble hotkeys (hardware controls) instead of Fn key as primary function.

A: I found the setting for the Fn key lock on the LG Gram in Linux. The setting is stored as a 1 or a 0 in a file called /sys/devices/platform/lg-laptop/fn_lock. To see what value is set, run cat /sys/devices/platform/lg-laptop/fn_lock. If it is 0 you need to press the Fn key to use the special functions, and if it is 1 you don't need to use the Fn key for the special functions. You can edit this file in a text editor, and change the value to 1 to lock the Fn key. But setting the value this way will only persist for the current session, and get reset on reboot.
To make this setting persistent after a reboot, you can create a udev rule. Create the file /etc/udev/rules.d/99-fnlock.rules with the following content:
SUBSYSTEM=="platform", DRIVER=="lg-laptop", ATTR{fn_lock}="1"

Now the function lock setting will be persistent after rebooting. You may find a few other interesting LG Gram feature settings here: https://www.kernel.org/doc/html/latest/admin-guide/laptops/lg-laptop.html


text:
Q: create one list from to two columns in need Help with oracle SQL.
I have a table with
 from   to
 F      B
 B      R
 R      D
 E      X
 X      Q

and I need the list
F
B
R
D
E
X
Q

so my problem is the jump from R-->D to E-->X
Edit: It's a big list with from and to, seperatet with a annother column as citerium. Normaly there is every from in the to column, so i used
SELECT from,snr as Nr FROM list where StrAbsNr = 1
union all
SELECT to,snr + 1 as Nr FROM list

to create a ordered list. But there are gaps in some parts, in the example there is D-->E missing
has anybody an idea ?

A: select "from" as val from table
union
select to from table

And if you want to keep the order:
select distinct val
from (select "from" as val, rownum, 1 as valOrder from table
    union
    select to, rownum, 2 as valOrder from table)
order by rownum,valOrder

A: for your example this work:
WITH ft AS
  (SELECT 'f' vfrom, 'b' AS vto FROM dual  UNION ALL
  SELECT 'b' , 'r' FROM dual  UNION ALL
  SELECT 'r','d' FROM dual  UNION ALL
  SELECT 'e','x' FROM dual  UNION ALL
  SELECT 'x','q' FROM dual  )
SELECT a.a,  MAX(rn), MIN(ob)
FROM
  ( SELECT vfrom a , rownum rn, 1 ob FROM ft
  UNION ALL
  SELECT vto , rownum rn, 2 ob FROM ft
  ) a
GROUP BY a
ORDER BY MAX(rn), MIN(ob)

A    MAX(RN)    MIN(OB)
- ---------- ----------
f          1          1
b          2          1
r          3          1
d          3          2
e          4          1
x          5          1
q          5          2

 7 rows selected

or analityc func row_number:
SELECT *
FROM
  (SELECT a.a,
    row_number() over (partition BY a order by rn, ob) rna,
    ob,
    rn
  FROM
    ( SELECT vfrom a, rownum rn, 1 ob FROM ft
    UNION ALL
    SELECT vto , rownum rn, 2 ob FROM ft
    ) a
  )
WHERE rna=1
ORDER BY rn,
  ob
A        RNA         OB         RN
- ---------- ---------- ----------
f          1          1          1
b          1          2          1
r          1          2          2
d          1          2          3
e          1          1          4
x          1          2          4
q          1          2          5

 7 rows selected


text:
Q: How to cancel tip in eclipse pydev? I use eclipse and pydev, I have canceled the tips by using

*

*perferences-general-editors-text editor-annotation: error, spelling errors and warning

*perferences-pydev-editor: hover, and  code analysis(including undefined)

*Preferences->Java->Editor->Hovers--Combined Hover
But when cursor stay on some function names, there's still a prompt box: "Undefined variable:function-name  press f2 for focus".
Could anyone please tell me how to cancel these tips ?


text:
Q: Evaluating definite integral with functions as limits This was a physics example regarding electric field, but I need some help in the calculation part.
Positive charge $Q$ is uniformly distributed along the $y-axis$ between $y=-a$ and $y=+a$. Find the electric field $P$ on the $x-axis$ at a distance $x$ from the origin
So the electric field is generated by a rod, which is broke into infinitesimal segments.
Rod below
| <== $dy$
|
| -------------$x$------------ $P$
|
|
Each segment is called $dy$
$x$ is the distance from $P$ to the rod
$2a$ is the length of rod
$Q$ is total charge, $Q/2a$ is the linear charge density
After a series of steps, the textbook reached the following step, for the $x$ component of the electric field:
$$ E_{x} = \frac{1}{4\pi \epsilon_{0}} \frac{Q}{2a} \int_{-a}^{a} \frac{x{\,}dy}{(x^2+y^2)^{3/2}} $$
the detail of evaluation was omitted in the textbook, but it's evaluated to  $$ E_{x} = \frac{Q}{4\pi \epsilon_{0}} \frac{1}{x \sqrt {x^2+a^2}} $$
I spent a good deal of time trying to evaluate this integral myself using substitution but all met dead ends. I need some guidance on this.

A: What you need is essentially the followig indefinite integral:
\begin{align}
\int \frac{1}{(x^2+y^2)^{3/2}}\,dy
&=\int \frac{\cos u}{x^2}du& (y=x\tan(u),\ dy=x\sec^2(u)du)\\
&=\frac{\sin(u)}{x^2}+C\\
&=\frac{\sin(\tan^{-1}\frac{y}{x})}{x^2}+C\\
&=\frac{y}{x^2\sqrt{x^2+y^2}}+C
\end{align}
It follows that
\begin{align}
\int_{-a}^a\frac{x}{(x^2+y^2)^{3/2}}dy
&=2x\int_{0}^a\frac{1}{(x^2+y^2)^{3/2}}dy\\
&=2x\cdot \frac{y}{x^2\sqrt{x^2+y^2}}\big|_{y=0}^{y=a}\\
&=\frac{2a}{x\sqrt{x^2+a^2}}
\end{align}

A: First, notice that $x$ is a constant with respect to the variable of integration, and so
\begin{align}
E_{x} &= \frac{1}{4\pi \epsilon_{0}} \frac{Q}{2a} \int_{-a}^{a} \frac{x{\,}dy}{(x^2+y^2)^{3/2}}\\
& = \frac{x}{4\pi \epsilon_{0}} \frac{Q}{2a} \int_{-a}^{a} \frac{dy}{(x^2+y^2)^{3/2}}.
\end{align}
Now, let
\begin{align}
y &= x\tan(u)\\
dy &= x\sec^{2}(u)\,du.
\end{align}
Then, using the identity $\tan^2(u) + 1 = \sec^2(u)$, we obtain
\begin{align}
\int \frac{dy}{(x^2+y^2)^{3/2}} &=\int\frac{x\sec^{2}(u)\,du}{(x^{2} + x^{2}\tan^{2}(u))^{3/2}}\\
&=\int\frac{x\sec^{2}(u)\,du}{(x^{2}\sec^2(u))^{3/2}}\\
&=\frac{1}{x^{2}}\int \cos(u)\,du\\
&=\frac{1}{x^{2}}\sin(u) + C.
\end{align}
Now, $$\tan(u) = \frac{y}{x} \implies \sin(u) = \frac{y}{\sqrt{x^2 + y^2}},$$ and so we have $$\int \frac{dy}{(x^2+y^2)^{3/2}} = \frac{y}{x^{2}\sqrt{x^{2} + y^{2}}} + C.$$  Using this to evaluate the definite integral:
$$\int_{-a}^{a} \frac{dy}{(x^2+y^2)^{3/2}} = \frac{y}{x^{2}\sqrt{x^{2} + y^{2}}}\Bigg|_{-a}^{a} = \frac{2a}{x^{2}\sqrt{x^2 + a^2}}.$$  Putting everything back together, then, we obtain
$$E_{x} = \frac{x}{4\pi \epsilon_{0}} \frac{Q}{2a} \int_{-a}^{a} \frac{dy}{(x^2+y^2)^{3/2}} = \frac{x}{4\pi \epsilon_{0}} \frac{Q}{2a}\frac{2a}{x^{2}\sqrt{x^2 + a^2}}=\frac{Q}{4\pi \epsilon_{0}} \frac{1}{x \sqrt {x^2+a^2}}.$$


text:
Q: Chartjs - pointColor to follow current color of gradient stroke I just created Line Chart using chartjs library and I managed to make stroke in gradient color. Here is simple fiddle example what I did so far.
What I need next, is to make pointColor to follow gradient stroke and to pick up the current color of it's position. Like on this photo.
Any ideas how to achieve that?
Thanks!

A: Update
From @AndyHolmes question at Is it possible to add a drop shadow to chart.js line chart?
The original solution (extending) is not required. All that is required is simply
  ...
  pointColor: gradientstroke
  ...

Original Solution
Just extend the line and update the point colors. You could do it in the draw function, but it would be efficient (when you have animation enabled) to do it in initialize function
Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        Chart.types.Line.prototype.initialize.apply(this, arguments);

        var ctx = this.chart.ctx;
        // draw a line with the gradient, we use this to get each points color
        ctx.fillStyle = data.datasets[0].strokeColor;
        ctx.fillRect(0, 0, this.chart.width, 1);

        this.datasets.forEach(function (dataset) {
            dataset.points.forEach(function (point) {
                // get the color from the gradient drew above
                var imageData = ctx.getImageData(point.x, 0, 1, 1);
                var color = 'rgba(' + imageData.data[0] + ', ' + imageData.data[1] + ', ' + imageData.data[2] + ', ' + imageData.data[3] + ')';

                // the _saved is used by the tooltip refresh to draw the point when you mouseout
                point.fillColor = color;
                point._saved.fillColor = color;
                point.strokeColor = color;
                point._saved.strokeColor = color;
            })
        })

        // we need to call the render function again to overwrite what was drawn in the initialize render (otherwise we don't see the changed color when animation is false)
        // this also wipes out the reference gradient
        this.render();
    }
});

The pointColor and pointStrokeColor in the lineChartData are actually not required. Note that you could also override the pointHighlightStroke and pointHighlightFill the same way if you wanted to.
You call it like so
new Chart(ctx).LineAlt(...

Fiddle - http://jsfiddle.net/w2nh153d/


text:
Q: PERL Email::Send::Gmail Cannot connect to Gmail account on Windows 7 I am trying to use Email::Send::Gmail to send an email, but for some reason I am getting an error that it is not allowing me to connect.
The code is the standard example:
#!/usr/bin/perl
use strict;
use warnings;
use Email::Send;
use Email::Send::Gmail;
use Email::Simple::Creator;

my $email = Email::Simple->create(
header => [
    From    => 'myaddress@gmail.com',
    To      => 'myaddress@gmail.com',
    Subject => 'Server down',
],
body => 'The server is down. Start panicing.',
);

my $sender = Email::Send->new(
{   mailer      => 'Gmail',
    mailer_args => [
        username => 'myaddress@gmail.com',
        password => 'XXXX',
    ]
}
);
eval { $sender->send($email) };
die "Error sending email: $@" if $@;

Exact Error is:
Email::Send::Gmail: error connecting to server smtp.gmail.com
at C:/Perl/site/lib/Email/Send.pm line 256.

I've looked around my gmail account and there doesn't seem to be anything there to "allow access".  I'm on Windows7 and running from the command line.
Any ideas?
Thanks,
A

A: Time to upgrade your dependencies.
Email::Gmail::Send depends on Net::SMTP::SSL which depends on IO::Socket::SSL.  The first step I take to solving this type of problem is to upgrade the module dependencies just in case a new issue has already been addressed.
Unfortunately, 4 Days ago when you first introduced this problem, I was unable to pass the test suite for IO::Socket::SSL 1.986 on Strawberry Perl 5.18.2.
t/public_suffix_lib_uri.t ......... ok
failed to connect: An operation was attempted on something that is not a socket. at t/public_suffix_ssl.t line 87.
# Looks like you planned 24 tests but ran 2.
# Looks like your test exited with 10038 just after 2.

Fortunately, since then the author has updated the module to IO::Socket::SSL 1.988, and I'm able to fully install and use it on both Windows 7 and Linux.  Currently it throws redefined warnings (cpan ticket 95881), but I was able to send Gmail messages on Windows after upgrading this dependency.
Note: You'll want to create an application specific password for this code, otherwise Gmail might block the login and send you a "Suspicious sign in prevented" email.

A:
Just Upgrade your active Perl version.

Then Install following modules:
ppm

*

*install Email::send:Gmail

*install Net::SMTP:SSL

*installIO::socket::SSL

Then try with below sample code.
 #!/home/ben/software/install/bin/perl
        use warnings;
        use strict;
        use Email::Send;
    use Email::Send::Gmail;
    use Email::Simple::Creator;

    my $email = Email::Simple->create (
        header => [
            From    => '@gmail.com',
                To      => '@gmail.com',
                Subject => 'Make it simple',
        ],

        body => 'buddy I got it ...',
    );

    my $sender = Email::Send->new
    ({
            mailer      => 'Gmail',
            mailer_args =>
[
                username => '',
                password => '',
        ]
    });

    $sender->send ($email);


text:
Q: Remote SSH user always gets "connection closed" I've tried service sshd restart, I've added sshd:all:allow to my /etc/allow.hosts and the remote user tried rm ~/.ssh/known_hosts. I also checked the logs: cat /var/logs/secure | grep ssh and it says Accepted password for $user from ...
This is the first time this particular user has tried connecting but other users have successfully connected to my machine for several days.
None of this has worked or pointed me to the error. Any ideas?
Edit: I SSH-d into his machine to see if I could get an error log or something by SSH-ing back to me. If I use ssh -vvv $host I get various messages, one of which is Unspecified GSS failure. Minor code may provide more information. Here's the complete error log (hostnames and IPs left out):
OpenSSH_5.3p1 Debian-3ubuntu7, OpenSSL 0.9.8k 25 Mar 2009
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to some_host [XX.XX.XX.XX] port 22.
debug1: Connection established.
debug1: identity file /home/ssr/.ssh/identity type -1
debug3: Not a RSA1 key file /home/ssr/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug2: key_type_from_name: unknown key type 'Proc-Type:'
debug3: key_read: missing keytype
debug2: key_type_from_name: unknown key type 'DEK-Info:'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /home/ssr/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /home/ssr/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9
debug1: match: OpenSSH_5.9 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.3p1 Debian-3ubuntu7
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug3: Wrote 792 bytes for a total of 831
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug3: Wrote 24 bytes for a total of 855
debug2: dh_gen_key: priv key bits set: 132/256
debug2: bits set: 509/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug3: Wrote 144 bytes for a total of 999
debug3: check_host_in_hostfile: filename /home/ssr/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 8
debug3: check_host_in_hostfile: filename /home/ssr/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 9
debug1: Host 'xxx' is known and matches the RSA host key.
debug1: Found key in /home/ssr/.ssh/known_hosts:8
debug2: bits set: 502/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: Wrote 16 bytes for a total of 1015
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug3: Wrote 48 bytes for a total of 1063
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/ssr/.ssh/identity ((nil))
debug2: key: /home/ssr/.ssh/id_rsa (0x20d2d350)
debug2: key: /home/ssr/.ssh/id_dsa ((nil))
debug3: Wrote 64 bytes for a total of 1127
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,password
debug3: preferred gssapi-keyex,gssapi-with-mic,gssapi,publickey,keyboard-interactive,password
debug3: authmethod_lookup gssapi-keyex
debug3: remaining preferred: gssapi-with-mic,gssapi,publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-keyex
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug2: we did not send a packet, disable method
debug3: authmethod_lookup gssapi-with-mic
debug3: remaining preferred: gssapi,publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-with-mic
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/krb5cc_1000' not found

debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/krb5cc_1000' not found

debug1: Unspecified GSS failure.  Minor code may provide more information

debug2: we did not send a packet, disable method
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/ssr/.ssh/identity
debug3: no such identity: /home/ssr/.ssh/identity
debug1: Offering public key: /home/ssr/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug3: Wrote 368 bytes for a total of 1495
Connection closed by $my.ip (no, don't want to share)

Another edit: other users seem to be able to connect. My version is: OpenSSH_5.9p1, OpenSSL 1.0.0j-fips 10 May 2012. His is older, as can bee seen from the error log.
New log

A: ssh sometimes gives misleading error-messages.
I found the best way to debug ssh-problems is from the server-side.

*

*ssh into the target server with a working connection.

*Stop sshd (your session will be kept running).

*Then start sshd in console/debug-mode $(which sshd) -d.

*Now retry and look closely at why sshd refuses the connection.

*Do not forget to start sshd again for normal operations.

If you do not see enough information with a single d increase the number - -ddd is the maximum verbosity - a single one on the server side will tell you more than the most verbose level on the client side...

A: I met this problem too, and after several hours of logs, tcpdump debug, found out simply UPDATE the openssh to the latest version will solve the problem.


text:
Q: Excel VBA - Multiline Highest value I have a multi-line cell with the below data, I need a function which finds highest age and give result. You can find age in the brackets. If multiple people have same age with highest age it should give both as output in a cell
Example:1
Ravi (11)\,Chandra (22)\,Krishna (22)\,Hemanth (11)

for the above date it should give output as below in a cell:
Chandra (22)\,Krishna (22)

Example:2
Ravi (11)\,Chandra (23)\,Krishna (22)\,Hemanth (11)

Output as below in a cell:
Chandra (23)

A: you could try this function:
Function AgeResult(cellVal As String) As String
    Dim elem As Variant
    Dim maxAgeNames As String
    Dim iniPos As Long, endPos As Long
    Dim maxAge As Long, age As Long

    For Each elem In Split(cellVal, ",")
        iniPos = InStr(elem, "(")
        endPos = InStr(elem, ")")
        age = Mid(elem, iniPos + 1, endPos - iniPos - 1)
        If age >= maxAge Then
            If age > maxAge Then
                maxAge = age
                maxAgeNames = elem
            Else
                maxAgeNames = maxAgeNames & "," & elem
            End If
        End If
    Next elem
    AgeResult = maxAgeNames
End Function

a possible use of which is what follows:
Sub main()
    Dim cell As Range
    For Each cell In Range("A1:A10") '<~~ range of cells to process the content of
        cell.Offset(, 1) = AgeResult(cell.Value) '<~~ this puts the resulting string in the adjacent cell to the right
    Next cell
End Sub


text:
Q: How to use more parameters in help-ballon grails-plugin I try to use more of the parameters but could not get it working with
<g:helpBalloon title="foo" content="bla" useEvent="['mouseover']" />

should result in
<script type="text/javascript"> new HelpBalloon({ title: 'foo', content: 'bla', useEvent: ['mouseover'] }); </script>

but useEvent="['mouseover']" seems not to be recognized?!
as seen on
http://www.beauscott.com/examples/help_balloons/doc/examples.htm

A: Looking at the code for that plugin, it looks like it doesn't do the useEvent bit


text:
Q: Can't use an undefined value as a symbol reference I'm trying to use an API for a Palo Alto Networks software. The code is supposed to submit username and ipaddress of user network logins to a web interface.
When I try using PANs' API with their sample code for a windows machine the following exception is thrown:
Can't use an undefined value as a symbol reference at
C:/Perl/lib/PAN/API.pm line 179 (#1)

PAN::API::UID::login('PAN::API::UID=HASH(0x7fd113828598)', 'SCU-DSM22/pmmertens', 172.16.6.117) called at API_events.pl line 12

This is the code-example that comes with the API documentation:
#!/usr/bin/perl -w

use strict;
use PAN::API;

my     $useridagent    = '10.0.0.99'; #I changed this to our PAN server address

my     $useridapi      = PAN::API::UID->new($useridagent);

my     $user           = $ENV{USERDOMAIN}.'/'.$ENV{USERNAME};
my     $ipaddress      = unpack('W4',gethostbyname($ENV{COMPUTERNAME}));

    $useridapi->login($user,$ipaddress);

I've ensure that all variables are retrieved correctly. Substituting literal values did not help either. Googling this error turned up references about hard and soft references but I don't see any infractions of these rules in the code below.
This is the codeblock from PAN/Api.pm. Line 179 is where the print starts.
sub submit () {
    my  $self               = shift;

    use IO::Socket::INET;
    use IO::Socket::SSL;

    my  $socket             = IO::Socket::INET->new(PeerAddr => $self->{server},
                                                PeerPort => $self->{port},
                                                Proto    => 'tcp');

    my  $socketssl          = IO::Socket::SSL->start_SSL(   $socket,
                                                    SSL_version     =>'TLSv1');
    print   $socketssl $self->xml;
            $socketssl->close;
            $socketssl->stop_SSL;
}

A: Both the IO::Socket::INET and IO::Socket::SSL lines should have error checking. Something like:
my $socket = IO::Socket::INET->new(....)
  or die "Failed to create socket: $!"

And:
my $socketssl = IO::Socket::SSL->start_SSL(...)
  or die "Failed to start SSL: ".IO::Socket::SSL::errstr();

Although instead of die I might go with Carp::confess.


text:
Q: How do I create multi level row level security in Tableau? I am trying to use the automated row level security in tableau 8.1 but if I create the security at the highest level it doesn't pass the security to the children of the level.  I can only achieve this by creating a massive excel sheet that has every object that I want to allow access to.  I could use the manual way but that is too tedious.  I am sure someone has found a way around this but I can't find anything online.

A: Click the sheet on which you want to create the row level filter and then click on "Server" ---> "Create User Filter" . This will give you a list of all the columns available in that sheet  and then you can select the column which decides the row level security , something like Region_Code (or similar field if you have have) . There itself you can give the list of groups and users which can access with that filter so next time when only those users will access that sheet they will see the filtered data based on the column selected above however rest all the people can still see everything as no security /filter been applied to them.
This link has more details -  http://kb.tableausoftware.com/articles/knowledgebase/row-level-security-and-user-filters


text:
Q: How can I estimate the variance of a dependent variable from a random variable with nonlinear relationship? I am working on a Kalman Filter and I've added a new state variable that is observable via one of the measurements via nonlinear relationship. My sensor reads $y \in \mathbb{R}$ and I am assuming that is has a measurement noise that is a normal distribution with zero mean and variance $\sigma^2_x$. The relationship to the new added state is:
$$
y = c_1 (c_2 x^{c_3} - c_4).
$$
I've set the observation matrix component corresponding to $y$ equal to one since the state is observable. However, how should I set the measurement noise matrix for $y$ from $\sigma^2_x$? Any reference reading or reference would be greatly appreciated!


text:
Q: how to read from and write to a serial port (ttys0) from another pc via ethernet (eth0) on Ubuntu/Debian? Well, there are two pc's connected via Wi-Fi and one of those (let's call it A) has a serial port printer (in ttys0) and a measure serial port device (in ttys1) connected too. So B needs to read some values from the mesure device connected on A and then write to the printer connected on A using a network connection.

A: ser2net is a good solution for this
aptitude install ser2net

Then edit the config in /etc/ser2net.conf
You can then make a tcp connection to a defined port and be connected to the serial port on the remote computer - very useful.

A: I don't know if Ubuntu has anything built-in, but you could run a couple of daemons using netcat.  Of course, if you want it to be secure, you'd need to do a little more work.


text:
Q: Active Directory Group membership inheritance I'm pretty new in active Directory so please be comprehensive..
I'm trying to make some 'sets' of security groups in AD. So I make some groups and members of these groups are groups again..
So I have a MasterGroup with 2 subGroups members. My question is, if I add some users to the MasterGroup, they are also members of the subGroups?
The objective is to make a user member of a unique group to make some kind of "membership inheritance".
Maybe something more simple exists in active directory to make this kind of tricks. I'm open to propositions..

A: If you add some users to the MasterGroup they will not be automatically members of the subGroups. But if you add some users to one of the subGroups, these users will inheredit permissions from the MasterGroup as subGroups are part of the MasterGroup. Please note that the resulting permission will be a combination of MasterGroup permission, subGroup permission and user permissions too.

A: Okay, your question is pretty badly worded but I think that's down to a lack of knowledge. I think you'd benefit from reading these Microsoft topics on Active Directory Groups:
http://technet.microsoft.com/en-us/library/cc776995(v=ws.10).aspx
In particular, Group Scope and Nested Groups
This isn't intended to be an RTFM answer, but those pages will explain the whole thing in more detail than can be reasonably achieved in an answer here.
If you have the following AD groups
[All Staff]
[Factory Staff]
[Office Staff]
[Assembly Team]
[Engineering Team]
[Sales Team]
[Accounts Team]
You could build a hierarchy as follows:
                                      [All Staff]
                                          |
                      -------------------------------------
                     |                                     |
            [Factory Staff]                        [Office Staff]
                     |                                     |
         -------------------                      ----------------
         |                  |                     |              |

[Assembly Team] [Engineering Team]          [Sales Team] [Accounts Team]

*

*Adding a user to [All Staff] will make the user a member of [All Staff]

*Adding a user to [Factory Staff] will make them a member of [Factory Staff] and [All Staff]

*Adding a user to [Assembly Team] will make them a member of [Assembly Team] and [Factory Staff] and [All Staff]


text:
Q: Activity Indicator not showing on PDF uiwebview load i am developing a app with a uiwebview and in that webview i need to load a local pdf file when uiwebview calls a native method through java. and i am successful doing that but when i browse through webisete activity indicator shows well but when native function calls and i load pdf in uiwebview it doesnot shows while loading pdf from url. let me post my code here.
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize webPage;
- (BOOL) shouldAutorotate{
    return NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    webLink = @"http://url.com/m/";
    liNk = webLink;
    [webPage loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:liNk]]];
    webPage.backgroundColor = [UIColor blackColor];
    //[[webPage.subviews objectAtIndex:0] setBounces:NO];
    [(UIScrollView*)[webPage.subviews objectAtIndex:0] setShowsVerticalScrollIndicator:NO];
    [webPage addSubview:activity];
    timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(loading) userInfo:nil repeats:YES];
    webPage.delegate = self;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] absoluteString] hasPrefix:@"ios:"]) {
        // Call the given selector
        [self performSelector:@selector(webToNativeCall)];
        return NO;
    }
    return YES;

}
- (void)webToNativeCall
{
        NSString *pdfurl = @"http://url.com/mypdf.pdf";
        NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:pdfurl]];
        NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"Documents"]];
        NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"mypdf.pdf"];
        [pdfData writeToFile:filePath atomically:YES];
        // Now create Request for the file that was saved in your documents folder
        NSURL *url = [NSURL fileURLWithPath:filePath];
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
        [webPage setUserInteractionEnabled:YES];
        [webPage setDelegate:self];
        [webPage loadRequest:requestObj];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

A: Try starting and stoping activity indicator in UIWebViewDelegate methods
  #pragma mark - UIWebViewDelegate -

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType
{
    [activity startAnimating];

    if ([[[inRequest URL] absoluteString] hasPrefix:@"ios:"])
    {
       // Call the given selector
       [self performSelector:@selector(webToNativeCall)];
       return NO;
    }

    return YES;
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [activity stopAnimating];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [activity stopAnimating];
}


text:
Q: os.join.path does change directory Hello I have a piece of code where I want to join a path with a picture name which I am getting from an excel file. The thing is that my code changes my path string.
src=os.path.join('C:\\Users\\ekrem\\Desktop\\Distributions\\16-17',ws.cell(row=cell.row,column=2).value)
print('src=',src)

so here my src variable should be something like this:
C:\Users\ekrem\Desktop\Distributions\16-17\26231043_1686575684735993_7548330554586169888_n.jpg

but as you see I printed the src variable and I got this
src= C:\Users\ekrem\Desktop\16-17\26231043_1686575684735993_7548330554586169888_n.jpg

here the distribution folder is missing, have you any idea why?
Thank you in advance

A: In this case assuming the end piece is always a single filename it might be easier to do this with f-strings. That way there is no path weirdness that happens something like this should work (Assuming you're on python 3.6+, if you aren't then do this instead):
src = f'C:\\Users\\ekrem\\Desktop\\Distributions\\16-17\\{ws.cell(row=cell.row,column=2).value}'

print(f'{source=}') # Print source with label

P.S I would recommend switching the C:\\Users\\<name> with %USERPROFILE% (so %USERPROFILE%\\Desktop\\Distributions\\16-17\\), that way if you change accounts or hard-drives this still works.
Then just do validation with:
if os.path.exists(src):
    # Do stuff
else:
    raise FileNotFoundError(f"{src} file could not be found")


text:
Q: Axis limits for scatter plot - Matplotlib I'm having the same problem presented here, however, the proposed solution didn't work for me.
I'm plotting a set of data which the main plot have this pattern:

Which is a plot which axis limits varies from (-1, 1) in both x and y, with a margin set with this piece of code:
plt.figure()
plt.show(data)
## Add some margin
l, r, b, t = plt.axis()
dx, dy = r-l, t-b
plt.axis([l-0.1*dx, r+0.1*dx, b-0.1*dy, t+0.1*dy])

The problem is 'cause I have more "complex" plot in which some changes had to me made. This is the code that produces it:
def plot_quiver_singularities(min_points, max_points, vector_field_x, vector_field_y, file_path):
    """
    Plot the singularities of vector field
    :param file_path : the path to save the data
    :param vector_field_x : the vector field x component to be plot
    :param vector_field_y : the vector field y component to be plot
    :param min_points : a set (x, y) of min points field
    :param max_points : a set (x, y) of max points  field
    """
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_axes([.13, .3, .6, .6])

    ## Plot quiver
    x, y = numpy.mgrid[-1:1:100*1j, -1:1:100*1j]
    m = numpy.sqrt(numpy.power(vector_field_x, 2) + numpy.power(vector_field_y, 2))
    quiver = ax.quiver(x, y, vector_field_x, vector_field_y, m, zorder=1)

    ## Plot critical points
    x = numpy.linspace(-1, 1, x_steps)
    y = numpy.linspace(-1, 1, y_steps)

    # Draw the min points
    x_indices = numpy.nonzero(min_points)[0]
    y_indices = numpy.nonzero(min_points)[1]
    ax.scatter(x[x_indices], y[y_indices], marker='$\\circlearrowright$', s=100, zorder=2)

    # Draw the max points
    x_indices = numpy.nonzero(max_points)[0]
    y_indices = numpy.nonzero(max_points)[1]
    ax.scatter(x[x_indices], y[y_indices], marker='$\\circlearrowleft$', s=100, zorder=2)

    ## Put legends
    marker_min = plt.Line2D((0, 0), (0, 0), markeredgecolor=(1.0, 0.4, 0.0), linestyle='',
                            marker='$\\circlearrowright$', markeredgewidth=1, markersize=10)
    marker_max = plt.Line2D((0, 0), (0, 0), markeredgecolor=(0.2, 0.2, 1.0), linestyle='',
                            marker='$\\circlearrowleft$', markeredgewidth=1, markersize=10)
    plt.legend([marker_min, marker_max], ['CW rot. center', 'CCW rot. center'], numpoints=1,
               loc='center left', bbox_to_anchor=(1, 0.5))

    quiver_cax = fig.add_axes([.13, .2, .6, .03])
    fig.colorbar(quiver, orientation='horizontal', cax=quiver_cax)

    ## Set axis limits
    plt.xlim(-1, 1)
    plt.ylim(-1, 1)

    ## Add some margin
    # l, r, b, t = plt.axis()
    # dx, dy = r-l, t-b
    # plt.axis([l-0.1*dx, r+0.1*dx, b-0.1*dy, t+0.1*dy])

    plt.savefig(file_path + '.png', dpi=dpi)
    plt.close()

This produces the following image:

As can be seen, the axis limits do not hold and I didn't found why yet.
Any help would be appreciated.
Thank you in advance.

A: I was able to solve the problem putting this piece of code
plt.xlim(-1, 1)
plt.ylim(-1, 1)

Right after calling scatter().

A: You can also set those to the ax object:
ax.set_xlim((-1,1))
ax.set_ylim((-1,1))