text:
Q: Add Getopt::Long options in a hash, even when using a repeat specifier Perl's Getopt::Long allows a developer to add their own options to a script. It's also possible to allow multiple values for an option by the use of a repeat specifier, as seen in regular expressions. For example:
GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);

Furthermore, option values can be stored in a hash, like so:
my %h = ();
GetOptions(\%h, 'length=i');    # will store in $h{length}

What I'm trying to do is, combine these two methods to end up with a hash of my options, even when they have multiple values.
As an example, say I want to allow three options: birthday (three integers), parents (one or two strings), first name (exactly one string).
Let's also say that I want to put these values into a hash. I tried the following:
use strict;
use warnings;

use Getopt::Long;
use Data::Dumper;

my %h = ();
GetOptions(\%h, 'bday=i{3}', 'parents=s{1,2}', 'name=s{1}');

print Dumper(\%h);

And tested it, but the output was as follows:
perl optstest.pl --bday 22 3 1986 --parents john mary --name ellen
$VAR1 = {
    'name' => 'ellen',
    'parents' => 'mary',
    'bday' => 1986
};

Only the last value of each option is actually used in the hash. What I would like, though, is:
$VAR1 = {
    'name' => 'ellen',
    'parents' => ['mary', 'john'],
    'bday' => [22, 3, 1986]
};

If 'ellen' would be in an array, or if everything was inside a hash, that'd be fine as well.
Is it not possible to combine these two functionalities of Getopt::Long, i.e. putting options in a hash and using repeat specifiers?

A: use Getopt::Long;
# enable for debugging purposes
# Getopt::Long::Configure("debug");
use Data::Dumper;

my %h = ();
GetOptions(\%h, 'bday=i{3}', 'parents=s@{1,2}', 'name=s@{1}');

print Dumper(\%h);

Is that what you want?
$VAR1 = {
          'bday' => 1986,
          'name' => [
                      'ellen'
                    ],
          'parents' => [
                         'john',
                         'mary'
                       ]
        };

A: If you want an array, you need to give it a reference to an array.
local @ARGV = qw( --x y z );
my %h = ( x => [] );
GetOptions(\%h, 'x=s{2}');
print(Dumper(\%h));

Or you need to specify that you want an array.
local @ARGV = qw( --x y z );
GetOptions(\my %h, 'x=s@{2}');
print(Dumper(\%h));

Output:
$VAR1 = {
          'x' => [
                   'y',
                   'z'
                 ]
        };

A: The Options with multiple values section of the documentation that you link to also says this

Warning: What follows is an experimental feature.

It says earlier on

GetOptions (\%h, 'colours=s@');   # will push to @{$h{colours}}

so I guess that it was the author's intent for it to work the same way with repeat specifiers, and that you have found a bug
I suggest that you report it to the Perl 5 Porters using the perlbug utility that is part of the Perl installation


text:
Q: How to connect socket.io to MongoDB server side of react project? I have done a project with React which uses ExpressJS to create a server-side already one and use MongoDB there. How to implement socket.io in the message component of the client site and server side or how to connect socket.io on the server side?
The server-side image is given below.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .Net Core HttpClientFactory dispose HttpClientHandler I am currently configuring my httpclientfactory this way
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }

};

serviceCollection.AddHttpClient("ignoreSSL", c =>
{}).ConfigurePrimaryHttpMessageHandler(h => httpClientHandler);

To disable the validation of security certificates, but when doing too many requests I receive this exception:

Cannot access a disposed object. Object name: 'SocketsHttpHandler'.

I currently build my httpclient this way
HttpClient client = _httpClientFactory.CreateClient("ignoreSSL");

Doing tests, this is solved in this way without httpclientfactory
HttpClient ad = new HttpClient(handler, false);

For more than I look for I can not find how to tell httpclientfactory not to make handler dispose?

A: The problem is caused because a single HttpClientHandler  instance is used for all requests. It's the HttpClientFactory's job to manage, pool and recycle handlers.
It looks like the actual question is how to disable certificate validation when using HttpClientFactory. This requires configuring the client handlers used by it.
As the documentation shows this is done using the ConfigurePrimaryHttpMessageHandler method. From the method's remarks :

Remarks
The delegate should return a new instance of the message handler each time it is invoked.

The handlers created by that method will be added to a handler pool and used by other handlers like Polly's retry handlers. HttpClientFactory will recycle older handlers to handle DNS registration changes.
The code should look like this:
services.AddHttpClient<HttpWrapper>("ignoreSSL")
        .ConfigurePrimaryHttpMessageHandler(() =>
        {
            return new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
            };
        });


