text:
Q: Consulta en 3 tablas con JOIN mysql ando ya dándole vueltas un par de dias a una consulta entre 3 tablas, yo creo que esta consulta ya muchos con experiencia la deben haber formulado en algún momento.
Tengo 3 tablas :
 CREATE TABLE printers (
  id int(11) NOT NULL AUTO_INCREMENT primary key,
  name varchar(255),
  model varchar(20),
  ip varchar(20),
  cod_patri varchar(20),
  serial_code varchar (50),
  property int (2) default 0,
  status int (2)  default 1
) ENGINE=InnoDB;

 CREATE TABLE areamdi(
    id int(11) int NOT NULL auto_increment primary key,
    name varchar(50),
    croquis_pdf varchar (50),
    croquis_visio varchar (50),
    piso int (3) not null,
    edificio int(3) not null
)ENGINE=InnoDB;

 CREATE TABLE ext_area (
  id int(11) NOT NULL AUTO_INCREMENT primary key,
  area_id int (11) not null default 1,
  printer_id int (11) not null default 1,
  FOREIGN KEY (printer_id) REFERENCES printers(id),
  FOREIGN KEY (area_id) REFERENCES areamdi(id)
) ENGINE=InnoDB;

Mi problema esta en que yo quiero hacer un select de las impresoras diponibles por Area , supongamos que inserto estos datos:
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A001','Ricoh SP5200','S9029600438','10.0.99.230');          /*2*/
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A002','Ricoh SP5200','S9038500133','10.0.120.241');         /*3*/
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A003','Ricoh SP5200','S9038500138','10.0.120.242');         /*4*/
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A004','Ricoh SP5200','S9049601296','10.0.120.246');         /*5*/
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A005','Ricoh SP5200','S9148701028','10.0.120.250');         /*6*/
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A006','Ricoh SP5200','S9038500131','192.168.11.120');       /*7*/
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A007','Ricoh SP5200','S9049300891','192.168.12.50');        /*8*/
INSERT INTO printers (name, model, serial_code, ip ) value ('SP5200_A008','Ricoh SP5200','S9148600679','192.168.10.250');       /*9*/

INSERT INTO areamdi (name, piso, edificio) value  ('LOGISTICA', 2, 3);
INSERT INTO areamdi (name, piso, edificio) value  ('ALMACEN', 1, 3);

insert into ext_area (area_id, printer_id) value (1,1);
insert into ext_area (area_id, printer_id) value (1,2);
insert into ext_area (area_id, printer_id) value (1,3);
insert into ext_area (area_id, printer_id) value (1,4);
insert into ext_area (area_id, printer_id) value (2,1);
insert into ext_area (area_id, printer_id) value (2,2);
insert into ext_area (area_id, printer_id) value (2,3);
insert into ext_area (area_id, printer_id) value (2,4);

Aqui yo ya asigne la impresora 1,2,3,4 al area 1(Logistica) y 2(Almacen), bueno lo que yo hago para intentar mostrar las impresoras disponibles para logistica que serian todas menos la 1,2,3 y 4, osea debería mostrar en logística como impresora disponible la 5,6,7,8,9,10 y en almacén de igual manera ya que a ambas les asigne las mismas impresoras estás 2 áreas comparten impresoras en caso tenga una nueva área debería poder ver las 10 impresoras ya que para una nueva área están disponibles todas las impresoras.
SELECT
printers.id as id_printer, printers.name as name_printer, model as model_printer, ip as ip_printer
FROM printers
LEFT JOIN ext_area ON printers.id = ext_area.printer_id
LEFT JOIN areamdi ON areamdi.id = ext_area.area_id
WHERE areamdi.id!=1 /* codigo del area que le paso por PHP*/

UNION

SELECT
printers.id as id_printer, printers.name as name_printer, model as model_printer, ip as ip_printer
FROM printers
LEFT JOIN ext_area ON printers.id = ext_area.printer_id
LEFT JOIN areamdi ON areamdi.id = ext_area.area_id
WHERE areamdi.name is null and printers.id>1

En un momento pense que lo habia conseguido pero al final no me cuadro, supuestamente me mostraba todas las impresoras disponibles, pero luego me di cuenta que al hacer mas registros de las mismas impresoras pero en otras  areas estas se inlcuyen en el select tambien y vuelven a aparecer en mis disponibles y entiendo que es porque se vuelven registros en ext_area y los estoy listando nuevamente.... que solucion podria darle?? alguien me podria ayudar porfavor..

A: Puedes valerte de la expresión not exists, para obtener solamente aquellas impresoras que no han sido asignadas a un área en particular.
Por ejemplo, para obtener las impresoras que no han sido asignadas a Logística, puedes hacer:
select printers.id, printers.name, printers.model, printers.ip
  from printers
 where not exists (select 1
                     from ext_area
                    where ext_area.printer_id = printers.id
                      and ext_area.area_id = 1 /* el id de logística */
                  )

En lenguaje natural esto sonaría algo como:
Seleccionar todas las impresoras para las que no existe una asignación de impresora en el departamento logística.


text:
Q: How many 10-letter words do not contain all the vowels I can't find where I am overcounting in the problem
How many 10-letter words do not contain all the vowels.

What I do is to count all the words that have at least 5 different vowels:
$$
\binom{10}{5}5!*26^5,
$$
this means that I have the $5$ different vowels which can be fit in $10$ spaces. The rest of the word could be also a 5-letter word (no constriction imposed).
So the result should be:
$$
26^{10} - \binom{10}{5}5!*26^5.
$$
What is wrong with it?

A: The question of "what is wrong with your count" has been answered above in the comments by @BrianM.Scott.  Here I begin the setup for the intended solution of the problem.
Let $N_a$ denote the event that there are no $a$'s in the word.  Let $N_e$ denote the event that there are no $e$'s in the word.  Etc. for the rest of the vowels.
Let our universal set, $S$, be all words that are of length ten (regardless of number of vowels present).
We have then $N_a^c$ represents the words of length ten which do have at least one $a$.
The number we are asked to calculate is $|N_a^c\cap N_e^c\cap N_i^c\cap N_o^c\cap N_u^c|$, in other words, the number of words which have at least one of each vowel.
Simplifying using DeMorgan's laws and inclusion exclusion, we have:
$\begin{array}{rl}|N_a^c\cap N_e^c\cap N_i^c\cap N_o^c\cap N_u^c| &= |S\setminus (N_a\cup N_e\cup N_i\cup N_o\cup N_u)| \\
&= |S| - |N_a\cup N_e\cup N_i\cup N_o\cup N_u|\\
&=|S|-|N_a|-|N_e|-|N_i|-\dots+|N_a\cap N_e|+\dots\\
&~~~~~~~~~~~~-|N_a\cap N_e\cap N_i|-\dots\end{array}$
Notice that $|N_a|=|N_e|=|N_i|=\dots$ and that $|N_a\cap N_e|=|N_a\cap N_i|=\dots$ etc. to simplify the above expression to:
$|S|-\binom{5}{1}|N_a|+\binom{5}{2}|N_a\cap N_e|-\binom{5}{3}|N_a\cap N_e\cap N_i|+\binom{5}{4}|N_a\cap N_e\cap N_i\cap N_o|-\binom{5}{5}|N_a\cap N_e\cap N_i\cap N_o\cap N_u|$
How big is something like $|N_a\cap N_e|$?
These are the words which simultaneously don't have $a$'s and don't have $e$'s.

It is as though our alphabet has two fewer letters available.  Ten positions with twenty four options for each, we have $|N_a\cap N_e|=24^{10}$

Simplify all of the above terms similarly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integration testing maven plugins There are five choices listed in the maven documentation on testing maven plugins:

*

*maven-verifier

*maven-invoker-plugin

*shitty-maven-plugin

*maven-it-plugin

*maven-plugin-management-plugin

I've tried a few of these and had a number of problems:

*

*maven-verifier appears to have only a limited set of verifications -- I need to be able to make arbitrary assertions

*shitty-maven-plugin has a bug that prevents it working with maven 3

*nethier maven-plugin-management-plugin nor maven-it-plugin are stable and don't seem to be under active development

Is anyone able to recommend any of these plugins?  Can you provide some example configuration?

A: The best thing i can recommend is the maven-invoker-plugin, cause it's can handle many situations and produces a real maven environment with all things which you really need to do integration test in relationship with Maven Plugins.


text:
Q: div containers and alignment this is my first time asking a question so please forgive me if I'm not asking the right questions. I'm having a problem with my website and I'm pretty sure it's somewhere in the divs and containers. I'm trying to keep the navigation at the top and I want to put some content underneath. The problem is the content isn't showing up. Also, I made a "spacer" id to push the text down where I wanted it. I'm not really sure how to align the text at the bottom without it. If anyone could help with that also, I would appreciate it.
I don't know which parts I should post so if it's any easier, I can just post the links to the page and the .css.
The page is:
http://www.preferredcaskets.com/Untitled.html
The CSS is:
http://preferredcaskets.com/nav.css
Again, forgive me if I'm not asking the right questions. It's late and I'm a little confused at the moment.
Thank you.

A: Try display inline in spacer
  #spacer {
   height:110px;
   width:auto;
   display:inline;

   }

JSFiddle - http://jsfiddle.net/a4enG/

A: You've put your background in an <img> tag, and given it position:fixed, which automatically places it on top of your other content. Quick fix: add 'style="z-index:-1;" to the <img> tag. A Better way is to add it as a background to your body (and also more semantically correct, since the background is not part of your content).
css:
body{
    background-image: url("images/bg.jpg");
}


text:
Q: отличие array_splice от array_slice Вот срабатывает как надо:
$a = [0,1,2,3,4];
echo array_sum(array_splice($a,2,3,true)) . "
";

А тут как надо срабатывает только первая:
$a = [0,1,2,3,4];
echo array_sum(array_splice($a,0,3,true)) . "
";
echo array_sum(array_splice($a,1,3,true)) . "
";
echo array_sum(array_splice($a,2,3,true)) . "
";
echo array_sum(array_splice($a,3,3,true)) . "
";
echo array_sum(array_splice($a,4,3,true)) . "

";

что я не понимаю, как оно работает?

A: Ответ прост, всё дело в одной букве:

Функция array_splice() — Удаляет часть массива и заменяет её чем-нибудь ещё

т.е splice работает как ctrl + x, если не указать чем заменяем вырезанное

Функция array_slice() — Выбирает срез массива

slice же в свою очередь работает как ctrl + c

A: <?php
$a = [0,1,2,3,4];

function ar($params) {
    return array_sum(array_splice($params[0],$params[1],$params[2],$params[3]));
}

echo ar([$a,0,3,true]).'
';
echo ar([$a,1,3,true]).'
';
echo ar([$a,2,3,true]).'
';
echo ar([$a,3,3,true]).'
';
echo ar([$a,4,3,true]).'
';

Результат
3
6
9
7
4

Если я правильно понял "вопрос"


text:
Q: insert into when select not matching I have this query :
INSERT INTO tbl_1(id , name)
SELECT  id, 'XXX'
FROM tbl_2 t WHERE t.name='XXX';

it's working when the SELECT clause match. I would like to execute the insert query with 0 in "id" field even when the SELECT does not match.

A: You can use a UNION which has the advantage that the number of rows returned by the "base" select is not limited to one:
INSERT INTO tbl_1 (id , name)
SELECT id, 'XXX'
FROM tbl_2 t
WHERE t.name='XXX'
union all
select 0, 'XXX'
where not exists (select 1 from tbl_2 t where t.name = 'XXX');

