text:
Q: PHP - Get IP when page calling by htaccess I have a website in PHP and need to know what the IP of the accessing client is. For this I am using the function below:
function get_client_ip() {
    $ipaddress = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    }

    return $ipaddress;
}

But when accessing the site by url omenorpreco.com/teste the page returns the server IP.
When access to page the url omenorpreco.com/teste.php, the page returns the client IP.
Possibly this error occurs because when you access the page without the extension ".php", the server interprets the page by .htaccess?
How can I adjust my application for both accesses, return the client's IP, and not the server IP?
above my htaccess code

    php_value allow_url_fopen on
    php_value allow_url_include 1
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule !.(js|ico|txt|gif|bmp|jpeg|jpg|png|css|log|rss|zip|xml|sql|pdf|doc|docx|xls)$ url_amigavel.php
    RewriteRule sitemap-categoria.xml$ sitemap.php?number=categoria
    RewriteRule sitemap-([0-9]+).xml$ sitemap.php?number=$1
    RewriteRule sitemap_index.xml$ sitemap_index.php

and url_amigavel.php code
<?php

$geturl = explode( "/", str_replace( strrchr( $_SERVER["REQUEST_URI"], "?" ), "", $_SERVER["REQUEST_URI"] ) );
array_shift( $geturl );

$tipo = $geturl[0];

if ( is_file( "$tipo.php" ) )
{
    include "$tipo.php";
}
else
{
    echo "page not found";

}

?>

EDIT: CAN I SET GLOBAL_VAR IN HTACCESS WITH THE CLIENT IP?

A: Put this in a file and run with and without the extension:
<?php
function get_ip_address() {
    return $_SERVER['REMOTE_ADDR'];
}
    echo get_ip_address();

?>

What error do you get if you run the above?
EDIT:
Can you edit your .htaccess like this and see if the error still occurs:
php_value allow_url_fopen on
php_value allow_url_include 1
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !.(js|ico|txt|gif|bmp|jpeg|jpg|png|css|log|rss|zip|xml|sql|pdf|doc|docx|xls)$ $1.php [L]
RewriteRule sitemap-categoria.xml$ sitemap.php?number=categoria
RewriteRule sitemap-([0-9]+).xml$ sitemap.php?number=$1
RewriteRule sitemap_index.xml$ sitemap_index.php

A: I think I just saw it work on your server!
Change .htaccess to;
php_value allow_url_fopen on
php_value allow_url_include 1

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !.(js|ico|txt|gif|bmp|jpeg|jpg|png|css|log|rss|zip|xml|sql|pdf|doc|docx|xls)$ url_amigavel.php
RewriteRule sitemap-categoria.xml$ sitemap.php?number=categoria
RewriteRule sitemap-([0-9]+).xml$ sitemap.php?number=$1
RewriteRule sitemap_index.xml$ sitemap_index.php

SetEnvIfNoCase Remote_Host "(.*)" HTTP_MY_REMOTE_HOST=$1
SetEnvIfNoCase Remote_Addr "(.*)" HTTP_MY_REMOTE_ADDR=$1

An change test.php to;
function get_client_ip() {
    if (isset($_SERVER[REDIRECT_HTTP_MY_REMOTE_ADDR])) {
        return $_SERVER[REDIRECT_HTTP_MY_REMOTE_ADDR];

    } else if (isset($_SERVER[REDIRECT_HTTP_MY_REMOTE_HOST])) {
        return $_SERVER[REDIRECT_HTTP_MY_REMOTE_HOST];

    } else if (isset($_SERVER[HTTP_MY_REMOTE_ADDR])) {
        return $_SERVER[HTTP_MY_REMOTE_ADDR];

    } else if (isset($_SERVER[HTTP_MY_REMOTE_HOST])) {
        return $_SERVER[HTTP_MY_REMOTE_HOST];

    }
}

echo get_client_ip();

Inspiration for setting variables in .htaccess from: http://www.askapache.com/htaccess/setenvif.html
Glad it finally worked!

A: You have allow_url_include set to 1 on your .htaccess. This is causing problems because as you are telling PHP to include a file, the preprocessor thinks it's a URL, other people have told you this so let's go straight.
My guess is, just disable allow_url_include. It's a bad practice, a security risk and there's nothing you can't do just with file_get_contents for example.
If you are still convinced that including remote files is a good idea, you should try using a full path, using this include with the code Benjy1996 gave you:
include(getcwd().$tipo.".php");
PD: you should probably change your ip function to return $_SERVER['REMOTE_ADDR'] only as well, as it's the one you can trust the most, because it's the most difficult to fake.


text:
Q: quadratic eq proof ;a,b,c odd, roots can't be rational no. Given odd integers $a,b,c$ prove that the equation $ax^2 + bx + c = 0$ cannot have a solution x which is a rational number
My approach:
if $a =1$ , $b=3$ , $c=1$;
then the eq. $x^2 + 3x + c = 0$ has roots
$x_1=-0.381...$,
$x_2=-2.62...$ ;
which is indeed true
but how can we prove this result??
please help

A: If $c$ is integer and the roots are rational then both roots have an odd numerator (since their product is $c/a$). Can you finish?

A: Suppose $a,b,c$ are odd integers, and suppose the equation
$$ax^2+bx+c=0$$
has a rational root, $r={\large{\frac{p}{q}}}$ say, where $p,q$ are integers, and $\text{gcd}(p,q)=1$ (i.e., the fraction is reduced to lowest terms).
\begin{align*}
\text{Then}\;\;&ar^2 + br + c = 0\\[4pt]
\implies\;&a\left({\small{\frac{p}{q}}}\right)^2+b\left({\small{\frac{p}{q}}}\right) + c = 0\\[4pt]\implies\;&ap^2 + bpq + cq^2 = 0\\[4pt]
\end{align*}
Consider $3$ cases . . .

Case $(1)\,$:$\;p,q$ are both even.

Then $\text{gcd}(p,q) > 1$, contradiction.

Case $(2)\,$:$\;p,q$ are both odd.

Then the LHS of the equation $ap^2 + bpq + cq^2 = 0$ is odd (since all three terms are odd), contradiction, since the RHS is even.

Case $(3)\,$:$\;$One of $p,q$ is even, and the other is odd.

Then the LHS of the equation $ap^2 + bpq + cq^2=0$ is odd (since  two of the terms are even, and the remaining term is odd), contradiction, since the RHS is even.

Thus, all $3$ cases yield a contradiction.

It follows that the equation $ax^2 + bx + c = 0$ does not have a rational root.

A: We need $$b^2-4ca$$ for the perfect square $=d^2$(say)
If $b$ is odd, so will be $d$
$$\implies4ca=b^2-d^2$$
Now if $x$ is odd, $$x^2\equiv1\pmod8\implies8|(b^2-d^2)$$ but $8\nmid4ca$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I print in tabular form in unix shell script and mail in tabular form in the outlook mail I have to print in tabular form machine names with below format in tabular form
Machine     Size Used Available Capacity Mountedon
m1 :  200G 11.9G 188G 6% /path
m2 : 200G 91.7G 108G 46% /path
m3 : 200G 49.6G 150G 25% path
m4 : 200G 60.3G 140G 31% path
m5 : 200G 25.5G 174G 13% path
m6 : 200G 101G 98.6G 51% path
m7 : 200G 50.4G 150G 26% path
m8 : 200G 54.7G 145G 28% path

#!/bin/bash
for i in m1 m2 m3 m4 m5 m6 m7 m8
FS=$(echo "$i : `ssh -q $i 'df -kh /path'`")

echo $FS >>/path/tempfile.txt
done

print "MIME-Version: 1.0" >> $tempfile.txt
print "Content -Type: =text/html" >> $tempfile.txt
print "" "
Machine	Size	Used>	Available>	Capacity	Mountedon	" >>$tempfile.txt
Print "
" >>$tempfile.txt

echo "From:xyz"
echo "To:xyz@gmail.com "
cat /path/tempfile.txt > FS.html |sendmail -t

enter image description here
but the code is not working and is giving errors .


text:
Q: Disabling single button I am having a problem of disabling single button
When I click to order for $10 it disables all buttons, and I only want the one which I have clicked to be disabled

