text:
Q: How to show a text in 2 colors in android? I have a text which has some other view overlapping with it (in a RelativeLayout). I want the part of text inside the overlapping view of a different color and that outside the view of different color. Please see the sample image for the same.
I have tried using a TextView for overlapping view and set its textColor attribute but that does not work. Any help would be appreciated.

Edit: As shown in the image, I want that some part of 'a' should be of different color and the rest inside oval to be of different color.
Edit: Consider the following sample code which illustrates my purpose. Here letter 'm' has some part inside the other part (red one). Currently all text is in white. What I need is that the part just after the boundary (from where the red color view starts) all text to be in black color. The screen shot is also attached below. Hope now I am clear.
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:background="#0000ff">

            <View
                android:layout_width="257dp"
                android:layout_height="match_parent"
                android:background="#ff0000"
                android:layout_alignParentRight="true"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="Hi I am some text"
                android:textColor="#ffffff"/>

        </RelativeLayout>

A: I figured out a way to achieve this. Although I could not find a way to show a text inside a TextView in two colors. But similar effect is possible if we create a custom view class and draw the shapes as well as text on canvas and use color blending (PorterDuffXferMode).
Here is the sample code of the onDraw method of the custom view which I used:
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int color1 = Color.rgb(137, 195, 246);  // outside background's color
    int color2 = Color.rgb(246, 187, 137);  // inside background's color
    int color3 = Color.WHITE;   // outside text's color
    int color4 = Color.BLACK;   // inside text's color

    canvas.drawColor(color1);   // fill outside background

    // make inside oval shape and fill it
    Paint paint = new Paint();
    paint.setColor(color2);
    canvas.drawArc(getWidth()*0.36f, 20, getWidth()*3/4, getHeight()-20, 0, 360, false, paint);

    /* create a bitnmap for a new canvas */
    Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), ARGB_8888);
    Canvas bitmapCanvas = new Canvas(bitmap);   // new canvas

    /* draw text on bitmapCanvas */
    paint.setColor(color3);
    paint.setTextSize(80);
    bitmapCanvas.drawText("Hi I am some text", 50, 140, paint);

    /* use "source in" PorterDuff mode and draw inside oval on bitmapCanvas
    *  using color4 so that only the text inside oval will remain in color4 and
    *  rest will be transparent*/
    Xfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    paint.setXfermode(xfermode);
    paint.setColor(color4);
    bitmapCanvas.drawArc(getWidth()*0.36f, 20, getWidth()*3/4, getHeight()-20, 0, 360, false, paint);

    /* draw this bitmap to original canvas */
    paint.setXfermode(null);
    canvas.drawBitmap(bitmap,0,0,paint);
}

And the view look likes this:

A: Try to  create Spannable  and set that Spannable to your textview,try like this
 TextView textview = (TextView)findViewById(R.id.textview);

    Spannable colorSpan = new SpannableString("HI I am some text");

    colorSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    textview.setText(colorSpan);

A: just add your sentence in string.xml like this:
<resources>
  <string name="some_text">Hi i amsome red text</string>
</resources>

and you can set like this:
String styledText = getResources().getString(R.string.some_text);
sometext.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);


text:
Q: onClick event - Run a javascript AFTER previous one has finished in the same onClick event Code looks like this (My PHP server generates this line replacing the %% variables):
<button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y');ShowFieldTotal('inv_items','iprice','sub-total',2);">+</button>;

I want THIS
ShowFieldTotal('inv_items','iprice','sub-total',2);

to run ONLY when the elements of the first script have been added on my webpage. Basically, it adds an item line in a table and, what I actually want it to do that I can't do, calculate the total of each items once their lines have been added to the table from the first script:
ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y')

A: Modify your ServInfo function like this.
function ServInfo (args...) {
    --- your code ---
    ....
    ....

    //call ShowFieldTotal when ServInfo() is finished.
    ShowFieldTotal(args...);
}

A: You can make another function which calls the two functions one after another and bind that function to the onclick event.

A: ControlAltDel's answer makes it simple and easy. I actually added another parameter to my ServInfo which catches a string which it converts to code. Basically, I called the "eval" function to parse the code written in a string I pass to ServInfo. My new onClick event looks like this:
<button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y','ShowFieldTotal(\'inv_items\',\'iprice\',\'sub-total\',2)');">+</button>

I added the following to my ServInfo code:
// Execute a string if a user defined one
        if (exec_string != "") {
            eval(exec_string);
        }

For the curious, My ServInfo function now looks like this:
// AJAX simple HTTP GET request
function ServInfo(pop_field_id,web_page,params="",form_id="",append_data_to_output = "",exec_string = "") {

var sparams = params;
var swpage = web_page;
var eobj = document.getElementById(pop_field_id);

// Get form field values if a form id is specified
if (form_id != "") {
    var efrm = document.getElementById(form_id);
    sparams += "&"+GetDivFields(form_id);
}

// If HTML element to populate does not exist, exit
if (typeof(eobj) == "!undefined" || eobj == null)   {return;}

if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else {
    // IE6-
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        if (append_data_to_output == "y") {
            document.getElementById(pop_field_id).innerHTML += this.responseText;
        }
        if (append_data_to_output == "") {
            document.getElementById(pop_field_id).innerHTML = this.responseText;
        }
        // Execute a string if a user defined one
        if (exec_string != "") {
            eval(exec_string);
        }
    }
};
// Add the question mark if there is any parameters to pass
if (sparams != "") {swpage += "?";}

xmlhttp.open("GET",swpage+sparams,true);
xmlhttp.send();

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should the header ctgmath/ tgmath.h be used? Should I use the header ctgmath? It automatically includes cmath and ccomplex. It has some predefined macros. Should its inclusion affect my code or usage of these macros decrease the efficacy?

A: No, Simply including the headers in your code doesn't decrease the efficiency... Also macro inclusion doesn't change the speed cos, macro expansion happens during compile time not at run time.


text:
Q: Jquery disable slide function on I am using smart slider (http://www.egrappler.com/jquery-slidertrackbar-smart-slider/ )
Which is a nice jquery.
For one use on one page though; I want the slider to appear though I want to disable the sliding effect. So it's just visual and not an interactive element. There is not a lot of documentation to this one and my changes seem to blow it up. Any thoughts would be greatly appreciated.
// JS
$('#trackbar1').strackbar({
    callback: onTick1,
    defaultValue: 20,
    sliderHeight: 25,
    sliderWidth: 500,
    style: 'style1',
    animate: true,
    ticks: false,
    labels: false,
    trackerHeight: 20,
    trackerWidth: 20
});
});

function onTick1(value) {
    $('#percentageworked').val(+ value);
}

// HTML

A: You could try to disable it.
$('#trackbar1').strackbar({
               callback: onTick1,
               defaultValue: 20,
               sliderHeight: 25,
               sliderWidth: 500,
               style: 'style1',
               animate: true,
               ticks: false,
               labels: false,
               trackerHeight: 20,
               trackerWidth: 20
}).prop('disabled', true);


text:
Q: É possível concatenar um seletor jQuery com uma variável? Tenho o seguinte código dentro de uma função javascript que esta dentro de uma pagina .php:
if (indice_da_aba == -1)
{
   window.alert('não existe ABAS AINDA');
}
else
if (indice_da_aba == 0)
{
   $('a[href="#tab_00"]').tab('show');
}
else
if (indice_da_aba == 1)
{
   $('a[href="#tab_01"]').tab('show');
}
else
if (indice_da_aba == 2)
{
   $('a[href="#tab_02"]').tab('show');
}

Como podem ver são muitos ifs.
Gostaria de saber se é possível escrever um if da seguinte forma:
if (indice_da_aba == -1)
{
   window.alert('não existe ABAS AINDA');
}
else
{
   $('a[href="#tab_0+indice_da_aba+"]').tab('show');
}

Do modo que escrevi não funciona.  Teria um modo certo de escrever (concatenar) essa linha ou não é possível?

A: Sim, usando o operador de concatenação (+).
$('a[href="#tab_0' + indice_da_aba + '"]').tab('show');

Só que pra isso, você precisa ter um valor em cada lado do operador. No código mostrado, você até usou os +, porém esqueceu de fechar as aspas para "fechar" a string.
Também pode fazer de uma forma mais moderna, usando template strings:
$(`a[href="#tab_0${indice_da_aba}"]`).tab('show');

Note que esta última forma pode não funcionar em alguns browsers.
Veja funcionando:

const indice_da_aba = 123;

console.log('a[href="#tab_0' + indice_da_aba + '"]');
console.log(`a[href="#tab_0${indice_da_aba}"]`);

A: Você apenas esqueceu as aspas simples antes e depois do +

if (indice_da_aba == -1){
   window.alert('não existe ABAS AINDA');
}else{
   $('a[href="#tab_0'+indice_da_aba+'"]').tab('show');
}


text:
Q: Blitting FBO Color Attachments I have 2 FBOs + MRT and they have identical attachments(4 color attachments each). using glBlitFrameBuffer works as expected for the depth buffer and for one color_attachment. However, when i blit multiple color attachments, things go bad. I have done a lot of research and tried a lot of different methods, none works. I am not using renderBufferStorage because my textures have different internal formats(RGBA and RGB16F). This sounds like a similar problem, except i am not using multisampling, only MRT.
OpenGL version 4.3
Why: I want to create a state of the terrain pre- lighting calculations so that i only need to render the terrain if there are changes(ie. camera movement) and then copy these color attachments to the next FBO. This is for deferred shading and the FBOs resembles the gBuffer a lot.
At first i expected that i should use glDrawBuffers which i am using in the initial setup, but there is no glReadBuffers and therefore i am assuming i have no way to link them. I might be wrong here, not an expert yet =)
Original code is written in Golang, should be easily transferable to C++ (will translate if requested).
UPDATE/SOLVED: For anyone stumbling onto this issue. When you are using glDrawBuffers() and using a call to glDrawBuffer() you are overwriting your glDrawBuffers() state. It needs to be reset to its orignal glDrawBuffers() state.
Update2: For those interested in a method like this i can confirm that it has incredible performance results, if you have a non-animated world and the camera doesn't move that often. For my purpose it is great (RTS), but for a FPS game like CS it would be a very bad approach.
Add the following after blitting (case specific):
var attachments = [4]uint32{gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1, gl.COLOR_ATTACHMENT2, gl.COLOR_ATTACHMENT3}
gl.DrawBuffers(4, &attachments[0])

FBO setup
gl.GenFramebuffers(1, &fbo.ID)
gl.BindFramebuffer(gl.FRAMEBUFFER, fbo.ID)

//setting up color attachments

gl.GenTextures(1, &fbo.Position)
gl.BindTexture(gl.TEXTURE_2D, fbo.Position)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGB16F, windowWidth, windowHeight, 0, gl.RGB, gl.FLOAT, nil)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, fbo.Position, 0)

//repeated 3 times for the additional color attachments

var attachments = [4]uint32{gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1, gl.COLOR_ATTACHMENT2, gl.COLOR_ATTACHMENT3}
gl.DrawBuffers(4, &attachments[0])

