text:
Q: How can I make an unclipped subview receive touch events? I have a small custom view that I use as a button.  I make this happen with a simple UIButtonTypeCustom, which I include as a subview over the bounds of the view.  Since the view is small, however, I want to increase the size of the hit target.  This is easily done (one would think) by setting the frame of my button to be larger than the bounds of the custom view and setting clipsToBounds to NO.  This works for the visual (the custom button draws outside the parent view) but it does not receive touchUpInside events on the area outside of the parent view.  How do I make the button receive touchUpInside events?
- (id) initWithFrame: (CGRect) frame {
  if (self = [super initWithFrame: frame]) {
    self.backgroundColor = [UIColor clearColor];
    self.clipsToBounds = NO;

    // ... various image views and labels ...

    UIButton *touchArea = [UIButton buttonWithType: UIButtonTypeCustom];
    touchArea.backgroundColor = [UIColor colorWithRed: 1 green: 0 blue: 0 alpha: .3]; // so I can see the bounds
    CGRect touchAreaFrame = self.bounds;
    CGFloat checkboxHitTargetExtension = 7;
    touchAreaFrame.origin.y -= checkboxHitTargetExtension;
    touchAreaFrame.size.height += (checkboxHitTargetExtension * 2);
    touchArea.frame = touchAreaFrame;
    [self addSubview: touchArea];

    // ... add listeners etc ...
  }
  return self;
}

A: You can use pointInside:withEvent: to define whether or not a specific point is "inside" the View. See the UIView reference for more info.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html
Also checkout CGRectOffset its very handy for making a CGRect bigger.

A: Make the button not a child of the view but a sibling to the view, and positioned on top of it, and then there are no clipping issues on the touches to the button.


text:
Q: Put python doctest at the end of the code file? I can put python doctests in the bodies of each function, which I sometimes like for small libraries, because they are in the same file as the function.
Or I can put them all together into a seperate file and execute the separate file, which is nice in case I do not want the doctest in between the functions. Sometimes I find the code is easier to work on if the docstrings are small.
Is there also a way to keep the python doctests in the same file, but put them all together at the end of the file?

EDIT: A solution, based on the accepted answer below:
def hello_world():
  return u'Hello World'

def hello(name):
  return u'Hello %s' % name

def doctest_container():
  """
  >>> hello_world()
  u'Hello World'

  >>> hello(u'Guido')
  u'Hello Guido'
  """
  pass

if __name__ == "__main__":
    import doctest
    doctest.testmod()

In fact it is simple, a dummy function is created as the last function that contains all the doctests in one docstring.

A: You can append the doctests to the docstring at the end of file like that:
def myfunc():
    """This is a docstring without a doctest
    """
    pass

# ... some other code here

# Add docstrings for doctest:
myfunc.__doc__ += """
>>> myfunc()
>>> repr(myfunc())
None
"""

A: doctest is to test that examples in your documentation are in sync with the implementation.
if there are many tests; unit tests written as code might be easier to maintain than doctest-based tests.
You could add a test function at the end of the module with desired doctests to avoid polluting docstrings of non-test code:
def test():
    """
    ..
    """
    import doctest
    doctest.testmod()

if __name__=="__main__":
    test()  # if the module is called as a script then run tests

redpajama_set_name: RedPajamaStackExchange


text:
Q: When to use std::invoke instead of simply calling the invokable? As I understand, std::invoke allows me to do something like:
std::invoke(f, arg1, arg2, ...);

Is there a scenario when it's more advantageous than simply doing:
f(arg1, arg2, ...);

A: std::invoke can be useful when you create a lambda and need to call it immediately. It the lambda is big, parentheses after it can be hard to observe:
[] (/* args */) {
    // many lines here
    // ...
} (/* args */)

vs
std::invoke(
    [] (/* args */) {
        // many lines here
        // ...
    },
    /* args */);

A: If the invocable is a pointer to a member function, then you need to do one of  these:
(arg1->*f)(arg2,...);
(arg1.*f)(arg2,...);

Depending on what arg1 is.
INVOKE (and its official library counterpart std::invoke) was pretty much designed to simplify such messes.
You'd use std::invoke to support the caller of your code passing any callable, and not having to adapt their call site with a lambda or a call to std::bind.

A: Trying to add on top of the two answers, one is giving a good theoretical explanation and the other is trying to provide a concrete example. Here is a good reason of why does std::invoke makes things better.
#include <functional>
#include <iostream>

struct foo
{
    void echo(){std::cout << "foo" << std::endl;};
};

int main()
{
    ////
    // Vanilla version of invoking .echo()
    foo(f);
    f.echo();

    ////
    // Pointer to *class* member function version
    void (foo::* pf)() =  &foo::echo;
    foo obj;

    (obj.*pf)();    // ugly
    // instead do ...
    std::invoke(pf, obj);

    // obj->echo(); <-- does not compile

    return 0;
}

A: #include <iostream>
#include <functional>
template< class Callable, typename ... Args>{}

    //f(args...);   // if arg1 is a class object pointer
                    // we should use it like this(arg1.*f)(args...);

    std::invoke(f, args...); //  now  every thing is ok
}

void foo(char c) {
    std::cout << "foo called\n";
}

int main()
{
    struct S {
        int f1(char c) {
            std::cout << "S::f1 called\n";
        }
        void operator()(char c) {
            std::cout << "S::operator() called\n";
        }
    };
    int (S:: * fptr)(char c) = &S::f1;
    S  obj;

    dosomething(fptr, obj, 'a');
    return 0;
}


text:
Q: ¿Cómo calcular días después a una fecha en MySQL? Necesito que muestre:

código de orden, fecha de orden, fecha requerida y posible fecha de envío

A todas las órdenes que no tengan fecha de envío ¿cómo puedo calcular la posible fecha de envío que debe calcularse con 15 días después de la fecha requerida?
Tengo la siguiente sintaxis:
Select OrderID, OrderDate, RequiredDate from orders;

A: Para lo que intentas obtener deberías ocupar:

*

*ADDDATE para agregar un intervalo de tiempo

*Como tratas de agregar un período de 15 días entonces usa INTERVAL 15 DAY

*Indicas que solo se aplique el incremento de días cuando no se tenga fecha de envío en las órdenes, pudieras entonces usar IS NULL en conjunto con WHERE
Tal vez de este modo:
Select OrderID,
       OrderDate,
       ADDDATE(RequiredDate, INTERVAL 15 DAY) AS Fecha
from orders
WHERE fechaenvio* IS NULL;

Indicando que solo aplique ese incremento de 15 días DONDE la fecha de envío este NULL

*Solo sustituye fechaenvio por el nombre de la columna que aplique para tu escenario.


text:
Q: How to find vertices of a $5$-dimensional simplex, where the vertices are formed by zeroes and ones? I'm trying to find the vertices of a simplex in the $5$-dimensional space, where the vertices are formed by only zeros and ones, similarly to these coordinates that represent a simplex in the $7$-dimensional space:
$$\begin{align}
\phantom{+}(0000000)+(0001111)+(0110011)+(0111100)\\
+(1010101)+(1011010)+(1100110)+(1101001)
\end{align}$$
Is there an algorithm or method to calculate these kinds of simplexes?

A: This is not an answer but it's too long for a comment (EDIT - There is now an answer at the end).  I don't think this is possible.  I conjecture that there exists an $n$-simplex whose vertices have coordinates $(a_1,a_2,\ldots,a_n)$ where $a_i\in\{0,1\}$ if and only if $n=2^k-1$ for some positive integer $k$.   I can prove the converse for now.  (See my edit at the end.  My conjecture is not true, but the proof below can be used to show that if an $n$-simplex with the required property exists, then a $(2n+1)$-simplex with the required property exists.)
Let $\oplus$ be the entry-wise addition modulo $2$.  For example $$(0,1,1,0)\oplus(1,0,1,0)=(1,1,0,0).$$  Define $h(x)$ for $x\in\{0,1\}^n$ to be the number of ones in $x$.  For example, $$h(0,0,1,1,1)=3.$$
For the converse, we prove inductively.  Let $x_0^k,x_1^k,\ldots,x_{2^k-1}^k$ be the vertices for a given $k$ such that $x_0^k=(\underbrace{0,0,\ldots,0}_{2^k-1\ \text{zeros}})$, and each $x_i^k$ has exactly $2^{k-1}$ ones for $i=1,2,\ldots,2^k-1$.
We define the following vectors:
$$X_i^k=\left(0,x_i^k\right)$$
and
$$\bar{X}_i^k=(\underbrace{1,1,\ldots,1}_{2^k\ \text{ones}})\oplus  X_i^k.$$  Now take
$$x_{2i}^{k+1}=\left(x_i^k,X_i^k\right)$$
and
$$x_{2i+1}^{k+1}=\left(x_i^k,\bar{X}_i^k\right).$$
We have
\begin{align}h\left(x_{2i}^{k+1}\oplus x_{2i+1}^{k+1}\right)&=h\left(\underbrace{0,0,\ldots,0}_{2^k-1\ \text{zeros}},\underbrace{1,1,\ldots,1}_{2^k\ \text{ones}}\right)=2^k.\end{align}
For $i\ne j$,
\begin{align}h\left(x_{2i}^{k+1}\oplus x_{2j}^{k+1}\right)&=h\left(x_i^k\oplus x_j^k,0,x_i^k\oplus x_j^k\right)\\&=2\cdot h(x_i^k\oplus x_j^k)=2\cdot2^{k-1}=2^k,\end{align}
\begin{align}h\left(x_{2i+1}^{k+1}\oplus x_{2j+1}^{k+1}\right)&=h\left(x_i^k\oplus x_j^k,0,x_i^k\oplus x_j^k\right)\\&=2\cdot h\left(x_i^k\oplus x_j^k\right)=2\cdot2^{k-1}=2^k,\end{align}
and
\begin{align}h\left(x_{2i}^{k+1}\oplus x_{2j+1}^{k+1}\right)&=h\left(x_i^k\oplus x_j^k,1,(\underbrace{1,1,\ldots,1}_{2^k-1\ \text{ones}})\oplus x_i^k\oplus x_j^k\right)\\&=h\left(x_i^k\oplus x_j^k\right)+2^k-h\left(x_i^k\oplus x_j^k\right)=2^k.\end{align}
For example, we start with $x_0^1=0$ and $x_1^1=1$.  Then we have
$$x_0^2=(0,0,0),x_1^2=(0,1,1),x_2^2=(1,0,1),x_3^2=(1,1,0).$$
Then
$$x_0^3=(0,0,0,0,0,0,0), x_1^3=(0,0,0,1,1,1,1),$$ $$x_2^3=(0,1,1,0,0,1,1),x_3^3=(0,1,1,1,1,0,0),$$
$$x_4^3=(1,0,1,0,1,0,1),x_5^3=(1,0,1,1,0,1,0),$$ $$x_6^3=(1,1,0,0,1,1,0),x_7^3=(1,1,0,1,0,0,1).$$