$(document).ready(function() {
  $('.btn-checkout').click(function(e) {
    $('.btn-checkout').html('proccesing order');
    $('.btn-checkout').attr("disabled", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form method="POST">
  <button type='button' class='btn-checkout'> order for $10</button>
  <button type='button' class='btn-checkout'> order for $20</button>
  <button type='button' class='btn-checkout'> order for $30</button>
</form>

A: Use $(this) which is the actual clicked item accessed by the selector

$(function() {
  $('.btn-checkout').on('click',function(e) {
    $(this).html('proccesing order');
    $(this).attr("disabled", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form method="POST">
  <button type='button' class='btn-checkout'> order for $10</button>
  <button type='button' class='btn-checkout'> order for $20</button>
  <button type='button' class='btn-checkout'> order for $30</button>
</form>

I would also delegate so you could add more buttons later

$(function() {
  $('#container').on('click','.btn-checkout',function(e) {
    $(this).html('proccesing order');
    $(this).attr("disabled", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form method="POST">
<div id="container">
  <button type='button' class='btn-checkout'> order for $10</button>
  <button type='button' class='btn-checkout'> order for $20</button>
  <button type='button' class='btn-checkout'> order for $30</button>
</div>
</form>


text:
Q: PHP MySQL multiple conditions in query I have a database with some records and columns: "type", "id" and others. I would like to select all records with any "type" that's mentioned in array $typearray but without records which id's are in $idarray. I tried to do something like:
$result = mysql_query("SELECT * FROM db
    WHERE type IN('".implode("','",$typearray)."')
    AND id NOT IN('".implode("','",$idarray)."')
    ORDER BY date DESC LIMIT 10");

But it doesn't seem to work - the:
type IN('".implode("','",$typearray)."')

condition works fine but the second does not. At first I thought the issue was with column types - both arrays contains strings, "type" column is a VARCHAR(10) and id is INT, but changing it to string didn't help. What am I doing wrong?
EDIT:
If I print a query I get this:
SELECT * FROM db
WHERE type IN('apple','tomato','potato')
AND id NOT IN('20','1','10','15','8')
ORDER BY date DESC LIMIT 10

The first condition works fine: it selects only apples, tomatoes and potatoes. The second condition does nothing and even if I type manually:
id NOT IN('20','1','10','15','8')

or
id NOT IN('20,1,10,15,8')

or
id NOT IN(20,1,10,15,8)

it still fails.
EDIT2:
Actually forget it. I'm an idiot. I've mixed up my variables a bit...

A: You should try this query, or at least do a echo $result, "\n";, into mysql workbench to see what it give.
And I'd say the default behavior to have when a query does not work: first in Mysql Workbench (or any SQL runner like Toad, Squirrel ...)
$result = mysql_query("SELECT * FROM db
    WHERE type IN('".implode("','",$typearray)."')
    AND id NOT IN('".implode("','",$idarray)."')
    ORDER BY date DESC LIMIT 10");

If $typearray is empty, you are looking for type IN (''), which might never matches.
If $idarray is empty, you are looking for id not in ('') which might always matches.
And if $typearray or $idarray contains invalid character, you will get an error.
[edit] by the way, if $typearray or $idarray may contains invalid character, you might use array_map and mysqli_escape_string:
$result = mysql_query("SELECT * FROM db
    WHERE type IN('".implode("','", array_map('mysql_escape_string', $typearray))."')
    AND id NOT IN('".implode("','", array_map('mysql_escape_string', $idarray))."')
    ORDER BY date DESC LIMIT 10");

A: you don't need to escape integer variables:
...
AND id NOT IN(" . implode(",", $idarray).")
...


text:
Q: Not another Sencha Touch 2 vs JQMobile 1.2.0 Performance Comparison Thread I know this has been asked a million times but i can't seem to find a good comparison that is with the new Sencha Touch 2 and the currently released and optimized JQMobile 1.2.0 or 1.1.1 even.
My main concern is i have worked with both but only with the old non optimized version of JQMobile so my question is.
How big is the improvement of the new JQuery Mobile that was just released in comparison to Sencha Touch 2 when it comes to packaging it into a native mobile application?
THanks,
Alex

A: I haven't made a Sencha App yet (although the demos look snappy), but I have just completed a jQuery Mobile app that I upgraded to 1.1.1 shortly before completing. The performance improvement was minimal. In short, jQuery Mobile performance just isn't very good at all if you're making a complex app. For simple stuff, it's great, but if you are building anything of greater size and complexity you really ought to look elsewhere. If you do go JQM be sure to search around for tips on how to keep performance up, but do know that even if you follow them all you may end up disappointed. On a sidenote JQM still has all sorts of obnoxious bugs when it comes to things like fixed headers and other visual elements...it's really just not worth using (yet) in anything but the simplest of use cases.


text:
Q: No glance method for objects of class drc error I am trying to fit growth models on longitudinal data using the Gompertz function in the drc package. To generate models on several countries simultaneously, I nested the data and used the map function from tidyverse. The modeling step using purrr::map runs fine, but when I try to get the model summaries using the glance option in broom, I am getting an error that no glance method exists for objects of class drc. However, glance appears to be operative on drc objects, as per this webpage: https://rdrr.io/github/tidyverse/broom/man/glance.drc.html
Below is an example, including the toy dataset involving 2 countries and 6 timepoints for each.
#Dataset tested
iso_code    total_cases num_days
IND 1   1
IND 3   10
IND 3   20
IND 3   30
IND 165 50
IND 979 60
SGP 3   1
SGP 18  10
SGP 47  20
SGP 86  30
SGP 187 50
SGP 455 60

#installing packages tidyverse and drc
> library(tidyverse)
> library(drc)

> data = read.delim("test_data.txt", sep='\t', header=T)
> dim(data)

[1] 12  3

> str(data)

'data.frame':   12 obs. of  3 variables:
 $ iso_code   : chr  "IND" "IND" "IND" "IND" ...
 $ total_cases: int  1 3 3 3 165 979 3 18 47 86 ...
 $ num_days   : int  1 10 20 30 50 60 1 10 20 30 ...

#nesting data by country
> by_country = data %>% group_by(iso_code)%>% nest()

#running drc gompertz model on nested data
> by_country_g = by_country %>% mutate(model= purrr::map(data,~  drm((total_cases)/max(total_cases) ~ num_days, fct=G.4(), data=.)))

#checking model contents
> by_country_g$model

[[1]]

A 'drc' model.

Call:
drm(formula = (total_cases)/max(total_cases) ~ num_days, data = .,     fct = G.4())

Coefficients:
b:(Intercept)  c:(Intercept)  d:(Intercept)  e:(Intercept)
    -0.164861       0.002555       1.531310      54.838386

[[2]]

A 'drc' model.

Call:
drm(formula = (total_cases)/max(total_cases) ~ num_days, data = ., fct = G.4())

Coefficients:
b:(Intercept)  c:(Intercept)  d:(Intercept)  e:(Intercept)
      -0.1257         0.0845         1.4638        52.9056

#extract model summaries by glance
> summary_g = by_country_g %>% mutate(glance = purrr::map(model, broom::glance))%>% unnest(glance)

Error: Problem with mutate() input glance.
x No glance method for objects of class drc
ℹ Input glance is purrr::map(model, broom::glance).
ℹ The error occured in group 1: iso_code = "IND".
Run rlang::last_error() to see where the error occurred.

A: library(tidyverse)
library(drc)

data %>%
  nest(data = -iso_code) %>%
  mutate(model= map(data,~  drm((total_cases)/max(total_cases) ~ num_days,
                    fct=G.4(), data=.)),
         glance = map(model, broom::glance)) %>%
  unnest(glance)

#   iso_code data             model     AIC    BIC logLik    df.residual
#  <chr>    <list>           <list>  <dbl>  <dbl> <logLik>        <int>
#1 IND      <tibble [6 × 2]> <drc>  -59.8  -60.8  34.884966           2
#2 SGP      <tibble [6 × 2]> <drc>   -7.39  -8.43  8.694533           2


text:
Q: Using regex to exclude string I've searched high and low and can't seem to find a definitive answer to this.
Basically I'm trying to use regex to show all pages on my site that contain:
/enquiry/ but that are not immediately followed by enquiryconfirmation/
All I can seem to get is regex that excludes single characters.  Also I've noticed that whenever I try to use a ! in GA it throws up an error?
Thanks

A: The question is probably off-topic (not about programming), but on the other hand regexp is code so here we go.....
Negation via "!" is not supported in the interface - that's why you have to choose between "include" and "exclude" when you set up filters. Basically "exclude" means to negate the whole expression, "whole" being the operative word here.
Therefore I would suggest using two filters, first "include regex /enquiry/" and then "exclude regex /enquiry/enquiryconfirmation/". Since filters are applied in sequence this should do what you want - the first filter will throw out everything that does not have /enquiry/ in it, the second filter will exclude from the remaining data the pages that contain /enquiry/enquiryconfirmation/.


text:
Q: How to get call stack in c in windows?
Possible Duplicate:
How can one grab a stack trace in C?

In PHP it's debug_backtrace,is there such a function in c?

A: On Windows you can call the StackWalk64 function that is exported by DBGHELP.DLL. It is shipped with Debugging Tools for Windows (WinDbg) but according to this link, "The redistribution policies for these included DLLs were specifically designed to make it as easy as possible for people to include these files in their own packages and releases."


text:
Q: Arduino UNO - Ayuda con Servomotor DS04-NFC Me encuentro con el siguiente problema:
Estoy intentando hacer girar un servomotor DS04-NFC al pulsar un pulsador.
Al pulsar una vez quiero que gire durante cierto tiempo (5 seg, por ejemplo)
Al mantener apretado el pulsador que gire hasta que lo suelte.
Esto lo logre sin inconvenientes. El problema viene si mantengo apretado el pulsador durante un tiempo menor al que debe girar cuando pulso una vez. Es decir, si tengo programado que al "hacer un click" sobre el pulsador el servo debe girar durante 5 segundos, si yo mantengo apretado durante un tiempo menor a estos 5 segundos, el servo gira hasta completar el tiempo (debiendo frenar al soltar el pulsador).
Les dejo el código:

#include <Servo.h>

const int pinBoton = 4;
Servo servo;
int estadoActual = 0;
int estadoAnterior = 0;
unsigned long tiempoDeGiro = 5000;
unsigned long tiempoQueSePresionoElBoton;

void setup() {
  pinMode(pinBoton, INPUT);
  servo.attach(12);
  Serial.begin(9600);
}

void loop() {
  estadoActual = digitalRead(pinBoton);

  if (estadoActual) { //Si el pulsador esta pulsado
    tiempoQueSePresionoElBoton = millis();  //Me guardo el momento el tiempo en el que pulsador se pulso

    if (estadoActual == estadoAnterior) { //Si antes estaba pulsado y ahora se mantiene pulsado gira continuamente
      servo.write(180);
    } else {
      unsigned long tiempoAuxiliar = millis(); //Me guardo el momento de tiempo para llegar al tiempo de giro

      while (tiempoAuxiliar < (tiempoQueSePresionoElBoton + tiempoDeGiro)) { //Si el tiempo de giro sumado al tiempo en que se presiono el boton es menor al tiempo actual gira
        servo.write(180);
        tiempoAuxiliar = millis();
      }

      servo.write(90);

    }

    estadoAnterior = estadoActual; //actualizo el estado anterior

  } else {
    estadoAnterior = estadoActual;
    servo.write(90);
  }

}

Saludos y desde ya, muchas gracias

A: Aca tengo una posible solucion, no estoy 100% segudo de que funcione por que hace muchisimo no utilizo un arduino y tampoco tengo uno para testear el codigo.
Por lo tanto, deberas probarlo y lo vamos arreglando a medida que vas encontrando fallas.
#include <Servo.h>

const int pinBoton = 4;
Servo servo;
int estadoActual = 0;
int estadoAnterior = 0;
unsigned long tiempoDeGiro = 5000;
unsigned long tiempoQueSePresionoElBoton;
unsigned long presionoBoton = 0;
unsigned long soltoBoton = 0;

void setup() {
  pinMode(pinBoton, INPUT);
  servo.attach(12);
  Serial.begin(9600);
}

void loop() {
  estadoActual = digitalRead(pinBoton);

  if(estadoActual && !estadoAnterior){
      //guardo el primer tiempo
      presionoBoton = milis();
  }

    if(estadoActual){
        //Giro mientras esta pulsado
        servo.write(180);
    }
    else if(!estadoActual && estadoAnterior){
        // guardo el ultimo tiempo
        soltoBoton = milis();
        if(soltoBoton - presionoBoton < 100){
            //Detecto si unicamente fue una presionada o mantubo por X tiempo presionando el boton
            //Si entra aca, es por que solo presiono
            while(millis() <= (soltoBoton + tiempoDeGiro){
                //giro 5 segundos
                servo.write(180);
            }
        }
      servo.write(90); //vuelvo a la posicion inicial
    }
    estadoAnterior = estadoActual; //Actualizo el estado anterior
}

EDIT:
No sabria exactamente cuanto es el tiempo de en que se cumple una presionada de boton, yo puse 100 como un numero bajo, pero deberias ir probando por que capaz solo en presionar el boton se demora por ejemplo 400ms
Esto hablando para la siguiente linea
if(soltoBoton - presionoBoton < 100)


text:
Q: Is there a way to operate the camera of a disassembled iPhone X? I recently disassembled my iPhone X; to straightforwardly ask, is there a way to operate the rear camera of this model? There are all the necessary parts: the display, central processor, the front camera with the TrueDepth sensor, and the rear camera.
I want to operate the camera using an external input device; store the images and recordings taken in an external storage.
Would using Arduino or Raspberry Pi be an option?

A: Yes, you can. How is a very difficult question to answer.
Broadly, as with developing any embedded electronic project, you first have to correctly identify each part, and obtain its technical specification / manual from the manufacturer. This will tell you what each part does and how to assemble and connect them all together. The second part is even more difficult - if the manufacturer doesn't provide a ready made software (or atleast a device driver or template software that you can customize), you will have to write the software / program yourself to use the hardware correctly. (in iPhone, this part is handled by iOS and the camera app.)
So if you are familiar with electronics and embedded technology, and embedded programming, you should be able to do this.
Realistically, it is a very diffult task and will take a lot of time and new skillsets. It would be better to start with a smaller and easier electronic project before trying this.
Go for it if you are interested in patiently learning these skills. Even if you fail, you will still learn a lot. (Take inspiration from Alyssa, a young woman, student and hacker who is progressing on reverse engineering Apple's GPU in its new ARM processors, to create a linux driver for it).
The knowledgeable people at iFixit may be able to help you identify the parts, and even obtain the technical schematics on it. You can also ask for more help and advice from the Electrical Engineering Stack Exchange and Reddit Embedded forum.

A: This is one of the cases where "if you have to ask, you'll never know" is applicable.
There's no published solution for your problem available. In theory it could very well be possible, but in practice no - you cannot do this. Apple does not publish the types of details about their camera units, nor does Arduinos or Raspberry Pis have a compatible connector - not mentioning all the other stuff you'll need (like drivers for instance).


text:
Q: UITabbar loses context when Tabbar Item changes In my app I have two Tabbar items A and B. From A view controller I have presented another view controller C under current context of view controller A so that presented view controller doesn't cover the fullscreen and UITabbar is visible. Then, when I select second tabbar item and switch back to first and dismiss the presented view controller, Current Tabbar item turns to back.
I have shared the demo example. Please follow the steps to regenerate the bugs.

*

*Run the app

*Press "Present C" button

*Select Bookmarks Item

*Select back to Top Rated Item

*Press "Dismiss" button**

Observation: Black screen
Expectation: View Controller in that Tabbar Item should be visible.

A: Normally, a modal view controller in this context would be used to perform some action related to that tab, and should be dismissed while still in that tab [Designed behaviour, otherwise behaves weird. If you use view debugger you will see there is no view controller in the tab after you dismiss the presented view], So use modal presentation style overFullScreen, which will hide tab bar.
If you really need that view (the one you're modally presenting) to stay visible, you might want to use a navigation controller as the root for that tab, and do a push instead. Bellow link holds these answers for you..
Black screen after presenting modal view controller in current context from UITabBarController


text:
Q: how to read atomic counter value using shader storage buffer I want to access atomic counter value in my code. My shader is
#version 430
#extension GL_EXT_compute_shader : enable
layout (local_size_x = 16, local_size_y = 16) in;
layout (binding = 0) uniform atomic_uint atRed;
layout(std140,binding = 0) buffer myBuffer
{
uint red;
uint inc_red;
}g_out;

void main() {
    g_out.inc_red=0;
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);
    g_out.inc_red+=atomicCounterIncrement(atRed);

    g_out.red=atomicCounterIncrement(atRed);

 }

In my access i am accessing these values using following code
GLuint*  counter=NULL;
glGenBuffers(1, &shaderStorageBufferID);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, shaderStorageBufferID);
glBufferData(GL_SHADER_STORAGE_BUFFER, 2*sizeof(GLuint), NULL ,GL_STATIC_DRAW);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0,shaderStorageBufferID );
glUseProgram(tdk_ShaderObject.cpsId);
glDispatchCompute(16,16,1);
counter = (GLuint*) glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0,2*sizeof(GLuint),   GL_MAP_READ_BIT );
printf("counter %d %d",*counter,*(counter+1));

glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

It is giving counter values as 0 0.
Is there anything wrong in above code?
This issue is solved now.Solution is
GLuint* counters=(GLuint*)tdkMalloc(sizeof(GLuint));
GLuint*  counter;
GLuint*  counter1;
*counters=1000;
glGenBuffers(1, &atomicsBuffer);
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, atomicsBuffer);

glUseProgram(cpsId);

glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint) * 1,counters, GL_STATIC_DRAW);
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, atomicsBuffer);
GLuint shaderStorageBufferID;

glGenBuffers(1, &shaderStorageBufferID);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, shaderStorageBufferID);
glBufferData(GL_SHADER_STORAGE_BUFFER, 1*sizeof(GLuint), NULL ,GL_STATIC_READ);
int buffer_index=tdk_glGetProgramResourceIndex(tdk_ShaderObject.cpsId, GL_SHADER_STORAGE_BLOCK, "myBuffer", nResult);
printf("buffer_index = %d", buffer_index);
glShaderStorageBlockBinding(tdk_ShaderObject.cpsId, buffer_index, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0,shaderStorageBufferID);
glDispatchCompute(1,1,1,nResult);
counter = (GLuint*) glMapBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0,1*sizeof(GLuint),  GL_MAP_READ_BIT|GL_MAP_WRITE_BIT );

printf("counter %d",*counter);

counter1 = (GLuint*) glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0,1*sizeof(GLuint), GL_MAP_READ_BIT|GL_MAP_WRITE_BIT   );
Printf("counter %d",*counter1);
tdk_glUnmapBuffer(GL_ATOMIC_COUNTER_BUFFER,nResult);
tdk_glUnmapBuffer(GL_SHADER_STORAGE_BUFFER,nResult);

both counter and counter1 are same


text:
Q: How to keep process (stress) running till I have testcase running I want to do stress testing of my software. I have multiple testcases with me with different runtime.
Currently, I'm running stress utility with required options and run testcase in another terminal. Once that testcase gets over, I kill stress process with ctr+C.
Now, I want to create a script which will run the stress utility and then run testcase and should be able to kill stress process after my testcase gets over.
I have a workaround as of now with stress i.e. --timeout option. So I'm running as follows:
stress -c 16 --timeout 3600
./runme //Testcase script

After an hour, stress utility gets finished. But there is following issue with the above mentioned workaround i.e. ./runme can take 1 min to 2-3 hours of time. So I can't put timeout value beforehand.
Please suggest a way to deal with this.

A: Run your stresser in the background and note it's pid which will be used to kill it later on. And now start your testcases in the foreground. After the testsuites finish, you go ahead n kill the stresser now:
stress -c 16 & #<--- note no timeoutoption given and assuming now it runs forever
pid_stress=$!

./rune //Testcases script

kill -9 "$pid_stress"


text:
Q: Installing PySerial 2.6 on Windows XP SP3 Ok, I am trying to install PySerial 2.6 on my windows XP SP3 machine. After having unpacked the PySerial download and running the setup.py file I get this error.
C:\PYSERIAL\dist\pyserial-2.6\setup.py
Traceback (most recent call last):
  File "C:\PYSERIAL\dist\pyserial-2.6\setup.py", line 44, in <module>
    open(os.path.join('serial', '__init__.py')).read()).group(1)
IOError: [Errno 2] No such file or directory: 'serial\\init_.py'

I don't see the problem. There is a file in the same directory as setup.py called 'serial' and
__init__.py

is inside that file. So whats going wrong? I'm sitting here looking at the file in the directory!

A: I used
easy_install

and the url where the file was located, it was all taken care of automatically.


text:
Q: How to get HTML string of dynamically changed element using jQuery?

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').val('hi');
  console.log(parent.prop('outerHTML'));
});

  <input type='text' id="bar" value="" />

I have a container div with child input element, the initial value is empty, after that I change it's value using jQuery and try to get the changed html string using .prop('outerHTML'). However it returns:

<input type="text" id="bar" value="">

I need to return it as:

<input type="text" id="bar" value="hi">

Is this possible ?

A: You can use .attr() instead.

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value', 'hi');
  console.log(parent.prop('outerHTML'));

  $('#txt').text('hello');
  console.log($('#par').find('#txt').prop('outerHTML'));
});

  <input type='text' id="bar" value="" />

  <textarea id='txt'></textarea>

For more details - visit following link.

A: Sure, use direct attrbite change, not element value.

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value', 'hi');
  console.log(parent.prop('outerHTML'));
});

  <input type='text' id="bar" value="" />

A: try this
$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value','hi');
  console.log(parent.prop('outerHTML'));
});


text:
Q: Azure AD B2C Custom Policies - Javascript Can we add javascript inside custom policies and can we use button click function to redirect to another page?
I have referred the following links when implementing custom policies.

A: JavaScript is now supported for custom policies. Here is the official documentation:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/javascript-samples
NB: it seems you need to use the b2clogin.com domain (not login.microsoftonline.com). I cannot find this documented at the moment, but a quick test shows that JavaScript is stripped out on login.microsoftonline.com. Here is the documentation for using b2clogin.com: https://learn.microsoft.com/en-us/azure/active-directory-b2c/b2clogin.

A: JavaScript is currently not supported in custom UI. See the note under Create your HTML5 content.

A: Custom JavaScript is not currently supported in Azure AD B2C. We are working to enable that feature - please vote for the feature here so that you can get an update when the preview is available.

A: Yes, you can use JavaScript in custom policies.  See this sample: active-directory-b2c-advanced-policies.
PlayerProfileUpdate.html
<script src="https://wingtipb2ctmpls.blob.core.windows.net/wingtiptoys/js/analytics.js" />
<script src="https://wingtipb2ctmpls.blob.core.windows.net/wingtiptoys/js/selfasserted-playerprofileupdate.js"></script>

I don't know for sure about the button click redirect.  On the surface, if you can use JavaScript then you should be able to do this.


text:
Q: Exclude all transitive dependencies with Apache Maven Shade Plugin I have used Apache Maven Shade Plugin to create fat jar (the jar which includes all classes from all dependencies). My current project folder structure looks something like this,
> Parent Module (packaging pom)

    > Module 1 (packaging jar)
        > Own classes
        > Dependency-1
        > Dependency-2

    > Module 2 (packaging jar)
        > Own classes
        > Module 1 (I want here only classes written in module-1, not any transitive dependencies)
        > Dependency-1
        > Dependency-2
        > Dependency-3

The pom.xml snap-shot from Parent Module,
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
            <execution>
                <id>common-shade</id>
                <goals>
                    <goal>shade</goal>
                </goals>
                <configuration>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.handlers</resource>
                        </transformer>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.schemas</resource>
                        </transformer>
                    </transformers>
                </configuration>
            </execution>
        </executions>
    </plugin>

The pom.xml snap-shot from Module-1 & Module-2 looks like this,
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <executions>
        <execution>
            <id>common-shade</id>
            <phase>package</phase>
        </execution>
    </executions>
</plugin>

The dependency declared for Module-1 in Module-2 pom looks like this,
<dependency>
    <groupId>my.com.groupId</groupId>
    <artifactId>my.artifactId</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <exclusions>
        <exclusion>
            <groupId>*</groupId>
            <artifactId>*</artifactId>
         </exclusion>
    </exclusions>
</dependency>

NOTE : Currently, if I see my dependencies using mvn dependency:tree -Dverbose, then it's showing as expected, but shade-plugin is not excluding it.
Problem : The module-1 & module-2 have some same dependencies with different versions. If I skip/disable shade-plugin declared in Module-1, then I can run Module-2 with no issues, but if I don't disable it, then the fat jar created by Module-2 includes some classes from jars with Module-1 versions, so my Module-2 stops running.
UPDATE :
I use fat jar to run individual modules like this,
java -cp module.jar com.mycom.Main
Any help please?


text:
Q: Loading ffmpeg-php module fails I've been trying this for a couple of days now. I am trying to install ffmpeg-php on my CentOS server.

*

*OS     : CentOS 6

*PHP    : 5.5

*ffmpeg     : 1.2.1

*ffmpeg-php : 0.6.0

The ffmpeg  installation went on without a hitch and I am able to convert files back and forth via the CLI.
While installing ffmpeg-php, I encountered errors while making (after configuring) due to time.h references which was corrected by renaming the files creating with an extension .loT to .lo (as rightly pointed out here)
Once this was done, the make process went on smoothly and the make install went through without a hitch. However, after specifying the extension=ffmpeg.so in the php.ini file and after restarting Apache, the module doesn't load or show up in phpinfo().
The Apache error log shows only "PHP Warning:  PHP Startup: Invalid library (maybe not a PHP library) 'ffmpeg.so' in Unknown on line 0" and nothing else.
make test also shows the same error and FAILS the associated tests. I've checked here which wasn't very helpful. Also, I read somewhere that it may be the issue with permissions but the permissions for the ffmpeg.so file is 755.
Any help is appreciated.
Thanks in advance.

A: After looking up for hours, it seems that time.h for some apparent reason has been used in ffmpeg 1.2.1 (this is what I tested). This caused conflict with the OS's own file of the same name. This causes the installation to break in CentOS 6.x, RHEL 5.6 and RHEL 6.x
While I cannot code in PHP (and can barely read PHP code), I have found a git repo maintained by tony2001 who has made changes to the original project and using his repo has helped me install it successfully on CentOS-6.2, CentOS-6.3 and CentOS-6.4.
You can find the repo here. This seems to solve the issues in CentOS 6.x, RHEL 5.6 and RHEL 6.x.
Hope this helps anyone else trying this in the future (and maybe someone else who lands up here eventually)
PS: Incidentally, at the time of writing this answer ffmpeg 2.0 has been released but I haven't got a chance to test it yet


text:
Q: Sleepy tired vs physically tired I'm trying to figure out if there is a better way to distinguish between being sleepy-tired, and being physically tired.

*

*Scenario A: You didn't get much sleep last night. It's only 10am so you've not done much today, but you keep nodding off. You are tired

*Scenario B: You've mowed the lawn, done a lot of heavy lifting, walked a lot, and now your muscles ache, you want to sit down. It's only lunchtime. You are physically tired, but wide awake. You are tired
I'm specifically asking about scenario B as you could use sleepy for Scenario A, which wouldn't get mixed up with physical tiredness.
I've looked at some synonyms such as exhausted and fatigued but I think these could also suggest some form of sleepiness.
I'm trying to find a one word or short way of saying "I'm tired, but not in the sleepy sense of the word" (*I'm physically tired, not sleepy tired)
I'm not asking for a way to say "It's bedtime, and although physically tired I'm still not sleepy"
The conversation scenario I'm trying to avoid:

A: sits down on the sofa, 8pm. "Boy, am I tired"
B: "well that's because you didn't have much sleep last night"
A: "No, I mean I'm physically tired, I'm actually not sleepy at all"

Is there a word A could initially use to avoid the sleep branch of the conversation? Does A have to resort to saying "Boy, I'm physically tired, but wide awake"?
Here's maybe a better way of what I'm driving at.

You didn't get much sleep during the night. You go to a long gym session at 9am and do more than you usually might, resulting in your muscles having a thorough workout. You have a coffee at 11am and then go home to your partner (who knows you didn't get much sleep) and flump on the sofa:

