text:
Q: Sum of alternating binomial-coefficient-type series Let $D,n\in \mathbb N$ with $0<D<n$, and $y>0$ is a real number.
Question: Is there a closed-form for the following alternating sequence
\begin{equation}
\sum_{k=0}^D (-y)^k {n\choose k}?
\end{equation}
This question is related to a similar question where $y=1$.
Motivation: These kind of expressions arrive in numerical schemes that I am working on.
First attempt: I tried to repeat some of the techniques from $y=1$ case. For instance, using the complex integral argument, we have
\begin{align}
\sum_{k=0}^D (-y)^k {n\choose k} &= \sum_{k=0}^D (-y)^k \oint_{0<|z|<1} \frac{(1+z)^n}{z^{k+1}}\frac{dz}{2\pi i} = \oint_{0<|z|<1} \frac{(1+z)^n}{z} \sum_{k=0}^D \left(-\frac{y}{z}\right)^k \frac{dz}{2\pi i} \\
&= \oint_{0<|z|<1} \frac{(1+z)^n}{z} \left[\frac{z+y(-y/z)^D}{z+y}\right] \frac{dz}{2\pi i} \\
&= \oint_{0<|z|<1} \frac{(1+z)^n}{z+y} \frac{dz}{2\pi i} + y(-y)^D \oint_{0<|z|<1} \frac{(1+z)^n}{z^{D+1}(z+y)} \frac{dz}{2\pi i}.
\end{align}
I don't know much about complex integrals and so don't know how to complete this argument. Any ideas?
Or are their any other techniques that will work here? Any ideas/hints are appreciated.

A: We show the difference between the variant with general $y$ and $y=1$. We use the coefficient of operator $[z^n]$ to denote the coefficient of $z^n$ in a series. This way we can write for instance
\begin{align*}
[z^k](1+z)^n=\binom{n}{k}=\oint_{0<|z|<1} \frac{(1+z)^n}{z^{k+1}}\frac{dz}{2\pi i} \tag{1}
\end{align*}

We obtain
  \begin{align*}
\color{blue}{\sum_{k=0}^D(-y)^k\binom{n}{k}}
&=\sum_{k=0}^D[z^k](1-yz)^n\tag{2}\\
&=[z^0](1-yz)^n\sum_{k=0}^Dz^{-k}\tag{3}\\
&=[z^0](1-yz)^n\frac{z^{-(D+1)}-1}{z^{-1}-1}\\
&=[z^{-1}](1-yz)^n\frac{z^{-(D+1)}-1}{1-z}\\
&=\left([z^D]-[z^{-1}]\right)\frac{(1-yz)^n}{1-z}\tag{4}\\
&\,\,\color{blue}{=[z^D]\frac{(1-yz)^n}{1-z}}\tag{5}
\end{align*}
We see in (5) that in case $y=1$ we get
  \begin{align*}
[z^D]\left.\frac{(1-yz)^n}{1-z}\right|_{y=1}=[z^D](1-z)^{n-1}=(-1)^D\binom{n-1}{D}
\end{align*}
  but there is no way to make similar simplifications with general $y$.

Comment:

*

*In (2) we apply the coefficient of operator according to (1).

*In (3) we use the rule $[z^{p-q}]A(z)=[z^p]z^qA(z)$.

*In (4) we note $\frac{(1-yz)^n}{1-z}=(1-yz)^n\sum_{j=0}^\infty z^j$ is a power series in $z$ so that the residue $[z^{-1}]$ is zero.

A: You could write it using a hypergeometric function:
$$  \left( 1-y \right) ^{n}-{n\choose D+1} \left( -y \right) ^{D+1}
{\mbox{$_2$F$_1$}(1,-n+D+1;\,D+2;\,y)}
$$


text:
Q: Using dlls written in C# in Java Project I'm working on a Java project and I'm not very familiar with using Java
I usually use C# with aforge for my computer vision projects
now I have to use Java and I want to use the aforge DLLs which are written in C#
is there a way to do this ?
Thank you

A: It is possible, but you'll need to do some work to get them calling properly. I've never done it myself, but until someone better equipped to answer the question comes along here's a few places to start.
Take a look at the JNI (Java Native Interface, google or wikipedia can tell you more), which lets you call out from Java to other languages. There seems to be a project called jni4net ( http://jni4net.sourceforge.net ) which is intended to do exactly what you want, but it's in alpha at the moment and might not be stable enough. Still it could be worth having a look.
You can also do it yourself, calling through the JNI as a C call which will then get through to the CLR eventually, but it looks like a lot of effort. I know this isn't a quick and easy solution, but it might give you a couple of places to get started. also http://www.codeproject.com/KB/cross-platform/javacsharp.aspx seemed to be a fairly good look at how to go about it.
As all of the other answers so far have said though, it's fiddly and a pain. If you can do something else instead, it will probably be worth it.

A: Have a look at Jni4Net and this stack overflow question: is there an effective tool to convert c# to java?

A: You would have to use native calls which would a) be really irritating to keep up to date and B) defeat the huge advantage of java being cross-platform.
Your best bet might be to try to find something that can convert C# to java--or better yet recode your C# code into java.
In the long run it will save you a lot of stress.

A: No sure about this possibility but your idea is not so good.
You still can use COM or hook or try ngen but this ways all are weird.
Java is very similar C# . Try to code in Java or something like stab , I think that is much easer to code in some JVM-based langue for jvm.

A: Diferent compilers dud, it's not possible. Unless You use java sharp language in visual studio, then the compilers mach.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error when Copying Query from linq to Datatable I just started working on a project that requires Linq to Sql, and I have been able to make queries and retrieve data. But right now I need to fill a DataTable with the data I am retrieving.
My first code was the following:
MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
            where cust.CustomerName != "Dante"
            orderby cust.CustomerName
            select new { Name = cust.CustomerName };

So, since I needed to copy the content of my query to a Datatable I tried this:
 IEnumerable<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
    select order;

// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();

Then, my code looks like this:
IEnumerable<DataRow> myQuery = from cust in db.Customers.AsEnumerable()
                    where cust.Name != "Dante"
                    orderby cust.Name
                    select new { Name = cust.Name };

DataTable myDataTable = myQuery.CopyToDataTable<DataRow>();

But with this code the compiler raises and error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<System.Data.DataRow>
The error is raised at the select word.
So, What am I doing wrong?? What can I do in order to avoid this conversion issue?
Hope someone can help me, thanks in advance.

A: There is a way to create a DataTable from a result other than IEnumerable<DataRow>, but it is rather involved. Implement CopyToDataTable Where the Generic Type T Is Not a DataRow.
For your case, though, I would recommend doing it the following way. Go back to your original query:
MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
            where cust.CustomerName != "Dante"
            orderby cust.CustomerName
            select new { Name = cust.CustomerName };

Then define your single field DataTable because when you eventually create a DataRow, it needs a schema to work from:
DataTable myDataTable = new DataTable();
myDataTable.Columns.Add(
    new DataColumn()
    {
        DataType = System.Type.GetType("System.String"),
        ColumnName = "Name"
    }
);

And finally, go through the results of your query and manually add the DataRows to your DataTable.
foreach (var element in query)
{
    var row = myDataTable.NewRow();
    row["Name"] = element.Name;
    myDataTable.Rows.Add(row);
}

A: The problem is exactly as the error states; your "select" clause is creating instances of an anonymous type with one member, "Name". This anonymous type is not and cannot be a DataRow, so the implicit conversion between what the query produces and the variable you want to set it into fails.
Instead, you should take this query, and for each element of the anonymous type that it returns, add the value as a new DataRow of the DataTable. You cannot just create a new DataRow from scratch; the DataRow class requires a context, namely the parent DataTable, to define the columns the DataRow should have.

A: This will do i guess
var myQuery = from cust in db.Customers.AsEnumerable()
                    where cust.Name != "Dante"
                    orderby cust.Name
                    select new { Name = cust.Name };

or try this
 string[] myQuery = db.Customers.Rows
                       .Cast<DataRow>()
                       .Where(r=>r.Name!="Dante")
                       .Orderby(r=>r.Name)
                       .Select(r=>r.Field<string>("Name"))
                       .ToArray()


text:
Q: Relation of Singleton pattern with dependency injection From here: http://www.codingwithoutcomments.com/

If you do use Singletons, try to use dependency injection instead of
  calling getInstance() from the constructor, use this:

public MyConstructor(Singleton singleton)
{
     this.singleton = singleton;
}

rather than this:

public MyConstructor()
{
     this.singleton = Singleton.getInstance();
}

At the very least, using dependency injection allows you to do some unit testing of the class by adhering to good encapsulation principles.

How is this "dependency injection"?  What is the meaning of dependency injection?
Doesn't this defeat the purpose of the Singleton pattern?
Is this supposed to be used for some time and then removed later on?

A:
How is this "dependency injection"?

"Dependency injection" means that you explicitly provide an object with references to all other objects that it depends on; that's what the first example does when it passes a reference to the constructor.
The alternative is to implicitly provide the objects that it depends on, by making them globally accessible. That's what the second example does.
The main advantage of dependency injection is that the dependency can be on an abstract interface; there's no need to tie your class to a particular concrete class, or to a particular instance of that class. This makes testing more convenient - your class can be tested in isolation, interacting with "stub" implementations of any interface that it depends on. It also makes it easier to keep track of the dependencies, since they are all explicitly stated in the code.
The main advantages of using globals are that they allow you to write slightly less code, and you don't need to worry about managing dependencies until they become a problem; when they do, you can simply abandon the project and start a new one.

Doesn't this defeat the purpose of the Singleton pattern?

That rather depends on what you think the purpose of the anti-pattern is. It certainly does remove the convenience of a globally-accessible instance; but, assuming the Singleton class does follow the anti-pattern, you still have the assurance that the object you receive is the One True Instance.

Is this supposed to be used for some time and then removed later on?

The singleton should be replaced by a normal class, passed by reference to its dependents, once you need to do things that the anti-pattern prevents (unit testing, multiple instances, subtypes, an abstract interface, etc.). There is little need to remove dependency injection once it's there; you'll only have to put it back again once you find that singletons don't meet your requirements.