gl.GenRenderbuffers(1, &fbo.DepthBuffer)
gl.BindRenderbuffer(gl.RENDERBUFFER, fbo.DepthBuffer)
gl.RenderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT, windowWidth, windowHeight)
gl.FramebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, fbo.DepthBuffer)

gl.BindFramebuffer(gl.FRAMEBUFFER, 0)

And now to the blitting part.
gl.BindFramebuffer(gl.READ_FRAMEBUFFER, fboIn.ID)
gl.BindFramebuffer(gl.DRAW_FRAMEBUFFER, fboOut.ID)

//works as expected
gl.BlitFramebuffer(0, 0, windowWidth, windowHeight, 0, 0, windowWidth, windowHeight, gl.DEPTH_BUFFER_BIT, gl.NEAREST)

//works as expected
gl.ReadBuffer(gl.COLOR_ATTACHMENT0)
gl.DrawBuffer(gl.COLOR_ATTACHMENT0)
gl.BlitFramebuffer(0, 0, windowWidth, windowHeight, 0, 0, windowWidth, windowHeight, gl.COLOR_BUFFER_BIT, gl.LINEAR)

//fails - no errors but produces some weird occurrences.
gl.ReadBuffer(gl.COLOR_ATTACHMENT1)
gl.DrawBuffer(gl.COLOR_ATTACHMENT1)
gl.BlitFramebuffer(0, 0, windowWidth, windowHeight, 0, 0, windowWidth, windowHeight, gl.COLOR_BUFFER_BIT, gl.LINEAR)

gl.BindFramebuffer(gl.FRAMEBUFFER, 0)

A: glDrawBuffer(x) is conceptually equivalent to calling GLenum bufs[1]={x}; glDrawBuffers(1, bufs). SInce the draw buffer state is part of the FBO state, your blitting code overwrites these states, and if these are not restored manually, the rendering afterwards will not work as intended. If you call this in a loop, this might lead to the wrong conclusion that the blitting is the issue, but in reality,the blitting is working correctly, just on wrong input data.


text:
Q: Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25 I'm trying to use javamail in a groovy script to send out an email via gmail. I've looked many places online and have been unable to get it working thus far. The error I'm getting when running my script is:
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 25, isSSL false
Caught: javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25 (javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?))

It appears to be trying to use port 25 even though I've specified that it should use port 587. Does anyone know what could be causing this problem, I've used telnet to connect to the smtp server on port 587, and thunderbird uses port 587 with STARTTLS security and is able to successfully send mail using the smtp server. This tells me that it is not a blocked port or connectivity issue. Here is the code I'm using to try and send the email:
import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('email@gmail.com', 'password');
    }
}

def  d_email = "email@gmail.com",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "587", //465,587
        m_to = "email@gmail.com",
        m_subject = "Testing",
        m_text = "This is a test."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport.send(msg)

Any help would be greatly appreciated. Thanks in advance!
-Bryan

A: Maybe useful for anyone else running into this issue: When setting the port on the properties:
props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

A: In Java you would do something similar to:
Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

A: For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:
import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('email@gmail.com', 'test1234');
    }
}

def  d_email = "email@gmail.com",
        d_uname = "email",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "465", //465,587
        m_to = "testepscript@gmail.com",
        m_subject = "Testing",
        m_text = "Hey, this is the testing email."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();


text:
Q: Unable to open .sps.bak database backup file with SQL Server 2012 Express edition I am using SQL Server 2012 Express edition. Client sent me the SQL Server backup file with the extension .sps.bak. I am not able to open it with SSMS. Please somebody help me here.
I get the following error message.

Restore of database failed.
  System.Data.SqlClient.SqlError: the
  database was backed up on a server running version 10.50.1600. That
  version is incompatible with this server, which is running 10.00.1600.
  Either restore the database on a server that supports the backup or
  use a backup that is compatible with this server.

I cannot open the database that was developed with a professional edition on an Express edition?

A: That's probably a Sharepoint backup. Restore it in Sharepoint, or ask for a SQL server backup
Your error message shows that you are connected to a SQL 2008 server, not SQL 2012, and that the backup was performed on a SQL 2008 R2 server. You need an R2 server, or SQL 2012, to restore it.


text:
Q: Why does this text not appear in JSF? I have the following HTML file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
>

<head>
<title>First Example JSF Program</title>
<head>

<body>
   Hello <h:outputText value="Darwin"></h:outputText>!
</body>
</html>

But the output, expected 'Hello Darwin!' won't appear. Only 'Hello !' appears. Why is this? There are no errors and I'm sure it has all JAR files necessary - if it didn't it would throw an error right?
Cheers
P.S. This is an HTML 5 file, does that make a difference?

A: That can happen if the request URL as you see in browser's address did not match the <url-pattern> of the FacesServlet as definied in webapp's web.xml and hence the FacesServlet wasn't able to do its job of performing all the JSF works.
If you right click the page in browser and do View Source, you should have noticed that the JSF <h:outputText> tag is completely unprocessed. JSF tags  aren't recognized by the webbrowser. They are supposed to be processed by the FacesServlet in the webserver. They are supposed to generate proper HTML code and the final HTML result should not contain any JSF tags at all.
You need to make sure that the request URL as you see in browser's address matches the <url-pattern> of the FacesServlet as definied in webapp's web.xml. Imagine that it is *.jsf like as
<url-pattern>*.jsf</url-pattern>

then you should need to change the URL in the address bar from /some.xhtml to /some.jsf.
Alternatively, you could also just change the web.xml to map the FacesServlet on *.xhtml directly
<url-pattern>*.xhtml</url-pattern>

so that you don't need to fiddle with virtual URLs anymore.
As to the file having HTML5 doctype, no that makes absolutely no difference. I'd only remove that XML prolog as that's valid for XHTML doctype only. See also Is it possible to use JSF+Facelets with HTML 4/5?


text:
Q: Prove that a complex valued polynomial over two variables has infinitely many zeroes This is a homework question that I am struggling with. Given a polynomial over the complex numbers in two variables, show that the polynomial has infinitely many zeroes.
So let's say that the polynomial is a functions of $u$ and $v$. Let's consider the polynomial as a function of $u$, with $v$ as a parameter: $P_v(u)$. Then for each $v$ there is going to be a finite set of values. So now I should be able to proceed by contradiction by finding a suitable value or constraint on $v$, but I'm not sure how to proceed.

A: Since you included the (algebraic-geometry) tag, let me answer in an algebro-geometric fashion:
The (closed) points of $\mathbb{A}^2_\mathbb{C}$ correspond to maximal ideals in the polynomial ring $\mathbb{C}[u,v]$. A polynomial $P \in \mathbb{C}[u,v]$ vanishes at a point $(u_0, v_0) \in \mathbb{A}^2_\mathbb{C}$ iff $P \in (u - u_0, v - v_0)$. If $P$ is nonconstant, then we can factor $P$ into irreducibles, and replacing $P$ by one of its irreducible factors, we may assume $P$ is irreducible.
Thus, we wish to show that the quotient ring $R = \mathbb{C}[u,v]/(P)$, which is a domain but not a field, has infinitely many maximal ideals. But $R$ is a Jacobson ring by the general Nullstellensatz, so the prime ideal $(0)$ in $R$ is an intersection of maximal ideals. If there were only finitely many maximal ideals, then $(0)$ would be a finite intersection of maximal ideals; but then $(0)$ would be maximal by the following proposition, contradiction.
Proposition: If a prime ideal $p$ is equal to a finite intersection of ideals, $p = I_1 \cap ... \cap I_n$, then $p = I_j$ for some $j$ (use the fact that if $IJ \subseteq p$, then $I \subseteq p$ or $J \subseteq p$).
Note 1: The same reasoning above works over any algebraically closed field, not just $\mathbb{C}$.
Note 2: This also works in higher dimensions: if $P$ is a nonconstant polynomial in $n$ variables over an algebraically closed field $k$, then the zero set $V(P)$ contains infinitely many closed points of $\mathbb{A}^n_k$.
Note 3: This was surprisingly complicated reasoning, requiring use of heavy theorems. I would be interested in seeing more elementary proofs of the statement in Note 2.

A: Let $f\in \mathbb{C}[x,y]$ and suppose $V(f)$ is finite. Take, $(a,b)\in V(f)$ and write $f$ as $$f(x,y)=\sum_{k=0}^{n}f_k(x)y^{k}.$$
Notice that $f(a,y)=\sum_{k=0}^{n}f_k(a)y^{k}$ is a non-constant polynomial. Otherwise, as $f(a,b)=0$ we would get $f(a,y)=0$ and therefore $V(f)$ would be infinite. As $f(a,y)$ is not constant we assure that there exists $0<k\leq n$ (if the only $k$ such that $f_k(a)\neq 0$ is k=0 then the polynomial would be again constant) such that $f_k(a)\neq 0$ and therefore $f_k(c)\neq 0$ for all $c\in \mathbb{C}$ except for finitely many exceptions.
But this means that the polynomial $f(c,y)$ is not constant for infinitely many $c$, and by the fundamental theorem of algebra, a root $y_c$ must exist! Therefore, for every $c\in \mathbb{C}$, there exists $y_c\in\mathbb{C}$ such that $(c,y_c)\in V(f)$. Therefore, $V(f)$ must be infinite! (in fact, uncountable)

A: Here is an elementary proof. The idea is straightforward, the details a little tedious.
Suppose $p$ is a non-constant polynomial. By translating if necessary, we may assume $p(0,0) \neq 0$.
Let $Z= p^{-1}\{0\} \subset \mathbb{C}^2$ be the zero set, and note that $(0,0) \notin Z$. Furthermore, since $p$ is non-constant, we can find some other point $(x_0,y_0) \notin Z$ such that $p(x_0,y_0) \neq p(0,0)$.
Hence we can find some $\epsilon>0$ such that if $(x,y) \in B((x_0,y_0), \epsilon)$, then $p(x,y) \neq 0$ and $p(x,y) \neq p(0,0)$.
Choose $\theta \in [0,\pi)$ and let $\lambda_\theta: \mathbb{C} \to \mathbb{C}^2$ be given by $\lambda_\theta(t) = (t \cos \theta, t \sin \theta)$. Note that if $\theta \neq \phi$ with $\theta,\phi \in [0,\pi)$, then $\lambda_\theta(\mathbb{C}) \cap \lambda_\phi(\mathbb{C}) = \{(0,0)\}$.

Define the polynomials $p_\theta:\mathbb{C} \to \mathbb{C}$ by $p_\theta = p \circ \lambda_\theta$, and let $Z_\theta = p_\theta^{-1}\{0\} \subset \mathbb{C}$. Note that $0 \notin Z_\theta$.
Let $\Theta = \{ \theta \in [0,\pi) | \lambda_\theta(\mathbb{C}) \cap B((x_0,y_0), \epsilon) \neq \emptyset \}$, and note that $\Theta$ must contain some interval $(\theta_0,\theta_1)$.
Note that if $\theta \in (\theta_0,\theta_1)$, then $p_\theta$ is a non-constant polynomial (in one variable) and hence $Z_\theta \neq \emptyset$.
Finally, let $W=\{\lambda_\theta(t) | \theta \in (\theta_0,\theta_1), t \in Z_\theta\}$, and note that $W$ is infinite (since $(\theta_0,\theta_1)$ is uncountable) and $W \subset Z$.


