text:
Q: Maximum sum of non consecutive elements Given an array of positive integers, what's the most efficient algorithm to find non-consecutive elements from this array which, when added together, produce the maximum sum?

A: Dynamic programming? Given an array A[0..n], let M(i) be the optimal solution using the elements with indices 0..i. Then M(-1) = 0 (used in the recurrence), M(0) = A[0], and M(i) = max(M(i - 1), M(i - 2) + A[i]) for i = 1, ..., n. M(n) is the solution we want. This is O(n). You can use another array to store which choice is made for each subproblem, and so recover the actual elements chosen.

A: Let A be the given array and Sum be another array such that Sum[i] represents the maximum sum of non-consecutive elements from arr[0]..arr[i].
We have:
Sum[0] = arr[0]
Sum[1] = max(Sum[0],arr[1])
Sum[2] = max(Sum[0]+arr[2],Sum[1])
...
Sum[i] = max(Sum[i-2]+arr[i],Sum[i-1]) when i>=2

If size is the number of elements in arr then sum[size-1] will be the answer.
One can code a simple recursive method in top down order as:
int sum(int *arr,int i) {
        if(i==0) {
                return arr[0];
        }else if(i==1) {
                return max(arr[0],arr[1]);
        }
        return max(sum(arr,i-2)+arr[i],sum(arr,i-1));
}

The above code is very inefficient as it makes exhaustive duplicate recursive calls. To avoid this we use memoization by using an auxiliary array called sum as:
int sum(int *arr,int size) {
        int *sum = malloc(sizeof(int) * size);
        int i;

        for(i=0;i<size;i++) {
                if(i==0) {
                        sum[0] = arr[0];
                }else if(i==1) {
                        sum[1] = max(sum[0],arr[1]);
                }else{
                        sum[i] = max(sum[i-2]+arr[i],sum[i-1]);
                }
        }
        return sum[size-1];
}

Which is O(N) in both space and time.

A: /**
 * Given an array of positive numbers, find the maximum sum of elements such
 * that no two adjacent elements are picked
 * Top down dynamic programming approach without memorisation.
 * An alternate to the bottom up approach.
 */

public class MaxSumNonConsec {

public static int maxSum(int a[], int start, int end) {
    int maxSum = 0;

    // Trivial cases
    if (start == end) {
        return a[start];
    } else if (start > end) {
        return 0;
    } else if (end - start == 1) {
        return a[start] > a[end] ? a[start] : a[end];
    } else if (start < 0) {
        return 0;
    } else if (end >= a.length) {
        return 0;
    }

    // Subproblem solutions, DP
    for (int i = start; i <= end; i++) {
        int possibleMaxSub1 = maxSum(a, i + 2, end);
        int possibleMaxSub2 = maxSum(a, start, i - 2);

        int possibleMax = possibleMaxSub1 + possibleMaxSub2 + a[i];
        if (possibleMax > maxSum) {
            maxSum = possibleMax;
        }
    }

    return maxSum;
}

public static void main(String args[]) {
    int a[] = { 8, 6, 11, 10, 11, 10 };
    System.out.println(maxSum(a, 0, a.length - 1));
}
}

A: The solution by @Ismail Badawi does not seem to work in the following case: Let us take the array: 8, 3, 1, 7 Then in this case, the algo returns max sum = 9 whereas it should be 15.
A solution to correct it is given an array A[0..n], let M(i) be the optimal solution using the elements with indices 0..i. Then M(0) = A[0], and M(i) = max(M(i - 1), M(i - 2) + A[i], M(i-3) + A[i]) for i = 3, ..., n. M(n) is the solution we want. This is O(n).

A: O(N) in time and O(1) in space (DP) solution:
int dp[2] = {a[0], a[1]};
for(int i = 2; i < a.size(); i++)
{
    int temp = dp[1];
    dp[1] = dp[0] + a[i];
    dp[0] = max(dp[0], temp);
}
int answer = max(dp[0], dp[1]);

A: IIUC: say your array is 1,2,3,4,5 then 3+5 would be 'correct' and 4+5 not, this means you'll have to find the largest numbers and check if they are consecutive. So an algorithm would be to make use of a second array, for the number of elements you need to add which you fill by traversing the original array and finding the largest non-consecutive integers, then add this up.
For the above array I guess [1,3], [1,4], [1,5], [1,3,5], [2,4], [2,5], [3,5] would be valid non-consecutive integers to be summed, the max sum would be 9 in this case [1,3,5]. So, to adapt the above algorithm, I would suggest you step through the array using several temporary arrays to find all the non-consecutive integer lists, and then check which is the largest. Keep in mind that 'most elements' does not mean 'largest sum'.

A:
Dynamic programming solution is the most elegant of all.
  And it serves for any value of the distance between two numbers that should not be considered.
  But for k= 1, which is for consecutive numbers constraint, I tried using backtracking.
There are different patterns to be compared for the maximum sum.  Below is the list :

Number of patterns for 1 = 1
[1]
Number of patterns for 2 = 2
[1][2]
Number of patterns for 3 = 2
[1, 3][2]
Number of patterns for 4 = 3
[1, 3][1, 4][2, 4]
Number of patterns for 5 = 4
[1, 3, 5][1, 4][2, 4][2, 5]
Number of patterns for 6 = 5
[1, 3, 5][1, 3, 6][1, 4, 6][2, 4, 6][2, 5]
Number of patterns for 7 = 7
[1, 3, 5, 7][1, 3, 6][1, 4, 6][1, 4, 7][2, 4, 6][2, 4, 7][2, 5, 7]
Number of patterns for 8 = 9
[1, 3, 5, 7][1, 3, 5, 8][1, 3, 6, 8][1, 4, 6, 8][1, 4, 7][2, 4, 6, 8][2, 4, 7][2, 5, 7][2, 5, 8]
Number of patterns for 9 = 12
[1, 3, 5, 7, 9][1, 3, 5, 8][1, 3, 6, 8][1, 3, 6, 9][1, 4, 6, 8][1, 4, 6, 9][1, 4, 7, 9][2, 4, 6, 8][2, 4, 6, 9][2, 4, 7, 9][2, 5, 7, 9][2, 5, 8]

Following is the code in java:

public class MaxSeqRecursive {

    private static int num = 5;
    private static int[] inputArry = new int[] { 1,3,9,20,7 };
    private static Object[] outArry;
    private static int maxSum = 0;

    public static void main(String[] args) {

        List<Integer> output = new ArrayList<Integer>();
        output.add(1);
        convert(output, -1);
        for (int i = 0; i < outArry.length; i++) {
            System.out.print(outArry[i] + ":");
        }

        System.out.print(maxSum);
    }

    public static void convert( List<Integer> posArry, int prevValue) {

        int currentValue = -1;

        if (posArry.size() == 0) {
            if (prevValue == 2) {
                return;
            } else {
                posArry.add(2);
                prevValue = -1;
            }

        }

        currentValue = (int) posArry.get(posArry.size() - 1);

        if (currentValue == num || currentValue == num - 1) {
            updateMax(posArry);
            prevValue = (int) posArry.get(posArry.size() - 1);
            posArry.remove(posArry.size() - 1);
        } else {
            int returnIndx = getNext(posArry, prevValue);
            if (returnIndx == -2)
                return;

            if (returnIndx == -1) {
                prevValue = (int) posArry.get(posArry.size() - 1);
                posArry.remove(posArry.size() - 1);
            } else {
                posArry.add(returnIndx);
                prevValue = -1;
            }
        }
        convert(posArry, prevValue);
    }

    public static int getNext( List<Integer> posArry, int prevValue) {
        int currIndx = posArry.size();
        int returnVal = -1;
        int value = (int) posArry.get(currIndx - 1);

        if (prevValue < num) {
            if (prevValue == -1)
                returnVal = value + 2;
            else if (prevValue - value < 3)
                returnVal = prevValue + 1;
            else
                returnVal = -1;
        }

        if (returnVal > num)
            returnVal = -1;

        return returnVal;
    }

    public static void updateMax(List posArry) {
        int sum = 0;
        for (int i = 0; i < posArry.size(); i++) {
            sum = sum + inputArry[(Integer) posArry.get(i) - 1];
        }
        if (sum > maxSum) {
            maxSum = sum;
            outArry = posArry.toArray();
        }
    }
}

Time complexity: O( number of patterns to be compared)

A: Another Java Implementation ( runs in linear time )
public class MaxSum {

private static int ofNonConsecutiveElements (int... elements) {
    int maxsofar,maxi2,maxi1;

    maxi1 = maxsofar = elements[0];
    maxi2 = 0;

    for (int i = 1; i < elements.length; i++) {
        maxsofar =  Math.max(maxi2 + elements[i], maxi1);
        maxi2 =  maxi1;
        maxi1 = maxsofar;
    }
    return maxsofar;
}

public static void main(String[] args) {
    System.out.println(ofNonConsecutiveElements(6, 4, 2, 8, 1));
}
}

A: My solution is O(N) time and O(1) space.
private int largestSumNonConsecutive(int[] a) {
    return largestSumNonConsecutive(a, a.length-1)[1];
}
private int[] largestSumNonConsecutive(int[] a, int end) {  //returns array largest(end-1),largest(end)
    if (end==0) return new int[]{0,a[0]};

    int[] largest = largestSumNonConsecutive(a, end-1);
    int tmp = largest[1];
    largest[1] = Math.max(largest[0] + a[end], largest[1]);
    largest[0] = tmp;

    return largest;
}

A: int nonContigousSum(vector<int> a, int n) {
    if (n < 0) {
        return 0;
    }
    return std::max(nonContigousSum(a, n - 1), nonContigousSum(a, n - 2) + a[n]);
}