A: There are no differences in the codes you provided, and that it not a dependency injection, because you are passing the singleton by value to the constructor (that's a constructor, right?).
If you have to use a singleton, then pass the object it manages to the constructor using a reference :
struct Abase
{
};
struct A : Abase // object of this type is created in the singleton
{
};

struct B
{
  B(Abase &a_) : a(a_)
  {
  }

private:
  Abase & a;
};

//...
B b( Singleton.getInstance() );
//...


text:
Q: New Automatic NuGet package resotore and NuGet.Config I'm migrating to new version of Automatic package restore as described in docs
This documents says, that .nuget folder should be removed completely. Including NuGet.Config, that contained a property, we need:
<config>
    <add key="repositoryPath" value="..\..\..\commonNugetPackages" />
  </config>

So how one should specify path where packages should be restored?
Update:
Updating to 2.8 fixed the issue. I guess it was this bug. Though it was fixed in 2.7.2 and I had 2.7.4.

A: I would keep the NuGet.Config file since you are using it to change the default packages directory.
You can delete the NuGet.exe and NuGet.targets file from the .nuget directory and remove the Import in your project files that refers to NuGet.targets.


text:
Q: Написать переход между двумя ViewController-ами Здравствуйте!
Возникла необходимость написать "руками" переход (по клику кнопки) между несколькими ViewController-ами( переход должен осуществляться при выполнении некоторого условия).

A: Swift 3
в сториборде во втором контроллере куда вы хотите перейти укажите в identity -  YourVC, где Main это название сториборда.
в зависимости от условия меня класс и соответственно меняй identity
let sb = UIStoryboard(name: "Main", bundle: nil)
let initialVC = sb.instantiateViewController(withIdentifier: "YourVC")
self.present(initialVC, animated: false, completion: nil)


text:
Q: User Cache and User Property GAS This is a google app script question. Below are the links for cache and properties functions.
https://developers.google.com/apps-script/reference/cache/cache-service#getUserCache()
https://developers.google.com/apps-script/reference/properties/properties
It says there is a function such as getUserCache for Cache and getUserProperty. However, how does the script determine the specific user for it? Meaning, how can more than 1 user access the same script if it is deployed? Also, how can you allow more than one user to use the script?

A: how does the script determine the specific user for it? : Based on the user email id
how can more than 1 user access the same script if it is deployed? : Using the web app link
how can you allow more than one user to use the script? : By sharing the web app link


text:
Q: boost serialization omit version for a wrapper How can I tell boost that for a particular structure it should not write/read a class "version" identifier?
I am writing some wrapper classes for serializing some types in a smaller fashion (like a variable length integer). If the wrapper gets a class version written the whole point of the size reduction is lost (it'll end up bigger in most cases).
For example, given integer a I'll be replacing this code:
ar & a;

with this:
ar & wrapper(a);

I see the is_wrapper trait, but I can't really find any docs on what that does, or if it might help.

A: Add
BOOST_CLASS_IMPLEMENTATION(wrapper, boost::serialization::object_serializable)

It's the documented way.


text:
Q: Find intersection by knowing a point, direction, circle position and radius (2D) #Problem
Hey I wondered how we can find the intersection between a point with a vector direction, assuming that the point is in the circle.
In Other words, how can I find where the particle will hit the circle circumference when I know the following: Circle position, radius, Particle Position and direction (velocity).
#Implementation
I am currently creating a flight radar, all flights are stored in a Queue and I need to sort the queue based on the time untill the flight leaves the cirlce (Radar Radius)
So I need to return a Point, thus I can just get the distance and calculate the time based on distance and velocity.

A: At first subtract center cordinates to simplify calculations (now circle center is coordinate origin)
x11 = x1 - x0
y11 = y1 - y0

Point position against time is
x = x11 + vx * t
y = y11 + vy * t

where vx, vy are components of velocity
Point is at circumference when
x^2 + y^2 = R^2

so
(x11 + vx * t)^2 + (y11 + vy * t)^2 = R^2
(vx^2+vy^2)*t^2 + (2*vx*x11+2*vy*y11)*t + (x11^2+y11^2-R^2) = 0

This is quadratic equation for unknown t. Solve it, find roots - none for outside moving, one for single touch case, two roots for regular intersection - larger one is needed time of intersection t_int
Substitute t into point position equations and get coordinates:
x_int = x1 + t_int * vx
y_int = y1 + t_int * vy


text:
Q: Use of word "HOW" for exclamation or praise Can I use the word "how" for praise in this way:

How they move!

I want to say that how beautifully they move. Is this a correct sentence?

A: The normal structure of an exclamatory sentence with 'How' is :

(1) How + adjective

e.g., "How beautiful!" "How nice!"

(2) How + Adjective/Adverb + Subject + Verb

e.g., "How happy (Adj) we were there!"
"How beautifully (Adv.) they move!"
However, you can omit this adverb and say :

"How they move!"


text:
Q: SendGrid Email Activity API rate limit In testing code that uses the SendGrid Email Activity API, I have received "too many messages" errors. I have examined the "rate limit" response headers and it appears that I am being limited to 10 requests per 5 minute block in the day.  That is, the first 5 minutes of every hour can have 10 requests, the next 5 minutes can have 10 requests, etc.
I asked SendGrid support about this. The first response was pretty generic, but seems to indicate that the threshold is correct and says I really should be using webhooks to get the status.  I haven't found anything in the documentation saying this and I haven't seen anything the specifies what the rate limits are.
For those of you using the Email Activity API, are you limited to 10 requests per 5 minutes? If yes, what do you do with the API?

A: Here's an snippet of what I ended up using with requests, tenacity and ratelimit:
from ratelimit import limits, sleep_and_retry
import requests
import tenacity

@sleep_and_retry
@limits(calls=2, period=60)
@tenacity.retry(
    retry=tenacity.retry_if_exception_type(requests.exceptions.HTTPError),
    stop=tenacity.stop_after_attempt(10),
    wait=tenacity.wait.wait_fixed(60),
)
def _call_api(headers, params):
    response = requests.get(
        "https://api.sendgrid.com/v3/messages",
        json={},
        headers={},
        params={},
    )
    try:
        response.raise_for_status()
    except requests.exceptions.HTTPError:
        logger.info(f"Request failed {response.headers}, retrying in 1 minute")
        raise
    return response

A: I received a response from SendGrid support that says:

Your findings are correct in that we do limit this endpoint to 10 requests per 5 minutes. This is a hard limit that we do not have the means of raising. The Email Activity Feed as well as the Email Activity API endpoint are meant for troubleshooting specific issues and attaining detailed message metadata.

A: I previously found the rate limit to be 10/5min but it appears that SendGrid have changed the rate limit to 2 requests every 60 seconds sometime in the past week. Can anyone confirm this?
I'm using the webhook to report non-delivery back to my application but I also need to use the activity API to resolve async bounce notifications. Async bounces are when a destination mail server accepts a message during the smtp session but subsequently sends a bounce notification email. When this occurs, SendGrid do not provide the detail of the bounced message in the webhook and the message is incorrectly reported as delivered in the SendGrid app. When asked, they respond that there's nothing they can do about it, even though I have explained to them how I use their activity api to resolve this.
I pay extra to use the activity API to fix a problem that they should address themselves, so I'm very frustrated that they apply such restrictive rate limits, then change them without notice.


text:
Q: Wordpress Gallery Border I'm wanting to add borders to gallery images. But in a chessboard effect so image 1, 3, 5, 7, 9... will be black and 2,4,6,8,10... will be white.
I've tried the following CSS and I've had no luck :(
#gallery-1:nth-child(odd) img {
    border: 3px solid #B8A8A8;
}
#gallery-1:nth-child(even) img {
    border: 3px solid #000000;
}

.attachment-thumbnail:nth-child(odd) {
    border: 3px solid #B8A8A8;
}
.attachment-thumbnail:nth-child(even) {
    border: 3px solid #000000;
}

Here is the HTML

Any help would be very much appreciated. Thanks!

A: Use this
.gallery-item img:nth-child(odd){}
.gallery-item img:nth-child(even){}

instead of
#gallery-1:nth-child(odd) img {
border: 3px solid #B8A8A8;}
#gallery-1:nth-child(even) img {
border: 3px solid #000000;}

I think, it may work.


text:
Q: Binomial distribution (working included) I've been working on this question but I'm not too sure if I am correct... Any feedback or advice would be much appreciated.
Question:
Suppose an aircraft has a capacity of 500 passengers. The airline that operates it 'overbooks' the plane by accepting reservations for up to 575 passengers, because it knows from experience that 5% of passengers do not check in for the flight.
a) Assuming that X, the number of passengers who check in for the flight, can be modelled by a binomial distribution, calculate the probability that one or more passengers will be denied the chance to board.
My working: We can safely use the normal approximation to the binomial with such large numbers.
mean = np = 575*0.95 = 546.25
sd = √(npq) = √(575*0.95*0.05) = 5.226
with continuity correction, > 500 becomes > 500.5
z-score = (500.5-546.25)/5.226 = -8.75
P(z> -8.75) ≈ 1
This means that for all practical persons, it is certain that one or more persons will be denied the chance to board.


text:
Q: Web App with Spring - Using properties in Service I want to load few values from a proporties files that is in the /WEB-INF/ folder.
I usually use this in my xml file when I develop a software using WebServices
<util:properties id="configProperties" location="classpath:/WEB-INF/config.properties" />

and then access to the value in Java using:
@Value("#{configProperties['clientURL']}")
private String clientURL;

public String urlClient() {
    return clientURL;
}

But it doesn't work on my webapp, it's always returning the null value.

A: WEB-INF is not on the classpath. The classpath starts from WEB-INF/classes/. So I would advise to place the properties file there (and change the location property accordingly). The service layer should not know that it serves a web application (which has WEB-INF)

A: I found the solution to my problem here:
http://codingbone.wordpress.com/2010/02/28/how-to-load-properties-files-into-spring-and-expose-to-the-java-classes/


text:
Q: Why does my URL redirect not work? I download CodeIgniter 2.1.0 and I followed the tutorial on CodeIgniter 2.1.0.
The problem is when I try to submit a form in this URL:
http://localhost/CodeIgniter/index.php/news/create

the page is redirected to this URL:
http://localhost/CodeIgniter/index.php/news/localhost/CodeIgniter/index.php/news/create

I tired many ways to change the route.php but it doesn't work. How can I fix this??
route.php
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';

This is the code for the form page:
public function create()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    $data['title'] = 'Create a news item';

    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('text', 'text', 'required');

    if ($this->form_validation->run() === FALSE)
    {
        $this->load->view('templates/header', $data);
        $this->load->view('news/create');
        $this->load->view('templates/footer');

    }
    else
    {
        $this->news_model->set_news();
        $this->load->view('news/success');
    }
}

I notice that when the form page when the page is loaded, below code segment will executed, however, the else segment never got changes to execute.
if ($this->form_validation->run() === FALSE)
    {
        $this->load->view('templates/header', $data);
        $this->load->view('news/create');
        $this->load->view('templates/footer');

    }

This is the form page, nothing special, just call the create function shown above.
create.php

Create a news item

<?php echo validation_errors(); ?>

<?php echo form_open('news/create') ?>

Title
<input type="input" name="title" />

Text
<textarea name="text"></textarea>

<input type="submit" name="submit" value="Create news item" />

</form>

This is the HTML for the form page:

<title>Create a news item - CodeIgniter 2 Tutorial</title>