text:
Q: How to Put the Back Button in Left of my ActionBar I'm building and finishing a Android App and this is one of the main things I need to Fix it up.
So, I have a Action Bar styled like this:
<resources>
    <style name="MyCustomTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBarTheme</item>
    </style>

    <style name="MyActionBarTheme" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#F6E6E7</item>
        <item name="android:textSize">10sp</item>
    </style>

    <style name="CustomTabWidget">
        <item name="android:textSize">15sp</item>
    </style>

</resources>

And this is the layout where i put the button
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->

    <item android:id="@+id/voltar"
        android:title="Voltar"
        android:icon="@drawable/abc_ic_ab_back_holo_light"
        android:showAsAction="ifRoom" />
    <!-- Settings, should always be in the overflow -->

</menu>

this Button Tittled Voltar is at the Right Side of the Action Bar.. What Should I Do to put this on Left Side?
Thank you for read this

A: You need to do two things. First declare this in the onCreate of your activity
getActionBar().setDisplayHomeAsUpEnabled(true);

Then implement the onOptionsItemSelected so that it handles the home as up button click event
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home ) {
        finish();
        return true;
    }
    // other menu select events may be present here

    return super.onOptionsItemSelected(item);
}

A: Declaring getActionBar().setDisplayHomeAsUpEnabled(true); in the onCreate of your activity is right.
However, onOptionsItemSelected implementation suggested by Nayan in the post above can be improved and should be handled as per code below:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        NavUtils.navigateUpFromSameTask(this);
//            finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

The id android.R.id.home represents the Home or Up button. Declaring getActionBar().setDisplayHomeAsUpEnabled(true); will cause the UP (Back/Left Arrow) button to be show. Use NavUtils to allow users to navigate up one level in the application structure.
For more details, see the Navigation pattern on Android Design:
http://developer.android.com/design/patterns/navigation.html#up-vs-back

A: Back Button is supported in android by default.
You don't need to create the button manually.
Just in the Activity's onCreate() method
getActionBar().setDisplayHomeAsUpEnabled(true);


text:
Q: Change full : App displayName, logo, iOS and Android [2018]? I have an existing app, on both stores, iOS, and Android. But I want to change the logo and of course the Name.

*

*I saw that I couldn't change the bundle ID (for ex: mobile.myapp.com) because it will create an entirely new app without savings ratings and downloads number.

*So I wanted to know that, if I was only modifying the display Name, there was a chance for the user to still access the bundle ID and see the previous name? And if it will affect the referencing on the store?

*For iOS, I can modify: Bundle Display Namewithout modify bundle ID right?
In both case, generally how long is the time review for submitting a completely new app or just an update but with modifications on the name and logo?
Thanks for the help


text:
Q: Limit number of textarea characters per line in Jquery In my text area, I should be able to enter only 13 characters per line in multiline textarea. In each line i need to check whether the value the user entered is 13 characters If suppose the user has entered less than 13 i need to show the alert message...How can i do that?? In the below code i have restricted space,dot etc from the input..