this is the recursive approach with the help of which we can solve this question
(OPTIMAL SUB-STRUCTURE HALLMARK OF DYNAMIC PROGRAMMING.
Here we are considering two cases, in first we exclude a[n] and in the second we include a[n] and return the max of those sub cases found.
We are basically finding all the subsets of the array and returning the length of the non-contiguous array with max sum.
Use tabulation or memoization for avoiding same sub-problems.

A: A penny from me.
public class Problem {

  /**
   * Solving by recursion, top down approach. Always try this recursion approach and then go with
   * iteration. We have to add dp table to optimize the time complexity.
   */
  public static int maxSumRecur(int arr[], int i) {
    if(i < 0) return 0;
    if(i == 0) return arr[0];
    if(i == 1) return Math.max(arr[0], arr[1]);

    int includeIthElement = arr[i] + maxSumRecur(arr, i-2);
    int excludeIthElement = maxSumRecur(arr, i-1);
    return Math.max(includeIthElement, excludeIthElement);
  }

  /**
   * Solving by iteration. Bottom up approach.
   */
  public static void maxSumIter(int arr[]) {
    System.out.println(Arrays.toString(arr));
    int dp[] = new int[arr.length];
    dp[0] = arr[0];
    dp[1] = Math.max(arr[0], arr[1]);

    for(int i=2; i <= arr.length - 1; i++) {
      dp[i] = Math.max(arr[i] + dp[i-2], dp[i-1]);
    }

    System.out.println("Max subsequence sum by Iteration " + dp[arr.length - 1] + "\n");
  }

  public static void maxSumRecurUtil(int arr[]) {
    System.out.println(Arrays.toString(arr));
    System.out.println("Max subsequence sum by Recursion " + maxSumRecur(arr, arr.length - 1) +
        "\n");
  }

  public static void main(String[] args) {
    maxSumRecurUtil(new int[]{5, 5, 10, 100, 10, 5});
    maxSumRecurUtil(new int[]{20, 1, 2, 3});

    maxSumIter(new int[]{5, 5, 10, 100, 10, 5});
    maxSumIter(new int[]{20, 1, 2, 3});

  }

}

A: Make a list of numbers that is the odd or even sums corresponding to each number so far; e.g. for input of [1,2,4,1,2,3,5,3,1,2,3,4,5,2] the odd-even sums would be [1,2,5,3,7,6,12,9,13,11,16,15,21,17]
Now walk the list backwards greedily summing but skipping those elements whose odd/even sum is less than that of next-to-be-considered element.
src = [1,2,4,1,2,3,5,3,1,2,3,4,5,2]

odd_even_sums = src[:2]
for i in xrange(2,len(src)):
    odd_even_sums.append(src[i] + odd_even_sums[i-2])

best = []
for i in xrange(len(src)-1,-1,-1):
    if i == 0:
        best.append(i)
    elif odd_even_sums[i-1] > odd_even_sums[i]:
        pass
    elif odd_even_sums[i-1] == odd_even_sums[i]:
        raise Exception("an exercise for the reader")
    else:
        best.append(i)

best.reverse()

print "Best:",",".join("%s=%s"%(b,src[b]) for b in best)
print "Scores:",sum(odd_even_sums[b] for b in best)

Outputs:
Best: 0=1,1=2,2=4,4=2,6=5,8=1,10=3,12=5
Scores: 77

A: public static int findMaxSum(int[] a){
        int sum0=0; //will hold the sum till i-2
        int sum1=0;//will hold the sum till i-1
        for(int k : a){
            int x=Math.max(sum0+k, sum1);//max(sum till (i-2)+a[i], sum till (i-1))
            sum0=sum1;
            sum1=x;
        }
        return sum1;
    }

Below is the crux of algorithm:
max(max sum till (i-2)+a[i], max sum till (i-1))
O(N) time complexity  and O(1) space complexity.

A: A rather naive yet complete implementation.
Recursion equation is T(n) = n^2 + nT(n-3), which if I'm not wrong leads to exponential time. The (n-3) comes from the fact a number cannot add with itself/previous/next numbers.
The program reports the constituent list that makes up the sum (there are multiple, exponentially growing, of these lists, but it just picks one).
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class MaxSumNoAdjacent {

    private static class Sum {
        int sum;
        List<Integer> constituents = new ArrayList<>();

        Sum(int sum, List<Integer> constituents) {
            this.sum = sum;
            this.constituents = constituents;
        }

        @Override
        public String toString() {
            return "sum: " + sum + " " + constituents.toString();
        }
    }

    public static Sum maxSum(int[] arr) {
        List<Integer> input = new ArrayList<>();
        for (int i : arr) {
            if (i != Integer.MIN_VALUE) { //Integer.MIN_VALUE indicates unreachability
                input.add(i);
            }
        }

        if (input.size() == 0) {
            return null;
        }

        if (input.size() == 1) {
            List<Integer> constituents = new ArrayList<>();
            constituents.add(input.get(0));
            return new Sum(input.get(0), constituents);
        }

        if (input.size() == 2) {
            int max = Math.max(input.get(0), input.get(1));
            List<Integer> constituents = new ArrayList<>();
            constituents.add(max);
            return new Sum(max, constituents);
        }

        Map<Integer, int[]> numberAndItsReachability = new HashMap<>();
        for (int i = 0; i < input.size(); i++) {
            int[] neighbours = new int[input.size()];
            if (i > 0) {
                neighbours[i-1] = Integer.MIN_VALUE; //unreachable to previous
            }

            if (i < input.size()-1) {
                neighbours[i+1] = Integer.MIN_VALUE; //unreachable to next
            }

            neighbours[i] = Integer.MIN_VALUE; //unreachable to itself

            for (int j = 0; j < neighbours.length; j++) {
                if (neighbours[j] == 0) {
                    neighbours[j] = input.get(j); //remember values of reachable neighbours
                }
            }

            numberAndItsReachability.put(input.get(i), neighbours);
        }

        Sum maxSum = new Sum(Integer.MIN_VALUE, null);
        for (Entry<Integer, int[]> pair : numberAndItsReachability.entrySet()) {
            Sum sumMinusThisNumber = maxSum(pair.getValue()); //call recursively on its reachable neighbours
            if (sumMinusThisNumber != null) {
                int candidateSum = sumMinusThisNumber.sum + pair.getKey();
                if (maxSum.sum < candidateSum) {
                    sumMinusThisNumber.constituents.add(pair.getKey());
                    maxSum = new Sum(candidateSum, sumMinusThisNumber.constituents);
                }
            }

        }

        return maxSum;
    }

    public static void main(String[] args) {
        int[] arr1 = {3,2,5,10,7};
        int[] arr2 = {3,2,7,10};
        int[] arr3 = {5,5,10,40,50,35};
        int[] arr4 = {4,4,4,4};
        System.out.println(maxSum(arr1).toString());
        System.out.println(maxSum(arr2).toString());
        System.out.println(maxSum(arr3).toString());
        System.out.println(maxSum(arr4).toString());
    }

}

A: Here is a C# version for reference (you may refer to: http://dream-e-r.blogspot.com/2014/07/maximum-sum-of-non-adjacent-subsequence.html):
In-order to solve a problem using dynamic programming there should be a solution which has optimal substructure and overlapping sub problems properties. And the current problem has optimal substructure property.
Say, f(i) is defined as maximum subsequence sum of non adjacent elements for 'i' items, then
f( i) =     0 if i = 0
            max (f(i-1), f(i-2) + a[i])
Below is the algorithm for the same (no
te it can solved without the encapsulating data in 'record' - i just preferred it this way) - which should illustrate the above idea:
int FindMaxNonAdjuscentSubsequentSum(int[] a)
        {
            a.ThrowIfNull("a");
            if(a.Length == 0)
            {
                return 0;
            }
            Record r = new Record()
            {
                max_including_item = a[0],
                max_excluding_item = 0
            };
            for (int i = 1; i < a.Length; i++)
            {
                var t = new Record();
                //there will be only two cases
                //1. if it includes the current item, max is maximum of non adjuscent sub
                //sequence sum so far, excluding the last item
                t.max_including_item = r.max_excluding_item + a[i];
                //2. if it excludes current item, max is maximum of non adjuscent subsequence sum
                t.max_excluding_item = r.Max;
                r = t;
            }
            return r.Max;
        }

Unit Tests
[TestMethod]
        [TestCategory(Constants.DynamicProgramming)]
        public void MaxNonAdjascentSubsequenceSum()
        {
            int[] a = new int[] { 3, 2, 5, 10, 7};
            Assert.IsTrue(15 == this.FindMaxNonAdjuscentSubsequentSum(a));
            a = new int[] { 3, 2, 5, 10 };
            Assert.IsTrue(13 == this.FindMaxNonAdjuscentSubsequentSum(a));
            a = new int[] { 5, 10, 40, 50, 35 };
            Assert.IsTrue(80 == this.FindMaxNonAdjuscentSubsequentSum(a));
            a = new int[] { 1, -1, 6, -4, 2, 2 };
            Assert.IsTrue(9 == this.FindMaxNonAdjuscentSubsequentSum(a));
            a = new int[] { 1, 6, 10, 14, -5, -1, 2, -1, 3 };
            Assert.IsTrue(25 == this.FindMaxNonAdjuscentSubsequentSum(a));
        }

where
public static int Max(int a, int b)
        {
            return (a > b) ? a : b;
        }
        class Record
        {
            public int max_including_item = int.MinValue;
            public int max_excluding_item = int.MinValue;
            public int Max
            {
                get
                {
                    return Max(max_including_item, max_excluding_item);
                }
            }
        }

A: public static int maxSumNoAdj(int[] nums){
    int[] dp = new int[nums.length];
    dp[0] = Math.max(0, nums[0]); // for dp[0], select the greater value (0,num[0])
    dp[1] = Math.max(nums[1], Math.max(0, dp[0]));
    int maxSum = Math.max(dp[0], dp[1]);
    for(int i = 2; i < nums.length; i++){
        int ifSelectCurrent = Math.max(nums[i] + dp[i-2], dp[i-2]);// if select, there are two possible
        int ifNotSelectCurrent = Math.max(dp[i-1], dp[i-2]);        // if not select, there are two posible
        dp[i] = Math.max(ifSelectCurrent, ifNotSelectCurrent);      // choose the greater one
        maxSum = Math.max(dp[i], maxSum);   // update the result
    }
    return maxSum;
}

public static void main(String[] args) {
    int[] nums = {-9, 2, 3, -7, 1, 1};
    System.out.println(maxSumNoAdj(nums));
}


text:
Q: completely remove a label I am writing a program to display 30 years of holiday photos.

*

*First display the thirty directories as radiobuttons and get user to choose one

*then display all thumbnails (up to 500) within the chosen directory as radiobuttons and get the user to choose one

*then before doing fun things clear out the radiobuttons and this is where I have a problem

In the code below I have stripped out (hopefully) all the distractions.  When run, output is
.!label2.!radiobutton
.!label2.!radiobutton1
.!label2.!radiobutton2
restart
.!label3.!radiobutton
.!label3.!radiobutton1
.!label3.!radiobutton2
restart
.!label4.!radiobutton
.!label4.!radiobutton1
.!label4.!radiobutton2

Tried putting "label" as a global entity to no effect
any advice or suggestions gratefully received as I have been on this for about a week now
also pointers to further reading welcomed
from tkinter import *

root = Tk()
dir_list = ['Hebrides','Berlin','Malaysia']
var=StringVar()

def radiobuttons():
    label=Label(root)
    for x in (dir_list):
        r = Radiobutton(label,text=x, value=x,variable=var)
        print(r)
label.destroy()

def restart():
    print("restart")
    label.destroy()
    radiobuttons()

label=Label(root)
radiobuttons()
restart()
restart()

root.mainloop()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Heroku web dyno running Django app not releasing memory I'm struggling with a memory issue on Heroku when running a Django application (with gunicorn).
I have the following code that takes a user-uploaded image, removes all EXIF data, and returns the image ready for it to be uploaded to S3. This is used both as a form data cleaner and when reading base64 data into memory.
def sanitise_image(img): # img is InMemoryUploadedFile
    try:
       image = Image.open(img)
    except IOError:
       return None
    # Move all pixel data into a new PIL image
    data = list(image.getdata())
    image_without_exif = Image.new(image.mode, image.size)
    image_without_exif.putdata(data)

    # Create new file with image_without_exif instead of input image.
    thumb_io = StringIO.StringIO()
    image_without_exif.save(thumb_io, format=image.format)
    io_len = thumb_io.len
    thumb_file = InMemoryUploadedFile(thumb_io, None, strip_tags(img.name), img.content_type,
                                  io_len, None)
    # DEL AND CLOSE EVERYTHING
    thumb_file.seek(0)
    img.close()
    del img
    thumb_io.close()
    image_without_exif.close()
    del image_without_exif
    image.close()
    del image
    return thumb_file

I basically take an InMemoryUploadedFile and return a new one with just the pixel data.
del and closes may be redundant, but they represent my attempt to fix the situation where Heroku memory usage keeps growing and is not released every time this function terminates, even remaining overnight:

Running this on localhost with Guppy and following the tutorial, there are no remaining InMemoryUploadedFiles nor StringIOs nor PIL Image left in the heap, leaving me puzzled.
My suspicion is Python does not release the memory back to the OS, as I've read in multiple threads on SO. Has anyone played around with InMemoryUploadedFile and can give me an explanation as to why this memory is not being released?
When I do not perform this sanitisation, the issue does not occur.
Thanks a lot!

A: I think the issue is creating the temporary list object:
data = list(image.getdata())

Try:
image_without_exif.putdata(image.getdata())

This is why I think that is the issue:
>>> images = [Image.new('RGBA', (100, 100)) for _ in range(100)]

Python memory usage increased ~4Mb.
>>> get_datas = [image.getdata() for image in images]

No memory increase.
>>> pixel_lists = [list(image.getdata()) for image in images]

Python memory usage increased by ~85Mb.

You probably don't want to make getdata() into a list unless you need the numbers explicitly.  From the Pillow docs:

Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).