text:
Q: .NET Start Process with higher rights I am trying to execute a program with admin rights through a C# application, which gets invoked with user rights only.
Code
        ProcessStartInfo psi;
        try
        {
            psi = new ProcessStartInfo(@"WINZIP32.EXE");

            psi.UseShellExecute = false;
            SecureString pw = new SecureString();
            pw.AppendChar('p');
            pw.AppendChar('a');
            pw.AppendChar('s');
            pw.AppendChar('s');
            pw.AppendChar('w');
            pw.AppendChar('o');
            pw.AppendChar('r');
            pw.AppendChar('d');
            psi.Password = pw;
            psi.UserName = "administrator";

            Process.Start(psi);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

It does start winzip, but only with user rights. Is there something I am doing wrong or is it even possible to start a process with higher rights?
thank you!
Edit:
Here is the reason behind the question, maybe it helps to understand what i actually need.

I used winzip for example to get a general idea what's incorrect with my code. The actual problem is, our company uses 2 versions of a program. But before you start any of the versions you need to import a dll file with regsvr32 (with admin rights). Now I would like to write a program that let the user select the version, import the dll and starts the correct application.

A: You can run a process as another user(even an administrator) using the CreateProcessAsUser function (Win32 API).
CreateProcessAsUser accepts a user token as the first parameter, that is an impersonation token.
You have to use DLLImport to load the function from the Windows DLL.
Take a look at this example implementation that i have used in one of my projects :
    [StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
    public IntPtr hProcess;
    public IntPtr hThread;
    public uint dwProcessId;
    public uint dwThreadId;
}

[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
    public uint nLength;
    public IntPtr lpSecurityDescriptor;
    public bool bInheritHandle;
}

[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
    public uint cb;
    public string lpReserved;
    public string lpDesktop;
    public string lpTitle;
    public uint dwX;
    public uint dwY;
    public uint dwXSize;
    public uint dwYSize;
    public uint dwXCountChars;
    public uint dwYCountChars;
    public uint dwFillAttribute;
    public uint dwFlags;
    public short wShowWindow;
    public short cbReserved2;
    public IntPtr lpReserved2;
    public IntPtr hStdInput;
    public IntPtr hStdOutput;
    public IntPtr hStdError;

}

internal enum SECURITY_IMPERSONATION_LEVEL
{
    SecurityAnonymous,
    SecurityIdentification,
    SecurityImpersonation,
    SecurityDelegation
}

internal enum TOKEN_TYPE
{
    TokenPrimary = 1,
    TokenImpersonation
}

public class ProcessAsUser
{

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool CreateProcessAsUser(
    IntPtr hToken,
    string lpApplicationName,
    string lpCommandLine,
    ref SECURITY_ATTRIBUTES lpProcessAttributes,
    ref SECURITY_ATTRIBUTES lpThreadAttributes,
    bool bInheritHandles,
    uint dwCreationFlags,
    IntPtr lpEnvironment,
    string lpCurrentDirectory,
    ref STARTUPINFO lpStartupInfo,
    out PROCESS_INFORMATION lpProcessInformation);

    [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
    private static extern bool DuplicateTokenEx(
    IntPtr hExistingToken,
    uint dwDesiredAccess,
    ref SECURITY_ATTRIBUTES lpThreadAttributes,
    Int32 ImpersonationLevel,
    Int32 dwTokenType,
    ref IntPtr phNewToken);

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(
    IntPtr ProcessHandle,
    UInt32 DesiredAccess,
    ref IntPtr TokenHandle);

    [DllImport("userenv.dll", SetLastError = true)]
    private static extern bool CreateEnvironmentBlock(
    ref IntPtr lpEnvironment,
    IntPtr hToken,
    bool bInherit);

    [DllImport("userenv.dll", SetLastError = true)]
    private static extern bool DestroyEnvironmentBlock(
    IntPtr lpEnvironment);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(
    IntPtr hObject);

    private const short SW_SHOW = 5;
    private const uint TOKEN_QUERY = 0x0008;
    private const uint TOKEN_DUPLICATE = 0x0002;
    private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
    private const int GENERIC_ALL_ACCESS = 0x10000000;
    private const int STARTF_USESHOWWINDOW = 0x00000001;
    private const int STARTF_FORCEONFEEDBACK = 0x00000040;
    private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
    private const int STARTF_RUNFULLSCREEN = 0x00000020;

    private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
    {
        bool result = false;

        PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
        SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
        SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
        saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
        saThread.nLength = (uint)Marshal.SizeOf(saThread);

        STARTUPINFO si = new STARTUPINFO();
        si.cb = (uint)Marshal.SizeOf(si);

        //if this member is NULL, the new process inherits the desktop
        //and window station of its parent process. If this member is
        //an empty string, the process does not inherit the desktop and
        //window station of its parent process; instead, the system
        //determines if a new desktop and window station need to be created.
        //If the impersonated user already has a desktop, the system uses the
        //existing desktop.

        si.lpDesktop = @"WinSta0\Default"; //Modify as needed
        si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
        si.wShowWindow = SW_SHOW;

        //Set other si properties as required.

        result = CreateProcessAsUser(
        token,
        null,
        cmdLine,
        ref saProcess,
        ref saThread,
        false,
        CREATE_UNICODE_ENVIRONMENT,
        envBlock,
        null,
        ref si,
        out pi);

        if (result == false)
        {
            int error = Marshal.GetLastWin32Error();
            string message = String.Format("CreateProcessAsUser Error: {0}", error);
            Debug.WriteLine(message);

        }

        return result;
    }

    /// <summary>
    /// LaunchProcess As User Overloaded for Window Mode
    /// </summary>
    /// <param name="cmdLine"></param>
    /// <param name="token"></param>
    /// <param name="envBlock"></param>
    /// <param name="WindowMode"></param>
    /// <returns></returns>
    private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock,uint WindowMode)
    {
        bool result = false;

        PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
        SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
        SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
        saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
        saThread.nLength = (uint)Marshal.SizeOf(saThread);

        STARTUPINFO si = new STARTUPINFO();
        si.cb = (uint)Marshal.SizeOf(si);

        //if this member is NULL, the new process inherits the desktop
        //and window station of its parent process. If this member is
        //an empty string, the process does not inherit the desktop and
        //window station of its parent process; instead, the system
        //determines if a new desktop and window station need to be created.
        //If the impersonated user already has a desktop, the system uses the
        //existing desktop.

        si.lpDesktop = @"WinSta0\Default"; //Default Vista/7 Desktop Session
        si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;

        //Check the Startup Mode of the Process
        if (WindowMode == 1)
            si.wShowWindow = SW_SHOW;
        else if (WindowMode == 2)
        { //Do Nothing
        }
        else if (WindowMode == 3)
            si.wShowWindow = 0; //Hide Window
        else if (WindowMode == 4)
            si.wShowWindow = 3; //Maximize Window
        else if (WindowMode == 5)
            si.wShowWindow = 6; //Minimize Window
        else
            si.wShowWindow = SW_SHOW;

        //Set other si properties as required.
        result = CreateProcessAsUser(
        token,
        null,
        cmdLine,
        ref saProcess,
        ref saThread,
        false,
        CREATE_UNICODE_ENVIRONMENT,
        envBlock,
        null,
        ref si,
        out pi);

        if (result == false)
        {
            int error = Marshal.GetLastWin32Error();
            string message = String.Format("CreateProcessAsUser Error: {0}", error);
            Debug.WriteLine(message);

        }

        return result;
    }

    private static IntPtr GetPrimaryToken(int processId)
    {
        IntPtr token = IntPtr.Zero;
        IntPtr primaryToken = IntPtr.Zero;
        bool retVal = false;
        Process p = null;

        try
        {
            p = Process.GetProcessById(processId);
        }

        catch (ArgumentException)
        {

            string details = String.Format("ProcessID {0} Not Available", processId);
            Debug.WriteLine(details);
            throw;
        }

        //Gets impersonation token
        retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
        if (retVal == true)
        {

            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.nLength = (uint)Marshal.SizeOf(sa);

            //Convert the impersonation token into Primary token
            retVal = DuplicateTokenEx(
            token,
            TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
            ref sa,
            (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
            (int)TOKEN_TYPE.TokenPrimary,
            ref primaryToken);

            //Close the Token that was previously opened.
            CloseHandle(token);
            if (retVal == false)
            {
                string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
                Debug.WriteLine(message);
            }

        }

        else
        {

            string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
            Debug.WriteLine(message);

        }

        //We'll Close this token after it is used.
        return primaryToken;

    }

    private static IntPtr GetEnvironmentBlock(IntPtr token)
    {

        IntPtr envBlock = IntPtr.Zero;
        bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
        if (retVal == false)
        {

            //Environment Block, things like common paths to My Documents etc.
            //Will not be created if "false"
            //It should not adversley affect CreateProcessAsUser.

            string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
            Debug.WriteLine(message);

        }
        return envBlock;
    }

    public static bool Launch(string appCmdLine /*,int processId*/)
    {

        bool ret = false;

        //Either specify the processID explicitly
        //Or try to get it from a process owned by the user.
        //In this case assuming there is only one explorer.exe

        Process[] ps = Process.GetProcessesByName("explorer");
        int processId = -1;//=processId
        if (ps.Length > 0)
        {
            processId = ps[0].Id;
        }

        if (processId > 1)
        {
            IntPtr token = GetPrimaryToken(processId);

            if (token != IntPtr.Zero)
            {

                IntPtr envBlock = GetEnvironmentBlock(token);
                ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
                if (envBlock != IntPtr.Zero)
                    DestroyEnvironmentBlock(envBlock);

                CloseHandle(token);
            }

        }
        return ret;
    }

A: You need to set ProcessStartInfo.UseShellExecute to true and ProcessStartInfo.Verb to runas:
Process process = null;
ProcessStartInfo processStartInfo = new ProcessStartInfo();

processStartInfo.FileName = "WINZIP32.EXE";

processStartInfo.Verb = "runas";
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;

process = Process.Start(processStartInfo);

This will cause the application to run as the administrator. UAC will however prompt the user to confirm. If this is not desirable then you'll need to add a manifest to permanently elevate the host process privilages.

A: Ref:
How to start a Process as administrator mode in C#
Elevating process privilege programmatically?
  var psi = new ProcessStartInfo
    {
        FileName = "notepad",
        UserName = "admin",
        Domain = "",
        Password = pass,
        UseShellExecute = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        Verb = "runas";
    };
    Process.Start(psi);

//
var pass = new SecureString();
pass.AppendChar('s');
pass.AppendChar('e');
pass.AppendChar('c');
pass.AppendChar('r');
pass.AppendChar('e');
pass.AppendChar('t');
Process.Start("notepad", "admin", pass, "");

//Vista or higher check
if (System.Environment.OSVersion.Version.Major >= 6)
{
   p.StartInfo.Verb = "runas";
}

Ref: How to run/start a new process with admin rights?  ASP.net Forum

Another way is to impersonate the admin user. You can do this by
  calling the Logon function and impersonate the user whose token you
  will get then. For impersonating a user in code, look at:
  WindowsImpersonationContext
  Class
  . Use the check
  http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=31611 for
  GetCurrentUser to see whether impersonation succeeded.

Code Snippet:
System.Diagnostics.Process process = null;
System.Diagnostics.ProcessStartInfo processStartInfo;

processStartInfo = new System.Diagnostics.ProcessStartInfo();

processStartInfo.FileName = "regedit.exe";

if (System.Environment.OSVersion.Version.Major >= 6)  // Windows Vista or higher
{
   processStartInfo.Verb = "runas";
}
else
{
   // No need to prompt to run as admin
}

processStartInfo.Arguments = "";
processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;

try
{
   process = System.Diagnostics.Process.Start(processStartInfo);
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
   if (process != null)
   {
      process.Dispose();
   }
}

//Try this with administrator login, i have not tested yet..
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        // Test harness.
        // If you incorporate this code into a DLL, be sure to demand FullTrust.
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        private void button1_Click(object sender, EventArgs e)
        {
            SafeTokenHandle safeTokenHandle;
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;
            bool returnValue = LogonUser("administrator", "", "password",
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }
            using (safeTokenHandle)
            {
                Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);

                // Check the identity.
                Console.WriteLine("Before impersonation: "
                    + WindowsIdentity.GetCurrent().Name);
                // Use the token handle returned by LogonUser.
                WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                {
                    System.Diagnostics.Process process = null;
                    System.Diagnostics.ProcessStartInfo processStartInfo;

                    processStartInfo = new System.Diagnostics.ProcessStartInfo();

                    processStartInfo.FileName = "regedit.exe";

                    //if (System.Environment.OSVersion.Version.Major >= 6)  // Windows Vista or higher
                    //{
                    //    processStartInfo.Verb = "runas";
                    //}
                    //else
                    //{
                    //    // No need to prompt to run as admin
                    //}

                    processStartInfo.Arguments = "";
                    processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    processStartInfo.UseShellExecute = true;

                    try
                    {
                        process = System.Diagnostics.Process.Start(processStartInfo);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        if (process != null)
                        {
                            process.Dispose();
                        }
                    }

                    // Check the identity.
                    Console.WriteLine("After impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
                }
                // Releasing the context object stops the impersonation
                // Check the identity.
                Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
            }
        }


text:
Q: Why do OpenGL buffers (and objects in general) work? Here is what I understand about how OpenGL buffers work: Sending data from the CPU to the GPU is slow, so we don't want to send, say, vertex data vertex by vertex. Instead, we send vertex data to the GPU all at once, and inform the GPU how to interpret what we send it. Buffers are involved in this process somehow (that's the point I do not understand).
So how to do this? We follow the OpenGL object creation model:

*

*Generate a buffer ID
GLuint VBO;
glGenBuffers(1, &VBO);

*Bind the buffer ID to a target buffer in the current state/context
glBindBuffer(GL_ARRAY_BUFFER, VBO);

*Modify or query data. For instance, glBufferData() called on the target GL_ARRAY_BUFFER can be used to send the vertex data.

*Set the target back to default
glBindBuffer(GL_ARRAY_BUFFER, 0);

*De-allocate resources (edit: after the buffer has served its purpose; for instance, after the end of the game loop)
glDeleteBuffers(1, &VBO);

So at one hand I have the abstract idea of a block of GPU memory, and on the other hand I have a procedure to access that block, and I do not understand how those two correlate.


text:
Q: Configure Kubernetes Traefik Ingress with different path rewrites for each service I'm in the process of migration of our application from single instance Docker-compose configuration to Kubernetes. I currently have the following example NGINX configuration, running as a reverse proxy of my application:
server {
  server_name             example.com;
  ssl_certificate         /etc/nginx/certs/${CERT_NAME};
  ssl_certificate_key     /etc/nginx/certs/${KEY_NAME};

  listen                  443 ssl;
  keepalive_timeout       70;

  access_log              /var/log/nginx/access.log mtail;

  ssl_protocols           xxxxxx
  ssl_ciphers             xxxxxx
  ssl_session_cache       shared:SSL:10m;
  ssl_session_timeout     10m;

  rewrite_log             on;
  resolver                127.0.0.11 ipv6=off;

  location /push/ {
        auth_basic                    "Restricted";
        auth_basic_user_file          /etc/nginx/htpasswd;
        rewrite /push/(.*)        /index.php/$1 break;
        proxy_pass                    pushinterface:3080;
  }

  location /flights/ {
        rewrite /flights/(.*)         /$1 break;
        proxy_pass                    flightstats:3090;
  }

  location /api/ {
        proxy_pass                    $api;
  }

  location /grafana/ {
        access_log                    off;
        log_not_found                 off;
        proxy_pass                    http://grafana:3000;
        rewrite ^/grafana/(.*)        /$1 break;
  }

}
My initial plans for the reverse proxy part was implementing an ingress with NGINX ingress controller, but I saw that my configuration can be created as Ingress only with NGINX Plus. That's why I decided to try with Traefik, but I'm not sure if it's still possible to have different rewrites of the path for each service.
I tried the following Ingress configuration, but it seems it's not working:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: example-traefik
  annotations:
    kubernetes.io/ingress.class: traefik
    traefik.frontend.rule.type: ReplacePathRegex
spec:
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: pushinterface
          servicePort: 80
        path: /push/(.*) /index/$1
      - backend:
          serviceName: flights
          servicePort: 80
        path: /flights/(.*) /$1
       - backend:
          serviceName: api
          servicePort: 80
        path: /api
      - backend:
          serviceName: grafana
          servicePort: 80
        path: /grafana/(.*) /$1

I will appreciate any help for solving this task

A: After several hours of unsuccessful attempts to solve my issue, I did it with Nginx ingress controller and it works great! Here's the ingress configuration:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      rewrite /push/(.*) /index/$1 break;
      rewrite /flights/(.*) /$1 break;
      rewrite /grafana/(.*) /$1 break;

spec:
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: pushinterface
          servicePort: 80
        path: /push
      - backend:
          serviceName: flights
          servicePort: 80
        path: /flights
       - backend:
          serviceName: api
          servicePort: 80
        path: /api
      - backend:
          serviceName: grafana
          servicePort: 80
        path: /grafana

Thanks to everyone for the answers! :)

A: Using ReplacePathRegex rule type in your example does not guarantee that incoming requests will be forwarded to the target backends, as mentioned in Traefik Documentation.
In order to route requests to the endpoints, use Matcher instead of Modifiers rules, as they are designed for that purpose.
Find a separate discussion on the similar issue here.


text:
Q: iOS Cordova App not showing version updates available Currently when making a new release android customers are given a notification that a new version of the is available for download.
I have searched for solutions on here (stackoverflow) but the only related answers are for apps developed in xcode.
How can I notify customers when releasing a new version of the app to itunes?

A: You could store the current app version in your database and use appVersion plugin to get the installed version on the device. Then you can compare the versions (on start-up e.g.) and notify the user somehow that there is a new version available. You can even provide add link to your app in App Store.
I'm using this plugin: https://github.com/WellBload/cordova-plugin-app-version/blob/4234061/README.md
It does require some maintenance because you have to update your database every time the update has been released. The choice is yours.


text:
Q: Mittag -Leffler function I am just reading about mittag leffler function and its properties :
The hyperbolic functions of order n .which are generalizations of the hyperbolic sine and cosine can  be expressed in terms of mittag -leffler function:
$
{h}_{r}{\mathrm{(}}{z}{\mathrm{,}}{n}{\mathrm{)}}\mathrm{{=}}\mathop{\sum}\limits_{{k}\mathrm{{=}}{0}}\limits^{\mathrm{\infty}}{\frac{{z}^{{nk}\mathrm{{+}}{r}\mathrm{{-}}{1}}}{{\mathrm{(}}{nk}\mathrm{{+}}{r}\mathrm{{-}}{1}{\mathrm{)}}}}\mathrm{{=}}{z}^{{r}\mathrm{{-}}{1}}{E}_{n\mathrm{,}r}{\mathrm{(}}{z}^{n}{\mathrm{).}}\hspace{0.33em}\hspace{0.33em}{\mathrm{(}}{r}\mathrm{{=}}{1}{\mathrm{,}}{2}{\mathrm{,...}}{n}{\mathrm{)}}
$
Is there any explanation for that relationship .


text:
Q: batch file: using a batch file to read multiple .txt files and assign a value to each I have a folder that contains multiple .txt files. I would like to be able to make a batch file to read those files and assign a variable to each value (each .txt file only contains one number). I have found scripts to read the individual files, but lack the ability to assign a variable to each of them.

A: Test this:
@echo off
set c=0
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir *.txt /b /a-d ') do (
set /a c+=1
set /p a[!c!]=<"%%a"
)
set a[
pause

A: @ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
:: remove variables starting JOB
FOR  /F "delims==" %%a In ('set JOB 2^>Nul') DO SET "%%a="

FOR /f "delims=" %%a IN (
  'dir /s /b /a-d "%sourcedir%\job_*.txt" '
  ) DO (
 FOR /f "delims=" %%b IN ('type "%%a"') DO (
  IF DEFINED %%~na (ECHO %%~na repeated) ELSE (SET "%%~na=%%b")
 )
)

SET job

GOTO :EOF

This job should set up variables named job_* containing the data read from each job_*.txt file found in the subtree with root at sourcedir - I used u:\sourcedir which suits my system. You would need to change that to suit yours.

A: You don't say how you want to name your variables. I'll assume you want a variable name that matches the job name. For example, if file is named JOB_123.txt, then the variable would be named JOB_123
for /f "tokens=1* delims=:" %%A in ('findstr "^" job_*.txt') do set "%%A=%%B"

If the job numbers don't matter, and you simply want an array of values, then:
for /f "tokens=1,2* delims=:" %%A in ('findstr "^" job_*.txt^|findstr /n "^"') do set jobCnt=%%A&set "job[%%A]=%%C"

This will create variables named job[1], job[2], etc. And jobCnt will contain the total number of values.


text:
Q: Twitter integration in android without adding twitter4j.jar in lib folder I want to use twitter in my application. My task is to upload the twitter status from my application. I have added the twitter4j jar file in my libs folder but the issue is; API is updated now and I need to recompile the code to use twitter functionality.
Isn't there a way to use twitter API without this twitter4j.jar file. Because each time when an update come, we are supposed to recompile our code with this updated jar file. Isn't there a way out?

A:
Isn't there a way out?

Simple answer will be "no".  When you are developing your application with any kind of third party library then you bound with that library. In future whenever that library gets update or stops its services your application also gets stop functioning.
Sometimes library updation brings smaller steps methods and removed old method which help our code to run easier.

A: There's no way around this, you can only use the new twitter API directly with twitter4j. Another option is to have a Web Service from where you make the petitions. Because twitter API only allows 300 petitions every 15 minutes or so, if you want to deploy a commercial app this would turn into a big problem because twitter can even get to ban your account.
IMHO I would addapt your app to the new Twitter API using a Web Service or twitter4j, depending on your app, but there is no way to automatically update a third party library so that is why I recommend using a Web Service, these don't have to depend on any third parties. Hope it helped you out.


text:
Q: Open-source java XSLT 2.0 implementation? I'm currently looking into using XSLT 2.0, but I cannot find any open-source java implementations (Saxon-B seems to fit the bill, but isn't schema-aware).
Am I missing something?