$('#splitLines').keypress(function(e) {
  if (!((e.which >= 65 && e.which <= 90) ||
      (e.which >= 48 && e.which <= 57) ||
      (e.which >= 96 && e.which <= 105) ||
      (e.which >= 97 && e.which <= 122) ||
      e.which == 13)) {
    e.preventDefault();
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="11" cols="60" name="txtarea[]" id="splitLines" value=""></textarea>

A: For testing:
$('#btn').on("click", function(e) {
  let num = $("#splitLines").val().split('\n')
  //get value and split it into new lines
  console.clear()
  console.log(num)
  num.forEach(e => {
  // for each new line
    let n = e.split("")
    //get number of chars
    console.log(n.length)
    if (n.length !== 13) {
    // if some line dos not have 13:
      alert("Each line needs 13 char")
    } else {
    // all good
      console.log(true)
    }
  })
});

Simplified solution:

$('#btn').on("click", function(e) {
  $("#splitLines").val().split('\n').forEach(e => {
    e.split("").length !== 13 ? alert("Each line needs 13 char") : console.log(true)
  })
});
1234567890123
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="11" cols="60" name="txtarea[]" id="splitLines" value=""></textarea>
<button type="button" id="btn">test</button>

And if you want to alert the line number of errors:

$('#btn').on("click", function(e) {
  $("#splitLines").val().split('\n').forEach(function callback(e, index) {
    e.split("").length !== 13 ? alert(`Each line needs 13 char, error on line ${index+1}`) : console.log(true)
  })
});
1234567890123
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="11" cols="60" name="txtarea[]" id="splitLines" value=""></textarea>
<button type="button" id="btn">test</button>

A: We can use .split("\n") to get the number of lines & then check its length to get the count.

$('#splitLines').keypress(function(e) {
  if (!((e.which >= 65 && e.which <= 90) ||
      (e.which >= 48 && e.which <= 57) ||
      (e.which >= 96 && e.which <= 105) ||
      (e.which >= 97 && e.which <= 122) ||
      e.which == 13)) {
    e.preventDefault();
    return false;
  }
});

// Restrict to 13 characters
$("#splitLines").keyup(function (event) {
    var maxlength = 13;

    var text = $(this).val();
    var lines = text.split(/(\r\n|\n|\r)/gm);
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > maxlength) {
            lines[i] = lines[i].substring(0, maxlength);
        }
    }
    $(this).val(lines.join(''));
});

//Show alert based on line length
$("#btnSubmit").click(function(){
  var text = $('#splitLines').val();

  lineCount = 0;
  flag = false;
  if (text) {
    var lines = text.split("\n");
    for (var i = 0; i < lines.length; i++) {
      console.log('each line length', lines[i].length);

      if (lines[i].length < 13) flag = true;
      if (lines[i].length > 0) lineCount++;
    }
    console.log('total lines with text', lineCount);
    if (flag === true) alert('Less than 13 in a line');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea rows="11" cols="60" name="txtarea[]" id="splitLines" value=""></textarea>
<button id="btnSubmit">Get Line Counts</button>


text:
Q: Cycle option when drawing between nodes in TikZ Cycle lets you close curves when drawing, and
\coordinate (a) at (0,0);
\coordinate (b) at (1,0);
\coordinate (c) at (0.5, -1);
\draw (a) -- (b) -- (c) -- cycle;

works fine. Shouldn't also
\node (a) at (0,0) {};
\node (b) at (1,0) {};
\node (c) at (0.5, -1) {};
\draw (a) -- (b) -- (c) -- cycle;

give the same result?
The former gives a triangle, while the second doesn't close up. Is this a bug or am I missing something regarding the cycle option?
(Of course, as a workaround I could use the coordinates to draw the cycled path, and then draw the nodes at the same coordinates, but still...)

A: When you specify a bare node as a coordinate, as in (a), then TikZ tries to be helpful and interpret that as the most appropriate target on a.  Most of the time, this is exactly what you want: \tikz \draw[->] (0,0) node (a) {A} (1,0) node (b) {B} (a) -- (b); typesets A → B, with the arrow starting a little to the right of the A and ending a little to the left of the B.
However, when doing a "cycle", you don't want that behaviour.  You want the lines to join up.  Even empty nodes have size, unless you explicitly tell them not to.  So you need to override this "helpfulness" which is done by specifying which target you mean.  Thus:
\node (a) at (0,0) {};
\node (b) at (1,0) {};
\node (c) at (0.5, -1) {};
\draw (a.center) -- (b.center) -- (c.center) -- cycle;

does what you want it to.
There are other ways to do this, in particular as your nodes are empty you could force them to have zero size.  Indeed, \coordinate is actually a shorthand for \node[coordinate] and the special shape coordinate has empty size.  So your first example, which works, is actually a special case of the second where the nodes are fiddled to be "point masses".


text:
Q: Refractive index variation with wavelength of light In my book it is written that

$$\text{refractive index} = c/v =\sqrt{\text{permeability} \times \text{permittivity}}$$
The dielectric constant medium is dependent on the frequency of the field. For example for dc fields, the dielectric constant of water is 80.4 while in the frequency range of visible light it is 1.8 only. It is because in highly oscillating fields the dipoles fail to orient with the oscillating field.

According to this refractive index should increase with increasing wavelength
But also
$$\text{refractive index} = a + b/\mathrm{wavelength}^2,$$
which decreases with increases wavelength. How is this possible?

A: $a + b / \lambda^2$ is just an approximation. It's typically used in a limited range, e.g. across visible light frequencies.
The approximation breaks down outside that range: X-rays don't refract strongly in glass.
Physically, the $1/\lambda^2$ term, perhaps better seen as an $\omega^2$ term, is due to the dipoles "falling behind" the incident wave. At higher frequencies, that lag matters more. At high enough frequencies, the dipoles start to behave in other ways, and the approximation breaks down.
More formally, the response of a material has poles and zeros, and this is an approximation to how you approach one.

A: Analytic and as well empiric equation $n(\lambda)$ are both material dependant. It is called dispersion relation.
For BK7 glass this seems quadratic with a positive coefficient $b$. See best resource refractiveindex.info including dispersion equation $n^2(\lambda)$ in polynominal approximation.

Depicted is BK7 of Hoya: $n^2(\lambda)\approx 2.27+ 0.0116\cdot\lambda^{-2}- 0.0092\cdot\lambda^{2}$


text:
Q: Email configuration in Redmine - undefined method `address=' I'm not an expert in Ruby and Redmine, but I'm trying to configure email notifications in redmine.
Redmine version 3.4
ruby 2.3.3p222
Phusion Passenger 5.1.7
In configuration.yml I have
production:
email_delivery:
delivery_method: :smtp
smtp_settings:
address: "xxxx.pl"
port: 587
authentication: :plain
domain: 'redmine.xxx.pl'
user_name: '.....@redmine.xxx.pl'
password: '......'

But I get this error:
Error ID: 54731089
  Error details saved to: /tmp/passenger-error-WqNBmN.html
  Message from application: undefined method `address=' for ActionMailer::Base:Class (NoMethodError)

I search little bit and figure out, that I have missing methods in application.rb file.
So in Redmine config/application.rb I add something like that:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address:              "xxx.pl",
port:                 587,
user_name:            'powiadomienia@redmine.xxx.pl',
password:            '.....',
authentication:       :plain
}

but still have the same error. Unfortunately I can't find any examples in Redmine configuration.
Can anyone help me?

A: Make sure your configuration.yml is properly indented (use 2 spaces per level of indentation):
production:
  email_delivery:
    delivery_method: :smtp
    smtp_settings:
      address: 'example.org'
      port: 587

The smtp settings (address, port etc) need to be keys in the smtp_settings hash. From the error you get I'd say they are keys on the same level as smtp_settings, which is wrong.


text:
Q: URL open new window adjust size I am using a map on my website. When you click a link on the map it opens a new window. The rest of the site uses colorbox to open new links so in a desire to keep it close to that in appearance, I would like the new window that opens to be more like a popup not like a new tab. Currently I just have this:
url_new_tab: 'yes',
Any help would be appreciated.

A: colorbox is good idea.
otherwise you may use
window.open('your_url', '_blank', 'width=600, height=300');

A: I figured it out for anyone having the same issue:
url: "javascript:'onclick'=window.open('url_here', '_blank','width=800, height=500');",


text:
Q: Dynamically change icon of a widget in NetBeans I am currently developing a plugin for NetBeans (in short the goal is to integrate my company's tool to NetBeans), and I thought it would be good to have a little widget on the widget bar to tell if my tool is enabled or not.
I saw Geertjan blog post  regarding widget buttons, but what he does is enable/disable the button, what I want to do is to change the icon to notify the user of the tools status, and when he clicks on it turns on/off the tool.
Is it doable on NetBeans?
I tried to change layer.xml iconbase attribute to a method to dynamically change this but it doesn't seem to work, at least with when I tried (<attr name="iconBase" stringvalue="TWIconWidget.CTCIcon.getIconPath"/>)
I also tried with an ImageWidget cast on the actionPerformed() of a widget but I can't find a way to see it in the widget toolbar.
Do you have any tips on how to do this?
Thanks in advance
EDIT :
If it is not possible, can you offer some alternatives to it, such as a slide button or something that could suit the needs and be visible on the widget bar

A: This post shows a way to do it (credits to the author Hermien Pellissier): http://www.pellissier.co.za/hermien/?p=646
Basically you create an Action using the Netbeans wizard and modify it to extend from AbstractAction and implement Presenter.Toolbar.
You can then override getToolbarPresenter() to return any Component you want to show in the toolbar, for example a JButton or a custom component.
Using the Component methods you can change its appearance, for example:
public final class SomeAction extends AbstractAction implements Presenter.Toolbar {

    private JButton button;

    @Override
    public void actionPerformed(ActionEvent e) {
        // change the button image
        ImageIcon icon = new ImageIcon("another_image.png");
        button.setIcon(icon);
    }

    @Override
    public Component getToolbarPresenter() {
        ImageIcon icon = new ImageIcon("image.png");

        // create the button to show
        button = new JButton(icon);
        button.addActionListener(this);

        return button;
    }
}


text:
Q: Does zmap / zlint includes the algorithms of kroeckx / x509lint? I'm trying to verify the integrity and format of certificates as part of a complex process.
There is an existing implementation of this process already using zlint and I have just updated it with the current 3.4.0 release.
As part of the planned changes I have to also check the certificates with x509lint but I'm a bit worried because the project doesn't seems to be so active and I cannot see anywhere in the repo, the algorithms that x509lint checks in order to compare the redundancy. So I'm thinking that maybe it's an unnecessary change because everything that x509lint would check, it's already covered by zlint, but I cannot find the the documentation to compare.
I searched on Google but there is little information of the project involved (x509lint).
I've also explored the code itself but couldn't find any clue (although I'm no C expert)


text:
Q: I keep getting status 400 bad request I am trying to use fetch function with post method to send some data to an api endpoint which is in my local, the problem is when I used client side to test the endpoint & the link I got successful response , however when I use it in my react app I keep getting status 400 bad request
what do you think the problem is?
my request code in my app:
const onClick=async()=>{

    try{
     let result=await fetch("http://127.0.0.1:3000/api/send",{
      method:"POST",
      headers:{
        "Accept":"application/json",
        "Content-type":"application/json;",
      },
      body:{
        "emails": [
            "aaa@aaa.com",
            "bbb@bbb.com"
        ]
    }
     });


text:
Q: Error 403 when trying to access Raspberry Pi web page from PC browser I'm working on a project for school and I'm trying to read data from a web page on my raspberry pi and display it on my page on my PC web page. I'm using ajax, but when I try to access the web page on RPi on IP 192.168.1.8 it gives me an: "error 403 forbidden" error so I don't know what to do
my code to get to the page:
function AddShoots() {
  $.ajax({
    method: "POST",
    url: "http://192.168.1.8",
    success: function (html) {
      alert(html);
    },
  });
}

error image:
if it's any help, sorry for the language I'm from Slovenia, so it's Slovene

A: Fixed it!

*

*I adjusted IP addresses on my PC and RPi. I have them connected through a straight-through ethernet cable, so I set a static IP on my PC for an ethernet connection and I set static IP on my RPi for eth0.

*I enabled cross-network sharing in the network settings on PC

*I enabled headers and added CORS header on apache (how to enable them on here)


text:
Q: Using a single DLL for multiple projects requiring it So, I have currently a lot of projects on my computer all using the same library. What bugs me is they all have to have the same DLL in their respective folders. Granted, I don't need to copy them manually(My compiler does the job for me), but that's not the problem. The problem is I have ~25 copies of the same, huge DLL lying around.
So I was wondering if I could define a path variable with the DLL or something of that kind, so that upon execution, the program can find it at a precise point. The thing is, since I sometimes pass these projects to others, it would need to work with the dynamic link library just inside the folder and not elsewhere. And of course, if there is an app that I download using the same library but another version, of course it should not priorize the DLL I defined the path to but the one bundled with it.
So, in summary, I need my programs that can't find a DLL in their folders to fall back on a precise, predefined directory to find it.
I'm not sure it is possible. Any help would be greatly appreciated, and already, thank you for reading this.

A: For local development, easiest way is to just have a copy of the DLL in your PATH environment.  The cheesiest way, although not recommended for customers, is to just copy the DLL to your your System directory. That is, copy it into c:\windows\system32 or c:\windows\syswow64. Perfectly fine for development purposes.
Or create a custom folder just to hold a copy of this DLL.  Update your Windows PATH via Control Panel to point to this directory that has the DLL.
Or use an App Paths registry key to amend the PATH for a specific EXE.
All of these solutions have a versioning issue, which may or may not be a problem for local development.
For distributing code to customers, just have the EXE and dependent DLLs in the same folder is the most tried and true method.
Also, read this: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order


text:
Q: Return spring mvc Model on Ajax response I am having a controller that return model objects like below
model.addAttribute("list", list);
When i click a button ajax call happens and it is goes to controller executing everything and it returns. But i don't know how to access this model object in my jsp on ajax response. When i use alert for success ajax response , I am just seeing a html kind of page.
Please give me some example or reference to achieve this
Thanks in advance
Please find my sample code snippet
Controller.java
@RequestMapping(value='/ajax' value="POST")
 Public @ResponseBody String displayDropdown(MyForm myform,Model model) {
 //logic to fetch details from DB
 List<String> list = fetchFromDB();
 model.addAttribute("list" list);
 return "ajaxResponse";
}

My JSP
In a button click, having the below ajax call
$.ajax {
   url:'/ajax',
   type:'POST',
   data: $("#myform").serialize();
   success:function(data) {
   alert(response);
   }
}

I want to get my model from this ajax response and use it in my jsp.

A: I am not sure, but from JSP all model attribute variables are accessible simply using ${attribute_name}. In your case it is ${list}

A: Maybe you can use
console.info(model)

A: I am not sure that you can access response with JSP. JSP is the server side and response you receive when the page is already sent to client. The only thing you can try is to use COOKIES. Set response in cookies and then access it from the server.

A: Yes You can easily get Model data from controller, simply
 @RequestMapping(value='/ajax' value="POST")
 Public String displayDropdown(MyForm myform,Model model) {
 //logic to fetch details from DB
 List<String> list = fetchFromDB();
 model.addAttribute("list" list);
 return "yourjsppage";
 }

 $.ajax {
 url:'/ajax',
 type:'POST',
 data: $("#myform").serialize();
 success:function(data) {
 $("#page-wrapper").html( data );
 }
 }

page-wrapper is your content div in jsp page. this returns all jsp page including your model. in this scenario it is also useful when you want (partial rendering) not wanting to refresh whole page but targeting specific page.


text:
Q: How to delete the current record in subform I have forms as below.
Parent Form : CustomerForm
Child Form : OrderForm - in DataSheet view
Each customer can have more orders.
if i select a order and click 'Delete' button, it has to delete. I am not able to get current record and its fields.
No = Me.Form.CurrentRecord

Someone pls help.
Thanks.

A: No need to store the current record. Use the unique identifier of the selected record in the Subform to select it, then use Docmd.RunSQL. Supposing the button is on your Mainform "Main" and the record in your subform "Sub" with the identifier "id":

    Dim sSQL as String
    sSQL = "DELETE FROM myTable WHERE id = " & Me!Sub!id
    DoCmd.RunSQL sSQL
    Me!Sub.Requery


text:
Q: exception while trying to deploy liferay portlet with spring I'm trying to create a portlet with liferay 6.2 and using spring. If I create a bean without using constructor-arg or factory-method then everything works fine. But if I use either of these then I get exceptions when the portlet is deployed.
an example:

the exception I'm getting is:
01:28:21,884 ERROR [ContextLoader:323] Context initialization failed
java.lang.IncompatibleClassChangeError: class org.springframework.core.LocalVariableTableParameterNameDiscoverer$ParameterNameDiscoveringVisitor has interface org.springframework.asm.ClassVisitor as super class
I realize that this can be caused by having 2 versions of ams, but im using the spring jars that come with liferay.

A: You give an option yourself - duplicate classes. But without knowing how you build and what you're doing, there's hardly anything to do apart from asking you to make extra extra extra sure that you don't have duplicate resources on the classpath:
Check your deployed web application (once it's deployed to your application server) and its WEB-INF/lib folder for such duplicates. They might come in only during the buildprocess, e.g. they might not be in your IDE's workspace. Or Liferay might inject them (due to declared dependencies) during deployment.
You'll have to figure out how (and in which phase) those resources get there, then eliminate that option (e.g. through proper maven scope, e.g. "provided")


text:
Q: Session variable equivalent in OWIN self-host I have a sample web API hosted in an OWIN process (self hosted, not in IIS). I get a JWT token in my controller and I want to be able to retreive it in another part of the application, a class that implements NserviceBus IMutateOutgoingTransportMessages. In my other web application POC (hosted in IIS), I used a simple session variable and it works just fine. But I'd like to know what would be the best way to do it in my new OWIN self hosted environment ? Static property in static class ?

A: This question is really broad and difficult to answer without detailed knowledge of your specific needs. Here's my interpretation of your issue:

*

*You're already signing each request, perhaps storing the token in the browser sessionStorage (or even localStorage), but this does not suffice

*You need to retrieve the token outside of or not in relation to any request cycle (if not, this is probably where you should be looking for answers)

*Your application does not need to be stateless

Just one static property for one token in a static class would of course start breaking as soon as more than one request hits the application at the same time. Implementing a class that maintains a list of tokens may be a solution, although I can't tell what key you should use to identify each token. Interface details would vary depending on things like if you need to retrieve the token more than once.
Thread safety issues would apply to all handling and implementation of such a class. Using Immutable Collections and functional programming practices as an inspiration may help.
If lingering tokens poses a problem (and they probably would from a security perspective, if nothing else), you need to figure out how to make sure that tokens do not outstay their welcome, even if the cycle is for some reason not completed.
Seeing how you used Session as a solution in your POC, I'm assuming you want some similar behavior, and that one user should not be allowed to carry two tokens at the same time. You could store the tokens i a database, or even in the local file system, making maintenance and validity a separate issue all together.
There are implementations of cache-like functionality already available for OWIN self-hosted applications, and maybe one of those would serve as a shortcut to implementing everything yourself.
If this token business in fact is the only reason for introducing state in your application, then the best solution IMHO would be to rethink your architecture so that the application can remain stateless.

A: I'm facing a similar dilemma on a server i'm currently developing for a customer. My problem is that the server must make calls (and retain a live connection) with a legacy, multithreaded DLL, (aka the SDK).
I struggled to get this working on IIS with a regular Web API project. Failed badly since IIS recycles threads when it determines that a thread is going rogue... witch is what the SDK thread looks like in that perspective. Also, the SDK must be able to callback on the caller (client - single page app) and for this I'm using SignalR.
I then tried a multi-part system (single page + web api on IIS + WCF service for the SDK integration). But it is a real nightmare to manage because of the 2 way async communication that must occur between all apps. Again: failure.
So I reverted to a single self hosted OWIN + WebAPI service in a console app (for now). My problem is that some of the calls are lengthy and are processed in a worker thread. I managed to pass the SignalR client id in each ajax calls via headers. I can extract the id when in web api controller. But when the task goes async, I need to get the id (via an Unity injected service) from the class that manages the async task. This is where my problem is similar to yours. In IIS hosted apps, we have HttpContext. It is contextualized on each client calls, and follows any thread changes in the pipeline... But not in self hosted OWIN WCF apps...
I'm looking into Thread Local Storage, CallContext... and other means of keeping track of the original caller info during the lifecycle of the async call. I have read about OWIN pipeline, I can capture the info in a OWIN middleware... but how to safely keep that info for use in injected services? I'm still searching for an answer...
I was wondering if you have found a solution to this rather interesting problem ?
I prefer adding to your thread rather than start another parallel thread / SO question.


text:
Q: scroll google map webpage sidebar using selenium and python I am trying to collect data on a google map webpage, this is the link. link
This is the code I have tried. My idea is to scroll to the "website name" (you can find the website name once you scroll down) once is present in the browser. but it is not scrolling.
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.maximize_window()

driver.get("https://www.google.com/maps/place/Amsterdamsche+Athleten+Club+Hercules/@52.36937,4.8049968,16.25z/data=!4m5!3m4!1s0x47c5e3c9cbb3d913:0xef85f93ef996cc06!8m2!3d52.3692292!4d4.8056684")

img_result = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,'//*[@id="QA0Szd"]/div/div/div[1]/div[2]/div/div[1]/div/div/div[7]/div[5]/a/div[1]/div[2]/div[1]')))
driver.execute_script("arguments[0].scrollIntoView(true);",img_result)

print(img_result.text)

driver.close()

what is the solution for this?
EDIT:This is what I'm trying to get.

A: At least on my side I see no need to scroll.
The following code worked:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)

url = "https://www.google.com/maps/place/Amsterdamsche+Athleten+Club+Hercules/@52.36937,4.8049968,16z/data=!4m5!3m4!1s0x47c5e3c9cbb3d913:0xef85f93ef996cc06!8m2!3d52.3692292!4d4.8056684"

driver.get(url)
name = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[data-item-id='authority']"))).text
print(name)

Output:
aachercules.nl

The same could be done with XPath instead of CSS Selectors.
This is the XPath I used:
name = wait.until(EC.visibility_of_element_located((By.XPATH, "//a[@data-item-id='authority']"))).text


text:
Q: How to isolate the same script for every element in the page - jquery I have multiple blocks on the same page that contains "cards", some of this are not visible, when I click on the showmore they will show.
How can I isolate the same script for each element?
This is my code:-
HTML

...

...

...

...

show more

...

...

...

...

...

...

...

show more

...

...

...

JQUERY
$('.showmore_cards').click(function() {
    var thisItem = $(this);
    $(this).parents('.card_container').find('.single_card').each(function(index) {
        if ($(this).hasClass('card_visible')) {
            $(this).show();
        }
        thisItem.hide();
    });
});

Now when I click on showmore button this shows all the cards in the page


text:
Q: Definite integral $\int_0^\infty e^{-y}e^{-xy}y^2dy$ I successfully solved the following integral of $\int _0^\infty e^{-y}e^{-xy}y^2dy$ by using partial integration two times, which was pretty hell long, and since solving this integral was not the main issue in the exercise I was doing, I wondered if there's an easier way to integrate it. Is there?
Thanks!
(btw my result was $\frac{2}{(x+1)^3}$)
P.S I am not familiar with gamma functions or anything beyond "common B.SC calculus".

A: \begin{align}
\int_0^\infty e^{-(1+x)y}y^2dy &= \frac{d^2}{dx^2}\int_0^\infty e^{-(1+x)y}dy
\\
&= \frac{d^2}{dx^2}\frac{1}{(1+x)}e^{-(1+x)y}\bigg|_0^\infty
\\
&= \frac{d^2}{dx^2}\frac{1}{(1+x)}
\\
&= \frac{2}{(1+x)^3}
\end{align}

A: To prove by induction that $\int_0^\infty y^n e^{-zy}dy=\frac{n!}{y^{n+1}}$ (for $\Re z>0$), note that $$\int_0^\infty e^{-zy}dy=\frac{1}{z},\,\int_0^\infty y^{n+1} e^{-zy}dy=-\partial_z\int_0^\infty y^{n+1} e^{-zy}dy.$$For your stated problem, you only need to differentiate the base case twice; the induction is in case you want to generalise it.

A: Since your questions are related to random variables, this answer uses an exponential RV to compute the integral. Note that for an exponential RV, $Y$, with pdf
$$f(y) = \lambda e^{-\lambda y}, \quad \lambda,y>0,$$
we have
$$E[Y] = \frac{1}{\lambda},$$
$$var(Y) = \frac{1}{\lambda^2} \implies E[Y^2] = \frac{2}{\lambda^2}.$$
That is,
$$\lambda\int_0^{\infty} y^2 e^{-\lambda y} dy = \frac{2}{\lambda^2} \implies \int_0^{\infty} y^2 e^{-\lambda y} dy = \frac{2}{\lambda^3}.$$
Can you guess $\lambda$ in your problem?

A: Try separating the integral like this
$$\int _0^\infty e^{-y(x+1)}y^2dy=\int _0^1 e^{-y(x+1)}y^2dy+\int _1^\infty e^{-y(x+1)}y^2dy$$
you can see that the first integral is a proper one hence the integral converges.
For the second one try taking the cases when $x+1 \lt0 $, $x+1 =0$  and $x+1 \gt0$
for $x+1 \gt0$  from $$\lim_{y\to \infty}\frac{e^{-y(x+1)}y^2}{\frac{1}{y2}}=0$$  this implies that $$\int _1^\infty e^{-y(x+1)}y^2dy\le\int _1^\infty \frac{1}{y^2}dy$$
the last integral converges, from the comparison test so will the integral  $\int _1^\infty e^{-y(x+1)}y^2dy$
Can you try the other cases?

A: $I(x) = \int_0^{\infty} e^{-y}e^{-xy}y^2 dy$
Integration under the integral
$I(x) = \frac {d}{dx} \int_0^{\infty} e^{-y}y^2(\int e^{-xy}\ dx) dy = \frac {d}{dx}\int_0^{\infty} e^{-y(1+x)}y\ dy$
And one more time.
$I(x) = \frac {d^2}{dx^2}\int_0^{\infty} e^{-y(1+x)} dy = \frac {d^2}{dx^2}\frac {1}{1+x} = \frac {1}{2(1+x)^3}$


text:
Q: CloudFront Whole Site Delivery and urls contained within html This is a simple question that possibly applies to all CDNs but I have not been able to find an answer to on the web or on the AWS site (http://aws.amazon.com/cloudfront/). Hopefully it is a simple answer for anyone familiar with CDNs or CloudFront and this might help others with understanding how this works.
If I were to use CloudFront for whole site delivery and set up an origin server (e.g. origin is www.myexample.com) then if I have an html file (example1.html) being served at www.myexample.com/example1.html and example1.html were to contain element that include an img tag with a src http://www.anothersite.com/anotherExample.jpg or even a S3 bucket source, then does this jpg from another source get cached in the cdn too?

A: You should connect the S3 bucket to a CloudFront distribution and use that links in the html code itself. I may be wrong, but I don't see how a CDN might be able to cache those links, as the client browser themselves request these resources based on the downloaded html code from the CDN.
Hence, in your example, only requests for myexample.com would go through your CloudFront distribution without any additional origin settings.
Edit: see @Skill M2 comment regarding adding multiple origin's for the same CloudFront distribution


text:
Q: GD2 Fonts locking on Windows/Apache I have a PHP script that uses GD2 to create an image. It uses a TrueTypeFont file to generate text in the image with imagettftext (and imagettfbbox).
This script can be run on both Windows and Linux machines so I decided to copy a TTF file from the Windows/Fonts directory into the source-code, else I wouldn't know where to look for it.
I'm not at all happy with this solution but I don't know of a better one.
The real problem though is that on Windows/Apache the font file gets locked after it's been used once. The only way to unlock it is to restart Apache. The locking is a problem because I can't delete the file when I want to, which is especially annoying if you're using a version system.
So my problem has 3 solutions:

*

*Is there a way to avoid locking of font files (in source code/webroot) on Windows/Apache?

*Or is there a way to avoid copying the font file and use a native available TrueTypeFont? (OS independent if at all possible, likely hosts are Windows and Linux - Mac, not so much)

*Or is there a way to avoid using a TrueTypeFont and still get pretty (aliased) text with PHP GD2?

--
GD Support  enabled
GD Version  bundled (2.0.34 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.1.9
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support     enabled
PNG Support     enabled
WBMP Support    enabled
XBM Support     enabled

A: Why not using the library-defined font path?
From the imagettftext() docs, you can use the library font path:

Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

See the gd_info() page to find out which ttf library your windows php version is using. Then check the according library documentation what the font-path is.
Using TTFs from the fontpath might have the problem.

A: I also faced such an issue with GD but on a Debian distro. I found two solutions that might lead to wamp solutions as well :
a- install the bundle graphic library from dotdeb.org libgd i/o native php GD library and recompile the sources the with-freetype option,
or
b- install imagick instead of GD
I applied solution "a" successfully on a debian distro.
Here are some links I used at that time :
imagick on wamp
howtoforge
drupal
libgd
boutell

A: My solution is a combination of suggestions. I checked StackOverflow policy on splitting bounties and it's not possible. The bounty must be awarded to a single comprehensive answer. I would like to split my bounty to all the people who replied / commented here, if there is an alternative way please contact me.
I didn't have much luck with the .gdf fonts, I can't really find any good looking fonts. It did point me in the direction of imagestring which can draw text without the need of any font file (gdf or ttf) - see the php doc. The 'default' font is just some monospace font which isn't very pretty but it serves nicely as a fallback.
To avoid the .ttf locking I will attempt to find the OS font folder and load the font from there. This has been tested on my Windows development machine. If the .ttf file can't be found it will use the native font fallback from imagestring.
I've chosen an Object-Oriented approach to make an abstraction on how the text is written to the image.
abstract class TextWriter {

    public static function getInstance() {
        $osName = php_uname( 's' );

        if (strtoupper(substr($osName, 0, 3)) === 'WIN') {
            $path = 'C:/Windows/Fonts/';
        } else if (strtoupper(substr($osName, 0, 5)) === 'LINUX') {
            $path = '/usr/share/fonts/truetype/';
        } else if (strtoupper(substr($osName, 0, 7)) === 'FREEBSD') {
            $path = '/usr/local/lib/X11/fonts/TrueType';
        }
        if (is_dir($path) && is_file($path . "/arial.ttf")) {
            return new TTFTextWriter($path . "/arial.ttf");
        }
        return new NativeTextWriter();
    }

    abstract public function get_dimenions($string);
    abstract public function write_text($img_resource, $x, $y, $text, $color);

}

class TTFTextWriter extends TextWriter {

    private $ttf_file;
    private $fontsize = 10;

    public function __construct($ttf_file) {
        $this->ttf_file = $ttf_file;
    }

    public function get_dimenions($text) {
        $dimenions = imagettfbbox($this->fontsize, 0, $this->ttf_file, $text);
        return array($dimenions[2], abs($dimenions[5] - $dimenions[3]));
    }

    public function write_text($img_resource, $x, $y, $text, $color) {
        imagettftext($img_resource, $this->fontsize, 0, $x, $y, $color, $this->ttf_file, $text);
    }

}

class NativeTextWriter extends TextWriter {

    private $fontsize = 3;  // number between 1-5 see manual for imagestring
    private $text_width = 7;  // corresponds to $fontsize 3
    private $text_height = 15;  // corresponds to $fontsize 3

    public function get_dimenions($text) {
        return array(strlen($text) * $this->text_width, $this->text_height);
    }

    public function write_text($img_resource, $x, $y, $text, $color) {
        imagestring($img_resource, $this->fontsize, $x, $y - $this->text_height, $text, $color);
    }
}

Use like:
$writer = TextWriter::getInstance();

$dimenions = $writer->get_dimenions($text);
$width = $dimenions[0];
$height = $dimenions[1];
$im = imagecreatetruecolor($width, $height);
$black = imagecolorallocate($im, 1, 1, 1);

$writer->write_text($im, 0, 0, $text, $black);
header('Content-Type: image/gif');

imagegif($im);
imagedestroy($im);

A: I do know a workaround that is a bit laborious. A similar solution as I suggested: imagettftext-and-the-euro-sign.
In my case this could work as I'm really just looking for a way to generate some very simple images with text. It averts my problem but of course doesn't fix the underlying issue.

A: Using GD fonts (.gdf) will solve the issue with the files getting locked. You can move/rename/delete them as you wish even after using them.
They aren't quite as pretty as .ttf fonts, but with a bit of tinkering with gaussian blur you can get them to look almost identical to their ttf counterparts in terms of anti aliasing. Sample text with arial:

$im = imagecreatetruecolor(400, 200);

$bg = imagecolorallocate($im, 255, 255, 255);

imagefill ( $im , 0 , 0 ,$bg );
$textcolor = imagecolorallocate($im, 0, 0, 0);
imageantialias ( $im ,true );

$font = imageloadfont('arial-reg-20.gdf');

imagestring($im, $font, 10, 10, 'Hello world!', $textcolor);

imagefilter($im, IMG_FILTER_GAUSSIAN_BLUR,10);
imagestring($im, $font, 10, 10, 'Hello world!', $textcolor);
imagefilter($im, IMG_FILTER_GAUSSIAN_BLUR,1);
// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);

A: Firstly, my apologies if this does not work. For i could only test them on WAMP. Where this bug (according to online research) does not affect.
1) Make sure to imagedestroy($im);
2) To get the font folders for either platforms
<?php
function fontFolder() {
    $osName = php_uname( 's' );

    if (strtoupper(substr($osName, 0, 3)) === 'WIN') {
        return '/Windows/Fonts/';
    }

    if (strtoupper(substr($osName, 0, 5)) === 'LINUX') {
        return '/usr/share/fonts/truetype/';
    }

    if (strtoupper(substr($osName, 0, 7)) === 'FREEBSD') {
        //This is not tested
        return '/usr/share/fonts/truetype/';
    }
}

echo fontFolder();
?>

*Note this list of OS is not fully extensive, you may need to add / modify it for your needs.
3) [NOT RECOMMENDED] Persudo-"Cache" the font files : And leave the cache to clear on its own after the first run on server reset. That way, while the fonts gets 'locked' it is only the cache copy that gets locked. Not the actual working files you are 'playing' with. Hence it does not affect your work cycle. The files does get deleted eventually, when the system is rebooted, and they are 'cleared to delete'.
EDIT: Note that you can always point the folder to a tmp folder in a linux setup, should work somewhat the same.
<?php
/**
Recursive delete, with a 'file/folder igonore option'
[$ignoreArra] : An array or a single string, to ignore delete (folder or file)
[$ignoreRootFolder] : Ignores the starting root folder
**/
function recursiveDelete($str, $ignoreArray = null, $ignoreRootFolder = false){
    if($str == '' || $str == '/')   {   //Prevent accidental 'worse case scenerios'
        return false;
    }

    //Ensures it working as an array
    if($ignoreArray == null) {
        $ignoreArray = array(); //new Array
    }
    if(!is_array( $ignoreArray ) ) {
        $ignoreArray = array( $ignoreArray );
    }

    if(is_file($str)){
        if(in_array( $str, $ignoreArray ) ) {
            return false;
        } //else
        return @unlink($str);
    }
    elseif(is_dir($str)){
        $scan = glob(rtrim($str,'/').'/*');
        $chk = true;
        foreach($scan as $index=>$path) {
            $buf = recursiveDelete($path, $ignoreArray);
            if( $buf == false ) {
                $chk = false;
            }
        }

        if( in_array( $str, $ignoreArray ) || $chk == false || $ignoreRootFolder ) {
            return false;
        } else {
            return @rmdir($str);
        }
    }   else    {
        return false;
    }
}

define('fontCacheFolder', './font_cache/');
function fontCache($fontFolder, $fontFile) {
    $cachedFile = fontCacheFolder.$fontFile;
    recursiveDelete( fontCacheFolder , $cachedFile , true);
    if( is_file( $cachedFile ) ) {
        return $cachedFile;
    }
    copy( $fontFolder.$fontFile, $cachedFile);
    return $cachedFile;
}

echo fontCache('./', 'arial.ttf');
?>

4) UPDATED: Just leave all your fonts in one folder, and only do deletes of what is not needed before the actual / final deployment of your server. =) Just leave the font folder alone.
Example shared server structure.
www/root
   +----- fonts
   +----- app A
   +----- site B

Hence for any website / application nested in the root www folder, to access the shared font folder just use
'../fonts/fontName.ttf'

Hence, whenever you make changes and updates to the app / site, you save the trouble of conflicts in fonts.


text:
Q: pac pcf push does not update component in dynamics I've been successfully building and updating PCF components for the last two months and all the sudden the command to push the component to dynamics does not seem to update any of the changes I make (not in the current project or in previous ones).
Does anyone know if there is something going on at MS why the pac pcf push command does not update components anymore?
I have the latest pac version and the npm build command runs successfully.
Thanks for your help!

A: I've recently had the same problem with "pac pcf push" not updating the changes anymore so I ended up reverting to pac CLI version 1.16.6 and that fixed the problem for me.


text:
Q: CLLocationManager does not call back method in delegate CLLocationManager does not call back method:
locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status;

after user's permission.
I'm allocating CLLocationManager instance in singleton class (sort of manager), assigning delegate to self, all is looking fine, but is not working.
Also I have many multithreading logic in my app, and I think, the problem is a deadlock or some other problem related to multithreading.
How can I reveal what is the problem.
P.S. I have also tried to call
startMonitoringSignificantLocationChanges;

on main thread and this does not help.

A: Ok, after hours of trying things, I have found this:
post.
The solution is to allocate CLLocationManager on main thread.

A: Do you have a strong reference to the CLLocationManager? It should be a strong property @property CLLocationManager *myManager; or an ivar (instance variable) inside your class' implementation. If you are instantiating the CLLocationManager inside a function/method, and not assinging any reference, it will be released as soon as you finish that function.
Have a strong reference to the instance.

A: alloc/init CLocationManager as soon as viewDidLoad gets called worked for me.
- (void)viewDidLoad {
    [super viewDidLoad];

    locationManager = [[CLLocationManager alloc] init];
}


text:
Q: Why does XeTeX change gray scale JPG to CMYK? I always thought that none of the engines is capable of converting colors of external image files. However today I noticed that a gray scale image gets – somehow – converted to CMYK when using xelatex instead of pdflatex.
This is my test code:
% !TeX program = xelatex
\documentclass{scrreprt}

\usepackage{graphicx}

\usepackage{metalogo}

\begin{document}
With \XeTeX
%With \LaTeX

\vspace{10mm}
\includegraphics{image}
\end{document}

You can download the image file, my code and the resulting PDFs here: grayscale-test.zip
Here's the result shown with Acrobats color separation preview. As you can see the PDF generated by xelatex has a CMYK image while the one made with pdflatex sticks to gray (K) only (same source file for the image!).

(the cross indicates the measuring point)

Update
In the meantime a colleague told me that both PDFs (from pdflatex and xetex) are missing the OutputIntent. So in fact the embedded images are in Grayscale but Acrobat doesn't know how to interpret them (I don't know what makes the difference in between the two engines). So the image seems to be CMYK and is interpreted as such but actually is in Grayscale.
This is the preflight result; showing that the image itself is still in gray scale.

