text:
Q: How do you free a 2D malloc'd array in C? I'm creating a 2D Array in C; am I freeing it correctly?
// create
int n = 3;
int (*X)[n] = malloc(sizeof(int[n][n]));

// set to 0
for(int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        X[i][j] = 0;
    }
}

// is this all I need?
free(X);

A: You must call free once for each malloc. Your code has one malloc and one free  (with the same address) so it is correct.

A: For every malloc(), there must be a matching free(). So if you call malloc() in a loop, there must be a similar loop later on that calls free() just as many times. Your code has one malloc() and one corresponding free(), so yes, you have freed everything you need to.
The most common way I've seen to allocate a two-dimensional array is to do something like:
int **arr = malloc(sizeof (int *) * num_rows);

for (i = 0; i < num_rows; ++i)
        arr[i] = malloc(sizeof (int) * num_cols);
/*
  * Using `sizeof *arr` and `sizeof **arr`
  * respectively would have been more safe,
  * but for the purpose of this example, I think
  * using `int *` and `int` is simpler to
  * understand.
  */

then later to free:
for (i = 0; i < num_rows; ++i)
        free(arr[i]);

free(arr);

This makes the outer dimension hold num_row pointers to pointers to int (each of the num_row pointers points to the starting address of the 'column'). So each element in the outer dimension points to a row, and in each row there are num_cols elements in the inner dimension (the 'columns'), which is just a group of num_cols integers. Does this make sense to you? So you have to allocate num_rows integer pointers, and each one of these points to the first 'column' of that row--for each row you have to allocate space for num_cols integers, so you can see the loop will make a total of num_rows * num cols integers, and they way they are allocated allows you to use array indexing notation (two-dimensional in this case--each element in the outer dimension points to the start of a 'row', which contains a pointer to the start of a 'column', hence the double pointer) to access the elements. I know this is probably confusing, that is why I tried to describe it so many different times/ways, but please just ask any questions, especially about what you don't understand in particular, and I will be more than happy to work with you in helping understand it.
I'm not saying you have to create your 2-D array this way; your way works fine too, I just wanted to show you this way since you are likely to run into it since it's very common.
Also, look into Valgrind. You can use that tool to see if you have forgotten any free()s / have an unmatched malloc(), and lets you know if there is any allocated memory unreachable/leaked (maybe the pointer was changed before the call to free() so the call doesn't properly free the memory and you get a leak).

A: RastaJedi - another couple of things to note:
After a call to free(), it's a good idea to set the free'd variable to NULL, which helps prevent use after free.
Also, if you malloc in one block of code, then free in some called function, and then return from that function, sometimes C forgets about the final free (in your example, free(arr)  ), and you should set the variable to NULL upon return.
I came here, and verified that the malloc and free calls that I wrote in the code I'm working on are indeed exactly as your "common" way, but kept running into a Seg Fault, because I was using malloc from in main, free-ing from a helper function which received the double-indirect head of the array.  Having that all wrapped in a while-loop for user interaction, a second pass around was checking the array head for NULL-ness, but not seeing it as NULL, despite explicitly setting to NULL inside the helper function.  Crawling thru the code with a debugger is how I identified the behavior, and why I came looking.
After being free'd, the memory is available, and variously (and randomly) reassigned; when the function with the free() calls returns, the memory that was allocated has been released, however it seems that the calling code still holds a pointer to that place in memory.  There then exists a possible race-condition; by the time the calling code regains control, there's no guarantee as regards the location pointed to by the variable used for the array head, and therefore it's a very good idea to set the variable to NULL after the function returns.
Although you can use malloc'd pointers for pass-by-reference behavior, after a call to free() inside some function, the by-reference behavior breaks (because the thing being referenced is what has been free'd).
So, thank you for your answer, which confirmed that I was looking at the wrong part of my problem - just figured maybe someone else may stumble here, and possibly have the same issue I did.


text:
Q: If I have all of the Google Geocoding data for multiple addresses, how do I calculate their proximity? I have multiple addresses recorded in my database and I've used the Google Geocoding service to get their longitude, latitude, etc.
What do I need to do to calculate the proximity of one address from another in miles?
Ideally I want to show an entry and then say below it: "The following recorded addresses are close by."

A: see http://www.movable-type.co.uk/scripts/latlong.html for example.
In meter:
D_AB = 6378137 * acos( cos(PI/ 180 * latA) * cos(PI/ 180 * lngA) *
  cos(PI/ 180 * latB) * cos(PI/ 180 * lngB) + cos(PI/ 180 * latA) *
  sin(PI/ 180 * lngA) * cos(PI/ 180 * latB) * sin(PI/ 180 * lngB) +
  sin(PI/ 180 * latA) * sin(PI/ 180 * latB))

A: There are several algorithms that convert latitude/longitude coordinates to distance in miles.
Refer to:
http://www.meridianworlddata.com/Distance-Calculation.asp
I tested all of them, and if you are really worried about performance, you can use:
sqrt(x * x + y * y)

where x = 69.1 * (lat2 - lat1)
and y = 53.0 * (lon2 - lon1)

Which is a good enough approximation.
Related: PHP MySql and geolocation

A: If all you are worried about is proximity then Manhattan distance may be sufficient.
boolean isProximate ( double latE , double longE )
{
      return ( ( Math . abs  ( latA - latB ) < latE ) && ( Math . abs ( longA - longB ) < longE ) ) ;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Turning Milliseconds in Hours without DATETIME I am running into trouble with SQL code for SQLite. It is a small homework problem I have gotten mostly figured out, but can't find the correct answer for converting an INT to something I can use ROUND with.
{sql connection=dbcon}
SELECT
    genres.Name,
    ROUND(SUM(CAST(Milliseconds AS DECIMAL(5, 2))) / 3600000, 2) AS 'Hours'
FROM
    genres
LEFT JOIN
    tracks ON genres.GenreId = tracks.GenreId
GROUP BY
    genres.GenreId

This code returns the answer of genres and their total summed track time. But it is required to get the time in hours rounded to 2 decimal points. My use of CAST is not flagged but ignored. Any help in understanding why would be appreciated. Thank you!
Edit: here are the query results

A: Actually, CAST(Milliseconds AS DECIMAL(5, 2)) does not cast Milliseconds to a floating point number (there is no DECIMAL data type in SQLite), so the result is an integer and the division performed afterwards will be an integer division which will truncate the result to an integer and ROUND() will do nothing.
Instead you should cast to REAL.
You can see this behavior here.
So, change to this:
ROUND(SUM(CAST(Milliseconds AS REAL)) / 3600000, 2) AS Hours

or:
ROUND(CAST(SUM(Milliseconds) AS REAL) / 3600000, 2) AS Hours

or, with an implicit conversion:
ROUND(SUM(Milliseconds) / 3600000.0, 2) AS Hours


text:
Q: Tree View Checkbox Expand collapse Am trying to add expand collapse effect , but its not working :(
Here is my fiddle

http://jsfiddle.net/Pervez/udc8f/6/
EDIT:
I also want to place these 'li' side by side in two column

A: *

*Your id='chk_7'' have an extra '.  You could see it clearly in the jsfiddle syntax highlighting.

*You better wrap the checkbox inside the label (will make label clicks work as checkbox clicks)

*It works a bit better but only when you click the
 not the checkbox.

There were several other small bugs, and some bugs remaining. You better practice debugging (ie. setting breakpoints, stepping the code, etc.). I changed it to handle checkbox clicks and few fixes here: http://jsfiddle.net/jjfaB/4/. Its still not perfect but you should be doing your own debugging...

A: here is a simple example of tree view I've made for you. It basically shows you to organize your code. If you cannot see it clearly, how can you manipulate it.
Super simple implementation
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta charset="utf-8" />
      <title></title>
      <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

        *<input type="checkbox" value="" />

<input type="checkbox" value="" class="child"/>

<input type="checkbox" value="" class="child"/>

<input type="checkbox" value="" class="child"/>

        *<input type="checkbox" value="" />

<input type="checkbox" value="" class="child"/>

<input type="checkbox" value="" class="child"/>

you can enhance to n-levels of node, animation, Id wise retrieval,
different color at each level and what not..

A: I have usedjstree for one of my project. http://luban.danse.us/jazzclub/javascripts/jquery/jsTree/reference/_examples/4_themes.html  ..check if it helps for you.


text:
Q: How to let dnsmasq transfer a reverse zone? Following the documentation for auth-zone, I tried to declare my dnsmasq server as authoritative for the 10.0.0.0/8 zone (I serve several IP sub-ranges in 10.x).
Unfortunately, whatever I try I end up with
Sep 07 14:37:36 bind named[6812]: transfer of '10.in-addr.arpa/IN' from 10.100.10.254#53: connected using 10.200.0.158#57941
Sep 07 14:37:36 bind named[6812]: transfer of '10.in-addr.arpa/IN' from 10.100.10.254#53: failed while receiving responses: SERVFAIL
Sep 07 14:37:36 bind named[6812]: transfer of '10.in-addr.arpa/IN' from 10.100.10.254#53: Transfer status: SERVFAIL
Sep 07 14:37:36 bind named[6812]: transfer of '10.in-addr.arpa/IN' from 10.100.10.254#53: Transfer completed: 0 messages, 0 records, 0 bytes, 0.001 secs (0 bytes/sec)

on the secondary BIND server (the direct zones are transferred OK).
How should I set this up?
The whole current configuration file for dnsmasq:
no-resolv
no-poll
server=1.1.1.1
server=8.8.4.4
expand-hosts
domain=example.com
domain-needed

auth-server=example.com,lan0,br0
auth-zone=example.com,10.0.0.0/8,lan0,br0
auth-sec-servers=rpi1,bind

dhcp-range=10.100.10.1,10.100.10.230,240h
dhcp-range=10.100.20.1,10.100.20.230,240h
(... more DHCP ranges ...)
dhcp-option=option:ntp-server,129.104.30.42,195.220.194.193
dhcp-option=option:dns-server,10.100.10.30,10.200.0.158
dhcp-authoritative

The config of the secondary BIND server:
zone "example.com" {
  type slave;
  masters { 10.100.10.254; };
  file "/etc/bind/db.example.com";
};

zone "10.in-addr.arpa" {
  type slave;
  masters { 10.100.10.254; };
  file "/etc/bind/db.10";
};

A: CLEANUP EDIT with PROPOSED PATCH
This is not possible yet so I have created a fork to stand as a proposed patch to Simon Kelley's official repository to address this. Please try it out!
Currently, while dnsmasq creates and serves individually the necessary PTR records, and delivers the correct SOA and IN records for 0.0.0.in-addr.arpa, given the line:
auth-zone=example.com,10.0.0.0/8,lan0,br0
it simply will not transfer a full zone.
If you declare auth-zone=0.0.10.in-addr.arpa that will output a garbled zone.
Note in the man page:
Note that at present, reverse (in-addr.arpa and ip6.arpa) zones are
not available in zone transfers, so there is no point arranging
secondary servers for reverse lookups.


text:
Q: Inserting extra item 2A in HTML
* I'm sure this must have been asked before, but I cannot locate it.
I'd like to create an ordered list in which the items are numbered 1, 2, 2A, 3, 4, ….  I have no choice on the numbering as it must conform to a published standard which inserted 2A to correct an omission in an earlier version without renumbering.
Obviously I can use a
 and put all the numbers in by hand, and absent a better solution I'll do that; but it feels wrong.  I cannot do
 as the attribute must be a number, and testing in Firefox 37 the "A" is ignored.  I've tried using li::before { content: '2A' } in CSS, but evidently Firefox doesn't use that to generate the marker as the CSS 3 Lists draft says.
Any suggestions?  I don't mind a solution that only works in relatively modern browsers.

A: You can try not to rely on the list-style-property but on the CSS counter-increment-property. It could look like this:

ol {list-style-type: none; counter-reset: section;}
li:before {
    display: inline-block;
    width: 2em;
    text-align: right;
    margin-right: 1em;
    counter-increment: section;
    content: counter(section) ". ";
}
li.special:before {
    counter-increment: none;
    content: counter(section) "A. ";
}

Thing 1

Thing 2

Thing 2 old

Thing 3

You will have to apply the .special-classes manually though and maybe need some more for "B" or "C". But maybe this is worth a shot.


text:
Q: Create iOS 7 UIButton With Text And Image Using Autolayout Using Autolayout and Interface Builder with the target device being iOS 7 iPhones, how do I create three of these kind of UIButtons that have an image, a divider line and text? The 3 images for each of the buttons all have the same size. The lines and text in one button must line up  with the other buttons' line and text (left align the text). Things can't go crazy if the phone is turned to landscape. All buttons are the same constant size.

The buttons are part of a home screen layout which has a logo at the top and so on. When one taps one of the buttons, the app does something.
One thought was to create a button with no text, put a label on top, a thin view for the line on top, and the uiimageview on top. Maybe explicit layout constraints are not even needed? Maybe a containing view is needed for the "button" contents to keep the "button" pieces together?

A: Image+text can be achieved using UIButton only without adding any autolayout constraints. You set both image and text using -setImage:forState and -setTitle:forState:, and then adjust button insets using *Insets properties. To set the insets properly, play with this great test project: https://github.com/jrturton/ButtonInsets (it's not quite clear from the docs how to use them simultaneously, and this test app should give you the idea).
As for the separator, I'd recommend adding it directly to your images.
But if you don't want to stick to the UIButton and its insets, you can subclass UIView, add 2 UIImageViews (the actual image and the separator), a UILabel, and throw in a couple of constraints. To make the view clickable, you attach a UITapGestureRecognizer to it.


text:
Q: How to setState without using .bind(this) in react-native? I have no idea How to set state.
Below is my code...
import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight, AsyncStorage, ListView } from 'react-native';

export default class App extends React.Component {

    constructor(){
        super();
        this.state = {
            myLeader: 'Joe',
        };
    }

    setMyLeader(name){
        this.setState({
            myLeader: name
        });
    }

    render() {
        return (
            <View>
                <TouchableHighlight

                    style={{padding: 30}}
                    onPress={this.setState(myLeader: 'xxx')}
                >
                    <Text>foo</Text>
                </TouchableHighlight>
            </View>
        );
    }
}

error message is this. 'Can't find variable: myLeader'
How to fix this problem?

A: Inside your onPress function you can:
a) directly set the state
onPress={() => this.setState({ myLeader: 'xxx' })}