A: Yes, I'm answering my own question from 2.5 years ago:
I haven't tried it yet, but I just stumbled upon Eclipse PsychoPath, which is (according to the docs) a XPath 2.0 XML Schema Aware processor that passes 96% of the XPath 2.0 test suite (version 1.1M1).

A: The only one is Saxon-HE:
Saxon-HE
The W3C hosts an online version of it for testing:
W3C Jigsaw XSLT 2.0 Service
And there is JSFiddle like version as well:
xsltransform.net
And the Frameless project hosts a JavaScript version of it:
XSLT Fiddle
There's also an App Engine project which uses it:
XSLT App Engine Test Harness
Other than that, there's an incomplete Xerces extension which implements XPath 2.0:
Xerces XPath 2.0 Extension
An Eclipse extension which implements XPath 2.0:
WTP XPath2.0 Processor
An incomplete Xalan-J branch which partially implements XSLT 2.0:

Some prototype work for XSLT 2.0
  support in the Xalan-J Interpretive processor went on in 2003, but then
  trailed off.  That prototype work is still available on the xslt20 branch
  http://svn.apache.org/repos/asf/xalan/java/branches/xslt20/, but since
  then nobdy has stepped forward to carry on that initial prototyping, and
  the Xalan PMC hasn't put in place any plans for XSLT 2.0 support.

As well as a server-side implementation of Saxon-CE which can run on Nashorn/Avatar.js:
xslty
References

*

*Running Node.js on Java 8 Nashorn with Avatar.js on Windows "no avatar-js in java.library.path"

*Re: Xalan-J XSLT 2.0 status

*org.eclipse.wst.xml.xpath2.processor.sdk.feature

*Nashorn - The Combined Power of Java and JavaScript in JDK 8

*Nodyn Completion of the Node.js API

*Saxonica Product Feature Matrix

A: For the archive, there's also AltovaXML, the free-as-in-beer, schema-aware XSLT 2.0 engine used in XMLSpy etc.
Unfortunately, like XMLSpy, it's Windows only.

A: Are you sure you really need a schema aware processor? It might help find errors in the stylesheets quicker but the cost might outweigh the benefit (both in terms of money, and license-wise).
Saxon-SA is the schema-aware version of Saxon B. It includes the open source Saxon B in full (published under the Mozilla Public License). It's only the "schema-aware" stuff which is closed source, so most of it is still free software (though only as in free speech..).


text:
Q: Wanting to sort a hash in ruby by value first, and key second
Possible Duplicate:
Sorting a hash in Ruby by its value first then its key.

I need to order a hash so that the value is the first priority, and then when the values are the same it orders by the key.
I am currently sorting using this code, but I don't see how to do sort_by with a second element.
Hash[@card_value_counts.sort_by{|k, v| k * -1}]

Examples of what I'm looking for would be:
pre_sorted = {10=>1, 9=>2, 3=>2, 2=>1, 1=>1}
sorted = {9=>2, 3=>2, 10=>1, 2=>1, 1=>1}

pre_sorted = {12=>2, 10=>3, 9=>4, 5=>3}
sorted = {9=>4, 10=>3, 5=>3, 12=>2}

A: Array has a cool feature: comparing two arrays with the <=> method will compare them element-by-element. You can exploit this for multi-value sorting:
sorted_hash = Hash[original_hash.sort_by { |k,v| [-1 * v, -1 * k] }]

UPDATE: Maybe you know this already, but I assumed you're using Ruby 1.9. In earlier versions, Hashes are not guaranteed to maintain their order.


text:
Q: Android Studios: Unable to create a New File I've been following The Complete Android Developer Course in Udemy. I followed the exact steps downloading the same files, I've already downloaded and saved JDK_HOME in the environmental variables with the right path accordingly.
I'm currently using Windows 10 and am not sure whether the files are supported. Any help would be appreciated!

A: It has been awhile since I did any android development or used Eclipse for that matter, but your error message looks like you havent set the PATH for Android SDK. Check to see if your SDK's path is selected by going to:
Window -> Preferences -> Android - > Browse for SDK.


text:
Q: Handle middleware using chai-http Node Js Express I am facing issue I am testing an api using chai-http but it struck in middlewear means it does not call next() function. Not sure how to handle this, little guide may be helps me alot. Here is my code may be it helps you understand better.
Middleware
function middleware(req, res, next) => {
  // doing some stuff
  console.log("step 1") // prints
  next()
}

API
router.get('/orders', middleware, (req, res) => {
  // some stuff
 console.log("step 2") // not prints
 res.send(result)
})

Test Case
  let order = new Order(mockOrder);
  order.save((err, order) => {
    chai.request(server)
    .get('/orders')
    .end((err, res) => {
    // some stuff
   })
  })