As remarked by Empy2, if there exists Hadamard matrix $H_{n+1}$ of size $(n+1)\times (n+1)$, then there exists such an $n$-simplex. If $H_{n+1}$ exists, we can assume that its first row and its first column are both $e=(\underbrace{1, 1, \ldots, 1}_{n+1\ \text{ones}})\in\Bbb R^{n+1}$.  Let $y_0,y_1,y_2,\ldots,y_{n}\in\Bbb \{1,-1\}^{n+1}$ be the columns of $H_{n+1}$. Since $y_0=e$ is orthogonal to $y_1,y_2,\ldots,y_n$, it follows that for $n>0$, $n$ must be odd and each $y_i$ has exactly $\frac{n+1}{2}$ ones for $i\ne 0$.
Define
$$X_i=\frac{1}{2}\big(e-y_i\big).$$
Then the first position of $X_i$ is always $0$.  We can take $x_0,x_1,\ldots,x_n\in\Bbb R^n$ to be
$$X_i=(0,x_i).$$
Then $x_0=(0,0,\ldots,0)$ and for $i=1,2,\ldots,n$, $x_i$ has exactly $\frac{n+1}{2}$ ones.
 If $i\ne 0$, we have
$$h(x_0\oplus x_i)=h(x_i)=\frac{n+1}{2}.$$
If $i,j\ne 0$, we have
$$h(x_i\oplus x_j)=h(x_i)+h(x_j)-2x_i\cdot x_j=(n+1)-\frac12(e-y_i)\cdot(e-y_j).$$
Thus for $i,j\ne 0$ and $i\ne j$, we get
$$h(x_i\oplus x_j)=(n+1)-\frac{n+1}{2}=\frac{n+1}{2}.$$
This means $x_0,x_1,\ldots,x_n$ form an $n$-simplex.
I think the converse holds too.  That is, I have the following conjecture.  I guess that if $h(x_i)=\delta$ for $i\ne 0$, then we can assume wlog that $x_0,x_1,x_2,\ldots,x_{2\delta-1}$ live in $\mathbb{R}^{2\delta-1}$.  The "wlog" assumption cannot yet be shown that it is indeed "wlog".

Conjecture:  An $n$-simplex whose vertices are $x_0,x_1,x_2,\ldots,x_n\in\{0,1\}^n$ exists if and only if a Hadamard matrix of size $(n+1)\times(n+1)$ exists.

It is conjectured that $H_{n+1}$ exists iff $n=0$, $n=1$, or $n=4k-1$ for some positive integer $k$. (The forward implication is known and not difficult to prove.  That is, if $H_{n+1}$ exists, then $n=0$, $n=1$, or $n=4k-1$.  See page 6 here.)  The conjecture is true at least for $n\le 100$.  Therefore at least for $n\le 100$ and $n=4k-1$, you can find your $n$-simplex.

For the situation at hand ($n=5$), such a simplex doesn't exist.  Suppose for contradiction that $x_0,x_1,x_2,x_3,x_4,x_5\in\{0,1\}^5$ exist so that $h(x_i\oplus x_j)=\delta$ for some fixed integer $\delta$.  WLOG, $x_0=(0,0,0,0,0)$.
Note that $h(x_i)=h(x_i\oplus x_0)=\delta$ for $i\ne 0$.  Therefore,
$$\delta=h(x_i\oplus x_j)=h(x_i)+h(x_j)-2x_i\cdot x_j=2\delta-2x_i\cdot x_j.$$
This means
$$\delta=2x_i\cdot x_j.$$
Hence $\delta$ is even.  Write $\delta=2d$.  Clearly, there are only two possible cases: $d=1$ or $d=2$.
If $d=2$, then $\delta=4$.  There are exactly $5$ vectors in $\{0,1\}^5$ with $4$ ones:
$$(0,1,1,1,1),(1,0,1,1,1),(1,1,0,1,1),(1,1,1,0,1),(1,1,1,1,0).$$
This means
$$h(x_i\oplus x_j)=2\ne\delta$$
for $i,j\ne 0$ and $i\ne j$.  So $d\ne 2$.
If $d=1$, then $\delta=2$.  Wlog, we can take
$$x_1=(0,0,0,1,1)\wedge x_2=(0,0,1,0,1).$$
Now, it follows that there is only one choice left for $x_3,x_4,x_5$, which is $(0,0,1,1,0)$.  We have a contradiction again.


text:
Q: ActionScript and SQLite parameters on Select using Like I tried looking on google but without luck...
I have a SELECT SQLStatement and I want to use the LIKE operator but the parameters won't work and the query give me an error
    public function getUsersList(username:String):SQLStatement
    {
        selectRecord= new SQLStatement();
        selectRecord.sqlConnection = connection;
        selectRecord.text =
            "SELECT id_user, username,password,profile,leg_cliente " +
            "FROM userlist  " +
            "WHERE username like '%:username%'";
        selectRecord.parameters[":username"] = username;

        return selectRecord;
    }

The error I got is

':username' parameter name(s) found in parameters property but not in
  the SQL specified.

A: I solved putting the wildcard % in the parameters instead of the statement...
        selectRecord.text =
            "SELECT id_user, username,password,profile,leg_cliente " +
            "FROM userlist  " +
            "WHERE username like :username";
        selectRecord.parameters[":username"] = "%"+ username+"%";

The starting problem was triggered because the query was like
    selectRecord.text =
        "SELECT id_user, username,password,profile,leg_cliente " +
        "FROM userlist  " +
        "WHERE username like '%:username%'";

Putting the single quote in the statement won't let the statement to set the parameter, I suppose because the parameter key (in statement.text) is seen as a text and not a parameter itself...

A: This is a weird issue I've been stuck with for quite some time now. One solution I've used is like this:
var statementText:String="SELECT id_user, username,password,profile,leg_cliente " +
        "FROM userlist  " +
        "WHERE username like '%:username%'";

var params:Dictionary=new Dictionary();
params[":username"] = username;

for(var key:Object in params) {
    while(statementText.indexOf(key.toString()) >= 0) {
        statementText= statementText.replace(key, params[key]);
    }
}

selectRecord.text = statementText;


text:
Q: request.getparamater int no=request.getParameter(Integer.parseInt("rollnumber"));

Description    Resource    Path    Location    Type
  The method getParameter(String) in the type ServletRequest is not applicable for the arguments (int)   Controller.java /SecondApp/src  line 21 Java Problem

A: First of all, please edit your question-title so it is a actual question.
Secondly, you call parseInt() in the wrong place.
The correct syntax would be:
int no= Integer.parseInt(request.getParameter("rollnumber"));

A: int no=Integer.parseInt(request.getParameter("rollnumber"));


text:
Q: Child Components in Native Android view does not resize correctly I have created native android view and it needs to wrap child components from react-native
I am using a TouchableOpacity as a child to the native android view which I created. When the screen loads the TouchableOpacity takes the whole width and height and which is not what I want but as soon as I comment and uncomment the width style of TouchableOpacity it relayout correctly. So in short as soon as Fast refresh is done the layout looks proper, not sure what the issue here is. Even giving a fix height to TouchableOpacity does not work
Layout when the app first loads

Layout when fast refresh is done by commenting and uncommenting the TouchableOpacity's width

Here is the code
class CealGradientView(context: Context): LinearLayout(context){

    fun configureViews(color: ReadableArray){
        val layoutParams: ViewGroup.LayoutParams =
            LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        setLayoutParams(layoutParams)

        val colorsCollection: ArrayList<Int> = ArrayList()
        for (i in 0 until color.size()) {
            colorsCollection.add(Color.parseColor(color.getString(i)))
        }
        val colors = colorsCollection.stream().mapToInt { i -> i }.toArray()
        val gradientDrawable = GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM,
            colors
        )
        background = gradientDrawable
}

class CealGradientManager(private val reactApplicationContext: ReactApplicationContext):
    ViewGroupManager<CealGradientView>() {

    private val cealGradientView = "CealGradientView"

    override fun getName() = cealGradientView

    override fun createViewInstance(reactContext: ThemedReactContext): CealGradientView {
        return CealGradientView(reactContext)
    }

    @ReactProp(name = "colors")
    fun configureView(view: CealGradientView, color: ReadableArray) {
        view.configureViews(color)
    }
}

<CealGradientView colors={[theme.Primary_50, theme.Information]} style={styles.linearGradient}>
<BorderButton text={EXISTING_USER} onPress={() => {}} isDarkMode={isDarkMode} />
    </CealGradientView>

const BorderButton = ({ text, isDarkMode, onPress }: Props) => {
  const theme = THEME_COLOR.SET(isDarkMode)

  return (
    <TouchableOpacity style={[styles.buttonStyle, { borderColor: theme.White }]} onPress={onPress}>
      <Text style={[styles.textStyle, { color: theme.White }]}>{text}</Text>
    </TouchableOpacity>
  )
}

const styles = StyleSheet.create({
  buttonStyle: {
    width: '100%',
    borderRadius: 8,
    alignItems: 'center',
    borderWidth: 1,
  },
  textStyle: {
    fontFamily: Fonts.InterSemiBold,
    fontSize: 16,
    lineHeight: 48,
    textTransform: 'uppercase',
  },
})

I have trying following this issue and tried some of the solutions mentioned but no luck
Sample reo https://github.com/PritishSawant/NativeAndroidLinearGradient
I have also tried adding following code but it does not work
private fun setupLayout() {
        Choreographer.getInstance().postFrameCallback(object: Choreographer.FrameCallback {
            override fun doFrame(frameTimeNanos: Long) {
                manuallyLayoutChildren()
                viewTreeObserver.dispatchOnGlobalLayout()
                Choreographer.getInstance().postFrameCallback(this)
            }
        })
    }

    /**
     * Layout all children properly
     */
    private fun manuallyLayoutChildren() {
        for (i in 0 until childCount) {
            val child = getChildAt(i)
            child.measure(MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY))
            child.layout(0, 0, child.measuredWidth, child.measuredHeight)
        }
    }

A: if your problem solved with commenting width, so instead of {{width:'100%'}} use {{width}} =>
const {width, height} = Dimensions.get('window');

A: I already encountered a similar problem, but working in Java. So i'll try my best to help you but my code may contains mistakes.
I resolved it by adding self measuring logic to my Layout, you can try adding it too and see if it helps.
Add the following methods to your CealGradientView class :
override fun requestLayout() {
    super.requestLayout()
    post(measureAndLayout)
}

private val measureAndLayout = Runnable {
    measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY))
    layout(left, top, right, bottom)
}

see this old SO answer for Java equivalent, hope it helps !


text:
Q: Why isn't params being read properly? When I try to run this in one of my controllers:
goal = @user.goals.detect{|g| g.id == params[:id]}
goal gets set to nil. The thing is, I've run puts params[:id] before this line and it output 112. So I plugged 112 into the detect in place of params[:id] and it worked fine. I don't understand why params[:id] isn't being read 'as 112', which is what puts outputs. Can anyone give me some suggestions?

