text:
Q: Lambda - C# - Dynamic expressions, using string.IsNullOrEmpty I have the following code block I am using to perform some dynamic filtering on a generic IQueryable list
    private static MethodInfo miTL = typeof(String).GetMethod("ToLower", Type.EmptyTypes);

    public static IQueryable<T> Where<T>(IQueryable<T> source, string member, object value)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        if (member == null)
        {
            throw new ArgumentNullException("member");
        }
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        if (value is string && !string.IsNullOrWhiteSpace(value.ToString()))
        {
            //If the type is string, force lowercase equals comparison for both sides.
            value = value.ToString().ToLower();

            var parameter = Expression.Parameter(typeof(T), "item");
            var parameterProperty = Expression.Property(parameter, member);

            //ToLower dynamic expression
            var dynamicExpression = Expression.Call(parameterProperty, miTL);

            var constantValue = Expression.Constant(value);
            var equalsExpression = Expression.Equal(dynamicExpression, constantValue);

            var lambdaExpression = Expression.Lambda<Func<T, bool>>(equalsExpression, parameter);

            return source.Where(lambdaExpression);
        }
        else
        {
            var item = Expression.Parameter(typeof(T), "item");
            var prop = Expression.Property(item, member);
            var soap = Expression.Constant(value);
            var equal = Expression.Equal(prop, soap);
            var lambda = Expression.Lambda<Func<T, bool>>(equal, item);
            return source.Where(lambda);
        }
    }

This all works fine - apart from the possibility of my source containing null values, which then returns a null reference exception.
It directly translates to (when the field is "Counterparty" :- {item => (item.Counterparty.ToLower() == "name of counterparty")}
What I actually need in Lambda expression form is :-
{item => !string.IsNullEmptyOrWhitespace(item.Counterparty) && (item.Counterparty.ToLower() == "name of counterparty")}
Any ideas how to achieve this dynamically?
--REVIEWED--
Here is the whole replacement code, using a much nicer string.Equals check
    public static IQueryable<T> Where<T>(IQueryable<T> source, string member, object value)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        if (member == null)
        {
            throw new ArgumentNullException("member");
        }
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        if (value is string && !string.IsNullOrWhiteSpace(value.ToString()))
        {
            var parameter = Expression.Parameter(typeof(T), "item");
            var parameterProperty = Expression.Property(parameter, member);

            var body =
                Expression.AndAlso(
                    Expression.Not(
                        Expression.Call(typeof(string), "IsNullOrEmpty", null, parameterProperty)
                    ),
                    Expression.Call(typeof(string), "Equals", null,
                        parameterProperty, Expression.Constant(value),
                        Expression.Constant(System.StringComparison.InvariantCultureIgnoreCase))
                );

            var body2 = Expression.Call(typeof(string), "Equals", null,
                parameterProperty, Expression.Constant(value),
                Expression.Constant(System.StringComparison.InvariantCultureIgnoreCase));

            var lambdaExpression = Expression.Lambda<Func<T, bool>>(body, parameter);

            return source.Where(lambdaExpression);
        }
        else
        {
            var item = Expression.Parameter(typeof(T), "item");
            var prop = Expression.Property(item, member);
            var soap = Expression.Constant(value);
            var equal = Expression.Equal(prop, soap);
            var lambda = Expression.Lambda<Func<T, bool>>(equal, item);
            return source.Where(lambda);
        }
    }

A: A literal translation would be something like:
var body =
    Expression.AndAlso(
        Expression.Not(
            Expression.Call(typeof(string), "IsNullOrWhiteSpace", null,
                                                       parameterProperty)
        ),
        Expression.Equal(
            Expression.Call(parameterProperty, "ToLower", null),
            Expression.Constant("name of counterparty")
        )
    );

However, you would do well to look at the various string.Equals overloads. For example:
var body = Expression.Call(typeof(string), "Equals", null,
    parameterProperty, Expression.Constant("name of counterparty"),
    Expression.Constant(System.StringComparison.InvariantCultureIgnoreCase));


text:
Q: Rest service and web service in the same Spring Boot application Is it possible to have both Soap Web Service and and Rest service in the same Spring Boot application? I created class for handling WS request annotated with @Endpoint annotation and controller for REST service annotated with @RestController annotation.
When I run application with both of them requests for REST service are being handled by WS service which complains about SOAP envelope. When I run the same application only with REST controller everything works fine. So is it possible to configure somehow Spring Boot application to have both WS and REST service coexist?

A: Possible, just use different URIs in mappings.
But I've put REST and WS mappings to different classes, just to be more convenient.

redpajama_set_name: RedPajamaStackExchange


text:
Q: APScheduler AsyncIOScheduler() exits after script completion I've read through a few of the Similar Questions provided, but I'm not able to get to a result that works for me.  Likely can be chalked up to a general lack of understanding of these kinds of concepts from my limited Python experience.
I'm trying to call an async function on a schedule.  The scheduler starts, but then the script exits.  I thought this was going to run in a loop, keeping the script in the foreground but it seems that it doesn't.
Any pointers?
import asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import c_logging
import c_seed

client = 'async'
state = 'live'
account = 'spot'

async def main():
    c_logging.logging.info("")
    c,l = await c_seed.init(client,state,account)
    await c_seed.seed(c,l)
    scheduler = AsyncIOScheduler()
    scheduler.add_job(c_seed.seed, 'cron', minute='*', second='5', args=(c,l))
    scheduler.start()
    scheduler.print_jobs()

if __name__ == "__main__":
    c_logging.logging.info("")
    asyncio.run(main())

2021-07-02 10:11:24,204 [INFO] <module>: c_client
2021-07-02 10:11:24,205 [INFO] <module>:
2021-07-02 10:11:24,205 [DEBUG] __init__: Using selector: KqueueSelector
2021-07-02 10:11:24,205 [INFO] main:
2021-07-02 10:11:24,205 [INFO] init:
2021-07-02 10:11:24,205 [INFO] create: c_client
2021-07-02 10:11:24,205 [INFO] create: c_client -> async
2021-07-02 10:11:24,205 [INFO] create: c_client -> live
2021-07-02 10:11:24,569 [INFO] pairs_list:
2021-07-02 10:11:24,731 [DEBUG] seed: async seed start
2021-07-02 10:11:30,143 [DEBUG] seed: async seed complete
2021-07-02 10:11:30,218 [INFO] add_job: Adding job tentatively -- it will be properly scheduled when the scheduler starts
2021-07-02 10:11:30,219 [INFO] _real_add_job: Added job "seed" to job store "default"
2021-07-02 10:11:30,219 [INFO] start: Scheduler started
Jobstore default:
    seed (trigger: cron[minute='*', second='5'], next run at: 2021-07-02 10:12:05 EDT)
2021-07-02 10:11:30,219 [DEBUG] _process_jobs: Looking for jobs to run
2021-07-02 10:11:30,220 [DEBUG] _process_jobs: Next wakeup is due at 2021-07-02 10:12:05-04:00 (in 34.779986 seconds)
%

A: Only when the script is running, the job will works.Look https://apscheduler.readthedocs.io/en/stable/faq.html

A: I think you should keep this script running endlessly because there is a cron task.
Just try to change asyncio.run(main()) to asyncio.get_event_loop().run_forever()
Hope this could help you.

You could check the following reference:
https://github.com/agronholm/apscheduler/blob/3.x/examples/schedulers/asyncio_.py
Run a function every n seconds in python with asyncio


text:
Q: magento variable for product detail view is there a variable to check if the product detail view (view.phtml) is used?
Why do I need this?
Price.phtml is used in product overview and product detail view also. I want to add a ifelse function when the price is shown on product detail view cause I want some more information.
Regards
Matt

A: Yup this is quite easy to achieve;
$pageIdentifier = Mage::app()->getFrontController()->getAction()->getFullActionName();
if($pageIdentifier == 'catalog_product_view') {
    // Do something on product view page only
    echo 'This is a product view page';
}


text:
Q: Extract AICs from an ARIMA using a nested loop I am trying to extract AICs & BICs from an ARIMA estimation with different
combinations of p & q (p=0,1,2,3
and q=0,1.2,3). I have tried using the following code, unsucessfully.

code: storage1 <- numeric(16) for (p in 0:3){

>     for (q in 0:3){
>
>     storage1[p]  <- arima(x,order=c(p,0,q), method="ML")} } storage1$aic

A: One way is to use expand.grid() to get all combinations of p and q, and apply them to your arima model, i.e.
apply(expand.grid(p, q), 1, function(i) arima(d1$cnt, order = c(i[1], 0, i[2]), method = "ML")$aic)

#[1] 47222.43 38589.14 36935.33 36118.44 42569.73 35183.35 35141.13 35143.02 39448.38 35142.96 35142.58 35142.60


text:
Q: Displaying group of results from SQL I'm wondering if someone could help me out.
I'm trying to construct a SQL query.
I have a bunch of filenames, which i have put into an array like so
'filename1.jpg', 'filename2.jpg', 'filename3.jpg', 'filename4.jpg'

I also have a table with the following columns
date | filename | like | ipaddress

Everytime someone likes the filename a new row gets added to the table
What i need to do is count the likes for each filename and then print out the filename and like count for each of the files, im using classic ASP

A: SELECT filename, sum(like) as likes FROM TABLE group by filename

to order by likes:
SELECT filename, sum(like) as likes FROM TABLE group by filename order by sum(like) desc


text:
Q: JSON filtering by time I have a JSON like this
[{
    "Event_code": "AB-001",
    "Interest_area": "Arts and Education",
    "Start_time": "9:00 AM",
    "End_time": "3:00 PM",
    "Session_type": "Course information session"
}, {
    "Event_code": "AB-002",
    "Interest_area": "Arts and Education",
    "Start_time": "12:30 PM",
    "End_time": "1:00 PM",
    "Session_type": "Course information session"
}, {
    "Event_code": "AB-003",
    "Interest_area": "",
    "Start_time": "9:00 AM",
    "End_time": "3:00 PM",
    "Session_type": "Course information session"
}, {
    "Event_code": "AB-004",
    "Interest_area": "Business",
    "Start_time": "10:30 AM",
    "End_time": "11:00 AM",
    "Session_type": "Course information session"
}, {
    "Event_code": "AB-005",
    "Interest_area": "General Interest",
    "Start_time": "9:30 AM",
    "End_time": "1:30 PM",
    "Session_type": "Experience"
}, {
    "Event_code": "AB-006",
    "Interest_area": "Environment ,    Business       ",
    "Start_time": "11:00 AM",
    "End_time": "11:30 AM",
    "Session_type": "Course information session"
}]

How do I filter this JSON to get events with "Start_time" after 12 noon ? I am thinking of doing something like
let filtered_data = data.filter(o => o.Start_time >= '12 PM');

But of course this will not work as "Start_time" is 'string' and not 'date' type.

A: You do not have a JSON there - you have an array of objects. JSON is a particular way of formatting a string to represent an object.
Luckily, in your case, it should be very easy - to filter for events after 12 noon, you can simply check the Start_time property to see if the string includes PM:

