text:
Q: Java how to divide a treemap into two equal maps based on values Okay I have this treemap that contains playerID and a players averageScore. I want to split it up into two other maps so each team has an even amount of players and the overall player score is around about the same(deviation of around +/-2)
private TreeMap<Integer, Double> teamScoreMap = new TreeMap<>();
private TreeMap<Integer, Double> team1 = new TreeMap<>();
private TreeMap<Integer, Double> team2 = new TreeMap<>();

public void createTeam()
   {
       teamScoreMap.put(001, 5.0);
       teamScoreMap.put(002, 8.4);
       teamScoreMap.put(003, 2.1);
       teamScoreMap.put(004, 6.5);
       teamScoreMap.put(005, 4.5);
       teamScoreMap.put(006, 3.2);
       teamScoreMap.put(007, 9.8);
       teamScoreMap.put(008, 7.6);
   }

A: Try this out
TreeMap<Integer,Double> teamScoreMap = new TreeMap<Integer, Integer>(bigMap);
int size = teamScoreMap.size();
SortedMap<Integer, Double> team1 = teamScoreMap .subMap(0, size/2);
SortedMap<Integer, Double> team2 = teamScoreMap .subMap((size/2)+1,size);

There is no reason to actually cast to a TreeMap because it doesn't provide any additional functionality over what a SortedMap does.

A: The logic is there, you just need to finish the code to add each team to each map.
Make all the possible teams, compare their average with the previous best average. If the difference is below the previous, swap them.
At the end, you get the best difference between both.

An example of output
{false=[1=5.0, 4=6.5, 5=4.5, 8=7.6], true=[2=8.4, 3=2.1, 6=3.2, 7=9.8]}
// false = 23.6 in total             true = 23.5 in total
// As you see, the difference between both is the minimum possible (0.1)

public class Test {
    private Map<Integer, Double> tsm = new TreeMap<>();
    private Map<Integer, Double> team1 = new TreeMap<>();
    private Map<Integer, Double> team2 = new TreeMap<>();

    public void splitTeams() {
        double average = tsm.values()
                            .stream()
                            .mapToDouble(x->x)
                            .average()
                            .getAsDouble();
        int[] bestTeam = new int[4];
        double bestAverage = 10;
        double tmp;

        for (int i = 1 ; i <= 8 ; i++) {
            for (int j = 1 ; j <= 8 ; j++) {
                for (int k = 1 ; k <= 8 ; k++) {
                    for (int l = 1 ; l <= 8 ; l++) {
                        if (Stream.of(i, j, k, l).distinct().count() == 4) {
                            tmp = Stream.of(tsm.get(i), tsm.get(j), tsm.get(k), tsm.get(l))
                                        .mapToDouble(x -> x)
                                        .average()
                                        .getAsDouble();
                            if (Math.abs(average - tmp) < bestAverage) {
                                bestTeam[0] = i;
                                bestTeam[1] = j;
                                bestTeam[2] = k;
                                bestTeam[3] = l;
                                bestAverage = Math.abs(average - tmp);
                            }
                        }
                    }
                }
            }
        }

        List<Integer> team1 = Arrays.stream(bestTeam).boxed().collect(Collectors.toList());
        Map<Boolean, List<Entry<Integer, Double>>> both = tsm.entrySet()
                                                             .stream()
                                                             .collect(Collectors.partitioningBy(e -> team1.contains(e.getKey())));
        System.out.println(both);
    }

    public void createTeam() {
        tsm.put(1, 5.0);
        tsm.put(2, 8.4);
        tsm.put(3, 2.1);
        tsm.put(4, 6.5);
        tsm.put(5, 4.5);
        tsm.put(6, 3.2);
        tsm.put(7, 9.8);
        tsm.put(8, 7.6);
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.createTeam();
        t.splitTeams();
        System.out.println();
    }
}

A: The answer by Yassin Hajaj shows one way of computing the optimal result for this particular case. More generally, what you are trying to solve is a special instance of the subset sum problem, and there are related questions - e.g. divide an array into two sets with minimal difference.
There basically is no efficient way of finding the optimal solution.
The brute-force way to compute the optimal solution is to compute all possible choices of half of the elements, compute their sum, and find the sum that has the least deviation from the desired sum.
However, in many cases, one is not interested in the optimal solution, but only in a "good" solution. This can be achieved with a greedy approach: First, sort the scores in decreasing order. Then, go through the list of team members, and assign each of them to the team that currently has the lower score.
Both approaches are implemented here, as an example:
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeMap;

public class MapSplit
{
    public static void main(String[] args)
    {
        TreeMap<Integer, Double> teamScoreMap = new TreeMap<Integer, Double>();
        teamScoreMap.put(1, 5.0);
        teamScoreMap.put(2, 8.4);
        teamScoreMap.put(3, 2.1);
        teamScoreMap.put(4, 6.5);
        teamScoreMap.put(5, 4.5);
        teamScoreMap.put(6, 3.2);
        teamScoreMap.put(7, 9.8);
        teamScoreMap.put(8, 7.6);

        solveOptimal(teamScoreMap);
        solveGreedy(teamScoreMap);
    }

    private static void solveOptimal(Map<Integer, Double> teamScoreMap)
    {
        List<Entry<Integer, Double>> entries =
            new ArrayList<Entry<Integer, Double>>(
                teamScoreMap.entrySet());

        double totalSum = computeSum(entries);
        ChoiceIterable<Entry<Integer, Double>> ci =
            new ChoiceIterable<Entry<Integer, Double>>(
                teamScoreMap.size() / 2, entries);

        List<Entry<Integer, Double>> bestTeam = null;
        double minError = Double.POSITIVE_INFINITY;
        for (List<Entry<Integer, Double>> team : ci)
        {
            double teamSum = computeSum(team);
            double error = Math.abs(teamSum - totalSum * 0.5);
            if (error < minError)
            {
                bestTeam = team;
                minError = error;
            }
        }

        Set<Entry<Integer, Double>> teamA =
            new LinkedHashSet<Entry<Integer, Double>>(bestTeam);
        Set<Entry<Integer, Double>> teamB =
            new LinkedHashSet<Entry<Integer, Double>>(
                teamScoreMap.entrySet());
        teamB.removeAll(teamA);

        System.out.println("Optimal result:");
        printResult(teamA, teamB);
    }

    private static void solveGreedy(Map<Integer, Double> teamScoreMap)
    {
        List<Entry<Integer, Double>> entries =
            new ArrayList<Entry<Integer, Double>>(
                teamScoreMap.entrySet());
        Collections.sort(entries, (e0, e1) ->
            Double.compare(e1.getValue(), e0.getValue()));

        Set<Entry<Integer, Double>> teamA =
            new LinkedHashSet<Entry<Integer, Double>>();
        double sumA = 0;
        Set<Entry<Integer, Double>> teamB =
            new LinkedHashSet<Entry<Integer, Double>>();
        double sumB = 0;

        for (Entry<Integer, Double> entry : entries)
        {
            if (sumA < sumB)
            {
                teamA.add(entry);
                sumA += entry.getValue();
            }
            else
            {
                teamB.add(entry);
                sumB += entry.getValue();
            }
        }

        System.out.println("Greedy result:");
        printResult(teamA, teamB);
    }

    private static void printResult(
        Collection<Entry<Integer, Double>> teamA,
        Collection<Entry<Integer, Double>> teamB)
    {
        System.out.println("Team A:");
        for (Entry<Integer, Double> entry : teamA)
        {
            System.out.println("  " + entry);
        }
        System.out.println("Sum: " + computeSum(teamA));

        System.out.println("Team B:");
        for (Entry<Integer, Double> entry : teamB)
        {
            System.out.println("  " + entry);
        }
        System.out.println("Sum: " + computeSum(teamB));
    }

    private static double computeSum(
        Collection<Entry<Integer, Double>> entries)
    {
        return entries.stream().map(
            e -> e.getValue()).reduce(0.0, (a,b) -> a+b);
    }

}

// From https://github.com/javagl/Combinatorics/blob/master/src/main/
// java/de/javagl/utils/math/combinatorics/CombinationIterable.java
class ChoiceIterable<T> implements Iterable<List<T>>
{
    private final List<T> input;
    private final int sampleSize;
    private final long numElements;
    public ChoiceIterable(int sampleSize, List<T> input)
    {
        this.sampleSize = sampleSize;
        this.input = input;
        BigInteger nf = factorial(input.size());
        BigInteger kf = factorial(sampleSize);
        BigInteger nmkf = factorial(input.size() - sampleSize);
        BigInteger divisor = kf.multiply(nmkf);
        BigInteger result = nf.divide(divisor);
        numElements = result.longValue();
    }

    public static BigInteger factorial(int n)
    {
        BigInteger f = BigInteger.ONE;
        for (int i = 2; i <= n; i++)
        {
            f = f.multiply(BigInteger.valueOf(i));
        }
        return f;
}
    @Override
    public Iterator<List<T>> iterator()
    {
        return new Iterator<List<T>>()
        {
            private int current = 0;
            private final int chosen[] = new int[sampleSize];
            // Initialization of first choice
            {
                for (int i = 0; i < sampleSize; i++)
                {
                    chosen[i] = i;
                }
            }

            @Override
            public boolean hasNext()
            {
                return current < numElements;
            }

            @Override
            public List<T> next()
            {
                if (!hasNext())
                {
                    throw new NoSuchElementException("No more elements");
                }

                List<T> result = new ArrayList<T>(sampleSize);
                for (int i = 0; i < sampleSize; i++)
                {
                    result.add(input.get(chosen[i]));
                }
                current++;
                if (current < numElements)
                {
                    increase(sampleSize - 1, input.size() - 1);
                }
                return result;
            }

            private void increase(int n, int max)
            {
                if (chosen[n] < max)
                {
                    chosen[n]++;
                    for (int i = n + 1; i < sampleSize; i++)
                    {
                        chosen[i] = chosen[i - 1] + 1;
                    }
                }
                else
                {
                    increase(n - 1, max - 1);
                }
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException(
                    "May not remove elements from a choice");
            }
        };
    }
}

(the class for computing the choices is taken from here)
The output is as follows:
Optimal result:
Team A:
  1=5.0
  4=6.5
  5=4.5
  8=7.6
Sum: 23.6
Team B:
  2=8.4
  3=2.1
  6=3.2
  7=9.8
Sum: 23.5
Greedy result:
Team A:
  2=8.4
  8=7.6
  1=5.0
  3=2.1
Sum: 23.1
Team B:
  7=9.8
  4=6.5
  5=4.5
  6=3.2
Sum: 24.0

showing that the greedy result is not the optimal one, but still rather good in this case.


text:
Q: Android app dev: Finding the best way to synchronize the timestamps of two sensors There's already a good answer on the technical details and constraints of timing the gyro measurement:
Movesense, timestamp source of imu data, and timing issues in general
However, I would like to ask more practical question from the Android app developer perspective working with two sensors and requirement for high accuracy with Gyro measurement timing.
What would be the most accurate way to synchronize/consolidate the timestamps from two sensors and put the measurements on the same time axis?
The sensor SW version 1.7 introduced Time/Detailed API to check the internal time stamp and the UTC time set on the sensor device. This is how I imagined it would play out with two sensors:

*

*Before subscribing anything, set the UTC time (microseconds) on the sensor1 and sensor2 based on Android device time (PUT /Time)

*Get the difference of the "Time since sensor turned on" (in milliseconds) and "UTC time set on sensor" (in microseconds) (on sensor1 and sensor2) (GET /Time/Detailed).

*Calculate the difference of these two timestamps (in milliseconds)(for both sensors).

*Get the gyro values from the sensor with the internal timestamp. Add the calculated value from step 3 to the internal timestamp to get the correct/global UTC time value.

