text:
Q: Can't play audio in Bluetooth headphones I have a pair of Bluetooth headphones that I would like to use as a playback device. The first time I turned my headphones on and entered "Bluetooth pairing" mode, I was able to see them in the list of available devices and thus connect to them. After the connection was established, the headphones were correctly selected as the default output device.
However, something weird happens when I turn my headphones off and turn them back on. In particular, I am able to connect to them via Bluetooth but I'm unable to select them as the output device - they don't even show up in the Audio settings.
The only way to make them work again is to:

*

*Turn the headphones off

*Delete them from the list of known Bluetooth devices

*Turn them back on and enter Bluetooth pairing mode

*Connect to them

Does anybody have a clue of why this happens and how could I solve the problem?
Here are some useful info about my setup:

*

*OS: KDE Neon 5.22

*KDE Plasma version: 5.22.1

*Headphones model: Panasonic RB-HF420B

EDIT: The problem occurs only when my laptop automatically connects to the headphones via Bluetooth. If I manually connect to the headphones, then they are correctly recognized as an output device.


text:
Q: Core-Data with API consumption I have an application which calls webservice in background thread and at the same time it displays data by fetching data from core-data in main-thread.
I am sure this approach has lots of loop-holes
I am looking for best approach to handle this scenario.

A: Use RestKit framework. It do all you needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to see the raw request sent by httpclient? Recently, I intend to mock a operation on a website using HttpClient.
When I catch the post request via chrome developer tools, The content-type is of multipart/form-data, so I'm trying to construct a MultiPartEntity to realise it. But I've always got 403 Forbidden. At this scenario, I'm sure that my cookie is of login-state, and I've tried doing other operations successfully.
So I'd like to know how to spy the raw request sent by httpclient so that I can compare it with the real one. Thanks a lot!
P.S.
Among all of the multiparts, there is one which shows as below:
------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="media_empty"; filename=""
Content-Type: application/octet-stream

I tried to using FileBody to represent this part. But as you can see, the filename as well as the content is empty. If I pass a new File("") to FileBody, it'll throw an exception indicating that file cannot be found. So right now, I'm just using this code:
multiPartEntity.addPart("media_empty", new FileBody(new File("C:\\Users\\zhudi.zd\\Desktop\\BeCJToRCMAA5SdV.jpg-large"), "application/octet-stream"));

Hope it'll show some clues to solving this problem.
FYI Here's the request information come from Chrome Dev Tools as well as my equivalent code snippet:
--Request Headers--
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en,zh-CN;q=0.8,zh;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:50305
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarySYkKonqDITW7A9Bv
Cookie:XXXXXX
Host:upload.twitter.com
Origin:https://target.com
Referer:https://target.com/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36

--Request Payload--
------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="post_authenticity_token"

199465e69ee
------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="iframe_callback"

window.top.swift_tweetbox_1393907901862
------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="in_reply_to_status_id"

------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="impression_id"

------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="earned"

------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="page_context"

------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="status"

------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="media_data[]"

ABCDEF
------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="media_empty"; filename=""
Content-Type: application/octet-stream

------WebKitFormBoundarySYkKonqDITW7A9Bv
Content-Disposition: form-data; name="place_id"

------WebKitFormBoundarySYkKonqDITW7A9Bv--

Equivalent code snippet of mine:
MultipartEntity entity = new MultipartEntity();
entity.addPart("post_authenticity_token", new StringBody(loginRequest.getAuthenticity_token()));
entity.addPart("iframe-callback", new StringBody("window.top.swift_tweetbox_"+String.valueOf(System.currentTimeMillis())));
entity.addPart("in-reply-to-status-id", new StringBody(""));
entity.addPart("impression-id", new StringBody(""));
entity.addPart("earned", new StringBody(""));
entity.addPart("page-context", new StringBody(""));
entity.addPart("status", new StringBody("some text here"));
entity.addPart("media_data[]", new StringBody("ABCDEF"));
entity.addPart("media_empty", new FileBody(new File("C:\\1.jpg"), "application/octet-stream"));  // trick part, I don't know how to set it as empty file
entity.addPart("place_id", new StringBody(""));

HttpPost post = new HttpPost("https://target.com/post");
post.setHeaders(...);//set all the headers posted above except the Content-Type, for multipartEntity will handle it automatically.
post.setEntity(entity);

response = httpClient.execute(post);

A: I had a miserable time with this on Android. You can use WebScarab to intercept browser/website communications (and you can choose to see the raw bytes as well). Basically, you set up a local proxy in your browser. It's a nice little solution.
Note that if you're using the MultipartEntityBuilder from Apache HTTP Tools, you have to chain the addPart() methods together since they each return a new MulitpartEntityBuilder, as in the following code:
    mpeb = MultipartEntityBuilder.create()
                .addTextBody("action", "upload")
                .addPart("repo_upload_file", fbp.getBody())
                .addTextBody("sesskey", jso.getString("sesskey"))
                .addTextBody("repo_id", "3")
                .addTextBody("itemid", jso.getString("itemid"))
                .addTextBody("author",  jso.getString("author"))
                .addTextBody("savepath", "/")
                .addTextBody("title", current_filename);

A: I've solved this problem by using ByteArrayEntity, which sends the raw data that is intercepted by Chrome Dev Tools. And it has worked fine by now.


text:
Q: Searching for only single words in Unix Is there any way to cat a file that has something like:
field1,field2,field number 3,field4,field5

field1,field2,field3,field4,field5

(Some fields have spaces, some fields do not)
I want to print using awk $1 and $3, but only lines that do not have a space in field 3.
I don't know if there is any way to make awk print something only if it starts with , and ends with ,

A: awk -F, '$3 !~ / / {print $1,$3}' input-file

A: Lines don't have the space in Field 3
awk -F, '{n=split($3,a," ");if(n==1){print $1,$3}}' filename

A: perl -F, -lane '$F[2] =~ /\s/ || print "@F[0,2]"' yourfile

sed -ne 's/^\([^,]*\),[^,]*,\([^ ,]*\)\(,.*\)\{0,\}$/\1 \2/p' yourfile

while IFS=, read -r f1 x f3 x; do case $f3 in *" "* ) : ;; * ) echo "$f1 $f3" ;; esac; done < yourfile


text:
Q: Windows.h error I am getting error :
WINDOWS.H already included.  MFC apps must not #include <windows.h>

Help needed.

A: Remove the second inclusion, from (presumably) your code. Here is a MSDN forum thread about the problem, it seems it can also depend on your exact inclusion order.

A: Using the /showIncludes preprocessor directive, the output window will display all the includes before the error.  There you can find which file erroneously includes windows.h.
Then find out why this file is needed.

A: If you use MFC, do not use #include <windows.h> manually anywhere in your code. MFC includes it in its own way and you already have access do all declarations of this header.

A: Oh well, the error message seems say just everything.
When you've created an MFC app, it already included windows.h.

A: Sometimes, the best way to fix errors is to do as the error message says.
Just a thought.

A: Use #include <afx.h> instead of #include <windows> when working with mfc.


text:
Q: How can I know the date of birth given the age (in decimals) and the date (of that age) in SAS? Create a new variable called "dob" which reflects a person's date of birth. the value of age represents exactly how old an individual is (in years) on the date given (i.e. Janet White is 44.2 years old on May 11th, 2018)
This is my dataset:
DATA mydata1;
input name $15. age date MMDDYY8.;
format date MMDDYY8.;
datalines;
Janet White     44.2 5/11/18
Bob Greene      32.1 6/14/18
Lou St. Pierren 29.9 4/28/18
;
run;