const input=[{"Event_code":"AB-001","Interest_area":"Arts and Education","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"Course information session"},{"Event_code":"AB-002","Interest_area":"Arts and Education","Start_time":"12:30 PM","End_time":"1:00 PM","Session_type":"Course information session"},{"Event_code":"AB-003","Interest_area":"","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"Course information session"},{"Event_code":"AB-004","Interest_area":"Business","Start_time":"10:30 AM","End_time":"11:00 AM","Session_type":"Course information session"},{"Event_code":"AB-005","Interest_area":"General Interest","Start_time":"9:30 AM","End_time":"1:30 PM","Session_type":"Experience"},{"Event_code":"AB-006","Interest_area":"Environment ,    Business       ","Start_time":"11:00 AM","End_time":"11:30 AM","Session_type":"Course information session"}];

console.log(
  input.filter(({ Start_time }) => Start_time.includes('PM'))
);

Note that includes is an ES6 function, you may want a polyfill.


text:
Q: Plans to support .NET Core in Bot Framework SDK? Is there any plan to support .NET Core in the near future? I mean, without refactoring my bot code. There are still components not compatible with it.

A: Yes, it is planned and in the works.  You can follow the topic on this related GitHub issue: [Feature Request] Porting to .NET core #572
Update 2017-10-26:
Bot Framework team is working on a complete rewrite of BotBuilder SDK (v4) which will be fully compatible with .NET Core.
Update 2017-12-14
Bot Builder v3 - New Bot Connector support for ASP.NET Core 2.0 and 1.1 has been released on NuGet!

We've released two new nuget packages for the Microsoft Bot Connector to support .NET Core 2.0:

*

*Microsoft.Bot.Connector.AspNetCore.1.1.3.2.nupkg

*Microsoft.Bot.Connector.AspNetCore.2.0.0.3.nupkg
The above packages each target ASPNetCore 1.x and ASPNetCore 2.x respectively, and provision authentication for your bot. They must also use Microsoft.Bot.Connector.3.12.2.4 or higher.


text:
Q: Convert a fluid nested flexbox grid to stacked for mobile I am using the CSS3 Flexible Box for a cross device site.
I have an existing flexbox layout for the desktop devices, like so:

body {
  text-align: center;
}

.wrapper {
  background-color: white;
  display: flex;
}

.nested-wrapper1 {
  background-color: cyan;
  width: 50%
}

.nested-wrapper2 {
  background-color: pink;
  width: 50%
}

1

2

3

How do I create a fluid layout for mobile devices where only 1,2 are in a grid and 3 should be stacked below 1,2; refer the following image:

A: Maybe there is a way with a flexbox - assuming the mobile view is below 650px, position the third div absolutely relative to the wrapper.
A possible issue can be that the third div fully overflows the wrapper. Well, check out the demo below:

body {
  text-align: center;
}

.wrapper {
  background-color: #ddd;
  display: flex;
  position: relative;
}

.nested-wrapper1 {
  display: flex;
  width: 50%;
}

.nested-wrapper2 {
  width: 50%;
}

.nested-wrapper1>[class='1'] {
  background-color: cyan;
  padding: 1em;
  flex: 1;
}

.nested-wrapper2>[class='2'] {
  background-color: pink;
  padding: 1em;
}

.nested-wrapper2>[class='3'] {
  background: lightblue;
  padding: 1em;
}

@media screen and (max-width: 650px) {
  .nested-wrapper2>[class='2'] {
    height: 100%;
  }
  .nested-wrapper2>[class='3'] {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    transform: translateY(100%);
  }
}

      1. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

      2. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
       2. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      3. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: You can do this using display:contents and a media query.
Codepen Demo
Display:contents @ MDN

These elements don't produce a specific box by themselves. They are replaced by their pseudo-box and their child boxes.
Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off.

Support...is poor. Chrome 58 & FF37 - No IE/Edge/Opera/Safari

body {
  text-align: center;
}

.wrapper {
  background-color: white;
  display: flex;
}

.nested-wrapper1 {
  background-color: cyan;
  width: 50%
}

.nested-wrapper2 {
  background-color: pink;
  width: 50%
}

.r-2 {
  background: red;
}

.r-3 {
  background: yellow;
}

@media (max-width:600px) {
  .wrapper {
    flex-wrap: wrap;
  }
  .nested-wrapper2 {
    display: contents;
  }
  .l-1,
  .r-2 {
    flex: 0 0 50%;
  }
  .r-3 {
    width: 100%;
  }
}

1

2

3

A: While the OP has asked for a flexbox solution, and as I'm not aware that you can do that layout with flexbox, you could use floats.
Depending on the content and the needed proportions of the elements this approach may or may not work.

body {
  margin: 0;
}
.flexo {
  height: 200px;
}
.flexo > div {
  float: left;
  width: 50%;
  height: 66.66666%;
}
.flexo > div:nth-child(1) {
  background-color: dodgerblue;
}
.flexo > div:nth-child(2) {
  background-color: deeppink;
}
.flexo > div:nth-child(3) {
  background-color: limegreen;
}
.flexo > div:nth-child(3) {
  height: 33.33333%;
  width: 100%;
}

@media ( min-width: 480px ) {

  .flexo > div:nth-child(1) {
    height: 100%;
  }
  .flexo > div:nth-child(2),
  .flexo > div:nth-child(3) {
    height: 50%;
    width: 50%;
  }

}

.cf:before,
.cf:after {
  content: " ";
  display: table;
}
.cf:after {
  clear: both;
}

1

2

3


text:
Q: figuring things out in linear algebra There are things in linear algebra that I would like to better understand, from an intuitive point of view. For example, matrices are entities that may be use to transform a domain into another, by means of rotation, shifting, stretching and so on. My first question is this: how much information do I need to know about a matrix to have an idea about what the matrix is doing? Would it be possible to get some rough idea about this without much information about its spectral properties, and say "Well just by looking at the structure of this matrix, and the numbers in it, I can guess this and that...".
The second question is if anyone knows fast method to compute eigenvalues/eigenvector in your head. I know people who can do this for any 2-be-2 matrix, but I don't know which methods are they using.

A:
how much information do I need to know about a matrix to have an idea about what the matrix is doing?