Is this procedure correct?
Is there a more efficient or accurate way to do this? E.g. the GATT service to set the time was mentioned in the linked post as the fastest way. Anything else?
How about the possible drift in the sensor time for gyro? Are there any tricks to limit the impact of the drift afterwards? Would it make sense to get the /Time/Detailed info during longer measurements and check if the internal clock has drifted/changed compared to the UTC time?
Thanks!

A: Very good guestion!
Looking at the accuracy of the crystals (+- 20 ppm) it means that typical drift between sensors should be no more than 40 ppm. That translates to about 0.14 seconds over an hour. for longer measurements and or better accuracy, a better synchronization is needed.
Luckily the clock drift should stay relatively constant unless the temperature of the sensor is changing rapidly. Therefore it should be enough to compare the mobile phone clock and each sensor UTC at the beginning and end of the measurement. Any drift of each of sensors should be visible and the timestamps easily compensated.
If there is need to even more accurate timestamps, taking regular samples of /Time/Detailed from each sensor and comparing it to the phone clock should provide a way to estimate possible sensor clock drift.
Full Disclosure: I work for the Movesense team

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic form validation in AngularJS - Is there a better solution/approach? I am able to create a basic dynamic form validation for an AngularJS app. It's one of those combo box + input field forms example so that when I change the combo box, a new set of validation rule gets applied to the input field. To keep things simple for this example, I just used a variable maxlength that changes when I select a different criteria in the combo box. In my real app, I'm also using regex pattern but same concept, a different pattern gets applied on combo box change.
JSFiddle Example
var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', ['$scope', function($scope) {
      $scope.maxlength = 1;

      $scope.change = function() {
        if($scope.type==='LastName') {
          $scope.maxlength = 10;
        }
        else if($scope.type==='UserName') {
          $scope.maxlength = 6;
        }
      }
    }]);

My question is: is there a better solution than this?
I'm still new to Angular and currently learning how to do things the proper way. Currently, this serves my purpose, but I'm hoping any AngularJS experts out there can suggest a better solution than what I have. Thanks.

A: You could have an array of rules, and bind the values of the selected rules to the validation directives like this.

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', ['$scope',
  function($scope) {
    $scope.rules = [{
      name: 'UserName',
      maxLength: 6
    }, {
      name: 'FirstName',
      maxLength: 8
    }, {
      name: 'LastName',
      maxLength: 10
    }];
    $scope.selectedRule = $scope.rules[0];
    $scope.search = '';
  }
]);

  <form name="myForm" novalidate>
    <select ng-options="rule.name for rule in rules" ng-model="selectedRule">
      <option ng-repeat="rule in rules" value="{{rule}}">{{rule.name}}</option>
    </select>
    <input name="searchbox" ng-model="search" ng-maxlength="selectedRule.maxLength" />
  </form>
  <tt>input valid? = {{myForm.searchbox.$valid}}</tt>

  <tt>maxlength = {{selectedRule.maxLength}}</tt>

  <tt>type = {{selectedRule.name}}</tt>


text:
Q: java ldap connection pool timeout property not working as expected In java LDAP connection pooling, I have noticed that the pool timeout setting property is not working properly. Given below are the ldap connection pooling logs while testing my application.
Following are the values for initSize & pool timeout properties
com.sun.jndi.ldap.connect.pool.initsize = 10
com.sun.jndi.ldap.connect.pool.timeout = 300000
==================== LDAP LOGS ======================
21:38:48,480  Create com.sun.jndi.ldap.LdapClient@e2d0ca3
21:38:48,480  Create com.sun.jndi.ldap.LdapClient@4f652edf
21:38:48,495  Create com.sun.jndi.ldap.LdapClient@53bb2d84
21:38:48,558  Create com.sun.jndi.ldap.LdapClient@45766ee8
21:38:48,558  Create com.sun.jndi.ldap.LdapClient@703c62f5
21:38:48,573  Create com.sun.jndi.ldap.LdapClient@279dd5ca
21:38:48,589  Create com.sun.jndi.ldap.LdapClient@51c329b8
21:38:48,605  Create com.sun.jndi.ldap.LdapClient@7ec5afb0
21:38:48,605  Create com.sun.jndi.ldap.LdapClient@3e3659c6
21:38:48,620  Create com.sun.jndi.ldap.LdapClient@5bef29e1
21:38:48,620  Create and use com.sun.jndi.ldap.LdapClient@332bf735
21:38:50,102  Release com.sun.jndi.ldap.LdapClient@332bf735
21:41:05,661  Expired com.sun.jndi.ldap.LdapClient@e2d0ca3 expired
21:41:05,661  Expired com.sun.jndi.ldap.LdapClient@4f652edf expired
21:41:05,661  Expired com.sun.jndi.ldap.LdapClient@53bb2d84 expired
21:41:05,661  Expired com.sun.jndi.ldap.LdapClient@45766ee8 expired
21:41:05,662  Expired com.sun.jndi.ldap.LdapClient@703c62f5 expired
21:41:05,693  Expired com.sun.jndi.ldap.LdapClient@279dd5ca expired
21:41:05,693  Expired com.sun.jndi.ldap.LdapClient@51c329b8 expired
21:41:05,693  Expired com.sun.jndi.ldap.LdapClient@7ec5afb0 expired
21:41:05,693  Expired com.sun.jndi.ldap.LdapClient@3e3659c6 expired
21:41:05,709  Expired com.sun.jndi.ldap.LdapClient@5bef29e1 expired
21:46:05,724  Expired com.sun.jndi.ldap.LdapClient@332bf735 expired
When the application requested for a first LDAP connection, 10 new connections are created (as init size is set to 10) along with the requested connection. After the used connection is released back to pool, it is not expired after 5 mins and same is the case with other 10 connections. I am not sure why the ldap pool timeout property is not working properly as I am getting different behaviors (some times connections getting expired in 1 min) while testing the same scenario different times. Has any one has experienced the same kind of behavior and any resolution for this?

A: Finally, after breaking my head for while I understand that the connection pool timeout property is working as designed and I have interpreted this in a wrong way.
My first LDAP connection pool was created at 16:36:04. So, starting from that time the pool cleaning job will run every 5 minutes. So, lets say if new LDAP connections are created just few seconds or minutes before this scheduled job, they will be removed from the pool as part of the cleaning process. So, all the connections shown in the above log were expired at 21:41:05 even though they were created at 21:38:48.
So, don't expect that the LDAP connection will be removed from the pool only after 5 minutes of idle time.


text:
Q: How can I change for automated-backup retention count in AlloyDB? I tried to change for automated-backup retention count by gcloud command below.
gcloud alloydb clusters update XXXXXXXX\
    --automated-backup-days-of-week="MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY" \
    --automated-backup-start-times="18:00,19:00,20:00,21:00,22:00" \
    **--automated-backup-retention-count=2** \
    --region="XXXXXXXX \
    --project="XXXXXXXX"

I thought the backup would only leave 2 data, but all data was not deleted.
By the way, I was able to change the time to get the backup.
Therefore, the gcloud command is successful.
I read the documents for gcloud cmmand below.
https://cloud.google.com/sdk/gcloud/reference/alloydb/clusters/update
My result below.
12/27 Five backups remain.
12/28 Five backups remain.
12/29 Five backups remain.
12/30 Five backups remain.
12/31 Five backups remain.
1/1 Five backups remain.
1/2 Five backups remain.
1/3 Five backups remain.
enter image description here

A: Huge apologies, but you've hit a (now) known bug. We're tracking to fix it shortly, but the issue is with the count limited backups. The time-limited backups still work.
There's actually two issues currently. The first is that the count flag doesn't reduce the number of backups. The SECOND bug is that garbage collection is also not working as intended currently.
Backups older than their retention period might still appear when you view your project's backups. Expired backups don't incur storage costs, but they are subject to automatic deletion. If you need to delete backups before the system deletes them, you can manually delete your backups at any time.
In order to ensure that you're not incorrectly charged during this period, we will issue billing corrections for your impacted projects to negate or refund backup charges. If you see charges that aren't corrected, please reach out to support and we can get it sorted out.


text:
Q: Service state on resume Given a service that return START_STICKY from its onStartCommand:
1) The documentation mentions killing of the service, as far as I understand this, that is not done by calling Content.stopService, but done by the system if it needs resources (or my service could also crash which would be effectively the same - no clean shutdown) ?
2) How can I simulate the killing mentioned in 1) ? The killing is probably different from stopping (stoppping != killing ?) the service using the application menu in the settings, so I can't use this menu for testing purposes?
3) If my service is killed and then restarted, according to the documentation, only onStartCommand seems to be called, but not onCreate. So I conclude that variables of my service are persistet before my service gets killed? Or why does onCreate not get aclled? Or does it maybe?
My aim is to make sure that my service still works reliable when it was killed and restarted. Thanks for any hint :-)

A: Killing means its process being killed by the out of memory killer.  You can simulate this from the adb shell -- use "ps" to find your app's process, and "kill" with the found pid to kill it.  The system will after a few seconds restart the process and service.
If you are only receiving onStartCommand(), then your service and process was already running and didn't need to be re-created.

A: I had the same issue, and was wondering what is going on.
After reading the referenced post, I simply moved my code from onStartCommand(..) to onCreate(..) and it was working as expected.


text:
Q: Invalid command 'SSLOpenSSLConfCmd', perhaps misspelled or defined by a module not included in the server configuration Like every other admin, I"m working through the Logjam fix.
I've upgraded to Apache 2.4.12 and openssl 1.0.2a on my centos 6.6 box.
When I start apache, I'm seeing this error message returned:
Invalid command 'SSLOpenSSLConfCmd', perhaps misspelled or defined by a module not included in the server configuration

Here is my apache build info:
Server version: Apache/2.4.12 (Unix)
Server built:   Jun  8 2015 22:04:38
Server's Module Magic Number: 20120211:41
Server loaded:  APR 1.4.5, APR-UTIL 1.3.12
Compiled using: APR 1.4.5, APR-UTIL 1.3.12
Architecture:   64-bit
Server MPM:     worker
  threaded:     yes (fixed thread count)
    forked:     yes (variable process count)
Server compiled with....
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=256
 -D HTTPD_ROOT="/opt/installs/apache/2_4_12"
 -D SUEXEC_BIN="/opt/installs/apache/2_4_12/bin/suexec"
 -D DEFAULT_PIDLOG="logs/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"

mod_ssl is included in my httpd.conf:
LoadModule ssl_module modules/mod_ssl.so

What am I missing?

A: The SSLOpenSSLConfCmd is only available on httpd 2.4.8 later.
However, you may still generate and use your own DH params on earlier versions, as explained well here:

If you are using Apache with LibreSSL, or Apache 2.4.7 and OpenSSL 0.9.8a or later, you can append the DHparams you generated earlier to the end of your certificate file. The documentation for that is here and below:
Custom DH parameters and an EC curve name for ephemeral keys, can also be added to end of the first file configured using SSLCertificateFile. This is supported in version 2.4.7 or later. Such parameters can be generated using the commands openssl dhparam and openssl ecparam. The parameters can be added as-is to the end of the first certificate file. Only the first file can be used for custom parameters, as they are applied independently of the authentication algorithm type.

Just use cat to append the dhparams.pem to your certificate file:
cat dhparams.pem >> cert.pem

A: Per Apache doc - The set of available SSLOpenSSLConfCmd commands depends on the OpenSSL version (need) being used for mod_ssl (at least version 1.0.2 is required). For a list of supported command names, see the section Supported configuration file commands in the SSL_CONF_cmd(3) manual page for OpenSSL.
Verify the commands you are using with SSLOpenSSLConfCmd

A: SSLOpenSSLConfCmd directive available in httpd 2.4.8 (which was not released) and later, if using OpenSSL 1.0.2 or later.

