text:
Q: DefaultEquality Comparator in LINQ I have the following code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<I> bars = new List<I>();
            bars.Add(new A() { Id = 1 });
            bars.Add(new B() { Id = 1 });
            bars.Add(new A() { Id = 1 });

            var distictBars = bars.Distinct();

            foreach (var item in distictBars)
            {
                Debug.WriteLine(item.Name);
            }
        }
    }

    interface I
    {
        string Name { get; }
    }

    class Base
    {
        public int Id { get; set; }
    }

    class A : Base, I, IEquatable<A>
    {
        public string Name
        {
            get { return this.Id + "-A"; }
        }

        public bool Equals(A other)
        {
            return this.Id == other.Id;
        }

        public override bool Equals(object obj)
        {
            if (obj is A)
                return this.Equals(obj as A);
            else
                return object.ReferenceEquals(this, obj);
        }
    }

    class B : Base, I, IEquatable<B>
    {
        public string Name
        {
            get { return this.Id + "-B"; }
        }

        public bool Equals(B other)
        {
            return this.Id == other.Id;
        }

        public override bool Equals(object obj)
        {
            if (obj is A)
                return this.Equals(obj as A);
            else
                return object.ReferenceEquals(this, obj);
        }
    }
}

The output is the following
1-A
1-B
1-A

I need however the following
1-A
1-B

that is, eliminate the duplicates of type A or B. It seems that the Distinct LINQ method didn't take in consideration my Equals override, nor the IEquitable interface implementation.
How should I proceed in order than that method does the specified comparison?

A: The Distinct method will likely use something similar to a HashSet<T> internally, which relies on a hash code (obviously). You will need to also override GetHashCode.

It seems to me you have some unnecessary duplication in general. Both your A and B classes share basically the same logic for determining equality; is what you want to ensure that two Base objects are equal if their IDs are equal and they are the same type? (This is what it looks like to me; your implementation seems to contain a couple of mistakes in this case, but that's still my best guess.)
If so, just make Base implement IEquatable<Base> and your A and B implementations become much simpler:
class Base : IEquatable<Base>
{
    public Base(int id)
    {
        Id = id;
    }

    public int Id { get; private set; }

    public bool Equals(Base other)
    {
        if (other == null)
        {
            return false;
        }

        // Ensure As only compare equal with other As
        // and the same for Bs (and potentially other subtypes).
        return other.GetType().Equals(GetType()) && other.Id == Id;
    }

    public override bool Equals(object other)
    {
        if (other is Base)
        {
            return Equals((Base)other);
        }

        return false;
    }

    public override int GetHashCode()
    {
        return Id;
    }
}

class A : Base, I
{
    public A(int id) : base(id)
    { }

    public string Name
    {
        get { return this.Id + "-A"; }
    }
}

class B : Base, I
{
    public B(int id) : base(id)
    { }

    public string Name
    {
        get { return this.Id + "-B"; }
    }
}

Notice that I also changed the setter on the Id property to private; in general, it's a very risky game to make a field or property publicly writable when it's used in the type's GetHashCode implementation (since if an object's hash code ever changes, it stops working as a key in a hashtable).

This comment becomes unnecessary if you apply my recommendation above.
Also, warning! It looks to me like you've got a risk of infinite recursion in your B.Equals method:
    public override bool Equals(object obj)
    {
        if (obj is A)
            // There is no method with the signature Equals(A);
            // so this will just call your Equals(object) method --
            // i.e., THIS method -- over and over again.
            return this.Equals(obj as A);
        else
            return object.ReferenceEquals(this, obj);
    }

A: You need to override .GetHashCode() in your objects.  I suggest something like this:
public override int GetHashCode() {
    return this.Id;
}