A: I found my own answer eventually. Huge thanks to Ryan Tran for pointing me in the right direction. list() does indeed cause the leak.
Using the equivalent split() and merge() method (docs) this is the updated code:
 with Image.open(img) as image:
        comp = image.split()
        image_without_exif = Image.merge(image.mode, comp)
        thumb_io = StringIO.StringIO()
        image_without_exif.save(thumb_io, format=image.format)
        io_len = thumb_io.len
        clean_img = InMemoryUploadedFile(thumb_io, None, strip_tags(img.name), img.content_type,
                                         io_len, None)
        clean_img.seek(0)
 return clean_img


text:
Q: MS Access Syntax Error (Missing Operator) in query expression NOT EXISTS I am currently working in MS Access and are coming across this error when I got to execute my query. "Syntax Error (Missing Operator) in query expression NOT EXISTS"
This is the query that is generating this error:
SELECT fName, lName, SSN
FROM Employee
WHERE NOT EXISTS
((SELECT storeID
FROM Store
WHERE storeID = 3)
EXCEPT
(SELECT orderID
FROM Works_On
WHERE  Employee.SSN = Works_On.SSN));

I have double checked spelling, syntax, and where I have my spaces and but I can't figure out what is causing this error, research online has also failed me  as well.
The results I want to achieve is having the name and SSN of all employees who work on an order who are from store 3.


text:
Q: How to pass the colored values of DataGridView to ListBox? How can I pass the value of the colored cells (DGV1 = DataGridView1)) to the ListBox? In the above example of the illustration, only one colored cell is transferred to the ListBox. But how can I transfer the value of all colored cells from the DataGridView to the ListBox (see DGV2)?
Thank you all for your help!
var YellowCell = dataGridView1.Rows.Cast<DataGridViewRow>().Select(row => new
{
    nameCol = row.Cells[row.Cells.Cast<DataGridViewCell>().First(cell => cell.OwningColumn.HeaderText == "XX").ColumnIndex].Value,

    coloredCells = row.Cells.Cast<DataGridViewCell>().First(c => c.Style.BackColor == Color.Yellow).Value,
}).ToList();

YellowCell.ForEach(s => listBox1.Items.Add($"{s.nameCol} : { s.coloredCells}"));

A: I would loop through your DataGridView rows and within that loop through the cells, then add the cell value to a collection when they match the criteria you've set out (in this case BackColor == Color.Yellow).
For example:
var yellowCellValues = new List<string>(); //the type should be whatever is in your dgv

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    foreach(DataGridViewCell cell in row.Cells)
    {
        if (cell.Style.BackColor == Color.Yellow)
        {
            yellowCellValues.Add(cell.Value.ToString());
        }
    }
}

You probably could do it in a LINQ statement, but if you're not familiar with LINQ I think the above foreach is much more intuitive and will allow you to easily use the same pattern for other things.


text:
Q: Django channels JsonWebsocketConsumer self.send_json() error i'm writing a consumer that sends a list of conversation and a profile
object (contact) after sending the via self.send_json() this error shows up
i really don't know what is going on wondering if you could help
Error:
Exception inside application: 'name'
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\sessions.py",
  line 183, in __call__
    return await self.inner(receive, self.send)
  File "C:\Users\DELL\ENVS\async\lib\site-
   packages\channels\middleware.py", line 41, in coroutine_call
    await inner_instance(receive, send)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py",
  line 62, in __call__
    await await_many_dispatch([receive], self.dispatch)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\utils.py",
  line 52, in await_many_dispatch
    await dispatch(result)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line
  238, in __call__
    return await asyncio.wait_for(future, timeout=None)
  File
"C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib
 \asyncio\tasks.py",
 line 4 14, in wait_for
    return await fut
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib
 \concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\db.py", line

14, in thread_handler
 return super().thread_handler(loop, *args, **kwargs)
File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line
271, in thread_handler
return func(*args, **kwargs)
File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py",
line 105, in dispatch
handler(message)
File "C:\Users\DELL\ENVS\async\lib\site-
packages\channels\generic\websocket.py", line 60, in websocket_receive
 self.receive(text_data=message["text"])
File "C:\Users\DELL\ENVS\async\lib\site-
packages\channels\generic\websocket.py", line 125, in receive
self.receive_json(self.decode_json(text_data), **kwargs)
File "E:\Personal Projects\Tolk\chat\consumers.py", line 41, in
receive_json
name = content['name']
'name'

Consumers.py:
```python
    class LoadConsumer(JsonWebsocketConsumer):

        def connect(self):
            if self.scope['user'].is_authenticated:
                self.accept()
            else:
                self.close()

        def receive_json(self, content, **kwargs):
            if content['command'] == "CHAT":
                name = content['name']
                data = self.load_conversation_contact(name)
            else:
                data = {"success": False, "errors": "no such command"}
            self.send_json(data) # the error happens here

        def load_conversation_contact(self, name):
            conversation = self.load_conversation(name)
            contact = self.load_contact()
            return {
                "success": True,
                "conversation": conversation['conversation'],
                "contact": contact['contact'],
            }

    def load_conversation(self, name):
        conversation = Conversation.objects.filter(name=name).first()
        if conversation:
            serializer = ConversationSerializer(conversation)
            data = serializer.data
            return {"success": True, "conversation": data}
        return {"success": False}
```

data :
```python
    {'success': True, 'conversation': {'type': 'couple', 'name':
    'conversation_8', 'contacts': [OrderedDict([('first_name', 'limbi'),
    ('last_name', 'salah'), ('location', 'London, UK'), ('contact_pic',
    '/media/users/1/profile/92a87524defac4511e17_avatar-male-2.jpg'),
    ('user',
    'limbi@main.com')]), OrderedDict([('first_name', 'cool'), ('last_name',
    'dude'), ('location', 'London, UK'), ('contact_pic',
    '/media/users/22/profile/f210d59103d63dd2ffa2_avatar-male-4.jpg'),
    ('user', 'wow@gmail.com')])], 'last_message_content': 'Lorem Ipsum is
    simply dummy text of the printing and typesetting industry.',
    'last_message_date': 'Yesterday', 'message_set':
    [OrderedDict([('content',
   'Lorem Ipsum is simply dummy text of the printing and typesetting
    industry.'), ('sender', 4), ('conversation', 8), ('sent', True),
    ('date_sent', '2019-09-01'), ('time_sent', '08:42:42.079479')])]},
    'contact': {'first_name': 'limbi', 'last_name': 'salah', 'location':
    'London, UK', 'contact_pic':
    '/media/users/1/profile/92a87524defac4511e17_avatar-male-2.jpg',
    'user':
    'limbi@main.com'}}
```

i've tried:
 1. debuging to see what's wrong
 2. changing the value of name

A: So a key was missing inside the JSON object


text:
Q: Does a 555 timer actually have a flip flop? I'm new to electronics and have been studying the 555 timer. One of the key components within the 555 timer is the "Flip-Flop", at least that's how every resource on the internet refers to it.
Here is a diagram of a 555 timer that is commonly found across the internet.

You can clearly see the component is labeled a "Flip-Flop". If you look at the Wikipedia page for a 555 timer it states it uses a "SR Flip-Flop".
As we know, a "Flip-Flop" uses a Latch as an integral component. So what is the difference between a Latch and a "Flip-Flop"? Every resource I find, describes a "Flip-Flop" as having one of these two defining characteristics:

*

*It is a Gated Latch

*It is enabled through a clock signal

So, the problem is, in a 555 timer, every diagram shows the "Flip-Flop" only taking 2 inputs, and has no enable pin, therefore, it is not gated. Thus, it must be a simple Latch.
Again, I'm new to electronics, but my question is:
Does a 555 timer actually have a "Flip-Flop" or is it just an SR Latch?