A: This update might be useful for you.It is from github.
Another large breaking change is that the chai.request(server) object will automatically close the server connection after the first request. This means if you have code like this:
you'll need to change it to:
const request = chai.request(app).keepOpen()


text:
Q: How to Delete XML Node? I have created methods for selecting and removing nodes from XML. My code runs but XML node is not removed.
I do not know where the code is wrong please help me for this problem:
public XmlNodeList getXmlNodeList(string XmlNodeName)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(_connection);
    XmlNodeList elemList = doc.GetElementsByTagName(XmlNodeName);
    return elemList;
}

public void deleteXmlNode(string XmlNodeName, string XmlNodeValue)
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(_connection);
    XmlNodeList xnode = getXmlNodeList(XmlNodeName);

    foreach (XmlNode item in xnode)
    {
        if (item.InnerText == XmlNodeValue)
        {
            item.ParentNode.RemoveChild(item);
            break;
        }
    }
    xdoc.Save(_connection);
}

My XML code:
<AriaGostarInformation>
  <MenuInformation>
    <MenuNames>
      one
    </MenuNames>
    <MenuNames Name="1">two</MenuNames>
    <MenuNames Name="2">three</MenuNames>
    <MenuNames Name="3">four</MenuNames>
    <MenuNames Name="4">five</MenuNames>
    <MenuNames Name="5">six</MenuNames>
    <SubMenuNames parentName="1">
      fgfgfgfgs
    </SubMenuNames>
    <SubMenuNames parentName="3">
    </SubMenuNames>
  </MenuInformation>
  <SliderInformation>
  </SliderInformation>
  <LasProductInformation>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
    <Product>
      <ImageAddress alt="">../Static/Css/Images/c.jpg</ImageAddress>
      <Subject>bere</Subject>
      <Description>nare</Description>
    </Product>
  </LasProductInformation>
</AriaGostarInformation>

A: You are hurting your performance by loading two separate XmlDocument objects to look up the nodes of your xmltree.  However, it does not look like you have anything actually wrong.  You may not be passing valid parameters.  Have you attempted to add in any tracing to see what values are being submitted to the methods?  Also just a suggestion that these two methods can be combined into a very short method using Linq-to-Xml using the following code for your delete node method.  The below can delete all matching nodes:
public void deleteXmlNode(string xmlNodeName, string xmlNodeValue)
{
     XDocument xDoc = XDocument.Load(_connection);
     var xNodeList = xDoc.Descendants(xmlNodeName).Where(n => n.Value == xmlNodeValue);
     xNodeList.Remove();
}

SOURCE: http://msdn.microsoft.com/en-us/library/bb357554(v=vs.110).aspx


text:
Q: Extract a Zip Archive using PHP what i'm trying to do is to basically extract the contents of Zip archives on my server.Here is some code:
$entry="test.zip";

    $zip = new ZipArchive;

    if ($zip->open($entry,ZIPARCHIVE::OVERWRITE) === TRUE)
    {
        $zip->extractTo('unpacked');
        $zip->close();

     }else
     {
        echo 'failed';

     }

the directory "unpacked" is writeable for everyone and all the used methods of the ZipArchive Class return true. However nothing is being extracted. Does anyone happen to have an idea what  could cause this behaviour? Any hint will be highly appreciated...Thanks in advance!

A: If you are using PHP 5.2.0 or later can you check zlib extension first http://www.zlib.net/
You also check PECL extensions, In order to access ZipArchive, you can also try zip_open, zip_read just for checking.

A: In case of failure you should echo out $zip as it contains the error.
Furthermore I'd guess that you may not have the needed permissions for test.zip

A: If this code is in-house, and you can safely make the assumption that you won't move this code from Linux to Windows (or vice versa), you also have the option to execute local system commands, which may help solve your problem.
<?php

echo `unzip myarchive.zip`;
echo `tar -xzf myotherarchive.tar.gz`;

?>

When developing internal-use and/or maintenance scripts, I used to opt for straight-up system calls, as it was more in-line with the commands sysadmins were used to using.

A: If your zip archive is big, sometimes you cannot extract all files during the maximum allowed execution time of your server.
The only solution, if you cannot change the maximum_execution_time in your php.ini, is to use a javascript to extract one file after the other. On the first javascript request you take the number of files in the archive
$nbr_of_files = $zip->numFiles;

And after you extract one file after another using the id number in the zip archive for each file
$zip->extractTo('unpacked', array($zip->getNameIndex($file_nbr)));

A: Please try removing the ZIPARCHIVE::OVERWRITE flag from the ZipArchive open method. (The flag may not be functioning as expected and may be the root of the issue if you have followed the advice in the other answers.)

A: I had the same issue too. The solution:
$zip->extractTo(public_path() .'/restoreDb/extracted/');

add the public_path() helper function.


text:
Q: Discount amount not showing on checkout I have created rule 50% discount. When buying product it does apply discount on the price but it does not showing that discount amount on checkout.
I tried to do my research and I found that I need this in my code:

/vendor/magento/module-sales-rule/view/frontend/layout/checkout_cart_index.xml

<item name="discount" xsi:type="array">
   <item name="component"     xsi:type="string">Magento_SalesRule/js/view/cart/totals/discount</item>
   <item name="config" xsi:type="array">
    <item name="title" xsi:type="string" translate="true">Discount</item>
   </item>
</item>

And I do have this in my code. Please, help me print out the discount amount from the catalog price rule as I am obligated to show the discount in my order and invoice email and pdf. Right now the discount amount is showing 0%, but it is set to be 50%.
Please help.


text:
Q: How to show images using Mysaifu JVM I'm using Mysaify JVM on Windows 6.1 CE to run Java SWT application.
Folowing codes work fine in WIndows XP - show images on window bar (next to window title)
1.
setImage(SWTResourceManager.getImage(LoginWindow.class, "/com/stream/icons/document16.png"));

2.
Image im = new Image(null, "D:\MWS\MWS_Panel\system\icons\document16.png");
setImage(im);