When I took Linear Algebra, it was really helpful to visualize the geometry of course! This is a really worthwhile endeavor in any branch of mathematics. When you're given a matrix, keep in mind always that you're looking at linear transformation from one vector space to another. The matrix can be thought of as column (row) vectors, depending on your point of view. Rather than try (in vain) to describe all of the geometry contained within a matrix, I will point you in the direction to begin:
If you haven't yet, please look at MIT's open courseware Linear Algebra video lectures by Dr. Gilbert Strang. His lectures are very good. I haven't studied his book, but I've studied from other books (both cheap and very good: Shilov's Linear Algebra and Axler's Linear Algebra Done Right; buy/rent/obtain them somehow).
The point of eigen(german for characteristic)values is that these vectors remain the same(up to a scaling factor, $\lambda$, under the linear transformation. Take a linear transformation that rotates by 180 degrees in $\mathbb{R}^2$. The vector $(1,0)$ is mapped to $(-1,0)$. This is peculiar: it seems we have only multiplied this vector by a $\lambda = -1$. You can probably guess this is going to be an eigenvalue (actually two). $(0,1)$ is similarly mapped to $(0,-1)$. And in general a vector $(a,b)$ is mapped to $(-a,-b)$. This computation is much easier when the matrix is in its diagonalized form (two -1's on the diagonals).

The second question is if anyone knows fast method to compute eigenvalues/eigenvector in your head. I know people who can do this for any 2-be-2 matrix, but I don't know which methods are they using.

You can try $\det{(A-\lambda I)}=0$. This determinant is not hard, and how the polynomial splits should be recognizable. There are other methods, of course. Maybe you could provide an example matrix? (see Axler for Linear Algebra with little mention of the determinant...) Hopefully you remember that if you have a diagonal matrix $A$, the eigenvalues are on the diagonal :-).
I hope this helped a bit.
Edit: Ohh! I forgot! What Yuval said is very good for quickly finding the product and sum of the eigenvalues.

A: So, you want to be able to just look at a $2\times2$ matrix, and see its geometric effect on the plane. I don't think you can always do this, but here are some special cases. I'll assume real entries.

*

*If one column is just a scalar multiple of the other, then the matrix flattens the plane into a line. For example, if $A=\pmatrix{4&6\cr6&9\cr}$ so the first column is two-thirds the second, and the matrix takes everything to the line through the origin and $(4,6)$ (the first column).

*If $A=\pmatrix{a&-b\cr b&a\cr}$ then $A$ is a dilation by the factor $\sqrt{a^2+b^2}$ and a  rotation. Write $A={1\over\sqrt{a^2+b^2}}\pmatrix{\cos\theta&-\sin\theta\cr\sin\theta&\cos\theta\cr}$ where $\tan\theta=b/a$, and you'll see the rotation is counterclockwise through $\theta$.

*If $A=\pmatrix{1&a\cr0&1\cr}$ then $A$ fixes $(1,0)$ but moves $(0,1)$ horizontally to $(a,1)$, so it is a shear.

*If $A=\pmatrix{r&0\cr0&s\cr}$ then it stretches the $x$-direction by a factor of $r$ (if $r\gt1$; shrinks by a factor of $r$, if $0\lt r\lt1$), and the $y$-direction by a factor of $s$. If $r$ (or $s$) is negative, then it also does a reflection in the $y$ (or $x$) axis.
Well, that should get you started.

A: You can use the singular value decomposition to learn the geometry of a linear transformation. In short, SVD says that every linear transformation maps the unit sphere in the domain to an ellipsoid in a subspace of the codomain.


text:
Q: AJAX not Posting date to PHP AJAX is sending a selected date - ('articleDate') - to a PHP document where it is then used within an SQL statement, however, I am getting an undefined error in my code when I run the PHP, on the line where I declare:
$date = $_POST['articleDate'];

Meaning that the value is not being posted to PHP.
I have checked the code and it seems to be working fine semantically. Is there a separate method for posting 'date' values within AJAX?
The PHP code works when there is no AJAX being used, and the form is being Posted via method - with the cue of a Submit Button.
HTML  code:

<?php include 'include/navbar.php';?>

                <form>
                    <input class="form-control" type="date" id="articleDate" onchange="viewArticle(this.value)">
                </form>

    <?php require 'include/footer.php';?>

Javascript
window.onload=function(){
    document.getElementById("articleDate").value="";
}
function viewArticle()
{
    $.ajax({
        type: "POST",
        url: "../pages/include/viewArticle.php",
        data: {
            Date: document.getElementById("articleDate").value
        },
        success: function (response) {
            document.getElementById("article").innerHTML=response;
        },
        error: function(xhr, status, error) {
            alert('article not sent');
         },
    });
}

PHP code (date initiation is where the error is(undefined variable):
#Get date
$date = $_POST['articleDate'];

$stmt = $conn->prepare("SELECT * FROM Article WHERE articleDate=? ORDER BY articleDate desc");
$stmt->bind_param("s", $date);
if($date !== "")
{
    if($stmt->execute()){
        $data = $stmt->get_result();

        #Check number of rows statement selects

        if($data->num_rows > 0)
        {
            #print data
            while($row = $data->fetch_assoc()){
                #create div
                echo '
';
                echo "";
                echo '
'.$row['articleHeadline'].'
';
                echo '
',$row['articleSummary']," ",'
';
                echo '
';
                echo '
' , $row['articleDate']," | " , $row['articleTopic'],'
';
                echo '
';
                echo '
';
            }
        }
        else
        {
            echo "
No articles exist on this date
";
        }
    }
    #$stmt->close();
    #$conn->close();
}
else{
    echo "Date not working";
}

Undefined varibale = $date

A: In the PHP you're getting the posted argument by name articleDate :
$_POST['articleDate']

When you're sending Date instead.
You've two choices :

*

*You could change the argument name in your JS like :
data: {
   articleDate: document.getElementById("articleDate").value
},

*Or you could change it in your PHP code like :
$_POST['Date']


text:
Q: Intersection and difference of two rectangles Searching the internet has not given a satisfactory solution for the following problem. Given a class Rectangle defined as the following:
class Rectangle:

    def __init__(self, x1, y1, x2, y2):
        if x1 > x2 or y1 > y2:
            raise ValueError('coordinates are invalid')
        self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2

    @property
    def width(self):
        return self.x2 - self.x1

    @property
    def height(self):
        return self.y2 - self.y1

    def bounds(self, other):
        return Rectangle(min(self.x1, other.x1), min(self.y1, other.y1),
                         max(self.x2, other.x2), max(self.y2, other.y2))

    def intersect(self, other):
        return self.x1 < other.x2 and self.x2 > other.x1 and \
               self.y1 < other.y2 and self.y2 > other.y1

How would you create a method to get the intersection and a generator to get the difference of two rectangles? Presumably, a more complete implementation of the following methods are needed, but it is not clear to me what should be written.
def __and__(self, other):
    if self.intersect(other):
        # return a new rectangle that provides
        # the intersection between self and other
    return None

def __sub__(self, other):
    take_away = self & other
    if take_away is None:
        return self
    if take_away is self:
        return None
    return self.get_partitions(take_away)

def get_partitions(self, take_away):
    # yield 1 or 3 rectangles that are not part of take_away
    # alternative:
    # yield 1 or 2 overlapping rectangles not part of take_away

Does anyone have an elegant implementation for these methods? My hope is to avoid writing code for every conceivable case that might be encountered.

A: Oleh Prypin was extremely helpful with the provided code. The following is a refactored version of the same.
from itertools import product, tee

def test():
    print('Example 1:')
    a = Rectangle(1, 1, 5, 5)
    b = Rectangle(3, 3, 7, 7)
    print(a & b)
    print(list(a - b))
    ##########################
    print('Example 2:')
    b = Rectangle(3, 2, 7, 4)
    print(a & b)
    print(list(a - b))
    ##########################
    print('Example 3:')
    b = Rectangle(2, 2, 4, 4)
    print(a & b)
    print(list(a - b))
    ##########################
    print('Example 4:')
    b = Rectangle(6, 2, 10, 6)
    print(a & b)
    print(list(a - b))
    ##########################
    print('Example 5:')
    b = Rectangle(0, 0, 6, 6)
    print(a & b)
    print(list(a - b))
    ##########################
    print('Example 6:')
    b = Rectangle(2, 0, 4, 6)
    print(a & b)
    print(list(a - b))

def pairwise(iterable):
    "s -> (s0, s1), (s1, s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

class Rectangle:

    __slots__ = '__x1', '__y1', '__x2', '__y2'

    def __init__(self, x1, y1, x2, y2):
        self.__setstate__((min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)))

    def __repr__(self):
        return '{}({})'.format(type(self).__name__, ', '.join(map(repr, self)))

    def __eq__(self, other):
        return self.data == other.data

    def __ne__(self, other):
        return self.data != other.data

    def __hash__(self):
        return hash(self.data)

    def __len__(self):
        return 4

    def __getitem__(self, key):
        return self.data[key]

    def __iter__(self):
        return iter(self.data)

    def __and__(self, other):
        x1, y1, x2, y2 = max(self.x1, other.x1), max(self.y1, other.y1), \
                         min(self.x2, other.x2), min(self.y2, other.y2)
        if x1 < x2 and y1 < y2:
            return type(self)(x1, y1, x2, y2)

    def __sub__(self, other):
        intersection = self & other
        if intersection is None:
            yield self
        else:
            x, y = {self.x1, self.x2}, {self.y1, self.y2}
            if self.x1 < other.x1 < self.x2:
                x.add(other.x1)
            if self.y1 < other.y1 < self.y2:
                y.add(other.y1)
            if self.x1 < other.x2 < self.x2:
                x.add(other.x2)
            if self.y1 < other.y2 < self.y2:
                y.add(other.y2)
            for (x1, x2), (y1, y2) in product(pairwise(sorted(x)),
                                              pairwise(sorted(y))):
                instance = type(self)(x1, y1, x2, y2)
                if instance != intersection:
                    yield instance

    def __getstate__(self):
        return self.x1, self.y1, self.x2, self.y2

    def __setstate__(self, state):
        self.__x1, self.__y1, self.__x2, self.__y2 = state

    @property
    def x1(self):
        return self.__x1

    @property
    def y1(self):
        return self.__y1

    @property
    def x2(self):
        return self.__x2

    @property
    def y2(self):
        return self.__y2

    @property
    def width(self):
        return self.x2 - self.x1

    @property
    def height(self):
        return self.y2 - self.y1

    intersection = __and__

    difference = __sub__

    data = property(__getstate__)

if __name__ == '__main__':
    test()

A: Here is a complete solution for you.
Methods in the class are ordered illogically so that the important parts are visible without scrolling.
import itertools

class Rectangle:
    def intersection(self, other):
        a, b = self, other
        x1 = max(min(a.x1, a.x2), min(b.x1, b.x2))
        y1 = max(min(a.y1, a.y2), min(b.y1, b.y2))
        x2 = min(max(a.x1, a.x2), max(b.x1, b.x2))
        y2 = min(max(a.y1, a.y2), max(b.y1, b.y2))
        if x1<x2 and y1<y2:
            return type(self)(x1, y1, x2, y2)
    __and__ = intersection

    def difference(self, other):
        inter = self&other
        if not inter:
            yield self
            return
        xs = {self.x1, self.x2}
        ys = {self.y1, self.y2}
        if self.x1<other.x1<self.x2: xs.add(other.x1)
        if self.x1<other.x2<self.x2: xs.add(other.x2)
        if self.y1<other.y1<self.y2: ys.add(other.y1)
        if self.y1<other.y2<self.y2: ys.add(other.y2)
        for (x1, x2), (y1, y2) in itertools.product(
            pairwise(sorted(xs)), pairwise(sorted(ys))
        ):
            rect = type(self)(x1, y1, x2, y2)
            if rect!=inter:
                yield rect
    __sub__ = difference

    def __init__(self, x1, y1, x2, y2):
        if x1>x2 or y1>y2:
            raise ValueError("Coordinates are invalid")
        self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2

    def __iter__(self):
        yield self.x1
        yield self.y1
        yield self.x2
        yield self.y2

    def __eq__(self, other):
        return isinstance(other, Rectangle) and tuple(self)==tuple(other)
    def __ne__(self, other):
        return not (self==other)

    def __repr__(self):
        return type(self).__name__+repr(tuple(self))

def pairwise(iterable):
    # https://docs.python.org/dev/library/itertools.html#recipes
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

# 1.
a = Rectangle(0, 0, 1, 1)
b = Rectangle(0.5, 0.5, 1.5, 1.5)
print(a&b)
# Rectangle(0.5, 0.5, 1, 1)
print(list(a-b))
# [Rectangle(0, 0, 0.5, 0.5), Rectangle(0, 0.5, 0.5, 1), Rectangle(0.5, 0, 1, 0.5)]

# 2.
b = Rectangle(0.25, 0.25, 1.25, 0.75)
print(a&b)
# Rectangle(0.25, 0.25, 1, 0.75)
print(list(a-b))
# [Rectangle(0, 0, 0.25, 0.25), Rectangle(0, 0.25, 0.25, 0.75), Rectangle(0, 0.75, 0.25, 1), Rectangle(0.25, 0, 1, 0.25), Rectangle(0.25, 0.75, 1, 1)]

# 3.
b = Rectangle(0.25, 0.25, 0.75, 0.75)
print(a&b)
# Rectangle(0.25, 0.25, 0.75, 0.75)
print(list(a-b))
# [Rectangle(0, 0, 0.25, 0.25), Rectangle(0, 0.25, 0.25, 0.75), Rectangle(0, 0.75, 0.25, 1), Rectangle(0.25, 0, 0.75, 0.25), Rectangle(0.25, 0.75, 0.75, 1), Rectangle(0.75, 0, 1, 0.25), Rectangle(0.75, 0.25, 1, 0.75), Rectangle(0.75, 0.75, 1, 1)]

# 4.
b = Rectangle(5, 5, 10, 10)
print(a&b)
# None
print(list(a-b))
# [Rectangle(0, 0, 1, 1)]

# 5.
b = Rectangle(-5, -5, 10, 10)
print(a&b)
# Rectangle(0, 0, 1, 1)
print(list(a-b))
# []

Intersection is based on SFML's implementation. It is proven correct and is not interesting to explain.
The difference, however, was a lot of fun to make.
Consider the following cases and compare them with corresponding examples at the bottom of the code. The method may return from 0 to 8 rectangles!

It works by finding all the vertical (xs) and horizontal (ys) lines that go through our rectangle (all the black and grey lines on the picture).
The coordinate sets are turned into sorted lists and taken pairwise ([a, b, c] becomes [(a, b), (b, c)]).
The product of such horizontal and vertical segments gives us all the rectangles that we divided the original one into by these lines.
All that remains is to yield all of these rectangles except the intersection.

A: For the complete program the Rectangle class was used in and as a practical example of its usage:
# The robots have requested your help setting up a new base on the
# island. They need you to define the visibility of a building from the
# southern edge of the base. To help you out, you have been given a map
# of the buildings in the complex. The map is an orthogonal projection
# of each of the buildings onto a horizontal plane. It is oriented on a
# rectangular coordinate system so that the positive x-axis points east
# and the positive y-axis points north. No two buildings in the map
# overlap or touch. Each of the buildings have perfectly rectangular
# sides and are aligned from north to south and from east to west. The
# map is a list of buildings. Every building is presented as the list
# with coordinate of south-west corner, coordinate of north-east corner
# and height - [Xsw, Ysw, Xne, Yne, height]. We need to determinate how
# many of the buildings are visible from the area just south of the base
# (excluding the angle of vision, just using projection.) See the
# illustration below.

# Input: Building coordinates and heights as a list of lists. The
# coordinates are integers. The heights are integers or floats.

# Output:The quantity of visible buildings as an integer.

# Example:
# checkio([
#     [1, 1, 4, 5, 3.5],
#     [2, 6, 4, 8, 5],
#     [5, 1, 9, 3, 6],
#     [5, 5, 6, 6, 8],
#     [7, 4, 10, 6, 4],
#     [5, 7, 10, 8, 3]
# ]) == 5 #"First"
# checkio([
#     [1, 1, 11, 2, 2],
#     [2, 3, 10, 4, 1],
#     [3, 5, 9, 6, 3],
#     [4, 7, 8, 8, 2]
# ]) == 2 #"Second"
# assert checkio([
#     [1, 1, 3, 3, 6],
#     [5, 1, 7, 3, 6],
#     [9, 1, 11, 3, 6],
#     [1, 4, 3, 6, 6],
#     [5, 4, 7, 6, 6],
#     [9, 4, 11, 6, 6],
#     [1, 7, 11, 8, 3.25]
# ]) == 4 #"Third"

# How it is used: This concept is useful for image recognition systems
# and graphical systems. When rendering of 3D model you should determine
# the visibility of the surfaces. This concept also can be applied in
# architecture and city planning, allowing you to plan out which sides
# of a building will receive sunlight, or if a building will block
# natural light in another building.

# Precondition: 0 < |buildings| < 10> 10
# ∀ x ∈ coordinate : x is an integer; 0 ≤ x ≤10
# ∀ h ∈ heights : x is an integer or a float; 0 < h ≤20

################################################################################

from itertools import combinations, product, starmap, tee
from pprint import pprint
from random import randint

################################################################################

TESTS = {
    "0. Basics": [
        #First
        {
            "input":
                [
                    [1, 1, 4, 5, 3.5],
                    [2, 6, 4, 8, 5],
                    [5, 1, 9, 3, 6],
                    [5, 5, 6, 6, 8],
                    [7, 4, 10, 6, 4],
                    [5, 7, 10, 8, 3]
                ],
            "answer": 5,
            "explanation": [5, 1, 3, 4, 0, 2]
        },
        #Second
        {
            "input":
                [
                    [1, 1, 11, 2, 2],
                    [2, 3, 10, 4, 1],
                    [3, 5, 9, 6, 3],
                    [4, 7, 8, 8, 2]
                ],
            "answer": 2
        },
        #Third
        {
            "input":
                [
                    [1, 1, 3, 3, 6],
                    [5, 1, 7, 3, 6],
                    [9, 1, 11, 3, 6],
                    [1, 4, 3, 6, 6],
                    [5, 4, 7, 6, 6],
                    [9, 4, 11, 6, 6],
                    [1, 7, 11, 8, 3.25]
                ],
            "answer": 4
        },
        #Alone
        {
            "input":
                [
                    [0, 0, 1, 1, 10]
                ],
            "answer": 1
        },
        #Shadow
        {
            "input":
                [
                    [2, 2, 3, 3, 4],
                    [2, 5, 3, 6, 4]
                ],
            "answer": 1
        },
    ],
    "1. Extra": [
        #H1
        {
            "input":
                [
                    [1, 1, 3, 3, 20],
                    [3, 4, 5, 6, 10],
                    [5, 1, 7, 3, 20],
                    [1, 7, 7, 9, 20]
                ],
            "answer": 4
        },
        #H2
        {
            "input":
                [
                    [1, 1, 3, 3, 20],
                    [3, 4, 5, 6, 20],
                    [5, 1, 7, 3, 20],
                    [1, 7, 7, 9, 20]

                ],
            "answer": 3
        },
        #H3
        {
            "input":
                [
                    [0, 1, 1, 2, 2.5],
                    [0, 3, 1, 4, 3.5],
                    [0, 5, 1, 6, 1.5],
                    [3, 0, 4, 2, 30],
                    [5, 0, 6, 2, 2],
                    [7, 0, 8, 2, 2],
                    [4, 3, 8, 4, 2],
                    [4, 5, 5, 6, 1],
                    [7, 5, 8, 6, 3]
                ],
            "answer": 7
        },
        #H4
        {
            "input":
                [
                    [0, 0, 10, 1, 10],
                    [3, 3, 4, 4, 1],
                    [5, 5, 6, 6, 1],
                    [7, 7, 8, 8, 1]
                ],
            "answer": 1
        },
    ],
    "2. Random": [
        #Half-Random
        {
            "input":
                [
                    [0, 0, 10, 1, 10],
                    [3, 3, 4, 4, randint(1, 9)],
                    [5, 5, 6, 6, randint(1, 9)],
                ],
            "answer": 1
        },

        #Half-Random
        {
            "input":
                [
                    [1, 1, 2, 2, 1],
                    [randint(3, 5), randint(3, 5), randint(6, 8), randint(6, 8), 1]
                ],
            "answer": 2
        },
    ]
}

################################################################################

def test():
    for category, tests in sorted(TESTS.items()):
        for test in tests:
            i, a = test['input'], test['answer']
            o = checkio(i)
            if o != a:
                print('Category:', category)
                print('  Input:')
                pprint(i, indent=8)
                print('  Output:', o)
                print('  Answer:', a)

def checkio(buildings):
    buildings = sorted(starmap(Building, buildings), key=lambda b: b.z)
    for a, b in combinations(buildings, 2):
        if a.seen:
            a.cover(b)
    return sum(b.seen for b in buildings)

################################################################################

class Building:

    def __init__(self, x1, y1, x2, y2, height):
        self.rect = [Rectangle(x1, 0, x2, height)]
        self.z = min(y1, y2)

    def __str__(self):
        return 'Z = {}; {}'.format(self.z, self.rect)

    def cover(self, other):
        for s in self.rect:
            other.rect = list(flatten(o - s for o in other.rect))

    @property
    def seen(self):
        return bool(self.rect)

def flatten(iterable):
    if isinstance(iterable, Rectangle):
        raise TypeError()
    for item in iterable:
        try:
            yield from flatten(item)
        except TypeError:
            yield item

################################################################################

class Rectangle:

    __slots__ = '__x1', '__y1', '__x2', '__y2'

    def __init__(self, x1, y1, x2, y2):
        self.__setstate__((min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)))

    def __repr__(self):
        return '{}({})'.format(type(self).__name__, ', '.join(map(repr, self)))

    def __eq__(self, other):
        return self.data == other.data

    def __ne__(self, other):
        return self.data != other.data

    def __hash__(self):
        return hash(self.data)

    def __len__(self):
        return 4

    def __getitem__(self, key):
        return self.data[key]

    def __iter__(self):
        return iter(self.data)

    def __and__(self, other):
        x1, y1, x2, y2 = max(self.x1, other.x1), max(self.y1, other.y1), \
                         min(self.x2, other.x2), min(self.y2, other.y2)
        if x1 < x2 and y1 < y2:
            return type(self)(x1, y1, x2, y2)

    def __sub__(self, other):
        intersection = self & other
        if intersection is None:
            yield self
        else:
            x, y = {self.x1, self.x2}, {self.y1, self.y2}
            if self.x1 < other.x1 < self.x2:
                x.add(other.x1)
            if self.y1 < other.y1 < self.y2:
                y.add(other.y1)
            if self.x1 < other.x2 < self.x2:
                x.add(other.x2)
            if self.y1 < other.y2 < self.y2:
                y.add(other.y2)
            for (x1, x2), (y1, y2) in product(pairwise(sorted(x)),
                                              pairwise(sorted(y))):
                instance = type(self)(x1, y1, x2, y2)
                if instance != intersection:
                    yield instance

    def __getstate__(self):
        return self.x1, self.y1, self.x2, self.y2

    def __setstate__(self, state):
        self.__x1, self.__y1, self.__x2, self.__y2 = state

    @property
    def x1(self):
        return self.__x1

    @property
    def y1(self):
        return self.__y1

    @property
    def x2(self):
        return self.__x2

    @property
    def y2(self):
        return self.__y2

    @property
    def width(self):
        return self.x2 - self.x1

    @property
    def height(self):
        return self.y2 - self.y1

    intersection = __and__

    difference = __sub__

    data = property(__getstate__)