A:
Why does XeTeX change gray scale JPG to CMYK?

Short answer: Neither XeLaTeX nor pdfTeX did convert the image. Proof: Export the image in Acrobat Pro and you get a grey gamma 1.8 .jpg with both engines.
The XeLaTeX behaviour is the standard way when a grey scale image is printed on a CMYK printer. This leads to darker black but registration errors may be visible.
Long answer:
Other people already have mentioned you should use an OutputIntent. They are correct but it does not answer the question.
If you intend to print your document on a printer with black ink only, you will obviously print all shades with black only. Plain black ink will be the darkest you can get.
However, if you print your document on a CMYK printer (standard case today) you have multiple options how to print black. One option would be to print black as 100% cyan, magenta and yellow as you would expect for subtractive colour theory. But in real world this would lead to a brownish black. And because there is too much paint on top of each other paint wouldn't dry fast enough (liquid paint) or not stick well enough on paper (digital/laser printing).
In practice black and dark greys are printed as pitch black (german Tiefschwarz). This means you use all four paints, with values between 60% and 70% for cyan, magenta and yellow, and ~90% black. The detailed values depend on the paper. More expensive paper can hold more ink and thus display darker black.
(sidenote: This is why OutputIntent is not only an ICC profile but also a paper type, together a reference printing condition.)
Each conversion method has it's advantages and disadvantages. The XeTeX method (called under colour reduction) results in darker blacks but registration errors may occur because the different paint never 100% lay over each other. Also grey shades can look less neutral. It's the preferred method for images. The Gray Component Replacement (GCR) applied by pdfTeX does not show registration errors at the price of a not so dark black. It's the preferred method for graphics with thin lines.
So is your «G» an image or a graphic? One could use both methods here but because it's a graphic letter alongside normal text (which is always printed black only) I would prefer the pdfTeX method. Both letters then look the same black.
So what was the problem? In my eyes it's better to define grey scale images as CMYK and select the colour method that fits the content best. Because the conversion from CMYK to grey scale is a function you still get the correct values on a b/w printer. But the opposite way round you get multiple solutions.
Assume you want to follow my suggestion to use black only and the image is already there: How to convert it correctly? In Photoshop, go to Colour Settings (Shift+Ctrl+K), click Custom CMYK, and along the values you get from your printshop selegt GCR and Maximum black generation.