Changes with Apache 2.4.8 (not released) ... mod_ssl: Add support for
  OpenSSL configuration commands by introducing
       the SSLOpenSSLConfCmd directive. [Stephen Henson, Kaspar Brand] ...

Build APR
# ./configure --host=x86_64-redhat-linux-gnu --build=x86_64-redhat-linux-gnu --prefix=/opt/apr-1.5.2 --with-devrandom=/dev/urandom

Build APR-UTIL
# ./configure --prefix=/opt/apr-util-1.5.4 --with-ldap --with-crypto --with-openssl=/opt/openssl-1.0.2a --with-apr=/opt/apr-1.5.2

Build Apache
# ./configure --prefix=/opt/httpd-2.4.12 --enable-mpms-shared=all --with-pcre --enable-mods-shared=all --enable-ssl --with-ssl=/opt/openssl-1.0.2a --with-apr=/opt/apr-1.5.2 --with-apr-util=/opt/apr-util-1.5.4 --enable-session-crypto
...
configure:
  setting INCLUDES to "-I."
  adding "-I$(top_srcdir)/os/$(OS_DIR)" to INCLUDES
  adding "-I$(top_srcdir)/include" to INCLUDES
  adding "-I/opt/apr-1.5.2/include/apr-1" to INCLUDES
  adding "-I/opt/apr-util-1.5.4/include/apr-1" to INCLUDES
  adding "-I/opt/openssl-1.0.2a/include" to INCLUDES
...

Check mod_ssl.so
# ldd mod_ssl.so | grep ssl
        libssl.so.1.0.0 => /opt/openssl-1.0.2a/lib/libssl.so.1.0.0 (0x00007f6f3c6bd000)
        libcrypto.so.1.0.0 => /opt/openssl-1.0.2a/lib/libcrypto.so.1.0.0 (0x00007f6f3c287000)

# strings mod_ssl.so | grep SSLOpenSSLConfCmd
SSLOpenSSLConfCmd
AH02407: "SSLOpenSSLConfCmd %s %s" failed for %s
AH02556: "SSLOpenSSLConfCmd %s %s" applied to %s

Check apache settings
# ./httpd -v
Server version: Apache/2.4.12 (Unix)
Server built:   Mar 27 2016 16:29:30

# ./httpd -V
Server version: Apache/2.4.12 (Unix)
Server built:   Mar 27 2016 16:29:30
Server's Module Magic Number: 20120211:41
Server loaded:  APR 1.5.2, APR-UTIL 1.5.4
Compiled using: APR 1.5.2, APR-UTIL 1.5.4
Architecture:   64-bit
Server MPM:     event
  threaded:     yes (fixed thread count)
    forked:     yes (variable process count)
Server compiled with....
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=256
 -D HTTPD_ROOT="/opt/httpd-2.4.12"
 -D SUEXEC_BIN="/opt/httpd-2.4.12/bin/suexec"
 -D DEFAULT_PIDLOG="logs/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"

# /opt/httpd-2.4.12/bin/apachectl -t
Syntax OK

Virtual host settings
# conf/extra/httpd-ssl.conf
Listen 443
SSLOpenSSLConfCmd DHParameters /etc/pki/httpd/dhparams_2048.pem
SSLCipherSuite kEECDH+AES128:kEECDH:kEDH:-3DES:kRSA+AES128:kEDH+3DES:DES-CBC3-SHA:!RC4:!aNULL:!eNULL:!MD5:!EXPORT:!LOW:!SEED:!CAMELLIA:!IDEA:!PSK:!SRP:!SSLv2
SSLHonorCipherOrder on
SSLPassPhraseDialog  builtin
SSLSessionCache "shmcb:/opt/httpd-2.4.12/logs/ssl_scache(512000)"
SSLSessionCacheTimeout  300
SSLProtocol All -SSLv2 -SSLv3

<VirtualHost _default_:443>

   DocumentRoot "/opt/httpd-2.4.12/htdocs"
   ServerName ssllabs.example.com:443
   ServerAdmin webmaster@example.com
   ErrorLog "/opt/httpd-2.4.12/logs/error_log"
   TransferLog "/opt/httpd-2.4.12/logs/access_log"

   SSLEngine on
   SSLCertificateFile /etc/pki/httpd/server.pem
   SSLCertificateKeyFile /etc/pki/httpd/server.key

   <FilesMatch "\.(cgi|shtml|phtml|php)$">
       SSLOptions +StdEnvVars
   </FilesMatch>
   <Directory "/opt/httpd-2.4.12/cgi-bin">
       SSLOptions +StdEnvVars
   </Directory>

   BrowserMatch "MSIE [2-5]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
   CustomLog "/opt/httpd-2.4.12/logs/ssl_request_log" "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>

Test result


text:
Q: Slideshow Gallery with PHP and Javascript Hi there I want to create Slideshow Gallery using PHP and Javascript.
I have a camera setup at my house that is sending picture in JPG format every time when motion is detected.
I want to be able when I visit:
camera.example.com/
Pictures from last 3 Days to start to appear in A slideshow fast.
The structure is like this:
camera.example.com
-snap (where the pictures from the camera are uploaded when motion is detected).

code of index.php:
<?

//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="snap") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo '
';
$curimage++;
}
}

closedir($handle);
}
return($files);
}

echo 'WHEN ALL OF THE PICTURES LOAD UP << CLICK ME >>

';
returnimages() //Output the array elements containing the image file names
?>

code of getimages.php:
<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");

//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="snap") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}

closedir($handle);
}
return($files);
}

echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>

code of: slideshow.php

<title>Timelapse</title>

Please help me with this, it doesn't neccesery have to be even my code.. all I want is to work so if someone gives me a better alternative it's fine.
I want to be able to view what happen on my Front yard during the past 3 days fast, without having to Open all pictures one by one.
I want them SORTED from the Newest to the Oldest.
I used the following tutorial to do this: Slideshow Gallery loading all images in directory
Thank you!

A: If you can edit the way your images are saved to date_something.jpg then you can use the following. You will have to work out how to place this into your own source code, I wouldn't want to do all the work for you.

*

*If it isn't possible for you to change the way image names are saved, please edit your question and display how your images are saved.

Date format: Year Month Day => 20150415
The following is going by today's date: 15th April 2015.
<?php
// Temporary Array of image names (demo use).
$ImageNames=array("20150415_one.jpg","20150414_two.jpg","20150413_three.jpg","20150412_four.jpg","20150411_five.jpg","20150410_six.jpg");
// Empty Array - To hold image names within date range
$ReturnImages=array();
// For each value in $ImageNames array
foreach ($ImageNames as $Image) {
// Split the image name to get the date
    $Uploaded=explode("_",$Image);
/*
$Uploaded[0] => Date
$Uploaded[1] => one.jpg / two.jpg / three.jpg
*/
// If image date is equal to or greater than.
    if($Uploaded[0]>=date('Ymd', strtotime('-3 day'))){
        array_push($ReturnImages, $Image);
    }
}
/* $ReturnImages now holds all the images within the date range (Last 3 days) */

//*********************************************************
// This foreach isn't required, this is to show the results
foreach ($ReturnImages as $display) {
echo $display.' ';
}
//*********************************************************
?>

Output: 20150415_one.jpg 20150414_two.jpg 20150413_three.jpg 20150412_four.jpg

20150411_five.jpg & 20150410_six.jpg will not return because the dates are more than 3 days old.
As you can see I have added comments to explain every step, if you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!


text:
Q: Proving a lemma for the irrationality of $e$ Define
$$I_n = \int_0^1 e^tt^ndt$$ where $n$ is a non-negative integer.
In a related question here, I asked how $e$ can be proven based on the following definitions and results:
$$I_{n+1} = e - (n + 1)I_n$$
$$I_n = (-1)^{n + 1}n! + e\sum_{r = 0}^n (-1)^r\frac{n!}{(n-r)!}$$
$$\frac{1}{n+1}\le I_n < \frac{e}{n} ~~~\text{for all $n \ge 1$}$$
The thing is, how would one go about proving the third inequality? I know that $e^{-1} = \sum_{k=0}^{n} \frac{(-1)^{k}}{k!}$ but I t doesn't seem to be of much use.

A: Notice that if $n \geq 1$, then $e^tt^n \leq e^1t^n$ for all $t \in [0, 1]$. This implies that:
$$\int_0^1 e^tt^ndt \leq e\int_0^1 t^ndt = \frac{e}{n+1} < \frac{e}{n}$$
Hence, $\displaystyle I_n < \frac{e}{n}$.


text:
Q: sed with literal string--not input file This should be easy:  I want to run sed against a literal string, not an input file.  If you wonder why, it is to, for example edit values stored in variables, not necessarily text data.
When I do:
sed 's/,/','/g' "A,B,C"

where A,B,C is the literal which I want to change to A','B','C
I get
Can't open A,B,C

As though it thinks A,B,C is a file.
I tried piping it to echo:
echo "A,B,C" | sed 's/,/','/g'

I get a prompt.
What is the right way to do it?

A: My version using variables in a bash script:
Find any backslashes and replace with forward slashes:
input="This has a backslash \\"

output=$(echo "$input" | sed 's,\\,/,g')

echo "$output"

A: You have a single quotes conflict, so use:
 echo "A,B,C" | sed "s/,/','/g"

If using bash, you can do too (<<< is a here-string):
sed "s/,/','/g" <<< "A,B,C"

but not
sed "s/,/','/g"  "A,B,C"

because sed expect file(s) as argument(s)
EDIT:
if you use ksh or any other ones :
echo string | sed ...

A: Works like you want:
echo "A,B,C" | sed s/,/\',\'/g


text:
Q: How do Markov Chains work and what is memorylessness? How do Markov Chains work? I have read wikipedia for Markov Chain, But the thing I don't get is memorylessness. Memorylessness states that:

The next state depends only on the current state and not on the
  sequence of events that preceded it.

If Markov Chain has this kind of property, then what is the use of chain in markov model?
Explain this property.

A: You can visualize Markov chains like a frog hopping from lily pad to lily pad on a pond. The frog does not remember which lily pad(s) it has previously visited. It also has a given probability for leaping from lily pad Ai to lily pad Aj, for all possible combinations of i and j. The Markov chain allows you to calculate the probability of the frog being on a certain lily pad at any given moment.
If the frog was a vegetarian and nibbled on the lily pad each time it landed on it, then the probability of it landing on lily pad Ai from lily pad Aj would also depend on how many times Ai was visited previously. Then, you would not be able to use a Markov chain to model the behavior and thus predict the location of the frog.