*

*You are physically tired (you just want to sit down as your muscles are tired)

*You've recovered from your immediate exertion (so you're not out of breath)

*You are mentally awake (You're ready to sit down and do the crossword)

*You don't feel sleepy at all (You could go to bed, but you wouldn't sleep. Why would you, it's the middle of the day and you've only just got up - you are not restless)

You want a short way to say "Phew, I'm tired!" but in a way that cannot be construed as being mentally tired or feeling the need for sleep. (and without having to qualify it with a longer sentence).

A: Exhausted/exhaustion is really the word to use here. The only places I can think of exhausted being a synonym for merely sleepy is when the speaker is engaged in hyperbole

I didn't have a nap today. I'm exhausted!

That could mean tired or sleepy. Missing a nap does not generally leave one exhausted (unless you're a toddler). Remember, exhausted also means most or all energy expended.

They fired the rocket engine until the fuel supply was exhausted

What might be confusing here is you can reach a state of physical exhaustion by ignoring sleep for too long.

Ralph had been up for 36 hours by that time, and he was exhausted

When you stay awake for too long, your body starts to malfunction and shut down. As such, this is now a physical state. Ralph is not being hyperbolic here, as he's literally on the verge of falling unconscious.

A: Pooped (participle form of the verb to poop) tends to be applied to physical exhaustion. Here is Merriam-Webster, poop verb (3):

poop verb (3)
pooped; pooping; poops
Definition of poop (Entry 5 of 6)
transitive verb slang : to put out of breath also : to tire out
intransitive verb slang : to become exhausted poop out

The out of breath meaning is especially relevant. Someone might say, "I'm pooped!" after a day of physical labor or after a long run. That may coincide with being sleepy (if you're pooped at the end of a long day you are most likely also at least a bit sleepy), but most often someone who is pooped is physically exhausted (from The Grammarphobia Blog):

After separating the recyclables into three bins and dragging them out to the street, my hubby turned to me and said he was pooped.

So in your hypothetical conversation, it might go like this:

A: sits down on the sofa, 8pm. "Boy, am I pooped."
B: "Did you have a long day at work?"
A: "Yeah, I had to haul furniture all day."

A: I think this is quite England-specific, but we'd use the word Knackered to distinguish from sleepy.

A: I think participles might help give the sense that something (e.g. physical exertion) has "worn you out" beyond the normal process of becoming sleepy. For example, wearied (as opposed to simply weary).
I think some colloquial constructions that use a passive form might also help give the sense of what you want, like these:

*

*done-in: worn out; exhausted; used up

*drained: to be deprived of strength

*sapped: to drain the [every; vitality] from

*spent: used up; consumed

*beat: exhausted; worn out

A: worn-out (from Wiktionary, 2019):

Exhausted or fatigued from exertion.

I think exhausted or depleted could also work when provided with more context.
The thing is sleep is a very complex state due to circadian and homeostatic processes.
Circadian: someone who is full of energy but has a strict sleeping pattern can still be sleepy at bed time.
Homeostatic: someone who is depleted of resources can still be wakeful or restless due to changes in hormonal processes such as adrenaline rushes from bodily stress and blocking adenosine from binding to its receptors when ingesting caffeine.

A: I need to sit down [ for a bit] conveys physical exhaustion. Likewise, I need a nap ( or, I need to lie down ) conveys sleepy-tired, or mental exhaustion.
There's no sharp demarcation in most common words and phrases, since physical exhaustion will soon lead to sleep if you allow it to. Sleep is the body's best way of replenishing its chemical energy stores, both those which are depleted by hard physical work and those which are depleted by having been awake for too long. However, a short sit-down from physical labour will go some considerable way towards restoring physical strength, whereas only sleep will work for mental exhausion.


text:
Q: IllegalAccessError to guava's StopWatch from org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus I'm trying to run small spark application and am getting the following exception:
Exception in thread "main" java.lang.IllegalAccessError: tried to access method com.google.common.base.Stopwatch.<init>()V from class org.apache.hadoop.mapreduce.lib.input.FileInputFormat
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:262)
    at org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat.getSplits(CombineFileInputFormat.java:217)
    at org.apache.spark.rdd.NewHadoopRDD.getPartitions(NewHadoopRDD.scala:95)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
    at scala.Option.getOrElse(Option.scala:120)

the relevant gradle dependencies section:
compile('org.apache.spark:spark-core_2.10:1.3.1')
compile('org.apache.hadoop:hadoop-mapreduce-client-core:2.6.2') {force = true}
compile('org.apache.hadoop:hadoop-mapreduce-client-app:2.6.2') {force = true}
compile('org.apache.hadoop:hadoop-mapreduce-client-shuffle:2.6.2') {force = true}
compile('com.google.guava:guava:19.0') { force = true }

A: I had this problem with Spark 1.6.1 because one of our additional dependencies evicted Guava 14.0.1 and replaced it with 18.0. Spark has the base dependency for hadoop-client of 2.2. See [Maven Repo] (https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10/1.6.1)
The solution that worked for is to add to sbt libraryDependencies the following: "org.apache.hadoop" % "hadoop-client" % "2.7.2"

A: Sounds like you've got a Guava version mismatch.
Something in your codebase is trying to invoke the Stopwatch constructor, but the constructors were removed from in Guava 17.0 in favor of static factory methods (createStarted() and createUnstarted()) that were added in Guava 15.0.
You should update whatever code is trying to use the constructors to use the static factory methods instead.

A: version 2.6.2 of hadoop:hadoop-mapreduce-client-core can't be used together with guava's new versions (I tried 17.0 - 19.0) since guava's StopWatch constructor can't be accessed (causing above IllegalAccessError)
using hadoop-mapreduce-client-core's latest version - 2.7.2 (in which they don't use guava's StopWatch in the above method, rather they use org.apache.hadoop.util.StopWatch) solved the problem, with two additional dependencies that were required:
compile('org.apache.hadoop:hadoop-mapreduce-client-core:2.7.2') {force = true}

compile('org.apache.hadoop:hadoop-common:2.7.2') {force = true} // required for org.apache.hadoop.util.StopWatch

compile('commons-io:commons-io:2.4') {force = true} // required for org.apache.commons.io.Charsets that is used internally

note:
there are two org.apache.commons.io packages:
commons-io:commons-io (ours here), and
org.apache.commons:commons-io (old one, 2007). make sure to include the correct one.

A: In my case, because of adding guava 21.0 result in error.
 <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
 </dependency>

After that, I am using guava 15.0 or remove above dependency. My code works well.

A: Solution

*

*Multiple versions of guava.jar files getting conflicted as transitive dependencies which is causing this exception.

*Identify the conflicting version and add as an exclusion in pom.xml will resolve this issue.

*In My case after adding pmml-evaluator version 1.4.1 dependency caused this exception.

*Identified through dependency hierarchy and added maven exclusions resolved this issue.
   <dependency>
    <groupId>org.jpmml</groupId>
    <artifactId>pmml-evaluator</artifactId>
    <version>1.4.1</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </exclusion>
    </exclusions>
   </dependency>

A: I just changed my guava version from 19.0 to 15.0 and it worked. I am currently using version spark 2.2
<dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>15.0</version>
      </dependency>

A: We just experienced the same situation using IntelliJ and Spark.
When using
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.3.1"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.3.1"

com.google.guava 20.0 is downloaded and hadoop client 2.6.5 is downloaded.
The quickest solution would be to force the guava library to version 15.0 (SBT)
dependencyOverrides += "com.google.guava" % "guava" % "15.0"

A: It seems that the problem comes from dependent libraries.
Basically, you will get the problem when your trying to put the data into hbase table.
Initially I had used <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>1.1.2</version> </dependency>
I got the similar problem as you and later I changed to <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-shaded-client</artifactId> <version>1.1.2</version> </dependency> and now the problem has been resolved.

A: If you want to workaround this problem without re-building Spark, for instance using a pre-built distribution of Spark, then I found the following worked on Apache Spark 2.3.0 (i.e. used the pre-built: 'spark-2.3.0-bin-without-hadoop'):

*

*Rename or remove the errant version of the 'hadoop-mapreduce-client-core' jar file (in my case this was 'hadoop-mapreduce-client-core-2.6.5.jar') from the Spark 'jars' directory.

*Copy-in (or soft-link) the compatible version (from your Hadoop installation) of the 'hadoop-mapreduce-client-core' jar into the Spark 'jars' directory.

It may also be possible to force the desired 'hadoop-mapreduce-client-core' jar file to be used by altering your classpath (so that Spark finds the version from  Hadoop rather than the one distributed with Spark).

A: spark version=2.4.8
scala version=2.12.12
I added below 3 dependencies
libraryDependencies += "com.google.guava" % "guava" % "15.0"
libraryDependencies += "org.apache.hadoop" % "hadoop-mapreduce-client-core" % "3.3.4"
libraryDependencies += "org.apache.hadoop" % "hadoop-common" % "3.3.4"
It's worked for me


text:
Q: Okta Widget - Get info from logged in user I was able to configure the widget for a web app, authenticate through it and redirect to the configured page.
That configured page gets an interaction_code and a status as query parameters.
How do I now get some profile info from the authenticated user?


text:
Q: UIFont with a custom leading? I would like to use the system font but with a custom leading, but the leading property of a UIFont is readonly. Is there a way to create a system font with a custom leading value?
I am trying to display multiple lines with a UILabel, but the default leading is too narrow.
(\n\n is too wide)
If there is no way, then I need to create multiple UILabels but that seems a bit overkill.

A: I think you can't do that. UIFont is pretty tightly constrained.
If you have the linebreaks in place yourself then it's fairly trivial to draw the string yourself rather than creating multiple UILabels. You can generating sub-strings using – componentsSeparatedByString: and rendering each of them at your specified leading increments using the UIKit NSString addition: – drawAtPoint:withFont:.
If you need to generate your own wrapping, it's difficult - see this related question.

A: There is a way to customize the line spacing in a multi line UILabel.  Instead of using the text attribute of the label, use the attributedText property.  The attributed text can have a paragraph style with a negative lineSpacing value to make the lines a closer together.  Here is an example:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = -4;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:yourStringHere];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, titleText.length)];
yourUILabel.attributedText = attributedString;