CodeIgniter 2 tutorial

Create a news item

<form action="localhost/CodeIgniter/index.php/news/create" method="post" accept-charset="utf-8">
Title
<input type="input" name="title" />

Text
<textarea name="text"></textarea>

<input type="submit" name="submit" value="Create news item" />

</form>©2012

And when I press the create new item button, the URL changed to
http://localhost/CodeIgniter/index.php/news/localhost/CodeIgniter/index.php/news/create

and page shows 404 Pages Not Found

A: I found the solution, it caused by the improper base url setting.
Before my base url was: $config['base_url'] = 'localhost/CodeIgniter';
Now I changed it to
$config['base_url'] = 'http://localhost/CodeIgniter/';

and it works fine now.
Thanks for whoever tried to help:)

A: Just a suggestion, may be it can helps you:
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

Set this in your config.php file, you will never be worried about $config['base_url']. Because it will set http or https port, domain, port number (ex. 8080, 8880 etc.) and codeigniter root folder. Also it can be reused in future in your any codeigniter project. :)
you can also check this article


text:
Q: pushButton click fires twice I have some problem with pushButton. When I click on that button it seems that
it clicked two times because function addDataToCsv write same data two times
class my_first_window(QMainWindow):
    def __init__(self):
        super(my_first_window, self).__init__()
        loadUi('untitled.ui', self)
        self.setWindowTitle('My First Window')
        self.pushButton.clicked.connect(self.on_pushButton_clicked)
        self.dialog = Second()
    @pyqtSlot()
    def on_pushButton_clicked(self):
        age = int(str(self.comboBox.currentText()))
        sex = str(self.comboBox_8.currentText())
        addDataToCsv(age, sex)

I cant find any solution for this.


text:
Q: Definite integral equal to zero Can $A(s)=\int_{0}^{\infty}f(x,s)\space dx $ have any zeros if $f(x,s)≠0$ for all complex $s$? $f(x,s)$ is a holomorphic function. Intuitively I would say $A(s)$ can't have any zeroes because the "area" between the function and the x-axis isn't zero since it never crosses zero, its bounds are not equal and $f(x,s)≠0$. The issue is that I can't really prove this and therefore I can't know for sure if I'm missing something. In short, what I'm wondering is the following: Does there exist an $s$ such that $A(s)=0$, and if not, could anyone provide a proof?
Thank you.

A: This is not really well-formulated as one can easily do the following: note that $\int_{-\infty}^{\infty}ye^{-y^2}dy=0$ and the integral is absolutely convergent, while the function inside has only one finite zero at $y=0$.
Change variables $y=\ln x, y=\ln x -1$ and get absolute convergent integrals of functions $h,g$ on $[0,\infty)$, where $h(0)=h(1)=0, g(0)=g(e)=0, \int_{0}^{\infty}h(x)dx=\int_{0}^{\infty}g(x)dx=0$ and $h,g$ have no other zeroes. Then shift variables for $h$ say, so for example we now take $h_1(x)=h(x-1), x \ge 1$,while we take say $h_1(x)=(x-1)(x-\frac{1}{3}), 0 \le x \le 1$ with integral zero on $[0,1]$ too (and we can smooth it more at $1$ if we want)
Now $h_1(x)+ig(x)$ has no zero when $x \ge 0$ and then if one takes $f(x,s)=e^s(h_1(x)+ig(x))$, $f(x,s)$ is holomorphic in $s$ and nonzero anywhere and $A(s)=0$.


text:
Q: How to display events from "selectable" multiple calendars using FullCalendar React? I have a "simple" React App that allow a user to select/unselect calendars to display in a @FullCalendar/React component. The app loads a list of calendars from the server, and then the user may select or unselect calendars - and the FullCalender component should update accordingly.
Below is a simplified version on Codesandbox with simulated server fetches. You'll notice it loads correctly, but FullCalendar doesn't update as calendars are selected. In the console, you can see the data is being updated, but not re-rendered in the calendar display.

The component that is causing the issues is CalendarDisplay. When render() is called again to update the display, the events={this._fetchEvents} handle is not called. Instead I'm wondering if I should use something like events={this.state.events} but then I run into the issue of knowing what date range FullCalendar is displaying.
/**
 * Display FullCalendar componenent with events from the selected calendars
 */
class CalendarDisplay extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // not used
      events: []
    };
  }

  render() {
    console.log("Rendering FullCalendar...");

    return (
      <FullCalendar
        plugins={[dayGridPlugin]}
        initialView="dayGridMonth"
        events={this._fetchEvents}
      />
    );
  }

  _fetchEvents = (info, successCallback, failureCallback) => {
    // Loop through props.calendars to see which calendars to fetch events for
    this.props.calendars.forEach((calendar) => {
      // Fetch events for calendar if "shown" using date range from FullCalendar
      if (calendar.shown) {
        let events = fetchEventsFromServer(
          calendar.id,
          info.start.valueOf(),
          info.end.valueOf()
        );

        // Load into FullCalendar
        successCallback(events);
      }
    });
  };
}

A: It turns out the way to do this is to make use of the FullCalendar EventSource api and update the event sources after the component is mounted or updated.
A working example is at the CodeSandbox below and the relavent code is posted below as well.

class CalendarDisplay extends Component {
  calendarRef = createRef();

  componentDidUpdate(prevProps) {
    this._fetchEvents();
  }

  componentDidMount() {
    this._fetchEvents();
  }

  /**
   * The trick is to render the FulCalendar with no events
   * and use the EventSource api after the component mounts
   * or updates
   */
  render() {
    return (
      <FullCalendar
        ref={this.calendarRef}
        plugins={[dayGridPlugin]}
        initialView="dayGridMonth"
      />
    );
  }

  /**
   * Method to add/remove EventSources when the components props
   * update (Calendars are selected/unslected)
   */
  _fetchEvents() {
    // Loop through props.calendars to see which calendars are selected
    this.props.calendars.forEach((calendar) => {
      let calendarApi = this.calendarRef.current.getApi();
      let eventSource = calendarApi.getEventSourceById(calendar.id);

      // Remove if present and unselected
      if (eventSource && !calendar.shown) {
        console.log("Removing EventSource. CalendarId: " + calendar.id);
        eventSource.remove();

        // Add if selected and not present
      } else if (calendar.shown && !eventSource) {
        calendarApi.addEventSource({
          id: calendar.id,
          events: function (info, successCallback, failureCallback) {
            // Here is where you would place your ajax() call
            let events = fetchEventsFromServer(
              calendar.id,
              info.start.valueOf(),
              info.end.valueOf()
            );
            // Load into FullCalendar
            successCallback(events);
          }
        });
      }
    });
  }
}


text:
Q: Testing API in Laravel 5.3 I am new in Laravel and I am a bit confused on how to test my api in 5.3.  I read the docs and I saw this kind of examples but I don't know if I applied the examples correctly.  Anyway, I'm always getting an ErrorException
Error Exception
I have this one in UserTest.php
<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserTest extends TestCase
{
   /**
    * A basic test example.
    *
    * @return void
   */
   public function testLoginSuccess()
   {
       $this->post('http://127.0.0.1/identificare_api/public/api/user/login', ['email' => 'identificare@gmail.com', 'password' => 'identificare']);
   }
}

and I tried this one also, still no go.
$this->json('POST', 'user/login', ['email' => 'identificare@gmail.com', 'password' => 'identificare']);

here's my route
Route::post('user/login', 'UserController@login');

Is it correct to do it this way? If no, what's the correct way of testing my api?

A: Correct way to call the post is
$this->post('/user/login', array('email' => 'identificare@gmail.com', 'password' => 'identificare'));

or
$this->call('POST','/user/login', array('email' => 'identificare@gmail.com', 'password' => 'identificare'));