A: Your params[:id] is going to be a string, and it's likely that your g.id is an integer. While they will both print the same, they are not equal:
>> "112" == 112
=> false
>> puts "112"
112
=> nil
>> puts 112
112
=> nil

You should probably convert your parameter to an integer before comparing it:
goal = @user.goals.detect{|g| g.id == params[:id].to_i}

A: I guess params[:id] equals to '112' (string), not 112 (integer).
Try this:
goal = @user.goals.detect{|g| g.id == params[:id].to_i}


text:
Q: Power App Subscription to run the power app If I share the power app with user in organization(Active directory), then do they need a power app subscription/Licence to run the power app. I want to create a simple data entry for and share it with users in organization.
Regards,
Mahesh

A: PowerPlatform licesing can quickly become a very complex topic.
Its highly dependant on:

*

*Which Office365 and Dynamics365 licensing your org has in place

*Whether your solution uses On-premise data

*Whether your solution uses Premium connectors

*etc.

Generally speaking, if everyone in your org has the correct Office365 license AND your solution uses only non-premium connectors (Sharepoint, Outlook365, OneDrive, etc.), you can expect your app to work for everyone at your org.
Please see pg. 6 ("Power Appsuse rights included with Office 365licenses") and Appendix B of the latest PowerPlatform licensing guide (currently found here: https://download.microsoft.com/download/9/5/6/9568EFD0-403D-4AE4-95F0-7FACA2CCB2E4/Power%20Apps,%20Power%20Automate%20and%20Power%20Virtual%20Agents%20Licensing%20Guide%20-%20Dec%202020.pdf)


text:
Q: Insert Procedure with IF statement I have procedure which i want to upgrade
it is inserting new record for client in pickup data table before insert it is checking if new record for this client was inserted this month if yes it not inserting new record
i am trying to update it  so it will check if client StatusID in (1,2,6). So far i have this
alter PROCEDURE dbo.InsertPickup
    @ClientID int, --Required ClientID and PickupDate
    @PickupDate date
AS
   IF NOT EXISTS (SELECT * FROM Pickup
                  WHERE ClientID = @ClientID
                    AND MONTH(PickupDate) = MONTH(@PickupDate)
                    AND YEAR(PickupDate) = YEAR(@PickupDate) )
if exists (select * from clients where statusid in (1,2,6))
      INSERT INTO Pickup (ClientID, PickupDate)
      VALUES (@ClientID, @PickupDate)

however it is not right it still inserting record if for example client  with statusid = 5 or 3 or 4

A: Proper indentation and BEGIN/END wrappers can go a long way toward spotting issues in queries. I've added the check to ClientID and also made your test against PickupDate sargable (in case there's an index now or will be one in the future).
IF NOT EXISTS
(
  SELECT 1
    FROM dbo.Pickup WHERE ClientID = @ClientID
    AND PickupDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, @PickupDate), 0)
    AND PickupDate < DATEADD(MONTH, DATEDIFF(MONTH, 0, @PickupDate)+1, 0)
)
BEGIN
  IF EXISTS
  (
    SELECT 1
      FROM dbo.clients WHERE ClientID = @ClientID
      AND statusid IN (1,2,6)
  )
  BEGIN
      INSERT INTO dbo.Pickup (ClientID, PickupDate)
      VALUES (@ClientID, @PickupDate);
  END
END

Of course you can also do this without all the nested IF tests:
INSERT dbo.Pickup(ClientID, PickupDate)
  SELECT @ClientID, @PickupDate
    WHERE EXISTS
    (
      SELECT 1 FROM dbo.clients WHERE ...
    )
    AND NOT EXISTS
    (
      SELECT 1 FROM dbo.Pickup WHERE ...
    );

A: You've not filtered your clients table by the @ClientID in your second IF EXISTS statement, hence it's not working as expected.  Try:
if exists (select * from clients where statusid in (1,2,6) AND ClientID = @ClientID)


text:
Q: Jquery method not working to fetch the value particular key I have a  function who is containing  a list of object i am loop it through but i want value according  to the name of the key like id only .. i am unable to do so.
data in comlist--
[{"id":1,"companyname":"AB Information System","acronym":"ABC"},
{"id":2,"companyname":"AC Information System","acronym":"AC"}]

handleData( responseData ) { // [object Object],[object Object]
        var comlist = responseData;
      $.each(comlist, function(key, value) {
           var comlistobj = comlist[key];
        $.each(comlistobj , function(key, value) {
             console.log(key); // if it prints for 1st iteration it prints "id"
             console.log(value); // if it prints for 1st iteration it prints 1
             console.log(value.id); // **but i want value according  to the name of the key id, it is printing undefined here**
            });
        });
    }
 });

Let me know if anything unclear in this.

A: You should avoid the second $.each loop to get the value based on the key.
$(document).ready(function() {

  var jsonResponse = [{"id":1,"companyname":"AB Information System","acronym":"ABC"}, {"id":2,"companyname":"AC Information System","acronym":"AC"}];

  $.each(jsonResponse, function( key, json ) {
    console.log(json.id)
  });
});

Take a look to the demo https://jsbin.com/damedigane/edit?js,console,output
Modification based on your codes:
[{"id":1,"companyname":"AB Information System","acronym":"ABC"},
{"id":2,"companyname":"AC Information System","acronym":"AC"}]

handleData( responseData ) { // [object Object],[object Object]
        var comlist = responseData;
      $.each(comlist, function(key, value) {

           // here value = comlist[key] is same
           var comlistobj = comlist[key];

        // Prefer to avoid this loop if you want the value based on key
        $.each(comlistobj , function(key, value) {
             console.log(key); // if it prints for 1st iteration it prints "id"
             console.log(value); // if it prints for 1st iteration it prints 1
             console.log(comlistobj.id); // works here
            });
        });
    }
 });


text:
Q: Form input, need help setting value of input i'm trying to get value of input field, so depending on if the input value is 0 or 1, the value of the input is one or two, and it's supposed to show up in console.
<!DOCTYPE html>

    <title>demo</title>
    <meta charset="utf-8">

Input 0 or 1.

    <input id="ok" type="text">
    <button onclick="functionn()"></button>

</html

A: You are so close!
The problem that you have is the "x" variable, it holds the value on the input after the page was loaded, which is and empty string.
You need to put that variable inside the function, so every time you click the button you will "go" and check the value of the input and then store it inside the "x" variable.
Hope this help! =]

A: try it:
<!DOCTYPE html>

        <title>demo</title>
        <meta charset="utf-8" />

Input 0 or 1.

        <input id="ok" type="text" />
        <button onclick="functionn()"></button>


text:
Q: Access web server on VirtualBox/Vagrant machine from host browser? I have a Django web server on a VirtualBox/Vagrant machine running Ubuntu.
I have followed this guide to create a Django project: https://docs.djangoproject.com/en/dev/intro/tutorial01/
I have a web server running at http://127.0.0.1:8000/ inside my guest machine. This is the first time I am running a Django web server. It is supposed to be a hello world app.
How can I access this web application from my host browser?
I have tried running ifconfig in the guest to get the IP that I should visit I found a promising IP address in inet addr.
But I have tried entering the following into my host browser and it didn't work.
http://inetaddrnumbers:8000/
How can I access the web server from my browser?

A: Try this.

*

*Open the vagrant file (should be in the directory where you specified to create a new vagrant machine).

*Search for config.vm.network. If you didn't setup the file earlier, it should be commented.

*Change it to look something like this config.vm.network "private_network", ip: "55.55.55.5". Here ip address (55.55.55.5) can be any ip address you want.

*Now logout from the vagrant machine and reload your vagrant machine by this command vagrant reload.

*Again ssh to your vagrant machine and restart your django server by this command python manage.py runserver 0.0.0.0:80. Again the port address (80) can be 8000 if you want so.

*After that, in your browser, enter the following address 55.55.55.5, and hopefully you should see your webapp.

Now if you would like to go further, you can edit your host file, and add this line
55.55.55.5 mynewdomain.com

Then in your browser, enter the follow address,
mynewdomain.com

And you should see your web app. Note that, www is not added in the domain name inside the host file, so only mynewdomain.com can be accessed. You can however add it.
Hope this helps. Cheers.

A: Complementing @Kakar answer, this configuration can also be done using this:
config.vm.network "private_network", type: "dhcp"
This will assign an IP automatically.
For further reading: https://www.vagrantup.com/docs/networking/private_network.html