A: It could be done by crating a custom category on UIFont and replacing property for lading with custom setter. I am still trying to do this.


text:
Q: TFS Build fails with "cannot access file *FakeTypesCache" since a few days we are experiencing issues with our TFS build. We use Microsoft Shims/Fakes for some of our unit tests and so far we had no issues with it.
But lately the UnitTest Step fails on the with the following error:
The following happens every once in a while:
2016-07-01T06:40:25.3532321Z ##[error]Error: System.IO.IOException: The process cannot access the file 'D:\Builds\Agent\87a4a39e\...\bin\Debug\mscorlib.4.0.0.0.Fakes.FakedTypesCache' because it is being used by another process.

2016-07-01T06:40:25.3532321Z ##[error]   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

2016-07-01T06:40:25.3532321Z ##[error]   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

2016-07-01T06:40:25.3532321Z ##[error]   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

2016-07-01T06:40:25.3532321Z ##[error]   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)

2016-07-01T06:40:25.3532321Z ##[error]   at System.IO.StreamReader..ctor(String path)

2016-07-01T06:40:25.3532321Z ##[error]   at Microsoft.VisualStudio.TraceCollector.FakesAssemblyReflector.LoadShimTypesFromCache(String fakedTypesCacheFilePath)

2016-07-01T06:40:25.3532321Z ##[error]   at Microsoft.VisualStudio.TraceCollector.FakesAssemblyReflector.ReflectShimTypes(String fakesAssemblyFullPath)