required swt-gdip-win32-3655.dll ( Mysaifu says  .dll dont want to load this dll ;( )
I tried to load:
png, bmp, jpg, gif
with no success.
Does anyone konow solution of this problem? It's realy hard to find some informationa by Google :(

A: SWT is backed on to native implementations of it's windowing toolkit, this is what is in swt-gdip-wind32-6355.dll, this dll in particalar is the Windows 32 (Windows NT, XP etc) implementation,
In order to use SWT on Windows CE you will need a Windows CE implementation of SWT.
You might be out of luck with SWT on Windows CE the Wikipedia entry doesn't list it as a supported platform.


text:
Q: Python: Why does opening Twitter with selenium in headless mode not open the "normal" Twitter login page? Situation: I am using selenium to scrape Twitter. My script works perfectly fine as long as I am not running headless. Now I am trying to speed up the process and I am trying to run Chrome in headless mode.
Problem: Once I add: options.add_argument('--headless') as an option, it stops working.
I found other posts on this issue and with the help driver.get_screenshot_as_file("screenshot.png") I took a screenshot. On the screenshot I can see the following thing: A twitter logo and the sentence that "This brower is no longer supported". I am confused by this, since everything works fine (meaning that I can get to the "normal" twitter login page) when I disable the "headless" mode.
Goal:
I would like to be able to scrape tweets in headless mode
Code:
def setup():
   options = Options()
   options.add_argument('--headless')
   options.add_argument("--window-size=1920,1080")
   options.add_argument('--disable-dev-shm-usage')
   driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
   driver.get("https://www.twitter.com/login")
   driver.get_screenshot_as_file("screenshot1.png")
   username = WebDriverWait(driver, 30).until(EC.presence_of_element_located(("xpath", '//input[@name = "text"]')))
   username.send_keys('myemailgoeshere@whatever.com')
   username.send_keys(Keys.RETURN)

   print("finished username") # control to check whether it finished the first part

   try:
       phone = WebDriverWait(driver, 5).until(EC.presence_of_element_located(("xpath", '//input[@data-testid = "ocfEnterTextTextInput"]')))
       phone.send_keys('+1234567890')
       phone.send_keys(Keys.RETURN)
   except TimeoutException:
       pass
   password = WebDriverWait(driver, 30).until(EC.presence_of_element_located(("xpath", '//input[@name = "password"]')))
   password.send_keys('mypassword')
   password.send_keys(Keys.RETURN)
   WebDriverWait(driver, 30).until(EC.presence_of_element_located(("xpath", './/span[contains(text(), "Refuse non-essential cookies")]'))).click()
   search_input = WebDriverWait(driver, 30).until(EC.presence_of_element_located(("xpath", '//input[@aria-label = "Search query"]')))
   search_input.send_keys('#life')
   search_input.send_keys(Keys.RETURN)

   print("finished setup")

   return driver

Error Message: Line 9 username = WebDriverWait(driver, 30).until(EC.presence_of_element_located(("xpath", '//input[@name = "text"]'))) gives a TimeoutException. This is because the "login-page" looks different/is not existed as described from the screenshot.
I am new to StackOverflow please let me know if anything is unclear or if I should add more information.
Thanks!

A: I solved the problem. Apparently Twitter was blocking the driver in headless mode. I added
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
options.add_argument(f'user-agent={user_agent}')
as options to the driver. I found the answer in this post chrome --headless mode not working however normal mode is working fine. Everything works now.


text:
Q: JMeter testing with BIRT report I'm writing scripts for Load Testing for an IBM maximo application. This Application creates some BIRT reports and displays them in the same browser window but in a different tab.
I'm clueless how to open these with JMeter http Request. I copied the same request in JMeter as I found in Fiddler, but encountered some errors in the response.
My fiddler request is as follows:
reportFile=asset_meters.rptdesign&reportNum=1170&__newrun=true&comments=&fromEmail=no&where=%25EF%25BF%258E%25EF%25BF%25B9%2522%2513%2508%25136%25EF%25BE%25A8J%25EF%25BE%25A8%2501%25EF%25BF%25B5%25EF%25BE%2591%2527%25EF%25BF%2593y%25EF%25BF%25ACU%2523%2518x%251B%25EF%25BF%2580%25EF%25BF%2592%25EF%25BF%25BAh%250C%25EF%25BF%25A8o%25EF%25BE%25B6%2517%25EF%25BF%25A4*%25EF%25BE%25A0o%25EF%25BE%258BN%25EF%25BF%258A%25EF%25BE%25A8b3%25EF%25BF%25A8%250F%2505%25EF%25BE%25BFcU%2522&mroOrg=QRC&redir=%2Fmaximo%2Freport%2F%3F__report%3Dasset_meters.rptdesign%26appname%3DASSET%26__requestid%3D1550750628853%26uisessionid%3D17617%26csrftoken%3D8dkj0qdgphnd347jreegt21lj5&mroApp=ASSET&maxPass=%25EF%25BE%25AA%25EF%25BE%25A5%2529%25EF%25BF%2592h%2510%25EF%25BE%2596%25EF%25BE%2594&redirParams=repositoryType%3DEnterprise&customrptServerLogonPass=&smtpHost=localhost&localTZ=Africa%2FAlgiers&locale=en_US&p_asset=M100000000003&reportDesc=QR+-+Asset+Meters+%26+Installed+Information&mroUniqueKey=190221160348853_29579&extendedFields=false&Email_Choice=PDF&emails=&userName=maxadmin&ParmUserName=maxdemo&reportFolder=ASSET&qbrDisplayWhere=%28assetnum+like+%27%25M100000000003%25%27%29&schema=maxdemo&reportType=BIRT&appname=ASSET&ParmPassword=%25EF%25BE%25AA%25EF%25BE%25A5%2529%25EF%25BF%2592h%2510%25EF%25BE%2596%25EF%25BE%2594&mroSite=METRO&paramdelimiter=%7C%7C&paramstring=appHierarchy%3DASSET&__scheduleType=immediate&__reportname=asset_meters.rptdesign&isDuplex=0&baseTable=ASSET&customserverURL=&__overwrite=new&baseUrl=http%3A%2F%2F172.17.43.71%3A9080
JMeter Request is:
reportFile=asset_meters.rptdesign&reportNum=1170&__newrun=true&comments=&fromEmail=no&where=%25EF%25BF%258E%25EF%25BF%25B9%2522%2513%2508%25136%25EF%25BE%25A8J%25EF%25BE%25A8%2501%25EF%25BF%25B5%25EF%25BE%2591%2527%25EF%25BF%2593y%25EF%25BF%25ACU%2523%2518x%251B%25EF%25BF%2580%25EF%25BF%2592%25EF%25BF%25BAh%250C%25EF%25BF%25A8o%25EF%25BE%25B6%2517%25EF%25BF%25A4*%25EF%25BE%25A0o%25EF%25BE%258BN%25EF%25BF%258A%25EF%25BE%25A8b3%25EF%25BF%25A8%250F%2505%25EF%25BE%25BFcU%2522&mroOrg=QRC&redir=%2Fmaximo%2Freport%2F%3F__report%3Dasset_meters.rptdesign%26appname%3DASSET%26__requestid%3D1550750847369%26uisessionid%3D17618%26csrftoken%3Detbohmkqeg5ufvpr1tvrv9qp9a&mroApp=ASSET&maxPass=%25EF%25BE%25AA%25EF%25BE%25A5%2529%25EF%25BF%2592h%2510%25EF%25BE%2596%25EF%25BE%2594&redirParams=repositoryType%3DEnterprise&customrptServerLogonPass=&smtpHost=localhost&localTZ=Africa%2FAlgiers&locale=en_US&p_asset=M100000000003&reportDesc=QR+-+Asset+Meters+%26+Installed+Information&mroUniqueKey=190221160727369_29580&extendedFields=false&Email_Choice=PDF&emails=&userName=maxadmin&ParmUserName=maxdemo&reportFolder=ASSET&qbrDisplayWhere=%28assetnum+like+%27%25M100000000003%25%27%29&schema=maxdemo&reportType=BIRT&appname=ASSET&ParmPassword=%25EF%25BE%25AA%25EF%25BE%25A5%2529%25EF%25BF%2592h%2510%25EF%25BE%2596%25EF%25BE%2594&mroSite=METRO&paramdelimiter=%7C%7C&paramstring=appHierarchy%3DASSET&__scheduleType=immediate&__reportname=asset_meters.rptdesign&isDuplex=0&baseTable=ASSET&customserverURL=&__overwrite=new&baseUrl=http%3A%2F%2F172.17.43.71%3A9080
The corresponding responses:
Fiddler response is:

JMeter response is:

I checked in the server logs, but found nothing suspicious.
Then I observed in the JSON tab (in the Fiddler request) something like:

Is this is the bottleneck reason for me?
How can I embed this in my JMeter request?

A: My expectation is that you need to implement correlation, to wit extract the dynamic values for the following parameters:

*

*__requestid

*csrftoken

*mroUniqueKey

*etc.

*

*Check previous response and carefully inspect it looking for the values of the (at least) aforementioned parameters

*Extract them using suitable JMeter Post-Processors and store into JMeter Variables

*Replace hard-coded (recorded?) values in the HTTP Request with the values from step 2

Given you send the same request in JMeter as browser does (apart from dynamic parameters) you should be able to see the same response.
Check out How to Handle Correlation in JMeter article to learn more about "correlation" concept


text:
Q: Как очистить столбец от непечатных символов так, чтобы остались только буквы и пробелы? Где-то в строках столбца ФИО засели символы, которые мне не удается вычистить.
То есть удается только удалив и все пробелы заодно. Между Фамилией, именем, и отчеством должны быть одинарные пробелы.
SELECT REGEXP_REPLACE("ФИО",'\s') FROM MyTable;

A: Вот как звучит вопрос, так и делайте: от символов [ не ^ печатных [:print:], получится:
select
    '>>'||"ФИО"||'<<' "ФИО", '>>'||regexp_replace ("ФИО", '[^[:print:]]+')||'<<' "ФИО"
from (
    select chr(9)||'Иванов '||chr(10)||'Иван Иваныч'||chr(7) "ФИО" from dual)
/

ФИО                       ФИО
------------------------- ----------------------
>>  Иванов                  >>Иванов Иван Иваныч<<
Иван Иваныч<<


text:
Q: Resolving Dependency from Github using Ivy.xml I have a github repo that I created a Release for.  While creating the release I manually added a .jar file. Lets call it exampleLibrary.jar
This would be github.com/MyExampleRepo/Releases
I have a project I want to add a dependency for to use this exampleLibrary.jar file I added in my release v1.0
This project using Ivy.xml for resolving dependencies.
To get the jar from github using maven with pom.xml I imagine it would look something like this:
<dependency>
    <groupId>com.github.User</groupId>
    <artifactId>Repo name</artifactId>
    <version>Release tag</version>
</dependency>

How would I do this using Ivy.xml? This is what I have tried:
<dependency org="com.github" name="MyExampleRepo" rev="v1.0"/>


text:
Q: Making checkbox transparent I've made a form with a checkbox. Now I need to make a checkbox appear as on the image:

What would be the best way to achieve this?
Also, they checkbox should be :checked once the label is clicked.
HTML:

    <input id="custom-checkbox" type="checkbox" required>
    Disclaimer: Click here if you are okay...

A: Like Mr_Green was saying, you could hide the checkbox and use the label. Make sure you have the label after the checkbox, not the label wrapping the checkbox.
SNIPPET

/* CheX */

input.chkrad {
  display: none;
}
input.chkrad + label {
  color: #111;
  font-size: 16px;
  background: url(http://i.imgur.com/clMMf.png) no-repeat; background-size: cover;
}
input.chkrad + label span {
  display: inline-block;
  width: 12px;
  height: 12px;
  margin: -1px 4px 0 0;
  vertical-align: baseline;
  cursor: pointer;
}
input + label span {
  background: #fff;
  line-height: 100%;
}
input.X:checked + label span {
  padding: -3px 0 3px;
}
input.X:checked + label span:before {
  content: 'X';
  color: #F00;
  font-family: cursive;
  font-style: oblique;
  font-weight: 900;
}
<input type='checkbox' name='chk3' id="chk3" class="chkrad X fade" value='x' />
 Disclaimer: Click anywhere on this text if you are okay...


text:
Q: How to rotate text drawn in a straight line (without radius) when using drawTextOnPath? I want to rotate the numbers in canvas,
This is what I have tried:
override fun onDraw(canvas: Canvas) {
var i = 0
while (i < rulerHeightInInch) {
val markingPositionYaxis =
            screenHeightInPx - (ydpinch * i + topThreshold)
paint.textSize = getPixelValueForDp(18.0f)
                    val path = Path()
                    path.reset()
                    path.moveTo(
                        (getPixelValueForDp(30f) + paint.textSize),
                        markingPositionYaxis +17
                    )
                    path.lineTo(
                        (getPixelValueForDp(30f) + paint.textSize),
                        markingPositionYaxis - (paint.textSize)
                    )
                    canvas.drawTextOnPath(nf.format(i / 32), path, 0f, 0f, paint)
}
i++
}
}

First image is what I have  right now

Second image is what I want

I don't want to draw in circular path or by using radius I want from top to bottom in a straight line

A: This is how i did it:
canvas.save()
canvas.rotate(180f,(getPixelValueForDp(30f) + paint.textSize),markingPositionYaxis)
canvas.drawTextOnPath(nf.format(i / 32), path, 0f, 0f, paint)
canvas.restore()


text:
Q: CustomView setting size I'm trying to set CustomView size, CustomView is in NSWindow. The problem is that when the window resizes, CustomView resizes with the window. Any ideas how to set CustomView size and make it not resizable?

A: check under the size inspector on the right pane in xcode and check if the view has any autosizing constraints that are making it do that.


text:
Q: Spring Junit Mockito Runner read property from test application properties file My test class is:
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource
public class FooClassTest {

    @Value("${foo.property}")
    String property;

    ...
}

In my application properties, inside test/resources folder, I have the property foo.property=some, but when I launch FooClassTest, property is null.
What I am doing wrong?

A: Remove the @TestPropertySource if you refer to the documenation (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html) it states

@TestPropertySource is a class-level annotation that is used to
  configure the locations() of properties files and inlined
  properties()....

It also states

Test property sources have higher precedence than those loaded from
  the operating system's environment or Java system properties as well
  as property sources added by the application declaratively


text:
Q: How can I call a lambda without defining it as a function? For lambda functions in the following code,
def myfunc(n):
  return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))

I am trying to understand why mydoubler becomes <class 'function'> and how I can call mydoubler(11) without defining it as a function.

A: A lambda is a function, but with only one expression (line of code).
That expression is executed when the function is called, and the result is returned.
So the equivalent of this lambda:
double = lambda x: x * 2

is this def function:
def double(x):
    return x * 2

You can read more here

A: A lambda is a function, so your code is doing something like
def myfunc(n):
    def result(a):
        return a * n
    return result # returns a function

mydoubler = myfunc(2)
print(f(11))

You're asking how to call mydoubler without defining it as a function, which isn't the clearest question, but you can call it without naming it like so
print( myfunc(2)(11) )