Then, convert your grey scale image to your custom CMYK profile.
PS: You show in the question a screenshot from Acrobat' print preview. But the most important setting is cropped: The simulation profile. Otherwise you would have seen that with UCR/XeTeX the exact values vary depending on the printing condition you select.

A: I had grayscale file with embedded color profile "Dot Gain 20%". Removing this color profile in Photoshop solved the problem (partly).
Other options you have:

*

*remove color profile by convert original.jpg +profile "*" clean.jpg

*make your final pdf grayscale:
gs -o path/to/output.pdf  \
   -sDEVICE=pdfwrite \
   -dPDFSETTINGS=/prepress \
   -sColorConversionStrategy=Gray \
   -sColorConversionStrategyForImages=Gray \
   -sProcessColorModel=DeviceGray \
   -dCompatibilityLevel=1.4 \
   /path/to/input.pdf

Update:
I do not know why, but grayscale photo after removing "Dot Gain 20%" profile becomes darker in PDF. So one more option is:

*

*convert your image to pdf via Photoshop "Save as...",  keeping the "Dot Gain 20%" profile, and use \includegrahics{my-grayscale-image.pdf} in your TeX file. This will increase your file size a little, but it will give a better result.

Update 2:
If you take a look at the code of your PDF files, you will see line /ColorSpace /DeviceGray in the ones generated by pdfLaTeX and luaTeX, and /ColorSpace 8 0 R in the one generated by XeLaTeX.
So, basing on this answer and especially this code, shown in the comment, you can use:
\usepackage{eso-pic}