2016-07-01T06:40:25.3532321Z ##[error]   at Microsoft.VisualStudio.TraceCollector.UnitTestIsolationDataCollector.PopulateCollectionPlan(_CollectionPlan plan, XmlElement settings)

2016-07-01T06:40:25.3532321Z ##[error]   at Microsoft.VisualStudio.TraceCollector.UnitTestIsolationDataCollector.OnSecondCollectorToInitialize(_CollectionPlan plan, XmlElement configurationElement)

2016-07-01T06:40:25.3532321Z ##[error]   at Microsoft.VisualStudio.TraceCollector.CommonDataCollector.OnInitialize(XmlElement configurationElement)

2016-07-01T06:40:25.3532321Z ##[error]   at Microsoft.VisualStudio.TraceCollector.BaseDataCollector.InternalConstruct(XmlElement configurationElement, IDataCollectionEvents events, IDataCollectionSink dataSink, IDataCollectionLogger logger, IDataCollectionAgentContext agentContext)

2016-07-01T06:40:25.3532321Z ##[error]   at Microsoft.VisualStudio.TraceCollector.BaseDataCollector.Initialize(XmlElement configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, DataCollectionEnvironmentContext environmentContext)

2016-07-01T06:40:25.3532321Z ##[error]   at WEX.TestExecution.DataCollectorTestMode.Initialize(ITestModeSettings settings, ICallbackRegistrar callbackRegistrar)

2016-07-01T06:40:25.3532321Z ##[error]

I'm not sure if it has to do something with our code coverage (because the stack trace mentions this datacollector). We use a runsettings file to in-/exclude certain things from the code coverage.
On the build server we have an installed Visual Studio 2015 Update 3 (but the problem occured as well with Update 2) and the TFS is version 2015 RTM.
The file that is apparently locked is not always the same, but it is always one of the "FakeTypeCaches".
Any help would be appreciated
Thanks
Edit
It seems that the problem was caused by running the unit tests in parallel (I think the option is available since VS 2015 Update 1). Running them not in parallel seems to have fixed the problem, but sadly running our tests now take considerably longer to run. Especially for our CI build this is not ideal as we would like to get the feedback as soon as possible.
If we could only run the tests that use Faked/Stubbed classes sequentially that would be ideal, but as of know I don't know how one would achieve this.
Our solution now to solve this problem is to mark all tests that use Fakes/Shims in any way with a TestCategory: [TestCategory("Sequential")]
On the build server we have defined two unit test steps, the first filters for all categories except "Sequential" and is run in parallel, the second then runs the "Sequential"s not in parallel.

A: Based on the error message, it seems that other process holding that file.
Try to use this tool to determine which file exactly is beeing locked by which process. Then stop the process when the building is in progress.

A: This is a known issue fixed in Update for Microsoft Visual Studio 2015 Update 2 (KB3151378).
You should just grab the latest update for Visual Studio, which at the time of this answer is: Visual Studio 2015 Update 3

A: we are on TFS2015 Update3 On-Promise, we have the same issue when run unit tests in parallel.
Our short term solution is disabled Repository clean option, and only use MSBuild clean,so those fakes cache file won't be cleaned. Seems the error only happens if multiple tests trying to create the fakes cache files at the same time.
However with disabling the Repository clean option, we are also experiencing some other random annoying issues. :(.
Kindly let me know if you have figure out a better way to avoid the issue.
Thanks,
Angel


text:
Q: Perishable Documents? Is there any way that MongoDB handles the deletion of documents automaticaly based on time?
I use Tornado (Python) and the IOLoop can do it, but it checks always for time, and the life of those documents is high (6 mounth),
So can Mongodb do it without making a clickable script or using the IOLoop?

A: Yes, it's a feature (new in 2.1) called TTL (time-to-live) indexes.
You can read all about them including examples here:
http://docs.mongodb.org/manual/tutorial/expire-data/


text:
Q: Delete QNetworkReply *reply cause SIGSEGV outside of the code? I wrote a simple program to automate the process setting the router. After a check, I find a pointer need to be delete (QNetworkReply *reply in replyFinish())and do the job, but after that the program crash and Qt show it stopped in some assembly code :(
So my questions are:

*

*Are there any common practices to handle situation like that (Qt
show the program stopped in some assembly code)

*What did I do wrong when delete a pointer which isn't used anymore?
    (pretty sure about that)
Here is the code:
#ifndef HTTPGETTER_H
#define HTTPGETTER_H
class QNetworkAccessManager;
class QNetworkReply;
class QNetworkRequest;
class QAuthenticator;
#include <QObject>

class httpGetter : public QObject
{
    Q_OBJECT
private:
    QNetworkAccessManager *nam;
public:
    explicit httpGetter(QObject *parent=0);
    ~httpGetter();
public slots:
    void replyFinish(QNetworkReply* reply);
    void onAuthen(QNetworkReply*,QAuthenticator*);
};

implements
#include "httpgetter.h"
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkAccessManager>
#include <QAuthenticator>
#include <QDebug>
httpGetter::httpGetter(QObject *parent) : QObject(parent)
{
    nam = new QNetworkAccessManager(this);
    QObject::connect(nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinish(QNetworkReply*)));
    QObject::connect(nam,SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),this,SLOT(onAuthen(QNetworkReply*,QAuthenticator*)));

    QUrl url("http://192.168.1.1");
    QNetworkReply *reply= nam->get(QNetworkRequest(url));

}
httpGetter::~httpGetter(){
    delete nam;
}
void httpGetter::replyFinish(QNetworkReply *reply)
{
    if (reply==NULL) {
        qDebug() << "NULL reply";
        return;
    }

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    qDebug() << statusCode.toString();

    if (reply->error()==QNetworkReply::NoError) {
        qDebug() << "NICE reply";
        QByteArray bytes = reply->readAll();
        QString answer = QString(bytes);
        qDebug()<< answer;
    }

    else {
        qDebug() << "reply error";
    }

    //delete reply; ==> delele cause sigsegv, if don't the program run like a     while(true)
    //reply == NULL;

}

void httpGetter::onAuthen(QNetworkReply* rep,QAuthenticator* auth)
{
    if ( rep==NULL || auth == NULL) {
        qDebug()<< "reply or authentication pointer is null";
        return;
    }

    qDebug()<< rep->readAll();
    auth->setUser("rolan");
    auth->setPassword("123456");
}

main
#include <QtCore/QCoreApplication>
#include "httpgetter.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    httpGetter abc;

    return a.exec();
}

A: According to the documentation:

Note: After the request has finished, it is the responsibility of the
  user to delete the QNetworkReply object at an appropriate time. Do not
  directly delete it inside the slot connected to finished(). You can
  use the deleteLater() function.

Also, since
nam = new QNetworkAccessManager(this);

creates a new QNetworkAccessManager with this as its parent, and QObject's destructor will automatically delete all of its children, your delete nam; in httpGetter's destructor is unnecessary and will end up causing a double delete.


text:
Q: WSO2 BAM 2.4.1 port offset error I am running BAM 2.4.1 in windows.
set   in carbon.xml.
<Ports>

        <!-- Ports offset. This entry will set the value of the ports defined below to
         the define value + Offset.
         e.g. Offset=2 and HTTPS port=9443 will set the effective HTTPS port to 9445
         -->
        <Offset>200</Offset>