A: Your myfunc is returning a lambda. Lambda is a small anonymous function. A lambda can take any number of arguments, but can only have one expression.
So after execution of the 3rd line, your mydoubler will become a lambda that's why when you try print(type(mydoubler)) it will return <class 'function'>.
Also in order to call mydoubler with 11, it must be function.

A: A lambda expression, like a def statement, defines functions. Your code could be equivalently written as
def myfunc(n):
  def _(a):
    return a * n
  return _
mydoubler = myfunc(2)
print(mydoubler(11))

Because the inner function is simple enough to be defined as a single expression, using a lambda expression saves you the trouble of coming up with the otherwise unused name the def statement requires.
The key here is that the inner function closes over the value of n, so that the function returned by myfunc retains a reference to the value of the argument passed to myfunc. That is, mydoubler is hard-coded to multiply its argument by 2, rather than whatever value n may get later. (Indeed, the purpose of the closure is to create a new variable n used by the inner function, one which cannot easily be changed from outside myfunc.)

A: using decorator you can achive this
from functools import wraps

def decorator_func_with_args(arg1):
    def decorator(f):
        @wraps(f)
        def wrapper(val):
            result = f(val)
            return result(arg1)
        return wrapper
    return decorator

@decorator_func_with_args(arg1=2)
def myfunc(n):
    return lambda arg:arg*n

result = myfunc(1211)
print(result)

output
2422

A: Do you mean this?
mydoubler = lambda a : a * 2
mydoubler(11)


text:
Q: Разметка в tkinter Двигается кнопка, если расширяется лэйбл. Может, ее можно как-то закрепить/заблокировать?
self.but_OK = Button(root, background="#555",  text='^Generate our sets^', font='Arial 12', height=3, command=self.generABC)
self.but_OK.grid(column=2, row=5, columnspan=4)
self.res = Label(root,height=6, text='D = ( (A \ B) | (B & A) ) \ (C | B) = {}\n'.format(initeq.initial_eq(self.A,self.B,self.C)), font='Arial 12 bold', bg='white')
self.res.grid(column=1, row=15, sticky=S)

Получается, когда результат D очень большой(а это множество), то моя кнопка сдвигается вправо.

A: При помощи .pack можно привязать виджет к определенной стороне left, right, top, bottom
Пример:
import tkinter
root = tkinter.Tk()
label_left = tkinter.Label(root, text='Label left')
label_left.pack(side="left")

label_top = tkinter.Label(root, text='Label top')
label_top.pack(side="top")

label_right = tkinter.Label(root, text='Label right')
label_right.pack(side="right")

label_bottom = tkinter.Label(root, text='Label bottom')
label_bottom.pack(side="bottom")
root.mainloop()

Так же можно при помощи .place(x=, y=) можно зафискировать на определенной оси x, y
Пример:
import tkinter
root = tkinter.Tk()
label_left = tkinter.Label(root, text='Label left')
label_left.place(x=0, y=0)

label_top = tkinter.Label(root, text='Label top')
label_top.place(x=0, y=50)

label_right = tkinter.Label(root, text='Label right')
label_right.place(x=0, y=100)

label_bottom = tkinter.Label(root, text='Label bottom')
label_bottom.place(x=0, y=150)
root.mainloop()


text:
Q: How to count users per group assuming many-to-many relation? I have two tables users and groups, as well as a third table that defines many-to-many relationship users_groups:
Table "group":
CREATE TABLE `group` (
  `ID` int(11) NOT NULL,
  `creation_date` date NOT NULL,
  `type` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `group` (`ID`, `creation_date`, `type`) VALUES
(1, '2017-06-01', 'AAA'),
(2, '2017-06-01', 'BBB'),
(3, '2017-06-01', 'CCC');

Table "user":
CREATE TABLE `user` (
  `ID` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `surnames` varchar(100) NOT NULL,
  `birthdate` date NOT NULL,
  `qualification` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user` (`ID`, `name`, `surnames`, `birthdate`, `qualification`) VALUES
(1, 'xxx', 'xxx', '1989-03-03', 'A'),
(2, 'xxx', 'xxx', '1990-06-15', 'A'),
(3, 'xxx', 'xxx', '1982-06-14', 'B'),
(4, 'xxx', 'xxx', '1988-06-19', 'B'),
(5, 'xxx', 'xxx', '1984-03-12', 'B'),
(6, 'xxx', 'xxx', '1987-12-19', 'C');

Table "users_groups":
CREATE TABLE `user_group` (
  `ID` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user_group` (`ID`, `user_id`, `group_id`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 2),
(4, 4, 2),
(5, 5, 2),
(6, 6, 3);

I need to count the number of users per group and summarize results as follows:
ID   creation_date    type   users_count_per_group
1    2017-06-01       AAA    2
2    2017-06-01       BBB    3
3    2017-06-01       CCC    1

This is my current query. I get stuck with many-to-many relation, which means that the same user may appear in different groups (though in my sample data all users appear just once per group):
SELECT `group`.`ID`, `group`.`creation_date`, `group`.`type`, COUNT(*)
FROM `group`, `user`, `user_group`
WHERE `group`.`ID`=`user_group`.`group_id`
      AND `user`.`ID`=`user_group`.`user_id`;

A: You're missing the group by clause:
SELECT   `group`.`ID`, `group`.`creation_date`, `group`.`type`, COUNT(*)
FROM     `group`, `user`, `user_group`
WHERE    `group`.`ID`=`user_group`.`group_id` AND
         `user`.`ID`=`user_group`.`user_id`
GROUP BY `group`.`ID`, `group`.`creation_date`, `group`.`type`

Note that implicit joins (i.e., using more than one table in the from clause) have been considered deprecated for quite some time now. It would be better to use explicit join clauses:
SELECT   `group`.`ID`, `group`.`creation_date`, `group`.`type`, COUNT(*)
FROM     `group`
JOIN     `user_group` ON `group`.`ID` = `user_group`.`group_id`
JOIN     `user` ON `user`.`ID` = `user_group`.`user_id`
GROUP BY `group`.`ID`, `group`.`creation_date`, `group`.`type`

A: Try this:
SELECT `group`.`ID`, `group`.`creation_date`, `group`.`type`, COUNT(*)
FROM `user_group`
JOIN `user` on `user`.ID = `user_group`.`user_id`
JOIN `group` on `group`.ID = `user_group`.`group_id`
GROUP BY `user_group`.`group_id`

A: You do not need to join in the users table to do what you want.  So, the query only requires one join:
SELECT g.id, g.creation_date, g.type, COUNT(*) as users_count_per_group
FROM `group` g JOIN
     user_group ug
     ON g.id = ug.group_id
GROUP BY g.id, g.creation_date, g.type;

Addition notes:

*

*group is a really bad name for a table, because it is a SQL keyword.  I name tables in the plural, which general avoids this problem.

*Table aliases make the query easier to write and to read.

*Backticks make the query harder to write and to read.


text:
Q: How to I make my background color a little black when pop up a message box?

$("documant").ready(function() {
  $("#add_form").hide(); //message box hide in the beginning
});

function checkID() {
  if ($("#add_form").is(":hidden")) {
    $("#userID").val("");
    $("#add_form").slideDown(500);
  } else {
    $("#add_form").hide();
  }
}

function closeForm() {
  $("#add_form").hide(); // hide form when click cancel
}
.center {
  position: absolute;
  text-align: center;
  z-index: 100;
}
#add_form {
  margin: 0 auto;
  width: 200px;
  background-color: #f0f0f0;
}
#add_form p {
  font-size: 1.2em;
}
#submitGetCancel,
#submitGetCheck {
  width: 40%;
  height: 50px;
  color: #740000;
  font-size: 1.3em;
}
#overlayBackground {
  background: #000;
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 5;
}

<button id="click" onclick="checkID();">Click</button>

Some text here

Please type your infos

    <input type="text" id="userID" name="userID">

    <button type="button" class="btn btn_cancel" id="submitGetCancel">Send</button>
    <button type="button" class="btn btn_add" id="submitGetCheck" onclick="closeForm();">Cancel</button>

When I click on button, a message box will display.
What can I do to make my background color a little black which mean I can still see content under message box when message box is display and also everything will back to default when click cancel of box?

A: You can create a dynamic overlay div and set the background color with rgba():

$(document).ready(function() {
  $("#add_form").hide(); //message box hide in the beginning
});

function checkID() {
  if ($("#add_form").is(":hidden")) {
    $("#userID").val("");
    $("#add_form").slideDown(500);
    $('
',{ // <------------------create a dynamic overlay div
      id:"overlay"
    }).appendTo("body"); //<-----append to body.
  } else {
    $("#add_form").hide();
  }
}

function closeForm() {
  $("#add_form").hide(); // hide form when click cancel
  $('#overlay').remove(); // <-----------------remove this overlay when cancel clicked.
}
.center {
  position: absolute;
  text-align: center;
  z-index: 100;
}
#add_form {
  margin: 0 auto;
  width: 200px;
  background-color: #f0f0f0;
}
#add_form p {
  font-size: 1.2em;
}
#submitGetCancel,
#submitGetCheck {
  width: 40%;
  height: 50px;
  color: #740000;
  font-size: 1.3em;
}
#overlayBackground {
  background: #000;
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 5;
}
#overlay{
  background:rgba(0, 0, 0, .5);
  width:100%;
  height:100%;
  position:fixed;
  left:0;
  top:0;
  z-index:2;
}

<button id="click" onclick="checkID();">Click</button>

Some text here

Please type your infos

    <input type="text" id="userID" name="userID">

    <button type="button" class="btn btn_cancel" id="submitGetCancel">Send</button>
    <button type="button" class="btn btn_add" id="submitGetCheck" onclick="closeForm();">Cancel</button>

A: There is a jQuery plugin for that.
Also it's easy to use: $.blockUI({ message: 'HTML CONTENT HERE', css: { backgroundColor: '#f00'} });
There are more paramaters that you can use, depends on situation. To remove it just use $.unblockUI();

More details you can find here.


text:
Q: Building glew on windows with mingw32 It is a duplicate and I am sorry about it but I don't have any other options because I can't make comments on answers and they didn't solved my problem.  Here is the original post:
Building glew on windows with mingw
And here is my problem:
1) When I try @LightningIsMyName's answer I get this error:

Makefile:1: *** missing seperator. Stop.

2) When I try @anon's answer I get this error:

Makefile:1: Makefile:1: *** commands commence before first target. Stop.

People says this andswer helped them but they didn't worked for me. I apogilize I duplicae a question somehow but I have no other chance with reputation limit for commenting. Hope you help. Thanks.