A: The idea of memorylessness is fundamental to the success of Markov chains. It does not mean that we don't care about the past. On contrary, it means that we retain only the most relevant information from the past for predicting the future and use that information to define the present.
This nice article provides a good background on the subject
http://www.americanscientist.org/issues/pub/first-links-in-the-markov-chain
There is a trade-off between the accuracy of your description of the past and the size of the associated state space. Say, there are three pubs in the neighborhood and every evening you choose one. If you choose those pubs randomly, this is not a Markov chain (or a trivial, zero-order one) – the outcome is random. More precisely, it is an independent random variable (modeling dependency was fundamental to Markov ideas underlying Markov chains).
In your choice of pubs you can factor in your last choice, i.e., which pub you went to the night before.  For example, you might want to avoid going to the same pub two days in a row.  While in reality this implies remembering where you have been yesterday (and thus remembering the past!), at your modeling level, your unit of time is one day, so your current state is the pub you went to yesterday. This is your classical  (first-order) Markov model with three states and 3 by 3 transition matrix that provides conditional probabilities for each permutation (if yesterday you went to pub I, what is the change that today you "hop" to pub J).
However, you can define a model where you "remember" the last two days. In this second-order Markov model "present" state will include the knowledge of the pub from last night and from the night before.  Now you have 9 possible states describing your present state, and therefore you have a 9 by 9 transition matrix.  Thankfully, this matrix is not fully populated.
To understand why, consider a slightly different setup when you are so well-organized that you make  firm plans for your pub choices both for today and tomorrow based on the last two visits. Then, you can select any possible permutations of pubs visited for two days in a row.  The result is a fully populated 9 by 9 matrix that maps your choices for the last two days into those for the next two days. However, in our original problem we make the decision every day, so our future state is constrained by what happened today: at the next time step (tomorrow) today becomes yesterday, but it will be still a part of your definition of "today" at that time step, and relevant to what happens the following day. The situation is analogous to moving averages, or receding horizon procedures. As a result, from a given state, you can only move to three possible states (indicating your today's choice of pubs), which means that each row of your transition matrix will have only three non-zero entries.
Let us tally up the number of parameters that characterize each problem: the zero- order Markov model with three states has two independent parameters (probabilities of hitting the first and the second pub, as the probability of visiting the third pub is the complement of the first two).  The first-order Markov model has a fully populated 3 by 3 matrix with each column summing up to one (again, indicating that one of the pubs will always be visited at any given day), so we end up with six independent parameters. The second-order Markov model has 9 by 9 matrix with each row having only 3 non-zero entries and all columns adding to one, so we have 18 independent parameters.
We can continue defining higher-order models, and our state space will grow accordingly.
Importantly, we can further refine the concept by identifying important features of the past and use only those features to define the present, i.e. compress the information about the past. This is what I referred to in the beginning. For example, instead of remembering all history we can only keep track only of some memorable events that impact our choice, and use this "sufficient statistics" to construct the model.
It all boils down to the way you define relevant variables (state space), and the Markov concepts naturally follow from the underlying fundamental mathematics concepts.  First-order (linear) relationships (and associated linear algebra operations) are at the core of most current mathematical applications. You can look at a polynomial equation on n-th with a single variable, or you can define an equivalent first-order (linear) system of n equations by defining auxiliary variables. Similarly, in classical mechanics you can either use second-order Lagrange equations or choose canonical coordinates that lead to (first-order) Hamiltonian formulation http://en.wikipedia.org/wiki/Hamiltonian_mechanics
Finally, a note on the steady-state vs. transient solutions of Markov problems. An overwhelming amount of practical applications (e.g., Page rank) relies on finding steady-state solutions.  Indeed, the presence of such convergence to a steady state was the original motivation for A. Markov for creating his chains in an effort to extend the application of central limit theorem to dependent variables. The transient effects (such as hitting times) of Markov processes are significantly less studied and more obscure. However, it is perfectly valid to consider Markov prediction of the outcomes at the specific point in the future (and not only the converged, "equilibrium" solution).


text:
Q: How to press the keys on keyboard without using keyboard in Objective-C? I want my program to press certain keys on my keyboard without me doing it physically.
for example, button in my app for (command + UP) if user press the button, my app will do same thing in the keyboard .
How i do this?

A: I'm assuming that you have a function that will be triggered when the user presses the command + up keys. So to illustrate:
  command + up ---> call function

And you are asking is there a way to:
  click a button ---> somehow trigger command + up event ---> call function

But why not you just do:
  click a button ---> call function

Much simpler and more straight-forward. Is there any specific reason you still need the command + up event triggered?

A: I am assuming it is that you have linked a menu item to an IBAction IN Interface Builder and given it a short cut of command+ up. If so just link your button to the same action
edit*
Have a look at these.
Xcode 4 xcode_help-interface_builder help including video examples
xcode 3 - Interface Builder User Guide pdf  look at chapter 7.
( I could not find the guide on apples site, it all points to v4?)


text:
Q: REST PUT create or update I want to create or update an item in one go with the following request:
PUT /items/{id}

Should I return 201 Created if the item has been created and 204 No Content when it has been updated? Or should I return the same status for both actions?

A: The answer is clearly stated in RFC2616, section 9.6:
If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

A: TL;DR
Use 200 OK in both cases if the distinction isn't important to clients.
Use 201 Created upon creation, and 200 OK upon update, if the distinction is important.
Details
With RESTful design, there's no single, correct way of doing things, but I've often found that the original HTTP status code specification provides good guidance.
It's always fine to return 200 OK if you don't expect the client to take separate action based on the response, but you can provide more information if you think the client is going to need it. Just be aware that clients may come to expect that of your API, so once you start providing more details, you can't easily change your mind.
That said, if you want to return 201 Created, then according to the specification:

The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate.

As an example, you can put the location in the Location header, but you can also put it in the body of the response (but then you must document the structure and content-type of that body).
When it comes to 204 No Content responses, they create dead ends for link-following clients, so if you're creating a true level 3 REST API then you should avoid that response type as a courtesy to clients.


text:
Q: Radio Button is not selected with GET Request Django FormModel Radio button Django is getting rendered in the form but the problem is when I try to get the selected Radio Button. It isn't selecting as per the value in the database. It just shows to select from the Radio Button
I am able to POST but not GET.
Model.py
class myModel(models.Model):
   STATUS_CHOICES = [(1, 'Ok'), (2, 'Not Ok')]
   left_leg = models.BooleanField(choices=STATUS_CHOICES,
                                     default=1,
                                     null=True)

forms.py
class myModelForm(forms.ModelForm):
  class Meta:
   model = myModel
   fields = ('left_leg')
   widgets = {'left_leg': forms.RadioSelect}

views.py
  def myview(request, pk):
      aa =  myModel.objects.get(pk=pk)
      if request.method == 'POST':
         form = myModelForm(request.POST, instance=aa)
    if form.is_valid():
        form.save()
        return redirect("/")
else:
    context = {'form': form}
    return render(request, "aa.html", context)

aa.html

         {{ form.left_leg.errors }}
               {% for choice in form.left_leg%}
                   {{ choice }}
               {% endfor %}

url.py
path('path/update/<int:pk>/',
     myView,
     name='xx'),

Please help

A: Choice must be True and False instead of 1 and 0


text:
Q: can you bind 2 way communication to a redux variable? Forgive the newbish nature of this question.  Just learning react native and redux with react native
I have a redux store built and running in a react native app.  I can store and get values and such, but i have a question.
Say i have a img filename string value for save profile avatar.  I bind it to an avatar source and say in the update profile screen I update my avatar, save it to the database as well as update it redux value which is where the avatar source is getting the file name.  Is there a way or methodology that i can use so that when the redux value changes, the avatar change as well to reflect the update.
Again, im very new to react and react native as a whole, and this may just be easy to accomplish, im just learning.
Thanks

A: You can only update your redux store with the help of Redux actions and reducers.
To get access to the redux store in any of your component, you need to connect to redux store using High order component connect
Your component will update once your component state or props are changed.
So to update your avatar inside your component you must be passing it as a prop.
If you are doing these things correctly then after updating your redux store your component will definitely be receiving updated props.
Let me give you one example -
const mapStateToProps = (state) => ({
  user: state.user,
  data: state.data
});

export default connect(mapStateToProps)(Post);

In the above example, mapStateToProps is used to map data inside the store to the local component as props.
So in above example whenever user and data are updated in the redux store, it will be going to update the post component with updated values of user and data.
Note here is that you can pass these props to as many components as you want and all will get updated values through props once store is updated.
Reference -
https://react-redux.js.org/api/connect
https://react-redux.js.org/using-react-redux/connect-mapdispatch


text:
Q: GridSplitter not working after applying an animation to a grid column I'm a beginner in wpf, today I come across an odd issue that the gridsplitter stops working if I add an animation to a grid column, below is the code snippet, it's a meaningless but quite simply test code, it does nothing except when the mouse enters the right column, the width of it will expand from 15 to 100
    <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Name="c1"/>
        <ColumnDefinition Name="c2" Width="15" MinWidth="15"/>
    </Grid.ColumnDefinitions>
    <Border Grid.Column="0" Background="Gray"></Border>
    <GridSplitter Width="8" Background="Yellow"></GridSplitter>
    <Border Grid.Column="1" Background="Silver" Name="bdRight" MouseEnter="bdRight_MouseEnter"></Border>
</Grid>

and this:
        bool flag = true;
    private void bdRight_MouseEnter(object sender, MouseEventArgs e)
    {
        if (flag)
        {
            flag = false;
            var da = new GridLengthAnimation();
            da.From = new GridLength(c2.MinWidth);
            da.To = new GridLength(100);
            var ef = new BounceEase();
            ef.EasingMode = EasingMode.EaseOut;
            da.EasingFunction = ef;
            this.c2.BeginAnimation(ColumnDefinition.WidthProperty, da);
        }
    }

and here's the GridLengthAnimation, I get it from internet after I find that DoubleAnimation cannot be used against the width of grid column.
public class GridLengthAnimation : AnimationTimeline
{
    public static readonly DependencyProperty FromProperty;
    public static readonly DependencyProperty ToProperty;
    public static readonly DependencyProperty EasingFunctionProperty;

    static GridLengthAnimation()
    {
        FromProperty = DependencyProperty.Register("From", typeof(GridLength), typeof(GridLengthAnimation));
        ToProperty = DependencyProperty.Register("To", typeof(GridLength), typeof(GridLengthAnimation));
        EasingFunctionProperty = DependencyProperty.Register("EasingFunction", typeof(IEasingFunction), typeof(GridLengthAnimation));
    }

    protected override Freezable CreateInstanceCore()
    {
        return new GridLengthAnimation();
    }

    public override Type TargetPropertyType
    {
        get { return typeof(GridLength); }
    }

    public IEasingFunction EasingFunction
    {
        get
        {
            return (IEasingFunction)GetValue(GridLengthAnimation.EasingFunctionProperty);
        }
        set
        {
            SetValue(GridLengthAnimation.EasingFunctionProperty, value);
        }

    }

    public GridLength From
    {
        get
        {
            return (GridLength)GetValue(GridLengthAnimation.FromProperty);
        }
        set
        {
            SetValue(GridLengthAnimation.FromProperty, value);
        }
    }

    public GridLength To
    {
        get
        {
            return (GridLength)GetValue(GridLengthAnimation.ToProperty);
        }
        set
        {
            SetValue(GridLengthAnimation.ToProperty, value);
        }
    }

    public override object GetCurrentValue(object defaultOriginValue, object defaultDestinationValue, AnimationClock animationClock)
    {
        double fromValue = ((GridLength)GetValue(GridLengthAnimation.FromProperty)).Value;
        double toValue = ((GridLength)GetValue(GridLengthAnimation.ToProperty)).Value;

        IEasingFunction easingFunction = this.EasingFunction;

        double progress = (easingFunction != null) ? easingFunction.Ease(animationClock.CurrentProgress.Value) : animationClock.CurrentProgress.Value;

        if (fromValue > toValue)
        {
            return new GridLength((1 - progress) * (fromValue - toValue) + toValue, this.To.IsStar ? GridUnitType.Star : GridUnitType.Pixel);
        }
        else
        {
            return new GridLength((progress) * (toValue - fromValue) + fromValue, this.To.IsStar ? GridUnitType.Star : GridUnitType.Pixel);
        }
    }
}

If I comment out codes in the MouseEnter event handler, the splitter works fine, otherwise, it stops working. Any ideas?

A: You have to set the FillBehavior property of your animation. The default value is HoldEnd, which means that the animation holds the final value after it has ended. If you set FillBehavior to Stop the animated value will revert back to the value it had before beeing animated.
If you add the following lines to your event handler code, it should work as expected:
...
da.FillBehavior = FillBehavior.Stop;
c2.Width = da.To; // set final value before starting the animation
c2.BeginAnimation(ColumnDefinition.WidthProperty, da);

In case setting the final value before starting the animation creates a flickering effect, you may instead set the final value in a Completed handler:
...
da.FillBehavior = FillBehavior.Stop;
da.Completed += (s, e) => c2.Width = da.To;
c2.BeginAnimation(ColumnDefinition.WidthProperty, da);

A: Just to expand on the earlier answer (would comment but not allowed by the stackoverflow overmaster):
For me, setting the final value before kicking off the animation generates an ugly flicker effect for my grid a split second before the animation kicks in.
What I did was to use the FillBehavior.Stop mentioned above but subscribe to the Animation.Completed event and set the final height of the grid column in there.
Works like a charm without any flickering.


text:
Q: Pandas: Joining information from multiple data frames, array Suppose I have three data structures:

*

*A data frame df1, with columns A, B, C of length 10000

*A data frame df2, with columns A, some extra misc. columns... of length 8000

*A Python list labels of length 8000, where the element at index i corresponds with row i in df2.

I'm trying to create a data frame from this information that, for every element in df2.a, I grab the relevant row from df1 and labels to pair up this information. It's possible that an entry in df2.A is NOT present in df1.A.
Currently, I'm doing this through a for i in xrange(len(df2)) loop, checking if df2.A.iloc[i] is present in df1.A, and if it is, I store df1.A, df1.B, df1.C, labels[i] into a dictionary with the first element as the key and the rest of the elements as a list.
Is there a more efficient way to do this and store the outputs df1.A, df1.B, df1.C, labels[i] into a 4 columns dataframe? The for loop is really slow.
Sample data:
df1
A       B       C
'uid1'  'Bob'   'Rock'
'uid2'  'Jack'  'Pop'
'uid5'  'Cat'   'Country'
...

df2
A
'uid10'
'uid3'
'uid1'
...

labels
[label10, label3, label1, ...]

A: OK from what I understand the following should work:
# create a new column for your labels, this will align to your index
df2['labels'] = labels
# now merge the rows from df1 on column 'A'
df2 = df2.merge(df1, on='A', how='left')

Example:
# setup my sample data
temp="""A       B       C
'uid1'  'Bob'   'Rock'
'uid2'  'Jack'  'Pop'
'uid5'  'Cat'   'Country'"""

temp1="""A
'uid10'
'uid3'
'uid1'"""
labels = ['label10', 'label3', 'label1']
df1 = pd.read_csv(io.StringIO(temp), sep='\s+')
df2 = pd.read_csv(io.StringIO(temp1))

In [97]:
# do the work
df2['labels'] = labels
df2 = df2.merge(df1, on='A', how='left')
df2
Out[97]:
         A   labels      B       C
0  'uid10'  label10    NaN     NaN
1   'uid3'   label3    NaN     NaN
2   'uid1'   label1  'Bob'  'Rock'

This will be considerably faster than looping


text:
Q: SOAP error: java.net.SocketException:Unexpected end of file I am developing an application which need to call a SOAP service developed using SOAP 1.1.The service which I am calling is accepting the file url(file should be available on internet)and some other information related to file. This service copies the file from location and upload to internal file location. When I am trying to call the service with small files then my application is working fine but when I am trying to upload bigger files then I am getting error as
 com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl:
 com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send failed
 Caused by: java.net.SocketException: Unexpected end of file from server
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1926)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1921)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1920)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1490)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:269)