def pairwise(iterable):
    "s -> (s0, s1), (s1, s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

################################################################################

if __name__ == '__main__':
    test()


text:
Q: Checking if an NSURL is instantiated in Swift vs. Objective-C I'm presently taking an iOS development course. As an assignment, I'm tasked with enabling iCloud on a project. I've found Tim Roadley's post to be helpful in explaining the process. The wrinkle: I've built my project in Swift.
In particular, one of the "checks" Mr. Roadley built in to check if there's an instance of the iCloud doesn't translate well to Swift. I'm trying to test if there's an instance of an NSURL called iCloud that's instantiated; if so, do one thing, if not do another.
From Mr. Roadley's tutorial:
            NSURL *iCloud = [fileManager URLForUbiquityContainerIdentifier:nil];

            if (iCloud) {

                NSLog(@"iCloud is working");

                // a bunch of code

                } else {
                NSLog(@"iCloud is working");

                // a bunch of code

                }

So I tried to convert that statement to Swift, as follows:
        let iCloud: NSURL = fileManager.URLForUbiquityContainerIdentifier(nil)!

        // TODO: having trouble "swiftifying" this line
        if (iCloud) {
            println("iCloud is working!")
        } else {
            println("iCloud is NOT working!")
        }

The compiler says this: Type 'NSURL' does not conform to protocol 'BooleanType'
What obvious thing am I missing?
Edit:
Thank you all for such fantastic, fast responses. They are greatly appreciated and I've learned something here.

A: You can check if it's equal to nil, or you can use the if let to unwrap it if it exists. fileManager.URLForUbiquityContainerIdentifier(nil) returns an optional NSURL, so you handle that as such:
Swift 3+
if let cloudURL = fileManager.url(forUbiquityContainerIdentifier: nil) {
    print("iCloud is working!")
} else {
    print("iCloud is NOT working!")
}

Older Versions
let iCloud = fileManager.URLForUbiquityContainerIdentifier(nil) // Remove the "!", and this should return an optional

if iCloud != nil {
    println("iCloud is working!")
} else {
    println("iCloud is NOT working!")
}

or with if let:
if let iCloud = fileManager.URLForUbiquityContainerIdentifier(nil) {
    // exists
} else {
    // doesn't exist
}

A: This line of code will crash your application if fileManager.URLForUbiquityContainerIdentifier doesn't succeed.
let iCloud: NSURL = fileManager.URLForUbiquityContainerIdentifier(nil)!

In Objective-C, this method returns either a URL or nil. In Swift, there are no nil objects. Therefore the method returns an optional URL. By using the ! you force that optional URL to be unwrapped. Unlike Objective-C, you don't get a valid URL or nil, you get a valid URL or a crash.
The variable iCloud is therefore an NSURL*, and it is guaranteed to be not nil (because you would have crashed). There is no point checking whether iCloud is nil or not, because it can't be nil.
If you remove the ! then iCloud becomes an optional NSURL*. In that case, you can check whether it has a value by checking
if (iCloud != nil)

The syntax
if (iCloud)

is illegal. An if statement requires a boolean value, and Swift doesn't just convert everything to a boolean value (it was legal at some point, but then people figured out that optional booleans were a nightmare if this was allowed).

A: In most cases the best tool for this is if-let:
if let iCloud = fileManager.URLForUbiquityContainerIdentifier(nil) {
    println("iCloud is working!") // And you can access iCloud here
} else {
    println("iCloud is NOT working!") // And you don't need iCloud here
}

Of course, if these are very long, you should likely move them into their own functions, and have the "can access" function take a full NSURL rather than an optional one. That way you don't have lots of code nested inside of an if. But beyond that, if-let is the normal tool for this kind of problem.


text:
Q: Newlines in Spreadsheet ML when read by Excel I'm trying to write a XSLT to produce a Spreadsheet ML to be further read by Excel and run into a problem with newlines. I need to add a newline to cell data. I made a sample in Excel to check the Excel idea of newline and got the following:
<Data>abc
def</Data>

Here the
 reference is a newline and Excel understands it just fine when it reads the file back. I try to produce the same with XSLT, but, naturally, I get a true 0x0A (LF) character instead, so my XML looks so:
<Data>abc
def</Data