A: I have performed many searches in order to find an answer to my problems. It took a lot of time so I am posting it here to help others.
To make GLEW work with MinGW you should download the source from GLEW website and put

gcc.exe from MinGW\bin
ar.exe from MinGW32\mingw32\bin

to GLEW's source folder and create and run a .bat in that folder like that:
gcc -DGLEW_NO_GLU -O2 -Wall -W -Iinclude  -DGLEW_BUILD -o src/glew.o -c src/glew.c
gcc -shared -Wl,-soname,libglew32.dll -Wl,--out-implib,lib/libglew32.dll.a    -o lib/glew32.dll src/glew.o -L/mingw/lib -lglu32 -lopengl32 -lgdi32 -luser32 -lkernel32
ar cr lib/libglew32.a src/glew.o

gcc -DGLEW_NO_GLU -DGLEW_MX -O2 -Wall -W -Iinclude  -DGLEW_BUILD -o src/glew.mx.o -c src/glew.c
gcc -shared -Wl,-soname,libglew32mx.dll -Wl,--out-implib,lib/libglew32mx.dll.a -o lib/glew32mx.dll src/glew.mx.o -L/mingw/lib -lglu32 -lopengl32 -lgdi32 -luser32 -lkernel32
ar cr lib/libglew32mx.a src/glew.mx.o

you will get your .dll and .a files in lib folder. Put .dll files to system32 folder and put .a files to MinGW lib folder.
Finally, if you are using SFML, link SFML libraries before GLEW and at last link OpenGL. If you change the linking order you will get a linker error.
Don't forget to call glewInit() after creating your window.

A: If you can't get it work in that way try mine (for Borland compilers):

*

*download GLEW source code (not the binaries)

*

*glew.c source code mine is ~900KB (I think GLEW 1.6)

*glew.h header mine is ~900KB (I think GLEW 1.6)

*I use local project path to store GLEW
I know it is redundant but I do not need to make changes after system changes like reinstall OS or new compiler version etc... but to get it work you need to do some changes inside glew.c:

*

*change #include <glew.h> to #include "glew.h"
if you want to use global path then add it to your compiler,copy the files there and leave the <> as are

*copy these 2 files to your project
this is how to correctly include it into project just add this to your main source file (where your winmain or main function is):
#include <windows.h> // optional windows
#include <math.h>    // optional
#define GLEW_STATIC  // this configure header and source of GLEW to compile correctly
#include "glew.c"    // header is included inside so no need to duplicate include
// here are the OpenGL includes like: gl.h,glext.h,....

*Now it should work
do not forget to call glewInit(); after OpenGL is initialized and before any extension is used ...

A: Try these commands:
1: gcc -DGLEW_NO_GLU -O2 -Wall -W -Iinclude -DGLEW_BUILD -o src/glew.o -c src/glew.c
2: gcc -shared -Wl,-soname,libglew32.dll -Wl,--out-implib,lib/libglew32.dll.a -o lib/glew32.dll src/glew.o -L/mingw/lib -lglu32 -lopengl32 -lgdi32 -luser32 -lkernel32
3: ar cr lib/libglew32.a src/glew.o


text:
Q: AWS CLI to filter images based on tags I want to get AMI's which are not having a specific tag using AWS CLI. I do not know how to use not included filter.
Tried this BUT getting error.
aws ec2 describe-images --profile prod --owners asfhjaf --filter "Name=name,Values=UAT" "Name=tag-key,Values!=Delete" --query 'Images[*].[ImageId,CreationDate]'

A: One of the options that you can try is to use --query parameter along with --fitlers.

*

*First filter key Name

*Then query where not sometag
aws ec2 describe-images  --owners asfhjaf  --filters Name=tag-key,Values=Name --query 'Images[].Tags[?Value != `sometagvalue`]'

output
[
    [
        {
            "Key": "Name",
            "Value": "demo"
        }
    ],
    [],
]

or to remove the empty array
aws ec2 describe-images  --owners asfhjaf  --filters Name=tag-key,Values=Name --query 'Images[].Tags[?Value != `sometagvalue`]' | jq '[ .[] | select(length > 0) ]'

To print Image ID and creation Date
aws ec2 describe-images  --owners abcd  --filters Name=tag-key,Values=Name --query 'Images[].{Tags:Tags[?Value != `sensu`],ImageId:ImageId,CreationDate:CreationDate}' | jq '[ .[].Tags | select(length > 0) ]'


text:
Q: Help me understand the operator norm The definition I have for the operator norm is:
$L(\Bbb U,\Bbb V)$ is the vector space of all linear transformations $f: \Bbb U \to \Bbb V$.  Let $\Bbb U\ \&\ \Bbb V$ be inner product spaces.  Define the operator norm on $L(\Bbb U,\Bbb V)$:
$$|f|_O=\max_{|u| \le1} |f(u)|$$
First, I need to show that this IS a norm.  I can prove all of the axioms except:
If $f \neq 0$ then $|f|_O \gt 0$.
In particular, why couldn't we have a linear function f with the property that $f(u)=0$ for some interval (like $0 \le u \le 1$) and then nonzero outside of that interval?  I don't see how that is not possible from $f(au)=af(u)$ or $f(u+v)=f(u)+f(v)$.
Second, I need to show that $|f(u)| \le |f|_O|u|$.
To me this looks like $|f|_O|u|=(max_{|u| \le1} |f(u)|)|u|=max_{|u| \le1} (|f(u)||u|)$ which I would think would be LESS than $|f(u)|$.

A: If $f(u)=0$ for all $u$ with $|u|=1$, it is easy to show that $f(v)=0$ for all $v$. Hint: take $u=\frac{v}{|v|}$.
Regarding the second question, you made a mistake when writing
$$\max_{|u|\leq 1}(|f(u)|)|u| = \max_{|u|\leq 1}(|f(u)||u|)$$
What you should write is
$$\max_{|u|\leq 1}(|f(u)|)|u| = \max_{|v|\leq 1}(|f(v)||u|)$$


text:
Q: Django: ModelForm validation not working I am trying to create a user registration form. I know there is a built-in user registration form in Django but I am challenging myself to create one.
I created a ModelForm from User model and wrote few methods to validate and confirm password . But it seems that the methods, clean_password() and clean() are not being executed by form.is_valid() at views.py.
Below is the snippet of RegistrationForm -
class RegistrationForm(ModelForm):
    re_password = CharField(widget = PasswordInput(attrs = {'placeholder' : 'Re-password'}))
    class Meta:
        model = User
        fields = ['username', 'email', 'password']
        widgets = {
                'username' : TextInput(attrs = {'placeholder':'Username'}),
                'email' : EmailInput(attrs = {'placeholder' : 'Email'}),
                'password' : PasswordInput(attrs = {'placeholder' : 'Password'})
                }

        def clean_password(self):
            password = self.cleaned_data['password']
            if len(password) < 6:
                raise forms.ValidationError('Password not long enough. Should be >= 6')
            return password

        def clean(self):
            if not self.cleaned_data['password'] == self.cleaned_data['re_password']:
                raise forms.ValidationError("Passwords should match")
            return self.cleaned_data

Additional question
The password does not seem to be encrypted by form.save(). I had to create new User instance and call its .set_password() method to encrypt it. Is this the right way to do it?

A: You are correct about having to set the password. Your view should look something like:
if form.is_valid():
    user = form.save(commit=False)  # Don't waste the database write
    user.set_password(form.cleaned_data['password'])
    user.save()

Update

*

*you need to remove your clean_password method and add validators=[validators.MinLengthValidator(6)] to the password model field's declaration (or simply define password as a field on the form manually, and provide min_length=6 to it).

*You need to dedent your clean method by 1 level or it will never be called (it's currently being defined as a method on your Meta class).

A: Indentation Error. The validators are inside the META instead of RegistrationForm.

A: Firstly, you can define min_length of password field in __init__ method of form, like this:
def __init__(self, *args, **kwargs):
    super(RegistrationForm, self).__init__(*args, **kwargs)
    self.fields['password'].min_length = 6

In second, yes, this right way


text:
Q: NSViewController -- dismiss with memory cleanup My environment is Yosemite 10.10.5 with Xcode 7.2 using ARC.
In a simple test program, I am attempting various ways to dismiss a NSViewController and all of them are showing problems with memory handling.
In my primary view controller, I have the following code.  (The notification pieces are there to test various ways of dismissing the presented controller.)
- (IBAction)showFirstReplacement:(id)sender {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissWithNotification:) name:@"removeFirst" object:nil];
    NSStoryboard *sb = [self storyboard];
    FirstReplacement *controller = [sb instantiateControllerWithIdentifier:@"first_replacement"];
    [self presentViewControllerAsSheet:controller];
}

- (void)dismissWithNotification:(NSNotification *)notification {
    NSViewController *controller = [notification object];
    [self dismissViewController:controller];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Inside FirstReplacement, I have:
- (IBAction)dismiss:(id)sender {
    [self dismissViewController:self];
//  [[NSNotificationCenter defaultCenter] postNotificationName:@"removeFirst" object:self];
//  [[self presentingViewController] dismissViewController:self];
}

Uncommenting any one of the three lines in this method produces the correct visual results but....  Depending on which of the calls I enable inside dismiss:, I get different results when profiling.  Using self dismissViewController:, I see no leaks but FirstReplacement objects are not deallocated.  Using either of the other two approaches gets rid of the dismissed FirstReplacement but leaks one 16-byte malloc block and one NSMutableArray every time a view controller is dismissed.
According to Instruments, the leaks are related to a method called [NSViewController _addPresentedViewController:].
Are there other clean-up steps necessary to prevent these leaks (or memory bloat in the non-leak case)?

A: The view controller that presents another view controller is also responsible for dismissing it. So none of the lines in FirstReplacement's dismiss method are correct. Instead, you should be creating a delegate in FirstReplacement so it can notify its delegate (the primary view controller) that it should be dismissed.
FirstReplacement.h
@class FirstReplacement;

@protocol FirstReplacementDelegate <NSObject>
- (void)firstReplacementShouldDismiss:(FirstReplacement *)controller;
@end

@interface FirstReplacement : NSViewController
@property (nonatomic, weak) id<FirstReplacementDelegate> delegate;
@end

FirstReplacement.m
- (IBAction)dismiss:(id)sender {
    [self.delegate firstReplacementShouldDismiss:self];
}

Then in your primary view controller:
- (IBAction)showFirstReplacement:(id)sender {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissWithNotification:) name:@"removeFirst" object:nil];
    NSStoryboard *sb = [self storyboard];
    FirstReplacement *controller = [sb instantiateControllerWithIdentifier:@"first_replacement"];
    controller.delegate = self;
    [self presentViewControllerAsSheet:controller];
}