text:
Q: REST POST API with path params vs query params I have an API to be designed, this one require only one parameter then to be inserted into DB.
So POST is the verb, but my doubt is on the parameter that will be passed as query param or path param ?
@RequestMapping(value = "/users-access/{userId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation("Promotes user access")
public boolean promoteUserAccess(@PathVariable String userId)
        throws BadRequestException, UnAuthorizedException {
      //actions
}

What's the best practices ? thanks !

A: You should send your data in the request body like below.
@RequestMapping(value = "/users", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation("Promotes user access")
public boolean promoteUserAccess(@RequestBody Request request)
        throws BadRequestException, UnAuthorizedException {
      //actions
}

public class Request {

  private String userId;

}

A: If the parameter is meant to refer a resource then use path param.
If the parameter is meant to filter the resource then use query param.
In your case, the userId refers to resource so you should use it as path param.
Generally,query param is used in GET requests to sort/filter the resources. Ex:
GET/users?id=5


text:
Q: Bidirectional gRPC stream sometimes stops processing responses after stopping and starting In short
We have a mobile app that streams fairly high volumes of data to and from a server through various bidirectional streams. The streams need to be closed on occasion (for example when the app is backgrounded). They are then reopened as needed. Sometimes when this happens, something goes wrong:

*

*From what I can tell, the stream is up and running on the device's side (the status of both the GRPCProtocall and the GRXWriter involved is either started or paused)

*The device sends data on the stream fine (the server receives the data)

*The server seems to send data back to the device fine (the server's Stream.Send calls return as successful)

*On the device, the result handler for data received on the stream is never called

More detail
Our code is heavily simplified below, but this should hopefully provide enough detail to indicate what we're doing. A bidirection stream is managed by a Switch class:
class Switch {
    /** The protocall over which we send and receive data */
    var protocall: GRPCProtoCall?

    /** The writer object that writes data to the protocall. */
    var writer: GRXBufferedPipe?

    /** A static GRPCProtoService as per the .proto */
    static let service = APPDataService(host: Settings.grpcHost)

    /** A response handler. APPData is the datatype defined by the .proto. */
    func rpcResponse(done: Bool, response: APPData?, error: Error?) {
        NSLog("Response received")
        // Handle response...
    }

    func start() {
        // Create a (new) instance of the writer
        // (A writer cannot be used on multiple protocalls)
        self.writer = GRXBufferedPipe()

        // Setup the protocall
        self.protocall = Switch.service.rpcToStream(withRequestWriter: self.writer!, eventHandler: self.rpcRespose(done:response:error:))

        // Start the stream
        self.protocall.start()
    }

    func stop() {
        // Stop the writer if it is started.
        if self.writer.state == .started || self.writer.state == .paused {
            self.writer.finishWithError(nil)
        }

        // Stop the proto call if it is started
        if self.protocall?.state == .started || self.protocall?.state == .paused {
            protocall?.cancel()
        }
        self.protocall = nil
    }

    private var needsRestart: Bool {
        if let protocall = self.protocall {
            if protocall.state == .notStarted || protocall.state == .finished {
                // protocall exists, but isn't running.
                return true
            } else if writer.state == .notStarted || writer.state == .finished {
                // writer isn't running
                return true
            } else {
                // protocall and writer are running
                return false
            }
        } else {
            // protocall doesn't exist.
            return true
        }
    }

    func restartIfNeeded() {
        guard self.needsRestart else { return }
        self.stop()
        self.start()
    }

    func write(data: APPData) {
        self.writer.writeValue(data)
    }
}

Like I said, heavily simplified, but it shows how we start, stop, and restart streams, and how we check whether a stream is healthy.
When the app is backgrounded, we call stop(). When it is foregrounded and we need the stream again, we call start(). And we periodically call restartIfNeeded(), eg. when screens that use the stream come into view.
As I mentioned above, what happens occasionally is that our response handler (rpcResponse) stops getting called when server writes data to the stream. The stream appears to be healthy (server receives the data we write to it, and protocall.state is neither .notStarted nor .finished). But not even the log on the first line of the response handler is executed.
First question: Are we managing the streams correctly, or is our way of stopping and restarting streams prone to errors? If so, what is the correct way of doing something like this?
Second question: How do we debug this? Everything we could think of that we can query for a status tells us that the stream is up and running, but it feels like the objc gRPC library keeps a lot of its mechanics hidden from us. Is there a way to see whether responses from server may do reach us, but fail to trigger our response handler?
Third question: As per the code above, we use the GRXBufferedPipe provided by the library. Its documentation advises against using it in production because it doesn't have a push-back mechanism. To our understanding, the writer is only used to feed data to the gRPC core in a synchronised, one-at-a-time fashion, and since server receives data from us fine, we don't think this is an issue. Are we wrong though? Is the writer also involved in feeding data received from server to our response handler? I.e. if the writer broke due to overload, could that manifest as a problem reading data from the stream, rather than writing to it?
UPDATE: Over a year after asking this, we have finally found a deadlock bug in our server-side code that was causing this behaviour on client-side. The streams appeared to hang because no communication sent by the client was handled by server, and vice-versa, but the streams were actually alive and well. The accepted answer provides good advice for how to manage these bi-directional streams, which I believe is still valuable (it helped us a lot!). But the issue was actually due to a programming error.
Also, for anyone running into this type of issue, it might be worth investigating whether you're experiencing this known issue where a channel gets silently dropped when iOS changes its network. This readme provides instructions for using Apple's CFStream API rather than TCP sockets as a possible fix for that issue.

A:
First question: Are we managing the streams correctly, or is our way of stopping and restarting streams prone to errors? If so, what is the correct way of doing something like this?

From what I can tell by looking at your code, the start() function seems to be right. In the stop() function, you do not need to call cancel() of self.protocall; the call will be finished with the previous self.writer.finishWithError(nil).
needsrestart() is where it gets a bit messy. First, you are not supposed to poll/set the state of protocall yourself. That state is altered by itself. Second, setting those state does not close your stream. It only pause a writer, and if app is in background, pausing a writer is like a no-op. If you want to close a stream, you should use finishWithError to terminate this call, and maybe start a new call later when needed.

Second question: How do we debug this?

One way is to turn on gRPC log (GRPC_TRACE and GRPC_VERBOSITY). Another way is to set breakpoint at here where gRPC objc library receives a gRPC message from the server.

Third question: Is the writer also involved in feeding data received from server to our response handler?

No. If you create a buffered pipe and feed that as request of your call, it only feed data to be sent to server. The receiving path is handled by another writer (which is in fact your protocall object).
I don't see where the usage of GRXBufferedPipe in production is discouraged. The known drawback about this utility is that if you pause the writer but keep writing data to it with writeWithValue, you end up buffering a lot of data without being able to flush them, which may cause memory issue.


text:
Q: Why is the induced representation a vector space of functions determined by coset values? I have been studying the induced representation of a finite group, in particular the form given by the following definition:
Given an $H$ representation, $(\mu, W)$,
$Ind_H^GW$ $= \{f:G \rightarrow W | f(gh) = \mu(h^{-1})f(g)$ $ \forall g \in G, h \in H \}$ .
I am told that it follows from this that every element of the induced representation is determined by the values it takes on the cosets of H in G, so that the induced representation has dimension $[G:H] dim(W)$. I am struggling to see how these functions are determined by their values on the cosets and would appreciate some help with this.

A: Well if $g\in g_iH$ then there is some $h$ such that $g= g_ih$ and so $f(g) = f(g_ih) = \mu(h^{-1})f(g_i)$.
This means that if $\displaystyle\bigsqcup_{i\in I} g_iH$ is a coset decomposition of $G$, and if $f$ and $f'$ coincide on the $g_i$'s then they coincide on all of $G$.
Using the same notations as above, this gives a linear isomorphism $$f\mapsto (f(g_i))_{i\in I}$$ which yields the desired dimension


text:
Q: .NetCore + Angular + Azure: Deployment I created a Web Api Asp.Net Core Project in server folder and an Angular-Cli Project in client folder.
In local:

*

*I launch the WebAPI with IIS Express and my angular project with
ng serve --proxy-config proxy.config.json*.

*In my Angular App, in environments/environment.ts, to be able to get the ApiUrl using environment.apiUrl (proxy doesnt work for websocket used with SignalR), I added a new parameter:
apiUrl: "http://localhost:49402/"

*File structure:

My project is available on git too:
https://github.com/ranouf/AspNetCore-SignalR/
On Azure:

*

*I created a new WebApp,

*I configured the deployment options, each time master is modified, the Web App is deployed which works well for my WebApi.
Problem:
How to deploy my Angular App in the Web App on Azure?
My thinking:
I added a post build command which will build my angular app in the wwwroot folder only in release mode. This solution works in local but doesnt work on Azure:
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<PostBuildEvent>
  cd "$(MSBuildProjectDirectory)/../../client"
  npm install
  npm run build
</PostBuildEvent>
</PropertyGroup>

And in startup.cs, I added
app.UseDefaultFiles();
app.UseStaticFiles();

Constraint:
I have to separate my 2 projects in Local, I can't use the webpack microsoft angular template.
Thanks for your help.
Cedric

Edit
So I m still working on it.
It s really hard to debug and understand what s happening on Azure Portal. The log on Deployment doesnt give the build output.

My new pre build command is :
echo "$(ProjectDir)..\..\client"
cd $(ProjectDir)..\..\client
echo "npm install"
npm install
echo "ng build"
ng build --env=prod --prod --output-path=$(ProjectDir)

But still, nothing is copied in the server folder ...
Please, can you share your thinking? How can I deploy my angular App using Deployment Option in Azure portal?

Edit 2
So, I saw no solution online, and no one answer here too, so what I want to do first seems to not be possible.
I try something else, the kudu deployment script. You need to add two file:

*

*.deployment with this lines inside:
[config]
command = deploy.cmd

*deploy.cmd:
@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Setup
:: -----
setlocal enabledelayedexpansion

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%ARTIFACTS%\repository
)

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------
echo Source: %DEPLOYMENT_SOURCE%...
echo Deployment: in %DEPLOYMENT_TARGET%...

echo Server off
touch %DEPLOYMENT_TARGET%\App_Offline.htm

pushd "%DEPLOYMENT_SOURCE%\src\client"
echo npm install --production
call :ExecuteCmd npm install --production
IF !ERRORLEVEL! NEQ 0 goto error

echo Deploy client
call :ExecuteCmd npm run build-azure
IF !ERRORLEVEL! NEQ 0 goto error
popd

echo Deploy API
call :ExecuteCmd dotnet publish src\server\AspNetCore-SignalR.Api\ -o %DEPLOYMENT_TARGET%
IF !ERRORLEVEL! NEQ 0 goto error

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: End
:: ---
IF !ERRORLEVEL! NEQ 0 goto error

goto end

:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

:exitSetErrorLevel
exit /b 1

:exitFromFunction
()

:end
endlocal
echo Finished successfully.

There is 2 good points:

*

*the deployment succeded

*all the files (DotNet Core publish + Angular publish) are in wwwroot

There is 1 BIG problem:

*

*I can access to the API using swagger (www.website.com/swagger) but the angular App is not available (error 404 on www.webiste.com)

*If I remove the web.config, the Angular App is now available, but not swagger or the API anymore.

How to make understand to the web.config that I want both work Angular App and Swagger?

A: I found the solution! It was hard, I tried many things even the Kudu Deploy script:

*

*https://github.com/ranouf/AspNetCore-SignalR/blob/0a648617eafd77be6c8e057160c2a66f2ee266b8/.deployment.old

*https://github.com/ranouf/AspNetCore-SignalR/blob/0a648617eafd77be6c8e057160c2a66f2ee266b8/deploy.cmd.old2
(for those who could be interested to see how to do that).
But finally, I choose the (maybe) easiest solution, the PreBuildEvent command.
In my csproj:
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
  <PreBuildEvent>
    cd "$(MSBuildProjectDirectory)/../../client"
    npm install
  </PreBuildEvent>
  <PostBuildEvent>
    cd "$(MSBuildProjectDirectory)/../../client"
    npm run build-azure
  </PostBuildEvent>
</PropertyGroup>

In Package.json:
"build": "ng build --env=prod --prod --output-path=../server/AspNetCore-SignalR.Api/wwwroot/",
"build-azure": "ng build --env=prod --prod --output-path=D:/home/site/wwwroot/wwwroot/",

The main things to know is when you want to deploy an Angular App, you need to do it in wwwroot folder.
In Azure, the .Net app is deployed in D:/home/site/wwwroot/. My mistake was to think that I have to deploy my angular app there too. The good thing to do is to deploy it in D:/home/site/wwwroot/wwwroot.
I hope, my work will help people too. If you have any recommendations to improve the process and reinforce the security, please let met know.


text:
Q: Dropping a nested column from Spark DataFrame I have a DataFrame with the schema
root
 |-- label: string (nullable = true)
 |-- features: struct (nullable = true)
 |    |-- feat1: string (nullable = true)
 |    |-- feat2: string (nullable = true)
 |    |-- feat3: string (nullable = true)

While, I am able to filter the data frame using
  val data = rawData
     .filter( !(rawData("features.feat1") <=> "100") )

I am unable to drop the columns using
  val data = rawData
       .drop("features.feat1")

Is it something that I am doing wrong here? I also tried (unsuccessfully) doing drop(rawData("features.feat1")), though it does not make much sense to do so.
Thanks in advance,
Nikhil

A: Expanding on spektom answer. With support for array types:
object DataFrameUtils {

  private def dropSubColumn(col: Column, colType: DataType, fullColName: String, dropColName: String): Option[Column] = {
    if (fullColName.equals(dropColName)) {
      None
    } else if (dropColName.startsWith(s"$fullColName.")) {
      colType match {
        case colType: StructType =>
          Some(struct(
            colType.fields
              .flatMap(f =>
                dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                  case Some(x) => Some(x.alias(f.name))
                  case None => None
                })
              : _*))
        case colType: ArrayType =>
          colType.elementType match {
            case innerType: StructType =>
              Some(struct(innerType.fields
                .flatMap(f =>
                  dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                  })
                : _*))
          }

        case other => Some(col)
      }
    } else {
      Some(col)
    }
  }

  protected def dropColumn(df: DataFrame, colName: String): DataFrame = {
    df.schema.fields
      .flatMap(f => {
        if (colName.startsWith(s"${f.name}.")) {
          dropSubColumn(col(f.name), f.dataType, f.name, colName) match {
            case Some(x) => Some((f.name, x))
            case None => None
          }
        } else {
          None
        }
      })
      .foldLeft(df.drop(colName)) {
        case (df, (colName, column)) => df.withColumn(colName, column)
      }
  }

  /**
    * Extended version of DataFrame that allows to operate on nested fields
    */
  implicit class ExtendedDataFrame(df: DataFrame) extends Serializable {
    /**
      * Drops nested field from DataFrame
      *
      * @param colName Dot-separated nested field name
      */
    def dropNestedColumn(colName: String): DataFrame = {
      DataFrameUtils.dropColumn(df, colName)
    }
  }

}