b) call your setLeader function
onPress={() => this.setMyLeader('xxx')}


text:
Q: Função que retorna outras funções Tenho três métodos sendo chamados separadamente no controller com JSON. Cada uma delas me retorna Id Name.
Preciso chamar esses três métodos numa mesma função no controller. Como posso juntar os três métodos na mesma função?
[HttpPost]
public ActionResult GetMessageClassByResourceByDevice(int resourceId, string deviceName)
{
    return  Json(EventFlow.GetMessageClassByResourceByDevice(resourceId, deviceName)
        .Select(f => new { EventMessageClassId = f.Id, FullName = f.Name }));

}

[HttpPost]
public ActionResult GetMessageGroupByResourceByDevice(int resourceId, string deviceName)
{
    return Json(EventFlow.GetMessageGroupByResourceByDevice(resourceId, deviceName)
        .Select(f => new { EventMessageGroupId = f.Id, FullName = f.Name }));

}

[HttpPost]
public ActionResult GetMessageByResourceByDevice(int resourceId, string deviceName)
{
    return Json(EventFlow.GetMessageByResourceByDevice(resourceId, deviceName)
        .Select(f => new { EventMessageId = f.Id, FullName = f.Name }));
}

A: Se você quer retornar a lista do conteúdo dos três retornos dos métodos, pode fazer o seguinte:
[HttpPost]
public ActionResult GetMessageClass(int resourceId, string deviceName)
{
  var list = new List<dynamic>();

  list.Add((dynamic)GetMessageClassByResourceByDevice(resourceId, deviceName).Data);
  list.Add((dynamic)GetMessageGroupByResourceByDevice(resourceId, deviceName).Data);
  list.Add((dynamic)GetMessageByResourceByDevice(resourceId, deviceName).Data);

  return Json(list);
}

Se você quiser retornar o primeiro dos retornos não nulos, pode fazer o seguinte:
[HttpPost]
public ActionResult GetMessageClass(int resourceId, string deviceName)
{
  var ret = (dynamic)GetMessageClassByResourceByDevice(resourceId, deviceName).Data;
  if (ret != null) {
    ret = (dynamic)GetMessageGroupByResourceByDevice(resourceId, deviceName).Data;
  }
  else if (ret != null) {
    ret = (dynamic)GetMessageByResourceByDevice(resourceId, deviceName).Data;
  }

  return Json(ret);
}


text:
Q: ¿Cómo añadir espacio vertical entre elemeentos en div? CSS Dispongo de un inventario de accesorios en mi web.
Deseo agruparlos todos ellos en un div (grupal), y que a su vez contengan otro div (individual). Dentro de cada div (individual), insertar la imagen de cada accesorio junto con su nombre y un checkbox al lado. Preferiblemente he decidido -ordenarlos- de 3 en 3, otorgándoles a cada uno de ellos "30%" y que floten a la izquierda.

Ver imagen:

Hasta aquí todo correcto.
Ahora la duda/pregunta: ¿cómo puedo añadir un espacio vertical, creo que se deberá utilizar "padding" para separar los elementos de una fila y otra fila?
Añado el código:

Accesorios

    <?php
        $objeto_accesorios = BD::obtenerAccesoriosPorCabana($_REQUEST["idcabana"]);
        $todos_accesorios = BD::todosAccesorios();
        foreach($todos_accesorios as $objeto){
            $existe = false;
            foreach($objeto_accesorios as $columna){
                //Si el accesorio global está en el accesorio de la cabaña, true.
                if($objeto->getIdaccesorio() == $columna->getIdaccesorio()){
                    $existe = true;
                    break;
                }
            }
            if($existe){
                echo "
getDescripcion().".png' height='28px' width='34px' title='".$objeto->getDescripcion()."'/>
getIdaccesorio()."'><input type='checkbox' value='".$objeto->getIdaccesorio()."' id='accesorio".$objeto->getIdaccesorio()."' name='accesorios[]' checked>".$objeto->getDescripcion()."
";
            }else{
                echo "
getDescripcion().".png' height='28px' width='34px' title='".$objeto->getDescripcion()."'/>
getIdaccesorio()."'><input type='checkbox' value='".$objeto->getIdaccesorio()."' id='accesorio".$objeto->getIdaccesorio()."' name='accesorios[]'>".$objeto->getDescripcion()."
";
            }
            $existe = false;
        }
    ?>

A: Lo único que debes hacer es agregarle a los div un margin-bottom:
echo "
getDescripcion().".png' height='28px' width='34px' title='".$objeto->getDescripcion()."'/>
getIdaccesorio()."'><input type='checkbox' value='".$objeto->getIdaccesorio()."' id='accesorio".$objeto->getIdaccesorio()."' name='accesorios[]'>".$objeto->getDescripcion()."
";

Ejemplo funcional

.caja{
  float: left;
  width: calc(30% - 20px);
  height: 150px;
  background: black;
  margin-left: 10px;
  margin-right: 10px;
  margin-bottom: 20px;
}

.caja:nth-child(2n){
  background: chocolate;
}

.caja:nth-child(2n + 1){
  background: green;
}

A:

      #div1, #div2, #div3 {background-color: #f4f4f4; margin: 5px; width: 50px; height: 80px;}
        #div2 {margin-top: 0px; margin-bottom: 0px; !important
<!DOCTYPE>

    <title>Divs with Margins</title>

Eso quiza puedas hacerlo con el elemento 'margin' del css. Te dejo un ejemplo donde están separados por 5px tanto arriba como abajo, a excepción del div2 que solo posee margin a los lados.
Aunque veo que ya hay una respuesta mejor que la mía


text:
Q: Monitor versus T.V I am looking to upgrade my computer system and am looking for a new "screen". I want to use it both as an extra screen for my computer and as a tv(direct cable, not streaming through internet). Should I be looking for Tv with monitor capabilities or a monitor with tv capabilities? What are the major differences?
Note: My computer does have a blue ray player if that makes a difference.
Any suggestions?

A: The question is more about resolution and pixel size.  TVs tend to be optimized for the 8-10' experience, so they have larger pixels and lower resolutions, and monitors tend to be optimized for a 2-3' experience.
Even the highest quality HDTVs only support 1920x1080, which is fine for a 24" screen but nowhere near suitable for computer text at 32" and above.
As mentioned elsewhere in the thread, Samsung makes monitors with TV tuners built-in, and if you have a cable box that supports HDMI, you'll be able to use any monitor with two or more HDMI inputs.  The only thing that a monitor won't have is sound, but a stereo with 2+ inputs isn't very expensive now (especially relative to the price of an HDTV).  In a pinch, you could just get an audio splitter/joiner for the TV signal and computer.

A: I have a 24" LCD monitor which has 3 inputs: VGA, DVI, and HDMI.  If you don't mind manually switching inputs, you can probably get a cable box with HDMI ouput.  You won't be able to use the TV and the computer at the same time, but if it's just a secondary display that might be OK.

A: Beware of using TVs as monitors. Overscan and automatic scaling will get you every time!!!
I built a HTPC with Win7 and am using a 720p TV with an HDMI port (converted with a plug to DVI). The problem is that the TV assumes the signal is overscanned, so it cuts off a margin of screen real estate around every edge.
So, I compensate with the Win7 / nVidia overscan settings by adding extra black space, but now, essentially, the TV is truncating and scaling. This doesn't matter much for images, but for text, it is painful. So painful in fact that I can't use it for anything other than watching movies, TV, etc.
The problem is less of an issue with 1080p, but beware. You can always add a tuner card to your PC, but unless your TV specifically allows for 1:1 pixel mapping, I would avoid using TVs as monitors.