- (void)firstReplacementShouldDismiss:(FirstReplacement *)controller {
    [self dismissViewController:controller];
}

While it may seem like posting a notification is the same as a delegate, it is not. The difference is that when dismissWithNotification fires, you are still executing the code from FirstReplacement::dismiss. NSNotificationCenter::postNotificationName does not finish executing until all observers have finished executing their selectors. So even though the dismissal code is executing in the primary view controller, it still being run from the dismiss method.
If you are still not convinced, override FirstReplacement::dealloc to print a log statement. You will see that dealloc is not called using any of your methods, but will be called using delegation.


text:
Q: How can I stop nHibernate from helpfully setting a date value on a non-null object field when the underlying database field value is null? I read with excitement the first article that popped up in google -- it was exactly my problem.  I have an object model with a non-null date field, but the underlying database field was nullable, and had a null value.  It was a DateTime.  nHibernate set the value to .Net's Date.MinValue, then tried to save it back, yielding an error.
The solution in the article:  Simply use "DateTime?" in the domain model.
That won't work for us.
Here's the thing:  We're doing a major refactor, which includes data migrations from one schema to another, moving from ADO to nHibernate, etc., complex stuff.  Bottom line:  The object model is correct as it is, it's NOT a nullable DateTime (A "CreatedDate").  Setting it to DateTime? would work technically, but it's wrong domain-ly.  What I REALLY want is for nHibernate to stop being so helpful and just throw an error when it runs across an attempt to load a null DateTime into a non-nullable domain object.  I believe this will help us to identify these issues much more quickly.
I know nHibernate is highly configurable/mappable... is there a way to achieve this behavior, and what's the best way to do it...?
Thanks in advance for any help!

A: Is DateTime.MinValue a useful value for you?
Can't you simply implement the setter and throw an exception when you get that value?

A: It sounds like the column itself should actually not be nullable in the database.  One thing I've seen in the past is to default the "CreateDate" column to getdate() in the database.  You could also implement a trigger to set the CreateDate to getdate() when a record is inserted.  If you use the default, the value will be set when the record is inserted (as long as you don't explicitly pass one in), and Hibernate should be able to return it to you after the save, or the next time you lookup the record.

A: The best solution is to make the field non-nullable in the database. Is there a reason you can't do that? It's important that nullability in your domain model matches the database schema.
I don't know of a way to set this behavior by configuration. If this affects a few fields you can hide the problem by mapping a private field and controlling it through a property but this won't give you an exception on load. To do that you would have to write an implementation of ILoadEventListener (I think that's the right one, I've never done it).


text:
Q: How to use sed to postfix specified letter in specified line I have a file like this:
www,/something else/,ese
www,/something else/,aes
arc,/something else/,ese
old,/something else/,ese

I wanna postfix ",0" to all lines except "www,/something else/,aes" with ",1","old,/something else/,ese" with nothing.
So the result should be like that:
www,/something else/,ese,0
www,/something else/,aee,1
arc,/something else/,ese,0
old,/something else/,ese

How can I made that? Thanks.

A: You can use this awk,
awk -F',' '{$4="0";} $1=="www" && $3=="aes"{$4="1";} $1=="old"{NF=NF-1}1' OFS=, yourfile

A: This may work.
awk 'p="0" $0~/aes/ {p=1} $0~/old/ {p=""} {print $0(p~/0|1/?",":"")p}' file
www,/something else/,ese,0
www,/something else/,aes,1
arc,/something else/,ese,0
old,/something else/,ese

A: sed '\#^www,/something else/,ese$# {s//&,1/;b;}
     \#^old,/something else/,ese$# b
     s/$/,0/' YourFile

the something else could be replaced by any pattern like .* but # (or use another delimiter)

A: You could use the following sed script:
example.sed:
# Append the 1 to www ... aes and got to next line in input
/www,\/something else\/,aes/ {s/.*/\0,1/;b next}

# Do nothing here and go to next line in input
/old,\/something else\/,ese/b next

# Append the 0 for all other lines
s/.*/\0,0/

# Label for above jump statements (b next)
:next

Execute it like this:
sed -f example.sed input.txt

A: This might work for you (GNU sed):
sed -r 's/$/,0/;s/^(www,/something else/,aes)..$/\1,1/;s/^(old,/something else/,ese)..$/\1/' file

Exactly as you described.


text:
Q: How to get JSON from php file using get()? Below is the code from where I am trying to fetch JSON from data.php file. What is the mistake I am making?
I am using XAMPP here to fetch the data. The path is correct. I also tried using an absolute path, but no luck.
Opening the absolute path in the browser fetches the array of data I am trying to echo here.

//Get data, and render chart
$.get("/web1/chart/data.php", function(data){
  //Get data
  var parsedData = ParseData(data);
  //Render chart
  InitChart(parsedData);
});

A: In javascript, you no where mentioned the data type is JSON, Please try to use $.getJSON( instead of $.get
Otherwise specify the data type as JSON in your get request.
$.get("/web1/chart/data.php", function( data ) {
  alert(JSON.stringify(data));
}, "json" );


text:
Q: Create Package in Bower Using bitbucket repository I am trying to register a package using bower register <name> https://git@bitbucket.org.. but bower is not creating a new package and throwing error as it is not a valid url and URl has to start with git://. But in bitbucket they have given Url with https:// and git@bitbucket.org.
I have kept trying with https:// for registering the package but still problem persits. It is not allowing to register the package inside the bower.
So I need some help on creating package in bower with bitbucket repository so i hope someone would have done it. Thanks for your help!

A: try to config  git global and try
 git config --global url."https://".insteadOf git://

 bower register <name>


text:
Q: RX events produced no more often than In my win forms application I get data from web service periodically or on user request. It is required, that the web service is queried no more often than every 2 seconds, whereas the timer period is 5 seconds. At the startup the app should also get the data immediately.
            IObservable<Timestamped<long>> timerObservable = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(5))
                                                                    .Timestamp();
        IObservable<Timestamped<long>> buttonObservable = Observable.FromEvent(handler => button1.Click += handler, handler => button1.Click -= handler)
                                                                    .Select(ev => 0L)
                                                                    .Timestamp();

        _subscription = timerObservable.Merge(buttonObservable)/*some code probably should be here*/
                                        .Subscribe(l => Debug.WriteLine("send request to web service received at: " + DateTime.Now.TimeOfDay));

I can't achieve that with throttle, because it always delays sending the request. I tried also bufferWithTime like this:
.BufferWithTime(TimeSpan.FromSeconds(2))
.Where(l => l.Count > 0)

but it delays the startup. Any solution to that? I use RX 1.0 as the application is .NET 3.5 based.


text:
Q: SonarQube analysis is failing after upgrade from 6.2 to 6.3.1 After upgrading SonarQube from 6.2 to 6.3.1 the analysis is failing with this error:
10:31:45.361 ERROR: Invalid value of sonar.sources for .....:F97737D2-1926-4521-A9F0-4093946864AA
10:31:45.363 INFO: ------------------------------------------------------------------------
10:31:45.363 INFO: EXECUTION FAILURE
10:31:45.363 INFO: ------------------------------------------------------------------------
10:31:45.363 INFO: Total time: 6.466s
10:31:45.418 INFO: Final Memory: 50M/285M
10:31:45.418 INFO: ------------------------------------------------------------------------
10:31:45.418 ERROR: Error during SonarQube Scanner execution
java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.scan.ProjectLock
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:70)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
at org.sonar.core.platform.ComponentContainer.getComponentByType(ComponentContainer.java:273)
at org.sonar.scanner.scan.ProjectScanContainer.doBeforeStart(ProjectScanContainer.java:112)
at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:141)
at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
at org.sonar.scanner.task.ScanTask.execute(ScanTask.java:47)
at org.sonar.scanner.task.TaskContainer.doAfterStart(TaskContainer.java:86)
at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
at org.sonar.scanner.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:118)
at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:117)
at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
at com.sun.proxy.$Proxy0.execute(Unknown Source)
at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis(EmbeddedScanner.java:151)
at org.sonarsource.scanner.cli.Main.runAnalysis(Main.java:123)
at org.sonarsource.scanner.cli.Main.execute(Main.java:77)
at org.sonarsource.scanner.cli.Main.main(Main.java:61)
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.api.batch.bootstrap.ProjectReactor
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:70)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:68)
... 23 more
Caused by: The folder 'C:\TFSBuildAgent\_work\5\s\....\Q_SAMPLE' does not exist for '.....:F97737D2-1926-4521-A9F0-4093946864AA' (base directory = C:\TFSBuildAgent\_work\5\s\.....)
10:31:45.422 ERROR:
10:31:45.422 ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.

I'm using the following configuration:

*

*SonarQube server v6.3.1

*SonarQube Scanner for MsBuild v2.1.0 (task
for TFS build)

*Oracle Database 12c

I checked the folder that is reported as not existing in the log (..Q_SAMPLE) and I found that it is not actually a folder but an XML file called Q_SAMPLE$0.xml. My suspect is that the scanner is interpreting the file name as a folder because of the character '$' in the file name, even if this is a valid Windows file name.

A: You are facing a bug that we are about to fix: SONARMSBRU-322.


text:
Q: Restrict SSH server tunneling port I have a SSH server running OpenSSH. I want to use it to setup a SOCKS server so that my friends in China can use it to access websites such as twitter. I want to enforce two restrictions: 1. no shell access, 2. only port 80 and 443 allowed.
My question is, how to enforce the second restriction? I tried to put the following line in /home/tunuser/.ssh/authorized_keys:
permitopen=":80",permitopen=":443",no-pty ...
I use ssh -D option, and the browser used SOCKS proxy. The ssh client logged in successfully, but my web browser can't establish a tunnel. The error message on the ssh server says the tunnel is not allowed.
After I removed the two "permitopen" options, my browser can successful browse.
Does openssh support "restrict only port, allow any host"?

A: Sorry it is not possible to use wildcard in hostnames
No pattern matching is performed on the specified hostnames,
they must be literal domains or addresses.

Man Page for permitopen
permitopen="host:port"
         Limit local ``ssh -L'' port forwarding such that it may only connect
to the specified host and port.  IPv6 addresses can be specified by enclosing
the address in square brackets.  Multiple permitopen options may be applied
separated by commas.  No pattern matching is performed on the specified
hostnames, they must be literal domains or addresses.  A port specification
of * matches any port.