Below is piece of code which I am using to call the SOAP service.
 URL endpoint =
              new URL(new URL(host), service,
                      new URLStreamHandler() {
                        @Override
     protected URLConnection openConnection(URL url)throws IOException {
    URL target = new URL(url.toString());
    URLConnection connection =  target.openConnection();
    // Connection settings
     connection.setConnectTimeout(60000000*300);
     connection.setReadTimeout(60000000*300);

    connection.setRequestProperty("Content-Type",
 "application/soap+xml; charset=UTF-8");

   connection.setDoInput(true);
   connection.setDoOutput(true);

                          return(connection);
                        }
                      });
    System.out.println("endpoint.."+endpoint.toString());

    String ingestSoapRequest = NPSClientHelper.createIngestRequestString(mimixStr, renditionId, isMac, urlList);

    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    InputStream is = new ByteArrayInputStream(ingestSoapRequest.getBytes());
    SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);
    SOAPMessage soapResponse = soapConnection.call(request, endpoint);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    soapResponse.writeTo(out);

    soapConnection.close();

    String ingestResponse = new String(out.toByteArray());

Can someone please help me to fix this error.
Thanks in advance.


text:
Q: hermitian operators with the same spectra I want to prove that if two hermitian matrices say $H_1$ and $H_2$ have the same spectra, then one of them is conjugate of the other by some unitary matrix.
$$H_1 = U H_2 U^{\dagger}$$
Any idea?


text:
Q: htaccess rewrite all subdomain to index.php I know this question has been asked a lot but I don't know why it does not work for me :-?
this is my htaccess:
Options +FollowSymLinks
IndexIgnore */*
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteRule ^(.*)$ index.php

this code should rewrite any link with any path including any subdomain to index.php but it doesn't.
name of the domain also should not come into htaccess since it is unknown!!!
I call this htaccess from 127.0.0.1 and many websites are supposed to be linked into localhost:
/etc/hosts
127.0.0.1   localhost
127.0.1.1   mypc
127.0.0.1   google.com
127.0.0.1   example.com

here, my browser does browse google.com or example.com successfully while their subdomains such as sub1.google.com or sub1.example.com cannot be found.
index.php
<?php
$uri = 'http'. ($_SERVER['HTTPS'] ? 's' : null) .'://'. $_SERVER['HTTP_HOST'].$_SERVER[REQUEST_URI];
print_r($uri);
?>

does any one know how this .htaccess code does work for subdomains too?

A: If I understood your question right you are asking why google.com correctly loads index.php on the localhost but sub1.google.com etc. subdomains do not.
You cannot override subdomain DNS using the hosts file. To accomplish this you either need to add all the subdomains to the hosts file or set up a private DNS server with records for google.com and *.google.com pointing to 127.0.0.1.


text:
Q: Jsoup Hanging Without Errors I'm having an issue with Jsoup and hanging. I was testing Jsoup code, that was previously working, when out of nowhere it stopped working.  I haven't changed any of the code since about a week ago, and until now, it has been working.
I've been trying to hit Wikipedia's Main Page to scrape links off of it for a homework assignment.
It hangs without throwing me any errors, nor does the program move past the URL connection .get() method.  I waited about 10 minutes and still nothing happened.
Below is my code:
    private WikiPage pullData(String url, WikiPage parent) {
    WikiPage wp;
    try {

        String decodedURL = URLDecoder.decode(url, "UTF-8");
        Document doc = Jsoup.connect(decodedURL).get();
        Elements links = doc.select("a");
        Elements paragraphs = doc.select("p");
        Element t = doc.select("title").first();

        StringBuilder words = new StringBuilder();
        String title = t.text().replace(" - Wikipedia", "");

        paragraphs.forEach(e -> {
            words.append(e.text().toLowerCase());
        });

        wp = new WikiPage(url, title, parent);

        for (int i = 0; i < AMOUNT_LINKS; i++) {
            boolean properLink = false;
            while (!properLink) {
                //int rnd = R_G.nextInt(links.size());
                String a = links.get(i).attr("href");
                if (a.length() >= 5 && a.substring(0, 5).equals("/wiki") && containsChecker(a)) {
                    String BASE_URL = "https://en.wikipedia.org";
                    String decode = URLDecoder.decode(BASE_URL + a, "UTF-8");
                    wp.addChildren(decode);
                    properLink = true;
                }
            }
        }

        String[] splitWords = words.toString().replaceAll("[_$&+,:;=?@#|'<>.^*()%!\\[\\]\\-\"/{}]", " ").split(" ");
        for (String s : splitWords) {
            if (s.length() >= 1) {
                wp.addToWords(new WordCount(s, 1, 0));
            }
        }

        System.out.printf("%1$-10s %2$-45s\n", counter, title);
        counter++;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return wp;

}

Here is a screenshot after running the program for 10 minutes with a break point at Elements links = doc.select("a"); :
Before hitting the .get() method
Hanging for about 10 minutes
I can't seem to see where the issue lies, and I've even tried different websites, but it just does not work at all.
Thanks for the help!


text:
Q: No tests found. Cypress could not detect tests in this file I am working with Cypress and the cucumber plugin. When I try to run Cypress I keep getting
No tests found.
Cypress could not detect tests in this file

I am referencing another question regarding this error, but it was going into a missing a spec file which is not the problem here. I've imported the correct step definitions as per docs but it's not pointing to that either.
For now here is my file structure.
cypress -
    -integrations
        -BDD
           -ecommerce
              -ecommerce.spec.js
           - ecommerce.feature

In my cypress.json file

    "testFiles":  "**/*.js",
    "baseUrl": "https://localhost:17843/GfmAdminConsole/",
    "env":{
        "url":"https://rahulshettyacademy.com"
    },
    "reporter": "mochawesome"

}

and here is the code I am trying to run
import {Given,When,Then,And} from 'cypress-cucumber-preprocessor/steps'
import HomePage from "./HomePage"
import ProductPage from "./ProductPage"
import CheckOutPg from "./CheckOutPg"

/// <reference types="Cypress" />
Given('I open ECommerce Page',()=>{
    cy.visit("https://rahulshettyacademy.com/angularpractice/")
})

//When using hook to load data, use non-es6 syntax for a function.....might need to check if this was updated in later releases
When('I add items to Cart',function(){
    const homePage = new HomePage()
    const productPage = new ProductPage()
    homePage.getShopTab().click()

    testData.productName.forEach((product)=>{
        cy.selectProduct(product)
    })

    productPage.getCheckoutBtn().click()

})

And('Validate the total price of the items selected',()=>{
    let sum = 0
    let total;
    const checkOut = new CheckOutPg()
    checkOut.getItemPrices().each(($el,index,$list)=>{
        let price = $el.text().split(' ')[1].trim()
        sum = Number(sum) + Number(price);
    }).then(()=>{
        cy.log(sum)

    })
    checkOut.getTotal().then((el)=> {
        total =   el.text().split(' ')[1].trim()
        expect(Number(total)).to.eq(sum)
       })

})

Then('Select the country submit and verify Thank you',()=>{
    cy.get(':nth-child(6) > :nth-child(5) > .btn').click()
    cy.get('#country').type('United States')
    cy.wait(6000)
    cy.get('.suggestions > ul > li > a').click()
    cy.get('input[type="checkbox"]').check({force:true})
    cy.get('.ng-untouched > .btn').click()
    cy.get('.alert').then((el)=>{
        const text = el.text()
       expect(text.includes('Success')).to.be.true
    })
})

EDIT:
ecommerce.feature file
Feature: End to end Ecommerce validation

application Regression test
@focus
Scenario: Ecommerce products delivery

Given I open ecommerce page
When I add items to cart
And Validate the total prices
Then select the country submit and verify Thankyou

Any guidance would be appreciated and thank you in advance.

A: Check your cypress.json according to https://github.com/TheBrainFamily/cypress-cucumber-preprocessor#cypress-configuration there should be
"testFiles": "**/*.feature"

A:
No tests found.
Cypress could not detect tests in this file

I also got this error. I did 2 things to resolve it.

*

*I added "testFiles": "**/*.feature" to my cypress.json file, just like @lojza mentioned in their answer. Thanks, @lojza!

*I added a Scenario to my .feature file. Now my .feature file has this structure:
Feature: My awesome feature
    Background: Background name: Login to my awesome site
        Given I login to my awesome site
    Scenario: Add cool stuff. Then logout.
        Then I logout


text:
Q: HL7 - FN DataType inside XCN DataType? I'm taking a look in Caristix HL7 v2.5 - Segment PV1:

And when I click PV1.9 DataType it shows DataType fields:

In XCN.2 shows FN as DataType, and FN is not just a string:

So, how can I make an example of HL7 with PV1.9 having datatype XCN that has FN inside too? I don't get it
Trying to make an example
MSH|^~\&|SA|SF||R|201802201803^450||ADT^A01^ADT_A01|2018022018035210|P|2.2||||||
EVN|A01|201802201803|||SHE7|
PV1|1|E|||||||1^Surname&Own Surname Prefix&Own Surname&Surname Prefix From Partner/Spouse&Surname From Partner/Spouse^||||

But it seems like is not right :(

A: The XCN - Extended Composite ID Number and Name for Persons datatype holds identifier, name (separated by components) and some additional information. Note that most of the fields in datatype are O (optional), C (conditional) or B (for backward compatibility).
In XCN, as said above, you can hold XCN.2 - Family Name which holds the datatype FN - Family Name which is just a string.

This data type allows full specification of the surname of a person. Where appropriate, it differentiates the person's own surname from that of the person's partner or spouse, in cases where the person's name may contain elements from either name. It also permits messages to distinguish the surname prefix (such as "van" or "de") from the surname root.

So basically, its a string separated by components. Your value becomes something like below:
IdNumber^FamilyName^GivenName^SecondAndFurtherGivenNamesOrInitialsThereof^Suffix^Prefix

Your PV1 segment becomes something like below:
PV1|1|E|||||||IdNumber^FamilyName^GivenName^SecondAndFurtherGivenNamesOrInitialsThereof^Suffix^Prefix||||

You may further refer PV1 segment.
You are just confused due to deep hierarchy or nested datatypes. If you map those to your programming language, it becomes quite simple.

A: After testing the message with different parsers, the way HL7 works for subcomponents are like this:
MSH|^~\&|SA|SF||R|201802201803^450||ADT^A01^ADT_A01|2018022018035210|P|2.2||||||
EVN|A01|201802201803|||SHE7|
PV1|1|E|||||||1^Surname&Own Surname Prefix&Own Surname&Surname Prefix From Partner/Spouse&Surname From Partner/Spouse^||||

Using Subcomponent separator character (&)
Then, parsed items will be like this
PV1
 |- PV1.1
 |  |- SI
 |    |- 1
 |- PV1.2
 |  |- IS
 |    |- E
 |- PV1.9
 |  |- PV1.9.1
 |    |- ST
 |      |- 1
 |  |- PV1.9.2
 |    |- XCN
 |      |- Surname
 |      |- Own Surname Prefix
 |      |- Surname Prefix From Partner/Spouse
 |      |- Surname Form Partner/Spouse

That's right.


text:
Q: minimal even partition among the ones $\geq$ a given partition Let $N$ be an even integer. A partition of $N$ is a sequence $(a_1,a_2,\cdots, a_N)$ of integers such that $a_1 \geq a_2 \geq \cdots \geq a_N \geq 0$, and $\sum_{j=1}^Na_j =N$.
Let $\mathscr P_N$ be the set of partitions of $N$. A partition $\nu \in \mathscr P_N$ is said to be even if $\nu = (\nu_1,\nu_2,\cdots \nu_N)$ satisfy $\nu_i$ is even for $i=1,2,\cdots, N$.
The order "$\leq$" is defined as follows. Let $\nu^1 =(\nu^1_1,\nu^1_2,\cdots,\nu^1_N)$, $\nu^2=(\nu^2_1,\nu^2_2,\cdots,\nu^2_N) \in \mathscr P_N$. We say that $\nu^1 \leq \nu^2$ if $\sum_{j=1}^i \nu^1_j \leq \sum_{j=1}^i \nu^2_j$ for $i =1,2,\cdots,N$. (It is easy to notice that $\mathscr P_N$ has a unique maximal element, which is $(N,0,0,\cdots,0)$, and a unique minimal element, which is $(1,1,\cdots,1)$.)
Let $\lambda \in \mathscr P_N$. Let $$\Gamma =\{\nu \in \mathscr P_N | \lambda \leq \nu \text{ and } \nu \text{ is even}\}.$$
Then does $\Gamma$ always have a unique minimal element (under "$\leq$")? Is there any standard process for me to find a minimal element of $\Gamma$ from $\lambda$?
Thanks to everyone.

A: To find a minimal element:
For convenience, let $\lambda=(\lambda_1, \lambda_2,\cdots, \lambda_N).$
If $\lambda $ is itself even then it is a minimal element. Otherwise, at least one $\lambda_i $  is odd.  Since N is even, and $\sum_{i=1}^{N}{\lambda_i}=N$, number  of $\lambda_i $ which are odd, is even. Now to find the minimal element $m=(m_1, m_2,\cdots, m_N)$ from $\lambda $:
Step-1: Keep/Retain all the even $\lambda_i$ as such in $m .$
Step-2: Add 1 to the first odd $\lambda_j$ and subtract 1 from the immediate next odd $\lambda_k .$ Do this till all $\lambda_i' s $ become even.
Step-3: Rearrange the resulting values so that $m_1\geq m_2\geq....\geq m_N.$
Does it help you?


text:
Q: Select image file on custom layout page and and copy the file to installation folder My goal is for the user to use this installer, insert your name, select your language and set custom parameters. That is done. But what I need is that the user selects an image to put it as avatar in the application, that is why the user to select an image and then copy the file to the application folder.
Something like this:

This is my code, if anyone can help would greatly appreciate it:
[Code]
{ RedesignWizardFormBegin } // Don't remove this line!
// Don't modify this section. It is generated automatically.
procedure RedesignWizardForm;
begin
  with WizardForm.WizardSmallBitmapImage do
  begin
    Left := ScaleX(350);
    Width := ScaleX(150);
    Height := ScaleY(57);
  end;

  with WizardForm.PageDescriptionLabel do
  begin
    Width := ScaleX(309);
  end;

  with WizardForm.PageNameLabel do
  begin
    Width := ScaleX(293);
  end;

{ ReservationBegin }
  // This part is for you. Add your specialized code here.

{ ReservationEnd }
end;
// Don't modify this section. It is generated automatically.
{ RedesignWizardFormEnd } // Don't remove this line!

var
  NameEdit: TNewEdit;
  ParametresEdit: TNewEdit;
  LanguageCombo: TNewComboBox;
  LanguageNames: TStringList;

function ConvertLanguageName(const Value: string): string;
var
  I: Integer;
  WideCharCode: Word;
begin
  Result := '';
  I := 1;
  while I <= Length(Value) do
  begin
    if Value[I] = '<' then
    begin
      WideCharCode := StrToInt('$' + Copy(Value, I + 1, 4));
      I := I + 6;
    end
    else
    begin
      WideCharCode := Ord(Value[I]);
      I := I + 1;
    end;
    SetLength(Result, Length(Result) + 1);
    Result[Length(Result)] := Chr(WideCharCode);
  end;
end;

function GetLanguageName(const Value: string): string;
begin
  Result := LanguageNames[LanguageCombo.ItemIndex];
end;

function GetPlayerName(const Value: string): string;
begin
  Result := NameEdit.Text;
end;

function GetParametres(const Value: string): string;
begin
  Result := ParametresEdit.Text;
end;

procedure InitializeWizard;
var
  PlayerSettingsPage: TWizardPage;
  NameLabel: TLabel;
  LanguageLabel: TLabel;
  ParaLabel: TLabel;
  Info1Label: TLabel;
  Info2Label: TLabel;
  Info3Label: TLabel;
  Info4Label: TLabel;
  Info5Label: TLabel;
  Info6Label: TLabel;

  begin
  RedesignWizardForm;
  PlayerSettingsPage := CreateCustomPage(wpSelectComponents, 'Ingrese Datos', 'Informacón del juego');

  NameLabel := TLabel.Create(WizardForm);
  NameLabel.Parent := PlayerSettingsPage.Surface;
  NameLabel.Left := 0;
  NameLabel.Top := 0;
  NameLabel.Font.Style := [fsBold];
  NameLabel.Caption := 'Nombre';
  NameEdit := TNewEdit.Create(WizardForm);
  NameEdit.Parent := PlayerSettingsPage.Surface;
  NameEdit.Left := 0;
  NameEdit.Top := NameLabel.Top + NameLabel.Height + 4;
  NameEdit.Width := 180;

  ParaLabel := TLabel.Create(WizardForm);
  ParaLabel.Parent := PlayerSettingsPage.Surface;
  ParaLabel.Left := 0;
  ParaLabel.Top := 100;
  ParaLabel.Font.Style := [fsBold];
  ParaLabel.Caption := 'Parametros de Left 4 Dead 2';
  ParametresEdit := TNewEdit.Create(WizardForm);
  ParametresEdit.Parent := PlayerSettingsPage.Surface;
  ParametresEdit.Left := 0;
  ParametresEdit.Top := ParaLabel.Top + ParaLabel.Height + 4;
  ParametresEdit.Width := 180;

  Info1Label := TLabel.Create(WizardForm);
  Info1Label.Parent := PlayerSettingsPage.Surface;
  Info1Label.Left := 190;
  Info1Label.Top := 15;
  Info1Label.Font.Style := [fsBold];
  Info1Label.Caption := 'Introduzca su Nombre que se mostrara';

  Info2Label := TLabel.Create(WizardForm);
  Info2Label.Parent := PlayerSettingsPage.Surface;
  Info2Label.Left := 190;
  Info2Label.Top := 30;
  Info2Label.Font.Style := [fsBold];
  Info2Label.Caption := 'en el juego';

  Info3Label := TLabel.Create(WizardForm);
  Info3Label.Parent := PlayerSettingsPage.Surface;
  Info3Label.Left := 190;
  Info3Label.Top := 65;
  Info3Label.Font.Style := [fsBold];
  Info3Label.Caption := 'Selecciona tu Idioma';

  Info4Label := TLabel.Create(WizardForm);
  Info4Label.Parent := PlayerSettingsPage.Surface;
  Info4Label.Left := 190;
  Info4Label.Top := 120;
  Info4Label.Font.Style := [fsBold];
  Info4Label.Caption := '-console: Muestra la consola';

  Info5Label := TLabel.Create(WizardForm);
  Info5Label.Parent := PlayerSettingsPage.Surface;
  Info5Label.Left := 190;
  Info5Label.Top := 135;
  Info5Label.Font.Style := [fsBold];
  Info5Label.Caption := '-novid: Salta el intro del juego';

  Info6Label := TLabel.Create(WizardForm);
  Info6Label.Parent := PlayerSettingsPage.Surface;
  Info6Label.Left := 190;
  Info6Label.Top := 150;
  Info6Label.Font.Style := [fsBold];
  Info6Label.Caption := '-sw: Fuerza al juego en modo ventana';

  LanguageNames := TStringList.Create;
  #sub AddLanguageInternalNames
    #define GetLanguageInternalName(str S) \
      Local[0] = Copy(S, Pos("Name:", S) + Len("Name:")), \
      Local[1] = Copy(Local[0], Pos("""", Local[0]) + 1), \
      Copy(Local[1], 1, Pos("""", Local[1]) - 1)
    #emit '  LanguageNames.Add(''' + GetLanguageInternalName(LanguageList[LanguageIndex]) + ''');'
  #endsub
  #for {LanguageIndex = 0; LanguageIndex < LanguageCount; LanguageIndex++} AddLanguageInternalNames

  LanguageLabel := TLabel.Create(WizardForm);
  LanguageLabel.Parent := PlayerSettingsPage.Surface;
  LanguageLabel.Left := 0;
  LanguageLabel.Top := NameEdit.Top + NameEdit.Height + 8;
  LanguageLabel.Font.Style := [fsBold];
  LanguageLabel.Caption := 'Lenguaje';
  LanguageCombo := TNewComboBox.Create(WizardForm);
  LanguageCombo.Parent := PlayerSettingsPage.Surface;
  LanguageCombo.Left := 0;
  LanguageCombo.Top := LanguageLabel.Top + LanguageLabel.Height + 4;
  LanguageCombo.Width := NameEdit.Width;
  LanguageCombo.Style := csDropDownList;
  #sub AddLanguageDisplayNames
    #define GetLanguageDisplayName(str S) \
      ReadIni(S, "LangOptions", "LanguageName")
    #define GetLanguageFile(str S) \
      Local[0] = Copy(S, Pos("MessagesFile:", S) + Len("MessagesFile:")), \
      Local[1] = Copy(Local[0], Pos("""", Local[0]) + 1), \
      StringChange(Copy(Local[1], 1, Pos("""", Local[1]) - 1), "compiler:", CompilerPath)
    #expr LanguageName = GetLanguageDisplayName(GetLanguageFile(LanguageList[LanguageIndex]))
    #emit '  LanguageCombo.Items.Add(ConvertLanguageName(''' + LanguageName + '''));'
  #endsub
  #for {LanguageIndex = 0; LanguageIndex < LanguageCount; LanguageIndex++} AddLanguageDisplayNames
  LanguageCombo.ItemIndex := LanguageNames.IndexOf(ActiveLanguage);
end;

procedure DeinitializeSetup;
begin
  LanguageNames.Free;
end;

My code currently produce this page:

A: The easiest if to make use of the TInputFileWizardPage created using the CreateInputFilePage function. There's nothing preventing you from adding your custom controls to the "input file" page. You just have to alter the layout of the automatically added "file input" controls.
You will also need to change type of the PlayerSettingsPage variable and make it global, so that you can access the values entered by the user outside of the InitializeWizard function.
// global variables
var
  PlayerSettingsPage: TInputFileWizardPage;
  AvatarIndex: Integer;

procedure InitializeWizard;
var
  Delta: Integer;
  ... // your other variables but not the PlayerSettingsPage
begin
  PlayerSettingsPage :=
    CreateInputFilePage(
      wpSelectComponents, 'Ingrese Datos', 'Informacon del juego', '');

  // Your existing code

  AvatarIndex :=
    PlayerSettingsPage.Add(
      'Avatar:', 'Image files|*.png;*.jpg;*.jpeg;*.gif|All files|*.*', '.jpg');
  Delta :=
    ParametresEdit.Top + ParametresEdit.Height + ScaleY(32) -
    PlayerSettingsPage.PromptLabels[AvatarIndex].Top;

  PlayerSettingsPage.PromptLabels[AvatarIndex].Top :=
    PlayerSettingsPage.PromptLabels[AvatarIndex].Top + Delta;
  PlayerSettingsPage.Edits[AvatarIndex].Top :=
    PlayerSettingsPage.Edits[AvatarIndex].Top + Delta;
  PlayerSettingsPage.Buttons[AvatarIndex].Top :=
    PlayerSettingsPage.Buttons[AvatarIndex].Top + Delta;
end;

Then install the selected avatar in the CurStepChanged(ssPostInstall):
procedure CurStepChanged(CurStep: TSetupStep);
var
  AvatarSource: string;
  AvatarDest: string;
begin
  if CurStep = ssPostInstall then
  begin
    AvatarSource := PlayerSettingsPage.Edits[AvatarIndex].Text;
    AvatarDest := ExpandConstant('{app}\' + ExtractFileName(AvatarSource));
    Log(Format('Installing avatar from "%s" to "%s"', [AvatarSource, AvatarDest]));
    if FileCopy(AvatarSource, AvatarDest, False) then
    begin
      Log('Avatar installer');
    end
      else
    begin
      Log('Error installing avatar');
    end;
  end;
end;


text:
Q: vb.net / events? I have a DataGridView and sometimes I use the CellValueChanged Event but othertime I don't want it to trigger. Is there a way that I can remove an event sub and then restore it.
I have 5 columns with a ComboBox. After licking one, and then another, the line bellow keeps repeating until stack crashes
 Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) _
                Handles DataGridView1.EditingControlShowing
        Try
            Debug.Print("entered the EditingControlShowing")
            Dim ColName As String = Me.DataGridView1.Columns(Me.DataGridView1.CurrentCell.ColumnIndex).Name
            If ColName = "Col1" Or ColName = "Col2" Or ColName = "Col3" Or ColName = "Col4" Or ColName = "Col5" Then

                'the column you want to cast
                Dim cmb As ComboBox = TryCast(e.Control, ComboBox)
                RemoveHandler cmb.SelectedIndexChanged, AddressOf cmb_SelectedIndexChanged
                AddHandler cmb.SelectedIndexChanged, AddressOf cmb_SelectedIndexChanged
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Sub cmb_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Debug.Print("about to update cell") <<===== this line just repeats until stack crashes
            Me.DataGridView1.Rows(Me.DataGridView1.CurrentRow.Index).Cells(Me.DataGridView1.CurrentCell.ColumnIndex).Value = CType(sender, ComboBox).SelectedItem
            UpdateAvgColumn(Me.DataGridView1.CurrentRow.Index)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Sub UpdateAvgColumn(ByVal r As Integer)
        Dim avg As Single = 0.0
        Debug.Print("UpdateAvgColumn")
        If CInt(Me.DataGridView1.Rows(r).Cells("Col1").Value) <> 0 And CInt(Me.DataGridView1.Rows(r).Cells("Col2").Value) <> 0 And _
            CInt(Me.DataGridView1.Rows(r).Cells("Col3").Value) <> 0 And CInt(Me.DataGridView1.Rows(r).Cells("Col4").Value) <> 0 And _
            CInt(Me.DataGridView1.Rows(r).Cells("Col5").Value) <> 0 Then
            avg = CSng((CInt(Me.DataGridView1.Rows(r).Cells("Col1").Value) + CInt(Me.DataGridView1.Rows(r).Cells("Col2").Value) + _
                        CInt(Me.DataGridView1.Rows(r).Cells("Col3").Value) + CInt(Me.DataGridView1.Rows(r).Cells("Col4").Value) + _
                            CInt(Me.DataGridView1.Rows(r).Cells("Col5").Value)) / 5)
        End If
        Me.DataGridView1.Rows(r).Cells("AvgCol").Value = avg
    End Sub

A: Yes, you can remove event handlers, by using RemoveHandler method. But the better approach will be validate the condition in the event and do process or ignore.


text:
Q: extracting diagonals (sideway down) from 5d matrices using einsum I only managed to extract one diagonal using Numpy einsum. How do I get the other diagonals like [6, 37, 68, 99] with help of einsum?
x =  np.arange(1, 26 ).reshape(5,5)
y =  np.arange(26, 51).reshape(5,5)
z =  np.arange(51, 76).reshape(5,5)
t =  np.arange(76, 101).reshape(5,5)
p =  np.arange(101, 126).reshape(5,5)

a4 = np.array([x, y, z, t, p]

Extracting one diagonal:
>>>np.einsum('iii->i', a4)
>>>[  1  32  63  94 125]

A: I don't have any "easy" solution using einsum but it is quite simple with a for loop:
import numpy as np

# Generation of a 3x3x3 matrix
x =  np.arange(1 , 10).reshape(3,3)
y =  np.arange(11, 20).reshape(3,3)
z =  np.arange(21, 30).reshape(3,3)

M = np.array([x, y, z])

# Generation of the index
I = np.arange(0,len(M))

# Generation of all the possible diagonals
for ii in [1,-1]:
    for jj in [1,-1]:
        print(M[I[::ii],I[::jj],I])

# OUTPUT:
# [ 1 15 29]
# [ 7 15 23]
# [21 15  9]
# [27 15  3]

We fix the index of the last dimension and we find all the possible combinations of backward and forward indexing for the other dimensions.

A: Do you realize that this einsum is the same as:
In [64]: a4=np.arange(1,126).reshape(5,5,5)
In [65]: i=np.arange(5)
In [66]: a4[i,i,i]
Out[66]: array([  1,  32,  63,  94, 125])

It should be easy to tweak the indices to get other diagonals.
In [73]: a4[np.arange(4),np.arange(1,5),np.arange(4)]
Out[73]: array([ 6, 37, 68, 99])

That `iii->i' producing the main diagonal is more of an happy accident than a designed feature.  Don't try to push it.


text:
Q: All values become the same when using stdClass() in a for loop I have a function getComment below. Problem with this function is that
$test->TestComments[$type] will all contain the same values, namley the last comment made together with its username and timestamp.
public function getComment($test) {
    $Id = $test->Id;
    $localComment = new stdClass();
    $queryComment = $this->getResultCommentQuery($Id);
    $result = odbc_exec($this, $queryComment);
    $no_results = odbc_num_rows($result);

    for ($i = 1; $i <= $no_results; $i++) {
        odbc_fetch_row($result, $i);
        $type = trim(odbc_result($result, "result"));
        $localComment->Comment = trim(odbc_result($result, "comment"));
        $localComment->Username = trim(odbc_result($result, "username"));
        $localComment->Timestamp = trim(odbc_result($result, "timestamp"));
        $test->TestComments[$type] = $localComment;//there are no unique
 //values here, every comment will have the same "timestamp", "comment", and "username", namley the last one.
echo($localComment->Comment);//If I do this I see that there are different values.
        }
        return $test; //But this will only contain a correct nr of array attributes with same content (last comment info), see bellow.
    }

For example what I get.
    TestComments":{"Pay":{"Comment":"Test","Username":"en","Timestamp":"2014-08-01 14:27:41.410"},
"Peak":{"Comment":"Test","Username":"en","Timestamp":"2014-08-01 14:27:41.410"}}

That is I get the same content twice instead of 2 rows with different values. Anyone see what might be wrong?
Thanks in advance.

A: Your problem is the use of
$test->TestComments[$type] = $localComment;

This is not doing what you think. It is actually copying a reference to the object to $test->TestComments[$type] and not the contents of the object itself.
So as you only have one actual $localComment object all of these references are pointing to that one object which will contain whatever was last placed into the object.
What you actually want to do is CLONE the object, which creates a copy of the object and not just assigns a reference to the original object.
So change this line
$test->TestComments[$type] = $localComment;

To
$test->TestComments[$type] = clone $localComment;

and your existing code should work as you expect.


text:
Q: PDO/MySQL - unable to use parameter for column I want to search my table based on user input for 1) searchtype and 2) query. searchtype will be the column selected (so searching by name, rating, location etc.)
My code is:
$pdo = new PDO('mysql:host=localhost;dbname=assignment','admin', 'puppies');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $result = $pdo->prepare('SELECT * FROM `profs` WHERE :searchtype LIKE :query');
    $result->bindValue(':searchtype', $_GET['searchtype']);
    $result->bindValue(':query', "%" . $_GET['query'] . "%");
    $result->execute();
    $result->debugDumpParams();
    } catch (PDOException $e) {
        echo $e->getMessage();
    }

    echo "
";
    foreach ($result as $record) {
        echo "
", $record['name'], '	';
        echo "", $record['school'], "	";
        echo "", $record['subject'], "	";
        echo "", $record['latitude'], ",", $record['longitude'], "
";
    }
    echo '
';

I know for sure that the problem is with searchtype. If I directly replace :searchtype with name in the prepare statement, my code works as planned. In the bindValue statement, I've even directly replaced  $_GET['searchtype'] with name, '"' . name . '"', and every other permutation I can think of.

A: Okay, we start with point that binding column names is not allowed. (Table names too, btw).
Going further, I don't think you need switch. You can define some whitelist of fields (yes, even if you have fields via select it is still vulnerable, cause I can change your <select> to my <input> with same name).
So, use a whiltelist, some basic code is:
$allowed_fields = ['field1', 'field2', 'field3'];  // whitelist here
if (in_array($_GET['searchtype'], $allowed_fields)) {
    $result = $pdo->prepare('SELECT * FROM `profs` WHERE ' . $_GET['searchtype'] . ' LIKE :query');
    $result->bindValue(':query', "%" . $_GET['query'] . "%");
    $result->execute();
    $result->debugDumpParams();
} catch (PDOException $e) {
    echo $e->getMessage();
}

A: You can not bind column name
And it is bad idea to $_GET column name, use switch


text:
Q: Find the Laurent series about $z_0=0$ for the following function, valid in the indicated regions. $$\frac{1}{z-1} - \frac{1}{z+1}, \qquad 2<|z|<\infty$$
I am not sure how to approach this question. Can anyone help me with this question?
Thank you.

A: Assuming you meant for $|z| > 2$ (and so $\frac{1}{|z|} < \frac{1}{2} < 1$):
$\frac{1}{z+1} = \frac{1}{z} \frac{1}{1+\frac{1}{z}} = \frac{1}{z} (1-\frac{1}{z} + \frac{1}{z} - \cdots)$.
Similarly for the other term.


text:
Q: why run exec command? What is the reason for this error? I dont understand . Command runs two pods but not running ubuntu pod?
vagrant@vagrant:~$ kubectl get po
NAME                   READY     STATUS    RESTARTS   AGE
cassandra-2p4m0        0/1       Running   1          1d
k8s-master-127.0.0.1   3/3       Running   6          1d
nginx-app-6q4cn        1/1       Running   0          1h
nginx-i3bja            1/1       Running   4          1d
ubuntu-app-nuuyh       0/1       Running   11         1h
vagrant@vagrant:~$ kubectl exec -ti cassandra-2p4m0  -- /bin/sh
# ls
bin     dev   kubernetes-cassandra.jar  media  proc  run.sh   srv  usr
boot        etc   lib           mnt    root  sbin     sys  var
cassandra_data  home  lib64         opt    run   selinux  tmp
# exit
vagrant@vagrant:~$ kubectl exec -ti nginx-i3bja -- /bin/sh
# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
# exit
vagrant@vagrant:~$ kubectl exec -ti ubuntu-app-nuuyh -- /bin/sh
error: Error executing remote command: Error executing command in container: container not found ("ubuntu-app")

A: The answer is already in the comments. The 11 restarts in the "get pods" output indicates that your container is repeatedly crashing. You can't exec into a dead container.
Look at the logs using "kubectl logs --previous ubuntu-app-nuuyh" to determine why if "kubectl get pod -o yaml ubuntu-app-nuuyh" doesn't provide enough information.


text:
Q: Inequality with Fibonacci numbers $ \sum \limits_{k=1}^{2n+1} (-1)^{k+1} F_k \: \text{arccot} F_k < \frac{\pi+1-\sqrt{5}}{2}$
Prove that $$ \sum \limits_{k=1}^{2n+1} (-1)^{k+1} F_k \: \text{arccot} F_k < \frac{\pi+1-\sqrt{5}}{2}$$ holds for all $n \in \mathbb{N}$.
(The Fibonacci sequence, defined by the recurrence $F_1 = F_2 = 1$ and $\forall n \in \mathbb{N},$ $F_{n+2} = F_{n+1} + F_n$)

My work. I proved that the sequence $a_n=\sum \limits_{k=1}^{2n+1} (-1)^{k+1} F_k \: \text{arccot} F_k \;$ is increasing. Therefore inequality cannot be proved by induction.

A: Not a full answer.
Let's group even and odd terms in the sum:
$$S_n=\sum_{k=1}^{2n+1} (-1)^{k+1} F_k   \operatorname{arccot} F_k= \\ = \sum_{l=0}^{n-1} (F_{2l+1} \operatorname{arccot} F_{2l+1}-F_{2l+2} \operatorname{arccot} F_{2l+2}) +F_{2n+1} \operatorname{arccot} F_{2n+1}$$
It's easy to prove that $F_{2n+1} \operatorname{arccot} F_{2n+1} < 1$ and:
$$\lim_{n \to \infty} F_{2n+1} \operatorname{arccot} F_{2n+1}=1$$
So we only need to find the limit for the rest of the sum.
Denote:
$$P_n=\sum_{l=0}^{n-1} (F_{2l+1} \operatorname{arccot} F_{2l+1}-F_{2l+2} \operatorname{arccot} F_{2l+2})$$
The first terms is $0$, it's easy to check. Also, this sum converges to a single limit, so we can denote:

$$P=\sum_{l=1}^\infty  \left(F_{2l+1} \arctan \frac{1}{ F_{2l+1} } -F_{2l+2} \arctan \frac{1}{ F_{2l+2} } \right)$$

We need to prove that ($\varphi$ - Golden ratio):

$$P= \frac{\pi}{2}-\varphi$$

In this post it is shown how to prove the following identity:
$$\frac{\pi}{2} = 2 \sum_{l=1}^\infty  \arctan \frac{1}{ F_{2l+1} }$$
So we are left to prove that:

$$Q=\sum_{l=1}^\infty  \left(F_{2l+2} \arctan \frac{1}{ F_{2l+2}}- (F_{2l+1}-2) \arctan \frac{1}{ F_{2l+1} }  \right)= \varphi$$

Numerically this works. The proof eludes me.
I've spent a few hours trying different methods, but haven't had much luck so far.
Some useful identities:
$$\arctan \frac{1}{a} = \int_0^1 \frac{a dt}{t^2+a^2}$$
$$\arctan \frac{1}{a} = \sum_{k=0}^\infty \frac{(-1)^k}{2k+1} \frac{1}{a^{2k+1}}$$
$$F_n= \frac{1}{\sqrt{5}} \left(\varphi^n -\frac{(-1)^n}{\varphi^n} \right)$$
Notice that we can write the odd terms as:
$$F_{2l+1}=\frac{2}{\sqrt{5}} \cosh ((2l+1) \alpha)$$
$$F_{2l+2}=\frac{2}{\sqrt{5}} \sinh ((2l+2) \alpha)$$
Where $$\alpha= \log \varphi$$
Let's not forget the special property of the golden ratio:
$$\varphi-1=\frac{1}{\varphi}$$

There's also a more general arctangent identity listed on this page:
$$\arctan \frac{1}{ F_{2l} }= \sum_{j=l}^\infty \arctan \frac{1}{ F_{2j+1} }$$

A: Because of the size, I'm writing this attempt as a separate answer.
Still no closer to the proof of the closed form, but I decided to try Euler-Maclaurin, since the integrals can be evaluated explicitly.
We change the sign for $P$ from my other answer, so it will be positive, and work with it:
$$P=\sum_{l=1}^\infty  \left(F_{2l+2} \arctan \frac{1}{ F_{2l+2} } -F_{2l+1} \arctan \frac{1}{ F_{2l+1} } \right)=\varphi- \frac{\pi}{2}= \\ = 0.047237661954998228973 \ldots$$
Using the integral representation of arctangent and the hyperbolic form of Fibonacci numbers, we have:
$$P= \int_0^1 \sum_{l=1}^\infty  \left( \frac{F_{2l+21}^2}{ t^2+F_{2l+2}^2 } - \frac{F_{2l+1}^2}{ t^2+F_{2l+1}^2 } \right) dt$$
Simple rearrangement leads to the sum of two convergent series:

$$P= \int_0^1 \sum_{l=1}^\infty  \left( \frac{t^2}{ t^2+F_{2l+1}^2 } - \frac{t^2}{ t^2+F_{2l+2}^2 } \right) dt$$

Or, explicitly:
$$P= \int_0^1 \sum_{l=1}^\infty  \left( \frac{ \frac54 t^2}{ \frac54 t^2+\cosh^2 (2l+1) \alpha } - \frac{\frac54 t^2}{\frac54 t^2+\sinh^2 (2l+2) \alpha } \right) dt$$

Let's denote $\frac54 t^2=y^2$ and consider the series:
$$S_1(y)=\sum_{l=1}^\infty   \frac{ 1}{y^2+\cosh^2 (2l+1) \alpha }$$
$$S_2(y)=\sum_{l=1}^\infty   \frac{ 1}{y^2+\sinh^2 (2l+2) \alpha }$$
I doubt the series have a general closed form, so let's try our hand at Euler-Maclaurin:
$$S_1(y) = \int_1^\infty \frac{ dx}{y^2+\cosh^2 (2x+1) \alpha }+ \\ +\frac{1}{2} \frac{ 1}{y^2+\cosh^2 3\alpha }- \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!} \frac{\partial^{2k-1}}{\partial x^{2k-1}} \left(\frac{ 1}{y^2+\cosh^2 (2x+1) \alpha } \right) \bigg|_{x=1}$$
$$S_2(y) = \int_1^\infty \frac{ dx}{y^2+\sinh^2 (2x+2) \alpha }+ \\ +\frac{1}{2} \frac{ 1}{y^2+\sinh^2 4\alpha }- \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!} \frac{\partial^{2k-1}}{\partial x^{2k-1}} \left(\frac{ 1}{y^2+\sinh^2 (2x+2) \alpha } \right) \bigg|_{x=1}$$
Where $B_{2k}$ are Bernoulli numbers. Here I assumed that all the derivatives at $x \to \infty$ give exactly $0$, which is a reasonable assumption. Even though the series is asymptotic, I suspect it converges in this case.

Both the double integrals can be found exactly, but I won't write the full solution here since it's too long, I'll just provide the values from Mathematica:
$$ \int_0^1 \int_1^\infty \frac{5/4 t^2 dx dt}{5/4 t^2+\cosh^2 (2x+1) \alpha }= \\ =\frac{\sqrt{5} \left(\log 8-3 \log \left(35-15 \sqrt{5}\right)+4 \arctan \left(\frac{4}{3}\right)\right)-10}{20 \alpha}=0.0425812 \ldots$$
$$ \int_0^1 \int_1^\infty \frac{5/4 t^2 dx dt}{5/4 t^2+\sinh^2 (2x+2) \alpha }= \\ = \frac{\sqrt{5}\left(\log 4- \log \left(15-5\sqrt{5}\right)+14 \arctan \left(\frac{1}{3}\right)\right)-10}{20 \alpha}=0.0182396 \ldots$$
Now for the second terms of the E-M expansion:
$$\frac{1}{2} \int_0^1 \frac{5/4 t^2 dt}{5/4 t^2+\cosh^2 3 \alpha }=\frac{1}{2} - \tan^{-1} \frac{1}{2}$$
$$\frac{1}{2} \int_0^1 \frac{5/4 t^2 dt}{5/4 t^2+\sinh^2 4 \alpha }=\frac{1}{2} - \frac{3}{2}\tan^{-1} \frac{1}{3}$$

Let's see what we get so far by adding all four terms:
$$P_0= \frac{ -2\log 5-\log \left(123-55 \sqrt{5}\right)+4 \arctan \left(\frac{4}{3}\right)-14 \arctan \left(\frac{1}{3}\right))}{4 \sqrt{5} \alpha}+\frac{3}{2}\tan^{-1} \frac{1}{3}-\tan^{-1} \frac{1}{2} = \\ = 0.043319806992170091958 \ldots$$
This doesn't simplify much (at least Mathematica can't do it), and the numerical value is not that close to the desired answer.

Considering that $B_2=1/6$, taking the first derivatives and evaluating the integrals w.r.t. $t$ gives us an additional correction:
$$\Delta_1 P = \frac{ \left(1+8 \arctan \left(\frac{1}{2}\right)-14 \arctan \left(\frac{1}{3}\right)\right) \alpha}{12 \sqrt{5}}$$
$$P_0+\Delta_1 P=0.046990354355256824367$$
Which is closer to the answer. Taking more derivatives, we get various more complicated terms with increasing odd powers of $\alpha$.

This was fun, but I don't see any reason to continue. Let's just say, this method might be interesting for more general series, while this case with Fibonacci numbers obviously has some simple trick that can be used to prove the closed form.