bam-datasources.xml
datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">

    <providers>
        <provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
    </providers>

    <datasources>

        <datasource>
            <name>WSO2BAM_DATASOURCE</name>
            <description>The datasource used for analyzer data</description>
            <definition type="RDBMS">
                <configuration>
                    <url>jdbc:h2:repository/database/samples/BAM_STATS_DB;AUTO_SERVER=TRUE</url>
                    <username>wso2carbon</username>
                    <password>wso2carbon</password>
                    <driverClassName>org.h2.Driver</driverClassName>
                    <maxActive>50</maxActive>
                    <maxWait>60000</maxWait>
                    <testOnBorrow>true</testOnBorrow>
                    <validationQuery>SELECT 1</validationQuery>
                    <validationInterval>30000</validationInterval>
                </configuration>
            </definition>
        </datasource>

        <datasource>
            <name>WSO2BAM_CASSANDRA_DATASOURCE</name>
            <description>The datasource used for Cassandra data</description>
            <definition type="RDBMS">
                <configuration>
                    <url>jdbc:cassandra://localhost:9160/EVENT_KS</url>
                    <username>admin</username>
                    <password>admin</password>
                </configuration>
            </definition>
        </datasource>

        <datasource>
            <name>WSO2BAM_UTIL_DATASOURCE</name>
            <description>The datasource used for BAM utilities, such as message store etc..</description>
            <definition type="RDBMS">
                <configuration>
                    <url>jdbc:cassandra://localhost:9160/BAM_UTIL_KS</url>
                    <username>admin</username>
                    <password>admin</password>
                    <dataSourceProps>
                        <property name="externalCassandra">false</property>
                    </dataSourceProps>
                </configuration>
            </definition>
        </datasource>

        <!-- The URL configs are loaded from hector-config.xml -->
        <datasource>
            <name>WSO2BAM_HIVE_INCREMENTAL_DATASOURCE</name>
            <definition type="RDBMS">
                <configuration>
                    <username>admin</username>
                    <password>admin</password>
                    <dataSourceProps>
                        <property name="replicationFactor">1</property>
                        <property name="strategyClass">org.apache.cassandra.locator.SimpleStrategy</property>
                        <property name="readConsistencyLevel">QUORUM</property>
                        <property name="writeConsistencyLevel">QUORUM</property>
                        <property name="keyspaceName">HIVE_INCREMENTAL_KS</property>
                    </dataSourceProps>
                </configuration>
            </definition>
        </datasource>

    </datasources>

</datasources-configuration>

no problem with start.
But after press "Cassandra Keyspaces" in "Main" of management console I get errors
in console
The following error details are available. Please refer logs for more details.
org.wso2.carbon.cassandra.mgt.ui.CassandraAdminClientException: Error retrieving keyspace names !
at org.wso2.carbon.cassandra.mgt.ui.CassandraKeyspaceAdminClient.listKeyspacesOfCurrentUSer(CassandraKeyspaceAdminClient.java:122)
at org.apache.jsp.cassandramgt.cassandra_005fkeyspaces_jsp._jspService(org.apache.jsp.cassandramgt.cassandra_005fkeyspaces_jsp:107)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:403)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492) ......

and error in server log
[2014-07-24 18:09:43,190]  WARN {me.prettyprint.cassandra.connection.CassandraHo
stRetryService} -  Downed localhost(127.0.0.1):9160 host still appears to be dow
n: Unable to open transport to localhost(127.0.0.1):9160 , java.net.ConnectExcep
tion: Connection refused: connect

note, what port 9160 is not correct.
https://wso2.org/jira/browse/BAM-1476
reported as Fixed [ 1 ] but....
What is wrong?

A: Change 9160 value in the WSO2BAM_CASSANDRA_DATASOURCE section to 9160+portOffset. Also change /conf/etc/hector-config.xml with the same value.


text:
Q: No holomorphic injective mapping $f:D\to \Bbb C^n$ if $\operatorname{\dim} D>n$ Take an open subset $D\subset\Bbb C^m$.
I suspect there is no holomorphic injective mapping $f:D\to \Bbb C^n$ if $m>n$.
Is this true?
Being $f$ injective holomorphic then it must be regular (that is its differential has maximum rank at each point), so the image is an open set in $\Bbb C^n$, then, intuitively, being the target too tight because of the smaller dimension, there is no room for the image of an injective mapping. But how can we prove it?

A: Invariance of domain is one way to go, but I think that's too much machinery. An alternative proof can be given using the constant-rank theorem (which is equivalent to the inverse function theorem and also to the implicit function theorem, and these are certainly available to students after a multivariable calculus course). We can actually prove this theorem:

Let $m,n$ be integers with $m>n$, let $D\subset \Bbb{R}^m$ be non-empty and open, and $f:D\to \Bbb{R}^n$ be a $C^1$ map. Then, $f$ is not injective.

To prove this, let $r$ be the maximum rank of $f$ on $D$, i.e
\begin{align}
r:=\max\{\text{rank}(Df_x)\,|\,\,\, x\in D\}
\end{align}
The maximum exists because this is a finite non-empty set of integers. Suppose $a\in D$ is a point where $r=\text{rank}(Df_a)$. Since the rank cannot decrease locally, and $r$ is the maximum rank, it follows there is an open set $A\subset D$ containing $a$, such that $f$ has constant rank $r$ on $A$. Therefore, by the constant rank theorem, there exist $C^1$ diffeomorphisms

*

*$\phi:A'\to \phi[A']\subset\Bbb{R}^m$, where $A'$ is some neighborhood of $a$ in $A$