This doesn't seem to agree with Excel way to represent newlines and when I open the file in Excel I get no newline.
I tried to research the problem, but got nothing except the following short discussion which doesn't really give a solution and suggests it may be a bug in Excel. (UPDATE: As far as I understand this is what the specs call "accidents of encoding" and an XML parser must not rely on them, while Excel does.)
Is there a way to work around this somehow and get a literal
 in output instead of the LF character? Or maybe solve this in another way?

A: Yes, Excel has its own way of distinguishing between a LF character and a character reference
 to that character.
I think with XSLT 1.0 if you want to force a character reference then doing <xsl:text disable-output-escaping="yes"><![CDATA[
]]></xsl:text> is the brute force way.


text:
Q: How to get the correct result in the sql query? I want an sql query to return the following data:
DES_EVENT | DATE_EVENT | INSCRIBED_PARTICIPANTS

And my Tables are (other columns are hidden)
**EVENT**
ID
DES_EVENT
DATE_EVENT

**EVENT_ACCESS**
NAME
EVENT_ID

**PARTICIPANT**
EVENT_ID

NOTE: The table participant registers every event in which a participant is enrolled.
I want to know what events a given user organized and how many participants were enrolled.
I've tried to do the following query:
SELECT
e.des_event,
e.date
FROM
event e,
event_access ea
WHERE
ea.name = ?
AND
ea.event_id = e.id

with this query I can not get the number of participants. So I tried to do the following query:
SELECT
e.des_event,
e.date
FROM
event e,
event_access ea,
participant p
WHERE
ea.name = ?
AND
ea.event_id = e.id
AND
p.event_id = ea.event_id

and the rows of each event are repeated for each participant enrolled on this event, but I want to get this numbers of replicates in another column in the result of the sql like I put on the top of the question.
If I use the count() function the oracle returns an error

(ORA-00937: not a single-group group function)

How can I get the correct results?

A: If I understand you, you want
SELECT e.des_event,
       e.date,
       count(*) num_participants
  FROM event e,
       event_access ea,
       participant p
 WHERE ea.name = ?
   AND ea.event_id = e.id
   AND p.event_id = ea.event_id
 GROUP BY e.ddes_event, e.date

If that is not what you want, can you post a bit of sample data and post the results that you are looking for?  Describing the results like you've done is great but some concrete test cases may help clarify things.

A: It sounds like you want this:
select e.des_event,
  e.date_event,
  p.NumberOfParticipants
from event e
inner join event_access ea
  on e.id = ea.event_id
inner join
(
  select count(*) NumberOfParticipants, event_id
  from participant
  group by event_id
) p
  on ea.event_id = p.event_id
where ea.name = ?


text:
Q: Does this double integral converge? I'm investigating the following double integral:
$$\displaystyle \int_{|k| \geqslant \rho} \int_{|\alpha| \geqslant \rho} \frac{J_{1}^{2}(|k - \alpha|)}{|k-\alpha|^2} \ \mathrm{d}\alpha \ \mathrm{d}k,$$
where $\rho \gg 1$ is some (very) large constant, $k \neq 0$ is a vector in $\mathbb{R}^2$, $\alpha \in \mathbb{R}^2$, $|\cdot|$ denotes the Euclidean norm on $\mathbb{R}^2$, and $J_{\nu}$ denotes the Bessel function of the first kind.
Note that, for sufficiently large, positive $z$, we have $|J_{\nu}(z)| \leqslant C_{\nu}|z|^{-1/2}$. This lets us bound the integral by
$$\displaystyle \int_{|k| \geqslant \rho} \int_{|\alpha| \geqslant \rho} \frac{1}{|k-\alpha|^3} \ \mathrm{d}\alpha \ \mathrm{d}k.$$
I would like to know whether or not this integral converges for any $\rho$ sufficiently large. I suppose this could be done by making the substitution $\tau = |k - \alpha|$, but I'm not sure how the limits of the integrals (particularly the lower limits) behave under this change of coordinates. Can anyone help?


text:
Q: How can I load data from a json file, containing array of arrays and not objects into a pyspark dataframe? I've tried using the following code after looking at https://stackoverflow.com/a/50969995 but I've understood that createDataFrame from the answer is different compared to spark.read.json and cannot be used in same way.
import findspark
findspark.init('/home/myuser/softwareInstallations/spark-3.1.1-bin-hadoop2.7')
import pyspark

from pyspark.sql import SparkSession
from pyspark.sql.types import StructField, StructType, IntegerType, StringType, ArrayType, FloatType

spark = SparkSession.builder.appName('Basics').getOrCreate()
data_schema = StructType([StructField('col1', IntegerType(), False),
                StructField('col2', IntegerType(), False),
                StructField('col3', FloatType(), False)])

df1 = spark.read.json('myfile.json', schema=data_schema)
df1.printSchema()
df1.show()

The answer link I shared demonstrated how to get array of 2 length arrays into df. How could I do the same for a data in a file. My data looks like this in the myfile.json.
[
  [58808,2,0.103],
  [58807,2,0.77345],
  [58805,1,0.05],
  [58804,4,0.58475]
]

I'm new to python and pyspark guys, hopefully you wont mistake my lack of understanding as laziness XD.

A: Your sample file contains multi-line JSON strings. In Spark when reading JSON there are two options supported and you have to use option("multiline", "true"):

*

*single line mode - splittable

*multi-line mode - non-splittable

from pyspark.sql import SparkSession

spark = (
    SparkSession.builder.master("local[*]").getOrCreate()
)
multiline_df = spark.read.option("multiline", "true").json(
    "myfile.json"
)
multiline_df.printSchema()
multiline_df.show()


text:
Q: Can't get the Rest Post response in Jquery Ajax post call I am calling the Rest call using the Ajax post method but i get the below error or response.
{"readyState":0,"status":0,"statusText":"error"}

Even i enable the cors($.support.cors = true; ) and crossDomain (crossDomain: true (add in headers)).
Here is the sample request:-

function() {
        $.support.cors = true;
        var evergentData = {
        "UpdateContactRequestMessage":{
         "channelPartnerID":"123456",
       "email":"greg@gmail.com",
       "firstName":"greg",
       "lastName":"chappel",
       "externalId":"GC123",
       "sessionToken":"f53095854bb230996f54fe32ed5a63f68c7718c7"
        }
      };

      //GetProducts();

      jQuery.ajax({
        type: 'POST',
        url: 'url for rest api call',
        contentType: "application/json",
        Accept: "application/json; charset=utf-8",
        dataType: 'json',
        data: evergentData,
        //data: JSON.stringify(evergentData),
        crossDomain: true,
        processData: true,
        headers: { 'access-control-allow-origin': '*',
        },
         success: function(resp){
             // we have the response
             alert("Server said123:\n '" + resp + "'");
           },
           error: function(e){
             alert('Error121212: ' + e);
             alert(e.toString());
             console.log('my message' + e);
             console.log('tables: ' + JSON.stringify(e));
           }

      });
    };

But i tested this Restapi call in the 'postman' google chrome extension i got the response(successfully got the response).

Here is the response headers:-
access-control-allow-headers → client_type, content-type, accept, accept-language, auth_token_base64, appID, accept-encoding, content-length, x-requested-with

access-control-allow-methods → POST, GET, OPTIONS, DELETE
access-control-allow-origin → *
allow → GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
content-length → 92
content-type → application/json
x-frame-options → sameorigin
x-webobjects-loadaverage → 0
Anyone help me why i didn't get response from rest api call in JqueryAjax post calls.
Thank's advance.

A: It is important to understand that access-control-allow-origin': '*' in REQUEST header does nothing.
The Access-Control-Allow-Origin header must be in the RESPONSE header of the service you are calling. So the service regulates who is allowed to call the resource, thus service must add your app URL to it's RESPONSE Access-Control-Allow-Origin header.
Also note that wildcard * does not work for resources accessed over HTTPS. For resources over HTTPS ONLY absolute paths are valid.
Why Postman works? Cause it ignores the headers and policies while browser does not.
More reading:

*

*https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS


text:
Q: Install seems to hang, but I'm not sure I am trying to install Ubuntu on an old computer that had Windows XP on it.
After struggling with why it wouldn't boot from the DVD, I ran across the solution where you typed help into the prompt  and that worked for me.
I took most of the defaults and chose to overwrite XP and only install Ubuntu.
It was painfully slow.  I attribute that to booting from the DVD.  At one point after I had answered all the questions and the bar at the bottom said "copying files" for quite a while, the install window simply disappeared.  My mouse icon is still a swirly and has been for hours.  The menu bar at the top of the screen is not functional so I can't even gracefully shutdown.
If I do shut down with a control/alt/delete and try to start without the DVD, it hangs and never comes close to starting.
I've repeated these steps several times.  What is going on????
Thanks,
dogulas

A: I've recently had installation problems during a 12.04 installation process on an older machine. I found that installing from the "alternative install CD " which will give you a text based installer, I could get it done without hiccups
http://releases.ubuntu.com/precise/