use an echo and exit in the login function and check whether test hitting the controller function.
It will be easier if you share a dummy code of your controller function ,because we could n`t figure out what this variable $e. Which should be in controller.


text:
Q: Using the Xwiki WYSIWYG editor in Grails .gsp files? I'm using Grails for one of my projects, and I've got the Xwiki rendering plugin (see http://grails.org/plugin/xwiki-rendering) installed. Now I wonder whether there is any way to use the xWiki WYSIWYG editor inside my .gsp files?
Any help would be appreciated!

A: Using the XWiki Wsywiyg editor should be possible. You can check some documentation here and also check this which is an example of an XWiki Platform branch allowing to build the XWiki Wysiwyg editor standalone.
You can come ask questions in the XWiki dev lists if you need help (See the xwiki.org web site)

A: I have faced the same issue on one of my project. It's not easy because the editor is part of the XWiki platform so you'll have to download the source code and extract it (there is no standalone editor).
What I did instead is using MarkItUp as it supports Wiki tags (and you can add custom macros).


text:
Q: Convex quadrilateral and perimeter Convex quadrilateral $ABCD$ is inscribed in a circle with diameter $AC=729$. Sides $AB$ and $CD$ each have positive integer length. I have to find the perimeter if $BD=715$. By Ptolemy's theorem, there is $AB∙CD+BC∙DA=AC∙BD=521235$ and furthermore we have: $CD^2+DA^2=AB^2+BC^2=AC^2=3^{12}$. What can I do next?

A: Let $AB=n$ and $CD=m$. Then
$$mn+\sqrt{729^2-m^2}\sqrt{729^2-n^2}=729\cdot 715 $$
can be written as
$$(729^2-m^2)(729^2-n^2)=(729\cdot 715-mn)^2 $$
or as
$$ 729 m^2 - 1430 mn + 729 n^2 = 729\cdot20216 $$
which does not have many integer solutions. Except the obvious $(m,n)\in\{(715,729),(729,715)\}$ there are only $(m,n)\in\{(279,405),(405,279)\}$, leading to a perimeter equal to
$$ 279+405+180\sqrt{14}+162\sqrt{14}=\color{red}{342(2+\sqrt{14})}.$$


text:
Q: How to cast User to Member during making Discord Bot with JDA? (Java) I have a problem with creating a Member variable during making Discord Bot with JDA. I wanted to create a Member variable with a concrete User ID but I bump into a problem that not all users of my Discord server are visible for bot.
Here's the code that shows only 1 user instead of 3. (prints only bot name)
jda.getUsers().stream()
            .map(User::getName)
            .forEach(System.out::println);

Here's the code that causes an error.
Member member = event.getGuild().getMemberById("*************");
System.out.println(member.getNickname());

For example, this code works correctly (prints neccessary username)
User user = event.getJDA().retrieveUserById("*************").complete();
System.out.println(user.getName)

Here's the error shown by IDE
(I need Member variable to change userName using .modifyNickname that available only for Member variable)
Have you got any ideas to create a Member variable using userID? Or maybe I can somehow cast User to Member? Thanks for your help.

A: Take a look at GatewayIntent. Currently, the members aren't cashed.
Depending on your use case it may be sufficient to simply retrieve the member similar to what you did with the user.
event.getGuild().retrieveMemberById(id).queue()

Please note that using .complete() is not recommended. Stick to .queue() since it's asynchronous and won't block your thread.


text:
Q: $\lim_{s \to 1^+} 1/\zeta(s) = 0$ obvious or not? I read the statement that
$$\frac{1}{\zeta(s)} = \sum_{n=1}^\infty \frac{\mu(n)}{n^s} \textrm{ for } \Re(s) > 1 \qquad (*)$$
In fact I can guess what the proof is: just expand both $\zeta$ and the right hand side of (*) as an Euler product, use $\Re(s) > 1$ to handwave away any concerns of changing the order of taking limits and taking products and conclude that the outcome of multiplying the right hand side of (*) by $\zeta(s)$ is the product of infinitely many $1$'s, hence 1 itself. So far so good.
Now suppose I wanted to evaluate the the limit $s \to 1^+$ of the right hand side of ( * ) , or in layman's terms, compute the sum $\sum_{n=1}^\infty \frac{\mu(n)}{n}$. From (*) I would quickly conclude that
$$\sum_{n=1}^\infty \frac{\mu(n)}{n} = 0 \qquad (**)$$
since $\zeta(1) = \sum_{n=1}^\infty \frac{1}{n}  = \infty$ (by the standard 'powers of 1/2'-argument) and, as we all know, $1/\infty = 0$. Very nice, very elementary, or... so it seems.
However the statement (**) is far from elementary: it is equivalent to the prime number theorem! (If you find that equivalence surprising: so did I. I asked a question about it three years ago, but the current question is about a different type of surprise that arises if we take this equivalence as given.)
We all know that the PNT is hard to prove. So what is wrong with simply taking the the limit $s \to 1$ in (*) as I did above? Am I secretly interchanging two limits where that is not allowed?
Where am I oversimplifying things?
I have a very vague feeling what is going on here (but perhaps I am completely off, so correct me if I am wrong) and that is that there is some weird theorem lurking in the background that states that we can only extend the equation (*) to the point $s = 1$ if and only if we can extend it to the entire line $\{s \colon \Re(s) = 1\}$. But what kind of weird theorem would that be? It goes again my nearly lifelong experience that one can do mathematics just fine without even realizing that complex numbers off the real line exist.

A: The question in the title is:

$\lim_{s \to 1^+} 1/\zeta(s) = 0$ obvious or not?

From the body of the text, I'm not sure that this is the real question the poster intended, but I answer the above question as it stands.
Claim: Suppose $a_n$ is a decreasing sequence of positive real numbers with $a_n\to 0$ and $\sum_{n=1}^{\infty} a_n = +\infty.$ Then, $\lim_{s\to 1^+} \sum_{n=1}^{\infty} {a_n}^s = \infty.$
Proof: Let $\gamma\in\mathbb{R}_{>0}$ (think about $\gamma$ being a large positive real number). We are given that $\sum a_n$ diverges to $+\infty.$ So, $\exists k$ such that $\sum_{n=1}^{k} a_n > 2\gamma$.
Proposition: $\exists s>1$ such that ${a_n}^s > a_n/2\quad \forall n\in \{1,\ldots,k\}.$ Proof of proposition: Take $s = 1+a_k.$
Therefore, $\ \sum_{n=1}^{\infty}{a_n}^s > \sum_{n=1}^{k}{a_n}^s > \sum_{n=1}^{k}{\frac{a_n}{2}} > \gamma.$
Furthermore, $1 <s' < s \implies \sum {a_n}^{s'} > \sum{a_n}^s,\ $ and so $\lim_{s\to 1^+} \sum_{n=1}^{\infty} {a_n}^s = \infty.$
This proves that claim. Now take $a_n = \frac{1}{n}.$ We see that the question in the title is proven.


text:
Q: OpenCV 3.0 cvAbsDiff() - No matching function for call to 'cvAbsDiff' So i see - No matching function for call to 'cvAbsDiff' message, i don't know why but i can't compile this code.
Xcode advise convert cv::Mat to CvArr. But this is crazy way.
cv::Mat firstFrame;

- (void)processImage:(Mat&)image;
{

    cv::Mat diffFrame=image.clone();

    cv::Mat currentFrame=image.clone();

    cvtColor(image, currentFrame, CV_BGR2GRAY);

    if (countNonZero(firstFrame) < 1){firstFrame=currentFrame;}
    else
    {

        cvAbsDiff(firstFrame,currentFrame,image);
//        image=diffFrame;

    }

}

A: The cvAbsDiff function is designed to work with the older C api, which uses IplImage rather than cv::Mat to store images. Instead when working with C++ you can just use the cv::absdiff function:
cv::absdiff(firstFrame, currentFrame, image);

For future reference, if you need to convert a cv::Mat to an IplImage, you can do so by assiging it, but generally you should try and avoid mixing the two API styles.
IplImage ipl = myMatImage;.

If you look at the OpenCV array operations documentation you will see that the various functions are listed with both their C and C++ variants.


text:
Q: Why does this terminate my app without throwing an exception? I am using the YAX Serializer (current NuGet version).  When I run this code:
void Main()
{
    try
    {
        int zero = 0;
        int result = 100 / zero;
    }
    catch (DivideByZeroException ex)
    {
        LogSaveException(ex);
    }
}

public void LogSaveException(object value)
{
    try
    {
        YAXSerializer serializer = new YAXSerializer(value.GetType());
        string loggedString = serializer.Serialize(value);
        Console.WriteLine(loggedString);
    }
    catch (StackOverflowException)
    {
        Console.WriteLine("Log Error", "Could Not Log object of type "
                  + value.GetType().ToString() +" due to stack overflow.");
    }
    catch (Exception)
    {
        Console.WriteLine("Log Error", "Could Not Log object of type "
                + value.GetType().ToString());
    }
}

The app ends on this line: string loggedString = serializer.Serialize(value);
I have tried to catch any exception that I can see would happen.  But the app just ends.
I tried running it in LinqPad and it crashed LinqPad.  I tried to debug the crash of LinqPad (even though I do not have the source, sometimes you can get some info from it.)  When I did that it said that there was a StackOverflowException.  But my catch statement did not catch it.
What would cause a total death like that?  How how do I guard against it?

A: Stackoverflow exceptions have limited "catchability" in CLR > 2.0.  See the blog post below for more details; the behavior you're experiencing is exactly what's described.
See: http://blogs.msdn.com/b/jaredpar/archive/2008/10/22/when-can-you-catch-a-stackoverflowexception.aspx
While annoying, this does make sense: if you've blown your stack, what would a consistent/safe/sane recovery look like?

A: Seems like a serious error with the YAXSerializer.
StackOverflowException cannot be caught (see here amongst others for reference) because there's rarely any recovery from such a serious error.
EDIT: or it's an error with the class you're serializing.  Do you have a cyclic reference in the object you're passing in?


text:
Q: Intellij IDEA - problem with JavaFX compilation I've reinstall my OS from Win7 to 10. After reinstalling Intellij IDEA + Corretto_11 + JavaFX libary I cannot compile programa that was working.
I'm quite green in Java, so i don't know hot to approche the problem.
Project set to Correto_11, language level 11, and FX libary added to module.
Even code from Course does not compile.
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x3a0bd002) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x3a0bd002
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at main.Main.start(Main.java:18)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    ... 1 more
Exception running application main.Main

Process finished with exit code 1

Edit:
After adding module I have following error:
"C:\Program Files\Amazon Corretto\jdk11.0.7_10\bin\java.exe" --add-modules javafx.base,javafx.graphics --add-reads javafx.base=ALL-UNNAMED --add-reads javafx.graphics=ALL-UNNAMED "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.1.1\lib\idea_rt.jar=50795:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.1.1\bin" -Dfile.encoding=UTF-8 -p C:\Users\Sebastian\Documents\javafx_11\lib\javafx.base.jar;C:\Users\Sebastian\Documents\javafx_11\lib\javafx.graphics.jar;C:\Users\Sebastian\Desktop\JavaProjects\JavaFX_ToDo\out\production\JavaFX_ToDo;C:\Users\Sebastian\Documents\javafx_11\lib\javafx-swt.jar;C:\Users\Sebastian\Documents\javafx_11\lib\javafx.controls.jar;C:\Users\Sebastian\Documents\javafx_11\lib\javafx.fxml.jar;C:\Users\Sebastian\Documents\javafx_11\lib\javafx.media.jar;C:\Users\Sebastian\Documents\javafx_11\lib\javafx.swing.jar;C:\Users\Sebastian\Documents\javafx_11\lib\javafx.web.jar -m JavaFX.ToDo/main.Main
Error occurred during initialization of boot layer
java.lang.module.FindException: Error reading module: C:\Users\Sebastian\Desktop\JavaProjects\JavaFX_ToDo\out\production\JavaFX_ToDo
Caused by: java.lang.module.InvalidModuleDescriptorException: Package JavaFX.ToDo not found in module

Process finished with exit code 1

Edit 2:
Project structure:

Edit 3:
Adding how my module look like:
module JavaFX.ToDo {
    requires javafx.graphics;
    requires javafx.controls;
    requires javafx.fxml;

    opens JavaFX.ToDo;
}

Edit 4:
Adding main content:
package main;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import main.models.TaskData;

import java.io.IOException;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("mainwindow.fxml"));
        primaryStage.setTitle("JavaFX: ToDo-App");
        primaryStage.setScene(new Scene(root, 900, 500));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);

    }
    @Override
    public void stop() throws Exception {
        try {
            TaskData.getInstance().storeTasks();

        } catch (IOException e){
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void init() throws Exception {
        try {
            TaskData.getInstance().loadTasks();

        } catch (IOException e){
            System.out.println(e.getMessage());
        }
    }

}

Or i can push all on my github.
https://github.com/s-osyra/JavaFX_ToDoList

A: The first error happened because your module wasn't open, and the javafx.fxml module (specifically FXMLLoader) wanted to use reflection.
The second error's just because you're using opens incorectly. It's meant to open packages, not modules.
This is your module-info file now:
module JavaFX.ToDo {
    requires javafx.graphics;
    requires javafx.controls;
    requires javafx.fxml;

    opens JavaFX.ToDo; //Here's the error
}

This is incorrect, because you don't have a package called JavaFX.ToDo, it's your module name. To make your module open (so javafx.fxml can do reflective access operations), you need to declare your module open like this:
open module JavaFX.ToDo {
  ...
}

xor this:
module JavaFX.ToDo {
  ...
  opens main; //This is where Main.java is, and where you use FXMLLoader
}

If you want it to be more secure, you could also declare it like this:
module JavaFX.ToDo {
  requires javafx.fxml;
  opens main to javafx.fxml; //Only fxml has reflective access to your package now
}

I would suggest reading this article about Java 9's module system. Scroll down to where they talk about open modules.
Side note: Module names are lowercase by convention. You probably want something like javafx_todo

A: I solved this as follows in IntelliJ:
Run -> Edit configuration -> Configuration tab -> add following in VM options:
--module-path c:\javafx-sdk-14.0.1\lib --add-modules=javafx.controls,javafx.fxml


text:
Q: Difference in accessing props after change in redux store between React class component and React functional component I`m having a problem in understanding why in a Class based component vs Functional component the same steps yield a different result. Below I have an example that presents this difference.
   class Test extends Component {
      handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields(async (err, values) => {

            await this.props.saveUserDetailsAction(values);

            const { error } = this.props; // expected modified prop

            if (!error.status) {
              this.props.router.push("/route");
            }
        });
      };
    }