A: I will expand upon mmendez.semantic's answer here, and accounting for the issues described in the sub-thread.
  def dropSubColumn(col: Column, colType: DataType, fullColName: String, dropColName: String): Option[Column] = {
    if (fullColName.equals(dropColName)) {
      None
    } else if (dropColName.startsWith(s"$fullColName.")) {
      colType match {
        case colType: StructType =>
          Some(struct(
            colType.fields
                .flatMap(f =>
                  dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                  })
                : _*))
        case colType: ArrayType =>
          colType.elementType match {
            case innerType: StructType =>
              // we are potentially dropping a column from within a struct, that is itself inside an array
              // Spark has some very strange behavior in this case, which they insist is not a bug
              // see https://issues.apache.org/jira/browse/SPARK-31779 and associated comments
              // and also the thread here: https://stackoverflow.com/a/39943812/375670
              // this is a workaround for that behavior

              // first, get all struct fields
              val innerFields = innerType.fields
              // next, create a new type for all the struct fields EXCEPT the column that is to be dropped
              // we will need this later
              val preserveNamesStruct = ArrayType(StructType(
                innerFields.filterNot(f => s"$fullColName.${f.name}".equals(dropColName))
              ))
              // next, apply dropSubColumn recursively to build up the new values after dropping the column
              val filteredInnerFields = innerFields.flatMap(f =>
                dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                }
              )
              // finally, use arrays_zip to unwrap the arrays that were introduced by building up the new. filtered
              // struct in this way (see comments in SPARK-31779), and then cast to the StructType we created earlier
              // to get the original names back
              Some(arrays_zip(filteredInnerFields:_*).cast(preserveNamesStruct))
          }

        case _ => Some(col)
      }
    } else {
      Some(col)
    }
  }

  def dropColumn(df: DataFrame, colName: String): DataFrame = {
    df.schema.fields.flatMap(f => {
      if (colName.startsWith(s"${f.name}.")) {
        dropSubColumn(col(f.name), f.dataType, f.name, colName) match {
          case Some(x) => Some((f.name, x))
          case None => None
        }
      } else {
        None
      }
    }).foldLeft(df.drop(colName)) {
      case (df, (colName, column)) => df.withColumn(colName, column)
    }
  }

Usage in spark-shell:
// if defining the functions above in your spark-shell session, you first need imports
import org.apache.spark.sql._
import org.apache.spark.sql.types._

// now you can paste the function definitions

// create a deeply nested and complex JSON structure
val jsonData = """{
      "foo": "bar",
      "top": {
        "child1": 5,
        "child2": [
          {
            "child2First": "one",
            "child2Second": 2,
            "child2Third": -19.51
          }
        ],
        "child3": ["foo", "bar", "baz"],
        "child4": [
          {
            "child2First": "two",
            "child2Second": 3,
            "child2Third": 16.78
          }
        ]
      }
    }"""

// read it into a DataFrame
val df = spark.read.option("multiline", "true").json(Seq(jsonData).toDS())

// remove a sub-column
val modifiedDf = dropColumn(df, "top.child2.child2First")

modifiedDf.printSchema
root
 |-- foo: string (nullable = true)
 |-- top: struct (nullable = false)
 |    |-- child1: long (nullable = true)
 |    |-- child2: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- child2Second: long (nullable = true)
 |    |    |    |-- child2Third: double (nullable = true)
 |    |-- child3: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |    |-- child4: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- child2First: string (nullable = true)
 |    |    |    |-- child2Second: long (nullable = true)
 |    |    |    |-- child2Third: double (nullable = true)

modifiedDf.show(truncate=false)
+---+------------------------------------------------------+
|foo|top                                                   |
+---+------------------------------------------------------+
|bar|[5, [[2, -19.51]], [foo, bar, baz], [[two, 3, 16.78]]]|
+---+------------------------------------------------------+

A: For Spark 3.1+, you can use method dropFields on struct type columns:

An expression that drops fields in StructType by name. This is a no-op
if schema doesn't contain field name(s).

val df = sql("SELECT named_struct('feat1', 1, 'feat2', 2, 'feat3', 3) features")

val df1 = df.withColumn("features", $"features".dropFields("feat1"))

A: Another (PySpark) way would be to drop the features.feat1 column by creating features again:
from pyspark.sql.functions import col, arrays_zip

display(df
        .withColumn("features", arrays_zip("features.feat2", "features.feat3"))
        .withColumn("features", col("features").cast(schema))
)

Where schema is the new schema (excluding features.feat1).
from pyspark.sql.types import StructType, StructField, StringType

schema = StructType(
    [
      StructField('feat2', StringType(), True),
      StructField('feat3', StringType(), True),
    ]
  )

A: It is just a programming exercise but you can try something like this:
import org.apache.spark.sql.{DataFrame, Column}
import org.apache.spark.sql.types.{StructType, StructField}
import org.apache.spark.sql.{functions => f}
import scala.util.Try

case class DFWithDropFrom(df: DataFrame) {
  def getSourceField(source: String): Try[StructField] = {
    Try(df.schema.fields.filter(_.name == source).head)
  }

  def getType(sourceField: StructField): Try[StructType] = {
    Try(sourceField.dataType.asInstanceOf[StructType])
  }

  def genOutputCol(names: Array[String], source: String): Column = {
    f.struct(names.map(x => f.col(source).getItem(x).alias(x)): _*)
  }

  def dropFrom(source: String, toDrop: Array[String]): DataFrame = {
    getSourceField(source)
      .flatMap(getType)
      .map(_.fieldNames.diff(toDrop))
      .map(genOutputCol(_, source))
      .map(df.withColumn(source, _))
      .getOrElse(df)
  }
}

Example usage:
scala> case class features(feat1: String, feat2: String, feat3: String)
defined class features

scala> case class record(label: String, features: features)
defined class record

scala> val df = sc.parallelize(Seq(record("a_label",  features("f1", "f2", "f3")))).toDF
df: org.apache.spark.sql.DataFrame = [label: string, features: struct<feat1:string,feat2:string,feat3:string>]

scala> DFWithDropFrom(df).dropFrom("features", Array("feat1")).show
+-------+--------+
|  label|features|
+-------+--------+
|a_label| [f2,f3]|
+-------+--------+

scala> DFWithDropFrom(df).dropFrom("foobar", Array("feat1")).show
+-------+----------+
|  label|  features|
+-------+----------+
|a_label|[f1,f2,f3]|
+-------+----------+

scala> DFWithDropFrom(df).dropFrom("features", Array("foobar")).show
+-------+----------+
|  label|  features|
+-------+----------+
|a_label|[f1,f2,f3]|
+-------+----------+

Add an implicit conversion and you're good to go.

A: This version allows you to remove nested columns at any level:
import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{StructType, DataType}

/**
  * Various Spark utilities and extensions of DataFrame
  */
object DataFrameUtils {

  private def dropSubColumn(col: Column, colType: DataType, fullColName: String, dropColName: String): Option[Column] = {
    if (fullColName.equals(dropColName)) {
      None
    } else {
      colType match {
        case colType: StructType =>
          if (dropColName.startsWith(s"${fullColName}.")) {
            Some(struct(
              colType.fields
                .flatMap(f =>
                  dropSubColumn(col.getField(f.name), f.dataType, s"${fullColName}.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                  })
                : _*))
          } else {
            Some(col)
          }
        case other => Some(col)
      }
    }
  }

  protected def dropColumn(df: DataFrame, colName: String): DataFrame = {
    df.schema.fields
      .flatMap(f => {
        if (colName.startsWith(s"${f.name}.")) {
          dropSubColumn(col(f.name), f.dataType, f.name, colName) match {
            case Some(x) => Some((f.name, x))
            case None => None
          }
        } else {
          None
        }
      })
      .foldLeft(df.drop(colName)) {
        case (df, (colName, column)) => df.withColumn(colName, column)
      }
  }

  /**
    * Extended version of DataFrame that allows to operate on nested fields
    */
  implicit class ExtendedDataFrame(df: DataFrame) extends Serializable {
    /**
      * Drops nested field from DataFrame
      *
      * @param colName Dot-separated nested field name
      */
    def dropNestedColumn(colName: String): DataFrame = {
      DataFrameUtils.dropColumn(df, colName)
    }
  }
}

Usage:
import DataFrameUtils._
df.dropNestedColumn("a.b.c.d")

A: Following spektom's code snippet for scala, I've created a similar code in Java.
Since java 8 doesn't have foldLeft, I used forEachOrdered. This code is suitable for spark 2.x (I'm using 2.1)
Also I noted that dropping a column and adding it using withColumn with the same name doesn't work, so I'm just replacing the column, and it seem to work.
Code is not fully tested, hope it works :-)
public class DataFrameUtils {

public static Dataset<Row> dropNestedColumn(Dataset<Row> dataFrame, String columnName) {
    final DataFrameFolder dataFrameFolder = new DataFrameFolder(dataFrame);
    Arrays.stream(dataFrame.schema().fields())
        .flatMap( f -> {
           if (columnName.startsWith(f.name() + ".")) {
               final Optional<Column> column = dropSubColumn(col(f.name()), f.dataType(), f.name(), columnName);
               if (column.isPresent()) {
                   return Stream.of(new Tuple2<>(f.name(), column));
               } else {
                   return Stream.empty();
               }
           } else {
               return Stream.empty();
           }
        }).forEachOrdered(colTuple -> dataFrameFolder.accept(colTuple));

    return dataFrameFolder.getDF();
}

private static Optional<Column> dropSubColumn(Column col, DataType colType, String fullColumnName, String dropColumnName) {
    Optional<Column> column = Optional.empty();
    if (!fullColumnName.equals(dropColumnName)) {
        if (colType instanceof StructType) {
            if (dropColumnName.startsWith(fullColumnName + ".")) {
                column = Optional.of(struct(getColumns(col, (StructType)colType, fullColumnName, dropColumnName)));
            }
        } else {
            column = Optional.of(col);
        }
    }

    return column;
}

private static Column[] getColumns(Column col, StructType colType, String fullColumnName, String dropColumnName) {
    return Arrays.stream(colType.fields())
        .flatMap(f -> {
                    final Optional<Column> column = dropSubColumn(col.getField(f.name()), f.dataType(),
                            fullColumnName + "." + f.name(), dropColumnName);
                    if (column.isPresent()) {
                        return Stream.of(column.get().alias(f.name()));
                    } else {
                        return Stream.empty();
                    }
                }
        ).toArray(Column[]::new);

}

private static class DataFrameFolder implements Consumer<Tuple2<String, Optional<Column>>> {
    private Dataset<Row> df;