text:
Q: Injective homomorphism of $\pi_1$ of genus $3$ surface to $\pi_1$ of genus $2$ surface. Let $S$ be a surface of genus $2$, and let $S'$ be a surface of genus $3$.
What is an injective homomorphism of $\pi_1(S')$ into $\pi_1(S)$?

A: The two to one covering $p:S' \to S$ defined in the answer to your previous question induces a homomoprhism
$$ p_* : \pi_1(S') \to \pi_1(S).$$
This is injective: see here


text:
Q: Zeroing of the last byte with sscanf() on Arduino Here is a strange issue with Arduino function sscanf(). It zeroes the last byte of scanned integer value (int, long) if 1-byte value (bool, byte, char) follows it.
int someInt;
byte someByte;

void setup() {
  Serial.begin(9600);

  sscanf("10000 10", "%d %d", &someInt, &someByte);
  Serial.println(someInt); // 9984 (0x2700 not 0x2710)
  Serial.println(someByte); // 10

  sscanf("7FFF F", "%x %x", &someInt, &someByte);
  Serial.println(someInt, HEX); // 7F00 (not 7FFF)
  Serial.println(someByte, HEX); // F
}

void loop() {
  // Some code what uses someInt and someByte
}

If someInt declared in setup() all is OK.
I tasted it on two different Arduinos and result was the same. Why does it happen?

A: It's Illegal:
 sscanf(buf, "%x", /* byte*/ &val )

sscanf family is not typesafe. the Programmer must control the code (printf family is dangerous too - sscanf is even more).
The 3rd argument (and those following, if there's more than one %d or %X) must be an adress(es) of integer(s). Integer in the sense of "natural on the platform", here 2 byte.
Your idea can be written as follows:
int someInt, wrkInt;
byte someByte;

void setup() {
  Serial.begin(9600);

  sscanf("10000 10", "%d %d", &someInt, &wrkInt);  // %X too, rule is the same
  someByte = wrkInt;
...
}


text:
Q: How to solve "All hosts are taken by other resources" on Google Cloud? I currently have a Kubernetes cluster running on GCP. In this cluster I have a working NGINX Ingress, but now I'm trying add a certificate to this by using cert-manager.
Everything works fine except the ACME challenge.
When I do a kubectl describe challenge I get the following:
Status:
  Presented:   true
  Processing:  true
  Reason:      Waiting for HTTP-01 challenge propagation: failed to perform self check GET request

When the acme challenge creates a solver service I get the follow error message on GCP:
"All hosts are taken by other resources"

Image of the error I'm getting in google cloud
I have tried to create a Issuer and ClusterIssuer but the same problem keeps popping up.

A: After trying to solve the issues and browsing the web, I have figured out the solution.
It is possible to add the following annotation:
annotations:
  acme.cert-manager.io/http01-edit-in-place: "true"

After adding this line to my Ingress resource everything seemed to work perfectly.
When this annotation is not passed in, cert-manager will create an extra Ingress for the acme challenge
See: Cert-manager, using an Ingress


text:
Q: How can I get Azure Devops API to return the clauses of a query? I'd like to get use the Azure DevOps API to get a specific query and modify it. My plan was to get the Get Query API, and add a new clause. However when I try to do this using the Azure DevOps C# SDK, I get null clauses. There is a read-only dictionary with a "wiql" url value, and when I load that up I see the results, not the query.
Is there a way for me to see the specific clauses in a query?
in C#, my code is specifically:
WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>();
var query = await workItemTrackingClient.GetQueryAsync(c_projectName, "<queryIdGuid>");

A: If you want to get wiql, you have to use expand parameter. Example:
QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(c_projectName, queryPath, QueryExpand.Wiql).Result;

The base rest API: Queries - Get (QueryExpand)


text:
Q: Unable to append JavaScript elements to Div I am trying to create a few elements dynamically and then want to append it to a div as child elements.
I am doing the same for other two divs but for the third one it is not appending rather it disturbs the already present static html divs too.
HTML:

    <input id="codes_Input" onkeyup="filter_category_Function()" type="text" placeholder="" style="position:relative; width:95%; border:1px solid #E5E5E5; margin-left:2.5%;margin-top:1%;border-radius:5px;"/>

JavaScript elements:
        var div = document.createElement("div");
        div.style.width = "100%";
        div.style.height = "10%";
        div.style.position = "relative";
        div.id = "code-" + obj.ID;
        //div.className = "drop_down";
        //div.style.borderBottom = "1px solid #F3F6F8";

        var input = document.createElement("INPUT");
        input.setAttribute("type", "checkbox");
        input.style.width = "5%";
        input.style.height = "60%";
        input.style.top = "12%";
        input.style.position = "absolute";
        input.id = "code-check-" + i;

        input.addEventListener("click", function()
        {
            func(obj.ID);

        });

        var label_input = document.createElement("LABEL");
        label_input.id = "code-" + obj.Name;
        label_input.style.position = "relative";
        label_input.style.top = "-15%";
        label_input.style.left = "10%";
        label_input.style.marginBottom = "1%";
        label_input.setAttribute("for", input);
        label_input.style.fontFamily = "Roboto";
        label_input.style.fontSize = "11px";
        label_input.style.color = "#000";

        var label_Text = document.createTextNode(obj.Name);
        label_input.appendChild(label_Text);

        div.appendChild(input);
        div.appendChild(label_input);
        $('#dropdow_list_codes').append(div);

A: Your code is working. I just changed the assignment of the for attribute for the label to label_input.htmlFor = input.id; (you had just 'input' which is an object, not a string).
Apart from that i don't know why you give 'obj.ID' to func(), since it is always the same value from the last iteration in the for loop. In my example below i changed it to func(this.parentNode.id); because you gave 'obj.ID' to the containing div as 'id'.
Working example:

var inputs = [
    {
        ID: "myID",
        Name: "myRadio"
    },
    {
        ID: "yourID",
        Name: "yourRadio"
    },
    {
        ID: "hisID",
        Name: "hisRadio"
    },
    {
        ID: "ourID",
        Name: "ourRadio"
    }
];

function func(id) {
    alert(id);
}

for (i = 0; i < inputs.length; i++) {

    var obj = inputs[i];

    var div = document.createElement("div");
    div.style.width = "100%";
    div.style.height = "10%";
    div.style.position = "relative";
    div.id = "code-" + obj.ID;

    var input = document.createElement("INPUT");
    input.setAttribute("type", "checkbox");
    input.style.width = "5%";
    input.style.height = "60%";
    input.style.top = "12%";
    input.style.position = "absolute";
    input.id = "code-check-" + i;

    input.addEventListener("click", function()
    {
        func(this.parentNode.id);
    });

    var label_input = document.createElement("LABEL");
    label_input.id = "code-" + obj.Name;
    label_input.style.position = "relative";
    label_input.style.top = "-15%";
    label_input.style.left = "10%";
    label_input.style.marginBottom = "1%";
    label_input.htmlFor = input.id;
    label_input.style.fontFamily = "Roboto";
    label_input.style.fontSize = "11px";
    label_input.style.color = "#000";

    var label_Text = document.createTextNode(obj.Name);

    label_input.appendChild(label_Text);
    div.appendChild(input);
    div.appendChild(label_input);
    $('#dropdow_list_codes').append(div);

}

    <input id="codes_Input" onkeyup="filter_category_Function()" type="text" placeholder="" style="position:relative; width:95%; border:1px solid #E5E5E5; margin-left:2.5%;margin-top:1%;border-radius:5px;"/>


text:
Q: jquery.validate lost on ajax replacement and only showing last error I am using jquery.validate in MVC 2 with MicrosoftMvcJQueryValidation.  I have data annotations on my model which is then being translated into jquery validators.  I am using a modification to MicrosoftMvcJQueryValidation as outlined by Soe Tun to allow my error messages to appear in a validation summary instead of beside the controls.
When the page loads, everything works as expected.  The problem is that I am using ajax forms with replace mode to rewrite the form. When I do this, I lose all of my client side validation.
Validation still happens server side, and the fields that have errors are correctly being given the css classes to change their style.  However, only the last error message is being shown in my validation summary.
The controller isn't anything special.  If the model is valid, do work, otherwise return the same model back into the view.
Here's a sample of my ajax form
<% using (Ajax.BeginForm("AddCreditCard", "Dashboard",
       new { },
       new AjaxOptions() {
           HttpMethod = "Post",
           InsertionMode = InsertionMode.Replace,
           UpdateTargetId = "quickpay-wrapper",
           OnSuccess = "newPaymentSetup",
           LoadingElementId = "loading-pane"
            }, new { id="new-credit-card-form" })) { %>

Here is the modified javascript.
jQuery.validator.addMethod("regex", function(value, element, params) {
    if (this.optional(element)) {
        return true;
    }

    var match = new RegExp(params).exec(value);
    return (match && (match.index == 0) && (match[0].length == value.length));
});

// glue

function __MVC_ApplyValidator_Range(object, min, max) {
    object["range"] = [min, max];
}

function __MVC_ApplyValidator_RegularExpression(object, pattern) {
    object["regex"] = pattern;
}

function __MVC_ApplyValidator_Required(object) {
    object["required"] = true;
}

function __MVC_ApplyValidator_StringLength(object, maxLength) {
    object["maxlength"] = maxLength;
}

function __MVC_ApplyValidator_Unknown(object, validationType, validationParameters) {
    object[validationType] = validationParameters;
}

function __MVC_CreateFieldToValidationMessageMapping(validationFields) {
    var mapping = {};

    for (var i = 0; i < validationFields.length; i++) {
        var thisField = validationFields[i];
        mapping[thisField.FieldName] = "#" + thisField.ValidationMessageId;
    }

    return mapping;
}

function __MVC_CreateErrorMessagesObject(validationFields) {
    var messagesObj = {};

    for (var i = 0; i < validationFields.length; i++) {
        var thisField = validationFields[i];
        var thisFieldMessages = {};
        messagesObj[thisField.FieldName] = thisFieldMessages;
        var validationRules = thisField.ValidationRules;

        for (var j = 0; j < validationRules.length; j++) {
            var thisRule = validationRules[j];
            if (thisRule.ErrorMessage) {
                var jQueryValidationType = thisRule.ValidationType;
                switch (thisRule.ValidationType) {
                    case "regularExpression":
                        jQueryValidationType = "regex";
                        break;

                    case "stringLength":
                        jQueryValidationType = "maxlength";
                        break;
                }

                thisFieldMessages[jQueryValidationType] = thisRule.ErrorMessage;
            }
        }
    }

    return messagesObj;
}

function __MVC_CreateRulesForField(validationField) {
    var validationRules = validationField.ValidationRules;

    // hook each rule into jquery
    var rulesObj = {};
    for (var i = 0; i < validationRules.length; i++) {
        var thisRule = validationRules[i];
        switch (thisRule.ValidationType) {
            case "range":
                __MVC_ApplyValidator_Range(rulesObj,
                    thisRule.ValidationParameters["minimum"], thisRule.ValidationParameters["maximum"]);
                break;

            case "regularExpression":
                __MVC_ApplyValidator_RegularExpression(rulesObj,
                    thisRule.ValidationParameters["pattern"]);
                break;

            case "required":
                var fieldName = validationField.FieldName.replace(".", "_");
                if ($("#" + fieldName).get(0).type !== 'checkbox') {
                    // only apply required if the input control is NOT a checkbox.
                    __MVC_ApplyValidator_Required(rulesObj);
                }
                break;

            case "stringLength":
                __MVC_ApplyValidator_StringLength(rulesObj,
                    thisRule.ValidationParameters["maximumLength"]);
                break;

            default:
                __MVC_ApplyValidator_Unknown(rulesObj,
                    thisRule.ValidationType, thisRule.ValidationParameters);
                break;
        }
    }

    return rulesObj;
}

function __MVC_CreateValidationOptions(validationFields) {
    var rulesObj = {};
    for (var i = 0; i < validationFields.length; i++) {
        var validationField = validationFields[i];
        var fieldName = validationField.FieldName;
        rulesObj[fieldName] = __MVC_CreateRulesForField(validationField);
    }

    return rulesObj;
}

function __MVC_EnableClientValidation(validationContext) {
    // this represents the form containing elements to be validated
    var theForm = $("#" + validationContext.FormId);

    var fields = validationContext.Fields;
    var rulesObj = __MVC_CreateValidationOptions(fields);
    var fieldToMessageMappings = __MVC_CreateFieldToValidationMessageMapping(fields);
    var errorMessagesObj = __MVC_CreateErrorMessagesObject(fields);

    var options = {
        errorClass: "input-validation-error",
        errorElement: "span",
        errorPlacement: function(error, element) {
            var messageSpan = fieldToMessageMappings[element.attr("name")];
            $(messageSpan).empty();
            $(messageSpan).removeClass("field-validation-valid");
            $(messageSpan).addClass("field-validation-error");
            error.removeClass("input-validation-error");
            error.attr("_for_validation_message", messageSpan);
            error.appendTo(messageSpan);
        },
        messages: errorMessagesObj,
        rules: rulesObj,
        success: function(label) {
            var messageSpan = $(label.attr("_for_validation_message"));
            $(messageSpan).empty();
            $(messageSpan).addClass("field-validation-valid");
            $(messageSpan).removeClass("field-validation-error");
        }
    };

    var validationSummaryId = validationContext.ValidationSummaryId;
    if (validationSummaryId) {
        // insert an empty
 into the validation summary
 tag (as necessary)
        $("
").appendTo($("#" + validationSummaryId + ":not(:has(ul:first))"));

        options = {
            errorContainer: "#" + validationSummaryId,
            errorLabelContainer: "#" + validationSummaryId + " ul:first",
            wrapper: "li",

            showErrors: function(errorMap, errorList) {
                var errContainer = $(this.settings.errorContainer);
                var errLabelContainer = $("ul:first", errContainer);

                // Add error CSS class to user-input controls with errors
                for (var i = 0; this.errorList[i]; i++) {
                    var element = this.errorList[i].element;
                    var messageSpan = $(fieldToMessageMappings[element.name]);
                    var msgSpanHtml = messageSpan.html();
                    if (!msgSpanHtml || msgSpanHtml.length == 0) {
                        // Don't override the existing Validation Message.
                        // Only if it is empty, set it to an asterisk.
                        //messageSpan.html("*");
                    }
                    messageSpan.removeClass("field-validation-valid").addClass("field-validation-error");
                    $("#" + element.id).addClass("input-validation-error");
                }
                for (var i = 0; this.successList[i]; i++) {
                    // Remove error CSS class from user-input controls with zero validation errors
                    var element = this.successList[i];
                    var messageSpan = fieldToMessageMappings[element.name];
                    $(messageSpan).addClass("field-validation-valid").removeClass("field-validation-error");
                    $("#" + element.id).removeClass("input-validation-error");
                }

                if (this.numberOfInvalids() > 0) {
                    errContainer.removeClass("validation-summary-valid").addClass("validation-summary-errors");
                }

                this.defaultShowErrors();

                // when server-side errors still exist in the Validation Summary, don't hide it
                var totalErrorCount = errLabelContainer.children("li:not(:has(label))").length + this.numberOfInvalids();
                if (totalErrorCount > 0) {
                    $(this.settings.errorContainer).css("display", "block").addClass("validation-summary-errors").removeClass("validation-summary-valid");
                    $(this.settings.errorLabelContainer).css("display", "block");
                }
            },
            messages: errorMessagesObj,
            rules: rulesObj
        };
    }

    // register callbacks with our AJAX system
    var formElement = document.getElementById(validationContext.FormId);
    var registeredValidatorCallbacks = formElement.validationCallbacks;
    if (!registeredValidatorCallbacks) {
        registeredValidatorCallbacks = [];
        formElement.validationCallbacks = registeredValidatorCallbacks;
    }
    registeredValidatorCallbacks.push(function() {
        theForm.validate();
        return theForm.valid();
    });

    theForm.validate(options);
}

// need to wait for the document to signal that it is ready
$(document).ready(function() {
    var allFormOptions = window.mvcClientValidationMetadata;
    if (allFormOptions) {
        while (allFormOptions.length > 0) {
            var thisFormOptions = allFormOptions.pop();
            __MVC_EnableClientValidation(thisFormOptions);
        }
    }
});

I've tried moving the calls at the bottom in the document ready into my OnSuccess method, but that didn't do it.
So, how do I get client side validation to reinitialize when I do my ajax replace, and how do I get all my errors to show in the validation summary?  I'm hoping that if I fix one issue, it will correct the other.
EDIT:
Here's a little more info about what I am doing
Here's the wrapper
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<QuickPayModel>" %>

<% if (Model.NewPaymentMethod) { %>
    <% Html.RenderAction<DashboardController>(x => x.QuickPayNewMethod()); %>
<% } else { %>
    <% Html.RenderPartial("QuickPayMakePayment", Model); %>
<% } %>

Here is the make a payment panel.
<%= Html.ClientValidationSummary(new { id = "valSumContainer" })%>
<% Html.EnableClientValidation(); %>

<% using (Ajax.BeginForm("QuickPay", "Dashboard",
       new { },
       new AjaxOptions() {
           HttpMethod = "Post",
           InsertionMode = InsertionMode.Replace,
           UpdateTargetId = "quickpay-wrapper",
           OnSuccess = "updatePaymentHistory",
           LoadingElementId = "loading-pane"
            }, new { }))
   { %>

<%= Html.Spacer() %>

    <% ViewContext.FormContext.ValidationSummaryId = "valSumContainer"; %>

    <%: Html.LabelFor(x => x.PaymentMethods)%>

    <% if (Model.HasOnePaymentMethod) { %>
            <%: Html.DisplayFor(x => x.SelectedPaymentMethodName) %>
            <%: Html.HiddenFor(x => x.SelectedPaymentMethodId) %>

    <% } else { %>
        <%: Html.DropDownListFor(x => x.SelectedPaymentMethodId, Model.PaymentMethodsSelectList, "Select a Payment Method", new { })%>
            <%: Html.HiddenFor(x => x.SelectedPaymentMethodName)%>

    <% } %>
    <%: Html.Spacer(12, 1) %><%: Ajax.ActionLink("New Payment Method", "QuickPayNewMethod",
                                 new AjaxOptions() { InsertionMode = InsertionMode.Replace,
                                                     UpdateTargetId = "quickpay-wrapper",
                                                     OnSuccess = "newPaymentSetup",
                                                     LoadingElementId = "loading-pane"
                                 })%>
    <%: Html.ValidationMessageFor(x => x.SelectedPaymentMethodId)%>

    <%: Html.LabelFor(x => x.Amount)%>
    <%: Html.TextBoxFor(x => x.Amount, new { disabled = Model.UseInvoicing ? "disabled" : String.Empty,
    title = Model.UseInvoicing ? "the total payment amount of all selected invoices" : String.Empty,
    @class = "small" })%>
    <%: Html.ValidationMessageFor(x => x.Amount)%>

    <%: Html.LabelFor(x => x.PayDate)%>
    <%: Html.TextBox("PayDate", Model.PayDate.ToShortDateString(), new { @class = "medium" })%>
    <%: Html.ValidationMessageFor(x => x.PayDate)%>

<%= Html.Spacer() %>

    <%= FTNI.Controls.Submit("Submit Payment") %>
    <%: Html.AntiForgeryToken() %>

    <%: Html.ValidationMessage("Payment-Result")%>
<% } %>

And now my new payment method panel

New Payment Method

    <% if(Model.HasPaymentMethods) { %>

            <%: Ajax.ActionLink("Cancel", "QuickPay",
                                 new AjaxOptions() {
                                     HttpMethod = "Get",
                                     InsertionMode = InsertionMode.Replace,
                                     UpdateTargetId = "quickpay-wrapper",
                                     OnSuccess = "quickPaySetup",
                                     LoadingElementId = "loading-pane"
                                 })%>

    <% } %>

Enter the information below to create a new payment method.

    <%= Html.ClientValidationSummary(new { id = "valSumContainer" })%>
    <% Html.EnableClientValidation(); %>

Credit Card

E-Check

        <% Html.RenderPartial("NewCreditCard", Model.CreditCardModel); %>

        <% Html.RenderPartial("NewACH", Model.ACHModel); %>

Each form starts off with something like this
<% using (Ajax.BeginForm("AddCreditCard", "Dashboard",
       new { },
       new AjaxOptions() {
           HttpMethod = "Post",
           InsertionMode = InsertionMode.Replace,
           UpdateTargetId = "quickpay-wrapper",
           OnSuccess = "newPaymentSetup",
           LoadingElementId = "loading-pane"
            }, new { id="new-credit-card-form" })) { %>
    <% ViewContext.FormContext.ValidationSummaryId = "valSumContainer"; %>

Initial load works.  Any ajax replaces cause the form context to be lost and not reinitialize no matter what I do.  The form posts back, validation occurs server side.  All invalid fields are changed (css error classes added), but only the last error is shown in the summary.

A: I am going to tell you how I did just a few days ago.  Please have a look to this question for details.
In my case I was showing the content of the form using an ajax call inside a jquery dialog. When the call complete I just replace the dialog content with the content sent back from the controller.
I have modified the code inside the Microsoft script as described in my question and then called the init method on document ready. This should work for your case too...
For the second error (how do I get all my errors to show in the validation summary?) I have simply modified the code as described in the same source post you are referring to and did not experienced any problem.
Hope it helps!

A: I ended up reworking my solution so that I was no longer writing the forms to the page through callbacks.  While this was not my intended approach, it does work.  I chose to use jquery modals to display the data rather than changing the content of one area of the screen.
Ideally, I would not have to render all of the forms to the page and could call them up on demand, but it seems jquery client side validation will not wire up unless the form is present on the page load.  I am unsure of the form elements are required present on form load, but it may be a limitation I just have to deal with.
Another workaround would have been to render them all to the page and just show/hide each form through jquery.  It's not much different than using modals, but at least the validation would work.  I'd still like to see a solution where forms using validation summaries and client side jquery validation through data annotations can be written to the page through callbacks and still wired up and function correctly.


text:
Q: Writing stdout into a file while executing it on the remote host I'm writing a python script capturing FQDN from within the remote host's itself just for some sanity checks, below is the small code I'm trying to run and want to capture the stdoutout of the same into my current host from i'm running it but rather its creating files into the remote hosts, and not the one from where I'm running.
#!/usr/bin/python3
system_name = socket.gethostname()
f = open("output.txt", "a")
print("Hostname: {}".format(system_name, file=f)
f.close()

OR
#!/usr/bin/python3
system_name = socket.gethostname()
sys.stdout=open("output.txt","a")
print("Hostname: {}".format(system_name)
sys.stdout.close()

Even i tried adopting like but that didn't worked though.
name = 'mycurrenthost'
system_name = socket.gethostname()
short_sysname = socket.gethostname().split('.', 1)[0]

if short_sysname == name:
  f = open("output.txt", "a")
  print("Hostname: {}".format(system_name), file=f)
  f.close()

My example myhostlist looks like..
mydbhost1
mydbhost2
mydnhost3
mydbhost4

Below id how I'm executing the above code..
$ for host in `cat myhostlist`;do timeout -t 20 ssh -o "StrictHostKeyChecking no" "$host" "python -s" < ./myPythonScript.py;done

My output on the current console while not writing to a file...
Hostname: mydbhost1.example.com
Hostname: mydbhost2.example.com:
Hostname: mydnhost3.example.com:
Hostname: mydbhost4.example.com:

please help

A: You're running the python application on the remote host; what do you expect it to do? It runs on the remote host, it writes to files on the remote host - it can't write to files locally -it does not have access to the file system from where you initiate the ssh session.
Instead you can print out the result to stdout with just print, and then capture the standard output locally in the shell with >> output.txt after the command (>> means that the output will be appended to output.txt).


text:
Q: Visual Studio Code show intellisense one line?
Normally in Visual Studio Code program,  the "intellisense" would show a difference of options for a user to choose, based on the 1st picture. However, it only showed in one option in my program as the 2nd picture, which was an error. Does anyone have any idea how to fix it please? Thank you so much.

A: I had the same issue. When I floated over the bottom edge of the single-line intellisense block it gave me a double arrow. From there I could drag the box to the size I want. Not sure how it became single-line, but that worked for me.


text:
Q: Why should the default template-argument of a mem func be explicitly defined as illegal? In N3126 (Warning:  very large PDF) 14.1/9, there are two statements that make me confused:
#1: "A default template-argument may be specified in a template declaration."
#2: "A default template-argument shall not be specified in the template-parameter-lists of the definition of a member of a class template that appears outside of the member's class."
#1 means the following code is legal:
template <class T = int>
void f(T = T())
{}

int main()
{
    int n = f(); // equivalent to f<int>() or f(0);
    return 0;
}

#2 means the following code is illegal:
template <class T>
struct X
{
    template <class U = T>
    void f(U a = U())
    {}
};

int main()
{
    X<int> x;
    x.f(); // illegal, though I think it should be equivalent to x.f<int>() or x.f(0)
    return 0;
}

I just wonder why the latter should be explicitly defined as illegal by the standard?
What is the rationale?

A: I might be mistaken, but my understanding of #2 is that it makes the following illegal :
template<class T>
struct A
{
    void foo();
};

template<class T = int>
void A<T>::foo() { /* ... */ }


text:
Q: Autosizing controls in XAML to fit a stack panel / dock panel, where the middle control is what needs to fill the space How can I create this...
command http://img841.imageshack.us/img841/2631/46lc.jpg
in WPF.
I've read alot of other questions on using stack panel vs dock panel but can't seem to recreate what I want. This is what I currently have..
command2 http://img13.imageshack.us/img13/5374/7oft.jpg
and my xaml..
<DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="DarkGray" Grid.ColumnSpan="2" Grid.Row="1" LastChildFill="False" >
            <TextBlock Text="{StaticResource commandText}" Style="{StaticResource Heading2}" Margin="0,0,0,0" VerticalAlignment="Center" DockPanel.Dock="Left" />
            <TextBox Name="inputTextBox" VerticalAlignment="Center" HorizontalAlignment="Stretch" />
            <Button x:Name="termSend" Content="{StaticResource sendText}" Margin="0,0,0,8" DockPanel.Dock="Right" VerticalAlignment="Center" />
        </DockPanel>

A: <DockPanel>
   <TextBlock VerticalAlignment="Center" Text="Command" DockPanel.Dock="Left"/>
   <Button Content="Send" VerticalAlignment="Center" DockPanel.Dock="Right"/>
   <TextBox VerticalAlignment="Center" Margin="5"/>
</DockPanel>


text:
Q: How to loop/iterate a script to extract data for each participant I have created a script to extract, manipulate and reorganise the information for a single .csv file (which contain the outcome of an experiment for ONE participant). (i.e. each .csv file contains information for one participant)
Now I would like to iterate the same process for each .csv file (more than 200) that I have in the same folder (which contain the outcome of the experiment for each participant).
I have manage to ask R to read each .csv file in the folder like this:
temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))

Now I need to apply the iteration/loop to this entire script (that for 1 participants is as follow):
(I WILL REPOST THE FULL SCRIPT BELOW)
In summary, the main thing I need is for the loop do run the same script for each Participant in this study (in this example participant M075), I need it to do the same for M076, M077, etc etc etc
#install tidyerse package
#install.packages("tidyverse")
#Load packages
#library(tidyverse)

#Read .csv and transform to df
data1<- read.csv('M075_4.csv', header=FALSE,  stringsAsFactors = FALSE)

# Count number of correct trials (to be added later in final summary table).
Correct_responses <-sum(data1$V7 == 1)

#Select only correct responses
correct_data <- filter(data1,V7 == TRUE)  # the filter function belongs to package dplyr

#Remove extreme values (data trimming) to leave the final data for analysis (note V6 = reaction time)

final_data <- correct_data %>%
  filter(V6 > 0.200 & V6 < 2.00) %>% #first set of boundaries
  mutate(cutoff_above = mean(V6) + 2*sd(V6)) %>% #create a cutoff for 2 SDs above the mean
  mutate(cutoff_below = mean(V6) - 2*sd(V6)) %>% #create a cutoff for 2 SDs below the mean
  filter(V6 < cutoff_above & V6 > cutoff_below ) %>% #remove extreme values above 3 SDs of the mean
  select(-cutoff_above) %>% #remove the cutoff column to tidy the table up
  select(-cutoff_below) #remove the cutoff column to tidy the table up

#Correct responses left after data trimming
Correct_and_timely_responses <-sum(final_data$V7 == 1)

write.csv(final_data, #final analysis ready table
          file = " M075_final.csv", #file name to be saved as in your WD
          row.names = FALSE) #avoid a new column be created with row numbers.

#Get the mean RT data for each condition after combining the two condition columns (V3 and V8)
AB_data <- final_data %>%
  mutate(Condition = paste0(V3, V8)) %>% #combine the two elements into separate conditions
  group_by(Condition) %>% #group the analysis to get separate means for each condition
  summarise(MeanRT = mean(V6)) #get the mean RT for each condition

#transpose rows and columns
AB_data_t <- as.data.frame(t(AB_data))

# rename columns
colnames(AB_data_t)[1] <- "AvS_Incongruent"
colnames(AB_data_t)[2] <- "AvS_Congruent"
colnames(AB_data_t)[3] <- "AvC_Incongruent"
colnames(AB_data_t)[4] <- "AvC_Congruent"
colnames(AB_data_t)[5] <- "CvS_Incongruent"
colnames(AB_data_t)[6] <- "CvS_Congruent"

#define new columns to add
Correct_responses <- c(Correct_responses)
Correct_after_trimming <- c(Correct_and_timely_responses)

#add column called 'Correct'
AB_data_t$Correct_responses <- Correct_responses
AB_data_t$Correct_after_trimming <- Correct_after_trimming

#add column by Ps numner (NOT SURE HOW TO DO THIS!!! in loop)

#remove first raw
AB_data_t<-AB_data_t[-1,]

#remove first column
AB_data_t<-AB_data_t[,-1]

#save as RT data for future reference
write.csv(AB_data_t, #final data
          file = "M075_Means.csv") #file name to be saved as in your WD

Thank you in advance for any help!

A: hard to test without the data files, but you might be able to handle with a quick for loop:
temp <- list.files(pattern="*.csv")

for (i in temp) {

  read_csv(i) %>%
    filter(V7 == TRUE) %>%
    filter(V6 > 0.200 & V6 < 2.00) %>%
    mutate(cutoff_above = mean(V6) + 2*sd(V6)) %>%
    mutate(cutoff_below = mean(V6) - 2*sd(V6)) %>%
    filter(V6 < cutoff_above & V6 > cutoff_below) %>%
    write_csv(file = str_replace(i, "\\.csv$", "_final.csv"))

}


text:
Q: How to create 2 threads and to print Thread id's alternatively and numbers from 1 to 20? Code
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_t tid[2];
void* fun(void* ptr)
{
    int i = *((int *) ptr);
    int self_id;
    self_id=pthread_self();
    printf("Thread %u  ",self_id);
    printf("printing %d \n", i);
    pthread_exit(NULL);
    return NULL;
}

int main()
{
    int i=0,j=1,k;
    for(j=1;j<21;)
    {
        for(i=0;i<2;i++)
        {
            pthread_create(&tid[i],NULL,fun,&j);
            sleep(1);
            j++;
        }

    }
    for(j=1;j<21;)
    {
        for(i=0;i<2;i++)
        {
            pthread_join(tid[i],NULL);
            j++;
        }
    }
        pthread_exit(NULL);
}

So if the 2 threads are t1 and t2 and their thread id's are say 1023 and 1024, then the output should be as
            Thread 1023 printing 1
            Thread 1024 printing 2
            Thread 1023 printing 3
            Thread 1024 printing 4

            and so on till printing 20

But the output of my code is
            Thread 1023 printing 1
            Thread 1024 printing 2
            Thread 1025 printing 3
            Thread 1026 printing 4

            and so on till printing 20

The thread id's are not alternating. How to make the thread id's alternate.

A: Here:
for(j=1;j<21;)
{
  for(i=0;i<2;i++)
  {
    pthread_create(&tid[i],NULL,fun,&j);
    ...

you create 20 * 2 threads, which explains the number of threads you witness.
In order to create two threads, you should only create two threads, like:
for(i=0;i<2;i++)
{
  pthread_create(&tid[i],NULL,fun,&j);
  ...

i.e., without the outer loop. Moreover, you have to modify fun() to print 10 times (so 2 * 10=20). Now the tricky part is to make fun() of first thread synchronize with second thread, if you really need to define the order of output messages. However, this kills parallelization.

PS: You need to #include <unistd.h> for sleep().

A: From the question what I can understand is, you want two threads, alternatingly printing 1 to 20.
First of all, you are spawning 40 threads, as gsamaras pointed out, because the outer loop iterates 20 times, and the inner one iterates 2 times. Therefore you have to just spawn 2 threads as pointed out by gsamaras.
Adding to it, if you want to alternate the printing, you must have some synchronisation, else the order of printing in a file (stdout in this case) is undefined. I would recommend using condition variable to alternate between the threads in this case to achieve your goal.
If you are relatively new to POSIX threads or threading, I would recommend you go through this: https://computing.llnl.gov/tutorials/pthreads/


text:
Q: iOS facebook login issue I have successfully integrated "Facebook Login" in iOS app. However there is one small issue with it's implementation.
After successfully logging in, the app should ideally display "HOME SCREEN". But instead of that app displays "LOGIN SCREEN" for 2 seconds before displaying "HOME SCREEN".
What method/s am I supposed to implement so that after successfully login via facebook app will display "HOME SCREEN" without going back to "LOGIN SCREEN"?
The facebook login code is as follows.
let loginManager = LoginManager()
loginManager.logIn([.publicProfile, .email], viewController: self)
        { (result) in
            switch result
            {
            case .failed(let error):
                print("Error")
            case .cancelled:
                print("User cancelled")
            case .success(_,_,_):
                self.getUserInfo
                    { userInfo, error in

                        let name = userInfo?["first_name"]
                        let email = userInfo?["email"]

                        let homeVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeVC") as! HomeViewController

                        homeVC.name = name as? String
                        homeVC.email = email as? String

                        self.present(homeVC, animated: true, completion: nil)

                }
            }
        }

Thanks

A: Inside the completion block make sure you do UI operations on the main thread:
let loginManager = LoginManager()
loginManager.logIn([.publicProfile, .email], viewController: self)
    { (result) in
        switch result
        {
        case .failed(let error):
            print("Error")
        case .cancelled:
            print("User cancelled")
        case .success(_,_,_):
            self.getUserInfo
                { userInfo, error in

                    // puts you back on the main thread
                    DispatchQueue.main.async(execute: {

                        let name = userInfo?["first_name"]
                        let email = userInfo?["email"]

                        let homeVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeVC") as! HomeViewController

                        homeVC.name = name as? String
                        homeVC.email = email as? String

                        self.present(homeVC, animated: true, completion: nil)
                    })

            }
        }
    }


text:
Q: Pass value from grid view to new page ASP.NET C#? I have a grid view.
I want to take the selected row from the grid view and pass on a column value in that row to a new page while storing that value in the session.
So far I know how to store it as a string from a tut, but don't know how to keep the value in int format not convert it to string.
Here is what I have in my C# code...Like I said this does write out the row as a string type I want it to remain a int.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            Int16 num = Convert.ToInt16(e.CommandArgument);
            TextBox2.Text = GridView1.Rows[num].Cells[0].Text;

        }
    }

Putting it into session will be easy. I figured out it is:
Session["customerID"] =  GridView1.Rows[num].Cells[0].Text;

So now the true question is how to keep the value in a int format.
Thanks!

A: You can not save it in int type directly.Session stores the value in object type. So you have to cast it as int.
int customerID = (int) Session["customerID"];
      // or
int customerID = Convert.ToInt32( Session["customerID"].ToString());
     // or
int customerID = int.Parse( Session["customerID"].ToString());

A: You get the value back by doing something like this:
var myInt = (int)Session["customerID"]

Session variables can store any object, not just strings. You could technically store your whole gridview object in a session variable.