const mapStateToProps = ({ app }) => ({
 error: app.error
});

const mapDispatchToProps = {
  saveUserDetailsAction,
};

export default compose(
  withRouter,
  connect(
    mapStateToProps,
    mapDispatchToProps
  )
)(Test);

The current error prop inside the class component reflects the changes in the redux store after the async function saveUserDetailsAction has completed, in this case dispatching an action if the request fails.
Accessing the error props after the saveUserDetailsAction function shows the updated prop.
The same code written as a functional component does not yield the same result. Accessing the error prop after the saveUserDetailsAction function completed doesn't reflect the change in the store yet.
  const Test = (props) => {
      const handleSubmit = e => {
        e.preventDefault();
        props.form.validateFields(async (err, values) => {

            await props.saveUserDetailsAction(values);

            const { error } = props;  // unchanged prop when accessed here

            if (!error.status) {
              props.router.push("/route");
            }
        });
      };
    }

const mapStateToProps = ({ app }) => ({
 error: app.error
});

const mapDispatchToProps = {
  saveUserDetailsAction,
};

export default compose(
  withRouter,
  connect(
    mapStateToProps,
    mapDispatchToProps
  )
)(Test);

A: To my point of view, it's an anti-pattern, you need to wait for another cycle to get the correct error props. Functional component is the right behavior.
What you need to do is find a way to return error here :
const { error } = await props.saveUserDetailsAction(values);

Redux store error variable can still be used in another component
Other way to do it is to use a useEffect(() => {}, [error]) and to distinguish 3 states "No Submitted Yet", "Submitted without error", "Submitted with error" but i don't recommend it


text:
Q: Postgres lo_import large object import from other table text data I need to convert text data in a table to large object data in another table. So the table structure is :-
Employee->
id (character varying(130)),name (character varying(130)), description (text)

EmployeeDetailed ->
detailed_id(character varying(130)), desc_lob (oid)

What query can I run in order to transfer all the rows from Employee table to EmployeeDetailed table so that detailed_id would be populated from Employee's id columns and description would be converted to large object and oid would be inserted in desc_lob.
Can I use lo_import(), would it help here?

A: lo_import() is a client interface command. You can use an INSERT statement, using the result of a SELECT, and use lo_from_bytea inside that SELECT clause:
INSERT INTO EmployeeDetailed (detailed_id, desc_lob)
SELECT id, lo_from_bytea(0, convert_to(description, 'LATIN1'))
FROM Employee

Change LATIN1 for whatever encoding you might like (see this answer)