A: Option 1: Most Dell monitors come with both DVI-D and HDMI connectors and they generally are a lot cheaper than your average TV in the smaller sizes. You may have to play with the colour and saturation levels more to get a pleasing tv experience, but most monitors allow seperate settings for each input.
Option 2: An LCD or worse plasma TV with a VGA input or an old style DVI connector will render text from your computer poorly, so other than games or watching video i wouldn't recommend this as a 2nd screen.

A: If your cable connection is on HDMI, I suggest to go with a monitor since HDMI is readily supported on monitors (either directly or via DVI).
And monitors are much more cheaper and sharper than TV for same screen size, See https://superuser.com/questions/148493/why-tvs-are-costlier-than-monitor-for-same-screen-size

A: Depending on your connections, you might consider a monitor with TV tuner. There are some and they look like the solution for your problem.


text:
Q: Why are significant figure rules in Multiplication/Division different than in Addition/Subtraction? I've never understood specifically why this is.
Here's what I mean.

In Addition/Subtraction, what matters are the digits after the decimal point. So for example:
1.689 + 4.3 =
  1.629
+ 4.3XX
---------
  5.929
---------
  5.9

This makes sense to me. I filled in uncertain values with X, and it makes sense why I can't use the 0.029 in the answer - because I added it to an uncertain value.

However, I don't understand the rules when it comes to Multiplication/Division.
The same little trick with X's doesn't help me here.
I know that what matters in Multiplication/Division are the significant figures. So for example:
12.3 * 4.6 =
  12.3
*  4.6
-------
   738
  492X
-------
  56.58
-------
  57

The answer is 57 according to significant figure rules of Multiplication/Division, but I just can't make sense of those rules like the way I did with Addition/Subtraction.
Does anyone have an intuitive explanation for the significant figure rules of Multiplication/Division?

A: The number of significant figures is a representation of the uncertainty of a number. $123.4$ has an uncertainty of $0.1$ since the first uncertain digit is usually included. So, your multiplication of
$$12.3 \times 4.6$$
is better represented as
$$(12.3 \pm 0.1) (4.6 \pm 0.1).$$
I'm going to use @barrycarter's trick of using scientific notation to better represent the values
$$(1.23 \pm 0.01) \cdot 10^1 \times (4.6 \pm 0.1) \cdot 10^0.$$
$$(1.23 \pm 0.01) (4.6 \pm 0.1) \times 10^1.$$
From this we can see that the number with more significant digits has less relative uncertainty. Relative uncertainty is approximately the measured uncertainty (also called absolute uncertainty) divided by the value.
Multiplying out:
$$((1.23)(4.6) + (1.23)(\pm 0.1) +  (4.6)(\pm 0.01) + (\pm 0.01)(\pm 0.1)) \times 10^1.$$
$$(5.658 + (\pm 0.123) +  (\pm 0.046) + (\pm 0.001)) \times 10^1.$$
The number of digits we can write down is determined by the total uncertainty, which here is dominated by $\pm 0.123$. So, our result is
$$(5.658 \pm 0.123) \times 10^1.$$
$$(5.7 \pm 0.1) \times 10^1.$$
$$57 \pm 1$$
which results in $57$.
To summarize, in multiplication, the largest relative uncertainty dominates the uncertainty of the final answer. This translates into the the number with fewer significant digits determining the significant digits of the final answer. This contrasts with addition, where the largest absolute uncertainty determines the uncertainty of the answer.

A: It makes more sense if you convert to scientific notation first, so 12.3 * 4.6 becomes: (1.23*10^1 * 4.6*10^1). In this case, you can't expect an answer more accurate than one place after the decimal point, since you don't know what comes after the 6 in 4.6.
In general, in scientific notation, you will essentially be multiplying numbers between 1.000 and 9.999... (and adding the powers of 10), so the accuracy you'd expect is the last decimal position of the least precise number.

A: Actually, I have two explanations, depending on what you consider more intuitive.
Interval arithmetic
This one is best explained by example. Remember that a value with a certain number of significant figures is supposed to represent that exact value $\pm 5$ in the first insignificant digit. For example, $12.3$ with three significant figures represents anything in the range $[12.25,12.35]$, and $4.6$ with two significant figures represents $[4.55,4.65]$. If you multiply these two ranges, you can get anything between a minimum of $4.55\times 12.25 = 55.7375$ and a maximum of $4.65\times 12.35 = 57.4275$. So strictly speaking, the result is $[55.7375,57.4275]$.
However, it's a lot more convenient to represent this range as a single number, using the same significant figure convention as before, where the uncertainty is $\pm 5$ in the first insignificant digit. We can't actually do this, though; the size of the range is $1.69$, which is not $5\times 10^n$ for any $n$. The sensible options are either to write $60$, which represents the range $[55,65]$, or $57$, which represents the range $[56.5,57.5]$. But there isn't a straightforward rule that justifies the first choice, without doing interval arithmetic every time. The second choice, on the other hand, can be justified by keeping the lower number of significant figures from either of the original operands. So that's what we do.
General error propagation
For a better justification, significant figure rules are chosen as they are because they're a decent match to the general formula for propagation of uncertainties. That general formula is as follows: if you have some quantity $y$ which is a function of several other variables, $y = f(x_1, x_2, \ldots)$, then the uncertainty in $y$ is given by
$$\sigma_y = \sqrt{\biggl(\frac{\partial y}{\partial x_1}\biggr)^2\sigma_{x_1}^2 + \biggl(\frac{\partial y}{\partial x_2}\biggr)^2\sigma_{x_2}^2 + \cdots}$$
Actually, this formula only applies under certain conditions, but they're very common conditions, and it would take a whole separate answer (or even more) to explain all the subtleties. (See here and here for examples.) So let's just take that formula as a starting point.
If a value $x$ has $n$ significant figures, that means its relative uncertainty $r = \frac{\sigma_x}{\lvert x\rvert}$ is between $(5\times 10^{-n})$, if $x$ is a power of $10$, and $(5\times 10^{-(n+1)})$, if $x$ is just less than a power of $10$ (like $99.99999$). Or within an order of magnitude, anyway. You could argue that maybe the $5$ should be a $3$ or something like that, but that gets into the conditions I already decided to skip discussing.
Multiplication and division
I do this case first because it's easier. If the function is $f(x_1, x_2) = x_1x_2$, the general error propagation formula gives
$$\sigma_y = \sqrt{x_2^2\sigma_{x_1}^2 + x_1^2\sigma_{x_2}^2}$$
Or substituting in $rx$ for the uncertainty, all the $x_1$s and $x_2$s cancel out and we get
$$r_y = \sqrt{r_1^2 + r_2^2}$$
Going through the argument for division, the algebra is a little different but you still get to this same formula for relative uncertainty.
There are three cases to consider here:

*

*$r_1 \ll r_2$: $r_1$ is basically insignificant and you can write $r_y \approx r_2$

*$r_1 \gg r_2$: $r_2$ is basically insignificant and you can write $r_y \approx r_1$

*$r_1 \approx r_2$: in this case you can approximate them as roughly equal and write $r_y \approx \sqrt{2} r_1$. Depending on the exact relative magnitudes, this factor might be a little different, but both $r_1$ and $2 r_1$ are likely to be around the same order of magnitude, which is all that matters for an uncertainty.

One can make this argument a little more precise, but the point is, the resulting uncertainty $r_y$ is more or less the same as the larger of $r_1$ and $r_2$. But remember, $r$ is related to the number of significant figures: $r \approx 10^{-n}$, meaning that a larger relative uncertainty $r$ corresponds to a smaller number of significant figures. So the final quantity $y$ will typically have the same number of significant figures as the less precise (fewer significant figures) of the two operands $x_1$ and $x_2$.
Addition and subtraction
It's also worth checking that this works for addition and subtraction.
If the function is $f(x_1, x_2) = x_1 \pm x_2$, then the partial derivatives are both equal to $1$. So the error propagation formula gives
$$\sigma_y = \sqrt{\sigma_{x_1}^2 + \sigma_{x_2}^2}$$
Here substituting in the relative uncertainty gives
$$r_y(x_1 \pm x_2) = \sqrt{r_1^2 x_1^2 + r_2^2 x_2^2}$$
but this isn't so useful because things don't cancel out. So let's go back to the previous formula, with the $\sigma$s. This time, the three cases break down as follows:

*

*$\sigma_1 \ll \sigma_2$: $\sigma_1$ is negligible and you can set $\sigma_y \approx \sigma_2$

*$\sigma_1 \gg \sigma_2$: $\sigma_2$ is negligible, so $\sigma_y \approx \sigma_1$

*$\sigma_1 \approx \sigma_2$: following more or less the same reasoning as before, $\sigma_y \approx \sigma_1$ to within an order of magnitude or so

Now, the actual uncertainty $\sigma$ is related, not to the number of significant figures, but to their position. The larger uncertainty corresponds to the leftmost insignificant figure among the two operands, which is exactly what you use.


text:
Q: Premade APK template for bundling static html website on Android? I have a 3MB website that's static HTML/CSS/JS and I'd like to package it up into an Android app for offline use.
Are there premade APK archives for static webapps... the kind where I can just insert the static html/css/js and the app is programmed to load "index.html" or something? Presumablty I'd need to put index.html in /res/raw or /assets. I'm not a Java programmer so that's that main reason I'm asking.
I understand that APK files need to be cryptographically signed but presumably I can do this later.

A: AppMobi takes your webapp, compiles it with their pre-built template, and gives you the resulting APK. Make sure you use a custom loading splash image and implement the hack workaround in the forums to speed up first-time loading.
You don't need to do anything but create a new project and paste your web-app into the project folder, then follow the screenshots. And that hack I mentioned.
If you have or understand gradle, I did this to prevent polluting the actual web-app:
task appmobi(dependsOn: [buildForWeb]) << {
    File indexFile = new File('build/index.html')

    def appMobiLoader = '''
'''

    def indexText = indexFile.text.replace("", "$appMobiLoader")
    indexFile.withWriter { writer ->
        writer.write(indexText)
    }
}

A: Check out the PhoneGap project. http://www.phonegap.com/


text:
Q: Grails: how to apply constraint on column to be shown in list I am new to grail, please give me idea how to apply constraint on column to be shown in list after writing scaffolding true in the controller i.e. i have columns in domain- name,email,password,phone but i want to show only name, email and phone in the grid when the list will be displayed, is there any way to do this through domain? please give me a solution for this thanks.