A: Include your query in a subselect (therefore it will always return at least one value):
INSERT INTO tbl_1(id , name)
SELECT COALESCE((SELECT id FROM tbl_2 t WHERE t.name='XXX'), 0), 'XXX';

or
INSERT INTO tbl_1(id , name)
SELECT COALESCE((SELECT id FROM tbl_2 t WHERE t.name=v.name), 0), v.name
FROM (VALUES ('XXX')) v(name);


text:
Q: Python 3.5: Calculating the mean for a list section that matches a for loop criteria I have multiple lists of data and one of which is a list of datetime.datetime objects that I want to use in a for loop to calculate subsections of other lists. What I am really doing is converting subhourly measurements to daily measurements but cannot get a single mean number for the entire day with my loop function
For example:
mean = []
for i in range(len(date)):
    if date[i].day == date[i+1].day:
        mean.append(np.mean(number[i:i+1])

But this doesn't take the mean for all numbers in number under that day


text:
Q: How to distinguish between added sentences and altered sentences with difflib and nltk? Downloading this page and making a very minor edit to it, changing the first 65 in this paragraph to 68:

I then run it through the following code to pull out the diffs.
import bs4
from bs4 import BeautifulSoup
import urllib2
import lxml.html as lh
url = 'https://secure.ssa.gov/apps10/reference.nsf/links/02092016062645AM'
response = urllib2.urlopen(url)
content = response.read()  # get response as list of lines
root = lh.fromstring(content)
section1 = root.xpath("//div[@class = 'column-12']")[0]
section1_text = section1.text_content()

url2 = 'file:///Users/Pyderman/repos/02092016062645AM-modified.html'
response2 = urllib2.urlopen(url2)
content2 = response2.read()  # get response as list of lines
root2 = lh.fromstring(content2)
section2 = root2.xpath("//div[@class = 'column-12']")[0]
section2_text = section2.text_content()

d = difflib.Differ()

soup = bs4.BeautifulSoup(unicode(section1_text))
soup2= bs4.BeautifulSoup(unicode(section2_text))

from nltk import sent_tokenize

sentences = [sentence for string in soup.stripped_strings for sentence in sent_tokenize(string)]
sentences2 = [sentence for string in soup2.stripped_strings for sentence in sent_tokenize(string)]

diff = d.compare(sentences, sentences2)
changes = [change for change in diff if change.startswith('-') or  change.startswith('+')]
for change in changes:
    print(change)

Printing the changes gives:
- It contains a Title II provision that changes the age at which workers compensation/public disability offset ends for disability beneficiaries from age 65 to full retirement age (FRA).
+ It contains a Title II provision that changes the age at which workers compensation/public disability offset ends for disability beneficiaries from age 68 to full retirement age (FRA).

So a change gets marked with a +, whether it's a new addition (a brand new full sentence also gets marked with a +) or a minor change to an existing sentence. As it stands then, unless my program does some additional processing, it will think that a new sentence was added and another one was removed.
How can we take advantage of the fact that what difflib sees as the apparently 'removed' sentence and the apparently 'added' sentence are very similar, in order to determine that we are in fact dealing with an in-place change to an existing sentence?
NOTE: The solution will need to be able to process potentially several changes in a single page, so it won't be sufficient to apply something like if sentence1 very similar to sentence 2: then it's a modification, since there will be several diffs to compare and contrast.


text:
Q: How to filter the DataGridView using ComboBox I need help on filtering my DataGridView using ComboBox
Here's my display code
cm = new SqlCommand();
cn = new SqlConnection(lgn.connections);
cn.Open();
cm.Connection = cn;
query = "Select * from Trails";
cm.CommandText = query;
SqlDataAdapter dar = new SqlDataAdapter(cm);
DataTable dt = new DataTable();
dar.Fill(dt);
dataGridView1.DataSource = dt;

dataGridView1.Columns[0].Width = 0;
dataGridView1.Columns[1].Width = 130;
dataGridView1.Columns[2].Width = 100;
dataGridView1.Columns[3].Width = 360;
dataGridView1.Columns[4].Width = 130;
this.dataGridView1.Columns[0].Visible = false;

RAW DATA:
ID  | TRANSACTYPE | DESCRIPTION | AUTHORIZED BY
-----------------------------------------------
1   | LOGIN       | blah blah   | BOB
2   | LOGOUT      | blah blah   | BOB
3   | LOGIN       | blah blah   | TIM
4   | LOGOUT      | blah blah   | KURT

I have ComboBox named cboFilter and if I changed the index to LOGIN the data that will show on the dataGridView1 is only LOGINs.

A: Try this:
DataTable dt = new DataTable();

private void cboFilter_SelectedIndexChanged(object sender, EventArgs e)
{
    DataView dv = dt.DefaultView;
    dv.RowFilter = string.Format("TRANSACTYPE  LIKE '%{0}%'", cboFilter.SelectedItem.ToString());
    dataGridView1.DataSource = dv;
}

A: If you need DataGridView data source always to be a DataTable as in my case.
DataTable dt = (DataTable)dgv.DataSource;
dgv.DataSource = dt.Select("IsActive = 1").CopyToDataTable();


text:
Q: Scientific number handling I am using package qvalue which has the following pre-processing step
 if(min(p)<0 || max(p)>1) {
    print("ERROR: p-values not in valid range"); return(0)
    }
    if(length(lambda)>1 && length(lambda)<4) {
    print("ERROR: If length of lambda greater than 1, you need at least 4 values."); return(0)
    }
    m <- length(p)

I have 6000 values like the following: I could show them due to character limit of the overflow
[1] 0.3671178710 0.9360140780 0.2428194940 0.5185496048 0.3280692392
   [6] 0.4681617243 0.3654880576 0.3121728291 0.6357866236 0.2576397417
  [11] 0.7224965457 0.4020649535 0.1359902232 0.4313780172 0.7543924642
  [16] 0.1915732183 0.4359938726 0.2705147307 0.5155629834 0.4446611542
  [21] 0.6636414268 0.4666097886 0.5121170670 0.7911474854 0.0662147755
  [26] 0.8659648750 0.0307181717 0.0910574293 0.7331402271 0.3078877515
  [31] 0.8331673742 0.4992904913 0.0773711040 0.6134791426 0.6714738843
  [36] 0.6620106441 0.3944466498 0.3330491388 0.7726571107 0.5989331217
  [41] 0.4429749257 0.7650029317 0.7608016901 0.3642432987 0.1672484189
  [46] 0.4305554981 0.4308085746 0.7999056710 0.8117493501 0.3325086551
  [51] 0.7233274303 0.4939756680 0.7763859166 0.8281922847 0.5195117763
  [56] 0.6581468025 0.7082172344 0.7201224910 0.8420571108 0.3118079731
  [5996] 0.3066819785 0.6066206806 0.7524323861 0.6815655815 0.7105895186

Whenever I fun the function for this variable:
    fdrq = qvalue(as.numeric( nd[,3]), fdr.level = 0.05 )
I am getting error:
[1] "ERROR: p-values not in valid range"

I tried to see the maximum and minimum, looks like it is in range.
> max(nd[,3])
[1] 1
> min(nd[,3])
[1] 0.0001641695

Please provide suggestion on what might be wrong ! is this something special on handling of decimal numbers .....  or this is a bug ...
Thanks;

A: I suspect that you have a value that's a tiny bit greater than 1, but that gets printed as "1":
> x <- 1.000000000000001
> x
[1] 1
> x > 1
[1] TRUE

You can configure R to display more digits:
> options(digits=20)
> x
[1] 1.000000000000001

A simple workaround might be to force all values greater than 1 to exactly 1.0:
> x <- c(1, 0.7, 1.000000000000001, 0.3, 0)
> x
[1] 1.000000000000000 0.700000000000000 1.000000000000001 0.300000000000000
[5] 0.000000000000000
> x[x>1] <- 1
> x
[1] 1.0 0.7 1.0 0.3 0.0

Whether this workaround is a sensible thing to do in your case, I don't know.


text:
Q: Problems with solving a 2 variable limit There is this exercise I'm trying to solve but can't seem to get it, it states the following:
Study the continuity in the origin (depending of $\alpha \in \mathbb{R}$) of $$f_\alpha(x,y) = \frac{x^6y^3}{(x^8+y^6)^\alpha}$$ when $(x,y) \neq (0,0)$ and $$f_\alpha(x,y) = 0$$ when $(x,y) = (0,0)$
I have tried various methods, passing to polar coordinates and so on but can't really seem to get anywhere, I know the only possible candidate for the limit is $0$ and thats the result I got several times, so I'm guessing it is continous at $0$ (maybe I'm wrong) and I would have to prove this using the definition but don't know how to do it.
Any hints are appreciated and sorry for my broken English.

A: If we switch to polar coordinates, we have $$f_{\alpha}(r,\varphi)=\frac{r^9cos^6(\varphi)sin^3(\varphi)}{(r^8cos^8(\varphi)+r^6sin^6(\varphi))^{\alpha}}=r^{9-6\alpha}\frac{cos^6(\varphi)sin^3(\varphi)}{(r^2cos^8(\varphi)+sin^6(\varphi))^{\alpha}}$$
If we now let $r$ go to $0$, the fraction part is bounded and $r^{9-6\alpha}$ goes either to $0$ if $6\alpha<9\Leftrightarrow \alpha<\frac{3}{2}$ or to infinity if $6\alpha>9\Leftrightarrow \alpha>\frac{3}{2} $.
From this, you can deduct when $f_{\alpha}$ is continous. Don't forget the case where $\alpha=\frac{3}{2}$

A: By polar coordinates for $\alpha<\frac32$ the limit is clearly equal to zero.
For $\alpha\ge \frac32$ by $x=t$ and $y=t$ with $t\to0$
$$ \frac{x^6y^3}{(x^8+y^6)^\alpha}= \frac{t^9}{(t^8+t^6)^\alpha}= \frac{1}{(t^{8-\frac9{\alpha}}+t^{6-\frac9{\alpha}})^\alpha}$$
which tends to $1$, when $\alpha=3/2$ or $\infty$, when $\alpha>3/2$.


text:
Q: Adding an alert to a  with an onclick event handler I have a 10 by 10 HTML table on my page that represents a game. I am currently trying to make the game grid clickable, but for some reason my onclick handler is not working properly. For testing purposes, I just want to display an alert when the user clicks inside one of the grid cells, but I can't seem to get it to work.
This is the code I have:
<body>
   <script type="text/javascript" language="javascript">
        var compDiv = document.getElementById("computer");
        var compCells = compDiv.getElementsByTagName("td");

        for (var i = 0; i < compCells.length; i++) {
            compCells[i].onclick = alertUser;
        }

        function alertUser() {
            alert("HI");
        }
   </script>
</body>

Any ideas?
UPDATE FIXED
I'm not sure what was going on but when I put the above code inside a function and called that function with onload in my <body> tag, it worked. It's now displaying as it should. :)


text:
Q: d3 equivalent for Ruby on Rails? I am looking to build a data visualization front-end for my company.  d3.js looks amazing, but I was hoping to find something more Rails-centric and perhaps slightly less complicated.  Any suggestions would be great!

A: With regards to your first question, as long as you create an endpoint which will return your data as JSON, any web app can be used with d3.
I think if you just want to add charts, something like nvd3 which is based on d3 but comes with generalized charts pre-made is a good alternative. If you want to avoid using svg, http://www.chartjs.org/ is another good alternative which uses a canvas element.


text:
Q: Component Exception: Element Type is Invalid, check render Method of app I am trying to make a simple chat app, but for some reason, I keep getting the same error:

Component Exception: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object... Check the Render method of 'App'

Here is app.js

import React from 'react';
import Main from './components/Main';
import Chat from './components/Chat';
import { createStackNavigator } from '@react-navigation/stack';
import {NavigationContainer} from '@react-navigation/native';

const stack = createStackNavigator();

const App = ()=>{
  return(
    <NavigationContainer>
      <Stack.navigator>
        <stack.screen name = "Main" component={Main}/>
        <stack.screen name = "Chat" component={Chat}/>
      </Stack.navigator>
    </NavigationContainer>
  );
}

export default App

And here is index.js

import { registerRootComponent } from 'expo';

import App from './App';

// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in the Expo client or in a native build,
// the environment is set up appropriately
registerRootComponent(App);

Does anyone have any ideas as to what I should do?

A: Try rewriting stack.screen as stack.Screen and it will probably solve your problem.
That's because there is no Components/Function named screen, since stack.screen is undefined you get that error.
edit: also, you should rewrite Stack.navigator as stack.Navigator for the same reason. Never forget that javascript/JSX is case sensitive.


text:
Q: How to download a webpage and parse in SQL I am simply trying to download a webpage and store it in an accessible format in SQL Server 2012. I have resorted to using dynamic SQL, but perhaps there is a cleaner, easier way to do this.  I have been able to successfully download the htm files to my local drive using the below code, but I am having difficulty working with the html itself. I am trying to convert the webpage to XML and parse from there, but I think I am not addressing the HTML to XML conversion properly.
I get the following error, "Parsing XML with internal subset DTDs not allowed. Use CONVERT with style option 2 to enable limited internal subset DTD support"
DECLARE @URL      NVARCHAR(500);
DECLARE @Ticker   NVARCHAR(10)
DECLARE @DynamicTickerNumber INT
SET @DynamicTickerNumber = 1

CREATE TABLE Parsed_HTML(
[Date] DATETIME
,[Ticker]    VarChar (8)
,[NodeName] VarChar (50)
,[Value]    NVARCHAR (50));

WHILE @DynamicTickerNumber <= 2
BEGIN

SET @Ticker = (SELECT [Ticker] FROM [Unique Tickers Yahoo] WHERE [Unique Tickers Yahoo].[Ticker Number]= @DynamicTickerNumber)

SET @URL ='http://finance.yahoo.com/q/ks?s=' + @Ticker + '+Key+Statistics'

DECLARE @cmd      NVARCHAR(250);
DECLARE @tOutput  TABLE(data NVARCHAR(100));
DECLARE @file     NVARCHAR(MAX);

SET @file='D:\Ressources\Execution Model\Execution Model for SQL\DB Temp\quoteYahooHTML.htm'
SET @cmd ='powershell "(new-object System.Net.WebClient).DownloadFile('''+@URL+''','''+@file+''')"'

EXEC master.dbo.xp_cmdshell @cmd, no_output

CREATE TABLE XmlImportTest
(
xmlFileName VARCHAR(300),
xml_data xml
);

DECLARE @xmlFileName VARCHAR(300)
SELECT  @xmlFileName = 'D:\Ressources\Execution Model\Execution Model for SQL\DB Temp\quoteYahooHTML.htm'

EXEC('
INSERT INTO XmlImportTest(xmlFileName, xml_data)

SELECT ''' + @xmlFileName + ''', xmlData
FROM
(
SELECT  *
FROM    OPENROWSET (BULK ''' + @xmlFileName + ''' , SINGLE_BLOB) AS XMLDATA
) AS FileImport (XMLDATA)
')

DECLARE @x XML;
DECLARE @string VARCHAR(MAX);
SET @x = (SELECT xml_data FROM XmlImportTest)
SET @string = CONVERT(VARCHAR(MAX), @x, 1);

INSERT INTO [Parsed_HTML] ([NodeName], [Value])
SELECT [NodeName], [Value] FROM dbo.XMLTable(@string)
--above references XMLTable Parsing function that works consistently

END

Unfortunately this needs to be run within the confines of SQL Server, and my understanding is that the HTML Agility Pack is not immediately compatible. I also notice that the intermediate table, XMLimportTest, never gets populated, so this is likely not a function of malformed HTML.

A: Short answer: don't.
SQL is very good for some things but for downloading and parsing HTML it's a terrible choice. In your example you're using PowerShell to download the file, why not parse the HTML in PowerShell too? Then you could write the parsed data into something like a CSV file and load that in using OPENROWSET.
Another option, still not using SQL but a bit more within SQL Server might be to use a .Net SP via SQL CLR.
As a few of the comments point out, if you could guarantee the HTML was well formed XML then you could use SQL XML functionality to parse it, but web pages are rarely well formed XML so this would be a risky choice.


text:
Q: How to find a $3\times 3$ permutation matrix? Could anyone tell me how to find a $3\times 3$ permutation matrix $P$ such that for any $3\times n$ matrix $A$ the matrix $PA$ is $A$ with its last two rows exchanged.
I am simply not understanding the problem at all. thanks for helping.

A: Use $P= \begin{bmatrix}
1 & 0 & 0  \\
0 & 0 &1  \\
0 & 1 & 0  \\
\end{bmatrix}.
$
Then for $A=
\begin{bmatrix}
a & b & c  \\
d & e &f  \\
g & h & i  \\
\end{bmatrix}
$  we have:
$$PA=\begin{bmatrix}
1 & 0 & 0  \\
0 & 0 &1  \\
0 & 1 & 0  \\
\end{bmatrix}\cdot \begin{bmatrix}
a & b & c  \\
d & e &f  \\
g & h & i  \\
\end{bmatrix} = \begin{bmatrix}
a & b & c  \\
g& h &i  \\
d & e & f  \\
\end{bmatrix} =A_{\text{swapped}} $$
The first column of $P$ ensures that the first row of $A$ does not change. The other two columns then swap the second and third row. If you swapped the second and third column in $P$ then $P$ would be the identity matrix and all rows in $A$ (and the columns too) would remain in their place.
For arbitrary $A\in \mathbb{R}^{3\times n}$ the result is the same.

A: Left-multiplying a matrix by the $i$th row of the appropriately-sized identity matrix picks out its $i$th row. Similarly, right-multiplying by the $j$th column of the identity picks out the $j$th column of the matrix.
You want to leave the first row of your matrix alone, so the first row of the permutation matrix is $\small{\begin{bmatrix}1&0&0\end{bmatrix}}$. You're swapping the second and third rows, i.e., the second row of the result should be the third row of the original matrix, so the second row of the permutation matrix is $\small{\begin{bmatrix}0&0&1\end{bmatrix}}$. Can you finish this on your own?


text:
Q: Error when inputting list of dicts to Bokeh ColumnDataSource I'm using Bokeh to graph some data that originates from a JSON blob (which is retrieved with Python). I want to pass the original JSON data into ColumnDataSource so that when the user clicks on a point, all of the data in the original JSON blob is displayed (using a CustomJS tooltip). However, when I do the following, I get 'Uncaught TypeError: Cannot read property '0' of undefined'.
Setting up graph:
source = ColumnDataSource(data=dict(
    x = xvals, # list of datetimes
    y = yvals, # list of strings (categorical variable),
    info = info, # list of dicts (each dict has the same 7 keys)
))

JS display part:
code = """
    selection = require("core/util/selection")
    indices = selection.get_indices(source)
    for (i = 0; i < indices.length; i++) {
        ind = indices[i]
        document.getElementById('info').style.display = 'block'
        document.getElementById('info').innerHTML= source.data['info']
    }
    """

All three lists are the same length. I've tried and this works fine with a list of lists, just not a list of dicts. Has anyone been able to get this to work/any suggestions on how to fix this? I am currently converting my list of dicts into 7 separate lists but would strongly prefer not to do that because I need this code to scale for a much larger JSON dataset.
Alternatively, is there another way (besides passing data through ColumnDataSource) to allow the CustomJS code to read the JSON data from Python? Thanks!

A: My suggestion would be to call json.dumps on each JSON blob, so that you are creating a column of strings, rather than a column of dicts. If you are just displaying the information then it's already a string. If you actually need the structure in a callback, etc. you could call JSON.parse on it.


text:
Q: I am trying to change the time scale of a discrete function in MATLAB bits = [1,0,1,1,0,0,0,1];
for a=1:length(bits)
if bits(a) == 1
    bit(a) = 5;
else
    bit(a) = -5;
end
end
i = 1;
t = 0:0.01:length(bits);
for b=1:length(t)
if t(b) <= i
    y(b) = bit(i);
else
    y(b) = bit(i);
    i = i+1;
end
end
plot(t,y);

I am plotting y at t from 0 to 8.
I need to change the time scale to 0 to 8us with each bit lasting 1us and a step of 10ns.
Simply changing the time scale will only plot the first value as length of array is 8. Any ideas on how to approach this problem?


text:
Q: Displaying a panel in another windows form on button click c# I'm working on a c# program and I want a panel to appear on a form when a button is clicked in another. So when the add button is clicked on form2 the panel requesting the details for this to be possible will be displayed on form 1.
I currently have a static method set up in form1 which can be accessed from form2 - however due to panel.Show() being non static it won't allow me to use this in the function.
In Form1 I have:
public static void showPanel()
{
   panel.Show()
}

In my second form I have the following:
private void btn_add_Click(object sender, EventArgs e)
{
   form1.showPanel();
   this.Hide();
}

I have tested with just having the static function show a message box which works. Is it possible to do it the way I want or do I need to take a few steps back and try a different technique?

A: Are we talking about a new instance of the second form if so you can try to instantiate the new form using:
Form newForm = new YourFormName(potential parameters);
newForm.showPanel();
newForm.Show();
If you want to execute the form on an open form you can give the first form a reference(field with instance) of the second form. Or you can try using: Application.OpenForms. if you give it [1] it'll give you the second open form probably. You can also use .OfType to get the correct form in case your form order isn't always the same.


text:
Q: RegEx Date Format MM/DD/YYYY Can anyone please tell me if there is something wrong with this regEx:
/^(0[1-9]|1[0-2])\/(19|20)\d{2}$/

I am trying to create a regEx for dates by MM/DD/YYYY, I thought this would cut it but for some reason it is still saying dates that are correct are invalid.
Such as 02/15/2015 , 01/31/2013 , etc. Any day that should be valid is not being validated so I am thinking this regEx is not doing what I was hoping it was doing...
Will anyone take a look at it and see where I may have messed up please?

A: This works for me in RegexBuddy, using it's default PCRE dialect:
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}

It successfully matches
01/01/2014
12/31/2000
07/15/1955
01-01-2012
12.22.1922

It fails (correctly) on
13/01/2001
12/33/2015
01/01/1200
15.36.1948
01.50.1922

A: Probably this shouldn't be addressed by a regex, mostly due to the complications arising from leap years. Anyway, disregarding this issue by accepting Feb 29th for all years and considering dates from the 20th and 21st century only, we have (pcre syntax; split across multiple lines for easier understanding. fold into a single line by eliminating all leading whitespace in a line):
/^
   (
       (0[13578]|1[02])\/(0[1-9]|[12][0-9]|3[01])
     | (0[469]|11)\/(0[1-9]|[12][0-9]|30)
     | 02\/(0[1-9]|[12][0-9])
   )
   \/(19|20)\d{2}
$/x

Live test on regex 101.


text:
Q: IIS 7.5 ignoring HttpCompression settings in web.config I'm trying to enable dynamic compression for the mime type application/json.
In applicationHost.config, I've made the following change:
<section name="httpCompression" allowDefinition="AppHostOnly" overrideModeDefault="Allow" />

I also tried unlocking the section with the following command:
appcmd unlock config /section:system.webserver/httpcompression

My web.config settings (same as applicationHost.config but with additional mimetype):
    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
        <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
        <staticTypes>
            <add mimeType="text/*" enabled="true" />
            <add mimeType="message/*" enabled="true" />
            <add mimeType="application/x-javascript" enabled="true" />
            <add mimeType="application/atom+xml" enabled="true" />
            <add mimeType="application/xaml+xml" enabled="true" />
            <add mimeType="*/*" enabled="false" />
        </staticTypes>
        <dynamicTypes>
            <add mimeType="text/*" enabled="true" />
            <add mimeType="message/*" enabled="true" />
            <add mimeType="application/x-javascript" enabled="true" />
            <add mimeType="application/json" enabled="true" />
            <add mimeType="*/*" enabled="false" />
        </dynamicTypes>
    </httpCompression>

But the response is not being gzipped. I know the settings are correct as it works if I add the mimetype directly to applicationHost.config.
I've enabled Failed Request Tracing and no errors are produced.

A: Try also adding the mime type:
 <add mimeType="application/json; charset=utf-8" enabled="true" />

A: I'm having the same problem i.e. trying to get IIS (IIS 10 in my case) to gzip application/json but have discovered a workaround.
I've tried editing the ApplicationHost.config as well as the web.config with no luck. IIS simply ignores any compress settings for .json data. It will happily gzip any other mimetype you tell it compress though. So I changed the mimetype to text/json in web.config and now I have gzipped reponses:
<system.webServer>
  <staticContent>
    <remove fileExtension=".json" />
    <mimeMap fileExtension=".json" mimeType="text/json" />
  </staticContent>
  <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
      <add mimeType="text/json" enabled="true"/>
    </dynamicTypes>
    <staticTypes>
      <add mimeType="text/json" enabled="true"/>
    </staticTypes>
  </httpCompression>
  <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>

Of course that may break other stuff - because now your response has Content-Type:text/json

A: HttpCompression from web.config is possible only if you use IIS 10. On IIS 7.5 you'll have to use it on appHost.config.
I was also fighting it until I've found that info on this post.


text:
Q: Triple monitor setup with an ATI Radeon 4200? I have a relatively new Powerspec computer (i5 quad core processor, about a year or two old) and just grabbed a new relatively inexpensive ($40?) graphics card. It has 1 DVI, one VGA, and one HDMI output.
I have two (different type) monitors plugged into the DVI and VGA slots, and they work great. However, I cannot seem to be able to get a third monitor in the HDMI slot to work. I can see the monitor (and monitor info) show up in display settings. However, if I try to switch the monitor to 'on' and click apply, nothing happens.
Anyone have the slightest idea what the problem might be? (It's a Radeon graphics card FYI; if I remember right I think it was the Radeon 4200?)

A: Sorry, based on the information in your question your card doesn't support three monitors.
The AMD/ATI technology for driving more than two monitors from the same card is called Eyefinity, but it is only supported on certain cards, see AMD's Eyefinity FAQ.
In brief, you need

*

*one of the Radeon models listed in the FAQ (all in the 5000 and 6000 series)

*and the card must have a DisplayPort connector.

The DisplayPort must be used for the third monitor.
In addition, AMD does not officially support Eyefinity on Radeon cards for Linux yet. Drivers exist, so with the proper combination of cards and monitors it can be made to work, but there are some limitations.
See also the question 3-monitor graphics on Linux on superuser.com.

A: You may be able to get a third monitor working using a USB video adapter from DisplayLink. Take a look at this thread I just posted to get some feedback on the ease of doing this. My alternative is to get a 2nd PC and run Synergy to use the same mouse+keyboard with both systems :(
Here is the DisplayLink on linux driver page


text:
Q: What does "trivial solution" mean? What does "trivial solution" mean exactly?
Must the trivial solution always be equal to the zero-solution (where all unknowns/variables are zero)?

A: It is not always the zero solution, but it always reflects solutions that one can "see" without actually having to solve anything, and for practical purposes they are almost always seen as irrelevant. They are also almost always "simpler" than the general solutions, and some times they cannot be expressed as part of a general solution formula.
For instance, a logistical system like, say, $y' = y(1-y)$ has two trivial solutions: $y(x) = 0$ and $y(x) = 1$ (trivial because they clearly make both sides of the equation equal $0$, and if you're looking for solutions like that, you easily find them without and calculations). The general solution, $y(x) = \frac{e^x}{C + e^x}$, can encompass one trivial solution ($y(x) = 1$, with $C = 0$), but it cannot encompass the other, since we're not allowed to put $C = \infty$.

A: This is a quote from Surely You're Joking MR. Feynman.

A Different Box of Tools
At the Princeton graduate school, the physics department and the math department shared a
common lounge, and every day at four o'clock we would have tea. It was a way of relaxing in the
afternoon, in addition to imitating an English college. People would sit around playing Go, or
discussing theorems. In those days topology was the big thing.
I still remember a guy sitting on the couch, thinking very hard, and another guy standing in front
of him, saying, "And therefore such-and-such is true."
"Why is that?" the guy on the couch asks.
"It's trivial! It's trivial!" the standing guy says, and he rapidly reels off a series of logical steps:
"First you assume thus-and-so, then we have Kerchoff's this-and-that; then there's Waffenstoffer's
Theorem, and we substitute this and construct that. Now you put the vector which goes around here
and then thus-and-so . . ." The guy on the couch is struggling to understand all this stuff, which
goes on at high speed for about fifteen minutes!
Finally the standing guy comes out the other end, and the guy on the couch says, "Yeah, yeah.
It's trivial."
We physicists were laughing, trying to figure them out. We decided that "trivial" means
"proved." So we joked with the mathematicians: "We have a new theorem--that mathematicians can
prove only trivial theorems, because every theorem that's proved is trivial."
The mathematicians didn't like that theorem, and I teased them about it. I said there are never
any surprises-- that the mathematicians only prove things that are obvious.

A: "Trivial" means something to the effect of "obvious". Obvious depends on context. For example, the Riemann Zeta Function satisfies the equation
$$\zeta(s) = 2^s\pi^{s-1} \sin\left(\frac{\pi s}{2}\right)\Gamma(1-s)\zeta(1-s)$$
and so it has obvious zeros for $s=-2,-4,-6,...$, and these are referred to as "trivial zeros". (Again, this depends on context. You have to know this functional equation to consider it "trivial")
In the context of differential equations, a trivial solution usually refers to the zero-function. However, I'm sure that some would refer to trivial solutions in cases when specific functions are obvious solutions.
See further information in the Triviality Wikipedia article.

A: The modifier "trivial" is always used in math in a single sense. It would not be wise to give it a definition here, so let me use some examples to give you a feeling of the sense.
1) Let $a,b,c$ be not all $0$. Then $(0,0,0)$ is a trivial solution to the equation $ax+by+cz = 0$, because you can "see" it at once.
2) To prove that $z\bar{z} = |z|^{2}$ for every complex $z$, the case where $z=0$ is a trivial case.
3) The statement that every real number is a real number is a trivial statement.
From the above, you see that "trivial" in math much or less means "obvious" or "non-surprising". It perhaps sometimes connotes "boring"?

A: Depending on the context, trivial solutions can be:

*

*the zero function $y = 0$

*singular solutions of the differential equation (e.g. where you divide by $0$ in the process of solving the differential equation)

*constant functions $y = c, c \in \mathbb{R}$

*or just solutions which one can see immediately

However, I would use the the term 'trivial solution' for the zero function only, as this is the most common use of that term in mathematics (e.g. the center of that group is non- trivial (for p-groups), the solution set of that system of equations is trivial, etc.)

A: The etymology of the word "trivial " has to do with things that are commonly known.   Literally "three-way", like things that would be known by most people at a marketplace,  say, or anywhere where three paths come together. ..
Mike Spivak wrote that "when mathematics is done correctly it is trivial"  (in his book calculus on manifolds)...


text:
Q: Mysql return value as 0 in the fetch result I have this two tables,
--
-- Table structure for table `t1`
--

CREATE TABLE `t1` (
  `pid` varchar(20) collate latin1_general_ci NOT NULL,
  `pname` varchar(20) collate latin1_general_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

--
-- Dumping data for table `t1`
--

INSERT INTO `t1` VALUES ('p1', 'pro1');
INSERT INTO `t1` VALUES ('p2', 'pro2');

-- --------------------------------------------------------

--
-- Table structure for table `t2`
--

CREATE TABLE `t2` (
  `pid` varchar(20) collate latin1_general_ci NOT NULL,
  `year` int(6) NOT NULL,
  `price` int(3) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

--
-- Dumping data for table `t2`
--

INSERT INTO `t2` VALUES ('p1', 2009, 50);
INSERT INTO `t2` VALUES ('p1', 2010, 60);
INSERT INTO `t2` VALUES ('p3', 2007, 200);
INSERT INTO `t2` VALUES ('p4', 2008, 501);

my query is,
SELECT *
FROM `t1`
LEFT JOIN `t2` ON t1.pid = t2.pid

Getting the result,
pid     pname   pid     year    price
p1      pro1    p1    2009    50
p1      pro1    p1    2010    60
p2      pro2    NULL    NULL    NULL

My question is, i want to get the price value is 0 instead of NULL.  How can i write the query to getting the price value is 0.
Thanks in advance for help.

A: you need to use IFNULL
SELECT pid,pname,pid,year,IFNULL(price,0)
  FROM `t1`
  LEFT JOIN `t2`
    ON (t1.pid = t2.pid)

IFNULL(field_to_test, value_to_show) will return 'value_to_show' when the field 'field_to_test' is null, when field_to_test is not null, it is returned directly.


text:
Q: Cannot run convolutional.py in anaconda tenserenv I have installed tensorflow in an anaconda environment called tensorenv and to test the installation I tried to run one of the examples convolutional.py and the follwing comes up.
Initialized!
E tensorflow/stream_executor/cuda/cuda_dnn.cc:346] Loaded cudnn library: 5005 but source was compiled against 4007.  If using a binary install, upgrade your cudnn library to match.  If building from sources, make sure the library loaded matches the version you specified during compile configuration.
F tensorflow/core/kernels/conv_ops.cc:457] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)
Aborted (core dumped)

After initialized it should start the training but this error comes up. Please help

A: You have to build from source if you want to use cuDNN v5.
According to the documentation:

Other versions are supported (Cuda toolkit >= 7.0 and cuDNN 6.5(v2), 7.0(v3), v5) only when installing from sources


text:
Q: GRAILS GORM how to update a parent property automatically when saving a child I have two objects.
TimeFrame{

  hasMany=[activity:Activity]

   Date startTime
   Date endTime
   Integer activeActivities

}
Activity{
   belongsTo=[timeFrame:TimeFrame]

  String name
  String description
  Date start
  Date end

}

Anytime I insert,update, or delete an Activity I want to automatically update the number of activeActivities a timeframe has. But when I add GROM event methods like...
def afterUpdate(){
    try{

        def num=0;
        def now=new Date();
        timeFrame.activities.each{i->
            if(!i.end || i.end < now){
                num+=1;
            }
        }
        timeFrame.activeActivities=num;
        timeFrame.save();
    }
    catch(e){
        log.debug('Unable to update active tally on Activity update:'+e)
    }
}

I get the error
  null id in com.application.tracker.Activity entry (don't flush the Session after an exception occurs).

What's a way around this?

A: The reason why your save is failing inside your afterUpdate is because you aren't using withNewSession. The documentation points out this detail.

Notice the usage of withNewSession method above. Since events are
  triggered whilst Hibernate is flushing using persistence methods like
  save() and delete() won't result in objects being saved unless you run
  your operations with a new Session.
Fortunately the withNewSession method lets you share the same
  transactional JDBC connection even though you're using a different
  underlying Session.


text:
Q: How to use checkBox widget in Google apps script? I am trying to figure out how to create a function that turns the color of the "productInfoButton" lime green when checked and grey when unchecked?  Could someone please help?
function doGet(e) {
  var app = UiApp.createApplication();

  var productInfoButton = app.createButton("Products").setId('productInfoButton');

  var handlerL = app.createServerClickHandler('prodCompleteHandlerL');
  var productCompleteCheckBox = app.createCheckBox().setId("productCompleteCheckBox")
  .setName("productCompleteCheckBox");
  productCompleteCheckBox.addClickHandler(handlerL);
  handlerL.addCallbackElement(productInfoButton);

  app.add(productInfoButton);
  app.add(productCompleteCheckBox);

  return app;
}

function prodCompleteHandlerL(e) {
  var app = UiApp.getActiveApplication();
  app.getElementById('productInfoButton').setStyleAttribute('background', 'lime')
  return app;
}

A: The state of the checkBox is available in the event info parameter using the name of the widget. In your code it would be :
function prodCompleteHandlerL(e) {
  var app = UiApp.getActiveApplication();
if(e.parameter.productCompleteCheckBox == 'true'){
  app.getElementById('productInfoButton').setStyleAttribute('background', 'lime')
}else{
  app.getElementById('productInfoButton').setStyleAttribute('background', '#dddddd') // is light grey
}
  return app;
}

EDIT : I didn't notice another problem (sorry about that) : the CallbackElement should include the productCompleteCheckBox.... so you should use productCompleteCheckBox as callBackElement in the main function (or use the parent widget that holds this wjidget (if any))
EDIT2 : following your comment :
You can find documentation on colors and styles by looking for CSS documentation  since it is what is used here... or you can have a look at the options available in the GUI builder to get inspiration and to see what happens in a WYSWYG environment. Everything that can be done with the GUI builder can of course be done using script (in fact script is even more powerful but it's nice to have an idea).
If you want to get a widget transparent simply use .setStyleAttribute('background','transparent')
EDIT 3 : getting the 'default look' for buttons:
Examinig the code from a page I noticed that it uses a .png file in a cache... since I couldn't find a way to use that I copied the file, put it on a public folder, get the url and used it in the style... quite a surprise : it's working. (the url found in the page seems to be specific to the script, I don't know if I could use it in another script)
Maybe someone smarter than me will find a more easy way to achieve the same goal, feel free to comment and/or suggest ;-)
Also : I copied all the parameters, some of them are useless in this use case, I know ^^
  var btn = app.getElementById('btn').setStyleAttributes({
  'margin': '5px',
  'padding': '3px 5px',
  'text-decoration': 'none',
  'font-size': 'small',
  'cursor': 'pointer',
  'cursor': 'hand',
  'background': 'url("https://dl.dropbox.com/u/211279/hborder.png") repeat-x 0px -27px',
  'border': '1px outset #ccc'
  })


text:
Q: Parsing the JSON Object with variable quantity of data in Android efficiently I am looking into ways to parse a JSON object efficiently in Android.
I can make it work using String operations but that isn't very efficient as the number of values can increase very rapidly.
Sample JSON Object
{
  "device": "Hello",
  "sensor": "There",
  "data": {
    "1465324280": 214,
    "1465324312": 215,
    "1465324344": 214,
    .
    .
    .
    "1465324394": 216
  }
}

I can create a JSON object MyJson and print the data by:
System.out.println(myJson.optString("data"));

Output:
{
    "1465324280": 214,
    "1465324312": 215,
    "1465324344": 214,
    .
    .
    .
    "1465324394": 216
}

On this output String operations can be taxing if it's huge, so I would want a way to store all the data in a 2D array for computation later on.
What would be the best approach?


text:
Q: Author custom fields post meta, the code? If I wanted to get a custom field of the current user I would use something like this.
<?php echo get_user_meta($user_info->ID,'address_line_2',true);?>
This time however I want the author so I tried multiple version of the following to no avail.
<?php
$thisauthorID = get_the_author_ID();

echo get_the_author_meta($thisauthorID,'address',true)
        ;?>

Any ideas?
Marvellous

A: get_the_author_meta() != get_user_meta().
Change to:
echo get_the_author_meta('address', $thisauthorID);


text:
Q: not able to execute ./sage I've downloaded the precompiled binary for sagemath 9.1(sage-9.1-Ubuntu_18.04-x86_64.tar.bz2), I'm on ubuntu 20.04. After extracting the file when I run ./sage in the terminal it says bash: ./sage: Permission denied. I made the file executable by changing the permission but then it says ./sage: no Sage installation found in $SAGE_ROOT = /home/my_pc/Downloads/SageMath. Can anyone help me with this?

A: The Sage installation guide says:
If your operating system does not provide SageMath, you can also use a pre-built binary...
Installation from a pre-built binary tarball is an easy and fast way to install Sage.
Note that on GNU/Linux a preferred way is to use your package manager (e.g. apt, pacman, yum).

Sagemath has packages for the following operating systems:
On GNU/Linux Debian version >= 9, Ubuntu version >= 18.04, Arch Linux
there are three packages to install
• sagemath (for the binaries)
• sagemath-jupyter (for the browser interface)
• and the documentation
which is called sagemath-doc-en on Debian/Ubuntu and sagemath-doc on
Arch Linux.

Using Apt-Get
First, try installing sagemath using the following command in your terminal because your OS is higher than Ubuntu 18.04.
sudo apt-get install sagemath sagemath-jupyter sagemath-doc-en

Then you should be able to run sage from the command line.
Using a Pre-Built Binary
It says you can extract the tarball to a folder in your home directory and run ./sage, which it seems you have done. If it didn't work from there, you can try installing from the package manager.

Source Links: Sage installation guide


text:
Q: optimizing ansible playbook to overcome redundant hardcoding for multiple clients I'm writing ansible-playbook for my new clients, where I have to copy a set of existing code to just replace new clients which resulting in redundancy.
I tried with Ansible lookup plugin with two variables(client_name,client_id) but it doesn't suit my problem
 - name: delete existing {{client_name}} deployment
   file: path=/opt/tomcat2/webapps/{{client_name}} state=absent

 - name: {{client_name}} dir create
   file: path=/opt/tomcat2/webapps/{{client_name}} state=directory   mode=0755

 - name: {{client_name}} deploy
   command: jar -xf /tmp/idp.war chdir=/opt/tomcat2/webapps/{{client_name}}
   sudo: True

 - name: template task-config.xml
   template: src=../roles/u4ia/templates/{{client_id}}task-config.xml dest=/opt/tomcat2/webapps/{{client_name}}/WEB-INF/classes/task-config.xml

whenever I need a new client, I shouldn't hardcode client names&id's by copying an existing snippet of code. I should have some variables so that simply I can add only once.

A: It's possible to put all the tasks into a separate file and to put variables into a specific dictionary. For example
$ cat update-clients.yml
 - name: delete existing {{ mlv.client_name }} deployment
   file: path=/opt/tomcat2/webapps/{{ mlv.client_name }} state=absent
 ...

Create a dictionary with the variables. For example
clients_update:
  - client_name: 'client-A'
    client_id: '007'
  - client_name: 'client-B'
    client_id: '008'
  - client_name: 'client-C'
    client_id: '009'

And loop include_tasks
- include_tasks: update-clients.yml
  loop: "{{ clients_update }}"
  loop_control:
    loop_var: mlv

Note. This solution is not idempotent. The apps will be deleted and created repeateadly. It would be good to add a condition to the loop and update only if needed.


text:
Q: I can't access the new files I make on my root folder in the terminal "no such file or directory" When I make a new directory, I can see it when I type ls in blue letters highlighted in green but when I try to access it it says "no such file or directory". There's another file in there that I can access but not the new ones I create.

root@CityWalk:~# cd ~/testing
root@CityWalk:~/testing# ls
1
root@CityWalk:~/testing# mkdir file
root@CityWalk:~/testing# ls
1   file
root@CityWalk:~/testing# cd ~/file
-bash: cd: /root/file: No such file or directory
root@CityWalk:~/testing#

How do I fix this?

A: I'm guessing here so I have two options.

*

*You might have created the folder without giving yourself permission. run this with the path to directory:
sudo chmod a+rwx /path/to/file

*You might have created with root but you're trying to access with your normal user. Open it with sudo.
sudo cd <directory>


text:
Q: What's the best field type and data usage to accelerate searches? I have a question about equivalent search result, that can occur on different fields.
Let's say I record the logical deletion state of records with 3 fields like :

*

*Boolean Deleted

*Date DeleteDate

*String DeleteUserName

The goal of the query is to avoid having deleted records into my selection.
So I can search the first field with only 2 values (True/False), or on the deletion date : a lot of different values, or on the username, different values but not a lot.
What will give the best search result time, regarding the index usage ?

A: What queries do you intend to exeute? Something like this:
SELECT * FROM mytable WHERE `deleted`=0

or
SELECT * FROM mytable WHERE `deleted_date` IS NULL

They should be about the same if deleted and deleted_date are indexed.

A: If you're doing:
SELECT * FROM table WHERE 'deleted' = 0
(In that format) then it would be the fastest:  The others don't search faster or slower, however, there is less overhead required to compare Bools than to compare Strings/Dates. (Usually, aspects of different systems change, some Bools are stored as 8-bit, and not optimized per equality testing)


text:
Q: XAMPP MySQL wont start after system crash I had an system crash while working on a project. Now MySQL in XAMPP v3.2.1 wont start anymore. Please help, I have not even a clue where to search for an solution.
2015-06-30 13:33:16 828 [Note] Plugin 'FEDERATED' is disabled.
2015-06-30 13:33:16 530 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2015-06-30 13:33:16 828 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-06-30 13:33:16 828 [Note] InnoDB: The InnoDB memory heap is disabled
2015-06-30 13:33:16 828 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-06-30 13:33:16 828 [Note] InnoDB: Memory barrier is not used
2015-06-30 13:33:16 828 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-06-30 13:33:16 828 [Note] InnoDB: Not using CPU crc32 instructions
2015-06-30 13:33:16 828 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2015-06-30 13:33:16 828 [Note] InnoDB: Completed initialization of buffer pool
2015-06-30 13:33:17 828 [Note] InnoDB: Restoring page 0 of tablespace 0
2015-06-30 13:33:17 828 [Warning] InnoDB: Doublewrite does not have page_no=0 of space: 0
2015-06-30 13:33:17 828 [ERROR] InnoDB: space header page consists of zero bytes in data file C:\xampp\mysql\data\ibdata1
2015-06-30 13:33:17 828 [ERROR] InnoDB: Could not open or create the system tablespace. If you tried to add new data files to the system tablespace, and it failed here, you should now edit innodb_data_file_path in my.cnf back to what it was, and remove the new ibdata files InnoDB created in this failed attempt. InnoDB only wrote those files full of zeros, but did not yet use them in any way. But be careful: do not remove old data files which contain your precious data!
2015-06-30 13:33:17 828 [ERROR] Plugin 'InnoDB' init function returned error.
2015-06-30 13:33:17 828 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2015-06-30 13:33:17 828 [ERROR] Unknown/unsupported storage engine: InnoDB
2015-06-30 13:33:17 828 [ERROR] Aborting

A: reinstalling solved the problem.


text:
Q: Not getting IPv6 address on Windows 10 when on wifi I have an IPv6 capable router/AP setup at home and when I connect to my main router via Ethernet my Windows 10 laptop gets an IPv6 address as expected (http://test-ipv6.com/ is all green, 10/10).

*

*When I connect to my AP via wifi my Windows 10 laptop doesn't receive an IPv6 address at all

*However if I connect to the same AP via wifi with my MacBook Air IPv6 works just fine

The only root cause I can think of is this:

*

*When I'm connecting to my main router I use an ASUS USB-Ethernet dongle (IPv6 is fine)

*When connecting via wifi my built-in Intel(R) Dual Band Wireless-AC 8260 adapter is used

I have checked and IPv6 is enabled on the adapter, it's configured to obtain an IPv6 address automatically. The adapter's drivers are up-to-date.
Any idea what can be the cause of this? Thanks for all the inputs.

A: Well, I've found out that disabling/enabling my wifi adapter in Windows network at Control Panel\All Control Panel Items\Network Connections fixes this.
More info here - note: this might only be a temporary fix, but it works at least.


text:
Q: Flex chart display with no datapoint I need to display price of item for every date in the month.
The chart can be Bar chart or plot chart.
Question:
Suppose there is no data available for 01/15/2010 then,
Is there a way to display (01/15/2010) on x axis but no (bar or plot point) corresponding y axis point ?
i.e. there will be a empty space between 2 bars or plot points.
Currently I am using 0 , But 0 is a valid value.
Let me know if such a display is possible.

A: No. You need to use some kind of value for a plot or a bar or a column. If you use null, no space will be reserved for that data point.
For example, if you have three columns — say, March, April and May — and the values in the dataProvider are [3, null, 5], the April column will simply not show up and March and April will each get wider.
What you can do is create a dataTipFunction (see ChartBase) that tells the user no data is available if the datum is 0.

A: Finally,
Here is the solution.
Say i want show the following data [jan, 10] [ feb , ]
Step 1:
To hide the point on the Barchart, send a NaN from server.
In the above example , it would mean [jan,10][Feb, NaN].
    --This causes an undesirable effect of showing the value near the title bar.
Step 2:
Now hide the data tip, Follow the solution at the link:
flex chart hide a datatip


text:
Q: Alternative to the `match = re.match(); if match: ...` idiom? If you want to check if something matches a regex, if so, print the first group, you do..
import re
match = re.match("(\d+)g", "123g")
if match is not None:
    print match.group(1)

This is completely pedantic, but the intermediate match variable is a bit annoying..
Languages like Perl do this by creating new $1..$9 variables for match groups, like..
if($blah ~= /(\d+)g/){
    print $1
}

From this reddit comment,
with re_context.match('^blah', s) as match:
    if match:
        ...
    else:
        ...

..which I thought was an interesting idea, so I wrote a simple implementation of it:
#!/usr/bin/env python2.6
import re

class SRE_Match_Wrapper:
    def __init__(self, match):
        self.match = match

    def __exit__(self, type, value, tb):
        pass

    def __enter__(self):
        return self.match

    def __getattr__(self, name):
        if name == "__exit__":
            return self.__exit__
        elif name == "__enter__":
            return self.__name__
        else:
            return getattr(self.match, name)

def rematch(pattern, inp):
    matcher = re.compile(pattern)
    x = SRE_Match_Wrapper(matcher.match(inp))
    return x
    return match

if __name__ == '__main__':
    # Example:
    with rematch("(\d+)g", "123g") as m:
        if m:
            print(m.group(1))

    with rematch("(\d+)g", "123") as m:
        if m:
            print(m.group(1))

(This functionality could theoretically be patched into the _sre.SRE_Match object)
It would be nice if you could skip the execution of the with statement's code block, if there was no match, which would simplify this to..
with rematch("(\d+)g", "123") as m:
    print(m.group(1)) # only executed if the match occurred

..but this seems impossible based of what I can deduce from PEP 343
Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..

A: Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can now capture the condition value re.match(r'(\d+)g', '123g') in a variable match in order to both check if it's not None and then re-use it within the body of the condition:
>>> if match := re.match(r'(\d+)g', '123g'):
...   print(match.group(1))
...
123
>>> if match := re.match(r'(\d+)g', 'dddf'):
...   print(match.group(1))
...
>>>

A: Another nice syntax would be something like this:
header = re.compile('(.*?) = (.*?)$')
footer = re.compile('(.*?): (.*?)$')

if header.match(line) as m:
    key, value = m.group(1,2)
elif footer.match(line) as m
    key, value = m.group(1,2)
else:
    key, value = None, None

A: I don't think it's trivial.  I don't want to have to sprinkle a redundant conditional around my code if I'm writing code like that often.
This is slightly odd, but you can do this with an iterator:
import re

def rematch(pattern, inp):
    matcher = re.compile(pattern)
    matches = matcher.match(inp)
    if matches:
        yield matches

if __name__ == '__main__':
    for m in rematch("(\d+)g", "123g"):
        print(m.group(1))

The odd thing is that it's using an iterator for something that isn't iterating--it's closer to a conditional, and at first glance it might look like it's going to yield multiple results for each match.
It does seem odd that a context manager can't cause its managed function to be skipped entirely; while that's not explicitly one of the use cases of "with", it seems like a natural extension.

A: I have another way of doing this, based on Glen Maynard's solution:
for match in [m for m in [re.match(pattern,key)] if m]:
    print "It matched: %s" % match

Similar to Glen's solution, this itterates either 0 (if no match) or 1 (if a match) times.
No sub needed, but less tidy as a result.

A: I don't think using with is the solution in this case. You'd have to raise an exception in the BLOCK part (which is specified by the user) and have the __exit__ method return True to "swallow" the exception. So it would never look good.
I'd suggest going for a syntax similar to the Perl syntax. Make your own extended re module (I'll call it rex) and have it set variables in its module namespace:
if rex.match('(\d+)g', '123g'):
    print rex._1

As you can see in the comments below, this method is neither scope- nor thread-safe. You would only use this if you were completely certain that your application wouldn't become multi-threaded in the future and that any functions called from the scope that you're using this in will also use the same method.

A: If you're doing a lot of these in one place, here's an alternative answer:
import re
class Matcher(object):
    def __init__(self):
        self.matches = None
    def set(self, matches):
        self.matches = matches
    def __getattr__(self, name):
        return getattr(self.matches, name)

class re2(object):
    def __init__(self, expr):
        self.re = re.compile(expr)

    def match(self, matcher, s):
        matches = self.re.match(s)
        matcher.set(matches)
        return matches

pattern = re2("(\d+)g")
m = Matcher()
if pattern.match(m, "123g"):
    print(m.group(1))
if not pattern.match(m, "x123g"):
    print "no match"

You can compile the regex once with the same thread safety as re, create a single reusable Matcher object for the whole function, and then you can use it very concisely.  This also has the benefit that you can reverse it in the obvious way--to do that with an iterator, you'd need to pass a flag to tell it to invert its result.
It's not much help if you're only doing a single match per function, though; you don't want to keep Matcher objects in a broader context than that; it'd cause the same issues as Blixt's solution.

A: This is not really pretty-looking, but you can profit from the getattr(object, name[, default]) built-in function using it like this:
>>> getattr(re.match("(\d+)g", "123g"), 'group', lambda n:'')(1)
'123'
>>> getattr(re.match("(\d+)g", "X23g"), 'group', lambda n:'')(1)
''

To mimic the if match print group flow, you can (ab)use the for statement this way:
>>> for group in filter(None, [getattr(re.match("(\d+)g", "123g"), 'group', None)]):
        print(group(1))
123
>>> for group in filter(None, [getattr(re.match("(\d+)g", "X23g"), 'group', None)]):
        print(group(1))
>>>

Of course you can define a little function to do the dirty work:
>>> matchgroup = lambda p,s: filter(None, [getattr(re.match(p, s), 'group', None)])
>>> for group in matchgroup("(\d+)g", "123g"):
        print(group(1))
123
>>> for group in matchgroup("(\d+)g", "X23g"):
        print(group(1))
>>>

A: Not the perfect solution, but does allow you to chain several match options for the same str:
class MatchWrapper(object):
  def __init__(self):
    self._matcher = None

  def wrap(self, matcher):
    self._matcher = matcher

  def __getattr__(self, attr):
    return getattr(self._matcher, attr)

def match(pattern, s, matcher):
  m = re.match(pattern, s)
  if m:
    matcher.wrap(m)
    return True
  else:
    return False

matcher = MatchWrapper()
s = "123g";
if _match("(\d+)g", line, matcher):
  print matcher.group(1)
elif _match("(\w+)g", line, matcher):
  print matcher.group(1)
else:
  print "no match"

A: Here's my solution:
import re

s = 'hello world'

match = []
if match.append(re.match('w\w+', s)) or any(match):
    print('W:', match.pop().group(0))
elif match.append(re.match('h\w+', s)) or any(match):
    print('H:', match.pop().group(0))
else:
    print('No match found')

You can use as many elif clauses as needed.
Even better:
import re

s = 'hello world'

if vars().update(match=re.match('w\w+', s)) or match:
    print('W:', match.group(0))
elif vars().update(match=re.match('h\w+', s)) or match:
    print('H:', match.group(0))
else:
    print('No match found')

Both append and update return None. So you have to actually check the result of your expression by using the or part in every case.
Unfortunately, this only works as long as the code resides top-level, i.e. not in a function.

A: This is what I do:
def re_match_cond (match_ref, regex, text):
    match = regex.match (text)
    del match_ref[:]
    match_ref.append (match)
    return match

if __name__ == '__main__':
    match_ref = []
    if re_match_cond (match_ref, regex_1, text):
        match = match_ref[0]
        ### ...
    elif re_match_cond (match_ref, regex_2, text):
        match = match_ref[0]
        ### ...
    elif re_match_cond (match_ref, regex_3, text):
        match = match_ref[0]
        ### ...
    else:
        ### no match
        ### ...

That is, I pass a list to the function to emulate pass-by-reference.


text:
Q: Change again the launcher logo in Android Studio 2.1.1 When I first built my Android application the launcher logo was automatically set to this:
android:icon="@mipmap/ic_launcher"

which shows the Android logo. Now I changed it (with the instruction of this link) to a flashlight picture. If I try to run my app everything is working fine and it is the right launcher logo (flashlight).
But I decided to take a new launcher logo, so I deleted the whole new folder which was created in my mipmap folder. At first, I changed the android:icon in the AndroidManifest.xml back to the ic_launcher.
But if I try to run the app again, my launcher logo is still the flashlight. But it should be the Android logo. What did I do wrong?
I followed the instruction again and tried to add a new .png file, but now not even the new mipmap-folder is created.
Is there something else I need to consider?

A: I could solve the problem by myself!

*

*I did the right-click on the app-folder

*I chose New -> Image Asset

*I checked the Image Checkbox as Asset Type and selected my desired path

BUT:
I forgot to review the Name. So ic_launcher was still selected!
That's why I got the following errors:

An icon with the same name already exists and will be overwritten.

And...

Some existing files will be overwritten by this operation. Files which replace existing files are marked red in the preview above.

So what you need to do is simply change the name of your image to something that is not flashlight or ic_launcher (i.e. flashlighttest , flashlight2 or ic_launcher2). Just make sure you will not overwrite an existing file!


text:
Q: Is "down to presentation" an idiom? And what does this line mean? I just heard this line in a movie.

"So much of fine cuisine's down to presentation, don't you think, son?"

Context is father talks to son at a dining table at breakfast, as the mother fills their plates. What does the father mean?
The script can be found here.

A: What he says is that one of the most essential parts of fine cuisine is not only how the food tastes, but also the way it looks. In other words, the success of a dish also very much depends on how it's presented to the people who are going to eat it. This is one of the numerous variations on the down to something idiom.
Example (not a perfect example, but it'll drive the point home):

Everyone else on the team has failed. It's all down to me now to win the game.

So, whether we're going to win the game now depends solely on me. I'm the deciding factor now.


text:
Q: How to debug a java system.loadlibrary error in linux? I have a Java program that is calling C code through JNI that I'm attempting to run on Linux.  The external code consists of two .so files: one for the JNI bindings (built with swig) and the other with the actual functions.  I have the two libraries in the same directory and LD_LIBRARY_PATH is set correctly.  ldd reports no problems when running from the command line, but when I set the LD_LIBRARY_PATH to the same value in the "run configurations" dialog in the Eclipse editor and attempt to execute the program, it gets the following error:
java.lang.UnsatisfiedLinkError: [path to libraries]/[JNI binding library].so: [actual code library].so: cannot open shared object file: No such file or directory
This leads me to believe that the JNI wrapper library is loaded successfully, but there is a failure when that library attempts to load the library containing the actual code.  Is there any way to debug this further?
I will further note that this problem is happening in the eclipse editor itself and that I haven't attempted to package the code into a jar and run it within a free-standing jvm instance.

A: I think the issue is with the call to System.loadLibrary(String) and using LD_LIBRARY_PATH.  Using loadLibrary("foo") will look in your java.library.path for something named libfoo.so.  If nothing named libfoo.so is found you will get this error.
Now if you just set up the LD_LIBRARY_PATH, the native symbols you want will automatically be picked up by the linker, so you don't need to set up -Djava.library.path.
In my experience with swig in the gdal project, this error is actually harmless and since the LD_LIBRARY_PATH is set up, this will work fine.
I would recommend using -Djava.library.path and calling loadLibrary explitly, the reason being that if you ever decide to deploy your app with webstart, you will explicitly need to call loadLibrary to get your native libs picked up.
When I use eclipse I follow the instructions that Daff gave where you edit the native library under the jar in the Libraries tab in the Build Path.  Just to mention again, this just sets java.library.path under the covers.

A: It may be that you just have to find the right place on the run config dialog to put the -Djava.library.path=... option. Offhand I think you want -D defines in the "vm arguments" on the arguments tab, whereas if you want to define LD_LIBRARY_PATH that goes on the environment tab.  Eclipse will merrily let you put things in places where they won't mean what you think they mean.  Anyway, I've used libraries this way before and if I get a chance I will look up what I did and edit my answer here.
Another thing to try is to play with LD_DEBUG. You can set the environment variable LD_DEBUG to various things (try ALL), and then the linux loader will divulge all sorts of useful information about what an application is trying to load, where it's looking for things, etc. Of course, this pre-supposes you launch eclipse from a command line, so you can both set the env vars and see the loader diagnostics; but as far as the system is concerned, when you run your app from inside eclipse, your app is just something eclipse is doing, so any library loading behavior can be seen in this way.

A: You could try -Djava.library.path=actual.so in command line parameters perhaps?
On windows, I had similar problems with a 3rd party library, which used a JNI wrapper DLL for its DLLs. My project had the DLL in the lib directory so I added lib to the PATH (e.g. PATH=%PATH%;./lib environment variable and everything started working.

A: As far as I know the Eclipse doesn't use the LD_LIBRARY_PATH.
The easiest way to set up the right native library path is to go to
Project properties -> Java Build Path -> Libraries
Then expand either the JRE System Library entry or (if available) the
Jar File that uses you native Library,
choose "Native Library Location" then click "Edit..." and choose the folder your libraries are in. Actually it does set the -Djava.library.path variable so you have to include this in your command line if you start your program from outside eclipse.

A: Are there any other libraries that your two libraries depend on?  If so, you need to make sure they are also accessible to the JVM.
Be aware, manually setting "-Djava.library.path" seems to erase the default library path.
So with the following code:
public class LibTest {
    public static void main(String[] args) {
        String property = System.getProperty("java.library.path");
        StringTokenizer parser = new StringTokenizer(property, ":");
        while (parser.hasMoreTokens()) {
            System.err.println(parser.nextToken());
        }
    }
}

Launched from eclipse with Java 1.6.0_14 outputs:
/opt/java/jre/lib/i386/client
/opt/java/jre/lib/i386
/opt/java/jre/../lib/i386
/opt/java/jre/lib/i386/client
/opt/java/jre/lib/i386
/usr/lib/xulrunner-devel-1.9.0.11
/usr/lib/xulrunner-devel-1.9.0.11
/usr/java/packages/lib/i386
/lib
/usr/lib

But when I set the JVM arg "-Djava.library.path=/tmp/" I only get:
/tmp/

If you are manually setting java.library.path this may explain why ldd works from the command line but your .so does not from eclipse/java.
You can try not setting java.library.path and use System.load with the absolute path to your library instead of calling System.loadLibrary.  This may allow the JVM to find your .so and still use the default path when searching for its dependencies.
Of course, if this is no use then you can also try turning on jni debug output with "-verbose:jni" on the command line.  This may give you some clues to the problem.

A: Yes the LD_LIBRARY_PATH worked for me

A: Adding this answer may be it can be useful In AIX Machines we need to setup LIBPATH environment variable instead of LD_LIBRARY_PATH.


text:
Q: Calculation of the weak coupling constant There are two ways to calculate the coupling constant of the weak interaction $g$.
1) From the electromagnetic coupling constant and the weak mixing angle, using the relation
$${\sf e} = g\sin(\theta_W)$$
where ${\sf e}=\sqrt{4\pi\alpha}$ is the elementary electric charge in natural units ($\alpha$ being the fine structure constant). Using the CODATA values of $\sin^2(\theta_W)=0.2223$ and $\alpha=7.297\cdot 10^{-3}$ this gives
$$g=0.641.$$
2) From the definition of the Fermi coupling constant
$$G_F = \frac{\sqrt{2}}{8}\frac{g^2}{m_W^2}$$
where $m_W$ is the mass of the W boson. Using the CODATA value of $G_F=1.166\cdot 10^{-5}\;{\rm GeV}^{-2}$ and the PDG value of $m_W=80.385\;{\rm GeV}$ this gives
$$g=0.653.$$
The difference is not big but nonetheless is significant. How can this be explained, since all the parameters used in the calculation are known with high precision?

A: Thank you @Cosmas Zachos for your reference to PDG review. Indeed the explanation after Table 10.2 is very useful. Actually, I used in the above calculation the so-called "on shell scheme" for the value of $\theta_W$; the caveat is that in the definition of $G_F$ the radiative corrections are not accounted for.
If one includes the radiative corrections $\frac{1}{\sqrt{1-\Delta r}}$ where $\Delta r=0.03648$ (as stated in the PDG review), one finds $1.019=\frac{0.653}{0.641}$, i.e. the ratio between the two calculated values of $g$. So, the difference is due to not taking in account the radiative corrections for $G_F$. Unluckily, this is not made also when stating the Higgs field vacuum expectation value $\upsilon=246.2\;\rm{GeV}$.
This same issue is addressed in the book "Quantum field theory and the Standard Model" by Matthew D. Schwartz (see (29.17) p. 588 for the calculation of $g$,  (29.75) p. 604 for the calculation of $\upsilon$, (31.3) p. 642 for the radiative corrections of $G_F$).
Alas, when speaking about QFT results, one has always to ask which renormalization scheme is being considered.

A: Given you used multiple sources and parameters, the discrepancy likely stems from this. Recall that say $G_F$, would have been determined from scattering processes at some scale, say $\mu_1$.
Now, $\alpha$ could have been evaluated from entirely different experiments, at some scale $\mu_2$. The values calculated from each, $g(\mu_1)$ and $g(\mu_2)$ must differ due to the renormalisation group flow.
We have something like,
$$\frac{\mathrm dg}{\mathrm d \log \mu} = -\frac{(22 - n_f-n_s)g^3}{48\pi^2} + \mathcal O (g^5)$$
where $n_f$ is the number of chiral fermions and $n_s$ the number of scalars. The point is though, regardless of the beta function's form, since $\beta \neq 0$, the couplings determined at different scales will necessarily have different values. It's not to do with precision but rather you've calculated two different but related quantites, despite both being "$g$".
Regardless, stay in the habit of propagating uncertainties. Sometimes a calculation should have two things agreeing, but within some margin of error

A: As far as I know, the coupling constant of the weak force is much smaller than all the above. It should be at 10^-7. According to my calculations: α_W  = 1.016 × 10^(-7). Less precise calculations yield: 2.739 × 10^(-7).
Reference:
http://hyperphysics.phy-astr.gsu.edu/hbase/Forces/couple.html


text:
Q: Yii controller setup with multiple conditions In Yii crud, I've setup a Model, View, and Controller based on my db table called Form. I've modified the controller and views to my liking thus far:
index.php/form/all (index)
index.php/form/new (create)
index.php/form/2 (view)
index.php/form/2/edit (edit)
index.php/form/2/delete (delete)

Now I'd like to setup some subpages that will be dynamic. The url patterns are below. How do I set this up inside of the FormController.php?
index.php/form/2/fields/all
index.php/form/2/fields/new
index.php/form/2/fields/1/edit
index.php/form/2/fields/1/delete

BTW - Fields is a separate db table with a separate yii model. Though I'd like to not create a controller for it if I don't need to.

A: Thanks Neophile, I ended up adding a fields controller. Here is a link to my finished solution: Yii URLManager rule for multiple controller action parameters


text:
Q: Delay from OSX "installer" I have the following script to install a Mac package from terminal:
#!/bin/sh
if [ -d /Applications/XX.app ]; then
    hdiutil mount XX.dmg
    cd /Volumes/XX
    sudo installer -pkg XX.pkg -target /
    cd ..
    hdiutil unmount XX
fi

Sometimes it works fine, but sometimes it ended up with error:
hdiutil: unmount: "XX" failed to unmount due to error 49168.
hdiutil: unmount failed - Resource busy

Actually, after several seconds, XX becomes unmountable. I realize that this may be due to a delay from "installer", which was not done yet when calling "unmount XX". Is there anyway to synchronize between "installer" and "unmount"?

A: I went through the "installer" command manual and not found a direct solution to
avoid this synchronizing issue.
The solution I came up with is that, after stepping out of "installer", I
will keep query the status from "hdiutil unmount" every other second until
a normal termination signal is achieved, i.e.:
#!/bin/sh
if [ ! -d /Applications/XX.app ]; then
    hdiutil mount XX.dmg
    cd /Volumes/XX
    sudo installer -pkg XX.pkg -target /
    cd ..
    flag=1
    while [ $flag -ne 0 ]
        do
            sleep 1
            hdiutil unmount XX
            flag=$?
        done
fi

I know this may not be the best solution, and I look forward to more elegant alternatives.


text:
Q: Cloudflare + Heroku with custom domain I have a Heroku app and connected Cloudflare. As I know, there is no way to remove a default Heroku domain (app.herokuapp.com), so I forward all requests with Host 'app.herokuapp.com' to 'mydomain.com'. But will Cloudflare secure me from attacks straight to a Heroku domain? If no, is it a way to remove default domain or hide it somehow?

A: You are correct at all points. I am giving you the easy ways for basic offloading of attacks. All methods are towards 301 redirect and/or packet forwarding.

But will Cloudflare secure me from attacks straight to a Heroku
  domain?

Cloudflare has a service which they say CNAME flattening. Few years back, it was dnsmadeeasy who discovered A Name. They are not RFC standardised. Many other DNS service has such things. Basic principle is easy. If app URL is my-ugly-url.herokuapp.com & your custom domain is my-custom.com then with  which you can set :
 | my-custom.com |
 @ my-ugly-url.herokuapp.com ( ANAME or ALIAS )
 app.my-custom.com CNAME my-ugly-url.herokuapp.com
 www.my-custom.com CNAME my-ugly-url.herokuapp.com

Then do 301 redirection at application's web server config, app.my-custom.com will redirect to my-ugly-url.herokuapp.com. Requests toward my-ugly-url.herokuapp.com will be forwarded to my-custom.com by dnsmadeeasy. There are probably more such DNS services now. Yes, chance of running attack over both domain in parallel is remaining. But also my-ugly-url.herokuapp.com get exposed on DNS record.

If no, is it a way to remove default domain or hide it somehow?

Officially 301 redirection, packet forwarding is also possible. There are ways to have dedicated IP and forward TCP packets. They have 3 types of add-ons --

*

*/addons/proximo.

*/addons/fixie.

*/addons/quotaguardstatic.

They are not always easy at application level but probably safer than having such naked subdomain open to all. PaaS is facing increasing DDoS now. That is different matter.


text:
Q: Accessing session data from a layout In my ASP.NET MVC solution I have a number of services.
One of them, SessionService, is used to access the currently selected region and time span.
I want to display those in a layout used to decorate views. What is the best design approach to access those values which are stored in the SessionService?
Right now I'm thinking about using calling a ChildAction from the layout which in turn calls the session service:
_Layout -> aController.ChildAction() -> SessionService.GetRegion()

Is it a good approach or can you recommend anything better?
UPDATE 1:
Other options for passing the values that are possible:

*

*via ViewBag

*via ViewModels

However the drawback for these options is the fact that it would be necessary to populate them in each and every action method which would lead to duplication of code (which could be mitigated by means of a filter, but again this will require decorating controllers with the filter).
UPDATE 2 (born in the discussion with O:rvar below):
Another option is to create a base controller which will be populating ViewBag properties upon creation. All other controllers should derive from it.

A: You should be able to access you session data in the view with the following code:
var region = @Session["Region"].ToString();

Or you could call the controller method as you mentioned with an ajax call and get the session data that way. Using the childaction approach is also a fine way of accomplishing what you want.


text:
Q: How to pass for example firebase login data to vuejs Almost every tutorial is creating a firebase.js file where they store the api key, url etc. to access the real time database for example.
When opening the app in the browser tho this data is also readable for everyone. How do i do this securely? I tried a .env file with process.env.MY_VAR - but this did not work, Neither on build or local run.


text:
Q: Non repeating series of non repeating numbers I will try to describe my problem as good as i can, since it's my first time here :)
So, i have to write a program in C++ wich as you may or may not guessed from the title, prints to screen a serie of random numbers that do not repeat either in the numbers themself and the serie.
I have 4 "slots" to fill with the serie of numbers. And the numbers can randomize from 0 to 4 (wich cannot repeat).
What i mean to do is this:
SLOT 1: 1 3 2 4
SLOT 2: 3 1 4 2       <----- As you can see, they do not repeat horizontally, nor vertically
SLOT 3: 2 4 3 1
SLOT 4: 4 2 1 3
This is the code i've came up with, until i got stuck (it is a preety ugly code, i know)
    void MC_Slot_Rand()
{
    text.setDefaultColor("white");//don't mind this
    srand((unsigned)time(NULL));
    int n1;
    int n2;
    int n3;
    int n4;
    int number;
    int slotN = 0;
    int slotN_2 = 1;
        while (slotN < dim)
        {
            color.red();//don't mind this
            cout << "SLOT " << slotN_2 << ":  ";
            color.white();//don't mind this either
            n1 = 1;//RESET
                   //for some reason, if i don't put 1
                   // the program repeats the numbers
            n2, n3, n4 = 10;//RESET
            do
            {
                number = rand() % 4;
            } while (number == n1);
            n1 = number;

            do
            {
                number = rand() % 4;
            } while (number == n1);
            n2 = number;

            do
            {
                number = rand() % 4;
            } while (number == n1 || number == n2);
            n3 = number;

            do
            {
                number = rand() % 4;
            } while (number == n1 || number == n2 || number == n3);
            n4 = number;

            //cout << n1 << n2 << n3 << n4;//debug
            MC_ENUM(n1);
            MC_ENUM(n2);//this function simply takes the number and
                        //transforms it into a letter using a switch statement
                        // example: 0 = A, 1 = B, etcetera...

            MC_ENUM(n3);
            MC_ENUM(n4);
            ut.spacer(3);//this function does cout<<endl; as many times
                         //as the number specifies
            slotN++;
            slotN_2++;

        }

}//END OF FUNCTION

What this piece of code does, is simply printing 4 series of non repeating numbers, BUT the numbers repeat vertically! And of course i don't want that to happen.
I hope someone more experienced than me out there can help me :)
Very important: If you want to try this code, cancel the lines commented with don't mind this, MC_ENUM(); functions and also ut.spacer(); as they are part of a library of mine and won't work with you :P
Thanks for your time.

A: Here's what you can do:
When you need the numbers to be unique, rather than generating random numbers, what you do is generate an array of all the unique numbers you want. In this case it's an array of length 4 with the values [1,2,3,4].
Now, shuffle the array randomly using a known good shuffling algorithm that guarantees near-equal opportunity to all permutations. If you want to prevent a certain digit from appearing in the same index, you can easily add a rule in the shuffle that requires unique placement for each shuffled digit.
Here's yet another approach: this approach is particularly good for small lengths. Generate all possible permutations and then pick a permutation at random. To uphold your additional requirement you simply disregard the non-fitting permutations. A clear advantage to this method is that it is entirely deterministic.

A: As I understand it, what you're doing is producing a randomised vector of all permutations of the numbers 1-4.
Fortunately the answer is in the standard library:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool column_match(const vector<int>& v1, const vector<int>& v2)
{
    auto N = std::min(v1.size(), v2.size());
    for (size_t i = 0 ; i < N ; ++i) {
        if (v1[i] == v2[i])
            return true;
    }
    return false;
}

int main()
{
    vector<int> nums = { 1, 2, 3, 4 };

    vector<vector<int>> series;
    do {
        series.push_back(nums);
    } while (next_permutation(begin(nums), end(nums)));

    random_shuffle(begin(series), end(series));

    vector<vector<int>> result;
    copy_if(begin(series), end(series), back_inserter(result), [&](const auto& candidate){
        return !any_of(begin(result), end(result), [&](const auto& check){
            return column_match(candidate, check);
        });
    });

    for (const auto& s : result) {
        copy(begin(s), end(s), ostream_iterator<int>(cout, ","));
        cout << endl;
    }

    return 0;
}

example output:
4,3,1,2,
3,2,4,1,
1,4,2,3,
2,1,3,4,
Program ended with exit code: 0

A: I think you shoud do it like this and this is my thought
fistly,you should define arry like a[4][4],when it produces a number you store the num in arry,then the next numbet is produced,compare it to others in this line horizontally,if it repeats and produce next,if not and store it
when the first line is done,in the second line when produce a number you not only compare it to this line horizontally but also to other lines vertically
like this one line by on line,you will make it.

A: You can cheat.  You already have one solution in your question:
1 3 2 4
3 1 4 2
2 4 3 1
4 2 1 3

You can use that solution to generate others.  First, convert that solution to letters:
A C B D
C A D B
B D C A
D B A C

Second, pick a random mapping from the four letters, A, B, C, D to the four digits, 1, 2, 3, 4.  Replace the letters in your grid with the corresponding digit from your mapping.  That will give a solution.
For further possible solutions, you can exchange columns in your grid or exchange rows in your grid, though some of the resulting grids may be disallowed.  You will need to check things more carefully if you do that.


text:
Q: Find the value of the constant k on a certain pdf I'm trying to understand a problem that ask for the following:
Given a random variable $X$ that has a pdf $f(x)= k(1-x)^{\frac1\theta-1}$, for x between 0 and 1, find the value of $k$ in function of θ (i'm translating from spanish, I hope it's like this). $\theta$ is a distribution parameter that's always larger than $0$.
I don't understand what the question is asking me to do, ¿could you help me see what I need to do, or maybe show me the first steps?

A: We use one property of a probability density function. The integral between $0$ and $1$ must be $1$, since $f(x)=0$ for $x<0,x>1$.
See here for the properties of a probability density function.
$$k\cdot \int_0^1 (1-x)^{\frac1\theta-1}  \, dx=1$$
We can substitute $\frac1\theta-1$ by constant $c$
$$k\cdot \int_0^1 (1-x)^c  \, dx=1$$
And the antiderivative of $(1-x)^c$ is
$-\frac{1}{c+1}\cdot (1-x)^{c+1}$
Can you proceed?

A: You have to find $k$ such that $f$ is a pdf. In fact, you have to choose $k$ such that $\displaystyle \int_0^1 f(x)dx =1$. Hence, $\displaystyle k = \dfrac{1}{\int_0^1 (1-x)^{\frac{1}{\theta}-1}dx}$.


text:
Q: Catch StatusCode from execution value in Xunit I want to compare the return value from controller execution whether that fulfill the condition or not. From debugging I noticed the 'StatusCode' but not got an way to catch that value for comparing. My Code for testing is
    public void PostAmount_Withdraw_Returns_Null()
    {
        // Arrange
        Amount amount = new Amount() { Id = 0, PaymentDate = DateTime.Today,
             PaymentTypeId = 3, PaymentAmount = 500, ClientId = 1, Balance = 0 };

        _accountServiceMock.Setup(s => s.Withdraw(amount)).Throws(new Exception());

        var target = SetupAmountsController();

        //Act
        var actual = target.PostAmount(amount);

        //Assert

        actual.ShouldNotBeNull();
        //actual.Value.ShouldBe(response);
    }

What call controller methods below : -
    public ActionResult<Amount> PostAmount(Amount amount)
    {
        try
        {
            if (amount.PaymentTypeId == 1)
            {
                _accountService.Deposit(amount);
            }
            else if (amount.PaymentTypeId == 2)
            {
                _accountService.Withdraw(amount);
            }
            else
            {
                return Problem("Model 'Amounts'  is null.");
            }
            return new OkObjectResult(new { Message = "Payment Success!" });
        }
        catch (DbUpdateConcurrencyException)
        {
            return Problem("There was error for updating model Payment");
        }
    }

And, returned the value after execution from Unit Test

I want to give condition likes below: -
 actual.Result.StatusCode = HttpStatusCode.BadRequest or
 actual.Result.StatusCode = 500

A: Just got the answer. It will be likes below: -
 (actual.Result as ObjectResult).StatusCode.ShouldBe((int)HttpStatusCode.InternalServerError);

you need to define here 'status code' what want to compare. In my case it was 500.