A: Tom's right in that the DOB can only be estimated here, and Craig's right in that the intnx function is the way to go (and also that we shouldn't do your homework..) but your answer should look something like:
data mydata2;
set mydata1;
format  DOB date9.;
        DOB = intnx('years',date,-age,'same');
run;


text:
Q: File Path Issue Using NodeJS In the client code below I attempt to display an image (space.jpg) which is located in the same directory as index.js and index.html.  The image is showing a broken link when I access the server and am served index.html.  Is there something about Node's native file structure when serving static HTML which I am not taking into account here?
I am testing in a local environment on OS X (10.10.5).
I have the following server code (index.js):
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');

  socket.on('chat message', function(msg){
      console.log('message: ' + msg);
      io.emit('chat message', msg);
  });

  socket.on('disconnect', function(){
  console.log('user disconnected');
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

And the following client code (index.html):
<!doctype html>

    <title>Infinium</title>

      <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

A: You have served index.html file but you haven't set up any static file serving functionality in your node.js code.
There is few npm packages for this like node-static and express-static. You can use this as middleware if you like.
Install any of these in your project as:
$npm install express-static --save
Then you can edit your index.js to use express-static as middleware. This will serve all the files under /public in your project root. So, you can put all your assets i.e. images, css, client-side js inside /public directory.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var static  = require('express-static');
app.use(static(__dirname + '/public'));

In production, it is recommended to use a front facing http server or reverse proxy like nginx or apache to serve static files since node.js is not good with big resource files.

A: That's because when the browser tries to request space.jpg, the server won't respond with anything, since you only created a listener for / in which you serve your index.html.
In order to send your image you will have to add this to your code:
app.get('/space.jpg', function(req, res) {
    res.sendfile('./space.jpg');
});

Alternatively, you could use express.static and set it up for a certain path that contains static content (e.g. images). This will then serve the according file.


text:
Q: Retrieving Super property of a object property in OWL Api 4 I have a object property Car and its sub property as Ferrari. I want to get super property i.e Car for Ferrari with owl api 4. I can get sub-properties of a property but not super property. Is there any api that i am missing ?

A: If the sub property relationship is directly asserted, you can use the OWLOntology::getObjectSubPropertyAxiomsForSubProperty method.
Example:
OWLOntology o = ...
OWLObjectProperty p = ...
o.getObjectSubPropertyAxiomsForSubProperty(p);

A: I am able to do this in following way :-
Set<OWLObjectProperty> props = ont.getObjectPropertiesInSignature();
            for (OWLObjectProperty p : props) {
                HashSet<OWLSubObjectPropertyOfAxiom> subPropertySet =   (HashSet)ont.getObjectSubPropertyAxiomsForSuperProperty(p);
                for (OWLSubObjectPropertyOfAxiom subPropAxiom : subPropertySet) {
                    OWLObjectPropertyExpression subObjectProperty = subPropAxiom.getSubProperty();
                    if (subObjectProperty.getNamedProperty().getIRI().equals(relationIRI)) {
                        d.setDerivedFrom(p.getIRI().getShortForm());

                    }
                }
            }

If there is better way to do this please let me know.

A: Iterator<OWLSubObjectPropertyOfAxiom> subItr = ont.getObjectSubPropertyAxiomsForSubProperty(factory.getOWLObjectProperty(relationIRI)).iterator();
            while (subItr.hasNext()) {
                OWLSubObjectPropertyOfAxiom subPropAxiom = subItr.next();
                d.setDerivedFrom(subPropAxiom.getSuperProperty().getNamedProperty().getIRI().getShortForm());
            }

Just adding to simon's answer...this works fine for me....


text:
Q: JqxCalendar Weekend Issue I am using jqx calendar plugin.
I want to disable the weekend dates in it.
But I am unable to find any function for it in the jqx plugin files.
Any help.???
Thanks in advance.

A: There is no easy way or a function to disable the weekends using jquery in jqx calendar. But you can always disable weekends dates using CSS.
Here is the code snippet to disable weekends.
    .jqx-calendar-cell-weekend {
    -moz-user-select: none !important;
    background: rgba(0, 0, 0, 0) none repeat scroll 0 0 !important;
    border: medium none !important;
    color: #898989 !important;
    cursor: default !important;
    opacity: 0.55 !important;
    pointer-events: none !important;
}


text:
Q: How to elegantly solve this rounding issue? I have this function that has 20 attempts to "guess" a number in the range 1-100:
int guess(int number) {
    int start = 1;
    int end = 100;
    int count = 20;
    int answer = 0;

    while (count--) {
        int half = start + round((double)(end - start) / 2);
        if (number < half) end = half;
        else if (number > half) start = half;
        else {
            answer = half;
            break;
        }
    }

    if (answer > 0) return 20 - count;
    else return 0;
}

The problem is that as it is right now rounding the result of the range halving, it cannot guess the number 1, and if I don't round, it cannot guess the other extreme of the range - 100.
The source of the issue is obvious as is the crude hack solution, but I don't seem to find an elegant way of solving it.

A: You know, that is easily corrected:
Do not keep the mid-point in the range of possibilities after checking it, it is not possible!
Why do you have those troubles? Because you are working with closed ranges instead of half-open ranges, as would be sensible.
As an aside, use integer arithmetic, like this:
    int half = (start + end) / 2;

(Integer-division rounds towards 0)

A: Use some kind of ceiling and floor depending of the side where the value reside.
So if your looking a value in the top side, then use floor (5.9 -> 5) and if you're looking for a value below the half, then use ceiling ( 90.2 = 91).
This should make your process include 1 and 100

A: This works, but it may take one more loop in some cases. Initializing end to 101 eliminates the issue with integer division rounding down (start could also be set to 0, but it's not needed). The code could also just check for 1 or 100 before doing the loop, but I'm not sure if that would count as two more loops.
int j;
int start;
int end;
int half;
    for(j = 1; j < 101; j++){
        start = 1;
        end = 101;
        while(1){
            half = (start + end)/2;
            if(half == j)
                break;
            if(half < j)
                start = half;
            else
                end = half;
        }
        printf("%3d\n", half);
    }


text:
Q: jQuery unexpected token due to margin-left I am editing the css values of some elements via jQuery, when I attempted to change the margin-left value of an element, resulting in an "Unexpected token" error due to the "-" in margin-left. Is there a means of changing the margins via jquery without resulting in this error?
Here's an excerpt from my code:
JS:
$(".settingslist").click(function() {
    $(".containcontacts,.containtodolist").css({
        display: "none"
    });
    $(".gChange, .aChange, .yChange, .fChange,.speedChange, .bgChange, .simple, .gClick, .aClick, .yClick, .fClick,.speedSave, #Btn, .gSave, .aSave, .ySave, .fSave ,.bgChange, .fSave,.speedClick,.speedtext,#ImageUrl,.settingstxt,.containweather,#ddbtn").css({
        display: "block"
    });
    $(".gChange, .aChange, .yChange, .fChange,.speedChange, .bgChange, .simple").css({
        margin-left:"60px"
    });
});

For reference, the full program can be found here (I didn't create a snippet, because it is not an isolated part of the code):
https://codepen.io/Refath/pen/rdZwxE

A: Basically, add double quotation marks on margin-left or use marginLeft instead.
Here is jQuery API's explanation:

...jQuery can equally interpret the CSS and DOM formatting of
  multiple-word properties. For example, jQuery understands and returns
  the correct value for both .css({ "background-color": "#ffe",
  "border-left": "5px solid #ccc" })and .css({backgroundColor:
  "#ffe", borderLeft: "5px solid #ccc" }). Notice that with the DOM
  notation, quotation marks around the property names are optional, but
  with CSS notation they're required due to the hyphen in the name.


text:
Q: How to perform a redirect in Enlight_Event_EventArgs object subscriber in Shopware 5? I have a subscriber to the event
'Shopware_Modules_Admin_SaveRegister_Successful'

and after certain actions, I want to perform a redirect in the end, but the $args object does not have a subject which means that I cannot call the $controller = $args->getSubject(); on it and perform a redirect.
Is there another way to perform a redirect inside of the callback function of this event? 'Shopware_Modules_Admin_SaveRegister_Successful' => 'onRegisterSuccessful'
public function onRegisterSuccessful($args){
         $controller = $args->getSubject();
         $controller->redirect(
                array(
                    'controller' => 'profile',
                    'action' => 'verify',
                    'name' => $name
                )
            );
}

A: Try like this. Note that you need to exit() after the redirect, because after the event is fired, Shopware makes its own redirect to the customer dashboard.
public static function getSubscribedEvents()
{
    return [
        'Shopware_Modules_Admin_SaveRegister_Successful' => 'onregister'
    ];
}

public function onRegister(\Enlight_Event_EventArgs $args)
{
    $url = Shopware()->Front()->Router()->assemble([
            'controller' => 'profile',
            'action' => 'verify'
    ]);

    header('Location: ' . $url, true);
    exit();
}

A: Your option would be to go a bit higher and register an controller's postDispatch event. There you can redirect.


text:
Q: Criar uma Lista HTML com JavaScript Olá, sou iniciante em programação e estou aprendendo a integrar JS nos meus códigos HTML... me propus a fazer um "programa" que receba o nome de  produtos e suas classes (já pré definidia em uma caixa de option) e retorne esses produtos listados pelas suas classes. Ja consigo fazer o JS receber as informações e imprimir no console, mas nao sei como posso ediar as
 do meu html segue o código:
codigo HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel=stylesheet href="css/reset.css">
        <link rel=stylesheet href="css/style.css">

        <title>Lista de Compras</title>

LISTA DE COMPRAS

                <form id="formulario">
                    Produto:
                    <input type="text" id="produto" class="caixa" name="produto" required placeholder="Insira o alimento desejado.">

                    <fieldset class="categoria">
                        <legend id="legenda">Qual é a categoria desse produto?</legend>
                        <select id="selecao" name="categoria">
                            <option class="item" id="itemFruta">Fruta</option>
                            <option class="item" id="itemLaticinio">Laticinio</option>
                            <option class="item" id="itemCongelado">Congelado</option>
                            <option class="item" id="itemDoce">Doce</option>
                        </select>
                    </fieldset>
                    <input type="submit" value="Listar produto" id="enviar">
                </form>

Sua lista de compras está separada em:

Fruta:

Laticinio:

Congelado:

Doce:

codigo js:

btnSalvar.addEventListener("click", function(event){
    event.preventDefault();

    const formulario = document.querySelector("#formulario");
    console.log(formulario.produto.value);
    console.log(formulario.categoria.value);
})

A: Primeiro seria bom você editar os id dos elementos p pois está com um ponto na frente, e ponto na frente é atalho para o CSS entender que trata-se de uma class. Pode deixar assim:
. Mas, se isso realmente é para aplicar os estilos CSS de uma classe chamada fruta, então é só trocar de id= para class=, porém também nesse caso tire os pontos da frente (por exemplo: class="fruta").
Feito isso, no seu script você pode ir concatenando os valores de várias formas, mas vou sugerir localizando o p correspondente da categoria e depois ir concatenando pelo innerHTML. O script ficaria assim:
const btnSalvar = document.querySelector("#enviar");

btnSalvar.addEventListener("click", function(event){
    event.preventDefault();

    const formulario = document.querySelector("#formulario");
    const produto = formulario.produto.value; // pega o value do produto
    const categoria = formulario.categoria.value.toLowerCase(); // toLowerCase para ficar tudo minúsculo
    const p = document.querySelector("#" + categoria); // pega o 'p' correspondente pelo id da categoria em questão

    // Agora é a parte que vai concatenar os valores.
    // Aqui está de uma forma que, caso o p esteja vazio, apenas concatena o produto. Caso não esteja vazio, coloca
    // uma vírgula antes de concatenar.
    if (p.innerHTML == "") {
        p.innerHTML += produto;
    }
    else {
        p.innerHTML += ", " + produto;
    }
});

Para o exemplo acima eu também removi aquele espaço entre os p (para dar certo na hora do if ver se o p está ou não vazio), troquei disso:

para isso:


text:
Q: Turn ISO 8601 date/time into "x minutes ago" type of string So I have an ISO 8601 date/time stamp like "2011-04-21T17:07:50-07:00", and I would like to convert it to say something like "23 minutes ago" or something of that sort. Is there a small bit of Java code or a library that would be able to do something like that easily?
Thanks!

A: What you are looking for is known as fuzzy time.  A quick Google on this term found jFuzzyDate

A: First, parse it into a Date object.  Then, make a new Date which will have the current date/time.  Then, call the .getTime() methods on both of the Date objects, and subtract.  Now you have your time in milliseconds.
You can do your own math from there, because until you start worrying about leap years it's all easy division.

A: Joda is a great time library and should have all the methods you need to do this: http://joda-time.sourceforge.net/.


text:
Q: How to Make columns in row Hi i want to know that how can we create column in a row with html and css.
Like this in the picture.1

A: You can try using one row like container, inside create 4 div's and add display flex and justify-content.

A: You could use Flex Box to have a single row of items and use the boxes to space appropriately, this will also provide scaling for different screen sizes.
Here is a link to a great explaination of what Flex Box can do: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
If that's not what you're looking for, there's always making a table.


text:
Q: Use VBA to make Excel refresh data from source My Excel sheet contains a table which fetches data from an outside source. I know I can refresh this data by right clicking the table and clicking "Refresh", but I want to be able to do this from inside my VBA code, so that I can force the data to be updated before performing certain calculations on it.
I have tried using Worksheets("Foo").Calculate as suggested by answers to similar questions, but that doesn't do the trick.

A: Should be able to use QueryTable("tableName").Refresh.  Here is the link to the Microsoft Developer Network page on Query Table.  Check out the refresh method from there.


text:
Q: Estimating laplace-beltrami spectra for a graph surface in $R^3$ Consider a surface $\Gamma$ in $R^3$.  The surface $\Gamma$ is a graph, i.e. $\Gamma = (x,y, h(x,y))$, for $x \in R^2$ and some smooth function $h$, where $h$ and all its derivatives are periodic on [0,1]^2.
I'm trying to estimate the eigenfunctions and eigenvalues of the Laplace-Beltrami operator for this surface.  Of course, the laplace beltrami operator can be very easily be expressed in local coordinates on $[0,1]^2$, and so the problem is effectively approximating the spectra of this second order elliptic operator on $L^2[0,1]^2$ with periodic boundary conditions.  This is what I am doing, however I still cannot obtain any useful estimates.
Is anyone aware of any references, or has had any experience with this problem?

A: Some suggestions:

*

*To show there is a spectral gap, one can use the following approach: The variational characterization of the first eigenvalue
$$
 E_1 = \inf_{\|\psi\| = 1} \langle \psi, H \psi \rangle
$$
can be used to obtain an upper bound on the first eigenvalue. Then Temple's inequality (I think it's in Reed-Simon IV) can be used to obtain a lower bound on the second eigenvalue. Note in order to show the existence of a spectral gap, one needs to study all the operators $H(k)$ of the Floquet-Bloch decomposition.

*But I would guess that at least as long as $h$ is "sufficiently small", there is no spectral gap (without having done any of the computations). Denote by $E_1(k)$ and $E_2(k)$ the first and second eigenvalue of $H_0(k)$. Here $H_0$ denotes the usual Laplacian and the Floquet--Bloch decomposition is done with respect to $[0,1]^2$. I believe that one has that
$$
  \sup_{k} E_1(k) > \inf_{k} E_2(k).
 $$
Then using that your operator will be a small perturbation of the Laplacian (in an appropriate sense), one should obtain that there is no spectral gap.
2b. (added in edit) It is clear that for fixed $k$, one has $E_1(k) < E_2(k)$. This follows from the first eigenfunction being positive.

*There is what is called "Bohr-Sommerfeld conjecture", which is related to higher eigenvalues.


text:
Q: Get Eclipse to recognize the maps api Hi I'm developing an Android app and trying to incorporate maps into one of my sub-activities.  Having followed all of the instructions from Android, my java file will not recognize the "MapActivity" or the import statements to include the needed api.  Here is my XML manifest and my class file.
<?xml version="1.0" encoding="utf-8"?>

  <uses-permission android:name="android.permissions.INTERNET"/>
  <uses-permission android:name="android.permissions.ACCESS_FINE_LOCATION"/>

<application android:icon="@drawable/icon" android:label="@string/app_name">

 <uses-library android:name="com.google.android.maps" />

    <activity android:name=".CadetCommand"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="RedLight"></activity>
    <activity android:name="PTCalculator"></activity>

</application>
<uses-sdk android:minSdkVersion="7"/>

here is my java file:
    package edu.elon.cs.mobile;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.os.Bundle;

public class LandNav extends MapActivity{

}

Any suggestion would help.

A: You have to use the "Google APIs by Google Inc." as SDK in eclipse, not the "SDK Platform Android".
If you don't have it available, it can be downloaded with the Android SDK and AVD manager (android-sdk/tools/android)

A: Haven't used it myself, but if you have an external jar you probably just need to right-click on it and choose "Add to build path" from within eclipse.


text:
Q: Getting true video Height/Width from ASF videos I am trying to convert an ASF video with FFmpeg using an interface called mediahandler.
The issue is, the metadata on the ASF video appears to be corrupt. It states that the video is 640x240, and 4:3 aspect ratio.
The aspect ratio is correct, but obviously the resolution is not. This causes the converter to incorrectly scale the video, because it uses the resolution to determine the original aspect ratio.
I am able to get the aspect ratio metadata, but I'm not sure this solves the issue, because I would think that if the resolution could be incorrect, then so could the aspect ratio metadata.
So, is there any way to get the actual height/width? It appears that players like VLC have no issue with this. How do I do such a thing w/ FFmpeg?


text:
Q: Does light from a super continuum laser remain coherent? Is the broad spectrum light from a super continuum (white) laser system when filtered for a particular wave length still temporally coherent to a similar degree as the source laser?
i.e. Does the part of the resultant beam of a specific wavelength still have the same temporal characteristics of a laser or is it more like an incoherent source such as monochromatic light filtered from the sun.

A: Temporal coherence$^{\text{1}}$ in supercontinuum generation (SCG) is a very active area of research in ultrafast optics at the moment. This is in part because there are a lot of exciting applications which rely on broadband coherent light, but also because there are so many nonlinear processes involved in supercontinuum generation that a full understanding of how they each interact to influence the coherence will take time. This means your question is a very exciting one, but also that it is extremely broad and difficult to answer.
This answer is largely based on information which can be found in Agrawal, this review article on SCG using anomalous dispersion pumping, and this article on SCG pumping in the normal dispersion regime, and includes simulations covering just four relatively broad example cases: Two where the coherence of the supercontinuum pump source is conserved, and two where it is destroyed. As there are plenty of other sources which go into detail about the underlying physics of each nonlinear process involved, I've left this information out except where it's necessary$^{\text{2}}$. Unfortunately this means assuming a degree of familiarity with SCG, but I will link some references at least. There are also a few extra modes of coherence degradation which I have not described, but are also detailed here.
Firstly, in the SCG community coherence is generally defined in the spectral domain as follows:
$\left|g_{1,2}^{(1)}(\lambda, t_{1}-t_{2})\right| = \left|\frac{\langle A_{1}^{*}(\lambda, t_{1})A_{2}(\lambda, t_{2}) \rangle}{\sqrt{\langle |A_{1}(\lambda, t_{1})|^{2} \rangle\langle |A_{2}(\lambda, t_{2})|^{2} \rangle} } \right|$
$\langle \rangle$ denote an ensemble average over independently generated pairs of spectra $A(\lambda)$, emitted by the supercontinuum source at different times $t_{1}$ and $t_{2}$. As SCG is most often carried out using pretty stable modelocked lasers, I will assume that these pairs of spectra are nearly identical at the input of the optical fibre except for a noise contribution. $|g_{1,2}^{(1)}|$ is a measure of amplitude and$^{\text{3}}$ phase stability as a function of wavelength, defined over the interval [0; 1] (with 1 indicating perfect coherence and 0 complete decoherence), and quantifies the sensitivity of the spectral broadening to the noise on the input signal.
PCF is widely used for supercontinuum generation because the fibre structure can be adjusted to customize the dispersion curve, and because the mode confinement can be very small allowing for extremely high optical intensities which provide a lot of nonlinearity. I will also assume single-mode silica PCF here. Propagation in these fibres is usually modelled using the generalized nonlinear Schrödinger equation. In short, this is a partial differential equation including two terms, one for loss and dispersion (linear term), and the other for the intensity-dependent material response (nonlinear term). Both terms contribute to whether the coherence is preserved or destroyed. Although the mechanism responsible for this can be loosely interpreted as a competition between the following nonlinear processes (not exhaustive):

*

*Self-phase modulation

*Soliton fission

*The Raman effect

*Modulation instability

it is arguably better to categorize it by the dispersion regime, i.e., whether the input optical signal is launched in the anomalous side of the PCF dispersion slope, or the normal side. Anomalous dispersion is characterised by short wavelengths having a higher group velocity than longer wavelengths, and normal dispersion is characterised by long wavelengths having a higher group velocity than shorter wavelengths.
Some useful quantities which I will refer to:

*

*$L_{NL} = \frac{2n_{2}}{P_{0}\lambda(\text{MFD}/2)^{2}}$ is the nonlinear length, and is the propagation distance over which the accumulated nonlinear phase reaches $2\pi$. $n_{2}=2.7\times 10^{-20}$ m$^{2}$/W is the nonlinear refractive index for silica, MFD is the mode field diameter, $P_{0}$ is the peak power of the pulse which has a wavelength $\lambda$.

*$L_{D} = \frac{T_{0}^{2}}{|\beta_{2}|}$ is the dispersion length, and is the propagation distance over which the accumulated dispersive phase reaches $2\pi$. $T_{0}$ is the FWHM duration of the pulse, and $\beta_{2}=\frac{-\lambda^{2}D(\lambda)}{2\pi c}$ is the group velocity dispersion in units of fs$^{2}$/m ($D(\lambda)$ is equivalent and has units of ps/(nmkm)).

Dispersion regimes and (very brief) summary of the dynamics.
Here's a couple of typical PCF dispersion curves designed for pumping around 1 $\mu$m (e.g., using an Yb-doped fibre laser):

The one on the left has both normal and anomalous dispersion regions, with a zero-dispersion wavelength at 1 $\mu$m inbetween. For this dispersion curve, supercontinuum is usually generated by pumping on the anomalous dispersion side, close to the zero-dispersion wavelength. Both coherent and incoherent spectral broadening are then driven by soliton propagation and dispersive wave generation in the fibre (ref). Whether the output spectral coherence is high or low depends on how the initial pulse divides into fundamental solitons, and this will be described in the first section below. In reference to the competition between nonlinear processes outlined above, the input pulse bandwidth and duration determine whether it divides by soliton fission (coherent), or due to modulation instability (MI, incoherent).
The dispersion curve on the right has only normal dispersion, and fibres with this kind of dispersion profile are referred to as all-normal dispersion (ANDi) fibre. Supercontinuum is usually generated by pumping at the dispersion minimum to maximize the peak intensity over the length of the fibre. In reference to the competition between nonlinear processes, coherence is either preserved or destroyed depending on whether optical wave breaking occurs (coherent), or whether there is significant Raman gain over the fibre length (incoherent). This process is described in the second section below.
Example 1: Incoherent and coherent broadening when pumping in the anomalous dispersion regime.
The image below shows incoherent supercontinuum generation over a 6 cm fibre length with a dispersion curve similar to that shown in the left-hand dispersion figure above. The input pulse was transform limited with a duration of 1 ps, central wavelength of 1040 nm, and energy of 30 nJ. The top figure shows the spectral development as a function of fibre length (spectral power density units of dBm/nm), and the bottom figure shows the coherence as a function of fibre length for the same simulation.

Initially the pulse undergoes SPM, which broadens the spectrum coherently with a linear dependence on fibre length. Modulation instability (MI) quickly follows, characterized by two symmetric sidebands appearing either side of the SPM-broadened pump. MI is an amplification process, and goes like $\text{exp}(g_{\text{MI}}z)$ causing rapid amplification of the sidebands after ~1 cm. After around 2.5 cm, four-wave mixing causes the MI process to cascade leading to very rapid bandwidth expansion.
MI arises because high peak power pulse propagation in the anomalous dispersion regime is unstable under the right conditions, and a perturbation analysis of the nonlinear Schrödinger equation shows that the SCG output is highly sensitive to intensity modulations (e.g., from input noise), which is amplified according to the following gain curve:
$g=2\sqrt{-\beta_{2}^{2}\omega_{m}-2\gamma P\beta_{2}\omega_{m}^{2}}$ for $\omega_{m}<\frac{-2\gamma P}{\beta_{2}}$
$g=0$ for $\omega_{m}\ge \frac{-2\gamma P}{\beta_{2}}$
where $\omega_m$ is the difference between the modulation angular frequency and the pulse central angular frequency, $P$ is the peak power, and $\gamma=(2\pi n_{2})/(\lambda (\text{MFD}/2)^{2})$. This gain curve shapes the MI sidebands shown in the figure.
This amplification of out-of-band noise results in interference with the residual input signal to create noisy, ultrafast and high peak power modulations in the time domain. The cascaded MI increases the time-domain interference and noise, resulting in modulations which can evolve into fundamental solitons. These then shed energy to high-frequency dispersive waves as they propagate and also undergo soliton self-frequency shifting to longer wavelengths, giving extended spectral broadening beyond that from MI. This latter process isn't shown in the figure, but would occur if the fibre length was extended. As this process is seeded by noise, the supercontinuum output will be incoherent. The coherence figure shows this, as the MI sidebands have zero coherence. The coherence of the residual pump also degrades rapidly as MI randomly strips energy from the signal.
The figure below shows the output time and wavelength domain ensemble distributions. The bold line is the ensemble average, and the shaded areas show the individual simulations in the ensemble. Although each pulse had the same time and spectral domain shapes, the different input noise has had a drastic influence on the propagation dynamics, with no two output pulses being alike. This is the consequence of low coherence, and filtering this spectrum at any particular wavelength would not give a stable time domain output.

MI can be suppressed to give highly coherent spectral broadening by using shorter pump pulses, which have a correspondingly broader bandwidth. This suppression occurs partly because the broad, coherent input bandwidth seeds the MI gain spectrum, reducing the influence of noise, and also because the broader bandwidth is more susceptible to higher-order dispersion and inter-pulse Raman scattering, which perturb the input pulse and cause it to fission into fundamental solitons more quickly than MI can amplify noise. This happens over a length scale given by:
$L_{\text{fission}}=\sqrt{L_{D}L_{NL}}$
As these two perturbations are insensitive to noise, the resulting SCG is coherent. If $L_{\text{fission}}$ is smaller than the length required for significant MI buildup, the output spectral coherence will be high.

This is precisely what is happening in the figure above, where the input pulse was 80 fs long, had a 1040 nm central wavelength, and energy of 1 nJ. The broad input bandwidth of the short pulse undergoes a small amount of SPM before soliton fission occurs, causing explosive spectral broadening just millimetres along the fibre length. The pulse gradually fissions into its constituent fundamental soliton parts, shedding excess energy as a high-frequency dispersive wave on the other side of the zero dispersion wavelength as it does so. Inter-pulse Raman scattering causes these solitons to gradually shift to lower frequencies which gradually broadens the spectrum with propagation distance. This process is called soliton self-frequency shifting (SSFS in the figure). The lower figure shows that these processes preserve coherence, which is very high over the whole supercontinuum bandwidth. Filtering this spectrum over a smaller wavelength band will give a stable output in the time domain.

The time and wavelength domain supercontinuum shapes are shown in the figure above. Unlike the case where MI was dominant, the individuals in the ensemble are indistinguishable indicating that the broadening process was insensitive to input noise.
Example 2: Incoherent and coherent broadening when pumping in ANDi fibre.
As with anomalous dispersion pumping, longer pulses more readily lead to incoherent spectral broadening in the ANDi regime. The figure below shows how a 7 ps input pulse with 60 nJ energy and central wavelength of 1040 nm propagates in the ANDi fibre shown in the right-hand dispersion figure. Again, SPM acts first to coherently broaden the input spectrum linearly with propagation distance. However, as ANDi fibres generally support dissipative high-intensity solutions, MI doesn't play a role in the spectral broadening in this dispersion regime and the Raman effect becomes significant instead. This is evident in the spectral figure, where a broad Stokes peak develops at the low-frequency side of the input pulse spectrum. As was the case with MI, the Raman effect in the ANDi regime generally leads to the amplification of out-of-band noise, with a gain bandwidth set by the material Raman response (gain peak at 13.2 THz detuning below the peak frequency of the input spectrum for silica). The Stokes wave is quickly followed by an anti-Stokes wave at the high-frequency side of the input spectrum. After approximately 60 cm of propagation, four-wave mixing causes the Raman effect to cascade, forming higher-order (anti-)Stokes peaks.

As the (anti-)Stokes peaks are seeded by noise, they have zero coherence. They are amplified during propagation and use the input pulse as a pump source, so the input pulse is randomly depleted over the fibre length causing its coherence to degrade as well. This is evident in the coherence figure at approximately 90 cm, where the coherence is beginning to degrade at the low-frequency side of the SPM-broadened input spectrum.

Looking at the time and wavelength domain output also shows how sensitive the propagation dynamics are to the input noise. The output stability degrades at the leading edge of the pulse in the time domain because the dominant red-shifted Stokes peaks in the output spectrum are brought to the front of the pulse by the normal dispersion. The Stokes and anti-Stokes portions of the spectrum show large-scale instability as well at the long and short wavelength sides of the spectrum. Filtering a smaller wavelength band would not produce a stable output.
It is possible to define a length over which Raman gain becomes significant, and this requires a gain coefficient with a dependence on the ratio of chromatic dispersion to nonlinearity, and describes the coupling between Raman and four wave mixing:
$g=2\gamma \text{Re}\left[ \sqrt{K(2q-K)} \right]$
where $K = -(\beta_{2}\Omega_{R}^{2})/(2\gamma P)$ is the linear phase mismatch between the pump and (anti-)Stokes wave with respect to the nonlinear contribution to the mismatch. $q$ is the (anti-)Stokes order, $\Omega_{R}$ is the frequency detuning which maximizes the Raman gain (13.2 THz for silica). For low phase mismatches ($|K|<1$), Raman is suppressed. As $|K|$ approaches infinity, Raman can contribute more. This is interesting in its own right, because it shows that the four wave mixing which cascades the Raman effect in the example above can also be very effective in suppressing it entirely if the peak power is very high. Using this, the Raman length is given by:
$L_{R}=1/(gP)$.
By pumping with shorter pulses, coherence degradation in the ANDi regime can largely be prevented. As the pulse duration is decreased, dispersion and SPM have a greater influence and can lead to optical wave breaking (OWB), shown in the figure below.

The output spectrum is extremely flat, and has very high coherence over the entire bandwidth. Filtering the spectrum for a small wavelength band will produce a stable time domain output. Looking at each simulation in the ensemble shows not only that the broadening is completely insensitive to input noise, but also that the process preserves the pulse time domain distribution, which is single-peaked.

Wave breaking occurs over a length scale approximated by:
$L_{\text{WB}}\approx 1.1T\sqrt{\frac{1}{\gamma P\beta_{2}}}=1.1\sqrt{L_{D}L_{NL}}$
If the pulse duration at the input is gradually increased, there will be a point where wave breaking requires a longer length of fibre than is required for significant Raman gain. As the competition between these two processes is central to the coherence conservation in this example, it is important to find which combination of input pulse duration and fibre length will give incoherent/coherent output. A coherence length will do this, and is given by taking the ratio of $L_{R}$ to $L_{WB}$:
$L_{c}\propto \frac{L_{R}}{L_{WB}}\propto \frac{1}{f_{R}\Omega_{R}T}$, where $f_{R}=0.18$ for fused silica.
So, if the pulse duration is reduced such that $L_{WB}$ is less than $L_{R}$, the output spectral coherence will be high. Note also that the parameter $K$ depends inversely on the peak power. High peak powers are commonly associated with short pulse durations, so when the input pulse duration is short Raman will be suppressed at the start of the propagation before dispersion becomes significant. This restriction doesn't apply to wave breaking, so this becomes the favourable route for spectral broadening in ANDi fiber at high peak powers and short pulse durations. This holds for peak powers in excess of 100 kW, and even if the peak power is only reduced by a factor of ~2 by dispersion after wave breaking takes place the peak power can still be high enough to suppress Raman very efficiently, giving excellent output spectral coherence.

1 Shortened to "coherence" from now on.
2 An explanation of supercontinuum generation is out of the scope of the question, which is about coherence.
3 I have seen a few instances of spectral amplitude being plugged into this equation with no phase information, and this is inappropriate.


text:
Q: XSLT replace dot I have to remove dot (.) from data, using translate, I am using XSLT 1.0 and can also use 2.0, I tried using translate and replace in xslt but it only work in other cased like removing space or some char or number, but when I use dot, there is no change.
XML:
<Message xmlns:ns1="http://www.Thermofisher.com/Integration/hci/EmployeeBacklog/PayloadToHANA/schema">
  <FSE_BKLOGType xmlns:ns1="http://www.w3.org/2005/Atom" xmlns:ns2="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:ns3="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:multimap="http://sap.com/xi/XI/SplitAndMerge">
    <Method xmlns:ns1="http://www.Thermofisher.com/Integration/hci/EmployeeBacklog/PayloadToHANA/schema">PUT</Method>
    <FSE_ID>203749</FSE_ID>
    <TICKET_TYPE>T</TICKET_TYPE>
    <T_COUNT>1.032</T_COUNT>
  </FSE_BKLOGType>
  <FSE_BKLOGType xmlns:ns1="http://www.w3.org/2005/Atom" xmlns:ns2="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:ns3="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:multimap="http://sap.com/xi/XI/SplitAndMerge">
    <Method xmlns:ns1="http://www.Thermofisher.com/Integration/hci/EmployeeBacklog/PayloadToHANA/schema">PUT</Method>
    <FSE_ID>203950</FSE_ID>
    <TICKET_TYPE>T</TICKET_TYPE>
    <T_COUNT>56</T_COUNT>
  </FSE_BKLOGType>
</Message>

XSLT:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <batchParts>
      <xsl:for-each select="/Message/FSE_BKLOGType">
        <batchChangeSet>
          <batchChangeSetPart>
            <method>
              <xsl:value-of select="Method"/>
            </method>
            <FSE_BKLOG>
              <FSE_BKLOGType>
                <FSE_ID>
                  <xsl:value-of select="FSE_ID"/>
                </FSE_ID>
                <TICKET_TYPE>
                  <xsl:value-of select="TICKET_TYPE"/>
                </TICKET_TYPE>
                <xsl:choose>
                <xsl:when test="contains(T_COUNT,' ')">
                <T_COUNT>
                  <xsl:value-of select="translate(T_COUNT,'.','')"/>
                </T_COUNT>
                </xsl:when>
                <xsl:otherwise>
                    <T_COUNT>
                    <xsl:value-of select="T_COUNT"/>
                    </T_COUNT>
                </xsl:otherwise>
                </xsl:choose>
              </FSE_BKLOGType>
            </FSE_BKLOG>
          </batchChangeSetPart>
        </batchChangeSet>
      </xsl:for-each>
    </batchParts>
  </xsl:template>
</xsl:stylesheet>

this is not removing the dot in <T_COUNT>1.032</T_COUNT>, I want to get like <T_COUNT>1032</T_COUNT>
Thanks
Yatan

A: That test <xsl:when test="contains(T_COUNT,' ')"> seems not to find any item in your input (<T_COUNT>1.032</T_COUNT> doesn't contain a space ' '), it is not clear what you need it for, the minimal code to simply remove any dot inside of T_COUNT would be
<xsl:template match="T_COUNT">
  <xsl:copy>
    <xsl:value-of select="translate(., '.', '')"/>
  </xsl:copy>
</xsl:template>


text:
Q: What Are The Best Practices For Business Folder Structure? We've tended in the past towards having departmental folders (Sales, Marketing, etc) on a single share and then adding folders below these ad-hoc as and when they're needed.
It's gotten a bit messy - I've been tasked with creating a 'folder hierarchy'.
Does anybody have any best practices for how to organise a folder structure?
We're running SBS2011 on the current file server.

A: There is no "one size fit all", but I would recommend that people be thought to keep things as closed to the physical universe as possible. When I see a person with 10 folder deep hiearchy, then I know they have no clue what files they have and never find anything.
In "real life", you have:
File Cabinets
  --> Drawers
        --> Folders
            --> Documents

Keep it like that in computer files. No more than 3-4 folders nesting.
Depending on the type of files, categories are either by date or by subject. File names would have yyyy-mm-dd-subjectoffile.ext kind of naming.

A:
Does anybody have any best practices for how to organise a folder structure?

Don't.
Believe me, you don't want to own the folder hierarchy for any department (except maybe your own).  You don't know what their needs are, don't have the knowledge or experience of other departments to make good choices, and don't want to be the company's file janitor.
And if you think they make a mess of it, that's nothing compared to the mess you'll make of things.  I know you say you've been tasked with doing this, but the best thing you can do for yourself, is to get untasked from it, quick.  This is an example of being set up to fail - no matter how you do it, someone is going to have a problem with it, and complain about or at you because of that.
The best practice is literally "[department head], here's your department share.  You're responsible for structure and permission below this level.  Set it up however best suits your needs."


text:
Q: Is there a way to bypass downloading of a jnlp file when using a web automation tool? We're currently using a web automation tool that makes us download a localexecute.jnlp file everytime before running the testcase. Then it says downloading application and that continues for about 3-4 minutes.
Is there a way to bypass this, because it is very time consuming.
Thanks.

A: You can try just saving the JNLP file somewhere (e.g., right click on the link in the browser and save it) and then opening the saved file directly.
This assumes that the JNLP file doesn't change each time, which it may well do (for example, to add some secure token). In that case, it won't work.
You also have to keep in mind that since you are testing, you might be invalidating your tests by not loading the latest JNLP file each time.


text:
Q: response header is null in $httpProvider.interceptors responseError in angularjs I add errorHandlerInterceptor to handle errors as you seen below:
(function() {
    'use strict';

    angular
        .module('rasool')
        .config(httpConfig);

    function httpConfig($httpProvider) {

        $httpProvider.interceptors.push('errorHandlerInterceptor');
    }
})();

and in the errorHandlerInterceptor i want to get a specific header from response headers like this:
(function() {
    'use strict';

    angular
        .module('rasool')
        .factory('errorHandlerInterceptor', errorHandlerInterceptor);

    function errorHandlerInterceptor ($q, toaster, $rootScope, $timeout) {
        var service = {
            responseError: responseError
        };

        return service;

        function responseError (response) {

            var errorHeader = response.headers('X-app-alert');

            if(errorHeader) {
                // do something
            }

            return $q.reject(response);
        }
    }
})();

The problem is that the errorHeader is null, but when i check the response headers with Chrome DevTools, this header exists and have a value as you can see in the below screenshot:

UPDATE
All of these part are running correctly in the website, but i created a copy of html, js and css files to create an ionic1 application, but when i run ionic serve command to test the application, i have this problem.

A: Did you try to call it like this:
var errorHeader = response.headers();

and after errorHeader should be an object that have the data you need.


text:
Q: OpenCV real-time stream very slow with pixel manipulation I am trying to write a script to manipulate video from a webcam. I am trying to do this through OpenCV with Python, but I am running into some issues.
If I run the video capture stream with no pixel manipulation applied, the stream works fine and has a smooth frame rate. However, I applied a threshold loop as a test, and my stream undergoes major lag and updates once every few seconds. Any ideas if it is possible to optimise this? Ideally, I am looking to get a 30 fps stream with the video manipulation applied. Here is the code:
import cv2
import numpy as np

cap = cv2.VideoCapture(0)
T = 100

while True:

    ret, frame = cap.read()
    height, width, channels = frame.shape

    for x in range(width):
        for y in range(height):
            if frame[y,x,0] < T:
                frame[y,x]=0
            else:
               frame[y,x]=255

    cv2.imshow('frame', frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

A: accessing Pixel by pixel in image processing in general is very bad practice as it slow the performance very much, packages like opencv and numpy has optimized this by doing matrix operations allowing your program to be much more faster, here is a sample code that will perform your task but much more faster.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
T = 100

while True:

    ret, frame = cap.read()
    height, width, channels = frame.shape
    B,G,R = cv2.split(frame)
#     for x in range(width):
#         for y in range(height):
#             if frame[y,x,0] < T:
#                 frame[y,x]=0
#             else:
#                 frame[y,x]=255

    _,B = cv2.threshold(B,T,255,cv2.THRESH_BINARY)
    frame = cv2.merge((B,G,R))

    cv2.imshow('frame', frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


text:
Q: Issue with redundant SSO permissions prompts; workflow for Apps Marketplace install I've been working over the past month with a Google support rep, who's responsible for validating SSO workflow/integration for Google App Marketplace submissions. We have everything setup, configured, and tested successfully -- with the exception of one mysterious issue. My Google rep recommended I post our issue here, as both he and I are unsure how to resolve it.
When you install our app (https://chrome.google.com/webstore/detail/floruit-labs-pond/bhalfbanckpdhnkjnknlhcoiohcigocm?hl=en), the workflow prompts you more than once to allow permissions. Which of course is a deal-breaker for getting published in the Marketplace.
At the risk of over sharing, I'm attaching background materials for context: screenshots of our install workflow
Also, copied below is the snippet of code embedded in our login page -- that adds the Google login button functionality:

<meta name="google-signin-client_id" content="743379733841-bt8rpjio0qs44kei4vlk5av888fbp0fs.apps.googleusercontent.com">

A: The Sign-in/OAuth2 dialog won't auto-approve if it contains additional scopes that the user or admin hasn't approved. The Google Sign-in button appears to always be including the "openid" scope, which isn't one of the scopes your application is configured for. Please add that scope to your Apps Marketplace configuration and it should resolve the issue.


text:
Q: Translator using a dictionary I'm trying to solve a problem that can be found in the Book The Coder's Apprentice by Pieter Spronck, in section 13.2.4. This is the code I wrote so far:
english_dutch = {"last":"laatst", "week":"week", "the":"de", "royal":"koninklijk",
    "festival":"feast", "hall":"hal", "saw":"zaag", "first":"eerst", "performance":"optreden",
    "of":"van", "a":"een", "new":"nieuw", "symphony":"symphonie", "by":"bij",
    "one":"een", "world":"wereld", "leading":"leidend", "modern":"modern",
    "composer":"componist", "composers:componisten" "two":"twee", "shed":"schuur", "sheds":"schuren"}

text = "Last week The Royal Festival Hall saw the first \
 performance of a new symphony by one of the world's leading \
 modern composers, Arthur 'Two-Sheds' Jackson."

def clean(t):
    t = t.lower()
    t = t.split()
    new_t = ""
    for word in t:
        new_word = ""
        for letter in word:
            if "a" <= letter <= "z":
                new_word += letter
            if letter == "-":
                new_word += " "
            else:
                continue
        new_t += new_word + " "
    return new_t

def translate(t):
    translation = ""
    for word in t.split():
        if english_dutch.get(word):
            translation += english_dutch[word] + " "
        else:
            translation += word + " "
    return translation

def auto_correct():
    news = ""
    a = translate(clean(text)).split()
    for word in a:
        if len(word) > 1:
            news += word + " "
    print(news)

auto_correct()

It seems to work OK, but when I run it, the words "composers" and "two" are not translated.

A: You forgot a comma between the word composers and the word two. In addiotion you wrote "composers:componisten" instead of "composers":"componisten". Change your dictionary like so
 english_dutch = {"last":"laatst", "week":"week",
     "the":"de", "royal":"koninklijk",
     "festival":"feast", "hall":"hal",
     "saw":"zaag", "first":"eerst",
     "performance":"optreden",
     "of":"van", "a":"een",
     "new":"nieuw", "symphony":"symphonie",
     "by":"bij",
     "one":"een", "world":"wereld",
     "leading":"leidend", "modern":"modern",
     "composer":"componist",
     "composers":"componisten", "two":"twee",  # <- HERE
     "shed":"schuur", "sheds":"schuren"}

Why it passed undetected? Check this:
>>> {"composers:componisten" "two":"twee"}
{'composers:componistentwo': 'twee'}

Because the comma was missing and the colon was within the string, python concatenated the strings, creating a useless (but valid) key/value pair.
This behaviour is documented here

Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".


text:
Q: child object in parent class method In answering this question, I noticed something like the following:
class A
{
  public:
  A();
  void foo();
};

class B: public A
{
  public:
  B();
};

void A::foo()
{
  B bar;

  //more code
}

Intuitively, I want to say this can't be done, but I don't know for sure. Regardless of whether its a good idea to do or not, does anyone know if it's illegal (and why)?
Edit: I rushed the example, I edited the code so the constructors are public.

A: What makes you think it can't be done? The example you gave is invalid, because the constructors are private. But after making A and B structs, it works perfectly fine (example here). There is no rule saying that a base class function cannot have a derived class object.

A: You have some intuitive feeling about why it seems like it can't be done, which I think is a good sign. When a base classes uses a derived class, the two classes are inter-dependent. It's a pattern that is often encountered but worth trying to avoid. The compiler certainly won't complain about inter-dependent classes.


text:
Q: Share text and image on twitter and email does not load the image in android 4.4 ACTION_SEND I have made the share text and picture on twitter with the intent ACTION_SEND, my images are accessed from my assets folder, for permission to access these resources have implemented a content provider and assigned permissions have, I tested the action of sharing in android 4.1.2 and running, but when testing with android 4.4 mark me an error and does not filter that you can not add image, text me just add, I did a test changing that image for the drawable and lists the image as a publisher but no longer done by giving adds.
Declaration of my content provider in manifest.xml
  <provider
        android:name="com.domain.app.helper.ImageProvider"
        android:authorities="com.domain.app"
        android:grantUriPermissions="true"
           android:exported="true"
           android:multiprocess="true"
        >
    </provider>

My content provider class
import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class ImageProvider extends ContentProvider {

@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public String getType(Uri arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Uri insert(Uri arg0, ContentValues arg1) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public boolean onCreate() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
        String arg4) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
    AssetManager am = getContext().getAssets();
    String file_name = uri.getLastPathSegment();
    Log.i("ICP", file_name);
    if(file_name == null)
        throw new FileNotFoundException();

    AssetFileDescriptor afd = null;
    try {
        afd = am.openFd("images/recipes/" + file_name);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return afd;
}

}

Using my content provider in terms of sharing
@SuppressLint("DefaultLocale")
private void share(View v, String nameApp, String infoText, String nameImage) {

    try {

        List<Intent> targetedShareIntents = new ArrayList<Intent>();
        Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("image/jpeg");
        List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(share, 0);
        if (!resInfo.isEmpty()){
            for (ResolveInfo info : resInfo) {
                Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);

                if (info.activityInfo.packageName.toLowerCase().contains(nameApp) ||
                        info.activityInfo.name.toLowerCase().contains(nameApp)) {

                    //fix Facebook only share link
                    if (info.activityInfo.packageName.toLowerCase().contains("facebook") ||
                            info.activityInfo.name.toLowerCase().contains("facebook")){

                        targetedShare.setType("text/plain"); // put here your mime type
                        targetedShare.putExtra(android.content.Intent.EXTRA_SUBJECT, "The app");
                        targetedShare.putExtra(android.content.Intent.EXTRA_TEXT, context.getResources().getString(R.string.url_short_app) );
                    }
                    else{
                        ///targetedShare.setType( "image/*");
                        targetedShare.setType( "*/*");

                        String bodyMsg = infoText + ", " + context.getResources().getString(R.string.firm_shared) +" > " + context.getResources().getString(R.string.url_short_app);
                        targetedShare.putExtra(Intent.EXTRA_TEXT, bodyMsg);
 //this change for test
//Uri uri = Uri.parse("android.resource://"+context.getPackageName()+"/drawable/table");

                        Uri theUri = Uri.parse("content://"+context.getPackageName()+"/"+nameImage);

                        targetedShare.putExtra(Intent.EXTRA_STREAM, theUri);

                    }
                    targetedShare.setPackage(info.activityInfo.packageName);
                    targetedShareIntents.add(targetedShare);

                }
            }

            Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
            v.getContext().startActivity(chooserIntent);
        }
    } catch (Exception e) {
        Log.i("ERROR_SHARE", e.toString());
    }
}

I hope you can help me find out what the fault have
I'm assuming that android 4.4 has changed the way to access content provider resources

A: Yes, Android 4.4 KitKat does change a lot of things. Since you are using the MmsSms  provider to send the message, it will (silently) deny writing to the ContentProvider unless you are the "default SMS app"
https://developer.android.com/about/versions/android-4.4.html#SMS
Our company is working on an "open" solution to this, but I do not know of any at this time... it simply won't work for you.


text:
Q: Two Html buttons for two different functions I have a form which has two Options, Submit and Overwrite.
It looks like this:
[ INPUT FIELD ]
[Submit] [Overwrite]

The Overwrite Button only appears when the value already is in the Database.
The HTML Code is:
<input type="text"  name="target" id="target">
<button id="submit" name="submit" type="submit" class="btn btn-primary"> Submit </button>
<button id="overwrite" name="overwrite" type="submit" class="btn btn-primary"> Overwrite </button>

The JS Code is:
    if(!problem){
        data = "submit=save";

        jQuery('#overwrite').click(function(){
        $(this).toggleClass('selected');

        if( $(this).hasClass('selected') ){
         data+="&overwrite=on";
         console.log( "overwrite=on" );
        }
       });

        sendToBean(href, data);

        jQuery.each(langs, function(i, lang){
             sendToBean(href, data);
        });
    }
}

If I only have the Submit button, it works.
If I only have the Overwrite button, it works.
But if I have both, the Overwrite button wont work anymore.
Does anyone have a solution to this problem?

A: put retrun false in the anonymous callback function will do the trick. since you declare that the button is a submit button
if(!problem){
    data = "submit=save";

    jQuery('#overwrite').click(function(){
    $(this).toggleClass('selected');

    if( $(this).hasClass('selected') ){
     data+="&overwrite=on";
     console.log( "overwrite=on" );
    }
    return false;
   });

    sendToBean(href, data);

    jQuery.each(langs, function(i, lang){
         sendToBean(href, data);
    });
}

}

A: When you click the submit button the page will be refreshed and the overwrite will return to the initial format and the selected will disappear, Try to change the input type to button :
<button id="overwrite" name="overwrite" type="button" class="btn btn-primary"> Overwrite </button>

Hope this helps.

A: Remove <input type=""> for Overwrite button you may use <button>
<a href="#" id="overwrite" class="btn btn-primary"> Overwrite </a>

A: <input type="text"  name="target" id="target">
<input type="submit" id="btnSubmit" name="btnSubmit" class="btn btn-primary" value="submit"/>
<input type="submit" id="btnOverwrite" name="btnOverwrite" class="btn btn-primary" value="Overwrite"/>

$(document).ready(function(){
    $("#btnOverwrite").unbind("click").bind("click",function(e){
    e.preventDefault();
    alert("overwrite called");
  });
  $("#btnSubmit").unbind("click").bind("click",function(e){
    e.preventDefault();
    alert("submit called");
  })
});

Review fiddle
https://jsfiddle.net/dipakchavda2912/rwdakvyg/


text:
Q: jquery autocomplete special char trigger i have the following problem:
i must make a special autocomplete with jquery triggered by char "@"
the problem is that if i begin the textbox with @ it works but if i enter @ after i write some chars it doesn't work.
how it must work:
-i write some text an i want to add someone from "utilizatoriJson",
-to add someone from "utilizatoriJson" i must press the @ key and an autocomplete dropdown must apear,
-after i select someone from dropdown or i type a full label from dropdown it must put space and let me continue my message
how can i do this ?
code that i wrote :
var utilizatoriJson = <%=utilizatoriJson%>;

$( '#textarea_mesaj_colaborare').autocomplete({
    source: utilizatoriJson

})            .autocomplete( "instance" )._renderItem = function( ul, item ) {
    return $( "
" )
            .append( "" + item.label + "" )
            .appendTo( ul );
}
$( '#textarea_mesaj_colaborare').autocomplete("disable");

$('#textarea_mesaj_colaborare').keyup(function(){
    if ($('#textarea_mesaj_colaborare').val()[$('#textarea_mesaj_colaborare').val().length-1]==='@'){
        var inceput = $('#textarea_mesaj_colaborare').val().length;

        $( '#textarea_mesaj_colaborare').autocomplete("enable");
    }

});

A: As already mentioned, you would require multiple words approach here.
The link to original source has already been provided above. So, I would like show what I understood from your doubt.
But first let me know if you want to have autocompletion like after '@' all label that start with 'a' should give results that only start with 'a' and not those which contain 'a'.
Since I suppose this would be of much better use, I have code for that part.
Working Demo: http://jsfiddle.net/AJmJt/2/

$(function() {
  //Since you told that labels start with '@'
  var utilizatoriJson = [
    {'label': "@ActionScript",'id':'1'},
    {'label': "@Java",'id':'2'},
    {'label': "@C++",'id':'3'},
    {'label': "@Javascript",'id':'4'},
    {'label': "@Python",'id':'5'},
    {'label': "@BASIC",'id':'6'},
    {'label': "@ColdFusion",'id':'7'},
    {'label': "@Haskell",'id':'8'},
    {'label': "@Lisp",'id':'9'},
    {'label': "@Scala",'id':'10'}
  ];
  function split( val ) {
    return val.split( / \s*/ );
  }
  function extractLast( term ) {
    return split( term ).pop();
  }

  $( "#tags" )
    // don't navigate away from the field on tab when selecting an item
    .bind( "keydown", function( event ) {
      if ( event.keyCode === $.ui.keyCode.TAB &&
          $( this ).autocomplete( "instance" ).menu.active ) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 1,
      source: function( request, response ) {
        // delegate back to autocomplete, but extract the last term
        var lastword = extractLast(request.term);
        // Regexp for filtering those labels that start with '@'
        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( lastword ), "i" );
        // Get all labels
        var labels = utilizatoriJson.map( function( item ) { return item.label; });
        var results = $.grep( labels, function( item ) {
           return matcher.test( item );
        });
        response( $.ui.autocomplete.filter( results, lastword ) );
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function( event, ui ) {
        var terms = split( this.value );
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push( ui.item.value );
        // add placeholder to get the comma-and-space at the end
        terms.push( "" );
        this.value = terms.join( " " );
        return false;
      }
    });
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

  Tags:
  <input id="tags" size="50">

If you don't want something like I said, then there is no need for RegExp matching, but there you need to see if word starts with '@' or not.
Code for this behavior working: http://jsfiddle.net/rPfY8/1/

$(function() {
  var utilizatoriJson = [
      {'label': "@ActionScript",'id':'1'},
      {'label': "@Java",'id':'2'},
      {'label': "@C++",'id':'3'},
      {'label': "@Javascript",'id':'4'},
      {'label': "@Python",'id':'5'},
      {'label': "@BASIC",'id':'6'},
      {'label': "@ColdFusion",'id':'7'},
      {'label': "@Haskell",'id':'8'},
      {'label': "@Lisp",'id':'9'},
      {'label': "@Scala",'id':'10'}
  ];
  function split( val ) {
    return val.split( / \s*/ );
  }
  function extractLast( term ) {
    return split( term ).pop();
  }

  $( "#tags" )
    // don't navigate away from the field on tab when selecting an item
    .bind( "keydown", function( event ) {
      if ( event.keyCode === $.ui.keyCode.TAB &&
          $( this ).autocomplete( "instance" ).menu.active ) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 1,
      source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          var lastword = extractLast(request.term);
          if(lastword[0] != '@')
              return false;
          // Get all labels
          var labels = utilizatoriJson.map(function(item){return item.label;});
          response( $.ui.autocomplete.filter(
          labels, lastword ) );
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function( event, ui ) {
        var terms = split( this.value );
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push( ui.item.value );
        // add placeholder to get the comma-and-space at the end
        terms.push( "" );
        this.value = terms.join( " " );
        return false;
      }
    });
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

  Tags:
  <input id="tags" size="50">

A: You don't want to disable/re-enable the autocomplete as that prevents the control from doing anything. You can do this the way you propose, but there's another approach. Take a look at the example here: http://jqueryui.com/autocomplete/#multiple
This should do what you're looking for, you can update the filter to only do a "starts with" search
Here's a JSFIDDLE example of what I mean: http://jsfiddle.net/UhL5d/
And the corresponding Javascript:
$(function () {
    var availableTags = [
        {value: 1, label: "@ActionScript" },
        {value: 2, label: "@AppleScript" },
        {value: 3, label: "@Asp" },
        {value: 4, label: "@BASIC" },
        {value: 5, label: "@C" } ];

    function split(val) {
        return val.split(/\s/);
    }

    function extractLast(term) {
        return split(term).pop();
    }

    $("#textarea_mesaj_colaborare").autocomplete({
        source: function (request, response) {
            // delegate back to autocomplete, but extract the last term
            response($.ui.autocomplete.filter(
            availableTags, extractLast(request.term)));
        },
        focus: function () {
            // prevent value inserted on focus
            return false;
        },
        select: function (event, ui) {
            var terms = split(this.value);

            // remove the current input
            terms.pop();
            // add the selected item
            terms.push(ui.item.label);
            // add placeholder to get the comma-and-space at the end
            terms.push("");
            this.value = terms.join(" ");
            return false;
        }
    });
});


text:
Q: accessing indices in two dimensions I have a vector a and a second vector b to access a range of indices in a, all working as I would expect:
a=1:5400; % a==[1 2 3 4 ...] value: (1x5400 double)
b=[1 2 3]; % b value: (1x3 double)
a(b); % returns [1 2 3]

however if a b is a 2D matrix and a is matched to the size of b:
a=1:5400;
b=[1 2 3; 4 5 6; 7 8 9];
a=repmat(a,3,1); %expand matrix to match dimensions of b
c=a(b);

I get an unexpected result: c == [1 1 1;2 2 2;3 3 3] when I expected [1 2 3;4 5 6;7 8 9]
Can somebody offer an explanation?


text:
Q: How to loop through a list to count keys from dictionary? I need to run through a speech that is parsed into a list called speech and count each instance of the punctuation mark and +1 the value in the dictionary. I have a punctuation list and dictionary below.
punclist = ['.', '!', '?']
puncdict = {'.':0,'!':0,'?':0}

A: Not sure why the speech is a list, but you could use a collection.Counter() to count occurrences of each character, then pick out those of interest:
from collections import Counter

text = 'We will fight them on the beaches! Where are the apples? Oh, they are over there. etc. etc. etc.'

c = Counter(text)
punclist = ['.', '!', '?']
punctuation_counts = {k: c[k] for k in punclist}
print(punctuation_counts)
# {'.': 4, '!': 1, '?': 1}

If you have a list of words then you would do this:
c = Counter(''.join(word_list))

And if you want counts for all punctuation characters:
import string

punctuation_counts = {k: c[k] for k in string.punctuation}
print(punctuation_counts)
# {'!': 1, '"': 0, '#': 0, '$': 0, '%': 0, '&': 0, "'": 0, '(': 0, ')': 0, '*': 0, '+': 0, ',': 1, '-': 0, '.': 4, '/': 0, ':': 0, ';': 0, '<': 0, '=': 0, '>': 0, '?': 1, '@': 0, '[': 0, '\\': 0, ']': 0, '^': 0, '_': 0, '`': 0, '{': 0, '|': 0, '}': 0, '~': 0}


text:
Q: Issue in creating platform using phonegap CLI I have used phonegap before to create android platform and successfully run it on my device using emulator.
Now I have issue once I create android version and try to import it to Android studio, it gives me this error:
Error:No installed build tools found. Please install the Android build tools version 19.1.0 or higher.
I have tried many solution exist in the website and youtube, and I already downloaded all build tools and API.
I am afraid that the problem is in phonegap instead, so I notice the output command after typing: phonegap platform add android is the following:
output1
output2


text:
Q: Is there any way to send messgae to someone i connected to his wireless network? I want to send message or something to computer that i connected to it by it's wireless router.
How to do that ?
note:
I've windows vista 64Bit

A: If you can see the other computer, you may use the Net Send Command :

net send name_of_user_or_computer message_text

EDIT
In Vista or Windows 7, the "net send" command can be replaced by msg.exe:

msg * /server:other-computer "message_text"

See this article: MSG.EXE replaces Net Send in Windows Vista.


text:
Q: Acer Aspire One 725 Temperature I just got my AO725 and I have sucessfully installed Xubuntu 12.10. It's all okay except the temperature which is pretty high if I look to some reviews on the web - it's about 70 to 85° C. I don't have any additional drivers installed, because I only installed the system and some programs.
What could be a problem or it's that the normal temperature for netbook like this?

A: I confirmed that AO725 is indeed running hotter with Ubuntu 12.10 as well than Windows 8.
Windows 8 is measured at 45to55° C, Ubuntu at 68to84° C
Are you using Psensor to monitor the temperature? Can you try increasing the PSensor Update interval to 5 seconds and Measure update interval to 5 seconds as well? Would that slightly bring down your CPU temperature?
Some guy here Ubuntu 12.10 Laptop temperature seem to have the answer to why ubuntu is hotter.


text:
Q: InvalidArgument error when calling LINQ First() method So my problem is that i am getting an invalid argument error in this section of code. What it is meant to do is take a hand of cards and get the sum of their total value. Then if the value is greater than 21 it checks to see if any of the cards in the hand is an ace(or the type is == ace and it's card totalVal == 11) now my problem is the statement i have written for this will run regardless of if there is an ace in the hand or not and throws an error.
I was wondering if there is any other way i can write the statement below in order to get this to run correctly?
        public int HandTotal()
        {

          int total = CurrentCards.Sum(n => n.Total);
          **while ( total > 21 && CurrentCards.First(n => n.Type == 13 && n.Total == 11) !=null)**
          {
              CurrentCards.First(n => n.Type == 13).Total = 1;
              total = CurrentCards.Sum(n => n.Total);
              return total;
          }
          return total;
        }

i've tried several different things including changing the != null into > 0 however that throws an invalid argument error saying that > cannot be used with this statement. Is there any other way that i can determine if CurrentCards.First(n => n.Type == 13 && n.Total == 11) is true or false?
Any help or suggestions are greatly appreciated.
Thank You

A: Instead of First, use Any with the predicate.
while(total > 21 && CurrentCards.Any(n => n.Type == 13 && n.Total == 11))

A: The First method throws an exception if there are no matching element.
You need to call FirstOrDefault, which can return null.

A: You should try using FirstOrDefault instead of First.First will throw an error if no elements a returned.
Also check that CurrentCards is not empty. Both First and FirstOrDefault will give an ArguementNullException if the IEnumumerable is empty.


text:
Q: Python - Constructing SOAP Packet - Requests Library Can anyone spot what may be incorrect in the below SOAP request?
I am receiving a 400 response, "Bad Request", with the below SOAP request. After chatting with support and looking at documentation, I can't isolate what is the issue. For my use-case, I cannot utilize the SDK
I have tried passing my variables through explicitly as well as changing up my headers (no luck).
I utilized a sample request from Postman as my base, URL below:
https://www.postman.com/salesforce-developers/workspace/salesforce-developers/request/14448118-3f18faee-ead6-4351-81ab-e48deba93dd3
I'm using python 3.7+ in Jupyter on Windows
url_ = f'https://{subdomain}.soap.marketingcloudapis.com/Service.asmx'

soap_payload = '''
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <s:Header>
        <a:Action s:mustUnderstand="1">Retrieve</a:Action>
        <a:To s:mustUnderstand="1">https://{subdomain}.soap.marketingcloudapis.com/Service.asmx</a:To>
        <fueloauth xmlns="http://exacttarget.com">{token}</fueloauth>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <RetrieveRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
            <RetrieveRequest>
                <ObjectType>DataExtension</ObjectType>
                <Properties>ObjectID</Properties>
                <Properties>CustomerKey</Properties>
                <Properties>Name</Properties>
            </RetrieveRequest>
        </RetrieveRequestMsg>
    </s:Body>
</s:Envelope>
'''

headers = {'Content-Type': 'text/xml'}

soap_response = requests.post(url_,data=soap_payload.format(subdomain=subdomain, token=token), headers=headers)

print(soap_response)
print(soap_response.text)

Below Is How I Was Generating My Token To Pass To The SOAP Packet (Which has been working):
payload = {
    'client_id': clientid,
    'client_secret': clientsecret,
    'grant_type': 'client_credentials'
}

 r = requests.post(auth_base_url,data=payload)

 body = json.loads(r.content)
 token = body['access_token']

A: Give this a try:
url_ = f'https://{subdomain}.soap.marketingcloudapis.com/Service.asmx'

soap_payload = \
"""
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <s:Header>
        <fueloauth xmlns="http://exacttarget.com">{0}</fueloauth>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <RetrieveRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
            <RetrieveRequest>
                <ObjectType>DataExtension</ObjectType>
                <Properties>CustomerKey</Properties>
                <Properties>Name</Properties>
                <Properties>ObjectID</Properties>
            </RetrieveRequest>
        </RetrieveRequestMsg>
    </s:Body>
</s:Envelope>
"""
soap_payload = soap_payload.format(token)

headers = {
'Content-Type': 'text/plain',
'SOAPAction': 'Retrieve'
}

soap_response = requests.request("POST", url_, headers=headers, data=soap_payload)

print(soap_response)
print(soap_response.text)

Here's a SOAP GetSystemStatus function I wrote in Python.  Perhaps you can retrofit it for your SOAP use case if you can't get the above functioning:
def GetSystemStatus(authEndpoint: str, clientId: str, clientSecret: str, mid:str):

  accessToken = getToken(authEndpoint, clientId, clientSecret, mid)
  url = soapEndpoint + "/Service.asmx"

  payload = \
  """
  <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:par="http://exacttarget.com/wsdl/partnerAPI">
      <soapenv:Header>
          <fueloauth xmlns="http://exacttarget.com">{0}</fueloauth>
      </soapenv:Header>
      <soapenv:Body>
          <par:SystemStatusRequestMsg/>
      </soapenv:Body>
  </soapenv:Envelope>
  """
  payload = payload.format(accessToken)

  headerVals = {
    'Content-Type': 'text/xml',
    'SOAPAction': 'GetSystemStatus'
  }

  response = requests.request("POST", url, headers=headerVals, data=payload)

  # must specify encoding in order to parse
  utf8_parser = etree.XMLParser(encoding='utf-8')
  responseXML = etree.fromstring(response.text.encode('utf-8'), parser=utf8_parser)

  # the . in the XPATH indicates a context item, double-slash indicates relative path anywhere
  # namespaces are required if used in response, {*} means any namespace
  StatusCode =  responseXML.find(".//{*}Result/{*}StatusCode").text
  StatusMessage = responseXML.find(".//{*}Result/{*}StatusMessage").text
  SystemStatus = responseXML.find(".//{*}Result/{*}SystemStatus").text
  OverallStatus = responseXML.find(".//{*}OverallStatus").text

  return OverallStatus

Here's the getToken function that goes along with it:
def getToken(authEndpoint: str, clientId: str, clientSecret: str, mid: str):

  token = None

  payload = {
        "grant_type": "client_credentials",
        "client_id": clientId,
        "client_secret": clientSecret,
        "account_id": mid
  }

  response = requests.post(authEndpoint + "/v2/token", data=payload)
  response.raise_for_status()
  token = json.loads(response.text)["access_token"]
  return token


text:
Q: Is this a Sinatra config issue, or an Apache config issue? I haven't decided if this is an Apache issue, or a Sinatra issue, basically, we have a bunch of little apps running on a single server, we deploy them with just built-in webrick instances and use apache to re-route those requests by subdomain to the right port. I am using gollum which is a sinatra app with a git persistence layer, but I am getting an unexpected app routing when it redirects (after edit action). I'm not sure if I can fix this by passing a startup option to Sinatra, or by configuring in the virtual host declaration for the app a rewrite rule. Please in your answer include which option you think is best and an example of how it might be accomplished.
Thanks,
# apache virtualhost declaration
<VirtualHost *:80>
  ServerName wiki.domain.com
  DocumentRoot "/var/www/html"

  ProxyPass / http://localhost:3006
  ProxyPassReverse / http://localhost:3006
</VirtualHost>

resolves with sinatra fine for GETs, eg
wiki.domain.com/Home

but fails on sinatra redirect
# expected
wiki.domain.com/Home

# actual
wiki.domain.com:3006/Home

and here is the Sinatra action (source: https://github.com/github/gollum/blob/master/lib/gollum/frontend/app.rb )
post '/edit/*' do
  name   = params[:splat].first
  wiki   = Gollum::Wiki.new(settings.gollum_path)
  page   = wiki.page(name)
  format = params[:format].intern
  name   = params[:rename] if params[:rename]

  wiki.update_page(page, name, format, params[:content], commit_message)

  redirect "/#{CGI.escape(Gollum::Page.cname(name))}"
end

A: It's a long shot, but perhaps the URLs in the ProxyPass directives need to have a trailing /? That's how it is in the documentation, and I got some strange entries in error.log without them.


text:
Q: My app randomally crashes the device (Galaxy Nexus and Nexus 4) with AccessibilityManager unhandled event This started to happen when I switched to 4.2 on my Galaxy Nexus and persists with my Nexus 4. My app crashes (soft reset) the device randomly, even with no user input.
Here is the Logcat right before the crash:
01-17 12:54:24.960: E/AccessibilityManager(10497): Error during sending EventType: TYPE_WINDOW_CONTENT_CHANGED; EventTime: 151405384; PackageName: com.ntasher.homeconII; MovementGranularity: 0; Action: 0 [ ClassName: android.widget.FrameLayout; Text: []; ContentDescription: null; ItemCount: -1; CurrentItemIndex: -1; IsEnabled: true; IsPassword: false; IsChecked: false; IsFullScreen: false; Scrollable: false; BeforeText: null; FromIndex: -1; ToIndex: -1; ScrollX: -1; ScrollY: -1; MaxScrollX: -1; MaxScrollY: -1; AddedCount: -1; RemovedCount: -1; ParcelableData: null ]; recordCount: 0
01-17 12:54:24.960: E/AccessibilityManager(10497): android.os.DeadObjectException
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.os.BinderProxy.transact(Native Method)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.accessibility.IAccessibilityManager$Stub$Proxy.sendAccessibilityEvent(IAccessibilityManager.java:227)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.accessibility.AccessibilityManager.sendAccessibilityEvent(AccessibilityManager.java:265)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.ViewRootImpl.requestSendAccessibilityEvent(ViewRootImpl.java:4700)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.View.sendAccessibilityEventUncheckedInternal(View.java:4699)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.View.sendAccessibilityEventUnchecked(View.java:4680)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.View.sendAccessibilityEventInternal(View.java:4657)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.View.sendAccessibilityEvent(View.java:4626)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at com.android.internal.policy.impl.PhoneWindow$DecorView.sendAccessibilityEvent(PhoneWindow.java:2067)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.view.ViewRootImpl$SendWindowContentChangedAccessibilityEvent.run(ViewRootImpl.java:5462)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.os.Handler.handleCallback(Handler.java:725)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.os.Looper.loop(Looper.java:137)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at android.app.ActivityThread.main(ActivityThread.java:5039)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at java.lang.reflect.Method.invokeNative(Native Method)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at java.lang.reflect.Method.invoke(Method.java:511)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-17 12:54:24.960: E/AccessibilityManager(10497):  at dalvik.system.NativeStart.main(Native Method)
01-17 12:54:25.931: E/InputEventReceiver(10497): channel '42466698 com.ntasher.homeconII/com.ntasher.homeconII.HomeConII (client)' ~ Publisher closed input channel or an error occurred.  events=0x9

After that the device soft resets (directly to the glowing "X").
What's happening here? is it some unhandled exception? how can I catch it?
Thanks.

A: You haven't provided any code, but I have a suspicion that this is the problem here.
You're passing an Activity Context when creating some object that's bound to the system. Due to this, when you're application is shut, and the object stays, it becomes a dead reference. A reference to an Activity which is no longer alive and visible.
In some place you're going to have lines like:
SomeClass object = new SomeClass(this); //Or getActivity() or something.

Here, change the Context parameter to getApplicationContext() (unless that code is creating and displaying a dialog, in which case let the Activity context be).