A: You can install the templates (http://grails.org/doc/latest/ref/Command%20Line/install-templates.html)
grails install-templates

Templates give you access to overwrite the default templating that Grails uses in controllers, views, etc.  If you look at src/templates/scaffolding/list.gsp you can see that they are already excluding some properties ('id' and 'version).  I added a static list to my domain class:
static excludedFromListViewProperties = ["password"]

In the list.gsp I replaced:
<%  excludedProps = Event.allEvents.toList() << 'id' << 'version'
allowedNames = domainClass.persistentProperties*.name << 'dateCreated' << 'lastUpdated'

with:
<%  excludedProps = Event.allEvents.toList() << 'id' << 'version'
excludedProps.addAll(domainClass.getClazz().excludedFromListViewProperties ?: [])
allowedNames = domainClass.persistentProperties*.name << 'dateCreated' << 'lastUpdated'

Let me know if that doesn't work for you.

A: scaffolding make things behind the scene. You can generate all views and controllers of specific domain class via:
grails generate-all packageName.DomainClass

After command is executed, you can simply change generated controllers and views as you wish.

A: You can have a look at Dynamic Scaffolding which states

Also, the standard scaffold views expect model variables of the form InstanceList for collections and Instance for single instances. It's tempting to use properties like 'books' and 'book', but those won't work.

So, maybe you can override your scaffolding actions by returning instances with only the fields you want. But you may need an intermediary data type I think. This is a way to explore

A: A slightly improved version of Jarred's answer that checks the existence of the excludedFromListViewProperties property:
domainClass.getClazz().metaClass.properties.findAll{
   if (it.name == "excludedFromListViewProperties"){
        excludedProps.addAll(domainClass.getClazz().excludedFromListViewProperties ?: [])
    }
}


text:
Q: Chef: Setup concurrency with poise application python recipe I'm using Chef with poise/application_python recipe to start Celery workers. But I didn't find how to setup concurrency of these workers.
Anyone knows how to do it?
Thanks in advance!
My recipe:
node['python-app'].each do |app|
  application '/srv/' + app['name'] do
    git do
      repository app['repo']
      revision app['branch'] if app['branch']
      deploy_key data_bag_item('ssh_keys', app['deploy_key'])['key'] if app['deploy_key']
    end
    virtualenv
    pip_requirements

    celery_worker do
      app_module 'tasks'
      user 'celery'
      service_name "scrawler"
    end

    celery_config do
      options do
        worker_concurrency 5  # nothing...
        concurrency 4  # nothing...
      end
    end
  end
end

A: As mentioned over on the GitHub issue, you need to use the old name for the config option: celeryd_concurrency.


text:
Q: What's the difference between Sharepoint Workspace, Groove Workspace, and Shared Folders? http://social.msdn.microsoft.com/Forums/eu/sharepoint2010general/thread/030f8e7f-d991-48e9-a958-33e83f18004d says:

SharePoint Workspace 2010 (No More Groove) provides much more features
  like taking SharePoint Site content Offline. The content(documents,
  lists) can be edited offline and synced once connected in
  Network/SharePoint server.
Shared Folder is just like a open space where documents or files can
  be stored. It can't be compared with SharePoint Workspace.
If you want to keep single copy and all your devices are always
  connected, then "Shared Folder" may fit.
Otherwise SharePoint Workspace 2010 is Perfect.

Okay the answer says "no more groove". Does that mean I can forget about groove? It says that Shared Folder may fit. Does it fit over internet? Does it fit if the computer is not only 100% all the time. What can you do with one and not the other and via versa? Why give so many similar choices?

A: Different products (if you can call Shared Folder as such). Basically SharePoint Workspace is the new Groove (in Office 2007). The Windows Process is still named Groove if you peek in your processes.
Groove Workspaces allow secure collaboration workspaces between partners, with the condition of both have SharePoint workspace running.
Otherwise, Shared Folders cannot even be compared as the SharePoint workspace enables offline scenarios and syncronization with SharePoint Sites (not just workspaces) of various content (multiple types supported - Task, Calendar, most important Document Libraries).
Hope it helps

A: An update to a very old question... (we are only now considering how to replace our Groove workspaces.)
Sharepoint Workspace is similar to but different from Groove Workspace.
Similar
 - Offline/Online scenarios (edit on or offline and sync later)
 - Many content types
Groove Advantages
 - Everything is secure/encrypted 100% of the time. Not just communications
 - Ability to have extensive Groove-based applications with secure sync on/offline collaboration... eg ToucanNavigate was amazing as a secure multipartner GIS (Mapping, data, analysis) available on/offline. We used for disaster situations with all infrastructure busted.
SharePoint Advantages
- Can sync with both local workspaces and cloud-based "Sharepoint Sites"


text:
Q: Change RootViewController & Remove All View Controllers I am having difficulty replacing the rootViewController in a custom class that constantly observers if a user is logged in or not.
While it does change the root view controller, the previous view controller & any presented views are still there underneath. How can I completely clear the slate and reset to a new view controller?
 func isLoggedIn () {

        UIApplication.shared.keyWindow?.rootViewController = storyboard.instantiateViewController(withIdentifier: "Main Menu")

    }

A: extension UINavigationController {
/**
 It removes all view controllers from navigation controller then set the new root view controller and it pops.

 - parameter vc: root view controller to set a new
 */
func initRootViewController(vc: UIViewController, transitionType type: String = kCATransition, duration: CFTimeInterval = 0.3) {
    self.addTransition(transitionType: type, duration: duration)
    self.viewControllers.removeAll()
    self.pushViewController(vc, animated: false)
    self.popToRootViewController(animated: false)
}

/**
 It adds the animation of navigation flow.

 - parameter type: kCATransitionType, it means style of animation
 - parameter duration: CFTimeInterval, duration of animation
 */
private func addTransition(transitionType type: String = kCATransition, duration: CFTimeInterval = 0.3) {
    let transition = CATransition()
    transition.duration = duration
    transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
    transition.type = CATransitionType(rawValue: type)
    self.view.layer.add(transition, forKey: nil)
}}

Use this


text:
Q: Bash Substitute a Variable in a variable I'm Banging my head end can not find the Answer.
I want to use a directory INPUT_DIR within a other Variable MINFILESIZE (Checking in a directory if there is a file large then 50 MB and echo that file)
I have so far
INPUT_DIR="${1%/*}"

MINFILESIZE="find ${INPUT_DIR} -type f -size +50M"

Echo"Minfile: $MINFILESIZE"

And i can not get it to work.

A: You are setting MINFILESIZE to a string. The output is going to output that variable as a string, not give you the output of the command. You can have bash run this as a command one of two ways. Use backticks ` .. ` or use $( .. ) for command substitution. Bash will interpret the command inside and give the output you expect as the value for your variable:
MINFILESIZE=$( find ${INPUT_DIR} -type f -size +50M )

The $( .. ) style is recommended, since this is the POSIX standard.


text:
Q: Write XML File from a flex application back to a rails Server I have a XML-file, which I want to send to a rails server. To do so I use the following code:
 <mx:HTTPService id="dataService"
 result="resultHandler(event)"
 resultFormat="e4x"/>

In a Function triggered by a save button, I do the following:
 var params:Object = {};
 params["xml_file"] = xmlDoc;
 dataService.method = "POST";
 dataService.url = "http://localhost:3000/containers";
 dataService.send(params);

Unfortunately there is always the Problem (see below) appearing. If I remove the params var, it runs a GET Request...
[RPC Fault faultString="HTTP request error" faultCode="Server.Error.Request" faultDetail="Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream-Fehler. URL: http://localhost:3000/containers"]. URL: http://localhost:3000/containers"]
what could be the problem?
Thanks for any hints!
Markus

A: you flex code is calling index action of your containers controller(/containers) but, when you don't send any parameters Rails will treat it as a get action, Please check your development.log file for more description on the error.


text:
Q: Python counter for counting the most commmon string listed in the output Hey guys I've been working on this code to do counting the number of string occured in the text document, it's on my previous question and the code appears like this:
from collections import Counter
with open("C:\\Documents and Settings\\Zha\\Desktop\\stringResult\\sguresult_lenght10.txt") as f:
    content = f.read()
a = Counter(content.split()).most_common()
for line in a:
        print line

the example of the result of print line will be like this
('KERNEL32.dll', 58)
('not', 49)
('.data', 49)
("nRX|'", 20)
('xZGVr', 20)
('TyN*u', 20)
('[Wu^D', 20)

the part before comma is the string and the next one is the number of occurrance
Now the question is I need to remove all the brackets outside and the ' ' single quotation in between leaving only the string and number i.e
KERNEL32.dll, 58
not, 49
.data, 49
etc

I've been trying using regex but it seems the I might got the pattern wrong since the single quotation sometimes is first part of the string itself. Is there any easy way to solve this? thanks

A: You can use this:
for line in a:
    print '%s, %s' % (line[0], line[1])

A: Use the * syntax:
for line in a:
    print *line

The * syntax tells the function to treat the elements in a collection as individual parameters.
Example:
>>>foo = ('Hello', 'World', 1, 2, 3,)
>>>print foo
('Hello', 'World', 1, 2, 3)
>>>print *foo
'Hello' 'World' 1 2 3

A: a= dict(Counter(content.split()).most_common())

for i,j in a.items():
    print i,j

my answer removes the quotation no need to add new conditions


text:
Q: I'm wanting to combine unknown number of rows into one Here is an example of data:
TABLE: DRIVERS
ID    | FNAME | LNAME
------+-------+------
WR558 | WILL  | RIKER
WW123 | WALT  | WHITE

TABLE: ACCIDENTS
DRIVER | ACCIDENT_NBR | ACCI_DATE  | ACCI_CITY | ACCI_ST
-------+--------------+------------+-----------+--------
WW123  | 4-7777       | 2014-01-01 | Chicago   | IL
WW123  | 4-7782       | 2014-01-03 | Houston   | TX
WW123  | 4-7988       | 2014-01-15 | El Paso   | NM

There could be any number of accidents listed for this driver in this table or there could be none
What i need to see is this:
ID    | FNAME | LNAME  | ACCIDENT1_NBR | ACCI1_DATE | ACCI1_CITY | ACCI1_ST | ACCIDENT2_NBR | ACCI2_DATE | ACCI2_CITY | ACCI2_ST | ACCIDENT3_NBR | ACCI3_DATE | ACCI3_CITY | ACCI3_ST | ... | ACCIDENT10_NBR | ACCI10_DATE | ACCI10_CITY | ACCI10_ST
------+-------+--------+---------------+------------+------------+----------+---------------+
WR558 | WILL  |  RIKER |               |            |            |          |               | ...
WW123 | WALT  |  WHITE | 4-7777        | 2014-01-01 | Chicago    | IL       | 4-7782        | ...

I need to pull the driver info and the 10 most recent accidents (if any) onto this one line.  I'm unsure if I need to use a PIVOT table or a FETCH.  Either way, I'm not sure how to iterate into the columns as needed.
Anyone's assistance is greatly appreciated!
I'm using SQL Server 2012 and this will ultimately get pulled into a .XLS SSRS file.  The pipes I included are only for display and will not be part of the final result

A: You should use PIVOT for this as ugly as it will be it is the correct choice if coding a C# solution is not viable.
Here is an example:  Simple Pivot sample


text:
Q: How do you implement Software Transactional Memory? In terms of actual low level atomic instructions and memory fences (I assume they're used), how do you implement STM?
The part that's mysterious to me is that given some arbitrary chunk of code, you need a way to go back afterwards and determine if the values used in each step were valid. How do you do that, and how do you do it efficiently? This would also seem to suggest that just like any other 'locking' solution you want to keep your critical sections as small as possible (to decrease the probability of a conflict), am I right?
Also, can STM simply detect "another thread entered this area while the computation was executing, therefore the computation is invalid" or can it actually detect whether clobbered values were used (and thus by luck sometimes two threads may execute the same critical section simultaneously without need for rollback)?

A: The simplest answer is "it depends". There are tons of radically different implementations working in pretty much any way imaginable.

The part that's mysterious to me is that given some arbitrary chunk of code, you need a way to go back afterward and determine if the values used in each step were valid. How do you do that, and how do you do it efficiently?

One solution is to use versioning. Every time an object is modified, its version number is updated. While the transaction is running, you validate each accessed object's version, and when the transaction commits, you verify that the objects are still valid.
This validation can be a simple integer comparison (if transaction_start_version >= object_version, the object is valid), so it can be done fairly efficiently.

This would also seem to suggest that just like any other 'locking' solution you want to keep your critical sections as small as possible (to decrease the probability of a conflict), am I right?

Very likely. I think a few implementations have gone the route of assuming/requiring everything to be a transaction, but yes, in most implementations, transactions are specially marked chunks of code, and the longer a transaction runs, the larger the chance of a conflict that may cause transactions to roll back.

Also, can STM simply detect "another thread entered this area while the computation was executing, therefore the computation is invalid" or can it actually detect whether clobbered values were used (and thus by luck sometimes two threads may execute the same critical section simultaneously without need for rollback)?

The latter. Keep in mind that the idea in TM is to protect data, rather than code.
Different code paths may access the same variable in different transactions. This has to be detected by the TM system. There's no real notion of "this area", since that refers to code, rather than data. The TM system doesn't care what code is executing, it tracks what data is being modified. In that way, it differs entirely from critical sections (which protect code, rather than data)

A: GHC's STM implementation is described in section six of:
Composable Memory Transactions. Tim Harris, Simon Marlow, Simon Peyton Jones, Maurice Herlihy. PPoPP'05: ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming, Chicago, Illinois, June 2005
And section five of:
Transactional memory with data invariants. Tim Harris, Simon Peyton-Jones. March 2006 TRANSACT '06

A: I suggest you watch this presentation: http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey
In the second half it explains how to update values without leaving them in an undefined state. For example - if you have a tree that you want to update in STM-style you don't change the previous version at all. Let's say that tree is a pointer to the root of the tree. The only thing you create is the nodes that changed (but they can refer to nodes in the original snapshot of the tree.
Then you do a compare-and-swap on the tree pointer. If it succeeded, then everyone will now see your new tree and the old one can be garbage-collected. If it hasn't, then you repeat the process and the tree you just constructed is garbage collected.
The big idea is that you don't need to detect if anyone else changed the tree until you actually swap the new and old values, so there are no "conflicts" or "clobbered values" from the typical multithreaded programming.

A: Some papers can be really difficult to read but two which are very clear and concise are:
Transactional Locking II, Dave Dice, Ori Shalev, Nir Shavit which describes the "TL2" STM algorithm in terms of any language.
Deuce: Noninvasive Software Transactional Memory in Java, Guy Korland, Nir Shavit, Pascal Felber which explains a load time class transformer which transforms regular java classes into in-memory classes which have additional bytecode to do STM. This is relevant to the question as the paper explains how code without STM can be mechanically transformed into code which is doing STM in any OO language.
The Deuce framework lets you plugin the actual algorithm you wish to use; including the TL2 algorithm. As the Deuce framework is Java the following discussion uses java terminology but is only assuming that you are writing in an OO language.
Below will outline the TL2 approach. The papers have links to alternative approaches but studying one algorithm answers a lot of questions.

how do you implement STM? The part that's mysterious to me is that given some arbitrary chunk of code, you need a way to go back afterward and determine if the values used in each step were valid.

One short answer for how TL2 does STM is "bookkeeping" and then only using write locks at commit time. Read the paper for the fine detail but a board brush outline is as follows. Every property that you can use in the original code would have a getter and setter. In the transformed code there would also be a version number of the property and additional code added to the getter and setter. You need to record the version of every attribute you read within the transaction as the transaction "read-set". You can do this by having every getter add the version of the attribute seen into a threadlocal linkedlist. You also need to buffer the writes as the "write-set" in a threadlocal until you commit. Note that the getter methods need to check and return a threadlocal write-set value for a given field if you have one. That way you see your uncommitted writes in your reads but no other thread is going to see them until you commit.
At commit time you take write locks against every attribute you are about to write. Whilst you have the locks you double check that your read-set is still valid; that the attributes you read in your transaction have not been updated to a higher version by another transaction. If so then your business logic may not be valid as you can have inconsistent reads so you need to rollback the whole transaction. If the final checks pass then you commit by flushing your write-set, bump the versions of those attributes, release the write locks, and final clear both the write-set and read-set threadlocal lists.
The paper explains that the algorithm can abort early if it detects that an attribute being read has been written to since the tx started. The paper has some neat tricks to speed up read-only transactions. It even has a trick to work out which blocks are read-only and which are read-write. Anyone expressing an interest in such things really should enjoy the two papers.
The Deuce framework in the paper above shows how to change all your getters and setters by injecting new java bytecode into your classes at load time. Other languages could have a special compiler or preprocessor which perform the same mechanical transformation of normal code into STM enabled code. Specifically with Deuce your source code objects can have simple getter setter pairs but transformed classes at runtime have enriched getter setters which do the bookwork.
Transforming regular code into STM code (particularly at runtime) is interesting but if you need to actually write a STM enabled data structure you don't need any magic sauce. Instead just create a Ref class with a get() and a set(x) and make every single relationship between your data structure objects made up of Ref handles. In the get and set of your Ref class you can do the threadlocal bookwork. Then you can implement a simple version of "TL2" or any other algorithm which works well for your data structures and your concurrency of read versus write.

This would also seem to suggest that just like any other 'locking'
solution you want to keep your critical sections as small as possible
(to decrease the probability of a conflict), am I right?

TL2 has a critical period in holding the write locks then doing final checks and writes which is easy to comprehend and optimise without any understanding of the application business logic. If you assign each property a unique number you can trivially avoid deadlock by taking locks in ascending order. It is important to note that all your business logic is done speculatively assuming that the commit checks will pass. You don't hold locks whilst you are doing arbitrary slow business logic. You can be doing multiple web service lookups or slow database calls and you won't take any locks until the commit. Clearly the professionals are going to tune the heck out of the generic critical section.
The paper makes it clear that the algorithm may be aborting more often that the specific business logic requires. The generic algorithm does not know whether specific dirty reads would not affect the actual write outcome. Handwritten logic which understands the actual business logic could know special cases when a rollback is not needed for a given sets of dirty reads. If however you have lots of code to write and an application where the likelihood of rollback is very low a generic mechanical STM approach may lead to less bugs and perform well.

Also, can STM simply detect "another thread entered this area while
the computation was executing, therefore the computation is invalid"
or can it actually detect whether clobbered values were used (and thus
by luck sometimes two threads may execute the same critical section
simultaneously without need for rollback)?

The TL2 approach as all about the data read or written not about the code which does it. It is what you get and set and which counts; and whether any other thread trod on your toes before you flush all the writes. All that is required of the code is that you have a begin(), commit() and rollback() in the business logic to start, end and abort the transaction. Even that can be generated code. With Java you could mark your methods with the @Transactional annotation on methods then generate code which wrap your method invocations in a try/catch/finally that does the begin/commit/rollback as idiomic java. Deuce injects such logic at class load time.
Once again you don't need such magic sauce to begin/commit/rollback in your own STM enabled data structures. You can be explicit and put in all that right into your data structure logic code to create your own explicitly STM enabled classes in any OO language.

A: If you are going with .NET framework,
You can check out this experimental

*

*.NET 4.0 STM.Net

*.NET rocks podcast on STM.Net: Dana Groff and Yossi Levanoni Talk STM


text:
Q: Difference operation from root Is there a way to make difference directly from root? I want to do something like this:
difference(){
    root();
    cube();
}

instead of this:
difference(){
    union(){
        object1();
        object2();
        .
        .
        objectN();
    }
    cube();
}

A: You are already on the there. You just need to define root() and cube() as modules like so:
difference(){
  root();
  cube();
}

module root(){
  object1();
  object2();
  ...
}

module cube(){
  //some cube definition
}

In the background OpenSCAD will secretly create a union() around every module for you, just as if you wrote:
module xyz(){
  union(){
    //objects
  }
}

So in this example an object root() is created and cube() will be subtracted from this object. By using the module definition you keep your code just as modular as you ask for.
You may also want to have a look at the official docu and cheat sheet here.

A: difference() module subtracts all other children from the first one. In first snippet, first child is root(), in second first child is union(), and in both cube is subtracted.


text:
Q: Using requirejs with retinajs I am using requirejs and am calling in retinajs as a plugin. I am using the shim along with a jQuery dependancy:
....
'plugins/retina.min': {
        'deps': ['jquery']
    }
....

I then init my application:
requirejs(['./main'], function(App) {
    App.init();
});

"main.js":
define(['jquery', 'foo', 'bar', 'plugins/domReady!', 'plugins/retina.min'], function($, foo, bar, retina) {....});

My logo on my page is getting updated correctly, however it seems I am running into a timing issue. Further down the page (or even subsequent page views) the script is getting executed before the page is ready.
Retina.js auto-exectues so there isn't a method to initialize per say. Is there a way to "call" a jquery plugin that auto-executes with require js?
This is wrong, but I think this is something along the lines of what I need:
define(['jquery', 'foo', 'bar', 'plugins/domReady!', 'plugins/retina.min'], function($, foo, bar, retina) {
    var App = {
        init: function() {

           retina.init(); // This doesn't exist
           <script src="/plugins/retina.js"></script> // Not even close to valid, but this is what I need.
         }

     };
    return App;
});

Thank you for your time and suggestions!

A: Try this:
define(['jquery', 'foo', 'bar', 'plugins/domReady!'], function($, foo, bar) {
    var App = {
        init: function() {
            require(['plugins/retina.min'], function(){
                // This is straight from retina.js's source: https://github.com/imulus/retinajs/blob/master/src/retina.js#L142
                if (Retina.isRetina()) {
                    Retina.init(window);
                }
            });
         }
     };
    return App;
});


text:
Q: Gelfand trigonometry question If we start with a lemma that states that when $ a^2+b^2=1$ there exists an angle $ \theta $ such that $ a=\cos\theta $ and $ b=\sin\theta$
Suppose that $\alpha$ is some angle  if $a=4\cos^3\alpha-3\cos\alpha $ and $ b=3\sin\alpha -4\sin^3\alpha $ show that there is an angle $\theta $ such that $ a=\cos\theta $ and $ b=\sin\theta$
Thanks. I think I have to expand and then reduce. But it isn't coming together.  Any suggestions?

A: If you are familiar with the triple angle formulas
$$a = 4\cos^3\alpha - 3\cos\alpha = \cos(3\alpha)$$
and
$$b = 3\sin\alpha - 4\sin^3\alpha = \sin(3\alpha)$$
then you can take $\theta = 3\alpha$.
If not, you can use the Pythagorean Identity $\sin^2\varphi + \cos^2\varphi = 1$ to simplify the problem.
\begin{align*}
a & = 4\cos^3\alpha - 3\cos\alpha\\
  & = 4\cos\alpha(1 - \sin^2\alpha) - 3\cos\alpha\\
  & = 4\cos\alpha - 4\cos\alpha\sin^2\alpha - 3\cos\alpha\\
  & = \cos\alpha - 4\cos\alpha\sin^2\alpha
\end{align*}
\begin{align*}
b & = 3\sin\alpha - 4\sin^3\alpha\\
  & = 3\sin\alpha - 4\sin\alpha(1 - \cos^2\alpha)\\
  & = 3\sin\alpha - 4\sin\alpha + 4\sin\alpha\cos^2\alpha\\
  & = -\sin\alpha + 4\sin\alpha\cos^2\alpha
\end{align*}
Therefore,
\begin{align*}
a^2 + b^2 & = (4\cos^3\alpha - 3\cos\alpha)^2 + (3\sin\alpha - 4\sin\alpha)^2\\
          & = (\cos\alpha - 4\cos\alpha\sin^2\alpha)^2 + (-\sin\alpha + 4\sin\alpha\cos^2\alpha)^2\\
          & = \cos^2\alpha - 8\cos^2\sin^2\alpha + 16\cos^2\sin^4\alpha + \sin^2\alpha - 8\sin^2\alpha\cos^2\alpha + 16\cos^4\alpha\sin^2\alpha\\
          & = 1 - 16\cos^2\alpha\sin^2\alpha + 16\cos^2\alpha\sin^4\alpha + 16\sin^2\alpha\cos^4\alpha\\
          & = 1 + 16\cos^2\alpha\sin^2\alpha(-1 + \sin^2\alpha + \cos^2\alpha)\\
          & = 1 + 16\cos^2\alpha\sin^2\alpha(-1 + 1)\\
          & = 1 + 0\\
          & = 1
\end{align*}
Hence, by the theorem in the text by Gelfand and Saul, there exists $\theta$ such that $a = \cos\theta$ and $b = \sin\theta$.

A: should be easy (edit: not really :-)
$$
(4c^3-3c)^2+(3s-4s^3)=
16c^6-24c^4+9c^2+9s^2-24s^4+16s^6=?
$$
and collect powers
$$
16c^6+16s^6-24c^4-24s^4+9c^2+9s^2=16(c^6+s^6)-24(c^4+s^4)+9(c^2+s^2)
$$
Now $9(c^2+s^2)=1$ and the other terms give you $-8$
$$
24=24\cdot 1=24 (c^2+s^2)^2=24(c^4+2s^2c^2+s^4)=24(c^4+s^4)+48s^2c^2
$$
and
$$
16=16\cdot 1=16 (c^2+s^2)^3=16(c^6+3c^4s^2+3c^2s^4+s^6)=16(c^6+s^6)+48c^4s^2+48c^2s^4
=16(c^6+s^6)+48c^2s^2(c^2+s^2)
$$
which is
$$
=16(c^6+s^6)+48c^2s^2
$$
Now subtract!


text:
Q: GridView image gallery onClick example I am new to the Android development so don't mind asking me simple question like this.
I am trying to implement simple gallery from example http://developer.android.com/guide/topics/ui/layout/gridview.html, but I am not sure how to make clicked thumbnail show in full screen or something like that.
Also, it would be very nice if someone could explain to me how to, in this case, load images from urls via AsyncTask.
Thanks!!


text:
Q: sycl/dpc++ accessing global variable using global pointer I am trying to access a global variable from inside the sycl kernel. A code that uses this pattern and its output is as follows.
#include<CL/sycl.hpp>
using namespace sycl;
int g_var = 22;
int * const g_ptr = &g_var;
int main() {
    queue q{host_selector{}};
    g_var = 27;
    std::cout<<"global var changed : " <<g_var<<" "<<*g_ptr<<"\n";
    q.submit( [=] (handler &h) {
        stream os(1024, 128, h);
        h.single_task([=] () {
            os<<"global var : "<<*g_ptr<<"\n";
        });
    }).wait();
    return 0;
}

Its output is as follows.
$$ dpcpp test.cpp; ./a.out
global var changed : 27 27
global var : 22

Even though g_var is changed to 27, it is printed with the initial value of 22 inside the kernel. Is this the intended behavior?
In general lambdas does not create a copy of global variables. Does dpc++ compiler create a copy of the global variable inside the device or does it propagate the constant value during compilation so as to not access the global memory at runtime?

A: SYCL divides execution and data through the "host" and "device." The data on the "host" lives on the CPU normally, and needs to be transferred to the "device" (GPU usuall) in order to be accessed for use in a SYCL kernel.
SYCL uses buffers and accessors, or "Unified Shared Memory" to transfer and provide access to data for the "device" side code (i.e. the code running on the GPU). So your pointer is never sent over to the device, and therefore never modified.
So instead of using int * const g_ptr = &g_var; you should use a buffer or USM.
There are some lessons on these for buffers and USM in SYCL Academy.
E.g. using buffers and accessors:
int a = 18, b = 24, r = 0;

  auto defaultQueue = sycl::queue{};

  {
    auto bufA = sycl::buffer{&a, sycl::range{1}};
    auto bufB = sycl::buffer{&b, sycl::range{1}};
    auto bufR = sycl::buffer{&r, sycl::range{1}};

    defaultQueue
        .submit([&](sycl::handler &cgh) {
          auto accA = sycl::accessor{bufA, cgh, sycl::read_only};
          auto accB = sycl::accessor{bufB, cgh, sycl::read_only};
          auto accR = sycl::accessor{bufR, cgh, sycl::write_only};

          cgh.single_task<scalar_add>([=] { accR[0] = accA[0] + accB[0]; });
        })
        .wait();
  }

And using USM:
 auto usmQueue = sycl::queue{usm_selector{}, asyncHandler};

 usmQueue.memcpy(devicePtrA, a, sizeof(float) * dataSize).wait();
 usmQueue.memcpy(devicePtrB, b, sizeof(float) * dataSize).wait();

 usmQueue
     .parallel_for<vector_add>(sycl::range{dataSize},
                                  [=](sycl::id<1> idx) {
                                    auto globalId = idx[0];
                                    devicePtrR[globalId] =
                                        devicePtrA[globalId] +
                                        devicePtrB[globalId];
                                  })
     .wait();

 usmQueue.memcpy(r, devicePtrR, sizeof(float) * dataSize).wait();

 sycl::free(devicePtrA, usmQueue);
 sycl::free(devicePtrB, usmQueue);
 sycl::free(devicePtrR, usmQueue);

 usmQueue.throw_asynchronous();


text:
Q: append() " element" twenty-five times to the " element" But the  only have 1 row when running HTML Can anyone explain why this loop in "code1" does'nt add 25 -Elements to the table? (Iam very newbie)
The code that only have 1 row in the table here  (code1):
https://jsfiddle.net/yuLr3p6s/2/

alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

let tr = $("

"); // create tr Element with Jquery
for (let i = 0; i < alphabet.length; i++) {

  let td = "" + alphabet[i] + "	";
  tr.append(td);
}

/* append tr Element to the end of Table element twenty-five times
and table will have twenty five rows*/
for (let i = 1; i <= 25; i++) {
  $("table").append(tr);
}
table, td {
    border: 1px solid black;
    border-collapse: collapse;
}

The code that have 25 rows in the table here     (code2):
https://jsfiddle.net/yuLr3p6s/1/

alphabet = ["A","B","C","D","E","F","G","H","I","J","K"        ,"L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

let tr = "
"; // create tr Element with Jquery
for (let i = 0 ; i < alphabet.length ; i++) {

    let td = "" + alphabet[i] + "	";
    tr += td;
}
tr += "
";

/* append tr Element to the end of Table element twenty-five times
and table will have twenty five rows*/
for (let i = 1; i <= 25 ; i++) {
    $("table").append(tr);
}
table, td {
    border: 1px solid black;
    border-collapse: collapse;
}

A: You are inserting  inside one row
try put inside the loop :
let td = "" + alphabet[i] + "";

A: Your code:
let tr = $("

");

create a DOM node, while
let tr = "
";

creates a string.
When you use jquery methods such as .append() and .appendTo() on DOM nodes, jquery will move that node rather than create new ones.
The same methods with a string will create new nodes; which is why it works in your second snippet.
TBH, it's not that clear from the jquery documentation, there's a small line about half-way down:

https://api.jquery.com/append/
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):


text:
Q: How to getElementBy...Value? Normally, when we want to click a radio button automatically on a website, we would use getElementsByName(), getElementbyID(), etc. However, if there is only value that can be use to identify the button, how this can be done?
<input type="radio" name="price" value="123" onclick="changeView(this);">

A: You can use document.querySelector().
It can take class names, id or even attributes. In your case, it will be
document.querySelector('input[value="123"]');


text:
Q: green dao update column on play store update has taken place this is my Generator class
public class Generator {
    public static void main(String[] args) throws Exception {
        Schema schema = new Schema(1, "app.abc.db.dao");
        createAbcDB(schema);

    }
    private static void createAbcDB(Schema schema) throws IOException, Exception {
        Entity abc = schema.addEntity("Abc");
        abc.addIdProperty();
        abc.addShortProperty("name");
    }
}

This is the code where i get abc dao from dao session. This works fine.
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(SurveyActivity.this, "abc.db", null);
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession(IdentityScopeType.None);
        abcDao = daoSession.getAbcDao();

I added one more column
abc.addShortProperty("email");

to createAbcDB in generator to new version of app. Once users get updated they are getting sql exception saying no column found. Because i am calling on new login
dropAllTables(db, true);
onCreate(db);

But problem is i have given one time login that user will always come to landing screen on upgrade from play store. So i don't know whether the user is upgraded app or not in order to drop and create all tables.
So my question is how to know my table has altered?

A: Each time that you do a significant modification like this, you have to update de Schema version number:
Schema schema = new Schema(2, "app.abc.db.dao");

This way, in the OpenHelper present in the DaoMaster, or in the SQLiteOpenHelper taht you're using, you can control this changes in onUpgrade() function:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
    dropAllTables(db, true);
    onCreate(db);
}


text: Q: How do I interpret t-ratio of interaction variable? I need to answer this question for my Econometrics HW: Does the gender gap differ significantly in urban versus non-urban areas? Test at the 5% level. If I am not wrong I need to use the t-test for this however I don't know how I should proceed as those are interaction variables, I basically need to account for the variable female and femaleXurban (female * urban) . What calculation is needed?


text:
Q: Can't reach containers with new 1.10 DNS SD I've been trying the latest RC's for docker and compose for a few days, and finally, today, the new stable versions (1.10 and 1.6 respectively).
The new networking stuff added in 1.9 has been great so far. But since I upgraded to 1.10rc1 (and so far for every RC and stable), containers in the same user defined network can no longer find each other. In fact, they can't even reach the outside world right now.
A quick example, file test_docker/docker-compose.yml:
version: '2'
services:
    db1:
        image: mysql
        environment:
            MYSQL_ALLOW_EMPTY_PASSWORD: yes
    db2:
        image: mysql
        environment:
            MYSQL_ALLOW_EMPTY_PASSWORD: yes

This creates two MySQL containers with the official image. According to the compose docs, a new testdocker_default should be created, with both containers automatically connected, which is the case:
docker network inspect testdocker_default
[
    {
        "Name": "testdocker_default",
        "Id": "820f702e8e685567e4f1a8638cd9be305e96e37fcd741306eed6c1cf0d54ba02",
        "Scope": "local",
        "Driver": "bridge",
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1/16"
                }
            ]
        },
        "Containers": {
            "16d5594bdfd11f55d33a207612b8447f6b50ff4be8b42d2313707b06ca618556": {
                "Name": "testdocker_db2_1",
                "EndpointID": "b6d5ff10fba860c01ac7a6508e56c5e116296cd06ea2158c695897e18fcd50ce",
                "MacAddress": "02:42:ac:11:00:03",
                "IPv4Address": "172.17.0.3/16",
                "IPv6Address": ""
            },
            "9b8b885dab3b5012c9663cb97a07af66fbe385f92c69a614a4d56bf85305ec3a": {
                "Name": "testdocker_db1_1",
                "EndpointID": "09e43aef8e14b0e876d47fabe67a3827dc4cea5d44b199113d9ab2678d8ce22a",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {}
    }
]

Now, the documentation also says that the containers should be able to reach each other through db1 and db2, but this is not the case:
root@9b8b885dab3b:/# mysql -h db2 -u root
ERROR 2005 (HY000): Unknown MySQL server host 'db2' (111)
root@9b8b885dab3b:/# mysql -h testdocker_db2_1 -u root
ERROR 2005 (HY000): Unknown MySQL server host 'testdocker_db2_1' (111)

Additionally, neither container is able to reach the internet, unless I explicitly add Google's DNS to the /etc/resolv.conf.
I'm pretty sure I'm doing something wrong here, because I can't find issues raised by other people, but I can't figure out what it is.
Thanks guys!
Edit:
To clarify, containers can ping each other through their IP address, but the hostnames are not resolved.

A: This issue was reported on GitHub. The suggested workaround for the moment is to disable firewalld altogether.
I will update this answer with a better solution to this issue as soon as one is found.
Edit #1:
Pull request solving this issue (tested for Fedora 23). This PR is already merged with master, for anyone wanting to compile Docker from source.
Couldn't find an expected release date, but I'm guessing it will be released as a patch version in the next couple weeks. Will update this answer again with further information when available.
Edit #2:
Docker's 1.10.1 RC solves this issue. I'll mark this answer as accepted just to close this topic.


text:
Q: In a rails 3.0 app I'm having trouble embedding an image in an email I am trying to get a QR Code image to display in an email. I have tried to apply solutions from similar questions here at SO but have not been able to get any variation of them to work. I don't want to download it from the site.
in my user_mailer.rb:
  def email_qrcode(from_whom, to_addy)
    @from_whom = from_whom
    @to_addy = to_addy
    attachments["qrcode.png"] = File.read(Rails.root + "public/images/qrcode.png")
    mail( :to => to_addy, :from => @from_whom.email, :subject => "QR Code" )
  end

in my email_qrcode.html.erb:

Here is the QR Code:

The email content that is displayed:
Here is the QR Code: (followed by the little blue question mark indicating no image)

It is also included as an attachment, but having to double click it to open it defeats the convenience factor.
Thanks for your help.

UPDATE:
Good marketing is about removing every obstacle that you can to make it easier for the potential customer. The more times the QR code is displayed without having to find and click another link, the better the results will be. So, to be clear...

*

*The attachment is there. In some email clients web mail servers it will even display as an attachment below the email. However, many (maybe most... not sure) email clients and web mail servers will not display an attachment unless you click on them to open them... another click (obstacle).

*In addition, many clients and web mail servers will prevent the download and display of images without clicking on a link to approve display of the image. However, many of those clients and servers will NOT block an image that is embedded in the email. In other words putting in a link to download the image increases the likelihood of the display being blocked requiring a click (obstacle to potential customer) to open the image.

ANOTHER UPDATE: solution
user_mailer.rb:
attachments.inline["qrcode"] = {
                                :data => File.read("#{Rails.root.to_s + '/public/images/qrcode.png'}"),
                                :mime_type => "image/png",
                                :encoding => "base64"
                              }

email_qrcode.html.erb:
<%= image_tag( attachments['qrcode'].url, :id => 'qrcode' ) %>

A: In your email_qrcode method, try changing:
attachments.["qrcode.png"]
to
attachments.inline["qrcode.png"].
This should get you moving in the right direction.


text:
Q: c# oracle sql prepared statement I am trying to create a prepared statement in c#.
For some reason everything I try ends up with an exeption.
*. This is my code for now:
the exception i am getting is: "Operation is not valid due to the current state of the object."
using (OracleCommand cmd = new OracleCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;

        cmd.CommandText = "insert into daily_cdr_logs " +
                "(message) " +
                "values " +
                "(:message)";

        cmd.Parameters.Add(:message, msg);
        //OracleDbType.Int32, postpaid_duration, ParameterDirection.Input);
        cmd.Prepare();
        cmd.ExecuteNonQuery();
    }

*

*i have seen some people doing this with Parameters.AddWithValue. but for some reason i cant find the function AddWithValue in OracleCommand.Parameters, i have imported Oracle.DataAccess.Client and i have oracle DataAccess refferance, using visual studio 2010.

A: The general rule is open a connection only when necessary and close / dispose it as soon as you're done. The connection pool is managed automatically, so opening a new connection is not reall a heavy task. When you open a connection, close it and open the same connection again, a new native connection isn't really created. The previous one is fetched from the connection pool. The defaults are usually fine so I'd recommend not passing pooling stuff when creating the connection. If you're executing 10 commands in succession, open a connection, execute 10 commands and close it. Do that only if they are guranteed to be executed one after the other and you're not "holding on" to connections when doing other things. If you need to do something else, close the connection before doing so. This usually results in best performance.
Almost. Try:
cmd = new command(...);
cmd.parameters.Add(...)
cmd.parameters.Add(...)

then connection.open()
//execute command and use results

A: The connection needs to be open before you call cmd.ExecuteNonQuery().
Try this:
cmd.Connection.Open();
cmd.ExecuteNonQuery();

A: Try this way:
using (OracleCommand cmd = new OracleCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;

        cmd.CommandText = "insert into daily_cdr_logs " +
                "(message) " +
                "values " +
                "(:message)";

         OracleParameter pMsg = new OracleParameter("message",OracleDbType.Varchar2);
            pMsg.Value = msg;

         cmd.Parameters.Add(pMsg);

        //OracleDbType.Int32, postpaid_duration, ParameterDirection.Input);
        cmd.Prepare();
        cmd.ExecuteNonQuery();
    }

A: The Sql Server version of the Prepare command requires

Before you call Prepare, specify the data type of each parameter in
  the statement to be prepared. For each parameter that has a variable
  length data type, you must set the Size property to the maximum size
  needed. Prepare returns an error if these conditions are not met

Because the Prepare command is defined in the IDbCommand class and inherited by other ADO.NET classes I suppose that this is true also for Oracle, thus add the following lines to add the parameter to your command (and be sure the connection is already open when you call Prepare)
cmd.CommandText = "insert into daily_cdr_logs (message) " +
                  "values (:message)";
OracleParameter p = new OracleParameter(":message", DbType.Varchar);
p.Size = 2000; // as a wild guess
p.Value = msg;
cmd.Parameters.Add(p);
cmd.Prepare();
cmd.ExecuteNonQuery();


text:
Q: Idiomatic translation of Django models to different API schemas, perhaps with Django Rest Framework Whats the best/idiomatic way to create and pass data between different API schemas/formats in Django or with Django Rest Framework? I'm imagining something like a translation serializer that hooks between APIs that could be reused anywhere or in nested format, and wanted to see what the best practices are.
Say I have a standard Django Rest Framework based API and model that I expose via DRF that looks something like this : (But has alot more complexity and nested relationships
class Person(models.Model):
    first_name = models.CharField(max_length=255, blank=True, null=True)
    middle_name = models.CharField(max_length=255, blank=True, null=True)
    last_name = models.CharField(max_length=255, blank=True, null=True)
    company = models.ForeignKey(Company, blank=True, null=True)

class PersonSerializer(serializers.HyperlinkedModelSerializer):
    company = CompanySerializer(required=False)
    class Meta:
        model = Person
        fields = '__all__'

class PersonViewSet(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

Response looks something like this
{
    "first_name": "Oliver",
    "middle_name": null,
    "last_name": "Zhou",
    "company": {
        "name": "Company ABC",
        "url": "http://localhost:8000/companies/1234/"
    }
}

Now, depending on different actions in the application, I have a different API I need to integrate with and pass the Person data to, for example, an API with a schema with something like this :
{
    "first_name": "Oliver",
    "middle_name": null,
    "last_name": "Zhou",
    "company": {
         "name": "Company ABC"
    }
}

What I've been doing is ugly and a spaghetti network of 'if' 'else' and nested logic trying to wrangle data into the proper format in a way that isn't reusable like a Serializer for each Django Model is for creation of standard Django Rest Framework ViewSets
def post_person(person)
    data = {}
    try:
         data['first_name'] = person.first_name
         data['last_name'] = person.last_name
         if person.company:
             data['company']['name'] = person.company.name
    except AttributeError as e:
        logger.info("AttributeError {}".format(e))

    # pseudocode here, but eventually after finishing the nesting
    # we post a response with the 'requests' library
    # response = requests.request(
    #    method, url, headers=headers, data=json.dumps(data))

A: I don't have a perfect solution to this problem but these are some of the things I did in the past to mitigate the pain:

*

*Heavily lean toward the direction of including a superset of the data/fields possibly needed. In most programming context it's harmless to have extra fields (company.url in your case). The obvious drawback of this approach is to have very bloated response body with most of the data just being thrown away at the client side.

*Have a hierarchy of Serializer classes that represent data at different detail level. For your case it can be SkeletonPersonSerializer <- BasicPersonSerializer <- DetailedPersonSerializer <- FullPersonSerializer, each class inheriting from the one before it and adds some more fields. But I have to admit that in reality this approach will get out of control pretty soon, especially when you have a network of related objects that need to be pulled in at different times.
The promise of GraphQL is to solve exactly this problem. I just got involved in a real-world, complex project that uses GraphQL. Will update this answer once I form some opinions on whether or not the real benefit of GraphQL deserves its hype.


text:
Q: jquery - animate two elements with one action I am trying to create a parallax effect where images slide over a background, and the background moves too, but only very slightly. Is that possible with jQuery?  I tried referencing both elements by ID with the animation but that isn't working.
            $(document).ready(function() {
                var timer;

                $("#leftarrow").hover(function() {
                    timer = setInterval(function() {slideLeft();}, 50);
                }, function() {
                    clearInterval(timer);
                });

            $("#rightarrow").hover(function() {
                    timer = setInterval(function() {slideRight();}, 50);
                }, function() {
                    clearInterval(timer);
                });

            function slideLeft() {
                $("img#background").stop().animate({
                    'left': '-=200px'
                }, 50);
                $(".mid").stop().animate({
                    'left': '-=20px'
                }, 50);

            }

            function slideRight() {
                $("img#background").stop().animate({
                    'left': '-=200px'
                }, 50);
                $(".mid").stop().animate({
                    'left': '+=20px'
                }, 50);
            }

            });

Here is a fiddle: http://jsfiddle.net/rYYDv/
Thank you for your help.

A: Instead of using an img tag for the background, set the image inside a div, and adjust the div accordingly.
Here is my implementation - jsfiddle


text:
Q: Jsoup Elements, авторизация на сайте(в сети) Доброго времени суток.
Интересуют следующие вопросы:
1) Как работать с Elements, а именно: как доставать оттуда ссылки в отдельный string.
2)В универе развернута опытная wi-fi сеть с авторизацией для того, что бы научить горе студентов(меня в.т.ч.) делать быстрые, оптимизированные веб-приложения и т.д. т.п. При подключении к этой сети можно либо подождать на черной странице 20 секунд, либо перейти по определенной ссылке, которая подгружается в html с помощью js на основную страницу авторизации, при переходе по этой ссылке дается доступ в интернет, задание в том, чтобы прошло максимально мало времени от момента подключения к сети до момента получения доступа в интернет. Это предыстория. То есть передо мной стоит задача распарсить основную страницу авторизации, получить эту ссылку и перейти по ней. (как же все просто на словах, аж диву даешься). Что я знаю из того, как и что мне надо делать, мне надо подключиться к странице, дождаться ее полной загрузки, затем в AsyncTask распарсить ее, найти нужную мне ссылку (их несколько, но в нужной присутствует некие несколько кодовых символов  в определенном порядке), затем передать эту ссылку отдельным string(про это 1 вопрос) обратно из AsyncTask, загрузить эту страницу. Понятное дело прикрутив куки, setuseragent(если что-то еще забыл, подскажите, пожалуйста). Грубо говоря, предыстория ни к чему, надо просто зайти на сайт, на нем найти ссылку, по ней перейти. Что я упустил? Правильно ли я это понимаю "на пальцах/словах"? Есть ли у кого-нибудь примеры выковыривания из Elements в String? Есть ли у кого-нибудь примеры чего-то подобного описанному? Одинаковый ли будет эффект для сервера, если я перейду по ссылке, кликнув на нее или перейду на сайт описанным способом через парсер, не будет ли сервер ругаться, заного переправлять меня на страницу авторизации, etc?
Так же буду очень благодарен если кто-нибудь напишет мне в телеграм @mhlchm (https://t.me/mhlchm) и сможет ответить на парочку-тройку вопросов (обещаю не грузить сильно и не доставать), там просто намного удобнее. Спасибо.

A: Как работать с Jsoup в ютубе можно легко найти. Например вот хорошее видео парсинг Html
Например запрос на авторизацию
Connection.Response resp = Jsoup.connect("http://soft.ru").referrer("http://soft.ru").userAgent(userAgent)
                .data("login", "operator", "password", "1234567")
                .method(Connection.Method.POST).timeout(10000).execute();

Парсим полученный ответ Document doc = resp.parse();
находим элементЫ  Elements elements = doc.getElementsByAttributeValue("class", "ticketDetailRow");
Теперь различные методы для сохранения результата в строку:
 String  phoneNumber = elements.get(1).getElementsByAttributeValue("class", "ticketDetailGrid3").get(1).getElementsByIndexEquals(1).attr("value");

Тут конечный метод attr(String str) сразу возвращает строку. Но чаще приходится переводить результат строку методом text()
Elements comments = doc.getElementsByAttributeValue("name", "col12");
String  comment = comments.get(comments.size() - 1).text();

В хроме браузере нажав F12 на вкладке elements можно видеть код страницы. Еще проще навести курсор на, в Вашем случае, ссылку и нажав правой кнопкой мыши в меню выбрать Посмотреть код
Jsoup это браузер без визуализации, так что сервер не поймет ничего (наверно, если нет изощренных методов защиты).
Приведенный тут мною код для Jsoup для Java, точно такие ли методы для Jsoup на андроид я не знаю.
По поводу выполнения js: как я понял, после выполнения js интернет получен и дальше парсить ничего не нужно. Значит мы получаем переходим по страничке в Jsoup, находим ссылку и переходим по ссылке,но уже не в jsoup, а в webview, он перейдет и исполнит js.  Но может случиться такое: в jsoup переходите по ссылке, парсите, переходите по второй ссылке в webview и тут он ругается, потому что это ссылка полученная другим браузером и ему нужны либо куки либо тот же userAgent, а то и вообще какие нибудь данные, которые выдала первая страница.   Я бы на вашем месте сперва проверил что требует вторая страница сниффером или в том же самом хроме, там есть вкладка network.  Вот вопрос в котором есть похожее решение, только там чуть сложнее. Как парсить данные из WebView


text:
Q: Create a mutable array of arrays each containing a dictionary in swift? I am trying to declare a variable that stores an array of arrays. Each array then contains a Dictionary object. I tried a bunch of different possible declarations but the compiler is not happy with any of them.
Any suggestion?
Thanks
Clarification on what I needed:
An array that contains arrays where each of them contains dictionaries.

A: You Said

Each array then contains a Dictionary object

that mean that each array will have a single Dictionary so why do you need that extra Array
anyway  the following code declare an Array that contain Dictionaries(The code assume that eventually your dictionary will contain strings but you can change that to any type you want)
var myObj  = Array<Dictionary<String,String>>()

var dic1:Dictionary<String,String> = Dictionary<String,String>()
dic1["A"] = "Alpha :A"
dic1["B"] = "Alpha :B"

var dic2:Dictionary<String,String> = Dictionary<String,String>()
dic2["C"] = "Alpha :C"
dic2["D"] = "Alpha :D"

myObj.append(dic1)
myObj.append(dic2)

if you need an array containing arrays of dictionaries it will be almost the same
var myObj  = Array<Array<Dictionary<String,String>>>()


text:
Q: Getting JSONDecodeError: Expecting value: line 1 column 1 (char 0) with Python + Zipline + Docker + Jupyter I installed Zipline and Jupyter using Docker:
https://github.com/quantopian/zipline/blob/master/Dockerfile
I am now trying to run the following Zipline code under Jupyter
%%zipline --bundle quantopian-quantl --start 2008-1-1 --end 2012-1-1 -o strat.pickle

from zipline.api import symbol, order, record

def initialize(context):
    pass

def handle_data(context, data):
    order(symbol('AAPL'), 10)
    record(AAPL=data[symbol('AAPL')].price)

The error message I am getting is:
**JSONDecodeError: Expecting value: line 1 column 1 (char 0)**

Here is the picture of the error:

Again, this takes place when I try to run the program.
What could the problem be? Any help, hints or advice is ~greatly~ appreciated!
TIA
Addendum:
I have also tried this as well:
https://docs.google.com/document/d/1mvZO_JDirbJNXJfM0bTS9uMipHE5cfSGFj0sUpJIcsw/edit?usp=sharing

A: I know this question is sort of solved, but I tried what they are offering on the github issues and it did not help me, so I desided to show how I fixed my problem. Maybe it will help you.
The problem is in the benchmark.py file (and several others) of zipline where it tries to get data from iex and fails because their function changed.
I will show you what I did in order to get the sample code running:
(I assume you already have zipline installed and runnig ther apple buying sample code)
1.benchmark.py: look into your zipline folder in your computer (what you have downloaded or pip/conda installed). Open benchmark.py (find it first) and edit it, change the whole code there to this:
import numpy as np
import pandas as pd
import pandas_datareader.data as pd_reader
def get_benchmark_returns(symbol, first_date, last_date):
    data = pd_reader.DataReader(
        symbol,
        'yahoo',
        first_date,
        last_date
    )

    data = data['Close']

    data[pd.Timestamp('2008-12-15')] = np.nan
    data[pd.Timestamp('2009-08-11')] = np.nan
    data[pd.Timestamp('2012-02-02')] = np.nan

    data = data.fillna(method='ffill')

    return data.sort_index().tz_localize('UTC').pct_change(1).iloc[1:]

this code was taken from the answer of shlomikushchi github page about the issue. Here shlomikushchi switched the data source from iex to pandas, yahoo.
2.Next, open the file: loaders.py , also somewhere in zipline:
there is a row there in which they call the function:
(look for this in the code)
data = get_benchmark_returns(symbol
change it to :
 data = get_benchmark_returns(symbol,first_date, last_date)

3.open trading.py , also somewhere in the zipline folder,
after this line:
class SimulationParameters(object):
def __init__(self, start_session, end_session,
             trading_calendar,
             capital_base=DEFAULT_CAPITAL_BASE,
             emission_rate='daily',
             data_frequency='daily',
             arena='backtest'):

enter those lines:
start_session = pd.Timestamp(start_session).tz_localize(tz='US/Central')
    end_session = pd.Timestamp(end_session).tz_localize(tz='US/Central')

now it should work when you run the code in here:
https://www.zipline.io/beginner-tutorial.html

A: step 3 should be:
start_session = pd.Timestamp(start_session).tz_convert('UTC')

end_session = pd.Timestamp(end_session).tz_convert('UTC')

A: Another solution -- mentioned on the Github issue -- is to sign-up for a free API token from IEX, and insert it into your zipline module's benchmark.py file. Change the request.get line to this:
r= requests.get(
        "https://cloud.iexapis.com/stable/stock/{}/chart/5y?chartCloseOnly=True&token={}".format(symbol, IEX_API_KEY)
    )
Needs to be a string, so surround your key with " " quotation marks


text:
Q: how to install and connect jdbc driver in adt bundle? can we install jdbc in adt bundle. if yes tell me how install jdbc driver in adt bundle and create connection. I have oracle 11g R2 in my computer running with windows 8. Thanks for your suggestions in advance..

A: *

*First of all please add the Android Tag as it is an Android Developer
Tools question.

*Second as you know you  are working on the ADT you must be understanding
that it's just a special bundle of Eclipse which is devoted for
purely android application development.(Eclipse supports various platforms regarding development).

*Third download the required package from the
link

*Fourth Integrate it with the ADT
Lastly if you still don't get any idea try this link as the last alternative link


text:
Q: VBA Dictionary - Adding Data I am really new to VBA (practicing for 2 weeks now) and I would greatly appreciate your help/advice's regarding the following topic:
I am trying to get to know the dictionary function within vba, but i have a couple of questions:

*

*-Is it possible to populate the dictionary with values from a pivot table? For example, you have 2 columns and you put one of them as
key and the other one as item.

*How can i use the dictionary as a VlookUp ? I would like to go through it and find the specific item corresponding to this key.
While writing this I feel that the questions are pretty basic but I would really appreciate your help and time and in case it is possible some examples.