A: It's a level-sensitive (level-triggered) latch (or level triggered flip-flop). I don't think it really helps to get bogged down into the definitions and taxonomy in this kind of thing unless you have some authoritative source to point at that is respected as such. Terminology evolves and the 555 is an ancient IC.
An R-S flip-flop is the same thing as an SR latch etc.
The Wikipedia entry actually notes this evolution:

Recently, some authors reserve the term flip-flop exclusively for
discussing clocked circuits; the simple ones are commonly called
transparent latches.[1][2] Using this terminology, a level-sensitive
flip-flop is called a transparent latch, whereas an edge-triggered
flip-flop is simply called a flip-flop. Using either terminology, the
term "flip-flop" refers to a device that stores a single bit of data,
but the term "latch" may also refer to a device that stores any number
of bits of data using a single trigger. The terms "edge-triggered",
and "level-triggered" may be used to avoid ambiguity.[3]

Even if some boffin attempts to encrispen the definitions, there's no guarantee the rest of us are going to cooperate, and those old datasheets are not going to revise themselves even if it was desirable.


text:
Q: Open a file whose name is stored inside a variable in python How i can read the contents of a file whose name is stored inside a variable? In this way it gives me error
filename=filedialog.askopenfilenames()
fname=Path(filename[0]).name
f=open(fname,"r")

It give me a error: No such file or directory: 'namefile.txt'

A: You could try:
fname = Path(filename[0])

Because you need to get the path of file you want to open.


text:
Q: rsync against a maven nexus repo Is it possible to add and pull files from a sonatype nexus repo using the command line ?
I'm looking at storing the source dir (tarballs and all) of a rpm build environment, and i've been told there's a nexus file repo locally available to do it.
However i've never encountered nexus before so i've no idea how to interact with it. From what i can tell its for java projects, but if it can do the job then im happy enough.
I was kind of hoping i could just rsync the files into a particular dir and nexus will make them known via its web interface.

A: Check this answer:
It's possible to put binary files on nexus repository?
The Maven command-line can be used to upload files and once uploaded they can be retrieved using a standard HTTP request.
The Nexus GUI also has a mechanism for a web based file upload.

A: For a rpm build environment I would suggest you take a look at the Nexus Yum Plugin. It can expose a repository in Nexus as a Yum repository hosting RPM packages. More documentation is on the site.
In terms of interacting with Nexus it is a just based around a set of REST API's and http requests. So you can script it with anything including bash and so on. Or you could write your own plugin as well.
In general Nexus has support for all sorts of artifacts with specific support for .net/NuGet, Eclipse Update Sites (P2), OSGI, Maven sites and of course Maven2 and Maven 1. But as you can see it can be expanded via plugin. I would love for someone to write a plugin that can expose Nexus as an apt-deb/deb repo.
All of this is documented in the free book about Nexus.
Disclaimer: I do Nexus related training and did some recent updates on the book.


text:
Q: How to CONCAT a update query in a procedure I am trying to create a procedure to update a row when a bug gets fixed. Here is what it looks like:
DELIMITER $$
CREATE PROCEDURE bugFix (
    IN rid_in INT,
    IN fix_details_in VARCHAR (300)
) BEGIN
    SET @resolved_qry = CONCAT('UPDATE _bug_report SET resolved = 1 WHERE rid = ', rid_in);
    PREPARE stmt FROM @resolved_qry;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    UPDATE _bug_report SET fix_details = CONCAT(fix_details, fix_details_in) WHERE rid = CONCAT(rid, rid_in);

END $$
DELIMITER ;

When changing the resolved type to 1:
SET @resolved_qry = CONCAT('UPDATE _bug_report SET resolved = 1 WHERE rid = ', rid_in);
PREPARE stmt FROM @resolved_qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

It works fine, however when updating the fix_details column to include the details it does not work:
UPDATE _bug_report SET fix_details = CONCAT(fix_details, fix_details_in) WHERE rid = CONCAT(rid, rid_in);

Here is how I call it:
CALL bugFix(1, 'Hey, we fixed it');

Any ideas how to do this to use the fix_details_in value?

A: Why are you using dynamic SQL?
DELIMITER $$
CREATE PROCEDURE bugFix (
    IN rid_in INT,
    IN fix_details_in VARCHAR (300)
) BEGIN
    UPDATE _bug_report
        SET resolved = 1,
            fix_details = CONCAT(fix_details, fix_details_in)
        WHERE rid = rid_in;
END $$
DELIMITER ;

Presumably, "not work" means that fix_details is not being updated.  That would be because nothing matches:
WHERE rid = CONCAT(rid, rid_in)

Given that rid_in is an integer, this will always fail.


text:
Q: How to set WPF window size to fit the screen? I want to shrink the window so it fits on a screen.
Normally my window has size of 1000x800 so there is enough space in most scenarios but I'm also checking screen area to make sure it's not bigger. However my boss gave me his pc where he has screen scale set to 150% and the window becomes bigger then available space. I thought I solved this by dividing screen size by it's current dpi but turns out this does not work in all scenarios.
This is the method I'm using to set the size based on current DPI:
private void setMainWindowDimensions() {
    //set window size and position with respect to current screen
    var windowInteropHelper = new WindowInteropHelper(nativeWindow);
    var screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
    var dpi = screen.getScale();
    nativeWindow.Width = Math.Min(screen.WorkingArea.Width / dpi.x, 1000);
    nativeWindow.Height = Math.Min(screen.WorkingArea.Height / dpi.y, 800);
}

And here is the getScale() extension method I'm using to get the scale factor:
//https://stackoverflow.com/questions/29438430/how-to-get-dpi-scale-for-all-screens
public static (uint x, uint y) GetDpi(this S screen, DpiType dpiType = default) {
    var pnt = new System.Drawing.Point(screen.Bounds.Left + 1, screen.Bounds.Top + 1);
    var mon = MonitorFromPoint(pnt, 2/*MONITOR_DEFAULTTONEAREST*/);
    GetDpiForMonitor(mon, dpiType, out var dpiX, out var dpiY);
    return (dpiX, dpiY);
}

//https://msdn.microsoft.com/en-us/library/windows/desktop/dd145062(v=vs.85).aspx
[DllImport("User32.dll")]
private static extern IntPtr MonitorFromPoint([In]System.Drawing.Point pt, [In]uint dwFlags);

//https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510(v=vs.85).aspx
[DllImport("Shcore.dll")]
private static extern IntPtr GetDpiForMonitor([In]IntPtr hmonitor, [In]DpiType dpiType, [Out]out uint dpiX, [Out]out uint dpiY);

This is is form the How to get DPI scale for all screens? answer.
Above code worked when I changed the scale of main monitor on my work pc, it correctly returned dpi of (1.5, 1.5). Few months later and my boss is back with he's computer saying it still don't work.
I figured out the DPI is taken form main screen, even if the window is opened on the other and here I still can't figure out how to get correct values.
I was following this article  But it doesn't work at all. The methods form the NativeHelpers project are returning some values but the result is the same as with original method. Basically the  SetPerMonitorDPIAware fails and I don't know why. I used slightly modified version and I thought that there is something wrong with my project configuration, but even when I create new WPF project, extending the window from PerMonitorDPIWindow class, the result is the same - it throws "Enabling Per-monitor DPI Failed."
private void createWindow() {
    var c = logCtx("Creating main applicaton window", ONE_TIME_LOG);
    var pma = PerMonitorDPIHelper.SetPerMonitorDPIAware();
    if (pma == 0) log("Could not set per monitor DPI awareness.", WARNING_LOG);
    else log("Per monitor awareness was set.", SUCCESS_LOG);
    window = new CWindow();
    nativeWindow.AllowDrop = true;
    setMainWindowDimensions();
    c.close();
}

private void setMainWindowDimensions() {
    //set window size and position with respect to current screen
    var windowInteropHelper = new WindowInteropHelper(nativeWindow);
    var screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
    var dpi = screen.getScale();

    var sdpi = PerMonitorDPIHelper.GetSystemDPI();
    var wdpi = PerMonitorDPIHelper.GetDpiForWindow(windowInteropHelper.Handle);
    log($@"DPI awareness: {PerMonitorDPIHelper.getPerMonitorDPIAware()}");
    log($@"system DPI: {sdpi}, window DPI: {wdpi}, screen DPI: {dpi}");

    nativeWindow.Width = Math.Min(screen.WorkingArea.Width / dpi.x, 1000);
    nativeWindow.Height = Math.Min(screen.WorkingArea.Height / dpi.y, 800);
}

private void onLoaded(object sender, RoutedEventArgs e) {
    var c = logCtx("Main window loaded", ONE_TIME_LOG);
    setMainWindowDimensions();
    c.close();
}

Here you can see returned DPI is 1.5 even if the window is opened on screen that is not scaled.
Since I have a drawing app, I'm also using the following method to determine real scale coordinates:
private (double x, double y) density {
    get {
        var m = PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget
            .TransformToDevice;
        return (96 / m.M11 / 25.4, 96 / m.M22 / 25.4);
    }
}