text:
Q: Amd, requirejs - want to ensure something always executes last I'm trying to avoid global scope for the following problem, but cannot see a way to avoid it.
I have a singleton Javascript object called "Application". This is an AMD module.
I then have many "Modules" (not to be confused with AMD modules) which are just javascript objects that I'd like to register with the "Application" instance.
For example:
 require(['Application'], function(app) {

        var module = {
            name: "theme-switcher",
            start: function() { console.log("started") } }

        app.registerModule(module)
 }

The architecture I am going for, is i'd like for each "Module" on the page to register itself with the "Application" instance.
Here is the tricky part: Only once ALL modules have been registered with the application, do I then want the "Application" instance, to loop through those registered modules and call their "Start()" methods.
The way I thought to do this was to just add another require block at the bottom of the page like this:
 <script type="text/javascript">
require(['Application'], function (app) {
    // start all the registered modules running.
    app.start(() => {
        // this could be a call back function once all modules started..
    });
});

Niavely thinking, that just because this require call was last, that it would allways be executed last. But actually, sometimes this gets fired BEFORE the require calls above - so the Application attempts to Start() all registered modules BEFORE the modules themselves have all registered themselves with the Application.
No matter how I think about this problem, I am often led back to the fact that I need to keep some state in global scope, Something like this:
Module 1:
var app = Application.Instance;
var moduleStart = function(){
    require(['jquery'], function(jquery) {

 // do module goodness here.
}};

app.registerModule({name: "theme-switcher", start: moduleStart })

// later on in page - some other widget
// Module 2
var app = Application.Instance;
var moduleStart = function(){
    require(['jquery'], function(jquery) {

 // do second module goodness here.
}};

app.registerModule({name: "foo", start: moduleStart })

And then at the bottom of the page,
var app = Application.Instance;
app.Start(); // loops through registered modules calling start() method.

Surely there must be a way to do this avoiding global scope?
The reason for me wanting to do this, is that I want the "Application" to manage the lifecycle for registered modules on the page - including starting / pausing / stopping them etc. I'd also like the Application to publish an event once ALL modules gave been started - as this is when I would typically stop displaying my "loading" animation, and actually display the DOM - as modules will often manipulate the DOM in their start() methods and I don't want the page to be visible before everything is started.

A: This will do it. If you make every object you are wanting an AMD module, which I think you should be doing if you have RequireJS in place anyway, then you'll just need an array of strings defining those AMD module names to pass as an argument to the app's init.
Application.js : -
define(function (require, exports, module) {
    "use strict";

    var modules = {};
    var moduleNames = [];
    var numberOfModules = 0;
    var loadedModules = 0;

    exports.init = function (dependencies) {
        numberOfModules = dependencies.length;

        for (var i = 0; i < numberOfModules; i++){
            var name = dependencies[i];
            moduleNames.push(name);

            require([name], function (moduleRef) {
                loadedModules++;
                modules[name] = moduleRef;

                if (numberOfModules === loadedModules) {
                    exports.start();
                }
            });
        }
    };

    exports.start = function () {
        // all modules available
        // use modules.myModuleName to access the module.
        modules.myModuleName.functionName();

        // or if they all have start() function and it needs calling

        for (var i = 0; i < moduleNames.length; i++) {
            modules[moduleNames[i]].start();
        }
    };

});

USAGE Depending on how you are loading your app, assuming you have an Application reference somewhere, just call:
// names of modules RequireJS uses to require, can be changed for each page.
var dependencies = ['moduleOne', 'moduleTwo', 'myModuleName'];
app.init(dependencies);

CodePen of this code, slightly altered to work on one page... http://codepen.io/owenayres/pen/MyMJYa


text:
Q: Sending Email From PHP Script I have a page which is used for booking room for meetings. I have form on which all the details for booking is required. I have fetched email id from the MySql db.I want to send email on click of submit button. I have 2 files namely home.php & insert.php. In home.php i have the form & insert.php inserts the data into the db. I tried the email functionality code but it's not working.
Please Help
room.php
<?php session_start();
if(isset($_GET['selecteddate']))
{
    $selecteddate=$_GET['selecteddate'];
}
else
{
    $selecteddate=date("Y-m-d");
}
?>

<title>MRA</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">

KARMA
(3-SEATER)

Home   <?php echo ucwords($_SESSION['usr_name']); ?>   Change Password   Logout   Help

        <?php
            $host="localhost"; // Host name
            $username="root"; // Mysql username
            $password=""; // Mysql password
            $db_name="testmra"; // Database name
            // Connect to server and select databse.
            $conn=mysqli_connect($host,$username,$password) or die("cannot connect");
            mysqli_select_db($conn,$db_name);
            $i = 0;
            $dateEntry = "SELECT `starttime` , `status_id` , `name` , floor(( time_to_sec(`endtime`)-time_to_sec(`starttime`) )/1800) as testing FROM `karmadetails` WHERE `date` = '$selecteddate' order by starttime";
            if ($result=mysqli_query($conn,$dateEntry)) {
                while ($obj=mysqli_fetch_object($result))
                {
                    $starttime[$i] = $obj->starttime;
                    $status[$i] = $obj->status_id;
                    $name[$i] = $obj->name;
                    $testing[$i] = $obj->testing;
                    $i++;
                }
            }
            mysqli_close($conn);
        ?>

Click to Book a Time Slot

Booked	Available

|  Today  |

<?php print $selecteddate; ?>

08:00

08:30

09:00

09:30

10:00

10:30

11:00

11:30

12:00

12:30

13:00

13:30

14:00

14:30

15:00

15:30

16:00

16:30

17:00

17:30

18:00

18:30

19:00

19:30

20:00

        <?php
            $name=$_SESSION['usr_name'];
            $host="localhost"; // Host name
            $username="root"; // Mysql username
            $password=""; // Mysql password
            $dbname="testmra"; // Database name
            // Create connection
            $conn = mysqli_connect($host, $username, $password, $dbname);
            // Check connection
            if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
            else{

                }
            $res  = mysqli_query($conn,"SELECT emailid FROM users WHERE username='$name'");
            while($row=mysqli_fetch_assoc($res))
            {
                $rows = $row['emailid'];

            }
        ?>

        Close
        <form align="center" method="post" id="inform">

Meeting Details

Room : 	<input type="text" name="txtrname" value="Karma" readonly>

Name :	<input type="text" name="txtname" readonly value="<?php echo ucwords($_SESSION['usr_name']);  ?>"   >

Email Id :	<input type="text" name="txtemail" readonly value="<?php echo $rows ?>">

Purpose of Meeting :	 <input id="meeting" type="text" name="txtpurpose">Enter the purpose of meeting

No. of Attendee :	<select name="attendee"><option value="2">2</option><option value="3">3</option></select>

Date :	 <input class="date" type="text" name="txtdate" readonly value="yyyy/mm/dd">

Time : 	Start Time <select class="start-time" name="btime">
            <option value="08:00:00">08:00</option>
            <option value="08:30:00">08:30</option>
            <option value="09:00:00">09:00</option>
            <option value="09:30:00">09:30</option>
            <option value="10:00:00">10:00</option>
            <option value="10:30:00">10:30</option>
            <option value="11:00:00">11:00</option>
            <option value="11:30:00">11:30</option>
            <option value="12:00:00">12:00</option>
            <option value="12:30:00">12:30</option>
            <option value="13:00:00">13:00</option>
            <option value="13:30:00">13:30</option>
            <option value="14:00:00">14:00</option>
            <option value="14:30:00">14:30</option>
            <option value="15:00:00">15:00</option>
            <option value="15:30:00">15:30</option>
            <option value="16:00:00">16:00</option>
            <option value="16:30:00">16:30</option>
            <option value="17:00:00">17:00</option>
            <option value="17:30:00">17:30</option>
            <option value="18:00:00">18:00</option>
            <option value="18:30:00">18:30</option>
            <option value="19:00:00">19:00</option>
            <option value="19:30:00">19:30</option>
            <option value="20:00:00" disabled>20:00</option>
        </select>
        - End Time <select class="end-time" name="etime">
            <option value="08:00:00">08:00</option>
            <option value="08:30:00">08:30</option>
            <option value="09:00:00">09:00</option>
            <option value="09:30:00">09:30</option>
            <option value="10:00:00">10:00</option>
            <option value="10:30:00">10:30</option>
            <option value="11:00:00">11:00</option>
            <option value="11:30:00">11:30</option>
            <option value="12:00:00">12:00</option>
            <option value="12:30:00">12:30</option>
            <option value="13:00:00">13:00</option>
            <option value="13:30:00">13:30</option>
            <option value="14:00:00">14:00</option>
            <option value="14:30:00">14:30</option>
            <option value="15:00:00">15:00</option>
            <option value="15:30:00">15:30</option>
            <option value="16:00:00">16:00</option>
            <option value="16:30:00">16:30</option>
            <option value="17:00:00">17:00</option>
            <option value="17:30:00">17:30</option>
            <option value="18:00:00">18:00</option>
            <option value="18:30:00">18:30</option>
            <option value="19:00:00">19:00</option>
            <option value="19:30:00">19:30</option>
            <option value="20:00:00">20:00</option>
        </select>

	<input class="submit-button" type="submit" value="Submit">

        </form>

Close
The selected time slot is booked.

Close
This time slot is already booked.

        <?php
            $user = ucwords($_SESSION['usr_name']);
            $host="localhost"; // Host name
            $username="root"; // Mysql username
            $password=""; // Mysql password
            $db_name="testmra"; // Database name
            // Connect to server and select databse.
            $conn=mysqli_connect($host,$username,$password) or die("cannot connect");
            mysqli_select_db($conn,$db_name);
            $result = mysqli_query($conn,"SELECT * FROM karmadetails WHERE name='$user' AND date='$selecteddate' AND (status_id=1 OR status_id=2)");
            echo "

                    User Id
                    Purpose
                    Date
                    Start Time
                    End Time
                    Cancel Booking

";
            while($row = mysqli_fetch_array($result))
            {
                echo "
";
                        echo "" . $row['id'] . 	";
                        echo "" . $row['purpose'] . "	";
                        echo "" . $row['date'] . "	";
                        echo "" . $row['starttime'] . "	";
                        echo "" . $row['endtime'] . "	";
                        echo ' Cancel 	';
                echo "
";
            }
            echo "
";
            mysqli_close($conn);
        ?>

insert.php
<?php
    $host="localhost"; // Host name
    $username="root"; // Mysql username
    $password=""; // Mysql password
    $db_name="testmra"; // Database name

    // Connect to server and select databse.
    $conn=mysqli_connect($host,$username,$password) or die("cannot connect");

    mysqli_select_db($conn,$db_name);

    $room = mysqli_real_escape_string($conn, $_POST['txtrname']);
    $name = mysqli_real_escape_string($conn, $_POST['txtname']);
    $email = mysqli_real_escape_string($conn, $_POST['txtemail']);
    $purpose = mysqli_real_escape_string($conn, $_POST['txtpurpose']);
    $attendee = mysqli_real_escape_string($conn, $_POST['attendee']);
    $date = mysqli_real_escape_string($conn, $_POST['txtdate']);
    $btime = mysqli_real_escape_string($conn, $_POST['btime']);
    $etime = mysqli_real_escape_string($conn, $_POST['etime']);

    $sql="INSERT INTO karmadetails (room,name,purpose,attendee,date,starttime,endtime,status_id)VALUES('$room','$name','$purpose','$attendee','$date','$btime','$etime','2')";

    $to = '$email';

        $subject = "Your Booking is Done!!!";

        $message = "
Hello $name . You've received this E-Mail because you have booked room $room from Timings $btime to $etime on Date $date.";

        $from = "kansaramankit@gmail.com";

        $headers = "From: $from";

        mail($to,$subject,$message,$headers);

    if (mysqli_query($conn,$sql))
      {
        echo "Record added";

        }
    else
    {
        die('Error: ' . mysqli_error());
     }
?>


text:
Q: Only one record in plugin I have a question. Is it possible for only one record to be created in the plugin? So in the backend, when I click on the backend menu, I get a form and not a list of records.
If I click on side bakend menu "Fakty" on picture then I need it to be displayed only form. No list of records.
See the picture

A: You can achieve that by Setting module of Octobercms.
Please read this documentation for that.
https://octobercms.com/docs/plugin/settings#writing-settings


text:
Q: Vehicles' or Vehicles are spinning out of control Is it Vehicles or Vehicles' were spinning out of control. I have checked the rule and I though the apostrophe is for ownership and i don't believe there is direct ownership in this line but my friend says that you put the apostrophe.

A: There is sometimes a need for an apostrophe, but that is usually when the word in question (e.g., vehicles) precedes a gerund. Even then, the apostrophe is not necessarily needed. For example, the following sentence does not need an apostrophe:

The vehicles speeding past the sign were too many to count.

On the other hand, the following sentence would need an apostrophe:

The vehicles' speeding was documented by a cop with a speed gun.

The former sentence has nothing to do with ownership, or possession, but simply the kind of vehicles they were; namely, speeding vehicles (adjective, noun). You could substitute bicycles, runners, birds--or whatever, for vehicles.
The latter sentence does have to do with ownership, or possession, in that the speeding, in a sense, belonged to the vehicles. It was their speeding, so to speak, which was caught by the cop with the speed gun.
With the ground rules I've laid out for you, is an apostrophe needed or not in the following sentences?

I was impressed by Jim's/Jim speeding.
The photographer captured two lions'/lions pouncing on the prey.
The girl's/girl smiling at me was the one I chose as my date for the dance.
If you ever see Sally's/Sally walking down Main Street, please let me know.
Paul's/Paul winning that many medals made me a bit envious.

[Answers: yes, no, no, no, yes]
Hint: If you're not sure an apostrophe is needed, simply ask the question (for example), "Whose speeding impressed you?" (my sentence 1), or "Whose winning made you envious?" (my sentence 5). If the possessive "whose" is an appropriate answer, then an apostrophe would in order. If not, then not.


text:
Q: Move to next field after input I am new to jquery.  I am trying to automatically move to the next field after a user inputs a correct format/pattern (regex value).
Here is what I have so far:
Form:
<form>
<label for="serial_number">Serial Number: </label>
<input type="text" id="serial_number" name="serial_number" placeholder="Serial Number" pattern="[0-9]{5}" maxlength="5" required autofocus />

<input type="text" id="second_entry" name="second_entry" placeholder="second_entry" pattern="[0-9]{5}" maxlength="5" required />

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

Jquery:
$('.serial_number').keyup(function() {
var inputVal = $(this).val();
var characterReg = /^[0-9]\d{20}$/;
if(characterReg.test(inputVal)) {

$("serial_number").change(function() {
var inputs = $(this).closest('form').find(':input');
inputs.eq( inputs.index(this)+ 1 ).focus();
});

}
});

Any assistance would be greatly appreciated!

A: There is error in your selector.
$('.serial_number').keyup(function() {

to
$('#serial_number').keyup(function() {

Update: Try the below code:
$('#serial_number').keyup(function () {
    var inputVal = $(this).val();
    var characterReg = /^[0-9]{5}$/;
    if (characterReg.test(inputVal)) {
        var inputs = $(this).closest('form').find(':input');
        inputs.eq(inputs.index(this) + 1).focus();
    }
});

There is no need for .change().  Check this JSFiddle
Also you need to change your regex  to

var characterReg = /^[0-9]{5}$/;

in the jQuery code because you have maxlength="5"

A: Here you are. Have a look at the code...
http://jsfiddle.net/aVdex/
jQuery(document).ready(function() {
    $('#serial_number').keyup(function() {
        var inputVal = $(this).val();
        var characterReg = /^\d{5}$/;
        if(characterReg.test(inputVal)) {
            $("#serial_number").next("input").focus();
        }
    });
});

For IDs you should use the # selector. For classes, use ..
The change event is not fired until the input loses focus, so you need to do all your checking in the keyup event.
You can use the next function to get an element's immediate sibling.
Focus sets the user's focus to that element, and so puts the cursor in the next input here


text:
Q: Get current action in extbase TYPO3 v8
I have created a custom Validator class in my extbase project.
I call the validator on the model:
* @validate ME\MyProject\Domain\Validator\MyCustomValidator

I need to check/test what the current Action is inside the validator class.
How do I find this out?
Thanks again T3 community


text:
Q: Add time to datetime object with PHP I have an datetime object and I try to add 2 days to that object using strtotime function (this is optional, I am open to any working solution).
When I add 2 days to my object I am getting a timestamp as a result:
$new_datetime = strtotime('+2 days' . date_format($datetime, 'd/m/Y h:i A'));

It would not be a problem but I want to loop through number of modified datetime objects with following code:
$datetimeArray[] = $datetime;
for ($i = 0; $i < $times; $i++){
    $datetimeArray[] = strtotime('+' . $interval . " " . $timeUnit .
                       date_format($datetimeArray[$i], 'd/m/Y h:i A'));
}

Because strtotime gives me a timestamp on the second spin of the loop I will get an error message:
date_format() expects parameter 1 to be DateTimeInterface, integer given
How can I modify my code to either have a array of datetime objects or timestamps?

A: You could try changing the dot in this line to a comma as it is a comma that seperates the parameters in a strtotime() function.
From
$datetimeArray[] = strtotime('+' . $interval . ' ' . $timeUnit .
                   date_format($datetimeArray[$i], 'd/m/Y h:i A'));

To
$datetimeArray[] = strtotime('+' . $interval . ' ' . $timeUnit ,
                   date_format($datetimeArray[$i], 'd/m/Y h:i A'));

But unless $times = 1 the second time through your for loop there will be nothing to process and it will probably crash.


text:
Q: Coverting String. Simple vs Unicode, Python I am writing a script in python that is used to validate the vales of each cell in a parent table and compares to values in a look up table.
So, in the parent table I have a number of columns and each column corresponds to a lookup table for the known values that should be in each record in that particular column.
When I read in the values from the parent table, there will be many types (i.e. unicode strings, ints, floats, dates, etc)
The look up tables have the same variety of types, but when it's a string, it's a simple string, not a unicode string which forces me to convert the values to match. (i.e. if the value in the cell from the parent table is a unicode string, then I need to create a conditional sentence to test if it's unicode and then convert to simple string
if isinstance(row.getValue(columnname), unicode):
    x = str(row.getValue(columnname)

My question is, would it better to convert the unicode strings to simple strings or vice versa to match the type? Why would it be better?
If it helps, my parent table is all in access and the lookup tables are all in excel. I don't think that really matters, but maybe I am missing something.

A: It'd be better to decode byte strings to unicode.
Unicode data is the canonical representation; encoded bytes differ based on what encoding was used.
You always want to work with Unicode within your program, then encode back to bytes as needed to send over the network or write data to files.
Compare this to using date/time values; you'd convert those to datetime objects as soon as possible too. Or images; loading an image from PNG or JPG you'd want to get a representation that lets you manipulate the colours and individual pixels, something that is much harder when working with the compressed image format on disk.


text:
Q: How to create simple funnel in LaTeX? I have a problem trying to create a simple funnel, as it can be seen on the attached file:

I have tried to look at the internet, trying to write the lines, but it won't work. I am using TikZ. The basic idea with the figure is to show the reader, that I do a delimitation.
If someone can help me or have another better option, I would be glad to hear about that.

A: Doesn't generalize very well, but...
\documentclass[tikz,border=5]{standalone}
\begin{document}
\begin{tikzpicture}[x=4cm,y=.5cm, >=stealth]
\foreach \i [evaluate={%
  \x=\i<4 ? \i : (\i<16 ?    1 : (\i<22 ?     2 : 3));
  \y=\i<4 ?  1 : (\i<16 ? 2-\i : (\i<22 ? 11-\i : 15-\i));
}] in {1,...,23}
  \node (text-\i) at (\x,\y) {Text \i};
\draw [->] ( text-4.north west -| text-15.west)++(0,1)  -- (text-22.north east);
\draw [->] (text-15.south west)++(0,-1) -- (text-23.south east);
\end{tikzpicture}

A: Something like this?
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows}

\begin{document}

\begin{tikzpicture}
% Line of Text
\node at (0,7) {Text 1};
\node at (4,7) {Text 2};
\node at (8,7) {Text 3};
% First column of Text
\node at (0,5.5) {Text 4};
\node at (0,5) {Text 5};
\node at (0,4.5) {Text 6};
\node at (0,4) {Text 7};
\node at (0,3.5) {Text 8};
\node at (0,3) {Text 9};
\node at (0,2.5) {Text 10};
\node at (0,2) {Text 11};
\node at (0,1.5) {Text 12};
\node at (0,1) {Text 13};
\node at (0,0.5) {Text 14};
\node at (0,0) {Text 15};
% Second column of Text
\node at (4,4) {Text 16};
\node at (4,3.5) {Text 17};
\node at (4,3) {Text 18};
\node at (4,2.5) {Text 19};
\node at (4,2) {Text 20};
\node at (4,1.5) {Text 21};
% Third column of Text
\node at (8,3) {Text 22};
\node at (8,2.5) {Text 23};
% Arrows
\draw[-triangle 60] (-1,6.5)--(9,3.5);
\draw[-triangle 60] (-1,-1)--(9,2);
\end{tikzpicture}

\end{document}

Yielding this:

Edit: An adjustment for shorter code, but less control over what might be placed in place of each specific "Text":
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,arrows}
\begin{document}

\begin{tikzpicture}
% Line of Text
\foreach \x in {1,2,3}{\node at ($(0,7)+(\x*4-4,0)$) {Text \x};}
% First column of Text
\foreach \x in {4,...,15}{\node at ($(0,6)+(0,\x*-.5+1.5)$) {Text \x};}
% Second column of Text
\foreach \x in {16,...,21}{\node at ($(4,4)+(0,\x*-.5+8)$) {Text \x};}
% Third column of Text
\foreach \x in {22,23}{\node at ($(8,3)+(0,\x*-.5+11)$) {Text \x};}
% Arrows
\draw[-triangle 60] (-1,6.5)--(9,3.5);
\draw[-triangle 60] (-1,-1)--(9,2);
\end{tikzpicture}

\end{document}

A: A PSTricks solution:
\documentclass{article}

\usepackage{pstricks}
\usepackage{multido}

\begin{document}

\begin{pspicture}(8,8.1)
  \psline{->}(0,0)(8,3)
  \psline{->}(0,7)(8,4)
  \multido{\iA = 1+3, \iB = 1+1}{3}{\rput(\iA,8){Text~\iB}}
  \multido{\r = 5.975+-0.45, \i = 4+1}{12}{\rput(1,\r){Text~\i}}
  \multido{\r = 4.625+-0.45, \i = 16+1}{6}{\rput(4,\r){Text~\i}}
  \multido{\r = 3.725+-0.45, \i = 22+1}{2}{\rput(7,\r){Text~\i}}
\end{pspicture}

\end{document}


text:
Q: Windows Mobile form size I'm creating a windows mobile app which uses a custom GUI. It has an image as background and some text and images rendered on it. I want to do as little image processing in the app itself, so I'm creating different skins for different screen resolutions. If I need to support another screen resolution I'll just add another skin.
But what concerns me is that different emulator images have different sizes on their taskbars and menu bars, so the size of the actual form is not the same for all devices with the same resolution. So far I've found emulators where the taskbar and menu is either 104 (usually VGA, WVGA…) or 52 (QVGA, QWVGA…) pixels high. Do those menus always take up 52 or 104 pixels, or do device vendors or power users install things like a 3px high battery meter so the menu suddenly takes up 107 pixels?

A: From what I've seen with windows mobile, there is a standard screen size and the various emulator's sizes are scalings of that standard size IE 104px is a scale factor of 2 over 52px. In NETCF at least, the drawing API handled the scaling fairly well.

A: yep i remember having problems with this in the past as well - iirc the default bar size was a multiple of 26 or something (so 52 and 104 seems to fit) - i dont have the code here unfortunately, but i think it used something like this:
uint titleBarHeight = GetSystemMetrics(SM_CYCAPTION);
if(!titleBarHeight)
{
    GetLastError()
    ..blah
    blah..
}

i remember there being a problem with the apps detecting if the bottom button bar was present, but that might have just been the order i did things in at load-time..
hth
fusi


text:
Q: How to add LUT filter (from .CUBE file) in realtime camera preview? Currently, I'm using the below code to show a preview of the camera on texture view. So can somebody help me with applying LUT filters from the cube file to the preview?
private void startPreview() {
    mCamera = Camera.open(camId);
    if (mCamera == null) {
        throw new RuntimeException("Default camera not available");
    }

    try {
        mCamera.setPreviewTexture(mSurfaceTexture);

        Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();

        if (display.getRotation() == Surface.ROTATION_0) {
            mCamera.setDisplayOrientation(90);
        }
        if (display.getRotation() == Surface.ROTATION_270) {
            mCamera.setDisplayOrientation(180);
        }
        mCamera.startPreview();
        inPreview = true;
    } catch (IOException ioe) {
        inPreview = false;
        Log.e(TAG, "Exception starting preview", ioe);
    }
}

Thank You.


text:
Q: Open new activity for searchview when search is clicked I want to open a new activity whenever the search icon is clicked on the mainactivity. This new activity called SearchableActivity will handle all the relevant search results in the listview. I have followed the steps described in this post.
This is what I currently have:

I want to open up the SearchableActivity when the user enters into SearchView.
Here is what my code looks like:
AndroidManifest.xml
     <activity
            android:name=".MainActivity"
            android:launchMode="singleTop">
            <!-- meta tag points to the activity which displays the results -->
            <meta-data
                android:name="android.app.default_searchable"
                android:value=".SearchableActivity" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SearchableActivity"
            android:parentActivityName=".MainActivity">
            <!-- Parent activity meta-data to support 4.0 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
            <!-- meta tag and intent filter go into results activity -->
            <meta-data android:name="android.app.searchable"
                android:resource="@xml/searchable" />
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
        </activity>

MainActivity
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.options_menu, menu)
        val manager = getSystemService(SEARCH_SERVICE) as SearchManager
        (menu?.findItem(R.id.search)?.actionView as SearchView).apply {
            setSearchableInfo(manager.getSearchableInfo(ComponentName(this.context, SearchableActivity::class.java)))

        }
        return true
    }

SearchableActivity
class SearchableActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_searchable)
        Toast.makeText(this@SearchableActivity, "SA created", Toast.LENGTH_LONG).show()
        handleIntent(intent)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent !== null)
            handleIntent(intent)
    }

    private fun handleIntent(intent: Intent) {
        if (Intent.ACTION_SEARCH == intent.action) {
            val query = intent.getStringExtra(SearchManager.QUERY)
            Toast.makeText(this@SearchableActivity, "QUERY: $query", Toast.LENGTH_LONG).show()
        }
    }
}

A: there is a method that handles option menu item click it is called
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if(item.itemId == R.id.myItemId){
        startActivity(Intent(applicationContext, searchAcctivity::class.java))
    }
    return super.onOptionsItemSelected(item)
}