text:
Q: inserting an item into a deque Focusing specifically on the insertFront() method in main, how do I go about creating an item that holds the values of num and price.  Further more should it hold the values of num and price or userinNum and userinPrice?
theQueue.insertFront(//ITEM???);

Main method MyDequeApp:
import java.*;
import java.util.*;

public class MyDequeApp {

public static void main(String[] args)
{
    String userinNum;
    double userinPrice;

    Item item1= new Item();

    Scanner scan1=new Scanner(System.in);

    System.out.println("Enter the number of elements in the que");
    int queElm=scan1.nextInt();

    MyDeque theQueue=new MyDeque(queElm);

    System.out.println("1. Insert to front");
    System.out.println("2. Insert to rear");
    System.out.println("3. Remove from front");
    System.out.println("4. Remove from rear");
    System.out.println("5. Peek front");
    System.out.println("6. Peek rear");
    System.out.println("7. Display que");
    System.out.println("8. Quit");

    int queOp=scan1.nextInt();

    switch(queOp)
    {
        //1. Insert to front
        case 1:
            System.out.println("Enter an item #");
            userinNum=scan1.nextLine();
            item1.setNum(userinNum);
            System.out.println("Enter a price");
            userinPrice=scan1.nextDouble();
            item1.setPrice(userinPrice);
            System.out.println(item1.toString());
            theQueue.insertFront();
                break;

        case 5:
            theQueue.peekFront();
                break;

        default:
            break;

    }

}

}

Class Item:
public class Item {

double price;
String num;

//set/get method
public void setPrice(double userinPrice)
{
    price=userinPrice;
}

public double getPrice()
{
    return price;
}

public void setNum(String userinNum)
{
    num=userinNum;
}

public String getNum()
{
    return num;
}

//toString()
public String toString()
{
    return "Item number: "+num+"\n"+"Price: $"+price;
}

}

Insert method from class MyDeque:
    public void insertFront(Item x)
    {
    if(front==maxSize)
        front=0;
    queArray[front++]=x;
    nItems++;
    }

A: Yes, I would insert the entire Item in the queue, which would have both the price and num set.
To create an Item just create and instance ('new it up'), then set the num and price:
Item newItem = new Item();
newItem.setPrice(someDoubleValue);
newItem.setNum(someStringValue);

theQueue.insertFront(newItem);

A: You can just create a constructor for Item that accepts the values of userinNum and userinPrice and invoke it after retrieving the user's inputs.
public Item(String num, double price){
    this.num = num;
    this.price = price;
}

By using a constructor like this, you can get the user's inputs and store them in variables, and then once you have the input you can invoke it and pass it those variables:
item1 = new Item(userinNum, userinPrice);

Then you can just add item1 to your dequeue. This combines the setNum() and setPrice() steps into one line.

A: Apologies if I've misunderstood your question here

Further more should it hold the values of num and price or userinNum
  and userinPrice?

userinNum and userinPrice are just variables you're using to hold the input given to you by the user. num and price just attributes of the Item class, to which you are assigning the values the user gave you.
To add your item to the queue, change the line theQueue.insertFront(); to  theQueue.insertFront(item1);.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MATLAB: How to 'color in' pixels of a grayscale image sequence? Supposing I have the linear indices of the pixels which I would like to 'color in'.
If I wanted to set all of those pixels to some specific value in my grayscale image sequence, I could do this:
gryscl_imSeq(LinearPixIndx) = 0.7;

edit: where 'LinearPixIndx' is a p-element vector containing the linear indices of the pixels in the image sequence.
If however, I  want to introduce some color, I would first need to convert my grayscale image sequence into an m x n x 3 x p matrix, which I could do like this:
RGBvideo = reshape(repmat(reshape(gryscl_imSeq,[],size(gryscl_imSeq,3)),3,1),...
         [size(gryscl_imSeq,1) size(gryscl_imSeq,2) 3 size(gryscl_imSeq,3)]);

If somebody could tell me how to convert my grayscale linear pixels indices into corresponding indices for the RGBvideo I would really appreciate it.
Or if there is a better way to go about what I'm trying to do, I would be very grateful for any suggestions.
Thanks in Advance,
N

A: The question isn't really clear, but I guess I understand what you want. Here's one way to do it.
First I think there's a slightly more elegant way to convert from grayscale to RGB:
% determine image sequence dimensions
[m, n, N] = size(gryscl_imSeq);
% expand to RGB
rgb_imSeq = reshape(gryscl_imSeq, [m, n, 1, N]);
rgb_imSeq = repmat(rgb_imSeq, [1, 1, 3, 1]);

After that, in order to be able to apply your linear indices to all color channels and all frames, you need to explicitly linearize the pixel index by reshaping. Then you can color the pixels, and transform back into the form width x height x color channels x frames:
% linearize image dimensions
rgb_imSeq = reshape(rgb_imSeq, [m * n, 3, N]);
% color pixels
rgb_imSeq(LinearPixIndx, :, :) = repmat([1 0 0], [numel(LinearPixIndx), 1, N]);
% original shape
rgb_imSeq = reshape(rgb_imSeq, [m, n, 3, N]);

Here [1 0 0] is the RGB representation of the color you want to use, in this case red.


text:
Q: Limit involving the laplacian I'm trying to prove that if $\Omega$ is an open subset of $\mathbb{R}^n$ and $u$ a $C^2$ function then $$\lim_{r\to 0}\frac{2n}{r^2}\left(u(x)-\frac{1}{|\partial B_r(x)|}\int_{\partial B_r(x)}u(y)d\sigma_y\right)=-\Delta u(x).$$
I tried to use the representation formula on balls, but nothing came out of it..

A: One can get this by writing out Taylor's expansion, but I'll try Green's second identity just to see what happens. Assume $n\ge 3$. Let $v(y)=|y-x|^{2-n}-r^{2-n}$ (noting that this is a fundamental solution of $\Delta$) and $U=\{y:\epsilon<|y-x|<r\}$. Then the boundary integral is
$$\int_{\partial U}\left(v\frac{\partial u}{\partial n}-u\frac{\partial v}{\partial n}\right) =-(n-2)\,r^{1-n}\int_{|y-x|=r} u(y) -\int_{|y-x|=\epsilon} \left( v\frac{\partial u}{\partial n} - (n-2)\,\epsilon^{1-n}u(y) \right) \\ \to (n-2)\left\{|\mathbb S^{n-1}| u(x)-r^{1-n}\int_{|y-x|=r} u(y)\right\} \qquad \text{as }\epsilon\to 0$$
This is encouraging. By the identity, the above integral is equal to
$$\int_U (v\Delta u-u\Delta v)=\int_U v\;\Delta u \approx  \Delta u(x)\, \int_U v$$
where $\approx $ is justified by the continuity of $\Delta u$. As $\epsilon\to 0$, the last integral converges to
$$\int_{0}^r (t-r^{2-n}t^{n-1})\,dt = \frac{r^2}{2}-\frac{r^2}{n}=\frac{n-2}{2n}r^2.$$
Hurray! $\Box$
Same idea works in two dimensions, but  with $v(y)=\log \frac{|y-x|}{r}$. Again, this is not the quickest proof, but I did not want to type out the boring Taylor's approximation argument.

A: Taking the mean value of the Taylor expansion over $\partial B_r(x)$ is a simple way to show this.
$$
\begin{align}
&\frac1{|\partial B_r(x)|}\int_{\partial B_r(x)}(u(y)-u(x))\,\mathrm{d}\sigma_y\\
&=\color{#C00000}{\frac1{|\partial B_r(x)|}\int_{\partial B_r(x)}\left(\sum_{k=1}^nu_k(x)(y_k-x_k)+\sum_{j< k}u_{jk}(x)(y_j-x_j)(y_k-x_k)\right)\,\mathrm{d}\sigma_y}\\
&+\color{#00A000}{\frac1{|\partial B_r(x)|}\int_{\partial B_r(x)}\frac12\sum_{k=1}^nu_{kk}(x)(y_k-x_k)^2\,\mathrm{d}\sigma_y}\\
&+\color{#0000FF}{\frac1{|\partial B_r(x)|}\int_{\partial B_r(x)}o(|y-x|^2)\,\mathrm{d}\sigma_y}\tag{1}
\end{align}
$$
By cancellation due to the symmetry of $\partial B_r(x)$, the red integral is $0$. It is simple to see that the blue integral is $o(r^2)$. All that is left is the green integral.
By symmetry, the mean value of $(y_k-x_k)^2$ over $\partial B_r(x)$ is independent of $k$, and the mean value of $\sum\limits_{k=1}^n(y_k-x_k)^2$  over $\partial B_r(x)$ is $r^2$. Thus, the mean value of $(y_k-x_k)^2$ over $\partial B_r(x)$ is $r^2/n$.
Thus,
$$
\begin{align}
&\lim_{r\to0}\frac{2n}{r^2}\frac1{|\partial B_r(x)|}\int_{\partial B_r(x)}(u(y)-u(x))\,\mathrm{d}\sigma_y\\
&=\lim_{r\to0}\frac{2n}{r^2}\color{#C00000}{0}\\
&+\lim_{r\to0}\frac{2n}{r^2}\color{#00A000}{\frac{r^2}{n}\frac12 \sum_{k=1}^nu_{kk}}\\
&+\lim_{r\to0}\frac{2n}{r^2}\color{#0000FF}{o(r^2)}\\
&=\sum_{k=1}^nu_{kk}\tag{2}
\end{align}
$$
Rearranging $(2)$ yields
$$
\lim_{r\to0}\frac{2n}{r^2}\left(u(x)-\frac1{|\partial B_r(x)|}\int_{\partial B_r(x)}u(y)\,\mathrm{d}\sigma_y\right)=-\Delta u(x)\tag{3}
$$


text:
Q: What is the fastest way to compare two strings in C? For clarity I'm only talking about null terminated strings.
I'm familiar with the standard way of doing string comparisons in C with the usage of strcmp. But I feel like it's slow and inefficient.
I'm not necessarily looking for the easiest method but the most efficient.
Can the current comparison method (strcmp) be optimized further while the underlying code remains cross platform?
If strcmp can't be optimized further, what is the fastest way which I could perform the string comparison without strcmp?
Current use case:

*

*Determine if two arbitrary strings match

*Strings will not exceed 4096 bytes, nor be less than 1 byte in size

*Strings are allocated/deallocated and compared within the same code/library

*Once comparison is complete I do pass the string to another C library which needs the format to be in a standard null terminated format

*System memory limits are not a huge concern, but I will have tens of thousands of such strings queued up for comparison

*Strings may contain high-ascii character set or UTF-8 characters but for my purposes I only need to know if they match, content is not a concern

*Application runs on x86 but should also run on x64

Reference to current strcmp() implementation:

*

*How does strcmp work?

*What does strcmp actually do?

*GLIBC strcmp() source code
Edit: Clarified the solution does not need to be a modification of strcmp.
Edit 2: Added specific examples for this use case.

A: I'm afraid your reference imlementation for strcmp() is both inaccurate and irrelevant:

*

*it is inaccurate because it compares characters using the char type instead of the unsigned char type as specified in the C11 Standard:

7.24.4 Comparison functions
The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.

*It is irrelevant because the actual implementation used by modern compilers is much more sophisticated, expanded inline using hand-coded assembly language.
Any generic implementation is likely to be less optimal, especially if coded to remain portable across platforms.
Here are a few directions to explore if your program's bottleneck is comparing strings.

*

*Analyze your algorithms, try and find ways to reduce the number of comparisons: for example if you search for a string in an array, sorting that array and using a binary search with drastically reduce the number of comparisons.

*If your strings are tokens used in many different places, allocate unique copies of these tokens and use those as scalar values.  The strings will be equal if and only if the pointers are equal. I use this trick in compilers and interpreters all the time with a hash table.

*If your strings have the same known length, you can use memcmp() instead of strcmp(). memcmp() is simpler than strcmp() and can be implemented even more efficiently in places where the strings are known to be properly aligned.

EDIT: with the extra information provided, you could use a structure like this for your strings:
typedef struct string_t {
    size_t len;
    size_t hash;  // optional
    char str[];   // flexible array, use [1] for pre-c99 compilers
} string_t;

You allocate this structure this way:
string_t *create_str(const char *s) {
    size_t len = strlen(s);
    string_t *str = malloc(sizeof(*str) + len + 1;
    str->len = len;
    str->hash = hash_str(s, len);
    memcpy(str->str, s, len + 1);
    return str;
}

If you can use these str things for all your strings, you can greatly improve the efficiency of the matching by first comparing the lengths or the hashes.  You can still pass the str member to your library function, it is properly null terminated.


text:
Q: React Native renderRow error: undefined is not an object (evaluating 'e.id') Trying to renderRow in a ListView in react native. The list is populated from the results of a user search. There is a debounce of 400 ms to keep the number of requests down. The problem is if I setState while the renderRow is happening on the last state Change the app will crash with undefined fetching the rowData.id. I've tried to catch if results are 'undefined' or null, through a serious of if statements, also checking this.state.dataSource.getRowCount() === 0 before rendering the ListView at all to try and avoid this. It is a listView with multiple sections and headers.
 renderRow: function(
    rowData: Object,
    sectionID: number | string,
    rowID: number | string,
    highlightRowFunc: (sectionID: ?number | string, rowID: ?number | string) => void,
  ) {
    if(rowData) {
      switch(sectionID) {
        case GLOBAL.PATHWAYTITLE:
        if(rowData){
          var content = <PMSearchPathwayCell
            refs="cell"
            key={rowData.pathway_id}
            onSelect={() => this.selectPathway(rowData) }
            onSelectMore={() => this.onSelectMore(rowData) }
            onHighlight={() => highlightRowFunc(sectionID, rowID) }
            onUnhighlight={() => highlightRowFunc(null, null) }
            pathway={rowData}
            />
        }
            break;
        case GLOBAL.PICMONICTITLE:
          if (rowData == null) {
            console.log(rowData.id);
          }
          if(rowData) {
          var content = <PMSearchCardCell
            refs="cell"
            key={rowData.id}
            onSelect={() => this.selectCard(rowData) }
            onSelectMore={() => this.onSelectMore(rowData) }
            onHighlight={() => highlightRowFunc(sectionID, rowID) }
            onUnhighlight={() => highlightRowFunc(null, null) }
            card={rowData}
            />
          }
            break;
            //Default added. Since we provide the array of pathwaytitle and picmonictitle this isn't a scenario that we
            //should ever encounter.
        default:
        console.log("SectionID for rowRender not set!");
        var content = <Text>Not Available</Text>
            break;
      }
    }

    return (
      <View>
      {content}
      </View>
    );
  },


text:
Q: jquery: keep aspect ratio and contain div inside window I am trying to create a div that will keep it's aspect ratio that maintains a with and height that will not exceed the screen's bounds.
This is the code that I have right now:

wW=$(window).width();
wH=$(window).height();
wHx=(wW/16)*9;
wWx=(wH/9)*16;
if(wW>wWx){
    vH1=$('.container').height();
    vW1=(vH1/9)*16;
    vP1=($(window).width()-vW1)*0.5;
    $('.container').css('width',vW1+'px');
    $('.container').css('left',vP1+'px');
    $('.container').css('height','100%');
    $('.container').css('top','0');
}
if(wH>wHx){
    vW2=$('.container').width();
    vH2=(vW2/16)*9;
    vP2=($(window).height()-vH2)*0.5;
    $('.container').css('height',vH2+'px');
    $('.container').css('top',vP2+'px');
    $('.container').css('width','100%');
    $('.container').css('left','0');
}

It almost works as intended but it fails in some random situations and the page needs to be refreshed to fix the problem.
Edit: the same function is executed on resize (it fails in some random cases during resize):
$(window).resize(function(){
    .........
});

Edit2: The script fails, after manually resizing the window and then clicking the minimize/maximize button of the browser. I've got the same results with Chrome and Firefox.

A: This could help
// HTML

// CSS (SASS)
.container {
  background: red;
  max-width: 100%;

  &:before {
    content: '';
    display: block;
    // for 16/9 this is the height you need
    padding-top: 56.25%;

  }
}

// JavaScript
$(function(){
  $(window).resize(function(){
    var width  = $(window).width(),
        height = $(window).height();

    if (width/height > 16/9) {
      $('.container').css('max-width', height * 16 / 9);
    } else {
      $('.container').css('max-width', '100%');
    }
  })
  // trigger resize so it takes the
  // right size on load
  .trigger('resize');

});

examle http://codepen.io/istavros/full/vxwVoW/

A: I believe this is what you are looking for:

//CSS
.container {
max-width: 100vw;
max-height: 100vh;
}


text:
Q: Mesons wavefunction symmetry Is it possible to write the valence quark wavefunction for mesons which is overall symmetric in nature?
Because acc. to me, we can not say directly that flavor and color wavefunction is symmetric as they builds from quark and anti-quark.
They do not obey pauli exclusion principles like baryons.
Is it correct to think like that?

A: Basically yes; you may connect quarks and antiquarks with the C operator, and introduce G-parity, etc, but, yes, indeed, it is a nonsensical mistake to attempt to play the same generalized Pauli exclusion game you play with baryons.
Just review the meson-building rules, first practicing on fermion-antifermion systems such as ortho and para positronium, and only then generalizing to quarks. Meson wavefunctions factorize into space, spin, and color and flavor parts.
Make sure you can prove
$$
P=(-)^L\\
C=(-)^{L+S}\\
G=(-)^{S+L+I}.
$$
It thus follows that the G parity of π s is -, whilst  + for ρ s...


text:
Q: Unknown Template Encoding of .iso File I have a file saved as .iso which looks like this on notepad++

I can read it using python:
def openfile():
  with open('file.iso', mode='rb') as file:
     data = file.read()

And this is the result I get

What is the encoding of the .iso file and how can I write a file in that format using python?

A: I figured it out. It's a fingerprint template saved as ASCII characters. I converted the data I got from the python script into hex and used this site
to convert it back to the ASCII characters.
Thanks for everyone who took his/her time to comment. Much appreciated


text:
Q: Detecting the upper side of a dice Is it possible to detect the upper side of a dice? While this will be an easy task if you look from the top, from many perspectives multiple sides are visible.
Here is an example of a dice, feel free to take your own pictures:

You usually want to know the score you have achieved. It is easy for me to extract ALL dots, but how to only extract those on the top? In this special case, the top side is the largest, but this might not always be true. I am looking for someting which evaluates the distortion of the top square (or circle in this case, which I can extract) in relation to the perspective given by the grid in the bottom.
Example program with some results is given below.
import numpy as np
import cv2

img = cv2.imread('dice.jpg')

# Colour range to be extracted
lower_blue = np.array([0,0,0])
upper_blue = np.array([24,24,24])

# Threshold the BGR image
dots = cv2.inRange(img, lower_blue, upper_blue)

# Colour range to be extracted
lower_blue = np.array([0,0,0])
upper_blue = np.array([226,122,154])

# Threshold the BGR image
upper_side_shape = cv2.inRange(img, lower_blue, upper_blue)

cv2.imshow('Upper side shape',upper_side_shape)
cv2.imshow('Dots',dots)

cv2.waitKey(0)
cv2.destroyAllWindows()

Some resulting images:

A: The best solution is dot size, which I mentioned in the comment. You find the largest dot, consider it as max, and then create a tolerance level.
But what if all dots are nearly equal (viewing it from the edge at angle that makes things equidistant), or even too small? The best solution for that is creating a boundary to capture the dots. This requires the analysis of the dice's edge (edge detection basically), but once you define the boundary, you're solid.
All you need is to capture the edges of the dice from the perspective you're seeing.
Here's a visual example:

Since you have a virtual boundary set, you'll simply measure dots above a specific point on the y-axis.

A: The dot size is a good heuristic, but I would also add the dot roundness: if you compute the second order image moments of the binarized dots, the more the x and y moment are similar, the more round the figure. This will of course fail, like the size, for a side view, but then what does "top-side" really means if you can't sense gravity..

A: why try to chop up the image at all? based on what numbers you see on the side you can infer what number is on the top. your side numbers can be used as a check to validate your guess.
note that you'll have to be careful about handedness (see: http://mathworld.wolfram.com/Dice.html)


text:
Q: How to append elements inside for loop in Bash? I have the below pseudo code:
#!/bin/bash
USERS_LIST=$(cat users.txt)

function exit_loop() {
    declare -a exceeded_users
    if [[ $SUM -gt 7000 ]];then
        echo $SUM
        exceeded_users+=("$USER")
    fi
    #CHECK LAST USER IN THE ARRAY
    if [[ $USER = ${a[exceeded_users{#exceeded_users[@]}-1]} ]];then
        break
    fi
    echo "${exceeded_users[@]}"
}

for USER in $USERS_LIST;do
    SUM=$(( $LAST_DATE_SIZE - $PREVIOUS_DATE_SIZE ))
    exit_loop
done

My goal is that the function "exit_loop" function will exit the loop once it's looped all the users what exceeded 700mb, but looks like when I am echoing the array exceeded_users[@] I am not getting any output. I need to get the array value at the second if statement.
If you got another way to exit the loop once the loop run once all
all the users that exceeded 700MB I will appropriate that.

A: The array exceeded_users is declared locally within the function exit_loop so it will not retain the values stored between calls. Try either declaring exceeded_users before the function exit_loop so it is global, or declaring it with the -g flag declare -ag exceeded_users to make it global. (Thanks to Charles Duffy for pointing out the -g flag)


text:
Q: Is there any way to look up the controller and method names from a request in Play Framework 2.0 When I'm in an Action block, how do I figure out which controller is calling me?
In Play 1.0, you could get this information directly from the request object. Is there any way of doing this in Play 2.0 without reparsing conf/routes?
def myAction = {
   implicit request =>
       Logger.info("The controller name is " + <cname>)
       Logger.info("The method name is " + <mname>)
}

A: I don't know of a way to get that info generically, but if you only need to check for a couple of specific routes then this is how I've done it:
(this is in Java but maybe you or someone can translate to Scala)
String requestPath = request().path();
String routeHome = routes.Application.index().toString();

if (requestPath.equals(routeHome))
{
  // user is on Application.index()
}


text:
Q: RSA algorithm for generating decryption key in C The formula for generating decryption key for RSA algorithm is ed = 1 mod T where T is generated using the formula (p-1)(q-1). p and q are two non identical prime number. e is the Encryption Key. So as per the formula if I like to implement the ed = 1 mod T in C program the code block should be
 d = (1%T)/e;

However, I found most of the coding websites(coding website) use d*e = 1 + k * T to generate the decryption key.
I can not understand from where they get k?

A: The modular multiplicative inverse can be found with the extended Euclidean algorithm.
Here is a simple demonstration implementation. Cryptographic implementations generally needed extended-precision arithmetic.
#include <stdio.h>
#include <stdlib.h>

//  Return the multiplicative inverse of e modulo t.
static int invert(int e, int t)
{
    /*  We will work with equations in the form:

            x = d*e + s*t

        where e and t are fixed, and x, d, and s change as we go along.

        Initially, we know these two equations:

            t = 0*e + 1*t.
            e = 1*e + 0*t.

        We will use the Euclidean algorithm to reduce the left side to the
        greatest common divisor of t and e.  If they are relatively prime,
        this eventually produces an equation with 1 on the left side, giving
        us:

            1 = d*e + s*t

        and then d is the multiplicative inverse of e since d*e is congruent to
        1 modulo t.
    */

    //  Now we start with our first values of x, d, and s:
    int x0 = t, d0 = 0, s0 = 1;
    int x1 = e, d1 = 1, s1 = 0;

    //  Then we iteratively reduce the equations.
    while (1)
    {
        /*  Find the largest q such that we can subtract q*x1 from x0 without
            getting a negative result.
        */
        int q = x0/x1;

        /*  Subtract the equation x1 = d1*e + s1*t from the equation
            x0 = d0*e + s0*t.
        */
        int x2 = x0 - q*x1;
        int d2 = d0 - q*d1;
        int s2 = s0 - q*s1;

        /*  If we found the inverse, return it.

            We could return d2 directly; it is mathematically correct.
            However, if it is negative, the positive equivalent might be
            preferred, so we return that.
        */
        if (x2 == 1)
            return d2 < 0 ? d2+t : d2;

        if (x2 == 0)
        {
            fprintf(stderr, "Error, %d is not relatively prime to %d.\n", e, t);
            exit(EXIT_FAILURE);
        }

        /*  Slide equation 1 to equation 0 and equation 2 to equation 1 so we
            can work on a new one.
        */
        x0 = x1; x1 = x2;
        d0 = d1; d1 = d2;
        s0 = s1; s1 = s2;
    }
}

int main(void)
{
    int e = 3, t = 3127, d = invert(e, t);
    printf("The multiplicative inverse of %d modulo %d is %d.\n", e, t, d);
}

Output:

The multiplicative inverse of 3 modulo 3127 is 2085.


text:
Q: NSInvalidArgumentException from OIDAuthorizationService when using google signin in SwiftUI I'm having a terrible day with this unfamiliar error
    2020-08-15 10:00:38.630941+0100 Wicrypt[44349:3718177] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[OIDAuthorizationService presentAuthorizationRequest:presentingViewController:callback:]: unrecognized selector sent to class 0x106b47af0'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000107dfb4b2 __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x0000000107a4b26e objc_exception_throw + 48
    2   CoreFoundation                      0x0000000107e09f12 __CFExceptionProem + 0
    3   CoreFoundation                      0x0000000107dff9e8 ___forwarding___ + 1479
    4   CoreFoundation                      0x0000000107e01a18 _CF_forwarding_prep_0 + 120
    5   Wicrypt                             0x0000000106aac8d2 -[GIDSignIn authenticateInteractivelyWithOptions:] + 626
    6   Wicrypt                             0x0000000106aacd5f -[GIDSignIn authenticateWithOptions:] + 74
    7   Wicrypt                             0x0000000106aac59a -[GIDSignIn signInWithOptions:] + 509
    8   Wicrypt                             0x0000000106aabde6 -[GIDSignIn signIn] + 64
    9   Wicrypt                             0x000000010671810b $s7Wicrypt18GoogleSignInScreenV4bodyQrvg7SwiftUI9TupleViewVyAE0J0PAEE5frame5width6height9alignmentQr12CoreGraphics7CGFloatVSg_AqE9AlignmentVtFQOyAE6SpacerV_Qo__AiEEAjklMQrAQ_AqStFQOyAE6VStackVyAGyAE4TextV_AZtGG_Qo_AuzE6ButtonVyAZGtGyXEfU_yycfU0_ + 91
    10  SwiftUI                             0x00000001095e1d91 $s7SwiftUI18WrappedButtonStyle33_AEEDD090E917AC57C12008D974DC6805LLV4BodyV4bodyQrvgyycAA09PrimitivedE13ConfigurationVcfu_yycfu0_TA + 17
    11  SwiftUI                             0x000000010989c000 $s7SwiftUI25PressableGestureCallbacksV8dispatch5phase5stateyycSgAA0D5PhaseOyxG_SbztFyycfU_ + 32
    12  SwiftUI                             0x0000000109657bac $sIeg_ytIegr_TR + 12
    13  SwiftUI                             0x00000001094dc901 $sIeg_ytIegr_TRTA + 17
    14  SwiftUI                             0x00000001094fbcd9 $sIeg_ytIegr_TRTA.1980 + 9
    15  SwiftUI                             0x0000000109657bcc $sytIegr_Ieg_TR + 12
    16  SwiftUI                             0x0000000109657bac $sIeg_ytIegr_TR + 12
    17  SwiftUI                             0x000000010964a791 $sIeg_ytIegr_TRTA + 17
    18  SwiftUI                             0x000000010964a044 $s7SwiftUI6UpdateO3endyyFZ + 436
    19  SwiftUI                             0x0000000109688a9d $s7SwiftUI19EventBindingManagerC4sendyySDyAA0C2IDVAA0C4Type_pGF + 301
    20  SwiftUI                             0x0000000109ac2a9c $s7SwiftUI18EventBindingBridgeC4send_6sourceySDyAA0C2IDVAA0C4Type_pG_AA0cD6Source_ptFTf4nen_nAA22UIKitGestureRecognizerC_Tg5 + 2060
    21  SwiftUI                             0x0000000109ac0782 $s7SwiftUI22UIKitGestureRecognizerC4send025_062C14327F4C9197D92807A7H6DF7F3BLL7touches5event5phaseyShySo7UITouchCG_So7UIEventCAA10EventPhaseOtF + 66
    22  SwiftUI                             0x0000000109ac15e3 $s7SwiftUI22UIKitGestureRecognizerC12touchesBegan_4withyShySo7UITouchCG_So7UIEventCtFToTm + 131
    23  SwiftUI                             0x0000000109ac0858 $s7SwiftUI22UIKitGestureRecognizerC12touchesEnded_4withyShySo7UITouchCG_So7UIEventCtFTo + 40
    24  UIKitCore                           0x000000011388b2f5 -[UIGestureRecognizer _componentsEnded:withEvent:] + 217
    25  UIKitCore                           0x0000000113dd2162 -[UITouchesEvent _sendEventToGestureRecognizer:] + 674
    26  UIKitCore                           0x000000011387f6fb __47-[UIGestureEnvironment _updateForEvent:window:]_block_invoke + 70
    27  UIKitCore                           0x000000011387f380 -[UIGestureEnvironment _updateForEvent:window:] + 489
    28  UIKitCore                           0x0000000113d84bb8 -[UIWindow sendEvent:] + 4752
    29  UIKitCore                           0x0000000113d5e7dd -[UIApplication sendEvent:] + 408
    30  UIKitCore                           0x0000000113dee8c0 __processEventQueue + 15007
    31  UIKitCore                           0x0000000113de5398 __eventFetcherSourceCallback + 106
    32  CoreFoundation                      0x0000000107d69b04 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    33  CoreFoundation                      0x0000000107d69a43 __CFRunLoopDoSource0 + 157
    34  CoreFoundation                      0x0000000107d69187 __CFRunLoopDoSources0 + 222
    35  CoreFoundation                      0x0000000107d63c68 __CFRunLoopRun + 882
    36  CoreFoundation                      0x0000000107d63542 CFRunLoopRunSpecific + 538
    37  GraphicsServices                    0x0000000111c15db3 GSEventRunModal + 139
    38  UIKitCore                           0x0000000113d4014e -[UIApplication _run] + 912
    39  UIKitCore                           0x0000000113d451b1 UIApplicationMain + 101
    40  Wicrypt                             0x00000001066f786b main + 75
    41  libdyld.dylib                       0x000000010e009411 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[OIDAuthorizationService presentAuthorizationRequest:presentingViewController:callback:]: unrecognized selector sent to class 0x106b47af0'
terminating with uncaught exception of type NSException
CoreSimulator 732.7 - Device: iPhone 11 (7A79AEEA-ED4B-4DCD-BC33-81C73615B7A7) - Runtime: iOS 14.0 (18A5332e) - DeviceType: iPhone 11

I have set the necessary delegate
GIDSignIn.sharedInstance()?.delegate = googleDelegate

I have also set the presenting controller properly
GIDSignIn.sharedInstance()!.presentingViewController = window.rootViewController

The closest resource I've seen is: https://openid.github.io/AppAuth-iOS/docs/latest/category_o_i_d_authorization_service_07_i_o_s_08.html#details
Please any help or reference will be resourceful

A: This may be this necessary step from docs if you don't use pods:
Add the ObjC linker flag to the app target's build settings:

Other Linker Flags: $(OTHER_LDFLAGS) -ObjC

A: The method that is being called, is present in this file.
If your runtime can not find this method, it means that this file is not included into the project.
If you are using CocoaPods, this file should be automatically included for ios platform. Please insure that you specify
platform :ios, '13.0'

in your Podfile.

A: We don't need to add -ObjC in OTHER_LINKER_FLAGS nor include AppAuthCore.framework in the app target's "Linked frameworks and libraries".
Adding AppAuth.framework alone is sufficient. (and in the associated carthage copy-frameworks Run Script phase.)"
(Based on the ratkins' comment on AppAuth's Git forum)


text:
Q: How can I resolve «Failed to lookup a channel to receive an incoming message. Either the endpoint or the SOAP action was not found» With CustomBinding I tried to consome a WCF service configured with CustomBinding and SSL/TLC Certificate but i Get everytime a System.ServiceModel.EndpointNotFoundException «There was no listening endpoint on https: //localhost/Helloword/HelloWord.svc that can accept the message.»
Here is my Service Web.config :
    <?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyCustomBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceCredentials>
            <clientCertificate>
              <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="LocalMachine" />
            </clientCertificate>
            <serviceCertificate findValue="ServerCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/>
          </serviceCredentials>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <customBinding>
        <binding name="MyCustomBinding">
          <textMessageEncoding />
          <security authenticationMode="CertificateOverTransport" requireSecurityContextCancellation="true"/>
          <httpsTransport authenticationScheme="IntegratedWindowsAuthentication" />
        </binding>
      </customBinding>
    </bindings>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service behaviorConfiguration="MyCustomBehavior" name="CustomBindingWifService.HelloWord">
        <host>
          <baseAddresses>
            <add baseAddress ="HelloWord.svc" />
          </baseAddresses>
        </host>
        <endpoint address="https://localhost/Helloword/HelloWord.svc" binding="customBinding"
            bindingConfiguration="MyCustomBinding" contract="CustomBindingWifService.IHelloWord">
          <identity>
            <certificateReference x509FindType="FindBySubjectName" findValue="ServerCert" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

And There is my Client App.config
    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="MyCustomBinding">
          <textMessageEncoding />
          <security authenticationMode="CertificateOverTransport" requireSecurityContextCancellation="true"/>
          <httpsTransport />
        </binding>
      </customBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="MyCustomBehavior">
          <clientCredentials>
            <clientCertificate
            findValue="ClientCert"
            storeLocation="LocalMachine"
            storeName="My"
            x509FindType="FindBySubjectName" />
            <serviceCertificate>
              <authentication
              certificateValidationMode="PeerTrust"/>
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <client>
      <endpoint address="https://localhost/Helloword/HelloWord.svc"
        binding="customBinding" bindingConfiguration="MyCustomBinding"
        contract="ServiceHelloWord.IHelloWord" name="HelloWordEndPoint"
        behaviorConfiguration="MyCustomBehavior" />
    </client>
  </system.serviceModel>
</configuration>

The Program.cs :
namespace CustomBindingWifServiceClient
{
    public class Program
    {
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

            var channel = new ChannelFactory<ServiceHelloWord.IHelloWord>("HelloWordEndPoint");

            var client = channel.CreateChannel();

            var input = "Client Console";

            while (input != null && input.ToLower() != "exit")
            {
                var result = client.HelloWord(input);
                Console.WriteLine(result);
                input = Console.ReadLine();
            }
        }
    }
}

I get Error in : var result = client.HelloWord(input);
In the Browser, the Service looks fine

Thanks for your reply


text:
Q: Port existing code first models, and fluent aPI configuration from Entity Framework 6 to Entity Framework Core 2.0 Assuming in an application utilizing Ef 6, I have the following model and fluentapi configurations that defines the relationship between a car owner and the car/cars he owns. The relationship between a Car and a CarOwner is 1 to 0 or 1, while the relationship between CarOwner and Car is 1 to 0 or many;
public class Car
{
    public int Id { get; set; }
    public string ChasisNumber { get; set; }
    public string EngineNumber { get; set; }

    public CarOwner CarOwner { get; set; }
}

public class CarOwner
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public IList<Car> Cars {get; set;}
}

With a corresponding fluent api configuration shown below
public class CarConfiguration : EntityTypeConfiguration<Car>
{
    HasKey(a => a.Id);
    Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
    HasOptional(x => x.CarOwner).WithMany(x => x.Cars).Map(x => x.MapKey("CarOwner_Id"));
}

public class CarOwnerConfiguration : EntityTypeConfiguration<CarOwner>
{
    HasKey(a => a.Id);
    Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
    HasMany(a => a.Cars).WithOptional(a => a.CarOwner);
}

In EF Core 2.0 the Car model changes because of the need to specify the CarOwner foreign key in the Model as a nullable integer property but I dont want to do that.
public class Car
{
    public int Id { get; set; }
    public string ChasisNumber { get; set; }
    public string EngineNumber { get; set; }

    public int? CarOwnerId { get;set; }
    public CarOwner CarOwner { get; set; }
}

Is there a way I can prevent adding the CarOwnerId as a reference key in the Car entity? I want to ensure my model stay same at it was in Entity Framework 6. I don't want to make any change to my model. I would prefer to make all the necessary changes in the fluent api configuration files.

A:
In EF Core 2.0 the Car model changes because of the need to specify the CarOwner foreign key in the Model as a nullable integer property

Definitely there is no need to do that. In fact EF Core gives you much more control over the shadow properties. Just the default FK name convention is different, so in order to keep the EF6 names you have to explicitly configure them with fluent API.
Here is the equivalent EF Core configuration of the original model (w/o public int? CarOwnerId { get;set; } inside the Car):
public class CarConfiguration : IEntityTypeConfiguration<Car>
{
    public void Configure(EntityTypeBuilder<Car> builder)
    {
        builder.HasKey(a => a.Id);
        builder.Property(a => a.Id).ValueGeneratedOnAdd().IsRequired();
        builder.HasOne(x => x.CarOwner)
            .WithMany(x => x.Cars)
            .HasForeignKey("CarOwner_Id") // <--
            .IsRequired(false);
    }
}

public class CarOwnerConfiguration : IEntityTypeConfiguration<CarOwner>
{
    public void Configure(EntityTypeBuilder<CarOwner> builder)
    {
        builder.HasKey(a => a.Id);
        builder.Property(a => a.Id).ValueGeneratedOnAdd().IsRequired();
    }
}

Note that most of the fluent configurations are redundant and can be omitted since they are the EF conventional defaults. Also relationship configuration should be in one place in order to avoid conflicting setups - relationship always has 2 ends, so logically it's not a part of any of the two entities (doesn't fit well in the entity type configuration separation).
The minimal fluent configuration which achieves the same mapping is like this (not using entity type configurations at all):
modelBuilder.Entity<Car>()
    .HasOne(x => x.CarOwner)
    .WithMany(x => x.Cars)
    .HasForeignKey("CarOwner_Id");


text:
Q: Ubuntu 12.10 Keeps rebooting randomly I just installed Ubuntu 12.10 using the 'Installing Ubuntu with the Windows installer' (wubi) feature on the www.ubuntu.com to install it on my computer. My computer is a ASUS with 6 ggs for ram and duo pentium core i5 64 bit system.  Ubuntu keep turning off then restarting.. and i dont know why.  It keeps doing a hard restart.

A: This is the same problem I am having.
I have the Asus U56E laptop with 6 gigs of memory, 750 gig hard drive and i5 processor (64-bit).
Ubuntu, Linux Mint, Debian, Crunchbang doesn't make a difference. It will randomly reboot.
NOTE:  PCLinuxOS runs fine and I never experience this problem.  It will stay up for days, weeks, and will not reboot unless I tell it to.
If I put Ubuntu back on it, it might stay up 15 minutes, then it will randomly reboot.  I have noticed that if I go away and come back later, the screensaver will have been activated (the screen is black) and after I move the mouse the screen comes to life and then almost immediately the laptop will reboot.
If the laptop is on battery power, the laptop won't reboot it will just stay off.
I will give anyone $50 bucks to solve this problem. I am 99% sure it is something in the distro(s) because, like I said, PCLinuxOS KDE/LXDE will run for days.
$50 bucks!


text:
Q: Cauchy-Riemann equations: Meromorphic Function A meromorphic function is a function that is holomorphic on all domain except for a set of isolated points. I know that a holomorphic function, by definition, satisfies the Cauchy-Riemann equations but I can't understand if the meromorphic function satisfies the Cauchy-Riemann equations.
Can we restrict meromorphic function to the holomorphic part so it satisfies the Cauchy-Riemann equations? Or due to the set of isolated points the meromorphic function doesn't satisfies the Cauchy-Riemann equations?
Thank you very much for your help!

A: Off the poles the meromorphic function is holomorphic, so satisfies the C-R equations.

A: Just to add to Chris' answer, remember in complex analysis everything is done in open sets.  So for a given meromorphic function, pick a point $z_0$ where it is actually defined, then since the poles are all isolated you can find an open disk about $z_0$ of non-zero radius such that the function is defined throughout it.  By definition, the your function is holomorphic on the disk and therefore satisfies the CR-equations throughout it.


text:
Q: Code to merge files in subdirectories not producing expected result using ArcPy The short python code below is intended to merge a series of files (GIS files) which are contained in a series of subfolders.
import arcpy
import sys
import os

PointsMerged = r"C:\GIS\Test_Workspace\MergeOutput\MergedPoints"    ## Provide name and path of the merged feature class

pointslist = []

if __name__ == "__main__":
    try:
        SrcPath = r"C:\GIS\Test_Workspace"  ## Provide the path for data with subfolder here
        for root, dirs, files in os.walk(SrcPath, topdown=True):
            for filename in files:

                # check if 'Test' name exists in shapefile name
                if filename.find("Test") == 0:
                        print os.path.join(root, filename)
                        points = str(os.path.join(root, filename))
                        pointslist.append(points)

        arcpy.Merge_management(pointslist, PointsMerged)

    except Exception, ErrorDesc:
        #If an error set output boolean parameter "Error" to True.
        arcpy.AddError(str(ErrorDesc))
        row = None
        rows = None

Below is the result of running the script. As far as I can tell the script runs up to the print function, resulting in a list of all files found in the specificied workspace (directory).
C:\GIS\Test_Workspace\Test_Points.dbf
C:\GIS\Test_Workspace\Test_Points.prj
C:\GIS\Test_Workspace\Test_Points.sbn
C:\GIS\Test_Workspace\Test_Points.sbx
C:\GIS\Test_Workspace\Test_Points.shp
C:\GIS\Test_Workspace\Test_Points.shp.xml
C:\GIS\Test_Workspace\Test_Points.shx
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.dbf
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.prj
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.sbn
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.sbx
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.shp
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.shp.xml
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.shx
C:\GIS\Test_Workspace\Test Sub\Test_Points_2.dbf
C:\GIS\Test_Workspace\Test Sub\Test_Points_2.sbn
C:\GIS\Test_Workspace\Test Sub\Test_Points_2.sbx
C:\GIS\Test_Workspace\Test Sub\Test_Points_2.shp
C:\GIS\Test_Workspace\Test Sub\Test_Points_2.shp.xml
C:\GIS\Test_Workspace\Test Sub\Test_Points_2.shx

Can anyone see why the merge may be failing?

A: Are you sure arcpy.Merge_management isn't failing because you are giving it files that it can't process.   You need to filter just the shape files out first
import arcpy
import sys
import os

PointsMerged = r"C:\GIS\Test_Workspace\MergeOutput\MergedPoints"    ## Provide name and path of the merged feature class

pointslist = []

if __name__ == "__main__":
    try:
        SrcPath = r"C:\GIS\Test_Workspace"  ## Provide the path for data with subfolder here
        for root, dirs, files in os.walk(SrcPath, topdown=True):
            for filename in files:
                # check if 'Test' name exists in shapefile name
                if filename.endswith(".shp") and "Test" in os.path.basename(filename):
                    fullpath = os.path.join(root, filename)
                    print fullpath
                    pointslist.append(fullpath)

        arcpy.Merge_management(pointslist, PointsMerged)

    except Exception, ErrorDesc:
        #If an error set output boolean parameter "Error" to True.
        arcpy.AddError(str(ErrorDesc))
        row = None
        rows = None

This should yield:
C:\GIS\Test_Workspace\Test_Points.shp
C:\GIS\Test_Workspace\Test Sub\Test_PointsCopy.shp
C:\GIS\Test_Workspace\Test Sub\Test_Points_2.shp

Note: I also used "Test" in os.path.basename(filename) because that will check only the filename for the word Test, if you don't care about that you can use "Test" in filename to just check anywhere in the whole path.


text:
Q: Custom Collection View is not showing up I'm working on an app that'll have a range of images and the collectionview is not showing up at all. I was following this article, which I translated to C#.
here is an example app I made to show a minimal example of what I'm trying to do.
When I run through the code, GetCell in the collection source isn't firing which I know is the problem, but I don't know why it's not firing and I'm simply at a lost on what I'm missing.

A: I test it again today and I can make sure that the problem is caused by the MosaicCollectionLayout.
What I did today is that I removed your collectionView and add a new collectionView, then I add Constrains to it with a fixed height and width(to make sure it appears even if there is no data), then I change the layout to FlowLayout, it works, here is the screenshot:

After that, I changed the layout back to MosaicCollectionLayout, I get an exception in the line             _cachedAttributes.Reverse(lastIndex.Row, firstMatchIndex.Value); inside the method LayoutAttributesForElementsInRect.
I checked the article and did not find a solution yet. Maybe there is some mistakes in the codes translated from swift to C#. So the problem is not related to the xib, please check the code in the method LayoutAttributesForElementsInRect.You can also try add Constrains  to your collectionView. Hope these information helps you.


text:
Q: Creating an executable from python file I need to make an executable out of a .py file. I looked into it and tried:

*

*py2exe -> this doesn't work with python3.8 (gives me "IndexError: tuple index out of range")

*pyinstaller -> still doesn't work (TypeError: an integer is required (got type bytes))

For pyinstaller I might have found a solution here but still doesn't work for me. (a user said to use the latest version compatible with 3.8 -> pip install https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz
Any alternative solution / fix would be greatly appreciated

A: This subject has been discussed here
The latest release of Py2exe (0.9.2.2) was built for Python 3.4 and will not work in 3.7+.
There is a Github project that is porting Py2exe to 3.7 (link here). I made some tests with Python 3.7 and it works well to generate exe files.


text:
Q: How to simplify the following mathematical expression? While solving one of the algorithmic problems, I came around with one mathematical expression, I tried solving it but not able to compress it into a smaller expression which can be calculated easily.
Suppose there are n numbers $(a_1,a_2{\ldots} a_n)$:
$$n*(a_1*a_2 \ldots a_n)+(n-1)*(a_1*a_3 \ldots a_n + a_1*a_2*a_4 \ldots a_n + a_1*a_2*a_3*a_5 \ldots a_n+ \ldots a_2*a_3*a_4 \ldots a_n) + (n-2)*(a_1*a_4 \ldots a_n + a_1*a_2*a_5 \ldots a_n + \ldots a_3*a_4 \ldots a_n) + \ldots 1*(a_1+a_2+a_3 \ldots a_n)$$
This seems like the well-known expression, but I am not able to find its compressed version.
To make the mathematical expression more clear, let's take n=4
$$4*(a_1*a_2*a_3*a_4)+ 3*(a_1*a_2*a_3 + a_1*a_3*a_4 + a_1*a_2*a_4 + a_2*a_3*a_4)+ 2*(a_1*a_2 + a_1*a_3 + a_1*a_4 + a_2*a_3 +a_2*a_4 + a_3*a_4)+ 1*(a_1+a_2+a_3+a_4)$$
Let me know if the mathematical expression is not clear.

A: The expression probably can't be simplified beyond
$$\sum_{s \subseteq S} |s| \prod_{x \in s}x$$

However, the calculation can be streamlined considerably.
If we define $f(S)$ as the expression above, we can calculate the extension by $y \not\in S$ as $$\begin{eqnarray}
f(S \cup \{y\})
&=& \sum_{s \subseteq S \cup \{y\}} |s| \prod_{x \in s}x \\
&=& \sum_{s \subseteq S} |s| \prod_{x \in s}x + \sum_{s \subseteq S} (|s|+1) y \prod_{x \in s}x \\
&=& f(S) + y\left(\sum_{s \subseteq S} |s| \prod_{x \in s}x + \sum_{s \subseteq S} \prod_{x \in s}x\right) \\
&=& f(S)(1 + y) + y\sum_{s \subseteq S} \prod_{x \in s}x \\
\end{eqnarray}$$
If we now define $g(S) = \sum_{s \subseteq S} \prod_{x \in s}x$ then similarly $$\begin{eqnarray}
g(S \cup \{y\})
&=& \sum_{s \subseteq S \cup \{y\}} \prod_{x \in s}x \\
&=& \sum_{s \subseteq S} \prod_{x \in s}x + \sum_{s \subseteq S} y \prod_{x \in s}x \\
&=& g(S)(1 + y)\end{eqnarray}$$
So we have $f(S \cup \{y\}) = f(S)(1 + y) + yg(S)$ and $g(S \cup \{y\}) = g(S)(1 + y)$, allowing an easy calculation starting from $f(\emptyset) = 0$ and $g(\emptyset) = 1$.


text:
Q: How do I output calabash query results to a textFile ok, I've read all the calabsh query docs on xamarin for android and iOS and the Ruby file class and still can't find the answer, so if anyone can help then that would be great.
What I trying to do is run querys in the calabash-android console window and write those results to a file on the fly.
so for instance :  query("this is my query", :type (class etc..)
I can also do query("*") - I will then take the text output and collate the information I require to build up an elements 'dictionary'
Ive tried query("*") f.write("C:\myFileName.txt",'w')  and the console complains..  I've also tried multiple operators on the query (f.write, f.open).
thanks guys in advance.

A: The calabash console is just ruby's irb console with the calabash modules loaded.  As such you can use any ruby commands to get things done.  This answer should cover you - How to write to file in Ruby?
e.g.
open('out.txt', 'a') { |f| f.puts query('*')}

will append the query results to out.txt.
or
outputs = []
outputs << query('*')
outputs << query("* text:'OK'")
open('out.txt', 'a') { |f| f.puts output}


text:
Q: User defined literal operator not found I am writing a class for time. Defined my own literals, but gives the error "user-defined literal operator not found".How can I correctly set a variable with a literal? Here is the literal code:
literals.hpp
namespace lab1 {

  ulli operator"" _d(ulli days);
  ulli operator"" _h(ulli hours);
  ulli operator"" _m (ulli minutes);
  ulli operator"" _s (ulli seconds);

}

literals.cpp
#include "literals.hpp"

  ulli operator"" _d(ulli days) {
      ulli timeInSeconds;
      timeInSeconds = days * 24 * 60 * 60;

      return timeInSeconds;
  }
....

main.cpp
#include <iostream>
#include "Timespan.hpp"
#include "Time.hpp"
#include "literals.hpp"

using namespace lab1;

int main() {

    ulli days = 12_d;
    Time Test = Time(days,24,52,32);

    std::cout << Test << std::endl;
}

ulli is using ulli = unsigned long long int;

A: The issue is you have declared the operator in lab1 scope but defined it in global scope. When you move the definition also to the lab1 namespace it works.
Here is the correct code.
#include <iostream>

using ulli = unsigned long long;

namespace lab1 {

  ulli operator"" _d(ulli days);
  ulli operator"" _h(ulli hours);
  ulli operator"" _m (ulli minutes);
  ulli operator"" _s (ulli seconds);

  ulli operator"" _d(ulli days) {
      ulli timeInSeconds;
      timeInSeconds = days * 24 * 60 * 60;

      return timeInSeconds;
  }

}

using namespace lab1;

int main() {

    ulli days = 12_d;
    std::cout<<days;

   return 0;
}


text:
Q: imagecopyresampled issue – black border right and bottom … The first option works, the second doesn't … I don't get why? I take an image 1500 by 1500 pixels, if it gets passed through the first option the result is right, if it gets passed through the second, I get a black border on the right and on the bottom …
if ($this_imagesize[0] > 1000)
    {
        $thumb_source = imagecreatefromjpeg('/path/' . $this_image_id . '.jpg');

        $thumbnail = imagecreatetruecolor(1000, intval(1000 * ($this_imagesize[1] / $this_imagesize[0])));

        imagefill($thumbnail, 0, 0, imagecolorallocate($tn, 255, 255, 255));

        imagecopyresampled($thumbnail, $thumb_source, 0, 0, 0, 0, 1000, intval(1000 * ($this_imagesize[1] / $this_imagesize[0])), $this_imagesize[0], $this_imagesize[1]);

        unlink('/path/' . $this_image_id . '.jpg');

        imagejpeg($thumbnail, '/path/' . $this_image_id . '.jpg', 75);
    }

if ($this_imagesize[1] > 1000)
    {
        $thumb_source = imagecreatefromjpeg('/path/' . $this_image_id . '.jpg');

        $thumbnail = imagecreatetruecolor(intval(1000 * ($this_imagesize[0] / $this_imagesize[1])), 1000);

        imagecopyresampled($thumbnail, $thumb_source, 0, 0, 0, 0, intval(1000 * ($this_imagesize[0] / $this_imagesize[1])), 1000, $this_imagesize[0], $this_imagesize[1]);

        unlink('/path/' . $this_image_id . '.jpg');

        imagejpeg($thumbnail, '/path/' . $this_image_id . '.jpg', 75);
    }


text:
Q: Cannot access properties set in Maven's pom.xml, System.getProperty returns always null I try to set up properties in my pom.xml and access them during my jUnit test.
The class I want to read them in, is imported by the jUnit Test.java and is using
String prop = System.getProperty("target1");
but it always is null. What I tried in my pom.xml already:
...
<profiles>
    <profile>
        <id>default</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <target1>2948</target1>
        </properties>
    </profile>
</profiles>

and also
...
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-failsafe-plugin</artifactId>
   <version>2.15</version>
   <systemPropertyVariables>
      <target2>2948</target2>
   </systemPropertyVariables>
   <systemProperties>
     <property>
        <name>target3</name>
        <value>2948</value>
     </property>
   </systemProperties>
...
</configuration>
...

I do have a parent pom.xml but that can't be the problem can it?
I'm using Netbeans and starting the Tests by hiting "Test File" on the pom.xml
Thanks yous :)

A: I don't know about maven-failsafe-plugin, but I am able to get the result by adding property and value in maven-surefire-plugin since that is what is used by junit tests in a maven project. Here is a detailed explanation: Specify system property to Maven project
from the maven site (http://maven.apache.org/surefire/maven-failsafe-plugin/) - "The Failsafe Plugin is designed to run integration tests while the Surefire Plugins is designed to run unit tests". Since you are running a junit, you should add your property to surefire plugin.


text:
Q: What does it mean that "the solution to a differential equation represents a vector field" Can someone demonstrate why the solution to a differential equation i.e. $du/dx = u$ represents a vector field?
What is deep interpretation of this fact?

A: The equation $\frac{dy}{dx}=x$ say you that the function $y(x)$ has slope $x$ at a point of his graph with abscissa $x$. You can represent this slope with a  vector parallel to the straight line having such slope and attached to the point $(x,y)$ and all this vectors are a vector field. You can see here for a graphical representation.


text:
Q: 'AxesSubplot' object has no attribute 'bar_label I'm trying to add labels in the bars of my group bar chart and I'm having problem doing so
this is my code:`
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('lifeExpectancy_SEA.csv')
bar = df.pivot(index = 'SEA_Countries ', columns = 'Years', values = 'Average_Age')
bar.plot(kind = 'bar',figsize = (20,8))
plt.xlabel('SEA Countries')
plt.ylabel('Average Life Expectancy of the population')
plt.title('Average Life Expectancy of the SEA population from the years 1950-1969 and 2000-2019')
plt.legend(loc = 'upper right')
plt.grid(axis= 'y', color = 'green', linestyle = '--')
fig, ax = plt.subplots()
ax.bar_label() #tried adding the proper parameters but still ended up with the same error
plt.show()

The error message is this:
AttributeError: 'AxesSubplot' object has no attribute 'bar_label'

Any comments or suggestions is greatly appreciated!


text:
Q: Save runtime created textbox value in database table I have create one form in that form  contain one textbox and one add another button & save button,on click event of add another button new textbox is generated but when i click on save button newly generated textbox value can not be save into database please anyone can guide me
Here is my code:
<?php
    global $Hostname;
    global $Username;
    global $Password;
    global $Database_name;

function getConnection()
{
    $Hostname = "localhost";
    $Username ="root";
    $Password ="";
    $Database_name="labdata";

    $oMysqli = new mysqli($Hostname,$Username,$Password,$Database_name);    //create connection object.

    return($oMysqli);
}
if(isset($_POST['submit']))
{
    $TestParameters = $_POST['testparameters'];
    $InsertQuery = "INSERT INTO test_table VALUES('$TestParameters')";
    $oMysqli=getConnection();
    $oMysqli->query($InsertQuery);

    //print_r($InsertQuery);exit();
    if(!$InsertQuery)
                {
                    die('Could not enter data:' . mysql_error());
                }
}
?>

<title>TestData</title>

<form name="testdetails" method="post" target="_self" action="<?php $_PHP_SELF ?>">

Testparameter
<input type="text" name="testparameters"></input>

     <input type="button" name="button" value="Add Test Parameter" onclick="create_row()">

<input type="submit" name="submit" value="submit">
</form>

A: Try this
if(isset($_POST['submit']))
    {

        $length = count($_POST['testparameters']);

        for($i=0; $i< $length; $i++){
            $TestParameters=$_POST['testparameters'][$i];
            if(!empty($TestParameters)){
            $InsertQuery = "INSERT INTO color(name) VALUES('$TestParameters')";
            $result=mysql_query($InsertQuery) or die(mysql_error());
        }
        }
        if(!$InsertQuery)
        {
            die('Could not enter data:' . mysql_error());
            }
    }

A: <?php
$n=0;
if(isset($_GET['button1']))
{

$n++;
     echo "hai";
      echo "
<input type='text' name='+i+'>";

}
     if(isset($_POST['submit']))
{

      $con=mysqli_connect("localhost","root","","ram123");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
//print_r($_POST);
  $count = count($_POST);
 for($x=1;$x<$count;$x++){
     $sql="INSERT INTO  names (name)VALUES('$_POST[$x]')";

    if (!mysqli_query($con,$sql))
      {
      die('Error: ' . mysqli_error($con));
      }

 }
 /*
$sql="INSERT INTO  names (name)VALUES('$_POST[1]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);
*/
}
?>

<title>TestData</title>

<form name="testdetails" method="post" target="_self" action="<?php $_PHP_SELF ?>">

     <input type="button" name="button1" value="Add Test Parameter" onclick="changeIt()">

<input type="submit" name="submit" value="submit">

</form>

A: you are using same name for all textbox
<input type="text" name="testparameters"></input>

use array for this,from this you will get value of all your textbox
<input type="text" name="testparameters[]"></input>

Code for iterating textbox value
$length = count($_POST['testparameters']);
for($i=0; $i< $length; $i++){
    echo $_POST['testparameters'][$i];
}


text:
Q: how to post data with kotlin i tried to post data to api with khttp but there is an error
this is my code
val payload = mapOf("review" to addReviewET.text, "rating" to quantity.toString(), "id_user" to "1", "id_movie" to id)
        val r = post(localhost.insertReview(), data = payload)
        println(r.text)

but it doesn't work it says error like this
FATAL EXCEPTION: main
              Process: com.mqa.android.moviereview, PID: 23984
              android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
                  at java.net.SocketInputStream.read(SocketInputStream.java:169)
                  at java.net.SocketInputStream.read(SocketInputStream.java:139)
                  at com.android.okhttp.okio.Okio$2.read(Okio.java:136)
                  at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
                  at com.android.okhttp.okio.RealBufferedSource.exhausted(RealBufferedSource.java:60)
                  at com.android.okhttp.internal.io.RealConnection.isHealthy(RealConnection.java:361)
                  at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:137)
                  at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
                  at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
                  at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
                  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
                  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
                  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
                  at khttp.responses.GenericResponse$Companion$defaultEndInitializers$1.invoke(GenericResponse.kt:90)
                  at khttp.responses.GenericResponse$Companion$defaultEndInitializers$1.invoke(GenericResponse.kt:32)
                  at khttp.responses.GenericResponse$connection$2.invoke(GenericResponse.kt:164)
                  at khttp.responses.GenericResponse$connection$2.invoke(GenericResponse.kt:30)
                  at khttp.responses.GenericResponse.openRedirectingConnection$khttp(GenericResponse.kt:124)
                  at khttp.responses.GenericResponse.getConnection(GenericResponse.kt:163)
                  at khttp.responses.GenericResponse.getRaw(GenericResponse.kt:207)
                  at khttp.responses.GenericResponse.getContent(GenericResponse.kt:216)
                  at khttp.responses.GenericResponse.init$khttp(GenericResponse.kt:350)
                  at khttp.KHttp.request(KHttp.kt:59)
                  at khttp.KHttp.post(KHttp.kt:48)
                  at khttp.KHttp.post$default(KHttp.kt:47)
                  at com.mqa.android.moviereview.module.activity.AddActivity$showMovieList$3.invokeSuspend(AddActivity.kt:90)
                  at com.mqa.android.moviereview.module.activity.AddActivity$showMovieList$3.invoke(Unknown Source:40)
                  at org.jetbrains.anko.sdk27.coroutines.Sdk27CoroutinesListenersWithCoroutinesKt$onClick$1$1.invokeSuspend(ListenersWithCoroutines.kt:300)
                  at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)
                  at kotlinx.coroutines.DispatchedTask$DefaultImpls.run(Dispatched.kt:235)
                  at kotlinx.coroutines.DispatchedContinuation.run(Dispatched.kt:81)
                  at android.os.Handler.handleCallback(Handler.java:789)
                  at android.os.Handler.dispatchMessage(Handler.java:98)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6541)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

what is this error exactly? and how to make it right? or if you have other way please let me know. thank you
i got the way from here

A: The issue is that you want to run the http request on the main thread.
There are two way to avoid this error.

*

*Disable strict mode, which means you can run the request on the main thread.

*Make the request with AsyncTask. This is the recommended way, however it involves some job to do and look for the results by having the app state under control.


text:
Q: .NET Framework support for multicore hardware I've been tasked to write a high performance, high availability service that will run on a multicore box.
Do I need to make use of Task Parellel Library to really leverage a multicore server or will the service automagically run faster if I throw more hardware (cores) at it? Does the .NET framework provide the magic for me under the covers?
As a corollary, will there be performance gains by upgrading the server with more cores (keeping the spec of each individual core the same) for .NET applications that do not use TPL?
As per my understanding (perusing Joe Duffy's book and his blogs), you really do need to program for multicore. Is my conclusion accurate?

A: This is difficult to answer accurately since parallel processing is not a generic problem. You'll need to analyze your project to find places where you can leverage parallel processing.
If your application can be easily broken down into concrete independent tasks, parallel processing will definitely improve. If its primarily serial in nature, multiple cores/threads won't really help at all.
If you've determined that parallel tasks represent the core of your process, a parallel library can help you perform the basic tasks as well as make it easier to get right.

A: Take a look at PLinq which will be coming in .Net 4.0.  It will give you a lot of parallel processing capabilities without needing to manage task/load algorithms.

A: A program needs to have several paths of execution to leverage anything more than 1 core/processor. Typically this is done by running more than 1 thread, as most OS's only way of providing more than execution path is either by running several processes(executables) or several threads within one process.
There's several high level abstractions built into modern languages to more easily dealing with what is essentially multi-threading, but better learn the basics first; Threads


text:
Q: Evaluate $\int\cos^3x\sin^2x\,dx$ My university mathematics is kind of poor. But as I am learning advanced mathematics this becomes a major shortcoming.
I tried to integrate
$\int$$\sin^3\theta$$\cos^2\theta$d$\theta$ = $\int$(-3$\cos^3\theta$$\sin$$\theta$d$\theta$)$\left(-\frac13\right)$$\sin^2\theta$
= $\int$$\left(-\frac13\right)$($\sin^2\theta$)d($\cos^3\theta$) = $\left(-\frac13\right)$($\sin^2\theta$$\cos^3\theta$) - $\left(-\frac13\right)$$\int$$\cos^3\theta$d$\sin^2\theta$ = $\left(-\frac13\right)$($\sin^2\theta$$\cos^3\theta$) - $\int$(-2)$\cos^4\theta$d$\theta$ = $\left(-\frac13\right)$($\sin^2\theta$$\cos^3\theta$) + $\left(\frac2{15}\right)$$\cos^5\theta$
But this certainly is wrong. Why?

A: This is a substitution. Note the odd power. Thus let $u=cos \theta$ so $du=-\sin \theta$
$$\int \sin^3 \theta \cos^2\theta d\theta=
\int (u^2-1)u^2 du$$

A: Another possible way to solve this:
To find: $$\int \cos^3x\sin^2x~dx$$
First we need to observe that $\sin^2x=1-\cos^2x$ and $\cos3x=4\cos^3x-3\cos x$. We can now rewrite the integral as
$$\int \cos^3x(1-\cos^2x)dx=\int \cos^3x -\int \cos^5x$$
$$\Rightarrow \int \cos^3x(1-\cos^2x)dx=\int \frac{\cos 3x-3cosx}{4}dx-\int(\cos^3x)^2dx$$
Rewrite $\cos^3 x$ in the second integral and square the term. Can you continue from here?
EDIT: it is a wonder that no one pointed out my mistake.Breaking the integral into two parts we get
$$\int \cos^3 x~dx-\int cos^5 x~dx  $$
Substitute second formula in the first integral. For the second integral:
Rewrite $\cos^5 x$ as $\cos^3 x \cos^2x$. Use $\cos2x=\cos^2x-1$. Substitute the formulas and you will get
$$(\frac{\cos 3x-3cosx}{4})(\cos 2x+1)=\frac{\cos3x\cos2x+\cos3x-3\cos x\cos2x-3\cos x}{4}$$
The work is not over yet. Finally use the fact that $\cos A+\cos B=2\cos \frac{A+B}{2} \cos \frac{A-B}{2}$. Hence $\cos3x\cos2x=\frac{cos 5x+cos x}{2}$ and $\cos x \cos 2x=\frac{\cos3x+\cos x}{2}$. I am sure you can take care of the rest. Substitue and integrate.

A: An idea: integration by parts:
$$\begin{align*}&u=\cos\theta\;\;\;\;\;\;\;\;\;\;\;\,u'=-\sin\theta\\
&v'=\sin^3\theta\cos\theta\;\;\;v=\frac14\sin^4\theta\end{align*}$$
and thus
$$\int \sin^3\theta\ cos^2\theta\;d\theta=\frac14\sin^4\theta\cos\theta +\frac14\int \sin^5\theta\;d\theta$$
For the last integral above you can use one fo the known reduction formulas...or calculate it by yourself. It isn't really hard, but it's boring.
Other idea, perhaps faster and simpler:
$$\int\sin^3\theta\cos^2\theta\;d\theta\int\sin^3\theta(1-\sin^2\theta)\;d\theta=\int\left(\sin^3\theta-\sin^5\theta\right)\;d\theta$$
and again the reduction formula twice.


text:
Q: Why Data Trigger is not firing I have a XAML code. I am trying to fill the rectangle on Datatrigger but its not firing
<ItemsControl Grid.Row="1" Grid.Column="1" ItemsSource="{Binding SelectedEnrollments}" Visibility="{Binding EnrollmentsExist, Converter={x:Static s:BooleanToVisibilityConverter.Default}, Mode=TwoWay}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <RadioButton Tag="{Binding Id}" GroupName="Enrollments" ToolTip="{Binding Title}" Checked="EnrollmentRadioButton_Checked" IsChecked="{Binding IsSelected}">
                <RadioButton.ContentTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">

                            <TextBlock TextTrimming="CharacterEllipsis"
                                       Text="{Binding ToolTip, RelativeSource={RelativeSource FindAncestor, AncestorType=RadioButton}}" />
                            <Rectangle x:Name="RankIcon" Width="30">
                                <Rectangle.Style>
                                    <Style>
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding Rank}" Value="Primary">
                                                <Setter  Property="Rectangle.Fill" Value="Blue"></Setter>
                                            </DataTrigger>
                                            <DataTrigger Binding="{Binding Rank}" Value="Secondary">
                                                <Setter  Property="Rectangle.Fill" Value="{DynamicResource IconRankSecondary}"></Setter>
                                            </DataTrigger>
                                        </Style.Triggers>
                                    </Style>
                                </Rectangle.Style>
                            </Rectangle>
                         </StackPanel>
                        <DataTemplate.Triggers>

                        </DataTemplate.Triggers>
                    </DataTemplate>
                </RadioButton.ContentTemplate>
            </RadioButton>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Please help anypne

A: Try changing the setters so that they use Property="Fill" instead of Property="Rectangle.Fill"

A: Move the data trigger into the resources of the page or view. I believe that it may be firing but the binding for Value="{DynamicResource IconRankSecondary}" may be unable to find the DynamicResource.
Verify Databinding issues by running it in debug mode and looking at the debug output specifying binding failures.


text:
Q: How can I test a regular variable against a specific array value? Is it possible to test a variable against a specific/all possible values within an array?
For instance, if I have:
var abc;
var array1 = ["item1", "item2", "item3"];

function someFunction(){
  abc = "item2"
  if (abc == !!**Either array1[item1] OR array1[item2] OR.. etc for x in array1**!!)
    {
      //*do stuff*
    }
}

What is the correct syntax for testing abc against any possible entry in array1?

A: There is no syntax for this, you need to loop over the array and compare values indiviually.
function  somefunction(){
  abc = "item2"

  for (var i = 0; i < array1.length; ++i) {
    if (abc == array1[i]) {
      //*do stuff*
    }
  }
}

A common way of shortening this (in the case where your test is for simple equality) is to use the built-in indexOf function, which returns the index of the item in the array, or -1 if it wasn't found.
if (array1.indexOf(abc) != -1) { ... }

A: I suggest using a loop:
for(i in array1){
  if(abc === array1[i]){
    // do stuff
  }
}

A: Use indexOf() to check what position the value appears at in the array.  If it returns -1, then the value doesn't exist.
if (array1.indexOf(abc) != -1) {
  // do stuff...
}


text:
Q: Is there a way to send SMS from Server? There is a way to send SMS from private online server?
Or another way to transfer text from server to a mobile phone?
Thank you.

A: You can pay a service or depending upon the carrier of the target phone there are various ways.  Here is the cheap way, simply send an email.  The carrier will create a text message:
Alltel
[10-digit phone number]@message.alltel.com
Example: 1234567890@message.alltel.com
AT&T (formerly Cingular)
[10-digit phone number]@txt.att.net
[10-digit phone number]@mms.att.net (MMS)
[10-digit phone number]@cingularme.com
Example: 1234567890@txt.att.net
Nextel (now Sprint Nextel)
[10-digit telephone number]@messaging.nextel.com
Example: 1234567890@messaging.nextel.com
Sprint PCS (now Sprint Nextel)
[10-digit phone number]@messaging.sprintpcs.com
[10-digit phone number]@pm.sprint.com (MMS)
Example: 1234567890@messaging.sprintpcs.com
T-Mobile
[10-digit phone number]@tmomail.net
Example: 1234567890@tmomail.net
US Cellular
[10-digit phone number]email.uscc.net (SMS)
[10-digit phone number]@mms.uscc.net (MMS)
Example: 1234567890@email.uscc.net
Verizon
[10-digit phone number]@vtext.com
[10-digit phone number]@vzwpix.com (MMS)
Example: 1234567890@vtext.com
Virgin Mobile USA
[10-digit phone number]@vmobl.com
Example: 1234567890@vmobl.com


text:
Q: mutable boost::mutex is it possible to separate lock and wait functions? So I have functions like read that can be called at the same time from multiple threads. but  also I have a function to write that needs to lock all that read functions. Where to get example of creating such archetecture?
I get that we can have:
mutable boost::mutex the_read_mutex;
mutable boost::mutex the_write_mutex;

and:
void write()
{
    // make all new readers wait and wait for all other currently running read threads();
}

void read()
{
    // do not make all new readers wait, and wait for all currently running write thread()
}

So how to do such thing?

A: You can use
boost::shared_mutex  m

Reader()
 shared_lock   lock(m)

Writer()
 upgradeable_lock lck(m)
 upgrade_to_unique_lock uniqueLock(lck);

To know more about boost-locks : Boost thread sync mechanisms
To know about the class of the problem you are dealing with : Wikpedia Link to Reader-WriterLock
To know more about POSIX reader-writer lock, which directly gives you reader write lock with much simple syntax : POSIX reader-witer locks


text:
Q: How to register an Android developer account for a company? I'm trying to register an Android Developer account for our company that we'll use to publish our company's apps to the market. So we don't want a account which is bound to a single developer.
But this statement which is displayed before paying the fee of $25 let me wonder if a developer account can be associated with a company at all.

Your registration fee enables you to publish software in the market. The name and billing address used to register will bind you to the Android Market Developer Distribution Agreement. So make sure you double check!

If I understand this correctly, then this means that the person whose credit card is used to pay the fee will be the person how accept the developer agreement and therefore will be legal responsible for the apps that are published under this account.
If this is correct then this is not exactly what we want, as we cannot make one of our developer personal legal responsible for the company's product.
So what are our options to avoid this? How could the account be legally bound to the company instead. Or did we miss understand the whole statement?

A: Go buy a prepaid debit card or something using company money, and use that to register as a developer.  Keep the receipt for the prepaid debit card for record-keeping/auditing.  Don't expect to ever get a receipt from Google for your 25 quid.

A: You need to create a google checkout account.
If you're interested in selling priced applications, you'll need to be registered as a Google Checkout Merchant as well. To do this from the Android Market publisher site:

*

*Log into your Android Market account at http://market.android.com/publish/

*Click on the "Edit profile" link.

*Select "Setup a Merchant Account at Google Checkout."

This will take you to the Google Checkout site to sign up as a Merchant; you'll need to have information about your business handy to complete this step. Learn more about the requirements to be a Google Checkout Merchant.
Company Registration in Android Market


text:
Q: How do Isolate a string of text in Excel that begins with a space and ends with a comma? I have a column of cells with addresses like below:

*

*34470 Yucaipa Boulevard Yucaipa, CA 992399

*15787 Main Street Hesperia, CA 92345

*15109 Bear Valley Road Victorville, CA 92345

I want to pull out the City, State Zip; I'm trying to write a formula to accomplish this but I am having trouble.
Basically I'm looking for a way to find a coma, read the string from right to left, and stop at the first space; seems simple enough....
So in the examples above I'm looking to pull out the following strings

*

*Yucaipa, CA 992399

*Hesperia, CA 92345

*Victorville, CA 92345

A: In Excel 2010, you can use the Text-to-Columns feature on the Data ribbon.
This explains it in more detail at addictivetips
After you've split the data into columns, add a new column that concatenates the city, state and zip together.  Something like =CONCATENATE(D2, " ", E2, " ", F2).

A: Try something like this:
=LEFT(
    RIGHT(A1,LEN(A1)-SEARCH(",",A1)-1),
    SEARCH(" ",RIGHT(A1,LEN(A1)-SEARCH(",",A1)-1))-1)

The only problem with this kind of search is that your data needs to be ultra-clean. In your sample I had to skip the space immediately after the comma, but if your data doesn't always have the space it won't work properly.
Based on your comments, try this:
=LEFT(
    RIGHT(A1,LEN(A1)-SEARCH(" ",A1)),
    SEARCH(",",RIGHT(A1,LEN(A1)-SEARCH(" ",A1)))-1)

A: You can use this:
=MID(A1,FIND("@",SUBSTITUTE(LEFT(A1,FIND(",",A1))," ","@",LEN(LEFT(A1,FIND(",",A1)))-LEN(SUBSTITUTE(LEFT(A1,FIND(",",A1))," ",""))))+1,LEN(A1))

This returns:
Yucaipa, CA 992399
Hesperia, CA 92345
Victorville, CA 92345

From your test data.
If by any chance you have @ symbol in your texts, you can try this instead:
=MID(A1,FIND(CHAR(1),SUBSTITUTE(LEFT(A1,FIND(",",A1))," ",CHAR(1),LEN(LEFT(A1,FIND(",",A1)))-LEN(SUBSTITUTE(LEFT(A1,FIND(",",A1))," ",""))))+1,LEN(A1))

Explanation
=LEFT(A1,FIND(",",A1)) gives 34470 Yucaipa Boulevard Yucaipa,. Let's call this bit 'Text'.
=SUBSTITUTE(Text," ","@",LEN(Text)-LEN(SUBSTITUTE(Text," ",""))). This bit is to replace the last instance of space by @. The 4th parameter of SUBSTITUTE gives the instance of the space to be replaced, and LEN(Text)-LEN(SUBSTITUTE(Text," ","")) gives the number of spaces in the text. You get 34470 Yucaipa Boulevard@Yucaipa, as result for this part
Then, do a MID on this to get the position of the @ till the end.

A: I hope this has not been mentioned:
=TRIM(RIGHT(SUBSTITUTE(A1," ",REPT(" ",99)),297))


text:
Q: How can I set dynamically the parameter of a lift snippet? Is there a way I can modify dynamically the param of a snippet?
E.g. If I call this URL
host:port/a_page?name=myname

I would like that my page look like this:

      ...

Is that even possible? I tried using some javascript in order to extract the param from the url and putting it in the class attribute of the div but in my understanding that won't work becase the scripts will always execute after lift framework does it's magic.
Thanks in advance! Any help is really appreciated.

I used both tips provided to make it work, like ajantis mentioned reading the param directly from snippet is the easiest way but doesnt work in a comet call. Rogach solution works.
So the solution is:

def wrap = {
val name = "lift:comet?type=MySnippet;name=" + S.param("name").openOr("...")
"#myid" #>

}

A: Why not just extract http parameter inside snippet processing? i.e.
def render = {
   val name = S.param("name").openOr("...")
....
}

A: You can try wrapping that comet snippet in other snippet, which would transform xml and add that name=myname to class. Like:

class Ex {
  def wrap = { (n: NodeSeq) =>
    // example transformation
    // AntiXML syntax
    import com.codecommit.antixml._;
    val comet = n \ "div" head;
    val comet2 =
      comet.copy(attrs = comet.attrs +
                         ("class" -> (comet.attrs("class") + ";name=myname")))
    n \ "div" updated (0, comet2) unselect
  }
 }


text:
Q: Why Spring @Transactional is successfully rolling back on (SQL insert) but fails when (SQL update) - Multiple Datasources I have a project that uses Spring Boot & JPA. APIs are exposed using REST.
I have two different databases (Mysql 8) connected and for pooling Hikari has been added. Chained transaction manager has been used for rolling back both DBs in case any one of them failed.
First Issue: If i mark TMSDbConfig as @Primary then no insertion takes place in secondary DB which is UserProfileDbConfig. Only One transactionManager start which is capable to insert in TMSDbConfig.
Second Issue: If i mark UserProfileDbConfig as @Primary then the above problem is solved and now i can insert in both DBs and on insert failure they both are rolling back as well. But when i get the Entity from DB (using findByName())do some changes and persist it back on the failure of second the first one never rollback.
I have tried, @EnableTransactionManagement on MainApp, @ComponentScan @EntityScan
Tried adding annotations @Repository or @Component as well.
Also tried to put the methods in different beans.
Nothing works.
Following are the configurations,
Main:
@SpringBootApplication
public class SingleEntryAuthServiceApp

DB Config,
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.mycompany.chainedtransactionmanager.repository.db2",
        entityManagerFactoryRef = "db2EntityManagerFactory", transactionManagerRef = "db2PlatformTransactionManager")
public class UserProfileDbConfig {

    @Primary
    @Bean(name = "db2DataSource")
    @ConfigurationProperties(prefix = "spring.userprofile-datasource")
    public DataSource db2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "db2EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean db2EntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(db2DataSource())
                .packages("com.mycompany.chainedtransactionmanager.model.db2")
                .persistenceUnit("db2")
                .build();
    }

    @Primary
    @Bean(name = "db2PlatformTransactionManager")
    public PlatformTransactionManager db2PlatformTransactionManager(EntityManagerFactory db2EntityManagerFactory) {
        return new JpaTransactionManager(db2EntityManagerFactory);
    }
}

Another DB Config,
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.mycompany.chainedtransactionmanager.repository.pgsql",
        entityManagerFactoryRef = "pgsqlEntityManagerFactory", transactionManagerRef = "pgsqlPlatformTransactionManager")
public class TMSDbConfig {

    @Bean(name = "pgsqlDataSource")
    @ConfigurationProperties(prefix = "spring.tms-datasource")
    public DataSource pgsqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "pgsqlEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
        pgsqlEntityManagerFactory(@Qualifier("pgsqlDataSource") DataSource
        pgsqlDataSource, EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(pgsqlDataSource)
                .packages("com.mycompany.chainedtransactionmanager.model.pgsql")
                .persistenceUnit("pgsql")
                .build();
    }

    @Bean(name = "pgsqlPlatformTransactionManager")
    public PlatformTransactionManager pgsqlPlatformTransactionManager(@Qualifier("pgsqlEntityManagerFactory") EntityManagerFactory pgsqlEntityManagerFactory) {
        return new JpaTransactionManager(pgsqlEntityManagerFactory);
    }
}

ChainedTransactionManager,
@Configuration
public class TransactionManagerConfig {

    @Bean(name = "chainedTransactionManager")
    public ChainedTransactionManager transactionManager(
            @Qualifier("db2PlatformTransactionManager") PlatformTransactionManager db2PlatformTransactionManager,
            @Qualifier("pgsqlPlatformTransactionManager") PlatformTransactionManager pgsqlPlatformTransactionManager) {
        return new ChainedTransactionManager(db2PlatformTransactionManager,
                pgsqlPlatformTransactionManager);
    }
}

Service Layer Insert Code, Successfully Rolling Back,
@Override
@Transactional(value = "chainedTransactionManager", rollbackFor = {Exception.class}, propagation = Propagation.REQUIRES_NEW)
public void saveService() {
    try {
        {//Insert code..

            DB2Test1 SecTable = new DB2Test1();
            SecTable.setName("LongTextToCreateSqlError");
            db2Repo.save(SecTable);

            DB1Test1 firstTable = new DB1Test1();
            firstTable.setName("acceptedText");
            db1Repo.save(firstTable);
        }
    } catch (Exception e) {
    }

Service Layer Update Code, Failed Rolling Back,
@Override
    @Transactional(value = "chainedTransactionManager", rollbackFor = {Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public void saveService() {
try {
    DB2Test1 SecTable = db2Repo.findByName("Jhon");
    SecTable.setName("LongTextToCreateFailed");

    try {
        db2Repo.save(SecTable);
    } catch (Exception e) {
        throw e;
    }
    DB1Test1 firstTable =  db1Repo.findByName("Jhon");
    firstTable.setName("AcceptedText");
    try {
        db1Repo.save(firstTable);
    } catch (Exception e) {
        throw e;
    }
} catch (Exception e) {
    throw e;
}
}

In the logs i can see that in case of Insert the entityManager didnt closed until both db operation got success,
but in case of update after running the first update Query the entityManager closed.
I am unable to understand the behavior,
Insert case is successfully rolling back but on update its not rolling back. If its realated with managed beans then what is the difference between insert code and update code.
Thanks a lot Greetings

A: Solution
Found a Solution, May be it will save couple of days for someone searching for this,
I switched from JPA simple .save() method to .saveAndFlush() and all the test cases have been passed either both persists in DB or both rollback.
Cheers!


text:
Q: azure rest api for azure container apps is there an api or azure golang sdk for "Azure Container Apps" service ?, this is still in preview.
https://learn.microsoft.com/en-us/azure/container-apps/?ocid=AID3042118
There is no listing of this in the Azure Rest API portal
https://learn.microsoft.com/en-us/rest/api/azure/
Thanks -Nen.

A: The REST API reference is now available here:
https://learn.microsoft.com/en-us/rest/api/containerapps/

A: As the Azure Container Apps is still in preview, there is no REST API for this service as of now


text:
Q: Would Upgrading to 16GB RAM be Beneficial? I'm running on an i3 processor, 2010 model, 3.06 GHz.

I'm currently have 4GB of RAM, but if I were to upgrade to 16GB, would:

*

*Applications open quicker?

*FPS increase in game?

*Overall performance increase?

Thanks for your help.

A: Looking at your memory usage you don't need more RAM.
To answer your questions:

*

*Apps may open faster if you are running lots of heavy duty apps, like Photoshop, Xcode, etc…

*I doubt you'd see much of an increase in the FPS in games. That depends on the video card and how well the game is written.

*Overall performance increase would probably be minimal. The biggest bottleneck is if you are running off a spinning disk, upgrading to an SSD would probably be the biggest performance gain, depending on what you use your computer for.

A: If you are using many programs at the same time e.g many browser tabs and you are left with little free RAM then yes, you will see performance increased.
It really depends on the usage. I can't work on a computer with less than 8GB of RAM (many, many chrome tabs, iTunes, and 3-4 programs open at the same time). But many people are OK with 4GB.

A: Yes, it seems that from your screen capture you do need more RAM.
From the Apple support pages:

Tip: Page outs occur when the Mac has to write information from RAM to
  the hard drive (because RAM is full).  Adding more RAM may reduce page
  outs.

So it seems that you're heavily maxing out your RAM. Check this value and try to determine when you're out of RAM, it could be a one off, but if you're always in the GB definitely upgrade.
Keep in mind that it won't be reset until you restart your computer, it's cumulative.


text:
Q: How to troubleshoot "Could not find platform independent libraries " in Python & buildozer Through buildozer in Ubuntu, I was running an app I am developing.
However, I faced the following error:
Could not find platform independent libraries <prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: initfsencoding: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

I searched and searched and searched for an adequate method for treating this particular problem on Google. Then, I found few methods to fix  this problem.
For the first attempt, I set: export PYTHONHOME=/usr/local/lib/python3.7 as suggested in the error comments. Unfortunately, the same error appeared even with this change. For the second attempt, I tried to delete virtual environment file and reset it as suggested on the following website: ImportError: No module named 'encodings'. But, again, I failed to eliminate this error.
I saw that some of the posts on Stackoverflow regarding this issue provide repetitive methods. I am stuck with this issue. I would deeply appreciate it if anyone can be kind enough to shed some light on this.
Blessings.

A: Follow these steps to avoid this

*

*Activate virtualenv by source venv/bin/activate

*Set ENV["PYTHON"] to correct Python path under the virtualenv

*Install PyCall by pip install pycall

*Open v0.6/PyCall/deps/deps.jl with a text editor and replace const PYTHONHOME = "..." with const PYTHONHOME = ""

*Run using PyCall
Further details