    public DataFrameFolder(Dataset<Row> df) {
        this.df = df;
    }

    public Dataset<Row> getDF() {
        return df;
    }

    @Override
    public void accept(Tuple2<String, Optional<Column>> colTuple) {
        if (!colTuple._2().isPresent()) {
            df = df.drop(colTuple._1());
        } else {
            df = df.withColumn(colTuple._1(), colTuple._2().get());
        }
    }
}

Usage example:
private class Pojo {
    private String str;
    private Integer number;
    private List<String> strList;
    private Pojo2 pojo2;

    public String getStr() {
        return str;
    }

    public Integer getNumber() {
        return number;
    }

    public List<String> getStrList() {
        return strList;
    }

    public Pojo2 getPojo2() {
        return pojo2;
    }

}

private class Pojo2 {
    private String str;
    private Integer number;
    private List<String> strList;

    public String getStr() {
        return str;
    }

    public Integer getNumber() {
        return number;
    }

    public List<String> getStrList() {
        return strList;
    }

}

SQLContext context = new SQLContext(new SparkContext("local[1]", "test"));
Dataset<Row> df = context.createDataFrame(Collections.emptyList(), Pojo.class);
Dataset<Row> dfRes = DataFrameUtils.dropNestedColumn(df, "pojo2.str");

Original struct:
root
 |-- number: integer (nullable = true)
 |-- pojo2: struct (nullable = true)
 |    |-- number: integer (nullable = true)
 |    |-- str: string (nullable = true)
 |    |-- strList: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |-- str: string (nullable = true)
 |-- strList: array (nullable = true)
 |    |-- element: string (containsNull = true)

After drop:
root
 |-- number: integer (nullable = true)
 |-- pojo2: struct (nullable = false)
 |    |-- number: integer (nullable = true)
 |    |-- strList: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |-- str: string (nullable = true)
 |-- strList: array (nullable = true)
 |    |-- element: string (containsNull = true)

A: PySpark implementation
import pyspark.sql.functions as sf

def _drop_nested_field(
    schema: StructType,
    field_to_drop: str,
    parents: List[str] = None,
) -> Column:
    parents = list() if parents is None else parents
    src_col = lambda field_names: sf.col('.'.join(f'`{c}`' for c in field_names))

    if '.' in field_to_drop:
        root, subfield = field_to_drop.split('.', maxsplit=1)
        field_to_drop_from = next(f for f in schema.fields if f.name == root)

        return sf.struct(
            *[src_col(parents + [f.name]) for f in schema.fields if f.name != root],
            _drop_nested_field(
                schema=field_to_drop_from.dataType,
                field_to_drop=subfield,
                parents=parents + [root]
            ).alias(root)
        )

    else:
        # select all columns except the one to drop
        return sf.struct(
            *[src_col(parents + [f.name])for f in schema.fields if f.name != field_to_drop],
        )

def drop_nested_field(
    df: DataFrame,
    field_to_drop: str,
) -> DataFrame:
    if '.' in field_to_drop:
        root, subfield = field_to_drop.split('.', maxsplit=1)
        field_to_drop_from = next(f for f in df.schema.fields if f.name == root)

