text:
Q: need to make perl script use https I need to make this monitoring script use https and port 443 instead of port 80. The script logs into a server to see how many "port" resources are in use. These are not network ports in the usual sense. They are VOIP port resources.
Anyway the script needs to use LWP::UserAgent in ssl mode . . . or something.
    use strict;
    use Getopt::Long;
    use LWP::UserAgent;
    use HTTP::Request::Common qw(GET POST);
    use XML::Simple;
    use Data::Dumper;
    use Sys::Hostname;
    Getopt::Long::Configure('bundling');

    my ( $oHelp, $oHost, $oUser, $oPw, $oAddress, $oPort, $oWarn, $oCrit );

    my @warn = ( -1, -1 );
    my @crit = ( -1, -1 );
    my $state    = 'OK';
    my $output   = '';
    my $perfdata = '';
    my $percentage;
    my @tmp;
    my $chr1;
    my $chr2;

    my $userAgent;
    my $token;
    my $uToken;
# Bridge refers to the telephony server itself.
    my $bridgeIp   = '';
    my $bridgeUser = '';
    my $bridgePw   = '';
    my $hostName   = hostname;
    my $bridgePort = '80';
# I tried changing the above 80 to 443 but it did not help.
    my $bridgeUrl  = '';

    # Exit-Status-Array
    my %ERRORS = ( 'UNKNOWN', '-1', 'OK', '0', 'WARNING', '1', 'CRITICAL', '2' );

    # Parameter handling ###########################################################

    GetOptions(
        "H|host:s"    => \$oHost,
        "U|user:s"    => \$oUser,
        "P|pw:s"      => \$oPw,
        "A|address:s" => \$oAddress,
        "w|warn:s"    => \$oWarn,
        "c|crit:s"    => \$oCrit,
        "p|port:i"    => \$oPort,
        "h|help"      => \$oHelp
    );

    if ( $oHelp || !$oUser || !$oHost || !$oPw || !$oAddress ) {
        print <<EOU;
    Usage: $0 -H <FQDN/IP: string> -A <URL/Address: string> -U <Username: string>
    -P <Password: string> [-p <Port: integer>] [-w <audio ports warn: integer>,<video ports warn: integer>]
    [-c <audio ports warn: integer>,<video ports warn: integer>]

    Options:

    -H --host STRING or IPADDRESS
        FQDN or IP-Address of the bridge
    -A --address STRING
        Address to the XML API (e.g. http://<hostname>/Receiver.asp)
    -U --user STRING
        User name on the bridge
    -P --pw STRING
        Password of the account on the bridge
    -p --port INTEGER
        TCP port the API listens on the bridge
    -w --warn INT.INT or INT%,INT%
        Warning thresholds. Give maximum number or percentage of audio/video ports to be
        occupied before warning state occurs.

        Example:
            A value of 50,25 would warn on 51 occupied audio- and/or 26 occupied
            A value of 75%,85% would warn if 76% of the total audio- and/or 86% of the total
            video ports are in use.
    -c --crit INT.INT or INT%,INT%
        Critical thresholds. Give maximum number of audio/video ports to be
        occupied before critical state occurs.

        Example:
            A value of 60,30 would alert on 61 occupied audio- and/or 31 occupied
            video ports.
            A value of 85%,95% would alert if 86% of the total audio- and/or 96% of the total
            video ports are in use.

    EOU
        exit( $ERRORS{'UNKNOWN'} );
    }

    $bridgeIp   = $oHost;
    $bridgeUrl  = $oAddress;
    $bridgeUser = $oUser;
    $bridgePw   = $oPw;

    if ($oPort) {
        $bridgePort = $oPort;
    }

    if (substr($oWarn, length($oWarn) -1, 1) =~ /\%/) {
        $percentage = "1";
        @tmp = split( ',', $oWarn);
        $chr1 = chop($tmp[0]);
        $chr2 = chop($tmp[1]);
        @warn = @tmp;
    }
    else {
        @warn = split( ',', $oWarn );
    }

    if (substr($oCrit, length($oCrit) -1, 1) =~ /\%/) {
        $percentage = "1";
        @tmp = split( ',', $oCrit);
        $chr1 = chop($tmp[0]);
        $chr2 = chop($tmp[1]);
        @crit = @tmp;
    }
    else {
        @crit = split( ',', $oCrit );
    }

    #if ($oWarn) {
    #    @warn = split( ',', $oWarn );
    #}
    #if ($oCrit) {
    #    @crit = split( ',', $oCrit );
    #}

    # Script start #################################################################

    connect_bridge() if !$userAgent;

    my $request =
        '<TRANS_RSRC_REPORT><TRANS_COMMON_PARAMS><MCU_TOKEN>'
      . $token
      . '</MCU_TOKEN>'
      . '<MCU_USER_TOKEN>'
      . $uToken
      . '</MCU_USER_TOKEN><MESSAGE_ID>0</MESSAGE_ID>'
      . '</TRANS_COMMON_PARAMS><ACTION><GET_CARMEL_REPORT/></ACTION></TRANS_RSRC_REPORT>';

    my $responseXml = http_post( $bridgeUrl, $request );
    my $oXml = XMLin($responseXml, ForceArray=>['RSRC_REPORT_RMX']);

    #print( $responseXml . "\n" );
    # DEBUG: print Dumper($oXml);
    #print Dumper($oXml);

    my $audioPorts;
    my $videoPorts;
    my $audioPortsHD;
    my $videoPortsHD;

    foreach my $report (
        @{
            $oXml->{'ACTION'}->{'GET_CARMEL_REPORT'}->{'RSRC_REPORT_RMX_LIST'}
              ->{'RSRC_REPORT_RMX'}
        }
      )
    {
        if ( $report->{'RSRC_REPORT_ITEM'} eq 'audio' ) {

            # Possible options:
            #$report->{'RSRC_REPORT_ITEM'}->{'RESERVED'}
            #$report->{'RSRC_REPORT_ITEM'}->{'OCCUPIED'}
            #$report->{'RSRC_REPORT_ITEM'}->{'TOTAL'}
            #$report->{'RSRC_REPORT_ITEM'}->{'FREE'}

            $audioPorts = $report;
        }
        elsif ( $report->{'RSRC_REPORT_ITEM'} eq 'video' ) {
            $videoPorts = $report;
        }
    }

    my $videoTypeHD;

    foreach my $reportHD (
        @{
            $oXml->{'ACTION'}->{'GET_CARMEL_REPORT'}->{'RSRC_REPORT_RMX_LIST_HD'}
              ->{'RSRC_REPORT_RMX'}
        }
      )
    {
        if ( $reportHD->{'RSRC_REPORT_ITEM'} eq 'audio' ) {

            # Possible options:
            #$report->{'RSRC_REPORT_ITEM'}->{'RESERVED'}
            #$report->{'RSRC_REPORT_ITEM'}->{'OCCUPIED'}
            #$report->{'RSRC_REPORT_ITEM'}->{'TOTAL'}
            #$report->{'RSRC_REPORT_ITEM'}->{'FREE'}

            $audioPortsHD = $reportHD;
        }
        elsif ( $reportHD->{'RSRC_REPORT_ITEM'} eq 'HD1080p60_video' ) {
            $videoPortsHD = $reportHD;
        }
        elsif ( $reportHD->{'RSRC_REPORT_ITEM'} eq 'HD1080p30_video' ) {
            $videoPortsHD = $reportHD;
        }
        elsif ( $reportHD->{'RSRC_REPORT_ITEM'} eq 'HD720p30_video' ) {
            $videoPortsHD = $reportHD;
        }
    }

    # Audio thresholds

    if ( $audioPorts ) {
        if ( $percentage ) {
            if ( $audioPorts->{'TOTAL'} != 0 ) {
                if ( $warn[0] != -1 && (( $audioPorts->{'OCCUPIED'} / $audioPorts->{'TOTAL'} ) * 100) > $warn[0] ) {
                    $state = 'WARNING';
                }
            }
        } elsif ( $warn[0] != -1 && $audioPorts->{'OCCUPIED'} > $warn[0] ) {
            $state = 'WARNING';
        }

        if ( $percentage ) {
            if ( $audioPorts->{'TOTAL'} != 0 ) {
                if ( $crit[0] != -1 && (( $audioPorts->{'OCCUPIED'} / $audioPorts->{'TOTAL'} ) * 100) > $crit[0] ) {
                    $state = 'WARNING';
                }
            }
        } elsif ( $crit[0] != -1 && $audioPorts->{'OCCUPIED'} > $crit[0] ) {
            $state = 'CRITICAL';
        }
    }

    # Audio HD Thresholds

    if ( $audioPortsHD ) {
        if ( $percentage ) {
            if ( $audioPortsHD->{'TOTAL'} != 0 ) {
                if ( $warn[0] != -1 && (( $audioPortsHD->{'OCCUPIED'} / $audioPortsHD->{'TOTAL'} ) * 100) > $warn[0] ) {
                    $state = 'WARNING';
                }
            }
        } elsif ( $warn[0] != -1 && $audioPortsHD->{'OCCUPIED'} > $warn[0] ) {
            $state = 'WARNING';
        }

        if ( $percentage ) {
            if ( $audioPortsHD->{'TOTAL'} != 0 ) {
                if ( $crit[0] != -1 && (( $audioPortsHD->{'OCCUPIED'} / $audioPortsHD->{'TOTAL'} ) * 100) > $crit[0] ) {
                    $state = 'WARNING';
                }
            }
        } elsif ( $crit[0] != -1 && $audioPortsHD->{'OCCUPIED'} > $crit[0] ) {
            $state = 'CRITICAL';
        }
    }

    # Video tresholds
    if ( $percentage ) {
        if ( $warn[0] != -1 && (( $videoPorts->{'OCCUPIED'} / $videoPorts->{'TOTAL'} ) * 100) > $warn[0] ) {
            $state = 'WARNING';
        }
    } elsif ( $warn[1] != -1 && $videoPorts->{'OCCUPIED'} > $warn[1] ) {
        $state = 'WARNING';
    }
    if ( $percentage ) {
        if ( $crit[0] != -1 && (( $videoPorts->{'OCCUPIED'} / $videoPorts->{'TOTAL'} ) * 100) > $crit[0] ) {
            $state = 'CRITICAL';
        }
    } elsif ( $crit[1] != -1 && $videoPorts->{'OCCUPIED'} > $crit[1] ) {
        $state = 'CRITICAL';
    }

    # HD Video tresholds
    if ( $percentage ) {
        if ( $warn[0] != -1 && (( $videoPortsHD->{'OCCUPIED'} / $videoPortsHD->{'TOTAL'} ) * 100) > $warn[0] ) {
            $state = 'WARNING';
        }
    } elsif ( $warn[1] != -1 && $videoPortsHD->{'OCCUPIED'} > $warn[1] ) {
        $state = 'WARNING';
    }
    if ( $percentage ) {
        if ( $crit[0] != -1 && (( $videoPortsHD->{'OCCUPIED'} / $videoPortsHD->{'TOTAL'} ) * 100) > $crit[0] ) {
            $state = 'CRITICAL';
        }
    } elsif ( $crit[1] != -1 && $videoPortsHD->{'OCCUPIED'} > $crit[1] ) {
        $state = 'CRITICAL';
    }

    if ( $audioPorts ) {
        $output =
            $state
          . ': Audio in use: '
          . $audioPorts->{'OCCUPIED'} . '/'
          . $audioPorts->{'TOTAL'} . 'SD, '
          . $audioPortsHD->{'OCCUPIED'} . '/'
          . $audioPortsHD->{'TOTAL'} . 'HD, '
          . ' Video in use: '
          . $videoPorts->{'OCCUPIED'} . '/'
          . $videoPorts->{'TOTAL'} . 'SD, '
          . $videoPortsHD->{'OCCUPIED'} . '/'
          . $videoPortsHD->{'TOTAL'} . 'HD';

        $perfdata =
            'audio='
          . $warn[0] . ';'
          . $crit[0] . ';'
          . $audioPorts->{'OCCUPIED'} . ';'
          . $audioPorts->{'TOTAL'} . ';'
          . $audioPortsHD->{'OCCUPIED'} . ';'
          . $audioPortsHD->{'TOTAL'}
          . ' video='
          . $warn[1] . ';'
          . $crit[1] . ';'
          . $videoPorts->{'OCCUPIED'} . ';'
          . $videoPorts->{'TOTAL'} . ';'
          . $videoPortsHD->{'OCCUPIED'} . ';'
          . $videoPortsHD->{'TOTAL'};
    } else {
        $output =
            $state
          . ': Audio in use: 0/0SD, 0/0HD, '
          . ' Video in use: '
          . $videoPorts->{'OCCUPIED'} . '/'
          . $videoPorts->{'TOTAL'} . 'SD, '
          . $videoPortsHD->{'OCCUPIED'} . '/'
          . $videoPortsHD->{'TOTAL'} . 'HD';

        $perfdata =
            'audio='
          . $warn[0] . ';'
          . $crit[0] . ';0;0;0;0'
          . ' video='
          . $warn[1] . ';'
          . $crit[1] . ';'
          . $videoPorts->{'OCCUPIED'} . ';'
          . $videoPorts->{'TOTAL'} . ';'
          . $videoPortsHD->{'OCCUPIED'} . ';'
          . $videoPortsHD->{'TOTAL'};
    }

    print( $output. ' | ' . $perfdata . "\n" );
    exit( $ERRORS{$state} );

    # Subs #########################################################################

    sub login_bridge {
        my $request =
            '<TRANS_MCU><TRANS_COMMON_PARAMS><MCU_TOKEN>-1</MCU_TOKEN>'
          . '<MCU_USER_TOKEN>-1</MCU_USER_TOKEN></TRANS_COMMON_PARAMS><ACTION><LOGIN>'
          . '<MCU_IP><IP>'
          . $bridgeIp . '</IP>'
          . '<LISTEN_PORT>'
          . $bridgePort
          . '</LISTEN_PORT>'
          . '</MCU_IP><USER_NAME>'
          . $bridgeUser
          . '</USER_NAME>'
          . '<PASSWORD>'
          . $bridgePw
          . '</PASSWORD>'
          . '<STATION_NAME>'
          . $hostName
          . '</STATION_NAME>'
          . '</LOGIN></ACTION></TRANS_MCU>';

        my $responseXml = http_post( $bridgeUrl, $request );
        my $xml = XMLin($responseXml);

        # DEBUG: print Dumper($xml);

        my $token  = 0;
        my $uToken = 0;
        if ( $xml->{'RETURN_STATUS'}->{'ID'} == 0 ) {
            $token  = $xml->{'ACTION'}->{'LOGIN'}->{'MCU_TOKEN'};
            $uToken = $xml->{'ACTION'}->{'LOGIN'}->{'MCU_USER_TOKEN'};
        }

        return ( $token, $uToken );
    }

    sub connect_bridge {
        $userAgent = LWP::UserAgent->new( agent => 'VCMgmtLib', keep_alive => 1 );

        ( $token, $uToken ) = login_bridge();

        if ( $token == 0 || $uToken == 0 ) {

            # Login failed
            print("UNKNOWN: Login failed!\n");
            exit( $ERRORS{'UNKNOWN'} );
        }
    }

    sub http_post {
        my ( $url, $content ) = @_;

        my $req = POST $bridgeUrl,
          Content_Type => 'application/x-www-form-urlencoded',
          Content      => $content;

        my $response = $userAgent->request($req);

        print $response->error_as_HTML unless $response->is_success;

        return $response->content;
    }

So I was thinking maybe I could change the stanza beginning with sub connect_bridge { but I'm getting nowhere.
Here's what I was trying:
sub connect_bridge {
    $userAgent = LWP::UserAgent->new( agent => 'VCMgmtLib', keep_alive => 1 );
    ssl_opts => {
        SSL_ca_path     => '/etc/ssl/certs',
        verify_hostname => 0,
    }

    if ( $token == 0 || $uToken == 0 ) {
    }
}

but that blows up the script.
syntax error at /usr/lib64/nagios/plugins/check_rmx_ports_ssl.pl line 385, near ") {"
syntax error at /usr/lib64/nagios/plugins/check_rmx_ports_ssl.pl line 387, near "}"
Can't use global @_ in "my" at /usr/lib64/nagios/plugins/check_rmx_ports_ssl.pl line 390, near "= @_"
Global symbol "$content" requires explicit package name at /usr/lib64/nagios/plugins/check_rmx_ports_ssl.pl line 394.
syntax error at /usr/lib64/nagios/plugins/check_rmx_ports_ssl.pl line 401, near "}"
Execution of /usr/lib64/nagios/plugins/check_rmx_ports_ssl.pl aborted due to compilation errors.

A: Correct syntax:
require LWP::Protocol::https;
# Fail at compile time if dependencies are not met.
# This belongs near the `use` statements at the top.

...

$userAgent = LWP::UserAgent->new(
    agent => 'VCMgmtLib',
    keep_alive => 1,
    ssl_opts => {
        SSL_ca_path     => '/etc/ssl/certs',
        verify_hostname => 0,
    }
);

See LWP::UserAgent#ssl_opts.
Related: How to ignore 'Certificate Verify Failed' error in perl?


text:
Q: query doesn't return expected results This query doesn't return the expected results:
 select users.username,firstname,lastname,nickname,address,mobile,email,gender
 from users
 where
   username = (select userid from friends where friendid = 'ahmedhosni84')  OR
   (select friendid from friends where userid = 'ahmedhosni84');

I want to get all the information about the friends to a specified user name and get out only the first subquery and i want to get out the both sub queries

A: You can't do queries like (and get the desired result)
username = 'X' or 'Y'

You either have to do
username = 'X' OR username = 'Y'

Or
username IN ('X', 'Y')

A: I think the syntax you're looking for is:
select users.username,firstname,lastname,nickname,address,mobile,email,gender
 from users
 where
 username IN (select userid from friends where friendid = 'ahmedhosni84')
 or
 username IN (select friendid from friends where userid = 'ahmedhosni84');

Edit: Using "IN" as these return more than one result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In Oracle what is the fastest way to limit the characters in a string? I have quite a number of text fields I need to deal with. In order to process them the first thing I need to do is to normalize the set of characters I deal with. I need my output string to contain the following;
A-Z, 0-9 and space and I want all lower case converted to upper case.
So I use the following in pl/sql;
X := UPPER(TRIM(REGEXP_REPLACE
(REGEXP_REPLACE(X, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));

This is rather slow. What would be faster?

A: You can try this approach, which looks to be much faster based on some (very) loose tests.  Its a function that's compiled natively:
CREATE OR REPLACE function clean_string(
    in_string    in varchar2)
 return varchar2 AS
   out_string varchar2(4000) := '';
   in_length number;
   cnt number := 0;
   in_char char(1);
   out_char char(1);
   dec_char number;
   prev_space boolean := false;
begin
   --dbms_output.put_line('In string: ' || in_string);
   in_length := LENGTH(in_string);
   while cnt < in_length
   LOOP
     cnt := cnt + 1;
     in_char := substr(in_string, cnt, 1);
     dec_char := ascii(in_char);
     -- blank out non alphanumerics
     IF (
       (dec_char >= 48 AND dec_char <= 57) OR
       (dec_char >= 65 AND dec_char <= 90) OR
       (dec_char >= 97 AND dec_char <= 122)
       ) THEN
         --keep it
         out_char := in_char;
     ELSE
       out_char := ' ';
     END IF;

     IF (NOT(prev_space AND out_char = ' ')) THEN
       out_string := out_string || out_char;
     END IF;

     <<endloop>>
     IF (out_char = ' ') THEN
       prev_space := true;
     ELSE
       prev_space := false;
     END IF;

   END LOOP;
   return trim(upper(out_string));
end;

ALTER SESSION SET PLSQL_CODE_TYPE=NATIVE;
ALTER function clean_string COMPILE;

And to test, I pulled 5 million rows from a table and cleaned some strings:
set serveroutput on
declare
    cursor sel_cur1 is
    select name, clean_string(name) as cln_name,
        address1, clean_string(address1) as cln_addr1,
        address2, clean_string(address2) as cln_addr2,
        city, clean_string(city) as cln_city,
        state, clean_string(state) as cln_state,
        postalcode, clean_string(postalcode) as cln_zip
    from my_table
    where rownum <= 5000000;

    cursor sel_cur2 is
    select name,
        address1,
        address2,
        city,
        state,
        postalcode
    from my_table
    where rownum <= 5000000;

    l_cnt integer := 0;
    l_cln_name varchar2(100);
    l_cln_addr1 varchar2(100);
    l_cln_addr2 varchar2(100);
    l_cln_city varchar2(100);
    l_cln_state varchar2(100);
    l_cln_zip varchar2(100);

    l_interval interval day to second(4);
    l_start timestamp;
    l_end timestamp;
begin
   l_start := systimestamp;
   for rec in sel_cur2
   loop
         l_cnt := l_cnt + 1;
         l_cln_name := clean_string(rec.name);
         l_cln_addr1 := clean_string(rec.address1);
         l_cln_addr2 := clean_string(rec.address2);
         l_cln_city := clean_string(rec.city);
         l_cln_state := clean_string(rec.state);
         l_cln_zip := clean_string(rec.postalcode);
   end loop;
    l_end := systimestamp;
    l_interval := l_end - l_start;
    dbms_output.put_line('Procedural approach timing: ' || l_interval);
   -------------------------------------------------
   l_cnt := 0;
   l_start := systimestamp;
   for rec in sel_cur1
   loop
         -- cleaning already done in SQL
         l_cnt := l_cnt + 1;
   end loop;
   l_end := systimestamp;
   l_interval := l_end - l_start;
   dbms_output.put_line('SQL approach timing: ' || l_interval);

   -------------------------------------------------
   l_cnt := 0;
   l_start := systimestamp;
   for rec in sel_cur2
   loop
         l_cnt := l_cnt + 1;
         l_cln_name := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(rec.name, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
         l_cln_addr1 := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(rec.address1, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
         l_cln_addr2 := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(rec.address2, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
         l_cln_city := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(rec.city, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
         l_cln_state := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(rec.state, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
         l_cln_zip := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(rec.postalcode, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
   end loop;
   l_end := systimestamp;
   l_interval := l_end - l_start;
   dbms_output.put_line('Existing approach timing: ' || l_interval);
end;

And the output was:
Procedural approach timing: +00 00:02:04.0320
SQL approach timing: +00 00:02:49.4326
Existing approach timing: +00 00:05:50.1607

Also, the native compilation seems to only help a procedural approach to the processing (rather than calling the function from a SQL query), but appears to be much faster than the regexp_replace solution.  Hope that helps.

A: First, let me say that I am not really answering my own question, but I am accepting tbone's answer. The reason for providing this answer, is the comments don't let me post what I really want.
I created a function almost identical to tbone's with a couple of tweaks, got rid of the UPPER by changing how I handle the lower case range of characters, and changed numbers to binary_integers.
  FUNCTION CLEAN_STRING(IN_STRING in VARCHAR2) RETURN VARCHAR2
  AS
    OUT_STRING VARCHAR2(32767) := '';
    IN_LENGTH BINARY_INTEGER;
    CNT BINARY_INTEGER := 0;
    IN_CHAR CHAR(1);
    OUT_CHAR CHAR(1);
    DEC_CHAR BINARY_INTEGER;
    PREV_SPACE BOOLEAN := FALSE;
  BEGIN
    IN_LENGTH := LENGTH(IN_STRING);
    WHILE CNT < IN_LENGTH
    LOOP
      CNT := CNT + 1;
      IN_CHAR := SUBSTR(IN_STRING, CNT, 1);
      DEC_CHAR := ASCII(IN_CHAR);
      -- blank out non alphanumerics
      IF ((DEC_CHAR >= 48 AND DEC_CHAR <= 57) OR
         (DEC_CHAR >= 65 AND DEC_CHAR <= 90))
      THEN
      --keep it
      OUT_CHAR := IN_CHAR;
      ELSE
        IF (DEC_CHAR >= 97 AND DEC_CHAR <= 122)
        THEN
          OUT_CHAR := CHR(DEC_CHAR - 32);
        ELSE
         OUT_CHAR := ' ';
        END IF;
      END IF;

      IF (NOT(PREV_SPACE AND OUT_CHAR = ' '))
      THEN
       OUT_STRING := OUT_STRING || OUT_CHAR;
      END IF;

      <<endloop>>
      IF (OUT_CHAR = ' ') THEN
       PREV_SPACE := TRUE;
      ELSE
       PREV_SPACE := FALSE;
      END IF;

    END LOOP;
    RETURN TRIM(OUT_STRING);
  END CLEAN_STRING;

I then created a simple test rig like tbone did, but I tested the three different routines against each other. First I verify that they all return the same results and then time each routine. Here is the test rig;
set serveroutput on
DECLARE
  CURSOR PATHMAST_CURS
  IS
    SELECT PATHMAST_TEXT_DIAGNOSIS FROM PATHMAST WHERE ROWNUM < 100000;
  DUMMY CLOB;
  DUMMY_1 CLOB;
  DUMMY_2 CLOB;
  l_interval interval day to second(4);
  l_start timestamp;
  l_end timestamp;
  diff_count_1 binary_integer := 0;
  diff_count_2 binary_integer := 0;
BEGIN

  FOR PATH_REC IN PATHMAST_CURS
  LOOP
    DUMMY := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(NVL(PATH_REC.PATHMAST_TEXT_DIAGNOSIS,' '), '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
    DUMMY_1 := pathmast_utility_3.CLEAN_STRING(NVL(PATH_REC.PATHMAST_TEXT_DIAGNOSIS,' '));
    DUMMY_2 := regexp_replace(trim(translate(NVL(PATH_REC.PATHMAST_TEXT_DIAGNOSIS,' '),'abcdefghijklmnopqrstuvwxyz`~!@#$%^&*()''_+-={[}]|/\":;,.<>?µ'±€'||chr(9),'ABCDEFGHIJKLMNOPQRSTUVWXYZ                                     ')),'( )* ',' ');
    IF DUMMY_1 != DUMMY
    THEN
      diff_count_1 := diff_count_1 + 1;
    END IF;
    IF DUMMY_2 != DUMMY
    THEN
      diff_count_2 := diff_count_2 + 1;
      dbms_output.put_line('Regexp: ' || DUMMY);
      dbms_output.put_line('Translate: ' || DUMMY_2);
    END IF;
  END LOOP;
  dbms_output.put_line('CLEAN_STRING differences: ' || diff_count_1);
  dbms_output.put_line('Translate differences: ' || diff_count_2);

  l_start := systimestamp;
  FOR PATH_REC IN PATHMAST_CURS
  LOOP
    DUMMY := UPPER(TRIM(REGEXP_REPLACE(REGEXP_REPLACE(PATH_REC.PATHMAST_TEXT_DIAGNOSIS, '[^0-9A-Za-z ]', ' '),'( )* ',' ')));
  END LOOP;
  l_end := systimestamp;
  l_interval := l_end - l_start;
  dbms_output.put_line('Regexp approach timing: ' || l_interval);
  -------------------------------------------------
  l_start := systimestamp;
  FOR PATH_REC IN PATHMAST_CURS
  LOOP
    DUMMY := pathmast_utility_3.CLEAN_STRING(PATH_REC.PATHMAST_TEXT_DIAGNOSIS);
  END LOOP;
  l_end := systimestamp;
  l_interval := l_end - l_start;
  dbms_output.put_line('CLEAN_STRING approach timing: ' || l_interval);
  -------------------------------------------------
  l_start := systimestamp;
  FOR PATH_REC IN PATHMAST_CURS
  LOOP
    DUMMY := regexp_replace(trim(translate(NVL(PATH_REC.PATHMAST_TEXT_DIAGNOSIS,' '),'abcdefghijklmnopqrstuvwxyz`~!@#$%^&*()''_+-={[}]|/\":;,.<>?µ'±€'||chr(9),'ABCDEFGHIJKLMNOPQRSTUVWXYZ                                     ')),'( )* ',' ');
  END LOOP;
  l_end := systimestamp;
  l_interval := l_end - l_start;
  dbms_output.put_line('TRANSLATE approach timing: ' || l_interval);
  -------------------------------------------------
END;

And here are the results;
anonymous block completed
CLEAN_STRING differences: 0
Translate differences: 0
Regexp approach timing: +00 00:00:52.9160
CLEAN_STRING approach timing: +00 00:00:05.5220
TRANSLATE approach timing: +00 00:00:13.4320

This is all without compiling native. So tbone is the big winner. Thank you tbone.
If for whatever reason you want/need to use the translate version, you should build the translate string programmatically in order to get all of the special characters.

A: Perhaps, you can use TRANSLATE instead of regex to remove special characters and convert lower case to upper case.
regexp_replace(
               trim(
                    translate(x,
                              'abcdefghijklmnopqrstuvwxyz`~!@#$%^&*()_+-={[}]|/\"'':;,.<>?',
                              'ABCDEFGHIJKLMNOPQRSTUVWXYZ                                '
                             )
                   ),
                   ' {2,}',
                   ' '
              )

Tried it on a table with 1000 rows and column with random characters from anywhere between 1 to 4000.
Resulted in around 35% less time.(Did not try in PLSQL).


text: Q: Как изменять скорость transition css или scss в зависимости от ширены элемента? Чем больше элемент тем медленнее анимация. Я использую React и scss. Варианты были разные функция calc(), transition-timing-function, даже через React пробовал. Если описывать проблему подробней то при наведении на кнопку ::after должен делать анимацию. Но В моем проекте кнопки разные и хотелось бы как-то оптимизировать. Чтобы оно автоматически определяло время анимации.


text:
Q: How to shift specific cells using Apache POI? My excel sheet contains different regions on the same sheet like:
region1:                region2:
John       2            A         1
John       1            B         2
Sue        1            C         3
Sue        2            D         4
Alice      5            E         5
Bob        1            F         6

I want to add new items into one of these regions without affecting the other regions.   I tried using rowShift() method but it is also deleting the complete rows. Is there any way that can shift the specific cells down and can insert rows into the specific regions like this:   In my given example I want to add one more row in region1 (also retaining all old rows) and it will become:
region1:                region2:
newval     newval       A         1
John       2            B         2
John       1            C         3
Sue        1            D         4
Sue        2            E         5
Alice      5            F         6
Bob        1

A: If the above issue still persisting, I can give you a method for the same.
public static void shiftCells(int startCellNo, int endCellNo, int shiftRowsBy, Sheet sheet){

    int lastRowNum = sheet.getLastRowNum();
    System.out.println(lastRowNum); //=7
    //      int rowNumAfterAdding = lastRowNum+shiftRowsBy;
    for(int rowNum=lastRowNum;rowNum>0;rowNum--){
        Row rowNew;
        if(sheet.getRow((int)rowNum+shiftRowsBy)==null){
            rowNew = sheet.createRow((int)rowNum+shiftRowsBy);
        }
        rowNew = sheet.getRow((int)rowNum+shiftRowsBy);
        Row rowOld = sheet.getRow(rowNum);
        System.out.println("RowNew is "+rowNum+" and Row Old is "+(int)(rowNum+shiftRowsBy));
        System.out.println("startCellNo = "+startCellNo+" endCellNo = "+endCellNo+" shiftRowBy = "+shiftRowsBy);
        for(int cellNo=startCellNo; cellNo<=endCellNo;cellNo++){
            rowNew.createCell(cellNo).setCellValue(rowOld.getCell(cellNo).getStringCellValue().toString());
            rowOld.getCell(cellNo).setCellValue("");
            System.out.println("working on " +cellNo);
        }
    }
}


text:
Q: React: Append component animations on local and redux state updates I am building a component that renders an animation on every local and redux state update. Local state is updated on a button click and it also makes an ajax request to a remote server to update that an user clicked the button. I update local state on every click like so:
 const [selfAnimations, setAnimations] = useState<AnimationRenders>(initialAnimationState);
const onButtonClickCallback = () => {
    makeRemoteAjaxCall();
    selfAnimations.localEventsCount += 1;
    selfAnimations.animationsToRender.push(Date.now);
    setAnimations(selfAnimations);
};

I update the data coming in from remote server like this:
    useEffect(() => {
        if (animationDataCount && animationDataCount > 0) {
            const {
                updatedLocalEventsCount,
                updatedAnimations,
            } = filterDedupedLocalEvents(selfAnimations, animationDataCount);
            setAnimations({
                localEventsCount: updatedLocalEventsCount,
                animationsToRender: updatedAnimations,
            });
        }
    }, [animationDataCount]);

I render a div with a component I created:

    <AnimationContainer numberOfAnimations={selfAnimations.animationsToRender.length} />

   <MyButton ... />

On client side, data is received on regular intervals. My AnimationContainer component can render any number of received animations. However, everytime a user clicks the button or client recieves remote data it updates the state and drops previous animations. Looking online I could delay the rerender with css but the behavior I need is to append to existing animations on state updates. Is there a mechanism that I could use for that behavior?

A: I misunderstood how react renders. React does not necessarily create a new child component and unmount the old component on props/state updates. In my case, instead of storing counts of what needed to be rendered, I need to store distinct keys for what needed to be rendered, because even if the AnimationContainer  component receives updates from props, if it only received counts, then it may not trigger rerenders because the count can be the same. I got around this by implementing the props of localEvents as an array of timestamps: number[]. By passing down timestamps to AnimationContainer and refactoring AnimationContainer to check props update and store into state of animations in middle of rendering and a queue of animations to render, I was able to create a component that can receive and continually renders animations based on events.


text:
Q: TextMate Bundle Document icons I am looking for these little document icons (not only for Python) inside of TextMate 2.

I looked in the Bundles folder of TextMate, but I couldn't find them. I really would like to use these icons as document icons in Finder.
Does anybody knows where they are located?
Fabian

A: https://github.com/textmate/textmate/blob/master/Frameworks/OakAppKit/icons/python.icns is the source of this icon.
Other icons are below, uncovered in the search.
TextMate.app/Contents/Resources/ is where textmate store's it's icons (version 1.5 and 2 both use the same folder).
/usr/local/Cellar/python/2.7.10_2/Python Launcher.app/Contents/Resources/PythonSource.icns is where some other Python icons come from. Note: your version is unlikely to match my version, so replace 2.7.10_2 with the version available on your system.


text:
Q: C# Bool operand usage I want to have the following results
A B =
T T T
F T F
T F F
F F F

I am using this clause to achieve it
A || B

but it does not provide correct results.
Am I using a wrong operand?

A: Allthough all other answers are correct, I'd like to point out that the operator you are asking for is neither || nor &&. The operator that actually does exactly what you are asking for is & (and the equivalent that you are mistakenly using would be |).
And, what is the difference? || and && are short circuiting operators. What does that mean? It means that whatever is on the right side of the operator is only evaluated if the left hand side is true. This does not happen with the non short circuit versions of the operators (the truly bolean logical and and or operators):
public bool True()
{
    Console.WriteLine("True called.");
    return true;
}

public bool False()
{
    Console.WriteLine("False called.");
    return false;
}

var b1 = False() && True(); //b1 will be false and "False called." will be
                            //printed on the console.

var b2 = False() & True();  //b2 will be false and "False called. True called."
                            //will be printed on the console.

A: You want an and, but you used an or.

A:
Am I using a wrong operand?

Yes you are.
You need the AND && operator which will be true only if all of the conditions are true.
You are using the OR || operator which will give you true even if one of the conditions are true.
Use the AND && operator instead of OR ||

A: Use && (which means 'and')
|| means 'or'


text:
Q: Asp page not running in firefox or chrome I have a classic asp page which is working on IE and safari but not in firefox or chrome.  Have a look at this url
Check it
My Asp Page code is

<TITLE>USER LOGIN</TITLE>

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">

      <%

' Check if User has previously rejected by the Server for invalid Log On
If Session("RequestLogOnSuccess_Delphi") = "NO" then
    Response.Write "
"
    Response.Write "
"
    Response.Write "YOUR LOG ON IS INVALID. PLEASE TRY AGAIN.	"
    Response.Write "
"
    Response.Write "
"
else
    Response.Write "

"
End if

    %>

<form method="post" action="../Request_WebProcess/Request_LogOn_Process.asp" name="Form1">

          <input name="txtUserID" type="text" class="v8blue" id="username" size="15">

          <input name="txtPassword" type="password" class="v8blue" id="password" size="15">

      SINGAPORE
        INTERNET PURCHASE

      (Please
        log in your user name and password )

      CLICK
        HERE IF YOU FORGET YOUR PASSWORD

</form>

A: Did you check the browser's console? This is the error that Chrome reports:
Uncaught TypeError: Property 'forms' of object #<HTMLDocument> is not a function

Change this line:
var field = document.forms("Form1").item("txtUserID");

to be:
var field = document.forms["Form1"]["txtUserID"];
// or
var field = document.forms.Form1.txtUserID;

Or I would probably do this:
var field = document.getElementById("username");

A: I have got the solution
Changed

To


text:
Q: android studio editor bug (cannot result symbol) Why sometimes android studio does not see external library even after adding dependencies in build.gradle? Dependecies are right, project synchronized with Gradle files.
P.S. Gradle complete building task  succesfully.


text:
Q: Proof of bases of fundamental subspaces Could anyone help me to prove the following theorems? Here SVD means singular value decomposition
i.e. $U$ is a $m\times m$ matrix with $\mathbf u_i=\frac{Av_i}{||Av_i||}$, V is $n\times n$ matrix with $v_i$ is the eigenvector of $A^TA$, and $\Sigma$ is kind of block matrix with left upper block a diagonal matrix with singular value of A and $0$ otherwise.

A: Sketch of the proof of the first claim:

*

*$V^\top$ is invertible so $\text{Col}(U\Sigma V^\top) = \text{Col}(U\Sigma)$

*$\Sigma$ is diagonal and the nonzero diagonal entries are the first $r$ diagonal entries. Thus $U\Sigma$ has columns $\sigma_1 u_1, \ldots, \sigma_r u_r$, and then the remaining $m-r$ columns are zero.


text:
Q: Looking for alternative result projection that works on mongodb 4.2.x As per my last question (Query document count by multiple ranges returning range start/end with matching element count), I built a query to check for count of documents in multiple, potentially overlapping date ranges.
The query works on MongoDB 4.4 but I need to run it on 4.2 as well.
On MongoDB 4.2, I get the following error:
Mongo Server error (MongoCommandException): Command failed with error 168 (InvalidPipelineOperator): 'Unrecognized expression '$first'' on server localhost:27017.

The full response is:
{
    "ok" : 0.0,
    "errmsg" : "Unrecognized expression '$first'",
    "code" : 168.0,
    "codeName" : "InvalidPipelineOperator"
}

How would you write the aggregation projection to achieve the same result structure.
Here is the complete code with data setup
db.createCollection("object_location_tracking");
db.getCollection("object_location_tracking").insertMany([
    {
        _id: "1",
        locationId: "locationA",
        objectId: "objectA",
        timestamp: ISODate("2020-01-01T00:00:00Z")
    },
    {
        _id: "2",
        locationId: "locationB",
        objectId: "objectA",
        timestamp: ISODate("2020-01-01T00:00:00Z")
    },
    {
        _id: "3",
        locationId: "locationA",
        objectId: "objectB",
        timestamp: ISODate("2019-01-01T00:00:00Z")
    },
    {
        _id: "4",
        locationId: "locationB",
        objectId: "objectB",
        timestamp: ISODate("2020-01-01T00:00:00Z")
    }
]);

db.getCollection("object_location_tracking").aggregate([
    {$facet: {
        "first_bucket_id": [
            {$match: {"objectId":"objectA",
                      "locationId":"locationA",
                      "timestamp": {$gte: new ISODate('2020-01-01'),
                                    $lt: new ISODate('2020-12-31')}
                     }},
            {$count: "N"}
        ],

        "second_bucket_id": [
            {$match: {"objectId":"objectA",
                      "locationId":"locationA",
                      "timestamp": {$gte: new ISODate('2020-01-01'),
                                    $lt: new ISODate('2022-12-31')}
                     }},
            {$count: "N"}
        ],

        "third_bucket_id": [
            {$match: {"objectId":"objectA",
                      "locationId":"locationB",
                      "timestamp": {$gte: new ISODate('2022-01-01'),
                                    $lt: new ISODate('2022-12-31')}
                     }},
            {$count: "N"}
        ]
    }},
    {
        $set: {
            first_bucket_id: { $first: "$first_bucket_id.N"},
            second_bucket_id: { $first: "$second_bucket_id.N"},
            third_bucket_id: { $first: "$third_bucket_id.N"}
        }
    }
    , {
        $project: {
            first_bucket_id: 1,
            second_bucket_id: 1,
            third_bucket_id: 1

        }
    }
]);

A: You are using the first array element, which as you can tell is a new operator added for version 4.4
Luckily for you this is quite easy to overcome, by just using $arrayElemAt, like so:
{
    $set: {
        first_bucket_id: {$arrayElemAt: ["$first_bucket_id.N", 0]},
        second_bucket_id: {$arrayElemAt: ["$second_bucket_id.N", 0]},
        third_bucket_id: {$arrayElemAt: ["$third_bucket_id.N", 0]}
    }
}


text:
Q: $\sum a_n$ converges $\iff$ $\sum f(a_n)$ converges For specific functions and $a_n >0$, we can say that $\sum a_n$ converges $\iff$ $\sum f(a_n)$ converges. I want to show this specifically for the case that $f(x)=sin(x)$. This is what I have thus far (which I admit is essentially nothing). Any direction would be welcome.
Proof:
$(\rightarrow)$ $\sum a_n$ converges. We know that:
(i) the partial sums of $a_n$ are bounded.
$(\leftarrow)$ $\sum f(a_n)$ converges. We know that:
...
This is not a duplicate of a previous question that I asked. Before, I asked for a proof of this concept (if it could be proved). This, I am asking for help with a direct application of the concept.

A: This is not true. For example, let $a_n=\pi$.

A: I will prove this in one direction in the case $f(x)=\sin(x)$ and $a_n\in\mathbb R$. Also, I will assume absolute convergence for the $a_n$ series.
Assume that $$\sum_{n=1}^\infty |a_n|<\infty.$$ We know that $|a_n|\geq|\sin(a_n)|$ for all $n$, so $$\sum_{n=1}^\infty|\sin(a_n)|\leq\sum_{n=1}^\infty|a_n|<\infty.$$
In general, $\sum |a_n|<\infty\Rightarrow\sum |f(a_n)|<\infty$ as long as $f$ is lipschitz and $f(0)=0$.
The converse is true if $f$ is Lipschitz and if $0$ is the only root of $f$.


text:
Q: Counting Number of Card Deck Orderings to fit Rules of Game I am investigating an interesting problem regarding a simple card game, and I ultimately want to calculate the probability that this game results in all the cards in a hand end up with the same value (they change based on the game rules).
In this game, all of the "cards in hand" of any number of players eventually converge to the same card after a certain number of iterations of the game. This game proceeds as follows:
1)
Each player randomly selects a card from a standard shuffled deck. These cards are known as the "cards in hand", or "hand cards". Once recorded, these cards are reinserted into the deck, which is subsequently reshuffled.
2)
A card is drawn from the top of the deck. If the suit of the drawn card matches the suit of a player's card in hand, the player then changes their recorded card in hand to that of the card subsequent the drawn card. For example, if a player's current card is a Jack of Spades, the drawn card is an Ace of Spades, and the next card in the deck is a Queen of Hearts, the player's card in hand changes to a Queen of Hearts. This process constitutes one iteration.
The card is not reinserted into the deck, and the deck is not reshuffled. Then, another iteration begins.
3)
At the end of the game, all of the recorded cards in hand should be the same.
In the version of the game I am investigating, I assume that there are three players, i.e. three "hand cards", and that they all pick cards of different suits. What I need help finding is the number of orderings of the deck (from which cards are drawn) so that at the end when all cards are draw, the three cards still have different suits (not necessarily the same ones). I was able to deduce, based on the game rules, that if the three cards have different suits in the hand, then they MUST have different suits at any point during the duration of this game. If this is to happen, then for every card draw, we can have:
a. the card drawn from the deck matches the suit of one of the hand cards, and the subsequent card drawn from the deck has the same suit as both - in this case the suits do not change in the hand
b. the card drawn from the deck matches the suit of one of the hand cards, and the subsequent drawn card from the deck is of the one suit that is NOT present in the hand (Spade, Heart, Club goes to Diamond, Heart, Club)
c. the card drawn from the deck does not match the suit of any of the hand cards, in which case nothing happens and the next card is drawn
I know this is a hard and lengthy question, and I will be grateful to whoever can help me figure it out.

A: Assuming my understanding of your statements is correct, the key thing to note here is that once your suit shows up in the draws, your card will change with every subsequent draw. If draw 1 is your suit, then your new card-in-hand is the card for the 2nd draw. but in that case, the 2nd draw is your suit as well, so your card switches to that of the 3rd draw and so on.
Since every suit occurs in the deck, as soon as the 4th suit appears in a draw, everybody is switching cards every time, and so they will always end with the final card in the deck.

If instead, you discard 2 cards with each turn - the first being the "draw", and the second being the new card-in-hand for all matching players, then things are a little more complicated, but not by much. The first time a draw of one suit comes with a card-in-hand from another suit, all players will from that point on be in only 3 suits. The players in the first suit will join those in the second. Even if players transfer back to that original suit, everyone in the transfering suit will do so, leaving that suit with no players. When a third suit comes up as card-in-hand for a different suit, then another suit will be lost, and all players will be in just 2 suits from then on. Eventually it is likely that one of the 2 suits will end up transferring to the other. After that, only one suit will remain. And if that suit ever shows up in the draw, everyone will end up with the same card.
Since each suit has 13 cards, it is not possible for them to show up paired only with a card-in-hand of the same suit. Therefore, at least one suit will be lost. However, it is possible to limit that loss to just one suit, so at the end of the game, there are players in each of the other three suits. For example,
The first three pairs could be:
$$\text{heart} \to \text{spade}\\
\text{heart} \to \text{club}\\
\text{heart}\to \text{diamond}$$
which removes an odd number of cards from each suit. If the remaining pairs of cards has the new card-in-hand from the same suit as the draw, only those players starting with a heart will move to another suit: spades. Spades, clubs, and diamonds will remain in those suits to the end. Though everybody in each suit will see their card-in-hand switch to the same value, there will still be 3 different card-in-hands at the end.


text:
Q: moving files from a subsubfolder to a folder x10000 times I have a lot of folders that need organizing that would take weeks to do by hand. I already know that the . trick will work, but then I will lose the already organized file structure. What I need is my main folder (let's call it C:\docs) that has hundreds of subfolders (folder a-j), have even more subfolders within the subfolders (which I am calling subsub folders) I don't want to lose the folder structure of folder a-j, but the folders within those folders need to be emptied to their respective subfolders.
DOCS
folder a
 sub folder 1
    file 1,2,3,4......
 sub folder 2
    file 5,6,7,8......
 sub folder 3
    file 9,10,11,12....
folder b
 sub folder 1
    file 1,2,3,4......
 sub folder 2
    file 5,6,7,8......
 sub folder 3
    file 9,10,11,12....

and so on.
INTO
DOCS
folder a
   file 1,2,3,4,5,6,7,8,9,10,11,12......
folder b
   file 1,2,3,4,5,6,7,8,9,10,11,12......

and so on.
Any help with this would be great. I can't even get the language right to google search my problem, because all I get is the - . trick, which again is fine but would take actual weeks to do with the number of folders that need this. Thanks in advance!

A: What I would do is to copy the structure with ROBOCOPY.EXE tool and save it somewhere like C:\Backup\
I would run a command DOS like this:
robocopy c:\docs*.* c:\backup\ /CREATE
This will copy only the structure of subdirectories.
type in a DOS box:
robocopy /?
to get all options


text:
Q: 'GameObject': no appropriate default constructor available I'm trying to create a game with GameObject being everything from tiles, player, enemy and walls. I'm trying to get my class Character (Parent to two more classes Player and Enemy) to the base class GameObject. I get the C2512 Error in the Character.cpp file when I'm trying to create the constructor for Characters. Can anyone point out what I could be doing wrong? Thanks in advance.
Characters.h
#ifndef CHARACTERS_H
#define CHARACTERS_H

#include <cstdlib>
#include <ctime>      /*cstdlib and ctime are used to help with the pseudo randomness for events*/
#include <cstdio>   /*allows remove function*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <array>
#include <string>
#include <vector>
#include "GameObject.h"

using namespace std;

class Character : public GameObject{
public:
    Character();
    ~Character();
    virtual void attack(vector<Character *>&characters) = 0;
    void set_values(string nam, int hp, int str, int mag) {
        name = nam;
        health = hp;
        strength = str;
        magic = mag;
    };
    string name;
    int health;
    int strength;
    int magic;

};

#endif

GameObject.h
#ifndef GAMEOBJECCT_H
#define GAMEOBJECT_H

#include "Direct3D.h"
#include "Mesh.h"
#include "InputController.h"

class GameObject {
protected:
    Vector3 m_position;
    float m_rotX, m_rotY, m_rotZ;
    float m_scaleX, m_scaleY, m_scaleZ; //Not really needed for A1.
    //Used for rendering
    Matrix m_world;
    Mesh* m_mesh;
    Texture* m_texture;
    Shader* m_shader;
    InputController* m_input; //Might have enemies who react to player input.

    float m_moveSpeed;
    float m_rotateSpeed;

public:
    //Constructor
    GameObject(Mesh* mesh, Shader* shader, InputController *input, Vector3 position, Texture* texture);
    ~GameObject();
    void Update(float timestep);
    void Render(Direct3D* renderer, Camera* cam);

Characters.cpp
#include "Characters.h"
#include <cstdlib>
#include <ctime>      /*cstdlib and ctime are used to help with the pseudo randomness for events*/
#include <cstdio>   /*allows remove function*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <array>
#include <string>
#include <vector>
using namespace std;

void Character::attack(vector<Character *>&characters) {};

Character::Character() {

};
Character::~Character() {};

A: Your GameObject should have a default constructor (constructor with no parameters).
Because in Character::Character(), compiler will generate a call to GameObject's default constructor.
If you don't implement any constructor for a class GameObject, compiler will generate an empty default constructor for it. But you have implemented a constructor for class GameObject, so compiler will not do it. You should provide a default constructor for it by yourself.

A: Character::Character() {};

is equivalent to
Character::Character() : GameObject() {};

Since GameObject does not have a default constructor, the compiler generates an error. Unless there are sensible default values for all the arguments used by the user defined constructor of GameObject, you should change Character to have a user defined constructor that accepts all the arguments that are needed to construct a GameObject.
Character(Mesh* mesh,
          Shader* shader,
          InputController *input,
          Vector3 position,
          Texture* texture);

and implement it as:
Character::Character(Mesh* mesh,
                     Shader* shader,
                     InputController *input,
                     Vector3 position,
                     Texture* texture) : GameObject(mesh, shader, input, position, texture) {}


text:
Q: How to apply the conditional formatting to multiple columns using excel macro I created a conditional formatting to change the color based on value compare for one cell, but I don't know how to apply this formatting for the whole column and even other columns? (do I have to use for loop to set the formatting for all the cells?)
'add conditionalFormating for one cell.
 Set rngCell = Cells(6, 7)
 Set objCF = rngCell.FormatConditions.Add _
            (Type:=xlExpression, _
            Formula1:="=" & rngCell.Address & " > " & rngCell.offset(, -3).Address)
'set formats for new CF

With objCF
    .Font.ColorIndex = 26
    .Interior.ColorIndex = 19
End With

Thanks in advance

A: Unfortunately, Excel 2007/2010 don't have as extensive a macro record function as earlier versions
If you are referencing other cells when applying conditional formatting, a good method is to apply it to one cell (which you know how to do), and then copy the formatting to the rest of the column; if you are filling down a column, this should not cause you to lose other cell formats you may wish to keep
So I would start your code with
rngCell.FormatConditions.Delete

Then once the format is added, you can simply use:
rngCell.Copy
rngOut.PasteSpecial xlPasteFormats

, where rngOut is defined as starting with rngCell and filling down to the last row in the table
To apply to other columns, you would probably need a different formula as there are different offsets. To minimise the required code, you could always manually add the full set of formats/conditional formats you want to a hidden row just above the table's headers. Then you can copy all of these to your table using code of the form...
Range("A1:J1").Copy
Range("A3:J100").PasteSpecial xlPasteFormats

...if we assume your header gets pushed down to row 2 when you add the formatted row in row 1
Although I have referred to cell addresses in the above example, I would always recommend referring to range names and using cells notation e.g. Range("A1") is Cells(1, 1). The use of range names to define columns in tables is covered in more detail in this expert Excel video. The benefits are immense...if your header row is defined with a range name, you can insert a new row above your table without having to re-write any code


text:
Q: Why can't I remove DOM element with jQuery? This is a piece of my code that should simply remove an element from the HTML DOM, but it won't for some reason...
...
clearError(fields['server_error'][fieldUniqueId], 'server_error');
...

function clearError($field, type){
    $("#" + getErrorLabelId($field, type)).remove();
}

function getErrorLabelId($field, type){
    return ValidatorInstance.ErrorLabelIdPrefix + "-" + $field.data(ValidatorInstance.uniqueIdKey) + "-" + type;
}

All the functions work and return with the values that they expected. For example if I change the line from $("#" + getErrorLabelId($field, type)).remove(); to $("#" + getErrorLabelId($field, type)).css('background.color', 'blue'); it perfectly sets the background-color. But it won't remove. Why is that?


text:
Q: The expected value of common neighbors on a random regular graph Given a random $d$-regular graph on $n$ nodes, what is the expected number of common neighbors between two nodes?
I don't know if it is as simple as just assuming that each neighbor of the first node has a $\frac{d}{n}$ probability of being a neighbor of the second, as the set of $d$-regular graphs on $n$ nodes is difficult to construct.

A: Yep, it is $\frac{d(d-1)}{n-1}$ in general. Fix a $d$-regular graph and average over the action of the permutation group on the vertices. We are interested in the event $S(x,y,z)=$"$x$ is connected to $y$ and $z$". If $E$ is the expected number of neighbors, then $\sum_{x,y,z}P(S(x,y,z))=n(n-1)E$, summing over $x$ first. On the other hand, if we sum over $y,z$ first, the same sum is evaluated as $nd(d-1)$.


text:
Q: What's wrong with iShares SP 500 ETF's Excel file? I am trying to parse iShares SP 500 ETF's Excel file, which looks like this:
<?xml version="1.0"?>
<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
<ss:Styles>
<ss:Style ss:ID="Default">
<ss:Alignment ss:Horizontal="Left"/>
</ss:Style>
...

It seems to be an old XLS Excel type file, but it is an XML file, yet xml.etree.ElementTree is complaining a lot.
I have tried:
import xml.etree.ElementTree as ET
tree = ET.parse(file_name)

and with encoding:
import xml.etree.ElementTree as ET
tree = ET.parse(file_name, parser=ET.XMLParser(recover=True))

import xml.etree.ElementTree as ET
tree = ET.parse(file_name, parser=ET.XMLParser(encoding='utf-8'))

error:
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 1

rb = xlrd.open_workbook(file_name, encoding_override='utf-8')
print(rb)

error:
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\xef\xbb\xbf\xef\xbb\xbf<?'

but none seems to work at all... could anyone guide me in the right direction?

A: Your "XML" file is not well-formed:

*

*It has two BOM characters before the XML declaration.
To remove (at least) one, see Convert UTF-8 with BOM to UTF-8 with no BOM in Python

*Remove the & or change it to & on line 43.
<ss:Data ss:Type="String">iShares Core S&P 500 ETF</ss:Data>
                                        ^

*Ditto for the & on line 117,188.
Without the above repairs, your file cannot be parsed as XML (because technically it isn't).
After the above repairs, you'll be able to parse it as XML, and Excel will be able to open it:

See also

*

*How to parse invalid (bad / not well-formed) XML?

*Error: The processing instruction target matching "[xX][mM][lL]" is not allowed


text:
Q: 302 Redirect in AWS Cloudfront I have a webstack that is currently serving both dynamic and static content. I want start serving the static content from AWS CloudFront without having to change all of the urls.
So I set up CloudFront to serve the static content from AWS S3 and the dynamic content from a custom url (current webstack). This worked however CloudFront was making the request to our webstack via a rewrite rule.
Is it possible for CloudFront to return a 302 redirect so that the request to my webstack would come from the users browser?
Unfortunately this is critical for our application to work properly.

A: I don't think it's possible, because CloudFront should follow 302 redirects and cache the result, rather than return the 302 redirect to the client.


text:
Q: Error in prediction in digit recognition using cnn I want to predict the digit is 5 or not from 0 to 9.I have used cmaterdb dataset.
For this task I have changed all the digit label 0 except 5 in the training and test dataset
new_train_label=np.copy(train_labels)
for i, label in enumerate(new_train_label):
     new_train_label[i] = 0 if (label == 5) else 1

new_test_label=np.copy(test_labels)
for i, label in enumerate(new_test_label):
     new_test_label[i] = 0 if (label == 5) else 1

#train up model using cnn

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils

model = Sequential()

model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Conv2D(15, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.02))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(train_examples, new_train_label, epochs=30)

val_loss, val_acc = model.evaluate(test_examples,new_test_label)
print(val_loss)
print(val_acc)

Although accuracy is good, it can't predict 5. what is the wrong in my code or logic?

A: I can guess, you have an accuracy of about 90%, but your model almost always predicts 0 ( not 5), right?
If it is the case, the reason can be the imbalanced classes. Your original dataset, I guess is balanced, like we have almost N 0s, almost N 1s, ... and almost N 9s. What you did, you kept the almost N 5s, and labeled it to 1, and turn the rest of almost 9*N examples to label 0. It means now you have 10% of data labeled 1( which are 5s) and 90% of data labeled 0. This is an imbalance case, and it is very normal you get a good accuracy of around 90%, but a poor prediction for the minority class. For imbalanced cases, accuracy is not a good metric or maybe it is not enough. Try to trace Precision,recall, and F1 as well.
my suggestion, sample from the non 5 classes ( 1/10 from each ) and keep all the
5s. You should get better predictions.


text:
Q: git auto merge two branches: which file's content will take precedence source file or destination file? Here is my situation,
I have to create a new branch C like this:- first branching off from A and then merging in B
The steps i followed:
New branch C is created branching off from A
B is merged into C
Now, the diff show no conflict however, which file's content will be resolved automatically whether is it the B's contents or C's content that will take precedence in a no conflict situation.?
Does the source branch's file contents take precedence or the destination branch's file contents will take precedence for auto merge.

A: By default, there is no "precedence". Git will try to merge the differences fro both branches together. There's a merge strategy available where you can tell git "forget about the changes on the other branch and take mine", but by default with recursive, the changes of both branches are considered and... well, merged together.


text:
Q: White-space between two values I have a column as like given below
EB.Liter+'L'+EB.CC+'cc'+'-ci'+EB.BlockType+EB.Cylinders+
         (
       EB.EngBoreIn+'x'+
        EB.EngStrokeIn+';'+
        EB.EngBoreMetric+'x'+
    EB.EngStrokeMetric
         ) as EngineBase

This pull data something like this
1.3   L 1339    cc L 4 (2.87      x3.15      ;73.0      x80.0      )

but i am trying to get something like
1.3L 1339cc -ci L4 (2.87x3.15; 73.0x80.0)

may anyone please suggest if possible
i have tried something like this.
LTRIM(RTRIM(EB.Liter))+'L'+LTRIM(RTRIM(EB.CC))+'cc'+'-
ci'+LTRIM(RTRIM(EB.BlockType))+LTRIM(RTRIM(EB.Cylinders))+
        + (
       LTRIM(RTRIM(EB.EngBoreIn))+'x'+
        LTRIM(RTRIM(EB.EngStrokeIn))+';'+
        LTRIM(RTRIM(EB.EngBoreMetric))+'x'+
    LTRIM(RTRIM(EB.EngStrokeMetric))
         ) as EBase

which get me result as below
    1.3L1339cc-ciL42.87x3.15;73.0x80.0
but correct output is as
    1.3L 1339cc -ciL4(2.87x3.15; 73.0x80.0)

A: modify like this
LTRIM(RTRIM(EB.Liter))+'L '+LTRIM(RTRIM(EB.CC))+'cc '+'-ci'+LTRIM(RTRIM(EB.BlockType))+LTRIM(RTRIM(EB.Cylinders))+
    + '('+
    LTRIM(RTRIM(EB.EngBoreIn))+'x'+
    LTRIM(RTRIM(EB.EngStrokeIn))+'; '+
    LTRIM(RTRIM(EB.EngBoreMetric))+'x'+
    LTRIM(RTRIM(EB.EngStrokeMetric))
    +')' as EBase

A: you can use trim functionality to remove leading and trailing spaces. Your query would look like that then:
TRIM(EB.Liter) + 'L'+TRIM(EB.CC)+'cc'+'-ci'+TRIM(EB.BlockType)+TRIM(EB.Cylinders)+
(
TRIM(EB.EngBoreIn)+'x'+
TRIM(EB.EngStrokeIn)+';'+
TRIM(EB.EngBoreMetric)+'x'+
TRIM(EB.EngStrokeMetric)
) as EngineBase


text:
Q: How to catch a database exception in ios? I have searched a lot on the internet on catching an sqlite exception.But all I could come across was this general exception
@catch (NSException *exception) {

        }

What type of exception can I use for sqlite exception handling?

A: Generally, SQLite does not return exceptions for recoverable errors. Rather, it returns an error code which you must check after each operation.
Some "wrapper" APIs for SQLite may return exceptions, but that would be a function of the particular API.


text:
Q: Copying SQL Server database I am working on a SQL Server on which I have three databases:

*

*User: This is the one where real data resides

*Test

*Development: This is used for testing and developement.

From time to time I want to copy the content of the user database into the test and / or development database to make sure that the developement and test environments are as close as possible to the user environment.
I thought I could use the "Copy Database Wizard" for this, but it fails with an error

"Object reference not set to an instance of an object

after I have chosen which hosts to copy from and to (localhost in both cases). I have not been able to find any solutions to this error.
Question

*

*Does anybody have any ideas about what causes this and how to correct the problem (maybe I need to install something or do something with the setup of the server?)

*What would be the selected way of doing the transfer if I cannot use the Copy Database Wizard? - This is to be done, I would guess, about once a month.
If it matters, I have full admin access on the database server but not on the underlying windows server.

A: Are you just looking for a complete copy of the data to completely replace what already lives on the destination instance?  In that case, a full backup of the source database and a restore into the destination instance would be the cleanest and easiest route.
If you are looking at select data copying (i.e. you don't want all data, or you don't want to replace the destination data) then you'll need to have a logic layer between the two data sources.  Some ideas behind this would be SSIS, PowerShell, or any other tool to do some brain work between both SQL Server databases.  The tool to use would depend on the specifics of your need as well as your comfort level with all the options.


text:
Q: .NET Core запускаемое приложение Я правильно понимаю, что на выходе платформы .NET Core получается dll, которую затем необходимо на клиентской платформе скормить консольной утилите для запуска?
Иными словами, если я захочу на LINUX сделать ярлык для своей программы, то должен в ярлык поместить вызов dotnet [путь к DLL] или какая-то компиляция в исполняемый файл целевой платформы все таки есть?


text:
Q: Remove HTML and Javascript comments automatically I want to remove HTML and JavaScript comments automatically. I am using ant-scripts for deployment and JSF on the server. What options or tools are available? Thanks in advance.

A: Replacing comments in files that mix HTML and JavaScript with regexes is risky. However, separately, you can do with good performance without relying on external tools, only node.js:
For HTML comments use the regex /<!--(?!>)[\S\s]*?-->/g. example:
function stripHtmlComments(content) {
  return content.replace(/<!--(?!>)[\S\s]*?-->/g, '');
}

Removing JavaScript comments is a bit more complex, you need mix several regexes to differentiate when comments are inside literal strings or regexes, and when a slash belongs to a regex :)
This tiny program removes both multiline and single-line comments from JavaScript files:
#!/usr/bin/env node
/*
  Removes multiline and single-line comments from a JavaScript source file.
  Author: aMarCruz - https://github.com/aMarCruz
  Usage: node [this-tool] [js-file]
*/
var path = require('path'),
    fs = require('fs'),
    file,
    str;

var RE_BLOCKS = new RegExp([
    /\/(\*)[^*]*\*+(?:[^*\/][^*]*\*+)*\//.source,           // $1: multi-line comment
    /\/(\/)[^\n]*$/.source,                                 // $2 single-line comment
    /"(?:[^"\\]*|\\[\S\s])*"|'(?:[^'\\]*|\\[\S\s])*'/.source, // string, don't care about embedded eols
    /(?:[$\w\)\]]|\+\+|--)\s*\/(?![*\/])/.source,           // division operator
    /\/(?=[^*\/])[^[/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[/\\]*)*?\/[gim]*/.source
    ].join('|'),                                            // regex
    'gm'  // note: global+multiline with replace() need test
    );

file = process.argv[2];
if (!path.extname(file))
    file += '.js';
str = fs.readFileSync(file, { encoding: 'utf8' });

console.log(stripJSComments(str));

// remove comments, keep other blocks
function stripJSComments(str) {
    return str.replace(RE_BLOCKS, function (match, mlc, slc) {
        return mlc ? ' ' :     // multiline comment (must be replaced with one space)
               slc ? '' :      // single-line comment
               match;          // divisor, regex, or string, return as-is
        });
}

Now (example) save as rcomms and run with:
node rcomms source-file > clean-file.js

NOTE:
This code is based on regexes from jspreproc, if you need more advanced processing, please visit http://github.com/aMarCruz/jspreproc.
I wrote jspreproc to deploy some riot modules.
jspreproc remove empty lines, supports filters for preserve some comments and conditional comments in C-style: #if-else,endif, #define, #include, etc.

A: You can use regular expressions to remove them with ease. For example, you can remove HTML comments by replace the matches of the regular expression /\<!--(.*)-\>/gi to nothing.

A: Library decomment does exactly what you described - removes comments from JSON, JavaScript, CSS, HTML, etc.
For use within the gulp system see gulp-decomment

A: Make a new target and use replaceregexp to replace all comments and other things you dont want in these files.
You could do sth. like that for html and something similar for js:
<target name="-trim.html.comments">

    <fileset id="html.fileset"
        dir="${build.dir}"
        includes="**/*.jsp, **/*.php, **/*.html"/>

    <!-- HTML Comments -->
    <replaceregexp replace="" flags="g"
        match="\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>">
        <fileset refid="html.fileset"/>
    </replaceregexp>

</target>

Source: http://www.julienlecomte.net/blog/2007/09/23/


text:
Q: Javascript email format not validating correctly The code below validating correctly with exception to the email address field. Do you have any suggestions as to how I can modify the code to get the email address field validation working? I want to ensure real email addresses are being entered and accepted.
$('#topError').empty();
$('#fnameError').empty();
$('#lnameError').empty();
$('#genderError').empty();
$('#bdayError').empty();
$('#emailError').empty();
$('#pass1Error').empty();
$('#pass2Error').empty();
$('#passcError').empty();

var fname = Apperyio('register_firstname').val();
var lname = Apperyio('register_lastname').val();
var gender = Apperyio('register_gender').val();
var bmonth = Apperyio('register_birthdaymonth').val();
var bday = Apperyio('register_birthdayday').val();
var byear = Apperyio('register_birthdayyear').val();
var email = Apperyio('register_email').val();
var pass1 = Apperyio('register_password1').val();
var pass2 = Apperyio('register_password2').val();
var re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;

var errorMsg = "";

if ($.trim(fname) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("fnameError").innerHTML = "Please enter your first name.";
}

if ($.trim(lname) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("lnameError").innerHTML = "Please enter your last name.";
}

if ($.trim(gender) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("genderError").innerHTML = "Please select your gender.";
}

if ($.trim(bmonth) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(bday) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(byear) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(email) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("emailError").innerHTML = "Please enter your email address.";
}

if (email.val() === "" || !re.test(email.val()))
{
    errorMsg = errorMsg + "1";
    document.getElementById("emailError").innerHTML = "Please enter a vaild email address.";
}

if ($.trim(pass1.length) < 6)
{
    errorMsg = errorMsg + "1";
    document.getElementById("pass1Error").innerHTML = "Please enter a password of at least 6 characters.";
}
if ($.trim(pass2) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("passcError").innerHTML = "Please confirm your password.";
}
if ($.trim(pass1) !== $.trim(pass2))
{
    errorMsg = errorMsg + "1";
    document.getElementById("emailError").innerHTML = "The passwords you entered do not match.";
}

if (errorMsg === "")
{
    //signupService.execute({});
    Apperyio.User.createUser({
"username": Apperyio('register_email').val(),
"password": Apperyio('register_password1').val(),
"email": Apperyio('register_email').val(),
"firstName": Apperyio('register_firstname').val(),
"lastName": Apperyio('register_lastname').val(),
"gender": Apperyio('register_gender').val(),
"birthday": (Apperyio('register_birthdayyear').val() + Apperyio('register_birthdaymonth').val() + Apperyio('register_birthdayday').val())
})
.then(function(result){
    Apperyio.navigateTo('Position1');
}
);
}

Update: I was able to resolve the issue. Thank you for your help.
Here is the updated code:

$('#topError').empty();
$('#fnameError').empty();
$('#lnameError').empty();
$('#genderError').empty();
$('#bdayError').empty();
$('#emailError').empty();
$('#pass1Error').empty();
$('#pass2Error').empty();
$('#passcError').empty();

var fname = Apperyio('register_firstname').val();
var lname = Apperyio('register_lastname').val();
var gender = Apperyio('register_gender').val();
var bmonth = Apperyio('register_birthdaymonth').val();
var bday = Apperyio('register_birthdayday').val();
var byear = Apperyio('register_birthdayyear').val();
var email = Apperyio('register_email').val();
var pass1 = Apperyio('register_password1').val();
var pass2 = Apperyio('register_password2').val();
var dateString = (bmonth + "/" + bday + "/" + byear);

var errorMsg = "";

if ($.trim(fname) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("fnameError").innerHTML = "Please enter your first name.";
}

if ($.trim(lname) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("lnameError").innerHTML = "Please enter your last name.";
}

if ($.trim(gender) === "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("genderError").innerHTML = "Please select your gender.";
}

var date_regex = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})$/;
if (!(date_regex.test(dateString)))
{
    errorMsg = errorMsg + "1";
    document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}

function validateEmail(email) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
    return true;
    }
    else {
    return false;
}
}

if ($.trim(email).length === 0) {
    errorMsg = errorMsg + "1";
    document.getElementById("emailError").innerHTML = "Please enter a valid email address.";
//            e.preventDefault();
        }
if (validateEmail(email)) {
            //alert('Email is valid');
}
        else {
    errorMsg = errorMsg + "1";
    document.getElementById("emailError").innerHTML = "Please enter a valid email address.";
//            e.preventDefault();
}

if ($.trim(pass1.length) < 6)
{
    errorMsg = errorMsg + "1";
    document.getElementById("pass1Error").innerHTML = "Please enter a password of at least 6 characters.";
}
if ($.trim(pass2) === "" & $.trim(pass1) !== "")
{
    errorMsg = errorMsg + "1";
    document.getElementById("passcError").innerHTML = "Please confirm your password.";
}
if ($.trim(pass1) !== $.trim(pass2))
{
    errorMsg = errorMsg + "1";
    document.getElementById("emailError").innerHTML = "The passwords you entered do not match.";
}

if (errorMsg === "")
{
    //signupService.execute({});
    Apperyio.User.createUser({
"username": Apperyio('register_email').val(),
"password": Apperyio('register_password1').val(),
"email": Apperyio('register_email').val(),
"firstName": Apperyio('register_firstname').val(),
"lastName": Apperyio('register_lastname').val(),
"gender": Apperyio('register_gender').val(),
"birthday": (Apperyio('register_birthdayyear').val() + Apperyio('register_birthdaymonth').val() + Apperyio('register_birthdayday').val())
})
.then(function(result){
    Apperyio.navigateTo('Position1');
}
);
}


text:
Q: Generalize converting a Linq-to-SQL object representing a table to a DataTable I have the following class:
    [Table(Name = "test")]
    public class Test
    {
        private string _Name;
        [Column(Storage = "_Name")]
        public string Name
        {
            get { return this._Name; }
            set { this._Name = value; }
        }

        private int _Age;
        [Column(Storage = "_Age")]
        public int Age
        {
            get { return this._Age; }
            set { this._Age = value; }
        }

        public static DataTable ConvertListToDataTable(List<Test> table) // Used for SqlBulkCopy
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Age", typeof(int));

            foreach (Test row in table)
            {
                DataRow dr = dt.NewRow();
                dr["Name"] = row.Name;
                dr["Age"] = row.Age;

                dt.Rows.Add(dr);
            }

            return dt;
        }
    }

But I'd like to abstract that ConvertListToDataTable method out into a parent base class. Is that possible using reflection? I wouldn't even know where to start.
Note the DataTable will have columns that exactly match (in name without the _ and type) all the properties of the class with a [Column] attribute

This is the reason I want the DataTable:
public void testBulkInsert(string connection, string table, DataTable dt)
    {
        using (SqlConnection con = new SqlConnection(connection))
        {
            con.Open();

            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
            {
                bulkCopy.DestinationTableName = table;

                bulkCopy.WriteToServer(dt);
            }
        }
    }


text:
Q: Converting & modifying a list of NamedTuples into a List of Dict's I need to convert a list of Named Tuples:
[Fruit(name='banana', colour='yellow', delicious=True), Fruit(name='mangosteen', colour='purple', delicious=True)]

Into a modified list of Dict's (note the extra text key):
[{'name': {'text': 'banana'}, 'colour': {'text': 'yellow'}}, {'name': {'text': 'mangosteen'}, 'colour': {'text': 'purple'}}]

I have managed to find a solution that works, but it seems ugly, I am fairly new to Python.
Fruit = namedtuple('Fruit', 'name colour')
fruitlist=[]
fruitlist.append(Fruit('banana', 'yellow'))
fruitlist.append(Fruit('mangosteen', 'purple'))

newfruitlist = []
for fruit in fruitlist:
    fruitdict = dict(fruit._asdict()) #convert NamedTuple to Dict
    tempdict={}
    for key, value in fruitdict.items():
        tempdict[key]={ 'text': value }
    newfruitlist.append(tempdict)

Question: what is a better/cleaner way to do this?

A: Combine list and dict comprehensions:
from collections import namedtuple

Fruit = namedtuple('Fruit', 'name colour')
fruitlist=[]
fruitlist.append(Fruit('banana', 'yellow'))
fruitlist.append(Fruit('mangosteen', 'purple'))

out = [{k:{'text':v} for k, v in f._asdict().items()} for f in fruitlist]

print(out)

Prints:
[{'name': {'text': 'banana'}, 'colour': {'text': 'yellow'}}, {'name': {'text': 'mangosteen'}, 'colour': {'text': 'purple'}}]


text:
Q: The Value of type 'Boolean' cannot be converted to 'System.Data.DataRow" am getting an error 1 message that states "The Value of type 'Boolean' cannot be converted to 'System.Data.DataRow". How do I convert a value type Boolean to System.Data.DataRow? Have tried but to no avail.
Here's my code
Dim newRow As DataRow

newRow = Database51DataSet1.Tables(0).NewRow
newRow.Item(0) = TextBox3.Text
newRow = ("orderID") = (TextBox3.Text.Trim() = "0"(Convert.ToInt32(TextBox3.Text)))
newRow.Item(1) = TextBox4.Text
newRow.Item(2) = TextBox5.Text
Database51DataSet1.Tables(0).Rows.Add(newRow)

A: You don't want to convert a boolean to a DataRow. The compiler assumes that because the comparison returns a Boolean and you assign that to newRow.
I think you want to assign the OrderId field value. So replace...
newRow = ("orderID") = (TextBox3.Text.Trim() = "0"(Convert.ToInt32(TextBox3.Text)))

with
Dim orderId As Int32
If Int32.TryParse(TextBox3.Text.Trim(), orderId) Then
    newRow("orderID") = orderId
End If

Which also handles the case that it's not a valid integer.
If that column is actually a string and you want to assign the value with a leading zero:
newRow("orderID") = TextBox3.Text.Trim().PadLeft(2, "0"c)


text:
Q: Transparent Form Background I tried to set backcolor to transparent by solution given at msdn but failed is there any way to make background transparent
http://msdn.microsoft.com/en-us/library/wk5b13s4(VS.71).aspx

A: Yes, set the form's TransparencyKey property.  Make the BackColor the same value.  You need to pick a color that won't appear anywhere else in the form.  Color.Fuchsia is a good choice, it's a fuchsed-up color.
This isn't a good idea for a splash screen.  The point of having one is that the user can see it.  The linked MSDN article is only appropriate for (some) child controls, not the form.


text:
Q: Electron - How to save information? I've recently learned about Electron, and given I have a rather well amount of knowledge of HTML, CSS, and Javascript, I decided to take a look at it. When I normally make web applications I use MySQL for storing user data mostly through PHP. I noticed Electron doesn't support PHP files like a normal browser does, so I'm curious as to what the best method for saving user data actually is. I read Electron allows for interaction of files like a real application does unlike web apps, but I feel like there's another way. Is there any "standard" when it comes to stuff like this?

A: As I mentioned in the comment, you could use a NoSQL solution (or as Paulo Galdo Sandoval mentioned, the HTML5 storage methods)
I googled and found these resources:
https://medium.com/@ccnokes/how-to-store-user-data-in-electron-3ba6bf66bc1e#.c45jm3tas
https://github.com/jviotti/electron-json-storage


text:
Q: How to Get Json object and Json Array in Same KEY by retrofit for android I am getting JSON Object when their is only one response(items) or JSON Array response but i want to array and object response.How to handle JSON Response?
JSON ARRAY when their is more than one items.And JSON OBJECT when their is only one items
.
{
   "product":[

      {
         "items":[
            {
               "name":"foo",
               "title":"toy"
            },
            {
               "name":"foo",
               "title":"toy"
            }
         ]
      },
     {   "items":
            {
               "name":"foo",
               "title":"toy"
            }
      }

   ]
}

A: First create model for this json Response using json to p
public class Example {

 @SerializedName("product")
 @Expose
private List<Product> product = null;

public List<Product> getProduct() {
return product;
}

public void setProduct(List<Product> product) {
this.product = product;
}

}

  public class Item {

  @SerializedName("name")
  @Expose
  private String name;
  @SerializedName("title")
  @Expose
  private String title;

 public String getName() {
 return name;
}

 public void setName(String name) {
 this.name = name;
  }

 public String getTitle() {
 return title;
}

public void setTitle(String title) {
this.title = title;
}

}

public class Product {

 @SerializedName("items")
 @Expose
 private List<Item> items = null;

 public List<Item> getItems() {
 return items;
 }

public void setItems(List<Item> items) {
this.items = items;
}

}

Pass this Exmaple class into your response like
Call and get the data usning model


text:
Q: The series $1 + v^2 + v^4 + v^6 + v^8 + ...$ is gamma squared Can anyone tell me anything about the series
$ 1 + v^2 + v^4 + v^6 + v^8 ... $
Does it have a name? Does it have any special properties?
I ask because $ \gamma = \sqrt{1 + v^2 + v^4 + v^6 + v^8 ...} $
Obviously it only works for v < 1
(i.e. less than the speed of light)
edit: hmmm...subtract one and divide by v^2 and the result is itself
edit: oh and $ \gamma - 1 \approx v^2/2 $ for small values hence
kinetic energy = $m (\gamma - 1) c^2  \approx ( E = m v^2/2$)

A: This is a question about special relativity, in which $v$ (often denoted $\beta$) satisfies $\gamma=1/\sqrt{1-v^2}$. As @ziprirovich notes, it's a geometric series, which converges to $\frac{1}{1-v^2}=\gamma^2$ because $|v|<1$.

A: Taking $v$ to be the speed of an object relative to some inertial frame $O$, $\gamma = (1-v^2/c^2)^{-1/2}$, then by the geometric series formula:
$$1+\frac{v^2}{c^2} + \frac{v^4}{c^4} + \ldots = \frac{1}{1-\frac{v^2}{c^2}}=\gamma^2$$
Therefore if $v$ in your question is in natural units, you have $1+v^2+v^4 + \ldots = \gamma^2$.


text:
Q: Common java class for json communication from server to client I'm currently working in migrating a project to java, keeping the data intact (database). Most data are taken via stored procedures(SP), and there's a hell lot of SP in the database.
So, while executing each SP, I have to write a class for that, which is building up a huge pile of classes.
Hence, is there any way to generalize the class, so that I could transform every SP results to this class, and then to client side(as json)?
Following scenarios are hidden n ma qn:

*

*Dynamic number of fields.

*Dynamic field names.

*Type could be string
(could deal with that).

I have tried sending data as java.util.List, but that doesn't comes in a pretty format. Have to take data assuming indexes.
PS: I have searched for the same, but couldn't find any. And sorry if I'm asking for too much.

A: Yes, it should be possible to write such a generic class. Here is a small example class as a starting point for you. I use Firebird with the example database employee.fdb because there are already some stored procedures defined.
So to connect to the Firebird server, I use the Jaybird JDBC driver and include the jaybird-full-2.2.5.jar JAR file.
There are several different JSON libraries for JAVA. I use the JSR 353: Java API for JSON Processing - Reference Implementation here in streaming mode (like StaX for XML). So the second external JAR here is javax.json-1.0.4.jar.
My example works only for stored procedures returning result sets. For stored procedures with output parameters a CallableStatement should be used instead of a PreparedStatement.
First, a generic SQL statement is created for the specific stored procedure with its input parameters. To call the stored procedure, a PreparedStatemend is used. The parameters are set according to the individual parameter types. (Procedures createSql() and createStatement())
In procedure convertToJson() the method ResultSet.getMetaData() is used to get the result set's column information (how many columns, column name and column type).
The executeStoredProcedure() methods are public API methods to call.
The main() method connects to the èmployee.fdb database and calls three stored procedures: GET_EMP_PROJ, MAIL_LABEL and ORG_CHART.
package com.genericsptojson;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;

public class GenericSpToJson {

  private static final String DB_URL = "jdbc:firebirdsql:localhost/3050:/var/lib/firebird/2.5/data/employee.fdb";
  private static final String DB_USER = "SYSDBA";
  private static final String DB_PWD = "***";

  private Connection con;

  public GenericSpToJson(Connection con) {
    this.con = con;
  }

  /**
   * Creates the SQL to call the stored procedure.
   *
   * @param spName
   *          Name of stored procecdure to call
   * @param paramCount
   *          number of input parameters
   * @return SQL with placeholders for input parameters
   */
  private String createSql(String spName, int paramCount) {
    if(paramCount > 0) {
      final StringBuilder params = new StringBuilder();
      boolean isFirst = true;
      for(int i = 0; i < paramCount; i++) {
        if(isFirst) {
          isFirst = false;
        } else {
          params.append(", ");
        }
        params.append('?');
      }
      return String.format("SELECT * FROM %s (%s)", spName, params.toString());
    } else {
      return String.format("SELECT * FROM %s", spName);
    }
  }

  /**
   * Creates a PreparedStatement to call the stored procedure. This works only
   * for stored procedures creating result sets. Stored procedures with OUT
   * parameters should be handled by a CallableStatement instead.
   *
   * @param spName
   *          The stored procedure name to be called.
   * @param params
   *          The input parameters.
   * @return A prepared statement. All parameters are set.
   * @throws SQLException
   */
  private PreparedStatement createStatement(String spName, Object... params) throws SQLException {
    final PreparedStatement stmt = con.prepareStatement(createSql(spName, params.length));
    for(int i = 0; i < params.length; i++) {
      final Object param = params[i];
      if(param instanceof String) {
        stmt.setString(i + 1, (String) param);
      } else if(param instanceof Integer) {
        stmt.setInt(i + 1, ((Integer) param).intValue());
      } else {
        // Handle other param types ...
      }
    }
    return stmt;
  }

  /**
   * Converts the result set to JSON in streaming mode.
   *
   * @param spName
   *          The stored procedure name.
   * @param rs
   *          The result set of the stored procedure call.
   * @param out
   *          The output stream to write the JSON into.
   * @throws SQLException
   */
  private void convertToJson(String spName, ResultSet rs, OutputStream out) throws SQLException {
    // Get the result set meta data to obtain column information on the fly.
    final ResultSetMetaData metaData = rs.getMetaData();

    // Create the JSON generator with pretty printing
    final Map<String, Object> properties = new HashMap<String, Object>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    final JsonGeneratorFactory jsonGeneratorFactory = Json.createGeneratorFactory(properties);
    final JsonGenerator generator = jsonGeneratorFactory.createGenerator(out);
    generator.writeStartObject(); // root object

    generator.write("storedProcedureName", spName);
    generator.write("columnCount", metaData.getColumnCount());
    generator.writeStartArray("records"); // records array
    while(rs.next()) {
      generator.writeStartObject(); // record object
      // Each record object contains one field for every column.
      // The field name is the columns name.
      for(int col = 1; col <= metaData.getColumnCount(); col++) {
        final String fieldName = metaData.getColumnName(col);
        switch(metaData.getColumnType(col)) {
          case Types.INTEGER:
            final int intValue = rs.getInt(col);
            if(rs.wasNull()) {
              generator.writeNull(fieldName);
            } else {
              generator.write(fieldName, intValue);
            }
            break;
          case Types.VARCHAR:
          case Types.CHAR:
            String stringValue = rs.getString(col);
            if(rs.wasNull()) {
              generator.writeNull(fieldName);
            } else {
              if(metaData.getColumnType(col) == Types.CHAR) {
                stringValue = stringValue.trim();
              }
              generator.write(fieldName, stringValue);
            }
            break;
          // Handle other types here
          default:
            System.out.println(String.format("Unhandled SQL type: %s", metaData.getColumnTypeName(col)));
        }
      }
      generator.writeEnd(); // record object
    }
    generator.writeEnd(); // records array
    generator.writeEnd(); // root object
    generator.flush();
    generator.close();
  }

  /**
   * Executes the stored procedures with the given input parameters and creates
   * JSON in streaming mode.
   *
   * @param spName
   *          The name of the stored procedure.
   * @param out
   *          The output stream to write the generated JSON into.
   * @param params
   *          The stored procedure's parameters.
   */
  public void executeStoredProcedure(String spName, OutputStream out, Object... params) {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
      stmt = createStatement(spName, params);
      rs = stmt.executeQuery();
      convertToJson(spName, rs, out);
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      // Cleaning up ...
      if(stmt != null) {
        try {
          stmt.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if(rs != null) {
        try {
          rs.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * Convenience method to call the stored procedure and create a JSON string.
   * This should only be called for short result sets. For longer result sets
   * use {@link #executeStoredProcedure(String, OutputStream, Object...)} where
   * it is not necessary to hold the entire JSON document in memory.
   *
   * @param spName
   *          The name of the stored procedure to call.
   * @param params
   *          The stored procedure's parameters
   * @return The stored procedure's call result as a JSON string.
   * @throws UnsupportedEncodingException
   */
  public String executeStoredProcedure(String spName, Object... params) throws UnsupportedEncodingException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    executeStoredProcedure(spName, out, params);
    return out.toString("UTF-8");
  }

  public static void main(String[] args) {
    Connection con = null;
    try {
      Class.forName("org.firebirdsql.jdbc.FBDriver");
      con = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);

      final GenericSpToJson converter = new GenericSpToJson(con);

      System.out.println("Executing stored procedure GET_EMP_PROJ (8):\n"
          + converter.executeStoredProcedure("GET_EMP_PROJ", 8));
      System.out.println("\n\nExecuting stored procedure MAIL_LABEL (1015):\n"
          + converter.executeStoredProcedure("MAIL_LABEL", 1015));
      System.out.println("\n\nExecuting stored procedure ORG_CHART:\n"
          + converter.executeStoredProcedure("ORG_CHART"));
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if(con != null) {
      try {
        con.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}

The output is (shortened):
Executing stored procedure GET_EMP_PROJ (8):

{
    "storedProcedureName":"GET_EMP_PROJ",
    "columnCount":1,
    "records":[
        {
            "PROJ_ID":"VBASE"
        },
        {
            "PROJ_ID":"GUIDE"
        },
        {
            "PROJ_ID":"MKTPR"
        }
    ]
}

Executing stored procedure MAIL_LABEL (1015):

{
    "storedProcedureName":"MAIL_LABEL",
    "columnCount":6,
    "records":[
        {
            "LINE1":"GeoTech Inc.",
            "LINE2":"K.M. Neppelenbroek",
            "LINE3":"P.0.Box 702",
            "LINE4":"",
            "LINE5":null,
            "LINE6":"Netherlands    2514"
        }
    ]
}

Executing stored procedure ORG_CHART:

{
    "storedProcedureName":"ORG_CHART",
    "columnCount":5,
    "records":[
        {
            "HEAD_DEPT":null,
            "DEPARTMENT":"Corporate Headquarters",
            "MNGR_NAME":"Bender, Oliver H.",
            "TITLE":"CEO",
            "EMP_CNT":2
        },
        {
            "HEAD_DEPT":"Corporate Headquarters",
            "DEPARTMENT":"Sales and Marketing",
            "MNGR_NAME":"MacDonald, Mary S.",
            "TITLE":"VP",
            "EMP_CNT":2
        },
        // ... SNIP ...
        {
            "HEAD_DEPT":"Corporate Headquarters",
            "DEPARTMENT":"Finance",
            "MNGR_NAME":"Steadman, Walter",
            "TITLE":"CFO",
            "EMP_CNT":2
        }
    ]
}


text:
Q: label argument in plt.fill_between not working I am working with line plots using:
x = np.arange(25,55,5)
y = np.random.randint(10000,50000,6)
y2 = np.random.randint(10000,60000,6)

Then the main plotting code is:
plt.style.use('fivethirtyeight')

plt.xlabel("some random ages")
plt.ylabel('some random salaries')
plt.title('whatever')
plt.legend(['first','second'])

plt.plot(x,y)
plt.plot(x,y2)

plt.fill_between(x,y,color = 'blue', alpha = 0.25, where = (y>np.median(y)), interpolate =True,
                 label = 'above median')
#Colour blue for salaries more than the median.

plt.fill_between(x,y,color = 'red', alpha = 0.25, where = (y<=np.median(y)), interpolate =True,
                 label = 'below median')
#Colour red for salaries less than the median.

plt.show()

The filling is working as intended, however the plot legends only have the entries specified in  plt.legend(). The label argument, which seems to work in the tutorial video I am watching as well as every other site I have seen, does not add the intended labels to the legends. I had the same problem in stack plots, where the tutor, who is using pycharm, used labels to add legend to the satckplot, and I had to use plt.legend because the labels command seemed to do nothing. However here I don't know how to add the legends for the fill colours along with the legends for the main line plots.
I am using the latest version of jupyter notebook and latest python version on macOS Monterey 12.4.

A: Either specify your labels in all places:
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
x = np.arange(25,55,5)
y = np.random.randint(10000,50000,6)
y2 = np.random.randint(10000,60000,6)

plt.style.use('fivethirtyeight')

plt.plot(x,y, label='red')
plt.plot(x,y2, label='blue')

#Colour blue for salaries more than the median.
plt.fill_between(x,y,color = 'blue', alpha = 0.25, where = (y>np.median(y)), interpolate =True,
                 label = 'above median')

#Colour red for salaries less than the median.
plt.fill_between(x,y,color = 'red', alpha = 0.25, where = (y<=np.median(y)), interpolate =True,
                 label = 'below median')

plt.xlabel("some random ages")
plt.ylabel('some random salaries')
plt.title('whatever')
plt.legend()

plt.show()

or specify all labels in the legend parameters:
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
x = np.arange(25,55,5)
y = np.random.randint(10000,50000,6)
y2 = np.random.randint(10000,60000,6)

plt.style.use('fivethirtyeight')

plt.plot(x,y)
plt.plot(x,y2)

#Colour blue for salaries more than the median.
plt.fill_between(x,y,color = 'blue', alpha = 0.25, where = (y>np.median(y)), interpolate =True)

#Colour red for salaries less than the median.
plt.fill_between(x,y,color = 'red', alpha = 0.25, where = (y<=np.median(y)), interpolate =True)

plt.xlabel("some random ages")
plt.ylabel('some random salaries')
plt.title('whatever')
plt.legend(['red', 'blue', 'above', 'below'])

plt.show()

Note that the first method is the recommended one (as noted by @JohanC) because it does the job for you and it adds the labels automatically. In the second, you are overwriting what is in the legend. That is what happened in your example -- you defined your labels in the label argument and then you passed a list to the legend function which overrides your labels.