*$\psi:B\to \psi[B]\subset\Bbb{R}^n$ where $B$ is a neighborhood of $f(a)$ in $\Bbb{R}^n$
such that $f(A')\subset B$ and the composition $\psi\circ (f|_{A'})\circ \phi^{-1}:\phi[A']\subset\Bbb{R}^m\to\Bbb{R}^n$ is equal to the rank $r$ linear transformation
\begin{align}
(x^1,\dots, x^m)\mapsto (x^1,\dots, x^r,0,\dots, 0)
\end{align}
Since $m>n\geq \min(m,n)\geq r$, it follows that $\psi\circ f\circ \phi^{-1}$ is not injective. Since $\psi,\phi$ are $C^1$ diffeomorphisms (in particular bijections), it follows that the restriction $f|_{A'}$ and hence $f$ are not injective.
Finally, in your case, holomorphic maps are certainly $C^1$, so by considering $\Bbb{C}^n\cong \Bbb{R}^{2n}$ etc it follows there is no holomorphic injective mapping $f:D\subset\Bbb{C}^m\to\Bbb{C}^n$ if $m>n$. (or you could repeat this entire argument, because the inverse function theorem, implicit function theorem, constant rank theorem all have natural analogues in the holomorphic case).


text:
Q: Why my data can't successful convert to json property I defined I'm try to convert a sqs message to a self defined SQS event, the message in convertMessageFromSqsForEvent is valid and it have value, but the sqsEventProperties is null, what is the problem?
fun convertMessageFromSqsForEvent(message: Message): SQSEventProperties? {
        var sqsEventProperties: SQSEventProperties? = null
        sqsEventProperties = mapper?.readValue(message.body, SQSEventProperties::class.java)

        return sqsEventProperties
 }

data class SQSEventProperties(
    @JsonProperty("attributes") var attributes: String?,
    @JsonProperty("awsRegion") var awsRegion: String?,
    @JsonProperty("body") var body: String?,
    @JsonProperty("eventSource") var eventSource: String?,
    @JsonProperty("eventSourceARN") var eventSourceARN: String?,
    @JsonProperty("md5OfBody") var md5OfBody: String?,
    @JsonProperty("md5OfMessageAttributes") var md5OfMessageAttributes: String?,
    @JsonProperty("messageId") var messageId: String?,
    @JsonProperty("receiptHandle") var receiptHandle: String?,
)

message
{MessageId: 94995ca7-ee33-4109-aabf-23d375878140,
ReceiptHandle: AQEBf5kvP0RwvFtKPmZglRhxXAS7FKGxbUCazYXD0+HFq6hpQGri3KU8TZirGC9NEu86DZretaBi5oeFbzzkWnMoxwzZ68/m7FZLt8fxX0gCoL2CxJMy0JXClRTZI+O06Hwn+CZMb5LOAKkGffJUS48dfe5GERKAZGsnLK4vA2pODrxfv1vvC6CXTzejoA9Dw+kuo51F5S86iRzXjItjzRJDxcJp4xeXdjrWps4Wfx233G+x4KiP9t9yZ73L9ucDLzdguDwTee07KG5SdRgHDQWyXcc0IJNtAe/NDmkIhWhigHoZSQmVCVNQFBtcYuB6X2khB+oQZsLz0Vh1NLs3zQVuusBbMg6tpk94N28FUKCIugtwDxBRjIdJqfbUXEeL1PxXCBcb+Pn3vLH9NHKHEclxbg==,
MD5OfBody: de5da762733bf71530cdb2aba2892a65,
Body: Please send request for updated data,
Attributes: {},
MessageAttributes: {}}

A: The name of the field of the data class must be the same as the key of the Json data. You can modify your data class and try again.

data class SQSEventProperties(
    @JsonProperty("Attributes") var attributes: String?,
    @JsonProperty("AwsRegion") var awsRegion: String?,
    @JsonProperty("Body") var body: String?,
    @JsonProperty("EventSource") var eventSource: String?,
    @JsonProperty("EventSourceARN") var eventSourceARN: String?,
    @JsonProperty("Md5OfBody") var md5OfBody: String?,
    @JsonProperty("Md5OfMessageAttributes") var md5OfMessageAttributes: String?,
    @JsonProperty("MessageId") var messageId: String?,
    @JsonProperty("ReceiptHandle") var receiptHandle: String?,
)


text:
Q: Determination of Adjoint Operator
Given energy eigenstates $|n\rangle$ and an annihilation operator $$A|n\rangle:=a_n|n-1\rangle$$ with $a_n\in\mathbb{C}$, how does one determine the adjoint $A^\dagger$?

By definition of the adjoint operator
$$\langle A^\dagger m|n\rangle=\langle m|An\rangle=a_n\langle m|n-1\rangle$$ holds, orthonormality of energy eigenstates $\langle m|n\rangle=\delta_{m,n}$ further yields
$$\langle A^\dagger m|n\rangle=a_n \delta_{m,n-1}= a_{m+1} \delta_{m+1,n}= a_{m+1}\langle m+1|n\rangle$$
 and thus
$$\langle A^\dagger m|= a_{m+1}\langle m+1|.$$
 So now I know how $A^\dagger$ acts on an eigenket from the left after turning the result into a bra. How do I retrieve the action on the ket? I got very confused here.


text:
Q: Minimising problem with sums and matrices We assume that $p_0,...,p_k$ are pairwise conjugate to Q and we define a function $f(x)=\frac{1}{2}x^TQx+g^Tx$, and then we have to show that the solution $\alpha_0,...,\alpha_k$ is $\alpha_k=-\frac{x_k^Tp_k+g^Tp_k}{p_k^TQp_k}$, is solution to following minimisation problem $min_{\alpha_0,...,\alpha_k}f(\sum_{i=0}^k \alpha_ip_i)$. So I end up with finding the the minimum of $\alpha$ for
$$min_{\alpha_0,...,\alpha_k}f(\sum_{i=0}^k \alpha_ip_i)=min_{\alpha_0,...,\alpha_k}(\frac{1}{2}(\sum_{i=0}^k \alpha_ip_i)^TQ(\sum_{i=0}^k \alpha_ip_i)+g^T(\sum_{i=0}^k \alpha_ip_i))$$But how do I show the minimum is gives as the given expression, I think some matrix computation tricks, but can see how to start. Can anyone help me with some tricks?

A: The classic conjugate gradient method. So you want to find $\alpha_{k}$ such that $f\left(x_{k}+\alpha_{k}p_{k}\right)$ is minimum.
$$
\begin{aligned}
f\left(x_{k}+\alpha_{k}p_{k}\right)
&=
\frac{1}{2}x_{k}Qx_{k}+\alpha_{k}p_{k}^{T}Qx_{k}+\frac{1}{2}\alpha_{k}^{2}p_{k}^{T}Qp_{k}+q^{T}x_{k}+\alpha q^{T}p_{k}
\\\\
0
&=
\frac{d}{d\alpha_{k}}
f\left(x_{k}+\alpha_{k}p_{k}\right)
\\
&=
p_{k}^{T}Qx_{k}
+
\alpha_{k}p_{k}^{T}Qp_{k}
+
q^{T}p_{k}
\end{aligned}
$$
So there is a mistake in your post. It should be $\alpha_{k}=-\frac{p_{k}^{T}Qx_{k}+q^{T}p_{k}}{p_{k}^{T}Qp_{k}}$


text:
Q: Call Java with Javascript (JTA telnet) I need a bit of your help. I hope you could find a minute to take a look at my problem.
I'm using JAVA telnet application ( http://javatelnet.org/space/start )
You can download JTA application at this link ( http://javassh.org/download/jta26.jar ) You can use this applet with html code below:
<html>
<body>
<applet CODEBASE="."
    ARCHIVE="jta26.jar"
    CODE="de.mud.jta.Applet"
    NAME="Appletas"
    style="width: 250px; height: 250px; float: left;">
    <param name="config" value="applet.conf">
</applet>
</body>
</html>

You could also use applet.conf file placed in the same directory as your html page and .jar file is.
For example, if you put these lines inside of the applet.conf file:
Applet.detach           =       true
Applet.detach.startText =       Press to Start!
Applet.detach.stopText  =       Press to Stop!
Applet.detach.immediately =     false

Socket.host             =       10.0.0.1
Socket.port             =       23

Applet would be loaded and you could see .startText (button with the "Press to Start!" text). If you click on that button, application will start. It will try to connect to the device which has ip address of 10.0.0.1 via telnet ( port 23) protocol.
I'm looking how to achieve this with javascript. I want to load this applet hidden at the start. After that, there would be my own buttons, written in html, not in java. I want to call this applet by clicking on these buttons, and they would execute the same java command ( command which is starting the applet when we press a button with .startText).
I know we can call java functions from javascript like this:
<SCRIPT LANGUAGE="JavaScript">
function runAppletFunction()
{
document.AppletName.functionWeWantToCall();
}
</SCRIPT>

So, I tried to find these functions on jta26.jar java code. I found a great java decompiler.
Looks like there is 3 main functions : init() , start(), stop(). Stop function is working, I can call this function from javascript, and java telnet application will close if it's running. I'm not successfull with another functions, there is no errors too. I don't know how could I debug what is happening when I click on the .startText button, and which function is called, because after that click, telnet application is opened (that's what I'm looking for).
To save your time, I will add the main code of the application in another post ( because I can't add more than 2 hyperlinks at once, please reply anyone to this post first), but if you have a minute, please, check my html code with the applet in real. I know you guys could help me to figure out this problem. I just need to call the right function , in the right way.
I highly appreciate your help.

A: hope this helps
http://www.javareference.com/jrexamples/viewexample.jsp?id=81   ?
if it doesnt solve, i think it gives you the reason, that the other two methods might not be public .


text:
Q: How can I prevent Sitecore content from being accessed under any language identifer? How do you remove the ability to find content under language identifiers in Sitecore?
Content here:
/about

Is also available at:
/en/about

Weirder yet, any attempt to find content under a different language identifier results in an error about not being able to find Views.
/es/about
/pt-br/about
/aa/about  (this is invented..)

I don't want content available under any language identifier -- the URLs above should simply be 404s.
I can't find where this language identifier is isolated and processed.  I removed the LanguageResolver from the httpRequestBegin pipeline, but this didn't change the behavior.
There are many blog posts about turning off language embedding in the LinkManager, which I've done, but that's not enough -- I do not want content being produced under any language code. The firs segment of the URL should be treated like any other segment. Requests for /en/[whatever] should 404.

A: As well as setting the LinkManager to never embed, you also need to set the Languages.AlwaysStripLanguage setting to false.
Source: http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2015/03/prevent-the-sitecore-aspnet-cms-from-interpreting-url-path-prefixes-as-language-names.aspx

A: Assuming you already have a custom 404 resolver in place, you just need to change the Sitecore setting Languages.AlwaysStripLanguage from true to false like so:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="Languages.AlwaysStripLanguage" value="false" />
    </settings>
  </sitecore>
</configuration>


text:
Q: Challenge: unable to logout of linux I'm currently doing a challenge where I am suppose to break out of a Linux box.
The user for this box isn't part of the sudo group and I can't add this myself to the sudo group nor can I exit, logout, or quit.
I can't su because I don't know the password for other accounts on this box.
Do any of you guys have any ideas of how to get out?

A: *

*type exit

*Press Ctrl + D

*kill or kill -9 your_shell_PID

*poweroff which will technically log you out

*Unplug from the mains

*Blow it all up

*Cut all the wires


text:
Q: Pass C++ vector of unique_ptr without passing ownership I have a class Outer which contains an Inner member and owns a vector of unique_ptr elements:
using Elements = std::vector<std::unique_ptr<Element>>;

class Outer
{
    void call()
    {
        _inner.aMethod(_vec);
    }

    Inner _inner;
    Elements _vec;   // This should remain the owner of each Element
};

Inner receives the vector of unique_ptr elements and it transfers ownership to it's own vector class member:
class Inner
{
    public:
    Inner() = default;
    ~Inner() = default;

    void aMethod(Elements& vec)
    {
        _vec = std::move(vec);
    }

    private:

    Elements _vec;  // This is a vector of unique_ptr but I don't want this class to own the memory
};

I stupidly used std::move() because otherwise the compiler complained I was trying to call a deleted function (probably the copy constructor) on each vector element.
I have an illegal memory access and I believe it is because both classes think they own the vector elements and one has tried to delete an already-deleted Element.
How do I have Outer owning the memory and just pass the elements to Inner to use (not take ownership)?

A: You cannot have two std::unique_ptrs pointing to the same object.  unique_ptr implies unique ownership.
If you need ownership to be shared, use std::shared_ptrs instead.  In your example, it should be a drop-in replacement, just change the using declaration:
using Elements = std::vector<std::shared_ptr<Element>>;

If you don't want Inner objects to own the objects pointed to by its _vec member, then it should be a vector of raw pointers:
class Outer
{
    void call()
    {
        std::vector<Element*> observer;
        std::transform(_vec.begin(), _vec.end(), std::back_inserter(observer),
                       [](std::unique_ptr<Element>& el) { return el.get(); });
        _inner.aMethod(observer);
    }

    //...
};

class Inner
{
    // ...

    void aMethod(std::vector<Element*> vec)
    {
        _vec = std::move(vec);
    }

private:
    std::vector<Element*> _vec;
};

Of course, doing this would mean that you run the risk of leaving _vec's elements dangling if Outer frees any of the Elements it owns without updating any Inner objects that are pointing to them.  You could partially mitigate that risk by storing a pointer to the Outer object instead of storing pointers directly to the Elements:
class Outer
{
    void call()
    {
        _inner.aMethod(this);
    }

    //...
};

class Inner
{
    // ...

    void aMethod(Outer* outer)
    {
        outer_ = outer;
    }

private:
    Outer* outer_;
};

Inner would then only access its Elements via the Outer object (you could make Inner a friend of Outer if necessary).  This still leaves the possibility that an Inner object could outlive the Outer object it points to, but it does reduce the risk somewhat.

A: If Inner is supposed to access the same vector but not own it, why not let Inner keep a reference to the vector in Outer given the fact that they have the same life cycle?
class Inner
{
    public:
    Inner(Elements& vec):_vec(vec) {}
    ~Inner() = default;

    private:

    Elements& _vec;  // This is a reference to vector of unique_ptr, no ownership
};


text:
Q: How to increase painting performance in Java Swing I am currently working on a complex project and struggle with increasing the performance, because I ran out of ideas.
So this is what my program looks like at the moment:

It is a Graph, that shows the path of an object, starting at the green node and ending at the red node. The container is a JPanel, which holds another JPanel at the top right corner, containing the buttons, a JLabel at the top left corner for the status and the different Nodes itself of course. The Nodes and lines are JPanels as well.
So what exactly is the problem?
The Graph contains lots of functionalities. Zooming, DnD and adding end deleting new nodes.
All of these functionalities need the container to repaint, especially DnD needs this very often. So this is just an example with 4 nodes. everything works fine. But at 1000+ nodes and 999 lines between them, it really gets slow. The graph should be able to work with ~20K nodes  without having big troubles.
Everytime you move a Node 1px with the mouse in any direction, the whole container gets repainted.
Creating a minimal reproducable example is not quiet possible, because the code for this application is long and there are a lot of dependencies, that would make it not "minimal".
The ideas I have to increase performance are:

*

*Reducing the amount of Nodes (and so the amount of lines), so that less components need to be repainted. This is quiet hard, most nodes are not in a straight line, means there are not many ways to do this. One option would be to reduce the Nodes and increase the level of detail with the zoom function.

*Clipping the area, that has to be repainted. The problem with this approach is, that I don't know how exactly this clipping function works or whether it is even possible.

*The last idea of mine would be, to somehow create a JLayer object containing (total amount of nodes / 100) layers, that are all visible and only repainting the layer, that contains the specific Node. This seems very unstructured, I don't really think that this is an option, just an idea.
What am I asking for right now?:
How do you manage so much components that have to be repainted? There are definitly ways and I am open to try them all. I just want you to give me some advice, hints on useful built in libraries, that I maybe haven't found in my research. And if one of my ideas could be the one I should go for.
I am not asking for concrete code examples, just for your experience.
Thank you in advance and I'm sorry if my question does not fit the SO conventions.


text:
Q: How to install ubuntu mini.iso? I am trying to install ubuntu mini 18.04 from a booted DVD .
I connected my laptop to the LAN of my college .
I restart my laptop and select 'install ubuntu' to install but it is not connecting/detecting my LAN cabel network .
What's the problem, i am not able to install Ubuntu mini .

A: Install mini system, then you`ll be able to install full desktop. https://help.ubuntu.com/community/Installation/MinimalCD

The minimal iso image will download packages from online archives at
  installation time instead of providing them on the install media
  itself. Downloading packages at install time reduces the size of the
  iso image to approximately ~40MB depending on architecture (see
  below), as well as providing only the packages needed for
  installation.

Mini requires internet connection. I don't remember exactly will mini provide text interface to install desktop or not, anyway you can always do it from command line, like:
sudo apt-get install gnome-desktop.
If you don't have internet connection with mini, its not your option to install, use full dvd.

While the minimal iso image is handy, it isn't useful for installing
  on UEFI-based systems that you want to run in UEFI mode. The mini iso
  lacks the proper files for booting the computer in UEFI mode. Thus,
  the computer will boot in BIOS compatibility mode, and the
  installation will be in BIOS mode.
You can use an Ubuntu Server amd64 iso file (64-bit) for 'mini
  installations' in UEFI mode.

Try server image.


text:
Q: TypeError: 'NoneType' object is not subscriptable discord.py Я сделал экономику в боте и сделал команду inventory(i) но при её вызове у меня появляется ошибка:
Traceback (most recent call last):
  File "C:\Users\fun\VirtualEnvDs\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\fun\PycharmProjects\ds_bot\Cogs\polina_shop.py", line 309, in inventory
    embed.add_field(name=fg[2], value=f"{x[1]}", inline=False)
TypeError: 'NoneType' object is not subscriptable
Command raised an exception: TypeError: 'NoneType' object is not subscriptable

Я нашёл бэкапы кода но это не помогло. Код самой команды inventory:
@commands.command(aliases=["i"])
    @cooldown(1, 2, BucketType.user)
    async def inventory(self, ctx, page: int = 1):
        if page > 5 or page < 1:
            await ctx.send("Page must be between 1 and 5")
            return
        bal = await ecomoney.find_one({"id": ctx.author.id})
        if bal is None:
            await self.open_account(ctx.author.id)
            bal = await ecomoney.find_one({"id": ctx.author.id})

        bag = await ecobag.find_one({"id": ctx.author.id})
        if bag is None:
            await self.open_bag(ctx.author.id)
            bag = await ecobag.find_one({"id": ctx.author.id})

        total = 0
        page_dict = {1: "0-9", 2: "10-20", 3: "20-30", 4: "30-40", 5: "40-50"}
        intial, final = page_dict[page].split('-')
        for x in bag['bag']:
            total += 1
        if total == 0:
            await ctx.send("Your bag is empty")
            return

        page_items = bag['bag'][int(intial):int(final) + 1]

        embed = discord.Embed(
            title=f"{ctx.author.name}'s Inventory",
            description=f"Page {page} | Total Items In Inventory: {total}",
            color=0xFF0000
        )
        for x in page_items:
            fg = items.get(x[0])
            embed.add_field(name=fg[2], value=f"{x[1]}", inline=False)

        embed.set_footer(
            text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}"
        )
        await ctx.send(embed=embed)


text:
Q: Django channels 2, accessing db in tests I recently updated my project to Django 2 and channels 2. Right now I am trying to rewrite my tests for chat app.
I am facing a problem with tests that depend on django db mark from pytest-django. I tried to create objects in fixtures, setup methods, in test function itself, using async_to_sync on WebsocketCommunicator. However, none of those worked.
If I create a user in a fixture and save it correctly gets an id. However, in my consumer Django does not see that User in the database. And treat it like an anonymous user.
I have a temporary token which I use to authenticate a user on websocket.connect.
@pytest.fixture
def room():
    room = generate_room()
    room.save()
    return room

@pytest.fixture
def room_with_user(room, normal_user):
    room.users.add(normal_user)
    yield room
    room.users.remove(normal_user)

@pytest.fixture
def normal_user():
    user = generate_user()
    user.save()
    return user

@pytest.mark.django_db
class TestConnect:

    @pytest.mark.asyncio
    async def test_get_connected_client(self, path, room_with_user, temp_token):
        assert get_path(room_with_user.id) == path

        communicator = QSWebsocketCommunicator(application, path, query_string=get_query_string(temp_token))
        connected, subprotocol = await communicator.connect()
        assert connected
        await communicator.disconnect()

Consumer:
class ChatConsumer(JsonWebsocketConsumer):
    def connect(self):
        # Called on connection. Either call

        self.user = self.scope['user']

        self.room_id = self.scope['url_route']['kwargs']['room_id']
        group = f'room_{self.room_id}'
        users = list(User.objects.all())  # no users here
        self.group_name = group

        if not (self.user is not None and self.user.is_authenticated):
            return self.close({'Error': 'Not authenticated user'})

        try:
            self.room = Room.objects.get(id=self.room_id, users__id=self.user.id)
        except ObjectDoesNotExist:
            return self.close({'Error': 'Room does not exists'})

        # Send success response
        self.accept()

        # Save user as active
        self.room.active_users.add(self.user)

My authentication Middleware
class OAuthTokenAuthMiddleware:
    """
    Custom middleware that takes Authorization header and read OAuth token from it.
    """

    def __init__(self, inner):
        # Store the ASGI application we were passed
        self.inner = inner

    def __call__(self, scope):
        temp_token = self.get_token(scope)
        scope['user'] = self.validate_token(temp_token)
        return self.inner(scope)

    @staticmethod
    def get_token(scope) -> str:
        return url_parse.parse_qs(scope['query_string'])[b'token'][0].decode("utf-8")

    @staticmethod
    def validate_token(token):
        try:
            token = TemporaryToken.objects.select_related('user').get(token=token)
            if token.is_active():
                token.delete()
                return token.user
            else:
                return AnonymousUser()
        except ObjectDoesNotExist:
            return AnonymousUser()

And custom WebsocketCommunicator which accepts query_string in order to include my one time token
class QSWebsocketCommunicator(WebsocketCommunicator):
    def __init__(self, application, path, headers=None, subprotocols=None,
                 query_string: Optional[Union[str, bytes]]=None):
        if isinstance(query_string, str):
            query_string = str.encode(query_string)
        self.scope = {
            "type": "websocket",
            "path": path,
            "headers": headers or [],
            "subprotocols": subprotocols or [],
            "query_string": query_string or ''
        }
        ApplicationCommunicator.__init__(self, application, self.scope)

My question is how can I create User, Room, etc. objects in tests/fixtures so that I can access them in Django consumer.
Or do you have another idea how can I overcome this?

A: It's pretty much impossible to reproduce your issue using the code you've provided. Read about How to create a Minimal, Complete, and Verifiable example. However, I suppose that you should use real transactions in your test as the plain pytest.mark.django_db will skip the transactions and not store any data in the database per se. A working example:
# routing.py

from django import http
from django.conf.urls import url
from django.contrib.auth.models import User
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.generic.websocket import JsonWebsocketConsumer

class ChatConsumer(JsonWebsocketConsumer):
    def connect(self):
        self.user = self.scope['user']
        print('user in scope, set by middleware:', self.user)
        users = list(User.objects.all())  # no users here
        print('all users in chat consumer:', users)

        if not (self.user is not None and self.user.is_authenticated):
            return self.close({'Error': 'Not authenticated user'})

        # Send success response
        self.accept()

class OAuthTokenAuthMiddleware:
    def __init__(self, inner):
        # Store the ASGI application we were passed
        self.inner = inner

    def __call__(self, scope):
        token = self.get_token(scope)
        print('token in middleware:', token)
        scope['user'] = User.objects.get(username=token)
        return self.inner(scope)

    @staticmethod
    def get_token(scope) -> str:
        d = http.QueryDict(scope['query_string'])
        return d['token']

APP = ProtocolTypeRouter({
    'websocket': OAuthTokenAuthMiddleware(URLRouter([url(r'^websocket/$', ChatConsumer)])),
})

Sample fixture that creates a user with username spam:
@pytest.fixture(scope='function', autouse=True)
def create_user():
    with transaction.atomic():
        User.objects.all().delete()
        user = User.objects.create_user(
            'spam', 'spam@example.com', password='eggs',
            first_name='foo', last_name='bar'
        )
    return user

Now, I mark the test as transactional one, meaning that each query is actually committed. Now the test user is stored into database and the queries made in middleware/consumer can actually return something meaningful:
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_get_connected_client():
    app = OAuthTokenAuthMiddleware(URLRouter([url(r'^websocket/$', ChatConsumer)]))
    communicator = QSWebsocketCommunicator(app, '/websocket/', query_string='token=spam')
    connected, subprotocol = await communicator.connect()
    assert connected
    await communicator.disconnect()

Running test test yields the desired result:
$ pytest -vs
================================== test session starts =================================
platform darwin -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python
cachedir: .pytest_cache
Django settings: spam.settings (from environment variable)
rootdir: /Users/hoefling/projects/private/stackoverflow/so-49136564/spam, inifile: pytest.ini
plugins: celery-4.1.0, forked-0.2, django-3.1.2, cov-2.5.1, asyncio-0.8.0, xdist-1.22.0, mock-1.6.3, hypothesis-3.44.4
collected 1 item

tests/test_middleware.py::test_get_connected_client Creating test database for alias 'default'...
token in middleware: spam
user in scope: spam
all users in chat consumer: [<User: spam>]
PASSEDDestroying test database for alias 'default'...

=============================== 1 passed in 0.38 seconds ================================

Btw you don't need to hack around the WebsocketCommunicator anymore since it is now able to deal with query strings, see this issue closed.


text:
Q: Why is my bubble sort code printing out this weird stuff? Ok, so here's my code. I think it should work fine to sort those numbers in the array. However, every time I attempt to run it, all it does is print "[I@178af9c0" or some weird variation on that. I have absolutely no idea what do about this and would appreciate any help that you can give me. Thank you very much!!!
public class BubbleSort {

    public void Print(){

    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] BubbleSort = {3, 4, 1, 2};
            int lengthOfArray = BubbleSort.length;

            for (int i = 0; i < lengthOfArray - 1; i++){
                for (int n = 1; n < lengthOfArray - i; n++){
                    if (BubbleSort[n - 1] > BubbleSort[n]){
                         Swap(i, n , BubbleSort);
                    }
                }
            }
            System.out.println(BubbleSort.toString());
    }

     private static void Swap(int index1, int index2, int[] array) {
         int temp;
         temp = array[index1];
         array[index1] = array[index2];
         array[index2] = temp;
     }
}

A: In Java, arrays are classes.  So that string is the reference to the array, not the contents of the array.  If you want to print the contents, probably the easiest way is to iterate over all the elements.
for(int  i : BubbleSort)  System.out.println(""+i);

(Tested on Java 8, twiddle for your version of Java.)
There are some logic errors in there, but as this looks like a homework question, I'll just mention that you are heading down the right lines, but may need to pencil out what you're actually doing and draw the flow.

A: To get a String representation of an Array, you can use Arrays.toString(yourArray);


text:
Q: mcimagemanager jump to last textarea I setup 2 text input which make use of javascript:mcImageManager.open and 2 textarea which load the tinymce richtext editor. when I click on the first text input on the top and load the imagemanager , without doing anything just click on the close button, the cursor will jump to the last textarea.
attach with a sample http://imknight.webfactional.com/ , click on the first text input image icon , then close it, cursor jump to the last textarea.

A: The answer to your question is "No, i do not have this problem".
You did not ask for a solution to your problem.


text: Q: Samples exes in the test complete is not closed When i run the automation in testcomplete my sample.exe is not closed though i have killed the process for every script and hence the scripts which uses same sample is not run and testcomplete  not responds or in some times it is idle for a long time.May i please know setting in testcomplete which will close the not responding exe and gather information about what went wrong.