This solution is from this question, and it also don't work in various dpi scenarios.
I've also read in one of the comments that shcore is available only since Windows 8. Our PCs have Win 10 but we also want to support Windows 7.
There is also on more strange thing. My boss PC is actually a laptop  with only one, main screen, yet it still doesn't get proper DPI. I don't have access to it right now so don't have logs I've just added...
Is there any method which works in all scenarios? It's seem that such such thing should require 2 lines of code yet it's became so convoluted I've already wasted 2 day on this and I'm out of ideas :(


text:
Q: Is it posible to insert a UITextView (or other UIKit view) into an augmented reality SCNScene? Weird crazy question I know. My current setup is a SCNScene with a camera controlled by the device's gyroscope. I'm able to add and light normal nodes, however I would like to add 2D UIView objects into the scene like UITextViews or maybe some buttons. The views would need to be inside the scene and thus become no longer visible if the camera moves away from them.
Firstly, is this even possible? Or would this be way more difficult to implement than rebuilding an editable textview as a node? Could this be achieved by categories or...?

A: I just talked to the scenekit people here at WWDC. He said that as of now it is completly impossible to do it in a nice, functional way. The only options he offered as a possible solution is to create the UIView element somewhere off screen or behind the scene and continuously take screenshots of the object and apply those images as a texture to a SCNNode. He also pointed out the performance will be very poor with this because taking screenshots is heavy and you can't get going very quick with it. So I guess this is a no-go until UIView adds support because, according to the engineer, it's impossible to implement this because of a UIView limitation and not a SceneKit one.


text:
Q: Coordinates for Center of Screen for iPhone 6S I would like to position an object in the center of my UIViewController. I have tried to use frame.width/2 and frame.height/2, for example, with a UIView:
let newView = UIView(frame: CGRect(x: frame.width/2, y: frame.height/2, width: 100, height: 100))

That method did not position the object in the center of the view as I expected. How can I position the object to the center of the view using the x-y coordinates of an iPhone 6s?

A: To get the actual center coordinates of the window, I'd use:
let centerX = UIScreen.mainScreen().bounds.maxX / 2
let centerY = UIScreen.mainScreen().bounds.maxY / 2

But otherwise, in whichever ViewController you're working, the center of the view is a CGPoint, the position of which can be found with:
view.center

If you just want the x and y coordinates you can get them by just adding a .x or .y after view.center.


text:
Q: How to get all the data from the inventory slots? So, im making a game in C# and im trying to get all the data from my inventory slots.
public bool AddItems(Item item){
            if(item == null || item.quantity <= 0)
                return false;

            List<Slot> listSlots = GetSlots(panel_Backpack.grid);
            if(listSlots.Count <= 0)
                return false;

                Slot slotFound = listSlots.FirstOrDefault(p => p.currentItem != null && p.currentItem.stackable && p.currentItem.quantity + item.quantity <= item.quantityMax);

                if(slotFound != null && slotFound.currentItem.itemId == item.itemId){
                    slotFound.currentItem.quantity += item.quantity;
                    slotFound.Refresh();
                } else {
                    slotFound = listSlots.FirstOrDefault(p => p.currentItem == null);
                    if(slotFound == null){
                        print("Inventory full!");
                        return false;
                    }
                    slotFound.ChangeItem(item);
                }

                return true;
        }

i make this code but im using the function FirstOrDefault() and I can only get the values of the first slot.
i need to check all slots because when i pick up an item from the ground it sends it to a new slot if the item is different
but if the item in the first slot is not full (each slot takes two items) and i pick up items it always creates new slots because it sees that the first one is not its full
EXAMPLE 1: I picked up a stone, a stone again and then a 2 squares.
EXAMPLE 2: I picked up a stone, a square and then a square again.
I want the squares to go to the same slot.
if anyone can help i would appreciate it.

A: You likely want to check if the Item type matches the slot's item type when you are checking FirstOrDefault instead of after. If you do it after it does not affect the list search.

Slot slotFound = listSlots.FirstOrDefault(p => p.currentItem != null && p.currentItem.stackable && p.currentItem.quantity + item.quantity <= item.quantityMax);

You use slotFound.currentItem.itemId == item.itemId to compare later in the method so if we instead move it into the FirstOrDefault search it should work. I am also just going to split the statement into multiple lines for ease of reading.
Slot slotFound = listSlots.FirstOrDefault(p =>
p.currentItem != null &&
p.currentItem.itemId == item.itemId &&
p.currentItem.stackable &&
p.currentItem.quantity + item.quantity <= item.quantityMax);

by checking the Slot Item has the same ID as the Item you are checking against in the FirstOrDefault() you will only get slots of the same "type". this should return the first slot that Stores The Same Item and is not full, or the default item if it can't find one.


text:
Q: Debugging mismatch when writing and reading binary file I have two application, a reader and writer.
The data I'm writing and reading is members of this class:
class MyClass
{
public:
   MyClass(){}
   ~MyClass(){}
public:
   //Getters and setters are removed for simplicity
   void write(std::ofstream& ofile);
   void read(std::ifstream& file);
private:
   Aenum a= Aenum_0;

   double b= 0.0;
   double c= 0.0;
   double d= 0.0;
   double e= 0.0;

   char charArr1[5];
   char charArr2[5];
   char charArr3[5];
   char charArr4[10];

   date_and_time time;
};

Where the struct and enum are:
struct date{
       int day = 1;
       int month = 1;
       int year = 2017;
    };
    struct hhmmss{
       int hours = 1;
       int minutes = 1;
       int seconds = 1;
    };
    struct date_and_time {
       date d;
       hhmmss t;
    };

    enum Aenum = {Aenum_0, Aenum_1, Aenum_2};

The write function:
void MyClass::write(std::ofstream& ofile){
   ofile.write((char*)&a, sizeof(int));
   ofile.write((char*)&b, sizeof(double));
   ofile.write((char*)&c, sizeof(double));
   ofile.write((char*)&d, sizeof(double));
   ofile.write((char*)&e, sizeof(double));
   ofile.write(&charArr1[0], sizeof(char)*5);
   ofile.write(&charArr2[0], sizeof(char)*5);
   ofile.write(&charArr3[0], sizeof(char)*5);
   ofile.write(&charArr4[0], sizeof(char)*10);
   ofile.write((char*)&time, sizeof(date_and_time));
}

The read function:
void MyClass::read(std::ifstream& file){
   file.read((char*)&a, sizeof(int));
   file.read((char*)&b, sizeof(double));
   file.read((char*)&d, sizeof(double));
   file.read((char*)&d, sizeof(double));
   file.read((char*)&e, sizeof(double));
   file.read(charArr1, sizeof(char)*5);
   file.read(charArr2, sizeof(char)*5);
   file.read(charArr3, sizeof(char)*5);
   file.read(charArr4, sizeof(char)*10);
   file.read((char*)&time, sizeof(date_and_time));
}

Then in my writer application I do this:
bool writeToBinaryFile(std::vector<myClass>& myClassCollection, const std::string& outputPath){

   std::ofstream ofile;
   ofile.open(outputPath);
   if (!ofile.is_open())
      return false;

   date_and_time dtnow = getDateAndTimeNow();
   ofile.write((char*)&dtnow, sizeof(date_and_time));

   int numberOfmyClass = myClassCollection.size();
   ofile.write((char*)&numberOfmyClass, sizeof(int));

   for (int i = 0; i < myClassCollection.size(); i++)
      myClassCollection[i].write(ofile);

   ofile.close();
   return true;
}

And in the reader I do this:
bool loadData(const std::string& filePath){

   std::ifstream file;
   file.open(filePath);
   if (!file.is_open())
      return false;

   date_and_time dtNow;
   int numberOfmyClass;
   file.read((char*)&dtNow, sizeof(date_and_time));
   file.read((char*)&numberOfmyClass, sizeof(int));

   for (size_t i = 0; i < numberOfmyClass; i++)
   {
      MyClass myClass;
      myClass.read(file);
      //use data
   }
   return true;
}

I know that the data in in class members is complete. I have another function where I write to an ASCII file, and there is no missing data.
When I read the binary file, I get correct data for the first 15 (out of 200+) members of the class. Then suddenly the values I'm reading are garbage, as if there are some bytes that shouldn't be there.
So what I'm asking is; am I doing something obviously wrong? And if not, what is the best way to debug such a problem?


text:
Q: Referencing Javascript Object's child from another child's child using a generic pointer Please check the following Object Structure:
var obj_parent = {
    obj_child : {
        obj_child_var : 15,
        fnc : function() {
            let self = this;
            alert('Called : obj_parent>fnc() | obj_child_var : '+self.obj_child_var);
            obj_parent.obj_fnc();
        }
    },
    obj_fnc : function() {
        alert('Called : obj_parent>obj_fnc();');
    }
};

$(function() {
    obj_parent.obj_child.fnc();
});

Test code at Codepen , just click the 'Click Here' button for testing.
At line#7, obj_parent.obj_child.fnc() is calling function obj_parent.obj_fnc() which is from it's parent's parent.
If it was not parent's parent, I could use 'this' to access(like 'obj_child_var' was accessed in lines #5,#6) the function.
Problem here is, if I have to rename 'obj_parent', I will have to rename it everywhere inside it.
What will be the best way to restructure the code where any child or more childs inside them can access any other child from the top root of the object without using it's direct name('obj_parent') but more of a generic way.
like: let self_root = pointer to the 'obj_parent';
And use this self_root instead of 'obj_parent' inside every level, everywhere inside 'obj_parent';
Here I want to keep the entire code compact inside: obj_parent = {..Everything..}
And don't want to put any code of 'obj_parent' outside of it, like using:
obj_parent.prototype.* * * = * * *;
Is there any suggestions on the best way to achieve this by restructuring the codes only inside obj_parent= {...}?
In short I am looking for something like the following inside obj_parent.obj_child.fnc():
...
fnc : function() {
  let root_obj_pointer = this.parent;// Points to 'obj_parent';
  root_obj_pointer.obj_fnc();// Instead of obj_parent.obj_fnc();
}
...

So that I do not have to rename the 'obj_parent' in obj_parent.obj_fnc(); if the root 'obj_parent' ever gets renamed.

A:
Problem here is, if I have to rename 'obj_parent', I will have to rename it everywhere inside it.

I would use an IIFE instead, so that you can give the object whatever name you want inside the IIFE's scope, and return the object - then, you can rename the outer variable name from obj_parent to whatever you want without problems:

const parentVariableName = (() => {
  const obj_parent = {
    obj_child : {
      obj_child_var : 15,
      fnc : function() {
        let self = this;
        alert('Called : obj_parent>fnc() | obj_child_var : '+self.obj_child_var);
        obj_parent.obj_fnc();
      }
    },
    obj_fnc : function() {
      alert('Called : obj_parent>obj_fnc();');
    }
  };
  return obj_parent;
})();

parentVariableName.obj_child.fnc();

A: Depending on your usage, you can rewrite your child function to an arrow function so the scope is the external context.
https://codepen.io/anon/pen/rZyPmz?editors=0010
var parent = {
  child: {
    x: 15,
    fnc: () => {
      let y = parent.child.x
      alert('child.fnc(): ' + y)
      parent.fnc(y)
    }
  },
  fnc: function(y) {
    alert('parent.fnc(): ' + y)
  }
};

function btn_clicked() {
  parent.child.fnc()
}


text:
Q: Alter statement in a Transaction I execute the code below:
use AdventureWorks2008R2
begin transaction
BEGIN
alter table HumanResources.Department add newcolumn int
update HumanResources.Department set newcolumn=1 where departmentid=1
END
commit

The error I get is:

Invalid column name 'newcolumn'.

Can ALTER statements be included in Transactions like this? If so, how can I prevent this error?
I have researched this online e.g. here.  I have not found an answer to my specific question.

A: Yes, you can include an ALTER in a transaction. The problem is that the parser validates the syntax for your UPDATE statement, and can't "see" that you are also performing an ALTER. One workaround is to use dynamic SQL, so that the parser doesn't inspect your syntax (and validate column names) until runtime, where the ALTER will have already happened:
BEGIN TRANSACTION;

  ALTER TABLE HumanResources.Department ADD newcolumn INT;

  EXEC sp_executesql N'UPDATE HumanResources.Department
    SET newcolumn = 1 WHERE DepartmentID = 1;';

COMMIT TRANSACTION;

Note that indentation makes code blocks much more easily identifiable (and your BEGIN/END was superfluous).

A: If you check the existence of column, then it should work.
BEGIN TRANSACTION;

    IF COL_LENGTH('table_name', 'newcolumn') IS NULL
    BEGIN
        ALTER TABLE table_name ADD newcolumn INT;
    END

  EXEC sp_executesql N'UPDATE table_name
    SET newcolumn = 1 WHERE DepartmentID = 1;';

COMMIT TRANSACTION;

A: Aaron has explained everything already. Another alternative that works for ad-hoc scripts in SSMS is to insert the batch separator GO so that the script is sent as two parts to the server. This only works if it is valid to split the script in the first place (you can't split an IF body for example).


text:
Q: Converges or diverges: $\sum_{n=1}^{\infty}\left [\arctan{\frac{(-1)^n}{n}}+{(-1)^n\over n^2}\right]$ How can I show that the following series converges or diverges ?
$$\sum_{n=1}^{\infty}\left [\arctan{\frac{(-1)^n}{n}}+{(-1)^n\over n^2}\right]$$
$\sum_{n=1}^{\infty}\left [\arctan{\frac{(-1)^n}{n}}\right]+\sum_{n=1}^{\infty}\left[{(-1)^n\over n^2}\right]$, for $\sum_{n=1}^{\infty}\left[{(-1)^n\over n^2}\right]$ I used Leibniz criteria, by showing that $1\over n^2$ is decreasing and its limit is zero, thus the series converges. For $\arctan...$ the first series I thought to use the same Leibniz criteria, because $1\over n$ is decreasing to zero, but I do not know, is it right to say that if ${(-1)^n \over n}$ decreases then $\left [\arctan{\frac{(-1)^n}{n}}\right]$ also decreases  ? Is it right what I did ? Thank you.

A: For small $z$, $\arctan z$ behaves exactly like $z$:
$$\arctan z = z+O(z^3) $$
hence $\sum_{n\geq 1}\arctan\frac{(-1)^n}{n}$ converges since $\sum_{n\geq 1}\frac{(-1)^n}{n}$ converges by Leibniz' test. By the way,
$$ \sum_{n=1}^{+\infty}\arctan\frac{(-1)^n}{n}=\operatorname{Arg}\frac{\Gamma\left(\frac{1+i}{2}\right)}{\Gamma\left(1+\frac{i}{2}\right)}=-0.506671\ldots$$

A: Hint. Recall that, for $x$ near $0$,
$$
\arctan x=x+\mathcal{O}\left(x^3\right)
$$
then
$$
\sum\arctan{\frac{(-1)^n}{n}}=\sum\frac{(-1)^n}{n}+\sum\mathcal{O}\left(\frac{1}{n^3}\right)
$$ is convergent being the sum of two convergent series.


text:
Q: Create Generic object inside class I am making a base class from which other classes can be derived.
public class BaseClass<T> where T
{
    public BaseClass()
    {
        TClassObject = new T("SomeText"); // Error here
    }

    public T TClassObject { get; set; }
}

'T': cannot provide arguments when creating an instance of a variable type.
What I am missing here.

A: From MSDN:

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.

So it needs to be parameterless. You may want to look at Activator.CreateInstance
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

A: The where T : new() constraint states that T must have a parameterless constructor. Your code is calling into a constructor that takes a string parameter, and it isn't guaranteed that your T will have such a constructor.
It is not possible in C# to create a constraint on a specific constructor signature. If you need this functionality, you're better off using something like one of the answers in this thread.


text:
Q: directx transformedcolored color field alpha value I am using C #. I need to draw points using DirectX and they should be semitransparent. I declared vertices to be transformedColored and set the color value to be:
 vertices[i].Color = Color.FromArgb(20,0,0,255).ToArgb();

This should be quite transparent blue but what I got was opaque blue. Whatever value I use for the alpha value, it always gets fully opaque.
Any ideas why? I hope the  transformedcolored color field supports alpha value.
Thanks in advance.
The drawing code is:
device.Clear(ClearFlags.Target, System.Drawing.Color.White, 1.0f, 0);

device.RenderState.AlphaBlendEnable = true;

device.RenderState.AlphaSourceBlend = Blend.SourceAlpha;

device.RenderState.AlphaDestinationBlend = Blend.InvSourceAlpha;

device.RenderState.BlendOperation = BlendOperation.Add;

CustomVertex.TransformedColored[] vertices = new CustomVertex.TransformedColored[N];

for (int i = 0; i < N; i++)
{
   vertices[i].Position = new Vector4(2.5f + (g_embed[i, 0] - minx) * (width - 5.0f) / maxx, 2.5f + (g_embed[i, 1] - miny) * (height - 5.0f) / maxy, 0f, 1f);//g_embed, minx, width,maxx, miny,height, maxy are all predifined

   vertices[i].Color = Color.FromArgb(20, 0, 0, 255).ToArgb();
}

 device.BeginScene();

 device.VertexFormat = CustomVertex.TransformedColored.Format;

 device.DrawUserPrimitives(PrimitiveType.PointList, N, vertices);

 device.EndScene();

 device.Present();

 this.Invalidate();

A: Your renderstates are used for premultiplied alpha. Using a real alpha-channel needs the following settings (Blendenumerationdoc):
graphics.GraphicsDevice.RenderState.AlphaBlendEnable = true;
graphics.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
graphics.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
graphics.GraphicsDevice.RenderState.BlendFunction = BlendFunction.Add;

It creates following the formular, where a is your alpha of the color: a * SourceColor + (1-a) * DestColor


text:
Q: How to consider "pratt" zero method in Wilcoxon Test of R, which is available in Python Scipy? I have a dataset of two columns which represent rank data. These ranks are ranged from 1, 2, and 3. To test the difference in medians between these two columns, I am considering the Wilcoxon rank-sum test with Paired samples. The data can be found as 'DemData.csv' in this link, where 'dem1m' and 'dem3m' are the columns to be tested.
First, I considered performing this test in Python using scipy.stats.wilcoxon() (Documentation). In this module, there is an argument named as zero_method= "pratt", which includes zero-differences in the ranking process. The default zero_method is wilcox here, which discards all zero-differences. The code considering these two different parameters are as follow:
Python 3.6.4
import pandas as pd
from scipy import stats
data = pd.read_csv('DemData.csv')
dem1m = data.iloc[:, 1].values # x
dem3m = data.iloc[:, 2].values # y
result_wilcox = stats.wilcoxon(dem1m, dem3m, zero_method='wilcox', correction=False)
result_pratt = stats.wilcoxon(dem1m, dem3m, zero_method='pratt', correction=False)

The result looks like this:
print(result_wilcox)
WilcoxonResult(statistic=394.0, pvalue=0.44822952395895177)
print(result_pratt)
WilcoxonResult(statistic=8769.0, pvalue=3.0819702413935615e-53)

I think the wilcox.test() (Documentation) function in R provide more robust results with different parameters. Here is my code:
data <- read.csv("DemData.csv")
result <- wilcox.test(data$dem1m, data$dem3m,
                     alternative = "two.sided",
                     paired = TRUE)

Here is the result from this function:
> print(result)

Wilcoxon signed rank test with continuity correction

data:  data$dem1m and data$dem3m
V = 509, p-value = 0.4522
alternative hypothesis: true location shift is not equal to 0

It seems like the p-value from R function and the "wilcox" version of scipy function is same. So, the R function here has considered only the "wilcox" as zero_method. My question is, can I consider "pratt" in the R dunction like in scipy function?


text:
Q: OpenCV remove background preserving the foreground I'm new to openCv and I'm trying to extract myself from the background in a video that I got from my webcam. So far I'm able to remove background while the foreground(video of me) is still appearing in white. I want it to be exactly like it was in the original video. Below is my current code:
fgbg = cv2.createBackgroundSubtractorMOG2()

while(1):
ret, frame = cap.read()

fgmask = fgbg.apply(frame)

cv2.imshow('fgmask',frame)
cv2.imshow('frame',fgmask)

Any hint or some sense of direction will be much appreciated.

A: fgmask is a white mask of the foreground. You must mask your original frame with this mask. Now, the frame is an RGB or possibly a BGR image, while the mask is a single channel (you can check by printing frame.shape and fgmask.shape). Therefore you must convert the mask to RGB and then apply the mask:
mask_rgb = cv2.cvtColor(fgmask, cv2.COLOR_GRAY2RGB)
out_frame = cv2.bitwise_and(frame, mask_rgb)
cv2.imshow("FG", out_frame)


text:
Q: How to add Web Pages 2 with razor syntax in an empty web application project in Visual Studio 2012? I want to create simple Web Pages 2 applications.
I want to use the File->New->Project->Empty Web Application and not the File->New-Web Site.
After i create a new empty web application i cant add a .cshtml file..
The only way that i could do it is:

*

*Nuget -> Install Web Pages 2 with razor libraries

*Add->New->Razor MVC View

I am NOT putting the .cshtml file in Views directory. Instead i leave it in root and name it Default.cshtml
Is THIS really the way to do it?

A: Actually, you can do this. I've done it this way.
Open VS 2013
From the main menu: File > New > Project
Under Installed Templates
Select
  Templates
    Visual C# (or VB)
      Web
     (do not select VS 2012)
Select ASP.NET Web Application from the list of projects on the right of screen
Next Screen - Select Empty Project, Check Webforms
Run once, get error for no default page
Only files in project
  Global.asax
  Web.config
Select "Project" in Solution Explorer
    (do not select the Solution)
    Select Manage NuGet Packages
Microsoft ASP.NET Web Pages
Microsoft ASP.NET Web Pages Data (Important! Includes WebMatrix dlls)

Add Layout and View pages
  Notice the code is recognized as an error
If you run, you get a Server Error that ViewBag does not exist
  Change ViewBag to Page
Run again. You should be able to develop like standard web pages but with Razor and no viewstate.
That should be it. I've been doing this since VS 2012 and love the results.
I contacted Scott H. at MS about adding this as a project type. Didn't get
far. He didn't see the point in doing a project this way. IMHO, I disagree.

A: Web Pages 2 applications are Web Sites, not Web Applications, so you should do the following:
File » New Web Site » ASP.NET Web Site (Razor 2)


text:
Q: List Mapped Drives of All Users I often have to replicate the mapping of drives of one machine to another. While I know how to easily output the data for the CURRENT user I have not found a way of doing this for others who are not currently logged on which for various reasons I need to be able to do.
I've tried in vain finding the data in the registry (once again I can find the mapped drives of the CURRENT user in HKCU\NETWORK but not for other users) and my searches on the internet haven't been too useful either so any help would be greatly appreciated!

A: In Hkey_USERS  all these wierd Id tag things S-1-5-21-1017659469-3233765421-1457166851-500  are the Users both current and non current.  there is a network folder in each of them. there is also CurrentControlSets and all the other usual stuff.
it is just a matter of finding the user TYPE Like 500 is admin, and a USER might be a 1000, like this  HKEY_USERS\S-1-5-21-1272468093-1708547768-1957994088-1006
I have always seen all the users that are created in XP ? (or thought I did) But I dont really have users.  So if that doesnt work, then it would be loading in thier Hive or Hve , to work with it. which is different.
(the above IDs are munged, and not actual)
Google search for how to Map network drives at log-in of users using scriipting


text:
Q: Opening existing database created with SQLiteStudio Currently the error message I get is that the file cannot be opened. All I'm trying to do is open my database, open my table and extract the information from this. Below is what I have so far:
public class MainActivity extends Activity
{
private static final String DATABASE_NAME = "ExerciseDatabase.db";
private static final String DATABASE_TABLE = "ExerciseList";

SQLiteDatabase myDatabase;

private void openDatabase(){
    myDatabase = openOrCreateDatabase("/databaseManipulation/assets/" + DATABASE_NAME, Context.MODE_PRIVATE, null);

}

protected void onCreate(Bundle savedInstanceState) {
openDatabase();
Cursor allData = myDatabase.rawQuery("SELECT * FROM ExerciseList", null);
Log.e("TESTLOG", allData.toString());

}
}

From what I've read it seems to suggest creating a new database and overwriting it with my existing one, any help would be great

A: add this function
public void CopyDB(InputStream inputStream,
            OutputStream outputStream) throws IOException {
                //---copy 1K bytes at a time---
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                inputStream.close();
                outputStream.close();
            }

use by this code
try {
        String destPath = "/data/data/" + getPackageName() +
            "/databases";
        File f = new File(destPath);
        if (!f.exists()) {
            f.mkdirs();
            f.createNewFile();

            //---copy the db from the assets folder into
            // the databases folder---
            CopyDB(getBaseContext().getAssets().open("MyDB"),
                new FileOutputStream(destPath + "/MyDB"));
            Log.i("esfandune", "esfandune");
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

A: You can try something like this
public class SystemHelper{

private final String DB_PATH;
private final String DB_NAME;
private final Context mContext;
private SQLiteDatabase mDataBase;

public SystemHelper(Context context) {
    super(context, "YOUR_DB_NAME_IN_ASSETS.db", null, 1);
    DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    DB_NAME = "YOUR_DB_NAME_IN_ASSETS.db";
    mContext = context;
    createDataBase();
    openDataBase();
}

public void createDataBase() {
    try {
        boolean mDataBaseExist = checkDataBase();
        this.getReadableDatabase();
        this.close();
        if (!mDataBaseExist) {
            Files.copyFromAssets(mContext, DB_NAME, DB_PATH);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private boolean checkDataBase() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

@Override
public SQLiteDatabase getWritableDatabase() {
    return mDataBase;
}

@Override
public synchronized void close() {
    if (mDataBase != null)
        mDataBase.close();
    super.close();
}

public void openDataBase() {
    String mPath = DB_PATH + DB_NAME;
    mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.OPEN_READWRITE);
}
}

and Files.copyFromAssets(mContext, DB_NAME, DB_PATH) method:
public static void copyFromAssets(Context context, String fileName, String path) {
    InputStream mInput = null;
    try {
        mInput = context.getAssets().open(fileName);
        File f = new File(path + fileName);
        if (!f.exists())
            f.createNewFile();
        OutputStream mOutput = new FileOutputStream(f);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


text:
Q: generation of offline documentation using swagger in CXF I'm trying to generate REST documentation using swagger with cxf and camel.
I've succeed to get swagger documentation. And I have swagger-ui working correctly !
So now i'm trying to export everything and build an offline documentation. In order to do that I use :
1) swagger-maven-plugin : REST -> json
2) swagger2markup-maven-plugin : json -> asciidoc
I managed to get a json file but it doesn't contain my api documentation..
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.jeffsbox</groupId>
    <artifactId>jaxrs-cxf-camel-spring-example</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <name>jaxrs-cxf-camel-spring-example</name>

    <description>
        An example demonstrating how to use create a REST web service using
        a gazillion wrappers (JAX-RS, CXF, Camel and Spring).
    </description>

    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <camel.version>2.17.1</camel.version>
        <spring.version>4.2.6.RELEASE</spring.version>
        <swagger-ui-version>2.1.0</swagger-ui-version>
        <jackson.version>1.9.0</jackson.version>
        <swagger.version>1.5.0</swagger.version>
        <cxf-rt.version>3.2.0-SNAPSHOT</cxf-rt.version>
        <cors-filter.version>2.1</cors-filter.version>
        <enunciate.version>2.5.0</enunciate.version>
        <swagger2markup.version>1.0.0</swagger2markup.version>
        <generated.asciidoc.directory>/asciidoc</generated.asciidoc.directory>
        <phase.generate-documentation>compile</phase.generate-documentation>
    </properties>

    <repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>jcenter-releases</id>
            <name>jcenter</name>
            <url>http://jcenter.bintray.com</url>
        </repository>
    </repositories>

    <dependencies>

        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>${swagger2markup.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-cxf</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-jaxrs</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-jaxrs</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                     <groupId>javax.ws.rs</groupId>
                     <artifactId>jsr311-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>${cxf-rt.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>${cxf-rt.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-service-description</artifactId>
            <version>${cxf-rt.version}</version>
        </dependency>

        <dependency>
            <groupId>com.thetransactioncompany</groupId>
            <artifactId>cors-filter</artifactId>
            <version>${cors-filter.version}</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>swagger-ui</artifactId>
            <version>2.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.9</version>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.webjars</groupId>
                                    <artifactId>swagger-ui</artifactId>
                                    <version>${swagger-ui-version}</version>
                                    <overWrite>true</overWrite>
                                    <outputDirectory>${project.build.directory}/swagger-ui</outputDirectory>
                                    <excludes>**/*.gz</excludes>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/${project.artifactId}-${project.version}</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${project.build.directory}/swagger-ui/META-INF/resources/webjars/swagger-ui/${swagger-ui-version}</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
<!--             <plugin> -->
<!--            <groupId>com.webcohesion.enunciate</groupId> -->
<!--            <artifactId>enunciate-maven-plugin</artifactId> -->
<!--            <version>${enunciate.version}</version> -->
<!--            <executions> -->
<!--               <execution> -->
<!--                      <goals> -->
<!--                        <goal>docs</goal> -->
<!--                      </goals> -->
<!--                      <configuration> -->
<!--                        <configFile>enunciate.xml</configFile> -->
<!--                        <docsDir>${project.build.directory}</docsDir> -->
<!--                      </configuration> -->
<!--               </execution> -->
<!--            </executions> -->
<!--            </plugin> -->
            <plugin>
                <groupId>com.github.kongchen</groupId>
                <artifactId>swagger-maven-plugin</artifactId>
                <version>3.1.3</version>
                <configuration>
                    <apiSources>
                        <apiSource>
                            <springmvc>false</springmvc>
                            <locations>net.jeffsbox.beans</locations>
                            <basePath>/api</basePath>
                            <info>
                                <title>DocId</title>
                                <description>documentation of DocId webservice</description>
                                <version>v1</version>
                            </info>
                            <swaggerDirectory>${project.build.directory}/api</swaggerDirectory>
                            <attachSwaggerArtifact>true</attachSwaggerArtifact>
                        </apiSource>
                    </apiSources>
                </configuration>
                <executions>
                    <execution>
                        <phase>${phase.generate-documentation}</phase>
                        <!-- fx process-classes phase -->
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>io.github.robwin</groupId>
                <artifactId>swagger2markup-maven-plugin</artifactId>
                <version>0.9.3</version>
                <configuration>
                    <inputDirectory>${project.build.directory}/api</inputDirectory>
                    <outputDirectory>${project.build.directory}/${generated.asciidoc.directory}</outputDirectory>
<!--                    specify location to place asciidoc files -->
                    <markupLanguage>asciidoc</markupLanguage>
                </configuration>
                <executions>
                    <execution>
                        <phase>${phase.generate-documentation}</phase>
                        <goals>
                            <goal>process-swagger</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <warSourceDirectory>${project.build.directory}/${project.artifactId}-${project.version}</warSourceDirectory>
                    <port>8080</port>
                    <path>/</path>
                </configuration>
                <executions>
                    <execution>
                        <id>run-tomcat</id>
                        <configuration>
                            <fork>true</fork>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Web.xml
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Example REST Service</display-name>

    <!-- location of spring xml files -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param>

    <!-- the listener that kick-starts Spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- CXF servlet -->
    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <!-- If you want to leverage the Servlet3's async feature in Tomcat, please enable this feature -->
<!--        <async-supported>true</async-supported> -->
    </servlet>

    <!-- all our webservices are mapped under this URI pattern -->
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>

    <filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

    <init-param>
        <param-name>cors.allowGenericHttpRequests</param-name>
        <param-value>true</param-value>
    </init-param>

    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>

    <init-param>
        <param-name>cors.allowSubdomains</param-name>
        <param-value>false</param-value>
    </init-param>

    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, HEAD, POST, DELETE, OPTIONS</param-value>
    </init-param>

    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>*</param-value>
    </init-param>

    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>true</param-value>
    </init-param>

    <init-param>
        <param-name>cors.maxAge</param-name>
        <param-value>3600</param-value>
    </init-param>

    </filter>

    <filter-mapping>
        <!-- CORS Filter mapping -->
        <filter-name>CORS</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>ApiOriginFilter</filter-name>
        <filter-class>com.github.kongchen.swagger.sample.wordnik.util.ApiOriginFilter</filter-class>
      </filter>
    <filter-mapping>
        <filter-name>ApiOriginFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
</web-app>

application.context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cxf="http://camel.apache.org/schema/cxf"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
        http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
        http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <!-- REST resources -->
    <bean id="docidService" class="net.jeffsbox.services.DocIDService" />
    <bean id="identityService" class="net.jeffsbox.services.IdentityService" />

    <!-- Camel beans definitions -->
    <bean id="monitorBean" class="net.jeffsbox.beans.MonitorBean" />
    <bean id="identityBean" class="net.jeffsbox.beans.IdentityBean" />
    <bean id="unimplementedHTTPError" class="net.jeffsbox.beans.RESTErrorBean">
        <property name="statusCode" value="501" />
        <property name="message" value="Resource not implemented" />
    </bean>

    <!-- JAXRS providers -->
    <bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />

    <bean id="swagger2Feature" class="org.apache.cxf.jaxrs.swagger.Swagger2Feature">
        <!-- customize some of the properties -->
        <property name="basePath" value="/api"/>
        <property name="resourcePackage" value="net.jeffsbox.services"/>
        <property name="version" value="1.0.0"/>
        <property name="host" value="localhost:8080"/>
        <property name="title" value="Swagger DocId"/>
        <property name="description" value="This is a app."/>
        <property name="contact" value="apiteam@swagger.io"/>
        <property name="license" value="Apache 2.0"/>
        <property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>
        <property name="scan" value="true"/>
    </bean>

    <!-- Tell CXF/JAX-RS where the REST service is defined -->
    <!-- Specifying the address as '/' or '/something' makes sure it uses the containing app server. In certain configurations,
        not including address causes Camel to start a Jetty instance which hosts the REST service. This can cause conflicts in dependencies. -->
    <jaxrs:server id="jaxRsServer" address="/jaxrs">
        <jaxrs:serviceBeans>
            <ref bean="docidService" />
            <ref bean="identityService" />
        </jaxrs:serviceBeans>
        <jaxrs:providers>
            <ref bean="jsonProvider" />
        </jaxrs:providers>
        <jaxrs:features>
            <ref bean="swagger2Feature" />
        </jaxrs:features>
    </jaxrs:server>

      <cxf:rsServer id="rsServer" address="/rest">
        <cxf:serviceBeans>
         <ref bean="docidService" />
         <ref bean="identityService" />
        </cxf:serviceBeans>
        <cxf:providers>
           <ref bean="jsonProvider"/>
        </cxf:providers>
      </cxf:rsServer>

    <!-- Camel routes definitions -->
    <camelContext trace="true" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="cxfrs://bean://rsServer" />
            <to uri="log:body?level=INFO" />
            <choice>
                <when>
                    <simple>${in.header.camelhttppath} == '/monitor/ping'</simple>
                    <to uri="direct:ping" />
                </when>
                <when>
                    <simple>${in.header.camelhttppath} == '/identity/get'</simple>
                    <to uri="direct:getIdentity" />
                </when>
                <when>
                    <simple>${in.header.camelhttppath} == '/identity/post'</simple>
                    <to uri="direct:notImplemented" />
                </when>
                <otherwise>
                    <to uri="direct:notImplemented" />
                </otherwise>
            </choice>
        </route>
        <route>
            <from uri="direct:ping" />
            <to uri="bean:monitorBean?method=processPing" />
        </route>
        <route>
            <from uri="direct:getIdentity" />
            <to uri="bean:identityBean?method=processGet" />
        </route>
        <route>
            <from uri="direct:notImplemented" />
            <to uri="bean:unimplementedHTTPError?method=fill" />
        </route>
    </camelContext>
</beans>

I can access te swagger-ui documentation at : http://localhost:8080/?url=http://localhost:8080/ws/jaxrs/swagger.json
This documentation contains everything !!

A: Just a basic error in the swagger-maven-plugin..
The attribute 'location' has to point on your services...


text:
Q: Is it possible to use the Stack Exchange engine internally? Is there a way to setup the Stack Exchange engine to run on an intranet for a corporation?
The idea being that users can go to the site, submit a question and have it routed appropriately by moderation.
This way non-technical users can go to the site, post up a question. And then IT can route the question to software, customer service, helpdesk, etc. Each division being its own specific site.
If possible, how feasible is it? Does it require a lot of setup/maintenance? Are there fees involved? Can it be re-skinned?


text:
Q: Android wifi's signal strength
Possible Duplicate:
Android: How to monitor WiFi signal strength

Is there a way to know the signal strength of a wifi network using code?

A: Take a look at these:
getScanResults()
level

http://developer.android.com/reference/android/net/wifi/WifiManager.html
http://developer.android.com/reference/android/net/wifi/ScanResult.html


text:
Q: BibLaTeX: What can I do to combine APA, numeric citations and German language options? (\apashortdash error) I am writing a text in German and I would like to use an APA-style bibliography with numeric citations in the text. (I know, biblatex-apa is not to be messed with, but both APA and numerics are explicitely required for the assignment.) Using the english option for babel, that works exactly as expected. As soon as I change to ngerman though, I get the known "\apashortdash undefined" error and TexMaker refuses to compile.
What can I do to combine APA, numeric citations and German?
Here is my MWE:
@Inbook{redei2008fish,
title="FISH (fluorescence in situ hybridization)",
bookTitle="Encyclopedia of Genetics, Genomics, Proteomics and Informatics",
year="2008",
publisher="Springer Netherlands",
address="Dordrecht",
pages="689--689",
doi="10.1007/978-1-4020-6754-9_6006"
}

@article{volpi2008fish,
  title={FISH glossary: an overview of the fluorescence in situ hybridization technique},
  author={Volpi, Emanuela V and Bridger, Joanna M},
  journal={Biotechniques},
  volume={45},
  number={4},
  pages={385--409},
  year={2008},
  publisher={Future Science}
}

\documentclass{scrartcl}

\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage[
    bibstyle=apa,
    citestyle=numeric-comp,
    backend=biber
    ]{biblatex}

\makeatletter
\RequireBibliographyStyle{numeric}
\makeatother

\addbibresource{fishbib.bib}

\usepackage[german=guillemets]{csquotes}
\usepackage[breaklinks=true]{hyperref}

\begin{document}
Beispieltext mit Bezug auf Text 1 \cite{redei2008fish}.
Beispieltext mit Bezug auf Text 2 \cite{volpi2008fish}.

\printbibliography

\end{document}

A: biblatex-apa is supposed to be used both as citation and bibliography style at the same time (i.e. style=apa,). No care has been taken to allow you to use the citation and bibliography style separately or independently of each other.
This means that the bibliography and citation styles may define or redefine macros in a way that assumes the other file is loaded as well.
Specifically your example never loads the citation style apa.cbx, which defines the command \apashortdash that is redefined by the localisation files. You can avoid this error by providing \apashortdash.
There is absolutely no guarantee that everything will look as you want, but the example compiles without error for me.
\documentclass{scrartcl}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[german=guillemets]{csquotes}
\usepackage[
  backend=biber,
  bibstyle=apa,
  citestyle=numeric-comp,
]{biblatex}
\usepackage[breaklinks=true]{hyperref}

\makeatletter
\RequireBibliographyStyle{numeric}
\makeatother

\providecommand{\apashortdash}{-}

\addbibresource{biblatex-examples.bib}

\begin{document}
Beispieltext mit Bezug auf Text 1 \cite{sigfridsson}.
Beispieltext mit Bezug auf Text 2 \cite{worman}.

\printbibliography
\end{document}


text:
Q: Replace field value(s) in a String Using Google Guava is there String utility to easily replace string field inside like this:
String query = mydb..sp_mySP ${userId}, ${groupId}, ${someOtherField}

Where I can do something like this:
StringUtil.setString(query)
   .setField("userId", "123")
   .setField("groupId", "456")
   .setField("someOtherField", "12-12-12");

Then the resulting String would be:
mydb..sp_mySP 123, 456, 12-12-12

Of course, setting the String field patter like ${<field>} before the operation...
Anyway, this is my approach:
public class StringUtil {
    public class FieldModifier {
        private String s;
        public FieldModifier(String s){
            this.s = s;
        }
        public FieldModifier setField(String fieldName, Object fieldValue){
            String value = String.valueOf(fieldValue);
            s = modifyField(s, fieldName, value);
            return new FieldModifier(s);
        }
        public String get() {
                return s;
        }
        private String modifyField(String s, String fieldName, String fieldValue){
            String modified = "";
            return modified;
        }
    }
    public FieldModifier parse(String s){
        FieldModifier fm = new FieldModifier(s);
        return fm;
    }
}

So in this case, I just need to put the actual code in the modifyField function that will modify the string in a straightforward way. Also if there's a way so the parse function be static so I can just do StringUtil.parse(...) without doing new StringUtil().parse(...) which really doesn't look good.

A: Yes, String.format().
String s = "Hey %s! Cool %s, right?";
System.out.println(String.format(s, "xybrek", "feature"));

A: There's no such thing in Guava. You can have a look at SpEL (Spring Expression Language) which can do string templating, or other templating frameworks such as Velocity or Freemarker.

A: Using Guava? No.
Though an enhancement has recently been requested to support this (see here).
Anyway, this is still doable using Apache Commons Lang's StrSubstitutor.


text:
Q: Biased lower bounded random walk I have a random walk with the following rules:

*

*It starts at 2

*At each step it goes up by 1 with chance .4, down by one with chance .4 and up by 2 with chance .2

*The walk ends if it reaches 0

I want to know two things...

*

*Firstly is this guaranteed to terminate at some point - I believe it is but confirmation would be nice. If not can a probability be given to it not finishing?

*What is the probability of the walk having a given maximum value (eg what is the probability of it getting to 10 but no higher before terminating at zero).

And just so you know I used to study maths at university but that was a while ago now so best to assume that I know basic stuff but try not to assume too much knowledge on my part in an answer. :) I also was never great at statistics. ;-)
I tried solving the problem using a difference equation but I got stuck trying that. I'm not sure that was the right way to go really...

A: I can handle part 1. I'm thinking about part 2, but it looks quite difficult in general - I'll edit this answer if I figure it out.
For part 1, look at the probability of eventually going one space left. Call this P.
Then the probability of eventually going two spaces left is just going to be the probability of going one space left, and then going another space left: $P^2$. Similarly, the probability of going three squares left is $P^3$, et cetera...
Now, directly from the random walk's parameters, we have:
$P=.4+.4P^2+.2P^3$
Why? Well, we have a .4 chance of going left immediately, in which case we're finished ($.4$). We have a .4 chance of starting by going right, in which case we have to work our way left two spaces eventually ($.4P^2$). And we have a .2 chance of starting by going right two spaces, in which case we have to go left three spaces eventually ($.2P^3$).
WolframAlpha tells us that of the three solutions to this equation, one is negative and the other two are P=1 and P=~0.561553.
The negative solution is obviously wrong. The P=1 solution is non-obviously wrong, but since your random walk tends to increase, there's a positive probability that it will just spiral towards infinity. Therefore P is about 0.561553, and the probability of finishing from the starting point of 2 is $0.561553^2$ which is about $0.315341$.