\AddToShipoutPicture{%
\makeatletter%
     \special{pdf: put @thispage <</Group << /S /Transparency /I true /CS /DeviceGray>> >>}%
\makeatother%
}

This will make the monochrome PDF for you with the colors you wanted: 100% black and 58% gray.


text:
Q: DQL Query format when field starts with single quote I was trying to query a field that started with a single quote. If the single quote is in the middle of a field value or at the end of a field value, escaping the single quote by using '' works. But it doesn't work at the start of the field value. Is there some other format or a way to skip that?
Queries tried:
FirstName = 'Al''exandra' finds FirstName="Al'exandra"
FirstName = 'Alexandra''' finds FirstName = "Alexandra'"
FirstName = '''Alexandra' won't find FirstName = "'Alexandra", it throws a bad request.
Am I missing something?

A: This is indeed a bug.  We've created a ticket for it (DADEV-531) and John will be taking a look at it.  Thank you for bringing this to our attention!


text:
Q: Problems with spacing and creating new lines I have been modifying SourceBans to look more modern and I came into a little pickle
That is that I want the search field to be in the right below the links on the top like this:
Here's a live version of the current page: ☻
Additional Resources:

*

*CSS

*Searchbar Sourcecode

A: Add width: 100% to the button input and remove width: 300px; float: left; from the #search.
That should fix it.

A: *

*remove float: left; from both #nav and #search

*remove width from  #search

*make your input width:100%
(and a little padding-top)

A: Try to add this:
    /*
    This container do not need to float: left, just use this:
    */
    #search
    {
       /* margin-left: 590px; my mistake ;) */
        padding: 2px 0 0;
        text-align: left;
        width: 300px;
    }

/* remove default marging and padding of the form element */
#search form
{
   margin: 0;
   padding:0;
}

/* grow searchbox to full width, if wanted */
#search .searchbox
{
   width: 100%;
}


text:
Q: Searching Arrays with Strings from other Arrays C# I have this thing for checking if the client entered some help command in the arguments while triggering the console application I've built in C#. Below is my current code to complete this task:
string[] help = { "-h", "--help", "/?", "help", "-help", "*help*" };
if (args.Contains(help[*])
{
    Usage(); // prints out application usage
    Environment.Exit(1); // exits console application only
}

I originally used the following, which worked, but I wanted to clean the code up a little bit:
if (args.Contains("-h") || args.Contains("--help") || args.Contains("/?") ...)
{
    Usage();
    Environment.Exit(1);
}

How would I perform the task I'm trying to perform in the cleanest coded way possible?
Thanks in advance :)

A: How about args.Any(arg => help.Contains(arg))?


text:
Q: Is every sub-$\sigma$-algebra of $\mathcal{B}(\mathbb{R})$ "universally countably generated"? This is a seemingly basic question that I realise I don't know the answer to:
Let $\mathcal{B}$ be the Borel $\sigma$-algebra of $\mathbb{R}$.

Is it the case that for every sub-$\sigma$-algebra $\mathcal{G}$ of $\mathcal{B}$ there exists a countably generated sub-$\sigma$-algebra $\mathcal{G}'$ of $\mathcal{G}$ such that for every probability measure $\mathbb{P}$ on $\mathcal{B}$, $\mathcal{G} \subset \sigma(\mathcal{G}' \cup \mathcal{N}_{\mathbb{P}})$?

(Here, $\mathcal{N}_\mathbb{P}$ denotes the set of $\mathbb{P}$-null sets.)

Although less important for me, it would also be interesting if possible to know the following:

*

*If the answer to the above question is no (in ZFC): Is the answer to the above question being yes consistent with ZF+DC?

*But if the answer is yes: Does it still remain yes if we replace "every probability measure $\mathbb{P}$ on $\mathcal{B}\,$" with "every probability measure $\mathbb{P}$ on $\mathcal{G}'\,$"?

A: I've now managed to work out that the answer is no:
Proposition. Let $\rho$ be a probability measure on $(\mathbb{R},\mathcal{B})$, and let $\mathcal{G}$ be a sub-$\sigma$-algebra of $\mathcal{B}$ such that

*

*$\rho(A) \in \{0,1\}$ for all $A \in \mathcal{G}$;

*for $\rho$-almost every $x \in \mathbb{R}$ there exists $A \in \mathcal{G}$ such that $x \in A$ and $\rho(A)=0$.

Then for every countably generated sub-$\sigma$-algebra $\mathcal{G}'$ of $\mathcal{G}$ there exists a probability measure $\mathbb{P}$ on $(\mathbb{R},\mathcal{B})$ such that $\mathcal{G} \not\subset \sigma(\mathcal{G}' \cup \mathcal{N}_\mathbb{P})$.
So, for instance, we could take $\mathcal{G}$ to be the countable-cocountable algebra (with $\rho$ being any atomless probability measure).
Proof. We can represent $\mathcal{G}'$ as $\sigma(N_i : i \in \mathbb{N})$ for some sequence of $\rho$-null sets $N_i \in \mathcal{G}$. Let $N:=\bigcup_{i=1}^\infty N_i$. It is clear that
$$ \mathcal{D} \ := \ \bigcup_{B \subset N} \{B , \mathbb{R} \!\setminus\! B\} $$
is a $\sigma$-algebra, and therefore $\mathcal{G}' \subset \mathcal{D}$. Fix $x \in \mathbb{R} \setminus N$ and $A \in \mathcal{G}$ such that $x \in A$ and $\rho(A)=0$. Let $\mathbb{P}=\frac{1}{2}\delta_x + \frac{1}{2}\rho$. Then $\mathbb{P}(A)=\frac{1}{2}$. However, for any $B \in \mathcal{D}$, if $B \subset N$ then $\mathbb{P}(B)=0$ but if $\mathbb{R} \!\setminus\! B \subset N$ then $\mathbb{P}(B)=1$. So in particular, every member of $\mathcal{G}'$ has $\mathbb{P}$-trivial measure, and so $A \not\in \sigma(\mathcal{G}' \cup \mathcal{N}_\mathbb{P})$. QED
[As for the additional question: the above proof is valid in ZF+DC.]


text:
Q: Timescales of any task in linux kernel? I am studying how Linux kernel works and getting interested in the timescale of anything that happens in the kernel.
Of course I know it depends on the HW, but would like to get an example.
For instance,

*

*Interrupt Service routine : ~1ms?

*System calls : ~10ms?

*Printf(output 1 character) : 20ms?(not sure at all)

It would be appreciated if anyone could leave any comment or recommend a website which includes info like the above.

A: Probably you are looking for top.
TIME+ column show you time of cpu usage by processes.
top - 13:33:24 up 2 days, 21:28, 7 users,  load average: 0.27, 0.95, 0.92
Tasks: 733 total,  19 running, 691 sleeping,   0 stopped,  23 zombie
%Cpu(s): 18.4 us, 24.5 sy, 57.1 ni,  0.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem:  16287248 total, 15047664 used,  1239584 free,   144600 buffers
KiB Swap: 37457960 total,  6876096 used, 30581864 free,  5184516 cached

  PID USER      PR  NI S  %CPU %MEM    TIME+  COMMAND
    1 root      20   0 S   0.0  0.0   1037:17 init
    2 root      20   0 S   0.0  0.0   0:00.03 kthreadd
    3 root      20   0 S   0.0  0.0  45:34.38 ksoftirqd/0
    5 root       0 -20 S   0.0  0.0   0:00.00 kworker/0:0H
    7 root       0 -20 S   0.0  0.0   0:00.00 kworker/u:0H
    8 root      rt   0 S   0.0  0.0   0:17.35 migration/0
    9 root      20   0 S   0.0  0.0   6:52.03 rcu_preempt
   10 root      20   0 S   0.0  0.0   0:00.00 rcu_bh
   11 root      20   0 S   0.0  0.0   0:00.00 rcu_sched
   12 root      rt   0 S   0.0  0.0   0:00.46 watchdog/0
   13 root      rt   0 S   0.0  0.0   0:00.47 watchdog/1
   14 root      20   0 S   8.4  0.0  22:22.00 ksoftirqd/1
   15 root      rt   0 S   0.0  0.0   0:19.23 migration/1
   18 root      rt   0 S   0.0  0.0   0:00.48 watchdog/2
   19 root      20   0 S   0.0  0.0  21:09.37 ksoftirqd/2
   20 root      rt   0 S   0.0  0.0   0:19.26 migration/2
   22 root       0 -20 S   0.0  0.0   0:00.00 kworker/2:0H
   23 root      rt   0 S   0.0  0.0   0:00.50 watchdog/3
   24 root      20   0 R   0.0  0.0  23:53.19 ksoftirqd/3
   25 root      rt   0 S   0.0  0.0   0:20.26 migration/3
   27 root       0 -20 S   0.0  0.0   0:00.00 kworker/3:0H
   28 root       0 -20 S   0.0  0.0   0:00.00 cpuset


text:
Q: proof that axiom of union and axiom of pairing imply weak axiom of union The axiom of union says that to every set $\mathcal{A}$ there is a set $\{z: \exists A \;  z \in A  \wedge A \in \mathcal{A}\}$ or in other words: $\forall \mathcal{A} \exists B: \forall z [z \in B \leftrightarrow \exists A \in \mathcal{A} \; z \in A]$.
The weak axiom of union says that $\forall A \forall B \exists C: \forall x (x \in C \leftrightarrow x \in A \vee x \in B)$.
The axiom of pairing says: $\forall x \forall y \exists p: \forall z [z \in p \leftrightarrow z = x \vee z = y]$.
I am trying to give a (not fully formal) proof that if the axiom of union and axiom of pairing do hold, then also the weak axiom of pairing does hold.
Futhermore, I'm looking for a structure in which the axiom of union does hold, but the weak axiom of union doesn't. (So obviously this has to be a structure where the axiom of union does hold, but the axiom of pairing does not.)
I'm still trying to find an apt structure, but I think that finally I'll find one.
So I'd primarily appreciate your help on giving a (nearly formal) proof, since I'm just not managing to. Thank you in advance!

A: Assume the axiom of union and the axiom of pairing hold. Then by the axiom of pairing $$\forall A\forall B\exists p:\forall S[S\in p\iff S=A\vee S=B],$$ and by the axiom of union $$\forall p\exists C:\forall z[z\in C\iff\exists S\in p:z\in S].$$ Therefore $$\forall A\forall B\exists C:\forall z[z\in C\iff\exists S:(S=A\vee S=B)\wedge z\in S].$$ I will leave the details to you.
EDIT: Full proof: Let $A,B$ be sets. By the axiom of pairing there exists a set $p$ such that $$\forall S[S\in p\iff S=A\vee S=B].$$ It follows that $\forall z:$
\begin{align}
(\exists S\in p:z\in S)
&\iff(\exists S:(S=A\vee S=B)\wedge z\in S)
\\&\iff(\exists S:(S=A\wedge z\in S)\vee(S=B\wedge z\in S))
\\&\iff(z\in A\vee z\in B).
\end{align}
By the axiom of union there exists a set $C$ such that $$\forall z[z\in C\iff\exists S\in p:z\in S].$$ Hence, we find $$\forall z[z\in C\iff z\in A\vee z\in B].$$ Since $A,B$ were arbitrary, we conclude $$\forall A\forall B\exists C:\forall z[z\in C\iff z\in A\vee z\in B].$$ So if the axiom of pairing and the axiom of union hold, then the weak axiom of union holds.
Fixed counterexample: A model where the axiom of union holds but the weak axiom of union does not hold would be the model where $\emptyset$, $\{\emptyset\}$ and $\{\{\emptyset\}\}$ are the only sets. The weak axiom of union would imply that $\{\emptyset\}\cup\{\{\emptyset\}\}=\{\emptyset,\{\emptyset\}\}$ would exist, which it does not. I leave it up to you to check that the axiom of union does hold.

A: For any sets $A$ and $B$ there is a set $C = \{ A, B \}$.  By Union, there must be a set $D$ that contains all and only the elements of the elements of $C$, i.e. $D$ will contain all and only elements of either $A$ or $B$. That's the set $'C'$ you are looking for in the definition of Weak Union .. not the initial $C$
The outline for the proof is so mechanical that I decided just to put it in formal proof format ... I left just the inside few steps for you if you wanted to complete this as a formal proof:


text:
Q: Estou com problemas ao importar um arquivo em ruby Estou tentando importar um arquivo em ruby usando o require e o require_relative mas sempre recebo este erro Traceback (most recent call last): 1: from app.ruby:1:in ' app.ruby:1:in require_relative': cannot load such file -- C:/xampp/htdocs/some-ruby-projects/project-10/product.ruby (LoadError)
Alguém pode me dar uma luz?
meu código
require_relative 'product.ruby'
require_relative 'market.ruby'

product = Product.new
market = Market.new(product)

product.price = "3.990"
product.name = "Iphone 6s"
market.buy(product)

A: Tire a extensão .ruby e a troque por .rb e ao invés de colocar  require_relative 'product.ruby' e require_relative 'market.ruby' deixe apenas 'product' e 'market', pois além da extensão .ruby não existir não é necessário colocar qualquer extensão quando se utiliza o require_relative, pois ele vai  procurar outro arquivo através da string que foi colocada entre ''


text:
Q: Flutter FireBase Добавляется коллекция с категорией и листом items. Если добавить заново item то, создается новый документ(категория) и лист items. Можно ли сделать добавление item в категорию с фильтрацией? то есть если добавляешь item в лист, он добавлялся именно в ту категорию, которая была выбрана при добавлении.
class DB {
  final CollectionReference categoryData =
      Firestore.instance.collection('category');

  Future addCategoryWithItem(Categories categories) async {
    return await categoryData.document().setData(categories.toMap());
  }
}

class Categories {
  String categoryname, id;
  List<Item> item;
  Categories({this.categoryname, this.id, this.item});

  Map<String, dynamic> toMap() {
    return {
      'categoryName': categoryname,
      'id': id,
      'items': item == null ? [] : item.map((e) => e.toMap()).toList()
    };
  }
}

class Item {
  String data, data1, data2;
  Categories category;
  Item({
    this.category,
    this.data,
    this.data1,
    this.data2,
  });

  Map<String, dynamic> toMap() {
    return {
      'categoryName': category.categoryname,
      'data': data,
      'data1': data1,
      'data2': data2,
    };
  }
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  Items items = Items();
  Categories categories = Categories(item: []);
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(onPressed: () async {
        if (items != null) {
          setState(() {
            categories.item.add(items);
          });
          await DB().addCategoryWithItem(categories);
        }
      }),
    );
  }
}


text: Q: Firestore Database Transaction Monitoring I need some inputs regarding Firestore Monitoring. I have found three ways to monitor the firestore transactions. First one is to go to Usage Tab in Firestore console. Second one is through Quotas in App Engine Tab(GCP Console). Third one is through creating dashboards in Stack Driver monitoring. But i am able to get the same information from First and third option like read/write operations. What i want is transaction level monitoring like which user has created/updated/deleted the document. So for that level of monitoring what can i do in Firestore? I have created the dashboard but not able to get this user level transaction information. Please help.


text:
Q: Efficiently Animating pcolormesh Im trying to save a GIF with the evolucion of some waves in 2d using pcolormesh (using surface or wireframe would also be ok).
This has been my aproach so far:
set the quadmesh to plot in polar coordinates:
from matplotlib import pyplot
from matplotlib.animation import FuncAnimation as FuncAnimation
pi=np.pi

rmax=6.
r=2*np.linspace(0,np.sqrt(rmax*.5),100)**2
phi=np.linspace(0,2*pi,80)

R, P = np.meshgrid(r, phi)
X, Y = R*np.cos(P), R*np.sin(P)

set the figure and functions for the animation:
count is the amount of frames i have.
Z is a count*2D-array with the values i want to plot.
(it has the sum of some fourier like series)
fig, ax = pyplot.subplots()
def anim_I(count,r,phi):
    anim=np.zeros((count,len(phi), len(r)))
    for i in range(count):
        anim[i,:,:]=coef_transf(final_coefs[i,:,:,:,0],r,phi)**2
    return anim

Z=anim_I(count,r,phi)
def animate(i):
    pyplot.title('Time: %s'%time[i])
    #This is where new data is inserted into the plot.
    plot=ax.pcolormesh(X, Y,Z[i,:,:],cmap=pyplot.get_cmap('viridis'),vmin=0., vmax=15.)
    return plot,

ax.pcolormesh(X, Y,Z[0,:,:],cmap=pyplot.get_cmap('viridis'),vmin=0., vmax=15.)
pyplot.colorbar()

anim = FuncAnimation(fig, animate,  frames = range(0,count,7), blit = False)

i don't really need to see it live, so i just save a gif.
anim.save('%d_%d_%d-%d.%d.%d-2dgif.gif' %(localtime()[0:6]), writer='imagemagick')
pyplot.close()

While this works, it can take to an hour to make the gif of a even a hundred frames.
I wan't to know what would be the correct way to do this so it could be usable.
I have seen the other post in this regard, but i couldn't get the code working, or it would be just as inneficient.

A: You could try to write
def animate(i):
pyplot.title('Time: %s'%time[i])
#This is where new data is inserted into the plot.
plot=plot.set_array(Z[i,:,:].ravel())
return plot,

instead of
def animate(i):
pyplot.title('Time: %s'%time[i])
#This is where new data is inserted into the plot.
plot=ax.pcolormesh(X, Y,Z[i,:,:],cmap=pyplot.get_cmap('viridis'),vmin=0., vmax=15.)
return plot,

This does not create a new object every time you call the animate funtion. Instead it changes the image of object that was already created.
However, the set_array method seems to need a flattened array, hence the .ravel().
This only produces the right image if you set the shading option of the pcolormap function to shading='gouraud'.
I don't know why, unfortunatelly, it seems to have to do with the sorting of the array.
I hoped, that helped a little.

A: I suggest inserting a
pyplot.clf()

at the beginning of your animate(i) function. This will start each frame with a blank figure. Otherwise, I suspect the plot will not be cleared, and the long time is due to actually plotting all previous frame below the new one.


text:
Q: Convert IntelliJ IDEA project to Eclipse I am trying to export IntelliJ IDEA 14 project to Eclipse (a console hello world template with JUnit) using "Export to Eclipse" in menu, but when I import it in Eclipse (4.4.1) via Import—>Existing Projects Into Workspace it says
Unbound classpath variable: 'APPLICATION_HOME_DIR/lib/junit-4.11.jar

Without JUnit it works fine.

A: The import fails because your project references the JUnit jar from the IntelliJ IDEA distribution. You need to put the jar under your own project directory.


text:
Q: Return upper left value in a range if string is found - Google Sheets I have a Google sheet that has 'categories' listed in one cell. Then the data for that category is listed in multiple cells to the right of the category. For example see the image:
example spreadsheet
I need a formula that searches for a name in B1:C5 AND returns all values in A that correspond. For example, if my search term was "Elvis" it should return "Discus, Shotput".
Can anyone help?
I have tried Queries and a combination of Join + Filter

A: You may try:
=join(", ",filter(scan(,A:A,lambda(a,c,if(c="",a,c))),(B:B=E1)+(C:C=E1)))