this code is written in kotlin, it shouldn't be that different in java just press ctrl + o and it should open a list of override methods search for "onOptionsItemSelected"

A: I'm not sure what you're trying to do but you can simply pass in the Search query to the intent of the activity at its creation.
First, add a companion object to your SearchableActivity :
  companion object {
        private const val EXTRA_QUERY = "SEARCH_QUERY"

        fun newIntent(context: Context?, query: String): Intent {
            return Intent(context, SearchableActivity::class.java)
                .putExtra(EXTRA_QUERY, query)
        }
    }

My understanding is that you want to open a new activity with the search query from MainActivity, next thing is handling the intent:
         private fun handleIntent(intent: Intent) {
                if (Intent.ACTION_SEARCH == intent.action) {
                    val query = intent.getStringExtra(EXTRA_QUERY)
                    Toast.makeText(this@SearchableActivity, "QUERY: $query", Toast.LENGTH_LONG).show()

            SearchableActivity.newIntent(this, query)
    }
  }

..et voila.


text:
Q: Could not find any resources appropriate for the specified culture or the neutral culture in c# I have an error like this. is anyone know how to fix it.
Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "LibraryMonitoringSystem.Properties.Resources.resources" was correctly embedded or linked into assembly "LibraryMonitoringSystem" at compile time, or that all the satellite assemblies required are loadable and fully signed.
I also tried to read this links
Could not find any resources appropriate for the specified culture or the neutral culture
Could not find any resources appropriate for the specified culture or the neutral culture
Could not find any resources for the specified culture or the neutral culture
.NET 4.0 to 3.0 could not find any resources appropriate for the specified culture or the neutral culture
Could not find any resources appropriate for the specified culture (C# WinForm Images in Resource File)
but none of them solve my problem..


text:
Q: Django 1.8.4 with REST Framework select opposite column based on request.user in contacts table I am not quite sure how to proceed on this and look for an answer that keeps performance on top.
I have the following model:
class Contact(models.Model):
    STATUS_VERIFIED = 'verified'
    STATUS_PENDING = 'pending'
    STATUS_CHOICES = (
        (STATUS_VERIFIED, STATUS_VERIFIED),
        (STATUS_PENDING, STATUS_PENDING),
    )

    FAVOURITE_A = 'fava'
    FAVOURITE_B = 'favb'
    FAVOURITE_NONE = 'none'
    FAVOURITE_BOTH = 'AndB'

    FAVOURITE_CHOICES = (
        (FAVOURITE_A, FAVOURITE_A),
        (FAVOURITE_B, FAVOURITE_B),
        (FAVOURITE_NONE, FAVOURITE_NONE),
        (FAVOURITE_BOTH, FAVOURITE_BOTH),
    )
    source = models.ForeignKey(Customer, related_name="source_user")
    destination = models.ForeignKey(Customer, related_name="destination_user")

    status = models.CharField(max_length=25, choices=STATUS_CHOICES)
    createdAt = models.DateTimeField(auto_now_add=True, auto_now=False)
    updatedAt = models.DateTimeField(auto_now_add=True, auto_now=False)
    favourite = models.CharField(max_length=25, choices=FAVOURITE_CHOICES)

The following serializer:
class ContactSerializer(serializers.ModelSerializer):
    source_uuid = serializers.SerializerMethodField('get_field_source_uuid')
    source_email = serializers.SerializerMethodField('get_field_source_email')
    source_first_name = serializers.SerializerMethodField('get_field_source_first_name')
    source_last_name = serializers.SerializerMethodField('get_field_source_last_name')

    destination_uuid = serializers.SerializerMethodField('get_field_destination_uuid')
    destination_email = serializers.SerializerMethodField('get_field_destination_email')
    destination_first_name = serializers.SerializerMethodField('get_field_destination_first_name')
    destination_last_name = serializers.SerializerMethodField('get_field_destination_last_name')

    def get_field_source_uuid(self, obj):
        return obj.source.uuid

    def get_field_source_email(self, obj):
        return obj.source.email

    def get_field_source_first_name(self, obj):
        return obj.source.first_name

    def get_field_source_last_name(self, obj):
        return obj.source.last_name

    def get_field_destination_uuid(self, obj):
        return obj.destination.uuid

    def get_field_destination_email(self, obj):
        return obj.destination.email

    def get_field_destination_first_name(self, obj):
        return obj.destination.first_name

    def get_field_destination_last_name(self, obj):
        return obj.destination.last_name

    class Meta:
        model = Contact
        fields = (
            'source_uuid',
            'source_email',
            'source_first_name',
            'source_last_name',
            'destination_uuid',
            'destination_email',
            'destination_first_name',
            'destination_last_name',
        )

And this is the related view:
class Addressbook(APIView):
    def get(self, request):
        try:
            addressbook = Contact.objects.filter(Q(source=request.user) or Q(destination=request.user), status=Contact.STATUS_VERIFIED)
            serializer = ContactSerializer(addressbook, many=True)
            return Response(serializer.data)
        except Customer.DoesNotExist:
            content = {'status': 1}
            return Response(content, status=status.HTTP_404_NOT_FOUND)

What is this:
I have an API which allows a user to add a contact. There are two users. Lets call them source and destination, as seen in the model. Whether they are "contacts" or not is defined by their status: Pending or Verified. A user can check for pending contact requests, as well as accept such request. These are not provided, as they are working fine.
A user can retrieve their addressbook. The addressbook should return a list of contacts that are verified. Which means, that the user should not appear in said addressbook.
What is the problem:
How can I tell the serializer to either use source or destination to add the contact to the returning data, depending on whichever the logged in user is.
So when source = request.user and destination is the verified contact it should only return destination. When the destination=request.user it should only return source in the seralized data. This should obviously work for many=True, therefore at the same time.
The question
Is this possible via OUTER JOINS within the filter statement? Or would I need to work with the serializer in python, which I would probably like to avoid to keep the code as simple as possible and reusable.

A: In your serializer method, you can access to request user
def get_field_emails(self,obj):
    request = self.context.get('request')
    user = request.user
    #Here you check you user type
    if your_user_is_destination:
        return destination.email
    else:
        return source.email


text:
Q: Version code is changed automatically in build When I generate play store apk then version code is changed automatically. Here is how I define version in flavouring. How can I fix it? Any help is highly appriciated.
    core {
        dimension DIMENSION_APP_TYPE
        applicationId "com.xyz"
        versionCode 17
        versionName "1.1.6"
    }

26323252


text:
Q: React How to remove popup from a dynamically created component when i click outside I need help with a code I have been struggling with for days.
I have a list of components that I generated dynamically from an array. Each of the generated components have a button to show a text when clicked. I have been able to show/hide the text when each button is clicked however I can't make the text hide when the body of the document is clicked.
import ReactDOM from "react-dom";
const items = [
  {
    id: 1,
    text: "wake"
  },
  {
    id: 2,
    text: "sleep"
  }
];
const ButtonText = ({ id, choosenItem }) => {
  const outsideClick = (e) => {};
  React.useEffect(() => {
    document.addEventListener("click", outsideClick);
  });
  return (

      {choosenItem === id && (

          Text inside {choosenItem}

      )}

  );
};

export default function App() {
  const [choosenItem, setChoosenItem] = React.useState(null);
  const open = (id) => {
    setChoosenItem(id);
  };
  return (

      {items.map((item) => {
        return (
          <React.Fragment key={item.id}>

{item.text}

            <button type="button" onClick={() => open(item.id)}>
              click
            </button>
            <ButtonText
              id={item.id}
              setChoosenItem={setChoosenItem}
              choosenItem={choosenItem}
            />
          </React.Fragment>
        );
      })}

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/recursing-snyder-3dwo59?file=/src/App.js
Thanks in anticipation


text:
Q: 'Kotlin not configured' in Maven project after doing git rebase I created a new branch and checked out some keys to that branch and then committed it to main. I then switched to a branch called 'feature' where I was working on some other code, and changed the passwords there too so it would work.
I then did a git rebase to eliminate the files from my commit because they are already committed to main. As soon as I did this I started getting a whole host of red syntax highlighting on all my files, including all pom.xml files.
However when I run mvn test I get build successful. How do I resolve this issue?


text:
Q: TypeError: Can't convert 'int' object to str implicitly variable in math equation i am new to python but i tried to put DogAge into a math equation, still not working
Animal = input("dog or cat? ")

if Animal == "dog":
    DogAge = int(input("how old is you dog? "))
else:
    CatAge = int(input("how old is your cat? "))

if DogAge == 1:
    print("your dog's age is 11")
elif DogAge == 2:
    print("your dog's age is 22")
else:
    print("your dog's age is " + (DogAge - 2 * 4 + 22))

Gives:

TypeError: Can't convert 'int' object to str implicitly

A: The error points exactly what's going wrong. Change this:
print("your dog's age is " + (DogAge - 2 * 4 + 22))

To this:
print("your dog's age is " + str(DogAge - 2 * 4 + 22))

You can't concatenate a string object with an integer.

A: Another solution:
print("your dog's age is {0}".format((DogAge - 2) * 4 + 22))

(assuming that you want to calculate (DogAge-2) * 4 + 22, not DogAge + 14).

A: You may want to consider reorganising your code differently, to separate out the calculation of the dogs age and the actual printing of the value.
As it's possible then to refactor that code into a function later on, if it gets more complicated.
Animal = input("dog or cat? ")

if Animal == "dog":
    DogAge = int(input("how old is you dog? "))
else:
    CatAge = int(input("how old is your cat? "))

if DogAge == 1:
    calculated_dogs_age = 11
elif DogAge == 2:
    calculated_dogs_age = 22
else:
    calculated_dogs_age = DogAge - 2 * 4 + 22

print("your dog's age is {0:d}".format(calculated_dogs_age))


text:
Q: How to union four different tables I have two tables whereby both of them use sub queries. These two tables are combined by using UNION ALL.
I have two other tables that only uses a WHERE clause and both of these are combined using UNION ALL.
I am struggling to join all 4 tables as I keep getting below error when I use UNION ALL and UNION.

Msg 205, Level 16, State 1, Line 1
  All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

A: It means the number of columns you select in the top query must be the same as the number of columns in the second. If you don't have the same number, you can work around it. Below I can add a NULL to the second query because it's missing a third column.
SELECT col1,col2,col3
FROM t1
UNION ALL
SELECT col1,col2, NULL
FROM t2


text:
Q: AttributeError: module 'pygal' has no attribute 'Worldmap' I'm trying to:
import pygal
wm = pygal.Worldmap()

but it raises:
AttributeError: module 'pygal' has no attribute 'Worldmap'

Can anyone tell me what the problem is?

A: You are probably looking at old documentation from what I can tell. The most recent docs state that you first need to install the map plugin with:
pip install pygal_maps_world

and then use it as:
import pygal
mm = pygal.maps.world.World()


text:
Q: sh script that change the title of a MATE terminal tab [tcsh] Im trying to understand how to write a shell script that changes the shell tab title. Is there a certain variable that controls it?
Any way the end goal this:
changeTitle.sh newTitle

Thanks,


text:
Q: Powershell - run PsExec on multiple servers at the same time How do I run PsExec on multiple servers in parallel, and output the result to a text file? Something like:
ForEach ($s in $Srvs) {
    Psexec -s -d \\$s someexe.exe > \\$s\c$\temp\$s.txt
}

This works without the -d option, but soon as I add -d, the output is blank.
I have tried Invoke-Command, Start-Process etc. in a PS Workflow, but nothing works with piping option ">" present. I have also tried 2> and 2>$&1, no go.
Any ideas?

A: I suspect what's happening is:

*

*PsExec runs on your computer.

*It creates a connection to the server and launches someexe.exe.

*That runs on the server, outputs a reply to PsExec.

*PsExec locally gets the out, and prints it on your local computer.

*That gets redirected over the network by > to the admin share on the server.

When you use -d, PsExec quits before getting anything back from someexe.exe, so the files end up empty.
You need to escape > so it is passed as a parameter to the remote command, instead of being interpreted locally. I'm not sure how to do that in PowerShell properly, in a command prompt the escape character would be ^, and that does seem to work in PowerShell, so maybe:
ForEach ($s in $Srvs) {
    Psexec -s -d \\$s someexe.exe ^> \\$s\c$\temp\$s.txt
}

EDIT
OK, that's not it. Best answer I have at the moment is to put the command into a batch file, e.g. c:\scripts\myscript.bat, making it launch the command interpreter as well:
cmd /C someexe.exe > c:\temp\%computername%.txt

Then run that with PsExec, copying the batch file over:
ForEach ($s in $srvs) {
    psexec -s -d -c -f \\$s c:\scripts\myscript.bat
}