        return df.withColumn(root, _drop_nested_field(
            schema=field_to_drop_from.dataType,
            field_to_drop=subfield,
            parents=[root]
        ))
    else:
        return df.drop(field_to_drop)

df = drop_nested_field(df, 'a.b.c.d')

A: Adding the java version Solution for this.
Utility Class(Pass your dataset and the nested column which has to be dropped to dropNestedColumn function).
(There are few bugs in Lior Chaga's answer, I have corrected them while I tried to use his answer).
public class NestedColumnActions {
/*
dataset : dataset in which we want to drop columns
columnName : nested column that needs to be deleted
*/
public static Dataset<?> dropNestedColumn(Dataset<?> dataset, String columnName) {

    //Special case of top level column deletion
    if(!columnName.contains("."))
        return dataset.drop(columnName);

    final DataSetModifier dataFrameFolder = new DataSetModifier(dataset);
    Arrays.stream(dataset.schema().fields())
            .flatMap(f -> {
                //If the column name to be deleted starts with current top level column
                if (columnName.startsWith(f.name() + DOT)) {
                    //Get new column structure under f , expected after deleting the required column
                    final Optional<Column> column = dropSubColumn(functions.col(f.name()), f.dataType(), f.name(), columnName);
                    if (column.isPresent()) {
                        return Stream.of(new Tuple2<>(f.name(), column));
                    } else {
                        return Stream.empty();
                    }
                } else {
                    return Stream.empty();
                }
            })
            //Call accept function with Tuples of (top level column name, new column structure under it)
            .forEach(colTuple -> dataFrameFolder.accept(colTuple));

    return dataFrameFolder.getDataset();
}

private static Optional<Column> dropSubColumn(Column col, DataType colType, String fullColumnName, String dropColumnName) {
    Optional<Column> column = Optional.empty();
    if (!fullColumnName.equals(dropColumnName)) {
        if (colType instanceof StructType) {
            if (dropColumnName.startsWith(fullColumnName + DOT)) {
                column = Optional.of(functions.struct(getColumns(col, (StructType) colType, fullColumnName, dropColumnName)));
            }
            else {
                column = Optional.of(col);
            }
        } else {
            column = Optional.of(col);
        }
    }

    return column;
}

private static Column[] getColumns(Column col, StructType colType, String fullColumnName, String dropColumnName) {
    return Arrays.stream(colType.fields())
            .flatMap(f -> {
                        final Optional<Column> column = dropSubColumn(col.getField(f.name()), f.dataType(),
                                fullColumnName + "." + f.name(), dropColumnName);
                        if (column.isPresent()) {
                            return Stream.of(column.get().alias(f.name()));
                        } else {
                            return Stream.empty();
                        }
                    }
            ).toArray(Column[]::new);

}

private static class DataSetModifier implements Consumer<Tuple2<String, Optional<Column>>> {
    private Dataset<?> df;

    public DataSetModifier(Dataset<?> df) {
        this.df = df;
    }

    public Dataset<?> getDataset() {
        return df;
    }

    /*
    colTuple[0]:top level column name
    colTuple[1]:new column structure under it
   */
    @Override
    public void accept(Tuple2<String, Optional<Column>> colTuple) {
        if (!colTuple._2().isPresent()) {
            df = df.drop(colTuple._1());
        } else {
            df = df.withColumn(colTuple._1(), colTuple._2().get());
        }
    }
}

}

A: The Make Structs Easy* library makes it easy to perform operations like adding, dropping, and renaming fields inside nested data structures. The library is available in both Scala and Python.
Assuming you have the following data:
import org.apache.spark.sql.functions._

case class Features(feat1: String, feat2: String, feat3: String)
case class Record(features: Features, arrayOfFeatures: Seq[Features])

val df = Seq(
   Record(Features("hello", "world", "!"), Seq(Features("red", "orange", "yellow"), Features("green", "blue", "indigo")))
).toDF

df.printSchema

// root
//  |-- features: struct (nullable = true)
//  |    |-- feat1: string (nullable = true)
//  |    |-- feat2: string (nullable = true)
//  |    |-- feat3: string (nullable = true)
//  |-- arrayOfFeatures: array (nullable = true)
//  |    |-- element: struct (containsNull = true)
//  |    |    |-- feat1: string (nullable = true)
//  |    |    |-- feat2: string (nullable = true)
//  |    |    |-- feat3: string (nullable = true)

df.show(false)

// +-----------------+----------------------------------------------+
// |features         |arrayOfFeatures                               |
// +-----------------+----------------------------------------------+
// |[hello, world, !]|[[red, orange, yellow], [green, blue, indigo]]|
// +-----------------+----------------------------------------------+

Then dropping feat2 from features is as simple as:
import com.github.fqaiser94.mse.methods._

// drop feat2 from features
df.withColumn("features", $"features".dropFields("feat2")).show(false)

// +----------+----------------------------------------------+
// |features  |arrayOfFeatures                               |
// +----------+----------------------------------------------+
// |[hello, !]|[[red, orange, yellow], [green, blue, indigo]]|
// +----------+----------------------------------------------+

I noticed there were a lot of follow-up comments on other solutions asking if there's a way to drop a Column nested inside a struct nested inside of an array. This can be done by combining the functions provided by the Make Structs Easy library with the functions provided by spark-hofs library, as follows:
import za.co.absa.spark.hofs._

// drop feat2 in each element of arrayOfFeatures
df.withColumn("arrayOfFeatures", transform($"arrayOfFeatures", features => features.dropFields("feat2"))).show(false)

// +-----------------+--------------------------------+
// |features         |arrayOfFeatures                 |
// +-----------------+--------------------------------+
// |[hello, world, !]|[[red, yellow], [green, indigo]]|
// +-----------------+--------------------------------+

*Full disclosure: I am the author of the Make Structs Easy library that is referenced in this answer.

A: With Spark 3.1+, short and effective:
object DatasetOps {
  implicit class DatasetOps[T](val dataset: Dataset[T]) {
    def dropFields(fieldNames: String*): DataFrame =
      fieldNames.foldLeft(dataset.toDF()) { (dataset, fieldName) =>
        val subFieldRegex = "(\\w+)\\.(.+)".r
        fieldName match {
          case subFieldRegex(columnName, subFieldPath) =>
            dataset.withColumn(columnName, col(columnName).dropFields(subFieldPath))
          case _ => dataset.drop(fieldName)
        }
      }
  }
}

This also preserves the required or not boolean in the schema.
Usage:
dataset.dropFields("some_column", "some_struct.some_sub_field.some_field")


text:
Q: Не индексируются страницы Почему-то вхожу, смотрю статистику в яндекс вебмастере, там написано, что страниц в поиске 1, и в поиск почему-то попадает только главная страничка( Кто-нибудь знает из-за чего это может быть?
A: Причины могут быть разные. Из самых очевидных:

*

*сайт новый и бот еще просто не успел проиндескировать новые страницы,

*robots.txt запрещает индексирование сайта,

*на главной странице сайта нет ссылок на другие страницы, по которым бот может их найти,


text:
Q: Which path for the Modelsim environment variable in order to run and use all modelsim commands like vcom, vsim etc. which enivronment variables are set in a windows system when NOT using the GUI to run those commands?

A: You need to put the binary path into PATH or call all commands with absolute paths.


text:
Q: Discover the return type of the current function in go I have a function that is being generated using reflection and reflect.MakeFunc, so I don't actually have the return type until runtime.
Inside the template function that MakeFunc is using, is there a way to determine the return type of the concrete function being templated?
Essentially, is there a way to determine the return type iof the currently executing function at runtime?
I know about the Out method:
fn.Type().Out(0)

And I can find the return type of a function easily enough?
But is there a way to find the return type of the currently executing function (as opposed to an explicit passed function reference).

A: You should check fn.Type().Out(0).Kind(), for example:
func main() {
    fnTmpl := func(in []reflect.Value) []reflect.Value {
        return []reflect.Value{in[0]}
    }
    makeFn := func(fptr interface{}) {
        fn := reflect.ValueOf(fptr).Elem()
        fn.Set(reflect.MakeFunc(fn.Type(), fnTmpl))
    }
    var nFn func(int) int
    makeFn(&nFn)
    kind := reflect.TypeOf(nFn).Out(0).Kind()
    switch kind {
    case reflect.Int:
        fmt.Println("int")

    }
}

A: In the case you are talking about, the return type of the currently executing function is always []reflect.Type (because that is what a function passed to reflect.MakeFunc must return). What you really want is the return type of the reflect.makeFuncStub function that called your function.
There is no way to get that (except perhaps some strange inspection of the call stack), but you can make an enhanced version of MakeFunc that provides the information:
package main

import (
    "fmt"
    "reflect"
)

// MakeFunc is like reflect.MakeFunc, but fn has an extra argument, retType, which
// is passed the desired return type.
func MakeFunc(typ reflect.Type, fn func(args []reflect.Value, retType reflect.Type) (results []reflect.Value)) reflect.Value {
    if n := typ.NumOut(); n != 1 {
        panic("wrong number of return values")
    }
    rt := typ.Out(0)
    return reflect.MakeFunc(typ, func(args []reflect.Value) (results []reflect.Value) {
        return fn(args, rt)
    })
}

func makeReturnOne(fptr interface{}) {
    fn := reflect.ValueOf(fptr).Elem()
    fn.Set(MakeFunc(fn.Type(), returnOne))
}

func returnOne(args []reflect.Value, retType reflect.Type) []reflect.Value {
    ret := reflect.New(retType).Elem()
    switch retType.Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        ret.SetInt(1)
    case reflect.Float32, reflect.Float64:
        ret.SetFloat(1.0)
    default:
        panic("returnOne only supports int and float types")
    }
    r := ret.Interface()
    fmt.Printf("returning %v as %T\n", r, r)
    return []reflect.Value{ret}
}

func main() {
    var r1f func() float64
    var r1i func() int
    makeReturnOne(&r1f)
    makeReturnOne(&r1i)
    fmt.Println(r1f())
    fmt.Println(r1i())
}

A: I might have misinterpreted what you are trying to achieve, but why not just take the kind of the value you are returning? Modifying OneOfOne's example as follows:
fnTmpl := func(in []reflect.Value) (res []reflect.Value) {
    res = []reflect.Value{in[0]}
    fmt.Println("Returned:", res[0].Kind())
    return res
}

Playground: http://play.golang.org/p/EujmxyGRrI


text:
Q: Is the Digit-Matrix in Cantors' Diagonal Argument square-shaped? It seems to me that the Digit-Matrix (the list of decimal expansions) in Cantor's Diagonal Argument is required to have at least as many columns (decimal places) as rows (listed real numbers), for the argument to work, since the generated diagonal number needs to pass through all the rows - thereby allowing it to differ from each listed number. With respect to the diagonal argument the Digit-Matrix then would ideally have a square shape.

But then again, how can it have a square shape?
With every additional column (decimal place) you necessarily multiply the number of rows (listed real numbers) by 10 (or b in a b-based number system), just like our decimal system allows for 10^availableDigits natural numbers (including zero), i.e. 10 numbers with one digit, 100 numbers with 2 digits and 1000 numbers with 3 digits.
Now this should result in a vertically stretched, rectangular-shaped Digit-Matrix measuring an area of numberOfDecimalPlaces * 10^numberOfDecimalPlaces, where the first factor would be the number of columns and the latter the number of rows.
Having a DigitMatrix with so many more rows (listed real numbers) than columns (decimal places) would mean that the diagonal argument wouldn't work, because the generated diagonal number would then only differ from the numbers in the square-area it crosses but not necessarily from all the numbers in the much longer part of the list below it.
I understand that Cantors Argument is about real numbers, which have infinitely many digits. Therefore one might argue that infinity is not a number and that infinite many decimal places might just be as infinite as a list with 10^infinity many entries.
Does this mean, that the Digit-Matrix in Cantor's Diagonal Argument can be considered an infinite square, even though the number of rows (length) clearly exceeds the number of columns (width) when regarding any finite number of decimal places of that diagonal number?
If not: How can the diagonal argument be applicable to a Digit-Matrix that is longer than wide, due to more real numbers than decimal places?
@Greg Martin:
To 1:
As stated in my question:
"I understand that Cantor's Argument is about real numbers, which have infinitely many digits."
I only mention those finite row counts to point out a general property of positional number systems: n-Digits allow for base^n unique numbers.
This is what I have on my mind when I look at the first n columns of Cantor's DigitMatrix: the decimal system with n decimal places.
And yes, this means indeed, that I am ignoring the infinite decimal expansions of the reals - but only for the moment.
Only to emphasise that any sufficiently completed list is much longer than only those first n numbers that differ from the generated n-digit diagonal number,
in fact so long that it actually includes the diagonal number somewhere deeper down, which means that Cantor's argument does not
work for any finite number n of decimal places.
But this is where I acknowledge that "…Cantors Argument is about real numbers, which have infinitely many digits."
To 2:
I understand that the DigitMatrix in Cantor's argument is a static mathematical object.
But anyway, here you are answering my question. You are answering it with "yes", by calling both sides of the DigitMatrix infinite and
the resulting shape a "square" which works fine with the diagonal argument.
I have expected this answer but I still have my difficulties to understand how that inequality: n digits != 10^n rows ,which we observe for any finite number of columns, can turn into an equality like: infinite many digits = infinite many rows.
To 3:
I am not proposing a specific way of ordering the real numbers.
I understand that the order might be, as you describe it: "someone's unexpected attempt to list all these real numbers" but
while I don't care about the order I still expect the list to be as complete as possible.
In case you are referring to the picture: the digits are named by indices i.e. a23 (3rd digit of second number) but they are still totally variable in their values.

A: There are a few misunderstandings here:

*

*First, from your description of how row are added, it seems that you are thinking of real numbers as having only finitely many (nonzero) decimal places. (At least that's the only way I can make sense out of the proposed counts of how many new rows are added.) That's not the case: real numbers can and do have infinite decimal expansions.

*Second, each row of the table is infinite, and there are infinitely many rows. That's as "square" as one can hope for in this context, and it doesn't depend on what "speed" we add rows or columns. The list is a static mathematical object, not a running process.

*Most importantly: you have proposed one specific way of ordering these real numbers into a list. But that's not how Cantor's proof works. We are given an arbitrary list of real numbers (perhaps someone's unexpected attempt to list all these real numbers) and the diagonal argument shows that it must omit some real number.


text:
Q: MySQL PHP GAE Form I have the following form:

Sign the Register

<form action="sign.php" method="post">

<textarea name="firstName" rows="3" cols="60" placeholder="First Name..." required="true"></textarea>

<textarea name="surname" value="mickey" rows="3" cols="60" placeholder="Surname..." required="true"></textarea>

<textarea name="course"  value="mickey" rows="3" cols="60" placeholder="Your Course..." required="true"></textarea>

<textarea name="subject" rows="3" cols="60" placeholder="Subject..." required="true"></textarea>

<textarea name="level" rows="3" cols="60" placeholder="Level: C, I, H, M..." required="true"></textarea>

<textarea name="date" rows="3" cols="60" placeholder="Date.." required="true"></textarea>

<textarea name="time" rows="3" cols="60" placeholder="Time.." required="true"></textarea>

<input type="submit" value="Sign Register">

And sign.php is (the connection is fine):
{
if (array_key_exists('firstName', 'surname', 'course', 'subject', 'level', 'date', 'time', $_POST)) {
$stmt = $db->prepare('INSERT INTO entries (firstName, surname, course, subject, level, date, time) VALUES (:firstName, :surname, :course, :subject, :level, :date, :time)');
$stmt->execute(array(':firstName' => htmlspecialchars($_POST['firstName']),
':surname' => htmlspecialchars($_POST['surname']),
':course' => htmlspecialchars($_POST['course']),
':subject' => htmlspecialchars($_POST['subject']),
':level' => htmlspecialchars($_POST['level']),
':date' => htmlspecialchars($_POST['date']),
':time' => htmlspecialchars($_POST['time'])));
 $affected_rows = $stmt->rowCount();

 }
 }
 $db = null;
 ?>

And when that is executed the user is taken to a following page which has the following:
    <?php

          try {
// Show existing entries.
foreach($db->query('SELECT * from entries') as $row) {
        echo "
" . $row['firstName'] . " wrote
 " . $row['course'] . "
";
 }
  } catch (PDOException $ex) {
echo "An error occurred in reading or writing to register.";
  }
  $db = null;
?>

But the problem is that none of the records are showing on the success page. I am using google app engine with cloud SQL database (the connection is fine). It is basically a form, the user fills in the form and then the data is sent to the cloud sql database. Also once the user submits the form, they are taken to a page which displays the information that is just been submitted. Any easier/better ways of doing this are welcome.
Thank you

A: array_key_exists expects only two parameters (key,array) you should split

if (array_key_exists('firstName', 'surname', 'course', 'subject', 'level', 'date', 'time', $_POST))

into multiple conditions
if(array_key_exists('firstName', $_POST) && array_key_exists('surname', $_POST) ... array_key_exists('time', $_POST))


text:
Q: Combine Similar Classes with jQuery .first() I'm trying to remove a common class between multiple divs but only target the first p in each div to remove that class name.
Here's my HTML:

This title

A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. Words are like wind. And now his watch is ended. Bastards are born of passion, aren't they? We don't despise them in Dorne. King in the North.

All men must die. It's ten thousand miles between Kings landing and the wall. A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. The wolf and the lion. All men must die.

This title

A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. Words are like wind. And now his watch is ended. Bastards are born of passion, aren't they? We don't despise them in Dorne. King in the North.

All men must die. It's ten thousand miles between Kings landing and the wall. A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. The wolf and the lion. All men must die.

This title

A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. Words are like wind. And now his watch is ended. Bastards are born of passion, aren't they? We don't despise them in Dorne. King in the North.

All men must die. It's ten thousand miles between Kings landing and the wall. A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. The wolf and the lion. All men must die.

When I do this:
$(".thing--one p, .thing--two p, .thing--three p").first().removeClass("extended-content");

It only removes the first extended-content class from the first p in the thing--one class.
So, currently I have it written out like this:
$(".thing--one p").first().removeClass("extended-content");
$(".thing--two p").first().removeClass("extended-content");
$(".thing--three p").first().removeClass("extended-content");

Which works, but that feels and seems really bloated and not the best way to go about removing a common class in those three divs.
Any ideas on how to make that a bit more semantic?

A: You could use index selector :eq(x) that selects the element at index x within the matched set, like :
$(".thing--one p:eq(0), .thing--two p:eq(0), .thing--three p:eq(0)").removeClass("extended-content");

If you want to loop through them it will be better to use jQuery method map() :
$(".thing").map(function() {
    $('p:eq(0)', this).removeClass("extended-content");
});

setTimeout(function() {
  $(".thing--one p:eq(0), .thing--two p:eq(0), .thing--three p:eq(0)").removeClass("extended-content");
}, 500);
.extended-content {
  background-color: pink;
}

This title 1

A good act does not wash out the bad, nor a bad act the good.

All men must die. It's ten thousand miles between Kings landing and the wall

This title 2

A good act does not wash out the bad, nor a bad act the good.

All men must die. It's ten thousand miles between Kings landing and the wall.

This title 3

A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. Words are like wind. And now his watch is ended. Bastards are born of passion, aren't they? We don't despise them in Dorne. King in the North.

All men must die. It's ten thousand miles between Kings landing and the wall. A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. The wolf and the lion. All men must die.

A: This is functionally exactly the same as what you have that does work, but I consider it a bit friendlier on the eye...
$(".thing--one, .thing--two, .thing--three").each(function() {
    $(this).find("p").first().removeClass("extended-content");
});

It finds all the container elements and then runs a .find() on the contents, finding the first
 tag.
Unless there's a reason not to, you could always change it to...
$(".thing").each(function() { etc..

A: Hope this helps

$(".thing").each(function(i) {
  $(this).find("p").first().removeClass("extended-content");
});
.extended-content {
  color: red;
}

This title

A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. Words are like wind. And now his watch is ended. Bastards are born of passion, aren't they? We don't despise them in Dorne. King in the North.

All men must die. It's ten thousand miles between Kings landing and the wall. A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. The wolf and the lion. All men must die.

This title

A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. Words are like wind. And now his watch is ended. Bastards are born of passion, aren't they? We don't despise them in Dorne. King in the North.

All men must die. It's ten thousand miles between Kings landing and the wall. A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. The wolf and the lion. All men must die.

This title

A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. Words are like wind. And now his watch is ended. Bastards are born of passion, aren't they? We don't despise them in Dorne. King in the North.

All men must die. It's ten thousand miles between Kings landing and the wall. A good act does not wash out the bad, nor a bad act the good. Each should have its own reward. The wolf and the lion. All men must die.


text:
Q: How to best use Spring JPA findByXXX where there are multiple combinations? I need to write a service that needs to find an entity using the following combinations:
firstName, lastName, phoneNumber, emailAddress
Its becoming a nightmare in my service class and repository to code this. The Permutations are getting out of hand. I still want to use Query Methods to achieve this but was looking to see if there's  more efficient way to do this?
public interface UniversitySearchRepository extends CrudRepository<University, Long> {
    public CcCase findByFirstName(
            @Param("firstName") String firstName);

    public CcCase findByLastName(
            @Param("lastName") String lastName);

    public CcCase findByEmailAddress(
            @Param("emailAddress") String emailAddress);

    public CcCase findByFirstNameAndLastName(
            @Param("firstName") String firstName,
            @Param("lastName") String lastName);

    public CcCase findByFirstNameAndEmailAddress(
            @Param("firstName") String firstName,
            @Param("emailAddress") String emailAddress);

    public CcCase findByLastNameAndEmailAddress(
            @Param("lastName") String lastName,
            @Param("emailAddress") String emailAddress);
    ....

A: You can try using query-by-example: org.springframework.data.jpa.repository.JpaRepository#findAll(Example<S>)
Related topic: Spring Data JPA: Query by Example?


text:
Q: PHP: is it possible to access static methods like this: Object::ChildObject::method()? In JS you can access methods in this fashion: ParentObject.ChildObject.ChildObjMethod() -- can same be done in PHP?

A: Not exactly.  The :: operator is for invoking static methods on a class.  So, you could store a reference to an object statically, but then you'd need to invoke the method with a -> operator.
<?php
    class Foo
    {
        static public $bar;

        static public function initStaticMembers()
        {
            self::$bar = new Bar();
        }
    }

    class Bar
    {
        public function method()
        {
            echo "Hello World\n";
        }

    }

    Foo::initStaticMembers();
    Foo::$bar->method();

There's no way to do
    Object::ChildObject::method();

Method chaining is essentially a shortcut for something like
    $o = Object::ChildObject;
    $o::method();

The first call is made, and returns or assigns something.  The next method is then called on the thing that's returned.  You can't store a class in a variable with PHP, or return a class from a function.  Therefore, the exact syntax for what you're asking to do is impossible.
That said, method chaining is becoming more popular in PHP.  Syntax like the following
    $o = new Baz();
    $o->method()->anotherMethod()->yetAnotherMethod();
    $o->someObjectReference->methodCall()->etc();

is becoming common place.  This works because each call or variable reference
    $o->method();
    $o->someObjectReference;

returns another Object instance, which can then have a method called on it.

A: The :: can be used for accessing static class members. But you can also access instantiated childobjects in PHP, using the normal -> arrow thingy:
$parent->child->child_method();

See also Reference - What does this symbol mean in PHP?


text:
Q: DBNull issue with Oracle 11g ODP.Net provider We are facing problem in checking output parameters for "DBNull".  "DBNull" value returned by Oracle stored procedure or function is treated as "null" string by oracle 11g client/ODP.Net provider. This works fine with oracle 10g client as it returns "DBNull".
Because of this all our "DBNull"  check fails

A: ODP.NET RETURNING "NULL" STRING WHEN THE VALUE IS NULL [ID 968857.1]
    Modified 04-JAN-2010 Type PROBLEM Status PUBLISHED

In this Document
Symptoms
Changes
Cause
Solution
Applies to:
Oracle Data Provider for .NET - Version: 10.2.0.2.20 to 11.1.0.7.10
Microsoft Windows (32-bit)
Microsoft Windows x64 (64-bit)
Symptoms
After migrating from a previous version of Oracle Data Provider for .NET, a change in behavior may occur with respect to null values being retrieved. Whereas the application previously returned an empty string, a string with the value "null" is now obtained.
Changes
Migration from 1.x ODP.NET to 2.x ODP.NET
Cause
The behavior is due to a migration from the 1.x Oracle Data Provider for .NET to the 2.x provider. 2.x ADO.NET supports the ability of the provider to return provider specific types, and this is one of the potential "breaking changes" going from .NET 1.x to 2.x.
ODP.NET versions 9.2.x, 10.1.x, 10.2.0.1.0 were all 1.x framework providers. Typically this behavior is noticed when migrating from an early version ODP to a newer version of ODP, but at the same time swtiching from the 1.x provider to the 2.x provider. It is the change in .NET framework support rather than the change in Oracle client version that causes this behavior.
This behavior may also be noticed migrating the application to a 64 bit operating system, as there is no 1.x 64 bit framework.
Solution
To resolve this behavior, the code will need to be modified.
As a workaround, using ODP.NET for 1.x (1.111.7.0 for example instead of 2.111.7.0) will result in the previous behavior, but note that the 1.x provider is not tested or supported on any version of framework other than 1.x, and that support for 1.x is not planned for any version later than 11.1.0.7.0
If the operating system is 64 bit, the application will need to be forced to run under the SYSWOW64 subsystem (ie, as 32 bit) in order to use 1.x ODP.NET.
To correct the code:
If the value is a DbType, you can check for param.Value==DbNull.Value
If the value is an OracleDbType, you can check for ((INullable)param.Value).IsNull since Oracle Types inherit INullable interface.

A: Following the breaking change that Oracle released (see comment below). You need to add the additional bit below:
if (oraParam[7] == null ||
    oraParam[7].Value == DBNull.Value ||
    ((INullable)oraParam[7].Value).IsNull)

INullable is in the Oracle.DataAccess.Types namespace.

A: Or you can try...
(OracleString)result == OracleString.Null


text:
Q: NSURL equal to server URL I'm getting url from my server. I used this code
self.bookURL = [aDictionary objectForKey:@"bookurl"];
The url is http://www.test.com/url. If this URL matches, I need to display a UIButton. How can I match this URL with self.bookURL? I used below NSLog, nothing displays in the log.
NSLog(@"book url is %@",bookURL);
NSString *thumburl=@"http://www.test.com/ur";
if(bookURL==thumburl){

}

A: You can compare URLs using
You can convert thumburl into an NSURL using
NSURL thumburl = [NSURL URLWithString:@"http://www.test.com/ur"];

and then compare the two NSURLs using
if([self.bookURL isEqual: thumburl]){
    //They match
}

If they are both strings use
if([self.bookURL isEqualToString:thumbURL]){
    //They match
}

If nothing is displaying in the log the dictionary is probably returning an empty string, check this by logging (or better yet put a break point on the line after your dictionary gets populated)

A: If you want a simple string compare convert with
[someURL absoluteString]
For more complicated cases that arise with URLs check the method provided here...
https://stackoverflow.com/a/12332091/1381053

A: You cannot compare strings (or objects for that matter) with ==.
You can either convert the NSString to an NSURL and compare like this:
NSURL *thumburl = [NSURL URLFromString:@"http://www.test.com/ur"];

if ([self.bookURL isEqual:thumburl]){
     //do something
}

This assumes that the value bookurl stored in the NSDictionary is an object of type NSURL. If you want to do a string comparison between two NSStrings (instead of working with NSURL), then you can do the following:
if ([self.bookURL isEqualToString:thumburl]){
     //do something
}

This second example assumes that the self.bookURL object that you are getting back is NSString instead of NSURL.