text:
Q: Creating a Javascript version of a PHP multidimensional associated array I have a set of data that is not normalized. I do the normalization in PHP it it works just fine.
The dataset looks like this (screenshot bellow), it is a lot larger tho. I am only interested in orginizing the category and the type. With those two orginized I can make good tables and menu's.
Problem
Now the problem is, I am switching to an AJAX system, and the data no longer comes into PHP. Instead it comes directly into the page using node.js/mongodb. Is there a way I can do something like this:

// ----------------
OLD SITUATION
//-----------------
In PHP I did this:
$sql = "SELECT *
        FROM mydb
        WHERE merk = 'webecos'
        ORDER BY categorie, type, code";

$result = $wpdb->get_results( $sql );

foreach($result as $row){
    $artikelen[$row->categorie][$row->type][] = $row;
}

Now I can make good sorted tables / menu with nested loops. The code I used is this.

    <?php foreach ( $artikelen as $categorie => $row ): ?>

            <?=$categorie; ?>

            <?php foreach ( $row as $type => $artikel ): ?>

                    <?=$type; ?>

            <?php endforeach; ?>

    <?php endforeach; ?>

Edit
Maybe this is a but better to understand. The array I am after looks like this:
array['categorie-name']['type-name'][x] = whole object;

A: Are you still able to work with PHP? If so, you can always bring the data from the server in the JSON format and let the client (in your case, the javascript language) read it and interpret it.

A: I'm not really sure I totally follow you, but do you mean something like this?
var data = [Object, Object, Object];
var artikelen = [];

for(var i=0; i<data.length; i++){

    if( !artikelen[data[i].category])
        artikelen[data[i].category] = new Array();

    if( !artikelen[data[i].category][data[i].type] )
        artikelen[data[i].category][data[i].type] = new Array();

    artikelen[data[i].category][data[i].type].push(data[i]);
}

More complete example:  (also note I put category instead of categorie, change if needed).

Key things to take away from this approach:

*

*Check if array at key exists

*If not, create it

*.push can be used on a javascript array to add an item to an array

Using a string as a type for an object:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;

var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;

var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;

// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];

for(var i=0; i<data.length; i++){

    if( !artikelen[data[i].category])
        artikelen[data[i].category] = new Array();

    if( !artikelen[data[i].category][data[i].type] )
        artikelen[data[i].category][data[i].type] = new Array();

    artikelen[data[i].category][data[i].type].push(data[i]);
}

alert( artikelen[1][2] ); // expected [object], [object]

alert( artikelen[1]["hello hello"][0].type ); // expected "hello hello"

EDIT
I gave it some more, thought and after reading this, it turns out that arrays in Javascript are not well suited to be used as associative arrays (like in PHP).  In actuality, you are just adding attributes to an object.  So making it an object instead is better.  For example, the following:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;

var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;

var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;

// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];

for(var i=0; i<data.length; i++){

    if( !artikelen[data[i].category])
        artikelen[data[i].category] = new Object();

    if( !artikelen[data[i].category][data[i].type] )
        artikelen[data[i].category][data[i].type] = new Object();

    artikelen[data[i].category][data[i].type] = (data[i]);
}

console.dir( artikelen ); // if using a debugger with console, gives detailed info

Also, if using a debugger, such as Firebug in Firefox, you can see detailed info with the console.dir function.


text:
Q: Setting up VLAN on switch I'm trying to setup multiple VLAN on my TP Link TL-SG2424 L2 managed switch but I'm not sure if I quite get the concept, or if I'm simply being stupid?!
So I have ~ 17 machines connected to my switch, which is in turn connected to the internet (and DHCP server) using a Draytek Vigor router via switch port 1 into router port 1.
On my Draytek I have 3 LAN's configured -
LAN1 - 192.168.1.10 - 192.168.1.255 (default)
LAN2 - 192.168.2.10 - 192.168.2.255
LAN3 - 192.168.3.10 - 192.168.3.255

I then have the following VLAN configuration -
VLAN 0 - Port 1, Subnet LAN 1, no VLAN tag
VLAN 1 - Port 1, Subnet LAN 2, VLAN Tag 20
VLAN 3 - Port 1, Subnet LAN 3, VLAN Tag 40

So my understanding is that I can now configure my switches to tag certain devices to belong in that port group. As such, they'll be assigned to the VLAN's respectively.
So on my switch I've created my VLAN with ID 20 and marked ports 8-12 as being part of VLAN 20 and removed them from Default VLAN (1).

I'd then expect traffic from devices I've plugged into 8-12 to be assigned with VLAN tag 20 and as such be assigned with an IP within the 192.168.2.1 range from the DrayTek router (or am I misunderstanding switch VLAN)?
Anyway, that isn't what is happening and I can't figure out why. I've tried various configurations and having no luck... I really, really hope someone can help!

A: Sorry, silly mistake but this might help others -
I wasn't tagging port 1 (the link to router/DHCP) in my VLAN group so essentially port 1 wasn't a member (which it needs to be). In addition, ports 8-12 don't need to be tagged as they already have the unique VLAN assigned to that entire port -

Note how port 1 (my outbound connection) is tagged and the rest are marked as members but left untagged.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Runtime error 1004 on ThisWorkbook.Activate In the code below, it is failing at the "FORMAT TEMPLATE" comment. I get a run time error 1004. What I am doing is - I am closing the previous window (from copying the template) and pasting it into the good workbook. I don't think I am switching workbooks properly.
Sub BBUorders()
'OPEN TEMPLATE
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "C:\Users\douglas.futato\Desktop\"
sFile = sPath & "BBU_CMD_TEMPLATE.xlsx"
Set wb = Workbooks.Open(sFile)

'COPY TEMPLATE PASTE IN BBU DOC
Dim tmplt As Workbook
On Error Resume Next
    Set tmplt = Workbooks("BBU_CMD_TEMPLATE.xlsx")
    If tmplt Is Nothing Then
        MsgBox "Template file needs to be open..."
        Exit Sub
    End If
On Error GoTo 0
With ThisWorkbook
    tmplt.ActiveSheet.Copy After:=.Sheets(.Sheets.Count)
End With

'CLOSE TEMPLATE
Windows("BBU_CMD_TEMPLATE.xlsx").Activate
ActiveWindow.Close False

'FORMAT TEMPLATE --------- THIS IS WHERE IS BOMBS OUT
ThisWorkbook.Activate
Worksheets("Sheet3").Activate
ActiveCell.Offset(-3, -8).Range("A1:H1").Select
Selection.AutoFilter
Cells.Replace What:="[BBU_CMD_TEMPLATE.xlsx]Price List", Replacement:=Sheet1.Name, LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
ActiveSheet.Range("$A$1:$H$61").AutoFilter Field:=6, Criteria1:="0"
Rows("2:100").Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=-18
ActiveSheet.Range("$A$1:$H$18").AutoFilter Field:=6
ActiveSheet.Range("$A$1:$H$18").AutoFilter Field:=7, Criteria1:="0"
Selection.Delete Shift:=xlUp
ActiveSheet.Range("$A$1:$H$17").AutoFilter Field:=7
Range("E2").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Range("E2").Select
Selection.AutoFill Destination:=Range("E2:E50"), Type:=xlFillDefault
Range("E2:E21").Select
Range("I1").Select
ActiveSheet.Range("$A$1:$H$50").AutoFilter Field:=1, Criteria1:="="
Rows("8:100").Select
Selection.Delete Shift:=xlUp
Range("A2:H2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveSheet.Range("$A$1:$H$7").AutoFilter Field:=1
Range("A1").Select
End Sub

A: What I noticed is the Worksheets("Sheet3").Activate
Have you tried replacing it with Worksheets("Sheet3").Activate
The ActiveCell.Offset should not contain negative value.
e.g. If your active cell is (1, 1), you will get an error because
-3 - 1 is less than 1, and is not a valid row. (same with column)

A: I know this isn't the cleanest code, but I figured out how to make it run. I had to add the worksheet as a reference. It was defaulting to sheet 2 when I was trying to work in the new sheet. Example: Worksheets("TEMPLATE").Range("E45").Select
Sub templateToBBU()
'OPEN TEMPLATE
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "C:\Users\douglas.futato\Desktop\"
sFile = sPath & "BBU_CMD_TEMPLATE.xlsx"
Set wb = Workbooks.Open(sFile)

'COPY TEMPLATE PASTE IN BBU DOC
Dim tmplt As Workbook
On Error Resume Next
    Set tmplt = Workbooks("BBU_CMD_TEMPLATE.xlsx")
    If tmplt Is Nothing Then
        MsgBox "Template file needs to be open..."
        Exit Sub
    End If
On Error GoTo 0
With ThisWorkbook
    tmplt.ActiveSheet.Copy After:=.Sheets(.Sheets.Count)
End With

'CLOSE TEMPLATE
Windows("BBU_CMD_TEMPLATE.xlsx").Activate
ActiveWindow.Close False
End Sub
Sub Macro1()
Worksheets("TEMPLATE").Range("A1:H1").Select
Selection.AutoFilter
Worksheets("TEMPLATE").Cells.Replace What:= _
    "C:\Users\douglas.futato\Desktop\[BBU_CMD_TEMPLATE.xlsx]Price List", _
    Replacement:=Sheet1.Name, LookAt:=xlPart, SearchOrder:=xlByRows,
MatchCase _
    :=False, SearchFormat:=False, ReplaceFormat:=False
Worksheets("TEMPLATE").Range("$A$1:$H$61").AutoFilter Field:=6,
Criteria1:="0"
Worksheets("TEMPLATE").Rows("2:100").Select
Selection.Delete Shift:=xlUp
Worksheets("TEMPLATE").Range("$A$1:$H$18").AutoFilter Field:=6
Worksheets("TEMPLATE").Range("$A$1:$H$18").AutoFilter Field:=7,
Criteria1:="0"
Selection.Delete Shift:=xlUp
Worksheets("TEMPLATE").Range("$A$1:$H$17").AutoFilter Field:=7
Worksheets("TEMPLATE").Range("E2").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E3").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E4").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E5").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E6").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E7").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E8").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E9").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E10").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E11").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E12").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E13").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E14").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E15").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E16").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E17").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E18").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E19").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E20").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E21").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E22").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E23").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E24").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E25").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E26").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E27").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E28").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E29").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E30").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E31").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E32").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E33").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E34").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E35").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E36").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E37").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E38").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E39").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E40").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E41").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E42").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E43").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E44").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E45").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E46").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E47").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E48").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E49").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E50").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"
Worksheets("TEMPLATE").Range("E51").Select
ActiveCell.FormulaR1C1 = "=R[-1]C+1"

'ST and Cust Mapping HERE
Worksheets("TEMPLATE").Range("$A$1:$H$50").AutoFilter Field:=1,
Criteria1:="="
Worksheets("TEMPLATE").Rows("8:100").Select
Selection.Delete Shift:=xlUp
Worksheets("TEMPLATE").Range("$A$1:$H$50").AutoFilter Field:=1

End Sub

Sub Main()
Call templateToBBU
Call Macro1
End Sub


text:
Q: Invert the left svg animation? Here is my code https://codepen.io/victoreugen2002/pen/PoJJPzP
I am trying to animate the left and right svg, to acheive this:

*

*both starting at the same time from the top and they continue drawing.

*until they both met at the bottom in the middle.

In order to acheive this I am thinking of inversing the animation for left svg, but it's not working:
.left {
    width: 50%;
    stroke-dasharray: 1855.968505859375;
    animation: dash 2s ease-in;

    @keyframes dash {
        from {
            stroke-dashoffset: 1855.968505859375;
        }
        to {
            stroke-dashoffset: 3710;
        }
    }

    svg {
        left: 0;
    }
}

A: You had to go from -1855.968505859375 to 0.

.left {
  width: 50%;
  stroke-dasharray: 1855.968505859375;
  animation: dash-left 2s ease-in;
}

.left svg {
  left: 0;
}

.right {
  width: 50%;
  stroke-dasharray: 1855.968505859375;
  animation: dash-right 2s ease-in;
}

.right svg {
  right: 0;
}

svg {
  position: absolute;
  top: 20px;
  width: 50%;
  stroke-width: 5px;
}

@keyframes dash-left {
  from { stroke-dashoffset: -1855.968505859375 }
  to { stroke-dashoffset: 0 }
}

@keyframes dash-right {
  from { stroke-dashoffset: 1855.968505859375 }
  to { stroke-dashoffset: 0 }
}

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 733 425">
    <path d="M733,424.5H39A38.5,38.5,0,0,1,.5,386V39A38.5,38.5,0,0,1,39,.5H733" style="fill: none;stroke: #78be21"/>
  </svg>

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 733 425">
    <path d="M0,.5H694A38.5,38.5,0,0,1,732.5,39V386A38.5,38.5,0,0,1,694,424.5H0" style="fill: none;stroke: #78be21"/>
  </svg>


text:
Q: Difference in paths for the base tag? I'm using the base tag
<base href="http://my_domain.com/web/source/" target="_blank">

but the domain will vary so I want to use
<base href="/web/source/" target="_blank">

or
<base href="web/source/" target="_blank">

Which one should I use.  Obviously I could just try both, but I want to understand why I should use the appropriate one.
Per, Mozilla, both absolute and relative paths are allowed.  The docs say see note selection below but I see no note section.

A: Keeping the preceding slash (/) will always ensure that the browser goes back to the root of the domain.
Leaving out the preceding slash could potentially send your users to /web/source/web/source/page.ext.


text:
Q: Slow WP Core and multi-site "Upgrade Network" timeout Having speed issues with a WordPress multi-site running on a dedicated server. The front end loads fine, but the WP Admin side takes a couple of minutes to load each page. Has happened since moving from one server to another (on the same network). New server has later versions of CentOS, PHP and MySQL.
I set up the P3 plugin to see if any plugins were causing the delay, but the main delay seems to be the WP Core loading (I'll update this when I can re-load the page to see how long it took).
I tried re-uploading a fresh download of the latest WP files but this didn't seem to help at all, so not sure if it's a DB issue.
Also, when trying to upgrade the network I'm getting this:

"Your server may not be able to connect to sites running on it.
      Error message: Connection timed out after 120001 milliseconds"

Edit: have now tried the Blackfire Profiler that @Steve mentioned in the comments and it's shown that the total load time for an admin page was 2 mins 1 second, with curl_exec() taking 2 minutes to process (99.6% of the processing time).
Does anyone know why this would take so long on the admin side?

A: Right - found out how to sort this using this SO question after finding that curl_exec() was the major slowdown (using Blackfire as recommended by @Steve).
Basically just updated my /etc/hosts file so that the internal IP of the server points to the site URL and now it runs like a dream.


text:
Q: Tensorflow XLA AOT: Eigen related Error Building Project I'm currently trying to work through the tensorflow XLA ahead of time compilation work flow for the first time, and I've hit a problem while trying to build the final executable binary which includes the AOT compiled object.
I've used the tutorial here to generate the test_graph_tfgather.pb and test_graph_tfgather.config.pbtxt files. Then I've used the tfcompile tool directly to produce MyClass.o and MyClass.h. So far so good.
I'm now building a simple makefile project which includes this compiled model, but I'm getting some errors related to Eigen. Could this be due to a different version of eigen3 being installed on my computer? I've also had to comment out the Eigen::ThreadPool lines due to eigen errors too so some version miss match may be the problem. Has anyone seen this problem before or does anyone have any ideas how to get this working?
Thanks.
The build errors:
g++ -c -std=c++11 -I . -I /usr/include/eigen3 -I /home/user/tensorflow_xla/tensorflow -I /usr/include main.cpp
In file included from /home/user/tensorflow_xla/tensorflow/tensorflow/compiler/xla/types.h:22:0,
                 from /home/user/tensorflow_xla/tensorflow/tensorflow/compiler/xla/executable_run_options.h:20,
                 from /home/user/tensorflow_xla/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h:22,
                 from MyClass.h:14,
                 from main.cpp:6:
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h: In static member function 'static tensorflow::bfloat16 Eigen::NumTraits<tensorflow::bfloat16>::infinity()':
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h:79:28: error: 'infinity' is not a member of 'Eigen::NumTraits<float>'
     return FloatToBFloat16(NumTraits<float>::infinity());
                            ^
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h: In static member function 'static tensorflow::bfloat16 Eigen::NumTraits<tensorflow::bfloat16>::quiet_NaN()':
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h:83:28: error: 'quiet_NaN' is not a member of 'Eigen::NumTraits<float>'
     return FloatToBFloat16(NumTraits<float>::quiet_NaN());
                            ^
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h: At global scope:
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h:95:34: error: 'log' is not a template function
     const tensorflow::bfloat16& x) {
                                  ^
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h:101:34: error: 'exp' is not a template function
     const tensorflow::bfloat16& x) {
                                  ^
/home/user/tensorflow_xla/tensorflow/tensorflow/core/framework/numeric_types.h:107:34: error: 'abs' is not a template function
     const tensorflow::bfloat16& x) {
                                  ^
Makefile:10: recipe for target 'main.o' failed

main.cpp source:
#define EIGEN_USE_THREADS
#define EIGEN_USE_CUSTOM_THREAD_POOL

#include <iostream>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "MyClass.h" // generated

int main(int argc, char** argv) {
  //Eigen::ThreadPool tp(2);  // Size the thread pool as appropriate.
  //Eigen::ThreadPoolDevice device(&tp, tp.NumThreads());

  MyClass matmul;
  //matmul.set_thread_pool(&device);

  // Set up args and run the computation.
  const float args[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
  std::copy(args + 0, args + 6, matmul.arg0_data());
  std::copy(args + 6, args + 12, matmul.arg1_data());
  matmul.Run();

  // Check result
  if (matmul.result0(0, 0) == 58) {
    std::cout << "Success" << std::endl;
  } else {
    std::cout << "Failed. Expected value 58 at 0,0. Got:"
              << matmul.result0(0, 0) << std::endl;
  }

  return 0;
}

Makefile
EIGEN_INC=-I /usr/include/eigen3
TF_INC=-I /home/user/tensorflow_xla/tensorflow
CPPFLAGS=-c -std=c++11

xla_hw: main.o MyClass.o
    g++ -o xla_hw main.o MyClass.o

main.o: main.cpp
    g++ $(CPPFLAGS) -I . $(TF_INC) $(EIGEN_INC) -I /usr/include main.cpp

A: I've solved this problem now, it turns out there is a specific version of eigen3 included with tensorflow and you need to use this version for it to work. When tensorflow has been built the correct version of eigen3 is located at <tensorflow path>bazel-tensorflow/external/eigen_archive
Below is the working makefile which includes the correct Eigen path as well as the libraries needed to link the project.
TF_INC=-I /home/user/tensorflow_xla/tensorflow/bazel-tensorflow/external/eigen_archive -I /home/user/tensorflow_xla/tensorflow

TF_LIBS=-L/home/user/tensorflow_xla/tensorflow/bazel-bin/tensorflow/compiler/tf2xla/ -lxla_compiled_cpu_function -L/home/user/tensorflow_xla/tensorflow/bazel-bin/tensorflow/compiler/aot -lruntime

CPPFLAGS=-c -std=c++11

xla_hw: main.o MyClass.o
    g++ -o xla_hw main.o MyClass.o $(TF_LIBS)

main.o: main.cpp
    g++ $(CPPFLAGS) -I . $(TF_INC) -I /usr/include main.cpp


text:
Q: iOS: Animate item twice Just starting out with core graphics. Playing with a simple button and label. I want this label to rotate 180 degrees on each click of the button. It only animates on the first click (the console does write "DONE" on each click, however)
- (IBAction)btnTest:(id)sender
{

    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{

        lblTest.layer.transform = CATransform3DMakeRotation(M_PI,0.0,1.0,0.0);

    }completion:^(BOOL finished) {
        if(finished)
            NSLog(@"DONE");
    }];
}

A: The reason its not working is because on the first button press, the views rotation is set to 180 deg. On the second button press you set the rotation to 180 deg again but since that is the same as the current value of the rotation, nothing happens. What you really want to be doing is setting the rotation to 180 deg + the current rotation. You can achieve this by rotating the current transform by 180 deg with the following change.
lblTest.layer.transform = CATransform3DRotate(lblTest.layer.transform, M_PI,0.0,1.0,0.0);


text:
Q: PHP ordering results in the code logic  Ok I have a results set of takeaways that I am looping through, the takeaway objects have the following properties id, name, address, postcode, distance, mile_cost, pizza, chinese, indian, kebab. If they have a pizza menu fr exampe it will contain 1 or a 0 if not etc
I want to filter the results in order to get the closest single pizza, Chinese, Indian and kebab selling restaurants. But also filter the results so that it doesn't show results with a distance greater than 10 and greater than the individual takeaways max deliver distance.
I have to do this in the php code rather than the mysql query and I am kinda stumped as how to do it. This is what I have so far
 foreach($takeaway as $takeaway){

        $distance = $this->geozip->get_distance($location, $takeaway->postcode);//get the distance between the two postcodes

        if($distance <= $takeaway->distance && $distance <= 10){

            $number = 0;

            echo $takeaway->name.' is '.$distance.'miles away
';

         ?>

Indian

 <?php
        }
    }
  ?>

I guess in order to get the closest single restaurant of each type I will have to find the ones with a distance closest to zero then order them some how?
Any help on how to do this would be much appreciated.

A: Use array_filter to filter you result.
And then use usort to sort by the distance.
In example:
function filter_function($takeaway) {
  return $takeaway->someProperty == 1; // could be your menu;
}

function sort_function($a, $b) {
  // distance must be set before elements are passed trough the sort function
  $ad = $a->distance;
  $bd = $b->distance;

  // sort is ASC
  if ($ad == $bd) {
      return 0;
  }
  // todo DESC change the < operator to >
  return ($ad < $bd) ? -1 : 1;
}

$takeaways = array_filter($takeaways, filter_function);
usort($takeaways, sort_function);


text:
Q: Batch Insert yii2 from checkbox Basically I have tow models in one form, and I have an array value from checkbox.
This is my form :
Model 1
$dataConditionContainer = ArrayHelper::map(ItemConditionIr::find()->all(), 'id', 'nama_condition');
echo $form->field($modelLinkItemConditionIrToIr, 'condition_id')->label("Container")->inline()->checkBoxList($dataConditionContainer);

Model2
<?= $form->field($modelInspectionReport, 'vehicle_no')->textInput(['maxlength' => true]) ?>

Now, from Model 1 that interprated by checkbox give me an array like this :
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

I want to insert them using batch insert, but this array need a value from model2 primary key like $inspectionReport = $modelInspectionReport->id.
Now How to make a batch insert ?
I know like this :
 $connection->createCommand()->batchInsert('link_item_condition_ir_to_ir',
       ['inspection_id', 'condition_id'], checkboxarraysuitable)->execute();

Is yii2 provide this ?
Please advise.

A: You can try this:
Yii::$app->db->createCommand()->batchInsert(ItemConditionIr::tableName(), [
                            'inspection_id',
                            'condition_id',
                        ], [[1,2], [3,4]])
                        ->execute();

A: Your $checkboxarraysuitable array is not properly structured. Your array must be in array of arrays structure. Here is an example of using BatchInsert() with proper array structure.


text:
Q: RSpec test routes with mounted engine I have a Rails app which mounts another engine to its routes, and also overrides some routes from the engine. Here is the routes.rb:
Spree::Core::Engine.routes.draw do
  # some other routes
  root :to => "home#index"
end

MyNamespace::Application.routes.draw do
  class CityConstraint
    def matches?(request)
      Spree::CityZone.where(:url => request.params[:city_name]).exists?
    end
  end
  mount Spree::Core::Engine, :at => ':city_name/', :constraints => CityConstraint.new, :as => :city
  mount Spree::Core::Engine, :at => '/'
end

When I try to test the routes with RSpec (2.14), I always get the following error:
#encoding: utf-8
require 'spec_helper'

RSpec.describe "routes.rb" do
  it "test routing" do
    expect(get: "/").to route_to(controller: "spree/home", action: "index")
  end
end

 Failure/Error: expect(get: "/").to route_to(controller: "home", action: "index")
   No route matches "/"
 # ./spec/routing/routes_spec.rb:6:in `block (2 levels) in <top (required)>'

I've found out, that when I add the following line, it works:
RSpec.describe "routes.rb" do
  routes { Spree::Core::Engine.routes } # this sets the routes
  it "test routing" do
    expect(get: "/").to route_to(controller: "spree/home", action: "index")
  end
end

The problem is, that I want to test the whole app, because we mount the app twice, under a city name scope (e.g. /your_city) and under root /.
When I try to set routes { MyNamespace::Application.routes } in my tests, I get the No route matches "/" error.
Any ideas how to test the whole stack of the mounted routes, including the routes from the engine?

A: You could try to add the needed routes manually:
RSpec.describe "routes.rb" do
  before :all do
    engine_routes = Proc.new do
      mount Spree::Core::Engine,
            :at => ':city_name/',
            :constraints => CityConstraint.new,
            :as => :city
      mount Spree::Core::Engine, :at => '/'
    end
    Rails.application.routes.send :eval_block, engine_routes
  end

  it "test routing" do
    expect(get: "/").to route_to(controller: "spree/home", action: "index")
  end
end

Idea taken from: http://makandracards.com/makandra/18761-rails-3-4-how-to-add-routes-for-specs-only


text:
Q: Is there a link that I can use to link fitbit to pc I want to link a fitbit to my PC but I cannot down load the software off the fitbit website as its says its not compaptable with Ubuntu

A: Ignore any compatibility messages and download it anyway.
Download this software: Wine
After you do, it should allow you to run .exe files like you ran windows. Run the installer normally. Make sure to create a shortcut on the desktop, it'll make your life easier. Open the software and it should work.


text:
Q: Unmarshal json optional element Golang The data I got are xlsx rows in this format: row 1 value 1 is the first cell (A1), row 1 value 2 is the second cell (B1) etc. Any cell can (but doesn't need to) contain styles e.g. Border, Fill etc. .Styles will be in curly brackets like in this data: [[["row 1 value 1",{"Border":null,"Fill":{"arrFill":{"BgColor":"red"}},"Font":null,"ApplyBorder":null}],"row 1 value 2","row 1 value 3"],["row 2 value 1","row 2 value 2","row 2 value 3"]]
How to unmarshal this data to get also the not neccessary style map?
Playground

A: You may need to use the reflect package to check data types in the resulting array/map. It looks tedious, but seems that is the only way out. I have pasted below some quick and dirt, but runnable code to illustrate the same:
package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func parsePrintArray(y interface{}) {
    var dummy []interface{}
    var dummy2 map[string]interface{}
    if reflect.TypeOf(y) == reflect.TypeOf("") {
        fmt.Printf("%s ", y)
        return
    }
    if reflect.TypeOf(y) == reflect.TypeOf(dummy2) {
        x := y.(map[string]interface{})
        for ks, vi := range x {
            fmt.Printf("\ndumping for key %s ", ks)
            if vi != nil {
                parsePrintArray(vi)
            }
        }
        return
    }
    for k, yl := range y.([]interface{}) {
        if reflect.TypeOf(yl) == reflect.TypeOf(dummy) {
            fmt.Println("")
            parsePrintArray(yl.([]interface{}))
        } else if reflect.TypeOf(yl) == reflect.TypeOf("") {
            fmt.Printf("%v: %s ", k, yl.(string))
        } else if reflect.TypeOf(yl) == reflect.TypeOf(dummy2) {
            x := yl.(map[string]interface{})
            for ks, vi := range x {
                fmt.Printf("\ndumping for key %s ", ks)
                if vi != nil {
                    parsePrintArray(vi)
                }
            }
        }
    }
}

func main() {

    x := "[[[\"row 1 value1\",{\"Border\":null,\"Fill\":{\"arrFill\":{\"BgColor\":\"red\"}},\"Font\":null,\"ApplyBorder\":null}],\"row 1 value2\",\"row 1 value 3\"],[\"row 2 value 1\",\"row 2 value 2\",\"row 2 value 3\"]]"

    var y []interface{}
    err := json.Unmarshal([]byte(x), &y)
    if err != nil {
        panic(err)
    }
    parsePrintArray(y)
    fmt.Println("")
}


text:
Q: Keep checkbox checked after form submit I have a page where I am displaying sql results as a table. I have it so that all the options are checked on default. However, when the user unchecks some locations and submits the form, he/she won't know what locations they're filtering on because all the checkboxes will still be checked. How can I make it so that only the checkboxes that were checked retain their value after the form is submitted?
Thank you
Here's my page so far:
   <?php

   $start=_GET['start'];
   $end=_GET['end'];

   if(empty($start)){
      $start=date("Ym");
    }
  if(empty($end)){
    $end=date("Ym");
 }

 $places=array();
if(!empty($_GET['cities'])){
    foreach($_GET['cities'] as $loc){
  array_push($places,$loc);
  }
}else{
   $places=('CHI','DET','LA','NYC','DALLAS','SPR','PHI');
}

?>

//html
<form method='GET'>
  START:<input type='text' name='start' value= '<?$start?>'>
   END: <input type='text' name='end' value='<?$end?>'>
 <input type='checkbox' name='cities[]' value='CHI' checked>CHICAGO
 <input type='checkbox' name='cities[]' value='DET' checked>DETROIT
 <input type='checkbox' name='cities[]' value='LA' checked>LAS ANGELES
 <input type='checkbox' name='cities[]' value='NYC' checked>NEW YORK
 <input type='checkbox' name='cities[]' value='DALLAS' checked>DALLAS
 <input type='checkbox' name='cities[]' value='SPR' checked>SPRINGFIELD
 <input type='checkbox' name='cities[]' value='PHI' checked>PHILIDELPHIA
 <input type='submit' value='Filter'>
 </form>

 <?
 $SQL="SELECT NAME,
     ID,
     PHONE,
     EMAIL,
     EVENT,
     LOCATION
 FROM SHOPPERS
 WHERE LOCATION IN ('".implode("', '", $places)."')
 AND EVENT BETWEEN '{$start}' and '{$end}'
 AND ID BETWEEN '25687' AND '28050'
  ";

   //and then fetch array to print out results...
  .....
  ?>

A: Rather than hard-coding your "checked" attribute into each of your <input type="checkbox"> fields, you should be using PHP to determine if the GET variable associated with each field was passed to the script. In that case, you want to append the checked attribute to your <input> field. You can accomplish this by using a ternary operator right inside the field, as such:
<input type='checkbox' name='cities[]' value='CHI' <?= (in_array('CHI', $places)) ? 'checked' : ''; ?> >CHICAGO
<input type='checkbox' name='cities[]' value='DET' <?= (in_array('DET', $places)) ? 'checked' : ''; ?> >DETROIT
<input type='checkbox' name='cities[]' value='LA' <?= (in_array('LA', $places)) ? 'checked' : ''; ?> >LAS ANGELES
<input type='checkbox' name='cities[]' value='NYC' <?= (in_array('NYC', $places)) ? 'checked' : ''; ?> >NEW YORK
<input type='checkbox' name='cities[]' value='DALLAS' <?= (in_array('DALLAS', $places)) ? 'checked' : ''; ?> >DALLAS
<input type='checkbox' name='cities[]' value='SPR' <?= (in_array('SPR', $places)) ? 'checked' : ''; ?> >SPRINGFIELD
<input type='checkbox' name='cities[]' value='PHI' <?= (in_array('PHI', $places)) ? 'checked' : ''; ?> >PHILIDELPHIA

A: you could send the parameter which checkbox is checked in GET request,
and check it in your page
e.g
if ($_GET['param1']==1) // checked
{
?>
<input type='checkbox' name='cities[]' value='CHI' checked>CHICAGO
<?
else
?>
<input type='checkbox' name='cities[]' value='CHI' >CHICAGO
?>

A: <?php
$citiesGroup = array();
$citiesGroup['CHI'] = 'CHICAGO';
$citiesGroup['DET'] = 'DETROIT';
$citiesGroup['LA'] = 'LAS ANGELES';
$citiesGroup['NYC'] = 'NEW YORK';
$citiesGroup['DALLAS'] = 'DALLAS';
$citiesGroup['SPR'] = 'SPRINGFIELD';
$citiesGroup['PHI'] = 'PHILIDELPHIA';

$citiesChecked = array();
if (!empty($_GET['cities'])) {
    foreach ($_GET['cities'] as $cityCode) {
        $citiesChecked[] = $cityCode;
    }
}
else {
    foreach ($citiesGroup as $key => $value) {
        $citiesChecked[] = $cityCode;
    }
}
?>
<?php
foreach ($citiesGroup as $cityId => $cityName) {
    $chekced = in_array($cityId, $citiesChecked) ? 'checked="checked"' : '';
?>
<input type='checkbox' name='cities[]' value='<?php echo $cityId;?>' <?php echo $chekced;?>><?php echo $cityName;?>
<?php
}
?>

Get all checkboxed HTML in array and loop over it.
Above is the working code.


text:
Q: Publsih action in Open Graph giving error I am using Post action in Open graph using the below code, but getting the error message "[Object Object]"
What might be the problem???, i followed all the step by step guidance to  publish an action from this URL
https://developers.facebook.com/docs/opengraph/tutorial/#publish
<script type="text/javascript">
       function postArticle() {
           FB.api(
        '/me/ICONSolutions-test:Read',
        'post',
        { Article: 'http://fbwerks.com:8000/zhen/cookie.html' },
        function (response) {
            if (!response || response.error) {
                alert(response.error);
            } else {
                alert('Successful! Action ID: ' + response.id);
            }
        });
       }
  </script>

<input type="button" value="POST" onclick="postArticle()" />

A: You're alert()-ing an object which has no toString method that gives a readable representation of the object.
Dump the value to the console instead, console.log(response) – and have a look at it in Firebug or a similar debugging tool that implements console.


text:
Q: 'Can only compare identically-labeled Series objects' error when trying to compare column in dataframe with single data point I have a dataframe z, of which one of the columns are in datetime format:
index       time
0      2017-03-01 09:30:00.233
1      2017-03-01 09:30:00.243
2      2017-03-01 09:30:00.319
3      2017-03-01 09:30:00.981
4      2017-03-01 09:30:02.555
5      2017-03-01 09:30:02.959
6      2017-03-01 09:30:03.908
7      2017-03-01 09:30:12.659
8      2017-03-01 09:30:19.006
9      2017-03-01 09:30:22.990
10     2017-03-01 09:30:23.166
11     2017-03-01 09:30:27.879
12     2017-03-01 09:30:28.370

Basically, I want to delete the rows that is before a specific time in the data. For example, let's say in this case I want to delete all rows before 09:30:22.990 (row 9). What I have is:
first_trade_AM = z['Time'][z['Time'].dt.day == date][z['EventType'] == 'trade'].head(1)

for simplicity's sake, lets say this formula returns
    9      2017-03-01 09:30:22.990

then I have

z.drop(z['Time'][z['Time'].dt.day == date] < first_trade_AM)

but I get the error message:
ValueError: Can only compare identically-labeled Series objects

Any help will be greatly appreciated. Been stuck here for a while. Thanks!
EDIT: The dataset I posted above is a subset of the entire month's worth of data. Every single day has a unique first_trade_AM, which I found using:
for date in z['Time'].dt.day.unique():
    first_trade_AM = z.loc[(z['Time'].dt.day == date) & (z['EventType'] == 'trade'), 'Time'].head(1).item()

My follow-up question being, how do I delete all the observations for unique days BEFORE the particular day's unique first_trade_AM, without affecting the data from other dates?
EDIT:
More general data:
index  time                      EventType
0      2017-03-01 09:30:00.233       other
1      2017-03-01 09:30:00.243       trade
2      2017-03-01 09:30:00.319       trade
3      2017-03-01 09:30:00.981       other
4      2017-03-01 09:30:02.555       other
5      2017-03-02 09:30:02.959       other
6      2017-03-02 09:30:03.908       other
7      2017-03-02 09:30:12.659       trade
8      2017-03-02 09:30:19.006       trade
9      2017-03-02 09:30:22.990       trade
10     2017-03-02 09:30:23.166       other
11     2017-03-02 09:30:27.879       other
12     2017-03-02 09:30:28.370       other

A: I think the best is for datetimes select by position, here by iat:
first_obs_AM = z.loc[(z['Time'].dt.day == date) & (z['EventType'] == 'trade'), 'Time'].iat[0]

And last filter out values less as first_trade_AM, so need change < to >=:
z = z[z['Time'] >= first_trade_AM]

same as solution with invert mask by ~:
z = z[~(z['Time'] < first_trade_AM)]

If want compare dates:
z = z[z['Time'].dt.date >= first_trade_AM.date()]

EDIT:
You can compare 0 created by DataFrameGroupBy.cumsum and filter out by boolean indexing:
m = (z['EventType'] == 'trade').groupby(z['time'].dt.day).cumsum() != 0

z = z[m]
print (z)
                         time EventType
index
1     2017-03-01 09:30:00.243     trade
2     2017-03-01 09:30:00.319     trade
3     2017-03-01 09:30:00.981     other
4     2017-03-01 09:30:02.555     other
7     2017-03-02 09:30:12.659     trade
8     2017-03-02 09:30:19.006     trade
9     2017-03-02 09:30:22.990     trade
10    2017-03-02 09:30:23.166     other
11    2017-03-02 09:30:27.879     other
12    2017-03-02 09:30:28.370     other

Detail:
print ((z['EventType'] == 'trade').groupby(z['time'].dt.day).cumsum())
index
0     0.0
1     1.0
2     2.0
3     2.0
4     2.0
5     0.0
6     0.0
7     1.0
8     2.0
9     3.0
10    3.0
11    3.0
12    3.0
Name: EventType, dtype: float64

print ((z['EventType'] == 'trade').groupby(z['time'].dt.day).cumsum() != 0)
index
0     False
1      True
2      True
3      True
4      True
5     False
6     False
7      True
8      True
9      True
10     True
11     True
12     True
Name: EventType, dtype: bool


text:
Q: FFTW 1 thread is always better than many threads I'm doing some tests with FFTW using threads, the time of 1d transform(forward and backward) of large double complex values is always better for 1 thread than 2-3 or 4 threads. Can someone help me to solve this problem ? Thank you!!
An output for 1 thread is:
time           N
0.001515        16384
0.003364        32768
0.002625        65536
0.006060        131072
0.016190        262144
0.042389        524288
0.091719        1048576
0.209468        2097152
0.523317        4194304
1.196903        8388608

while for 4 threads (results is similar for 2 or 3 threads...) :
time            N
0.002071        16384
0.004009        32768
0.007989        65536
0.008715        131072
0.020615        262144
0.055483        524288
0.159392        1048576
0.322355        2097152
0.761479        4194304
1.647288        8388608

I test my code on two different machine with same results.
machine 1 :
Ubuntu 10.04.1 LTS
2.6.32-24-generic  x86_64 GNU/Linux
gcc version 4.4.3
Intel(R) Core(TM)2 Quad CPU    Q9550  @ 2.83GHz
ram 4gb

machine 2 :
Ubuntu 10.04.1 LTS
2.6.32-21-server  x86_64 GNU/Linux
gcc version 4.4.3
Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz
ram 8gb

I have code that generate random complex values and make forward and backward transform and take time of this two operation without take into account the calls for plan  or memory allocations.
FFTW is configurated as :
./configure --prefix=/home/.... --enable-threads

I try with -sse2 option too but with same results, 1 thread is always better.
I compile with :
gcc 1DFFTW.c -o 1DFFTW -I/$HOME/opt/fftw-3.3.2/include -L/$HOME/opt/fftw-3.3.2/lib -lrt -lfftw3_threads -lfftw3 -lpthread -lm

The important part of code is :
  if(nThreads>1){
     int err=fftw_init_threads();
     if (err==0)
        printf("thread creation error : %d\n",err);
     else
        fftw_plan_with_nthreads(nThreads);
  }
  int i;
  fftw_complex *in;
  fftw_complex *in2;

  fftw_complex *out;

  fftw_plan plan_backward;
  fftw_plan plan_forward;

  struct timespec start, stop;
  printf ( "\n" );
  printf ( "N= %d \n",n);

  in = fftw_malloc ( sizeof ( fftw_complex ) * n );

  srand ( time(NULL) );

  for ( i = 0; i < n; i++ )
  {
    in[i][0] = rand() / (double)RAND_MAX;
    in[i][1] = rand() / (double)RAND_MAX;
  }

  out = fftw_malloc ( sizeof ( fftw_complex ) * n );

  in2 = fftw_malloc ( sizeof ( fftw_complex ) * n );

  plan_forward = fftw_plan_dft_1d ( n, in, out, FFTW_FORWARD, FFTW_ESTIMATE );

  plan_backward = fftw_plan_dft_1d ( n, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE );

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&start);

  fftw_execute ( plan_forward );

  fftw_execute ( plan_backward );

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&stop);

A: The multithreaded algorithm has overhead associated with distributing the task among multiple CPUs and consolidating the results of the individual sub-problem. You are measuring the CPU time, not the wall clock time.
If you want to minimize CPU time, use one thread. That way, there's no threading overhead. If you want to minimize wall time, use more threads.


text:
Q: pass c structs (from c++ to Python) through boost python get_override method I've created a python 3 wrapper for a pure virtual C++ function using boost python.
I'm using get_override method to call my python wrapper as shown:
override f = this->get_override("handleMsg");
I can use the override f object to send primitive arguments to my python wrapper, for example:
f(10,20);//this works

int tmp =10;
f(10,20); //this works

My python method is simply printing an acknowledgement using print().
However, I need to pass either a cpp struct, or a shared_ptr to my python method.
If I try to send these, my python script crashes without any stack trace in gdb.
How can I send a cpp struct, pointer or boost shared_ptr to my python wrapper ?
I've tried numerous implementations described here, but none have worked.
I'm using Boost 1.48 and Python 3


text:
Q: geb.driver.DriverCreationException: failed to create driver from callback I'm setting up some Geb tests and I'm getting "geb.driver.DriverCreationException: failed to create driver from callback " errors.  Geb will try to launch the testing browser window, but once it does,  none of my tests ever run and I get the above error.
I just did an automatic Firefox update to Firefox 32.0.2 so I suspect that the new version and the Selenium Web Driver aren't playing nice any more?    How do I fix that?
here is the Geb.config file I've been using?  I haven't changed it about 5 months and it's worked fine until now...
import org.openqa.selenium.firefox.FirefoxDriver
import geb.waiting.WaitingSupport

reportsDir = "target/geb-reports"
driver = {
    //path is specific to each machine. This is the path to firefox.exe
    def pathToBin = 'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'
    System.setProperty("webdriver.firefox.bin",pathToBin)
    def driverInstance = new FirefoxDriver();
    driverInstance.manage().window().maximize()
    driverInstance
}

A: It was indeed what I thought it was.   Upgraded the jar dependency to Selenium 2.43.1 and it works fine.  Was using 2.42.2 before


text:
Q: is not null or not equal clause in cassandra does cassandra java datastax driver has a support for not equal operations or at least filtering nulls?
Something like
query = QueryBuilder.select().from(table).where(field.ne(null))

A: You can try:
select * from mytable where column_which_might_contain_null >= '';

if your column_which_might_contain_null is a text column.

A: It's not a problem of the driver. Cassandra doesn't support the "is not null" operator nor the "is not equal" operator. Have a look at supported operators. So there's no way to filter nulls either.
By the way, if you have these needs, I think you probably have a problem in your model.


text:
Q: How to display an image into an XCB window? I'm having trouble displaying an image (PNG extracted with libpng) into an XCB window, it is always entirely empty/white. I'm pretty sure the PNG extraction is correct since I can perfectly re-write it into another file.
I've tried everything I found (explanations, guides, documentation) and I'm running out of ideas:

*

*Creating an xcb_pixmap_t calling xcb_create_pixmap_from_bitmap_data() with the data taken from the PNG, then calling xcb_copy_area() into the EXPOSE part of the event loop.

*Creating an xcb_image_t* calling xcb_image_create_from_bitmap_data() then trying to map it to the window with xcb_image_put(). I've even tried to display each pixel with xcb_image_put_pixel(), but without success.

Code sample:
  xcb_pixmap_t pixmap = xcb_create_pixmap_from_bitmap_data(
                            connection, // xcb_connect(0, 0)    (type: xcb_connection_t*)
                            window, // xcb_generate_id(connection)    (type: xcb_window_t)
                            img.getData(), // uint8_t*
                            img.getWidth(), // 128
                            img.getHeight(), // 128
                            img.getBitDepth(), // 8
                            screen->black_pixel, // screen = xcb_setup_roots_iterator(xcb_get_setup(connection)).data    (type: xcb_screen_t*)
                            screen->white_pixel,
                            nullptr);

   // "img" is an instance of my own custom class, result of PNG reading
  xcb_image_t* image = xcb_image_create_from_bitmap_data(
                              img.getData(),
                              img.getWidth(),
                              img.getHeight()); // image->data seems fine

  xcb_image_put(connection,
                window,
                graphicsContext,
                image, 0, 0, 0); // This does nothing

  for (unsigned int i = 0; i < screen->height_in_pixels; ++i)
    for (unsigned int j = 0; j < screen->width_in_pixels; ++j)
      xcb_image_put_pixel(image, j, i, 0); // Displays nothing

  [...]

  // Into event loop
  case XCB_EXPOSE: {
    xcb_expose_event_t* exposeEvent = reinterpret_cast<xcb_expose_event_t*>(event);
    xcb_copy_area(connection,
                  pixmap,
                  window,
                  graphicsContext,
                  exposeEvent->x, exposeEvent->y, // Top left x & y coordinates of the source's region to copy
                  exposeEvent->x, exposeEvent->y, // Top left x & y coordinates of the destination's region to copy to
                  exposeEvent->width,
                  exposeEvent->height);
    xcb_flush(connection);
    break;
  }

From the examples I found I saw that it didn't need a colormap, but could that be the case? Could anyone tell me where I've gone wrong?

A: I threw together a simple xcb image viewer about 4 years ago, but just noticed this question, so apologies for the necromancy.
It uses xcb_image, stb_image and nanosvg, but compiles to a relatively small static binary (with a musl or uclibc toolchain)
#include <xcb/xcb.h>
#include <xcb/xcb_image.h>
#define STBI_NO_HDR
#define STBI_NO_LINEAR
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define NANOSVG_IMPLEMENTATION
#include "nanosvg.h"
#define NANOSVGRAST_IMPLEMENTATION
#include "nanosvgrast.h"

int main(int argc, char **argv){
   xcb_connection_t *c = xcb_connect(0, 0);
   xcb_screen_t *s = xcb_setup_roots_iterator(xcb_get_setup(c)).data;
   int w, h, n,
      depth = s->root_depth,
      win_class = XCB_WINDOW_CLASS_INPUT_OUTPUT,
      format = XCB_IMAGE_FORMAT_Z_PIXMAP;
   xcb_colormap_t colormap = s->default_colormap;
   xcb_drawable_t win = xcb_generate_id(c);
   xcb_gcontext_t gc = xcb_generate_id(c);
   xcb_pixmap_t pixmap = xcb_generate_id(c);
   xcb_generic_event_t *ev;
   xcb_image_t *image;
   NSVGimage *shapes = NULL;
   NSVGrasterizer *rast = NULL;
   char *data = NULL;
   unsigned *dp;
   size_t i, len;
   uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
      value_mask = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS,
      values[] = { s->black_pixel, value_mask };

   if (argc<2) return -1;
   if ((data = stbi_load(argv[1], &w, &h, &n, 4)))
      ;
   else if ((shapes = nsvgParseFromFile(argv[1], "px", 96.0f))) {
      w = (int)shapes->width;
      h = (int)shapes->height;
      rast = nsvgCreateRasterizer();
      data = malloc(w*h*4);
      nsvgRasterize(rast, shapes, 0,0,1, data, w, h, w*4);
   }else return -1;
   for(i=0,len=w*h,dp=(unsigned *)data;i<len;i++) //rgba to bgra
      dp[i]=dp[i]&0xff00ff00|((dp[i]>>16)&0xFF)|((dp[i]<<16)&0xFF0000);
   xcb_create_window(c,depth,win,s->root,0,0,w,h,1,win_class,s->root_visual,mask,values);
   xcb_create_pixmap(c,depth,pixmap,win,w,h);
   xcb_create_gc(c,gc,pixmap,0,NULL);
   image = xcb_image_create_native(c,w,h,format,depth,data,w*h*4,data);
   xcb_image_put(c, pixmap, gc, image, 0, 0, 0);
   xcb_image_destroy(image);
   xcb_map_window(c, win);
   xcb_flush(c);
   while ((ev = xcb_wait_for_event(c))) {
      switch (ev->response_type & ~0x80){
      case XCB_EXPOSE: {
         xcb_expose_event_t *x = (xcb_expose_event_t *)ev;
         xcb_copy_area(c,pixmap,win,gc,x->x,x->y,x->x,x->y,x->width,x->height);
         xcb_flush(c);
      }break;
      case XCB_BUTTON_PRESS: goto end;
      default: break;
      }
   }
end:
   xcb_free_pixmap(c, pixmap);
   xcb_disconnect(c);
   return 0;
}


text:
Q: Grouping in django query set I have an query set object with has two attributes: words, number_of_letters. I would like to group the words by the no of letters in them. For example, all the words with 4 letters should be grouped together. How do I do this when I don't know the maximum number of letters the grouping has? Will I be able to put the grouping into separate objects?
Also, is there a way to modify all the words in the object in one go? For example, if I need to prefix a string to all the words in the object?


text:
Q: How can I cleanly construct a NewType using a non-compatible type in Python? I'm working on a project where I've defined a number of NewType types to represent various identifiers, so that they can't be accidentally mingled together.
from typing import NewType
UserId = NewType('UserId', int)

Although this has brought the benefits mentioned above, there are cases where it has been frustrating. For server routes that accept these identifiers as arguments in the query string, the process of converting to the required type seems needlessly tedious.
@app.get('/some_route')
def some_route():
    user = UserId(int(request.args['user_id']))

Is there a way I can cleanly use the default int constructor when initialising a UserId. I'm looking for syntax as clean as the following, but without the complexity of needing to create a class for each type?
@app.get('/some_route')
def some_route():
    # The conversion from str to int is performed behind the scenes automatically
    user = UserId(request.args['user_id'])

A: Ok so it turns out that I overlooked the simplest solution: just use a subclass.
In this case, the type is created using
class UserId(int):
    pass

Note that this does have the performance drawbacks associated with creating a subclass, however.


text:
Q: Reserve CPU time for one program? Prerequisites
I have a (physical) server running multiple (virtual) servers. There are 11 servers in total, number 0 through 9 are invoked by
servinit XXXXn

Where XXXXn is the port number and n is the server number. The other server is invoked by
apiinit

And runs on port 8080. In conclusion, there are 11 processes, 10 with the binary name servinit and one with apiinit.
Goal
The servinit processes must always be responsive, in other words, the apiinit process must never consume all CPU time. I want to limit the total CPU time for apiinit to a percentage number, lets say 90, so that the servinit processes always have 10 percent CPU headroom to operate flawlessly.
What is the most efficient way of handling this?
Software
The physical server runs
Ubuntu Desktop
Release 12.04 (precise) 64-bit
Kernel: 3.14.32-xxxx-std-ipv6-64

A: Since you run a 3.14+ Linux kernel you can easily constrain the CPU share of a running application through the SCHED_DEADLINE policy. This policy allows you to set the CPU share of an application by setting a budget and a period (the emaining is that the application is not allowed to consume more than its budget on a period of time). For example, if budget is 3msec and period is 10msec, the application can at most consume at most 30% of the CPU. In particular, the system will guarantee 3msec every 10msec.

A: Solved using the optional package cpulimit.
Example, limiting apiinit to 50 percent CPU time (on a dual-core CPU):
sudo cpulimit -e apiinit -l 100 &


text:
Q: Query nested JSON with LINQ I have the following JSON:
{
  "rooms": [
    {
      "roomId": 1,
      "lightsPreset": [
        {
          "lightsPresetId": 1,
          "loadValues": [ 1, 2, 3 ]
        },
        {
          "lightsPresetId": 2,
          "loadValues": [ 11, 12, 13 ]
        }]
    },
    {
      "roomId": 2,
      "lightsPreset": [
        {
          "lightsPresetId": 1,
          "loadValues": [ 21, 22, 23 ]
        },
        {
          "lightsPresetId": 2,
          "loadValues": [ 211, 212, 213 ]
        }]
    }
  ]
}

and I need to get loadValues out of it (say roomId = 1 and lightsPresetId = 1)
I managed to do it using JSONPath
IEnumerable<JToken> loadValues = o.SelectTokens("$.rooms[?(@.roomId == 1)].lightsPreset[?(@.lightsPresetId == 1)].loadValues[*]");

but my goal is to make it work in .Net Framework 3.5 where JSONPath didn't work.
Trying this with LINQ gives me everything for roomId = 1, but I can't figure out how to query nested arrays.
JObject o = JObject.Parse(rawJson);
var itemList = from values in o["rooms"].Children()
where (decimal)values["roomId"] == 1
select values;

Thank you.

A: try this
var rooms = (JArray) JObject.Parse(json)["rooms"];

var roomId=1;
var lightsPresetId =1;

int[] values = rooms.Where(r => (int)r["roomId"] == roomId)
    .Select(r=> r["lightsPreset"]).FirstOrDefault()
    .FirstOrDefault(x => (int)x["lightsPresetId"] == lightsPresetId)["loadValues"]
    .ToObject<int[]>().ToArray();

A: On a PC now, so I can post it up as an answer rather than comment from the phone
If you visit https://quicktype.io you can use it to generate classes from your JSON:
// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using SomeNamespace;
//
//    var someRootClassName = SomeRootClassName.FromJson(jsonString);

namespace SomeNamespace
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class SomeRootClassName
    {
        [JsonProperty("rooms")]
        public List<Room> Rooms { get; set; }
    }

    public partial class Room
    {
        [JsonProperty("roomId")]
        public long RoomId { get; set; }

        [JsonProperty("lightsPreset")]
        public List<LightsPreset> LightsPresets { get; set; }
    }

    public partial class LightsPreset
    {
        [JsonProperty("lightsPresetId")]
        public long LightsPresetId { get; set; }

        [JsonProperty("loadValues")]
        public List<long> LoadValues { get; set; }
    }

    public partial class SomeRootClassName
    {
        public static SomeRootClassName FromJson(string json) => JsonConvert.DeserializeObject<SomeRootClassName>(json, SomeNamespace.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this SomeRootClassName self) => JsonConvert.SerializeObject(self, SomeNamespace.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

Then you can convert your JSON to objects like this:
var root = SomeRootClassName.FromJson(rawJson);

And you can query it like:
var array = root.Rooms.First(r => r.RoomId == 1).LightsPresets.First(lp => lp.LightsPresetId == 1).LoadValues;

Or if those IDs might not exist:
var array = root.Rooms.FirstOrDefault(r => r.RoomId == 1)?.LightsPresets.First(lp => lp.LightsPresetId == 1)?.LoadValues;
if(array != null) ....

When working with LINQ, it helps to make sure that anything that is a collection/array has a plural name. Then you can easily know whether you can just access a property of it (if it's singular) or have to use some method like First, Last, Single, Any, Where etc, if it has a plural name:
root.Rooms                             //plural, collection
  .First(r => r.RoomId == 1)           //.First on a plural results in a singular, a room object
  .LightsPresets                       //access a plural property of the single room above
  .First(lp => lp.LightsPresetId == 1) //first lightpresent in many LightPresets in the room
  .LoadValues                          //plural again; it's an array. The LINQ query resolves to an array output

Give your lambda arguments sensible names too - don't use x for everything; i used r for "a room in the collection of rooms", and lp for "a lightpreset in the collection of lightpresets"


text:
Q: Finding the tangent lines to an implicit curve Let $x \gt 0$. Find the tangent lines to the curve $x^{\sin y} + y^2 - x = (\pi^2)/(4)$ at the points of the intersection of the given curve and the line $x=1$.
I found this result $y=\pm \pi/2$ but I'm not sure.

A: $$x^{\sin y} +y^2 -x =\frac{\pi^2}{4} $$ When $x=1$, $$1+y^2-1=\frac{\pi^2}{4} \implies y=\pm \frac{\pi}{2} $$
Now differentiate.  $\bigg [(x ^{\sin y} )' = ( e^{\sin y \ln x} )' = x^{\sin y}\left ( \frac{\sin y}{x} + \ln x\cos y \frac{dy}{dx} \right) \bigg]$
$$x^{\sin y}\left ( \frac{\sin y}{x} + \ln x\cos y \frac{dy}{dx} \right) +2y\frac{dy}{dx} -1 =0 $$
to readily obtain $y'(1,\pi/2) = 0$ and $y'(1,-\pi/2) = -\frac{2}{\pi}$ and the equations of the tangents:
$$y=\frac{\pi}{2} \\ y+\frac{\pi}{2} = -\frac{2}{\pi} (x-1) $$


text:
Q: Recursively get pivot table data This one is quite hard to explain and word, so i apologise if the title doesn't make sense!
Basically at the moment I have a pivot table like this
ID | USER_ID | FRIEND_ID
1  |       1 |        2
2  |       5 |        10
3  |       2 |        5
4  |       3 |        9
5  |       5 |        4

And I can get all of the friends for a user by having my relationship like this
public function user_friends(){
    return $this->belongsToMany('App\Friends', 'user_friend', 'USER_ID', 'FRIEND_ID');
}

I want to be able to access all of my friends friends recursively in the cleanest way possible by referencing 1 id.
For example, if i get the user with an id of 1 and call the above user_friends method, it would return friend with an id of 2 and that is it.
But friend 2 also has a friend with the id of 5, and id 5 has friends with the id's of 10 and 4, and so on, so i also want to get all of those as-well.
Basically by calling a single user id, I want to get each of the friends that are directly linked to user 1, then recursively get each of their friends, and so on and so forth until I have all of the friends that can be linked to user 1 in some way, shape or form.
Is this possible?


text:
Q: How to add a button to Form View's action without creating Wizard I want to add a button inside Action found in Form View.I don't want to create a seperate wizard for it.crm.lead is my model.
Python Code
def create_booking(self):
    print "hello_from_booking"
    print "hello_from_booking"
    print "hello_from_booking"

XML
<record id="create_booking_form" model="ir.ui.view">
    <field name="name">create_booking</field>
    <field name="model">crm.lead</field>
    <field name="arch" type="xml">
        <form string="Create Booking">
       </form>
    </field>
</record>

<record id="action_view_create_booking" model="ir.actions.act_window">
    <field name="name">Create Booking</field>
    <field name="res_model">crm.lead</field>
    <field name="view_type">form</field>
    <field name="view_mode">tree,form</field>
    <field name="view_id" ref="create_booking_form"/>
    <field name="target">new</field>
</record>

<record model="ir.values" id="action_create_booking">
    <field name="name">Create Booking</field>
    <field name="key2">client_action_multi</field>
    <field name="value" eval="'ir.actions.act_window,' +str(ref('action_view_create_booking'))" />
    <field name="key">action</field>
    <field name="model">crm.lead</field>
</record>

Thanks in Advance...

A: You could use an ir.actions.server instead of ir.actions.act_window to be able to run a custom action code directly from the action "Create Booking"


text:
Q: Remember Me Cookie in CakePHP 3 with auth How to use "remember me" cookie with auth in CakePHP 3?
I have use the following code in my controller:
if ($this->request->data['data']['rememberMe'] == "on") {
    $cookie = array();
    $cookie['username'] = $this->request->data['username'];
    $cookie['password'] = $this->request->data['password'];
    $this->request->Cookie->write('rememberMe', $cookie, true, "1 week");
    unset($this->request->data['rememberMe']);
}

and get the error :

Call to a member function write() on a non-object

A: Just like the error says. You should write cookies like this instead:
$this->Cookie->write ();
See this link for more detailed information: http://book.cakephp.org/3.0/en/controllers/components/cookie.html#Cake\Controller\Component\CookieComponent::write


text:
Q: jquery selector for background images What is the right selector to pick background image/s of a div?

A: You can use css('background-image'), however, it will return a string like so...
url(../images/image.png)

To strip away the url() wrapper, use this...
var image = element.css('background-image').replace(/^url\((.*?)\)$/, '$1');

jsFiddle.

A: Select the divs and get the attribute:
$("div").each(function(){
    alert($(this).css("background-image"));
});

If you want to skip divs without a background image you can use .filter to skip those.

A: $("#myElement").css("background-image");


text:
Q: Workflow to create global mapbox tileset I am in process of creating a hiking map rendered from OSM data using Mapbox. It works quite fine already, however some data are missing in the Mapbox Streets V7 datasets, namely:

*

*bus stops

*power lines

*marked hiking/cycling routes

I am able to get all those data using Overpass Turbo for small regions and upload them as tilesets, however the largest area I am able to process this way is about 200x200 km for highly detailed areas like Europe.
Given the quite generous 50 GB limit for tilesets, I think I should be able to achieve a global (or at least continental) coverage with custom tilesets for those features. However I am not sure how to proceed. I have found an article which describes a workflow like this, however it does not show any implementation details:
Building a Custom Trail Map Using OSM and Mapbox
I think it could be possible to build some tool which would download data using Overpass API part by part. I understand the tools needs to avoid being too heavy on Overpass servers and I am fine with that, I can develop my queries using small region only and I am fine with downloading global data for a few weeks if needed. However I am bit concerned with issues about duplicate / missing data on the part boundaries. Is there any tool which would be able do handle the splitting and merging of the Overpass requests and responses (or at least merging the responses)? If not, is there any advice how to build such tool?

A: As suggested by mmd, it seems more practical to process planet or region files locally. I was surprised how are the tools performing the processing fast. The only operation which really took look for me was downloading the data.
Filtering / manipulating data using OsmComvert + OsmFilter (osmctools) or Osmium is quite easy, I think easier then trying to invent complicated Overpass QL querys.
My current workflow is:

*

*use osmconvert to add/modify tags and convert to o5m format

*use osmfilter to select just the data I want and convert to osm format

*use ogr2ogr to extract individual layers as GeoJSON

*use tippecanoe to merge the layers and process them into MBTiles

Currently I am processing about 3 GB of data (three European countries) and it takes about 10 minutes to complete all the steps above.


text:
Q: Postgresql: Recursive query for undirected graph I want to traverse through an undirected graph via SQL in Postgresql.
I have one table which consists of all edges with starting points and end points (as ids).
edge_id | start_node | end_node
      1            4          5
      2            5          7
      3            1          5

This is what I tried so far. This works in some cases but travels directed trough the graph which leads to mistakes in some cases.
WITH RECURSIVE path AS
(
    SELECT
        edge_id, start_node, end_node
    FROM
        simulation.edge_data
    WHERE
        start_node = ANY ('{ 1,8}'::int[])
        OR end_node = ANY ('{ 1,8}'::int[])

    UNION

    SELECT
        e.edge_id, e.start_node, e.end_node
    FROM
        simulation.edge_data e, path s
    WHERE
        s.start_node = e.start_node
        OR s.start_node = e.end_node
        OR s.end_node = e.end_node
        OR s.end_node = e.start_node
)
SELECT * FROM path;

Output should be all edges that are connected to a starting point


text:
Q: Solve the equation $y''+y'=\sec(x)$ Solve the equation $$y''+y'=\sec(x).$$ By solving the associated homogenous equation, I get complementary solution is $y_c(x)=A+Be^{-x}$. Then by using the method of variation of parameter, I let $y_p(x)=u_1+u_2e^{-x}$ where $u_1,u_2$ satisfy  $$u_1'+u_2' e^{-x}=0, \quad -u_2' e^{-x}=\sec(x).$$ Then I stuck at finding $u_2$ as $u_2^{\prime}=-e^x \sec(x)$ and I have no idea on how to integrate this. Can anyone guide me?

A: $y''+y'=sec(x)$
$(y'e^x)'=\dfrac{d\int sec(x)e^xdx}{dx}$
$y'=e^{-x}\int sec(x)e^xdx
+Ce^{-x}$
$y=\int e^{-x}\int sec(x)e^xdx dx+ C_1e^{-x}+C_2$
I do not know of any elementary form for the integrals. Wolfram gives an answer


text:
Q: Não consigo obter o tamanho do arquivo Pessoal estou com o seguinte problema no meu código ele não consegue entrar na função para obter o tamanho do arquivo, estou usando o Phonegap para desenvolvimento, segue o código abaixo
function onSuccess(imageData) {
  window.resolveLocalFileSystemURL(imageData, function (fileEntry) {
        fileEntry.file(function (file) {
            if (file.size > 2097152) {
                alert("não pode ser maior que 2mb");
            } else {
             //aqui vai o codigo para mostrar a imagem

            }
        }, function (evt) {

        });
    },
    function () {

    });
   }

Então, estou tentando o obter o tamanho do arquivo mas ele não entra na função , não mostra nada, alguém sabe me dizer o problema ou estou fazendo errado.

A: Tenta colocar file.files[0].size no lugar de file.size

A: Consegui resolver o problema eu concatenei com 'file:///'+imageData e o caminho ficou correto


text:
Q: Jquery selection, adding id just to make selection easier, good or not? I just would like to ask you if It's good or not to add IDs on some HTML elements just to make their selection easier. Instead of using all the methods available to traverse the dom in Jquery for exemple.
For sure, It makes the HTML a bit heavier as I add IDs on more elements, but is there anything else bad with this practice ?
Thank you,

A: Advantages

*

*It's faster, jQuery "#id" selector use the native document.getElementById. and the uniqueness of an ID make it really fast (it must implement an BST I guess)

*Your code is cleaner. When I read code I prefer $("#mycustomItem") rather than $"(div ul li:eq(3)"). so you will ba able to maintain your code easily and find bug quickly

Disadvantages

*

*HTML heavier. I don't think and id will make your file significantly heavier. If you use compression like gzip you won't be able to notice the difference even for a high number of elements

*Server-side logic more complicated : if you generate id's you will make to compute them on server-side, so it will increase the complexity of your code. In most of the case this complexity added will be  more important than the complexity you remove on the client size.

Conclusion
If you can add id's use them but if it increase the complexity on your server side logic don't do it. The speed you earn will not worth the time/complexity you spend generating the id on server-side.


text:
Q: How can I adjust sales percentages by population? In my data below, I can figure in my head that regions A and B will end up roughly equal, but I can't figure out how to calculate it.
$$
\begin{array}{crr}
  region & \% \text{ population} & \% \text{ sales} \\\hline
  A & 49.1 & 83.0 \\
  B &  5.5 &  9.1 \\
  C & 31.8 &  4.5 \\
  D &  3.7 &  2.3 \\
  E &  9.9 &  1.1
\end{array}
$$

A: As you thought about it, "normalize" the results to get, for example,
$$\begin{array}{crr}
 \text{ region} & P & S & \frac SP\\
A&  49.1 & 83.0 & 1.690 \\
 B &5.5 & 9.1 & 1.655 \\
C & 31.8 & 4.5 & 0.142 \\
D &  3.7 & 2.3 & 0.622 \\
E & 9.9 & 1.1 & 0.111
\end{array}$$


text:
Q: Java: Newbie-ish inheritance question Suppose I have a base class B, and a derived class D.  I wish to have a method foo() within my base class that returns a new object of whatever type the instance is.  So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.
Is this possible?

A: As long as each class has a default constructor:
    public B instance() throws Exception {
        return getClass().newInstance();
    }

A: Don't. Make the "foo" method abstract.
abstract class B {
    public abstract B foo();
}

Or receive an abstract factory through the base class constructor:
abstract class B {
    private final BFactory factory;
    protected B(BFactory factory) {
        this.factory = factory;
    }
    public B foo() {
        return factory.create();
    }
}
interface BFactory {
    B create();
}

Add covariant return types and generics to taste.

A: I think this might be possible to do using reflection, i.e. in your superclass you have:
public ClassName getFoo() throws InstantiationException, IllegalAccessException
{
    return getClass().newInstance();
}

Where ClassName is the name of your base class.
You'll have to cast it wherever you want to use it though... I'm not sure this is really a great solution!
Edit: newInstance() type methods are usually static, and of course you won't have an idea of what the type of your subclass is with a static method.
I don't think there's any way of getting a static method to (dynamically) create an instance of a subclass.

A: Well, I could be off but I would assume that since "this" always refers to the current object, you could do something like
public B foo() {
    return this.getClass().newInstance();
}

or something along those lines? If you create an instance of D and then call d.foo() you should get an instance of D returned as a B. You could return it as a plain Object but you should be as specific as possible in this instance, I think.

A: Apart from the fact that I think there probably is a design flaw if you want to accomplish this, you could try the following approach.
In your question, you are using static (class) methods, B.foo(), D.foo(), this cannot be accomplished using inheritance because the static methods do not have a dynamic nature, they do not take part in the lookup system. So you don't have enough type information.
If you are using a member function foo() you could have the following construct:
public class B {
    public B foo()
    throws IllegalAccessException, InstantiationException {
        return this.getClass().newInstance();
    }
}

public class D  extends B{
}

public class Test {
    public static final void main(String[] args)
    {
        try {
            System.out.println((new B()).foo());
            System.out.println((new D()).foo());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}

A: As the other answers say, you can use getClass().newInstance() if there is a no-argument constructor in each subclass (make sure to catch InstantiationException and IllegalAccessException).
If any of the constructors require arguments, you can either use reflection or (preferable in my view) define a method like getNewInstance() which you can override in the subclass only if needed.
e.g.
Thing foo() {
    Thing th = getNewInstance();
    // do some stuff with th
    return th;
}

Thing getNewInstance() {
    return getClass().newInstance();
}

Then getNewInstance() can be overridden only if you really need to, for subclasses that don't have the default constructor.
Thing getNewInstance() {
    return new BigThing(10, ThingSize.METRES);
}

A: @Rik
Well, the real problem is that I have a abstract base class Thing.  And Thing has a method called getNextThing() which returns a new instance of Thing.
Then, I have a number of subclasses like BigThing, LittleThing, SomethingThing, and I don't want to keep rewriting the getNextThing() method for each of them.  It seems wasteful, since they all do the same... thing.
Am I incorrect in my approach?

A: I'm not sure why you're trying to do what you're actually trying to do.  Providing more of a context might let us give you more help.
public class B <X extends B>{

public X foo() throws InstantiationException, IllegalAccessException{
    return (X)this.getClass().newInstance();
}
}
public class C extends B<C>{

}

Let me offer you this piece of advice.  The way CS classes tend to be taught is that professors are enamored with inheritance, but haven't figured out composition.  I think What you might be looking for is composition.   So instead of calling getNextThing on the Thing itself, maybe you should think about making Thing implement Iterable
This means you will just need to write an Iterator that can encapsulate the logic of getting the next thing, as it doesn't seem to fit into your inheritance model.  Another advantage of this is that you get some nice syntactic devices out of this (enhanced for loop comprehension).


text:
Q: Issue while evaluating the condition in javascript I am fetching one value from controller to jsp and trying to validate the value as follows,
<c:set var="healthWorkerOptions" value='${map["healthWorkerOptions"]}' />

<script>
validateSelectedOption();

function validateSelectedOption()
{
        alert("test");

        if(healthWorkerOptions != null)
        {
        alert("not null");
        }
        else{
        alert("null");
        }
}
</script>

Value is coming from the controller and able see the fetched value with following statement,
<p> ${healthWorkerOptions} </p>

But while evaluating the condition nothing is happening. What's wrong in my code? I am able to see only test alert but not not null or null alert.
Any suggestion

A: healthWorkerOptions is not defined in scope of your JS. A debugger should tell you this.
function validateSelectedOption() {
    var healthWorkerOptions = '<c:out value="${healthWorkerOptions}" />';

    [...]
}

A: You can directly use el in JavaScript also like below :
healthWorkerOptions = "${healthWorkerOptions}";
if(healthWorkerOptions != null)
{
    alert("not null");
} else {
    alert("null");
}


text:
Q: Changing Css From Array Value I know in Angular you can dynamically add a class to the element but how do I change the value of a property? I want each button to be the next spotColour of the array. I feel like my example explains it well:
<button style="background-color: arrThemes[0]['spotColour']"></button>
<button style="background-color: arrThemes[1]['spotColour']"></button>
<button style="background-color: arrThemes[2]['spotColour']"></button>

arrThemes = [
  {spotColour : 'rgb(238, 68, 136)', baseColour : 'rgb(80, 54, 78)'},
  {spotColour : 'rgb(179, 165, 136)', baseColour : 'rgb(88, 67, 59)'},
  {spotColour : 'rgb(87, 167, 82)', baseColour : 'rgb(47, 68, 46)'},
];

A: Try something like this expression with
<button style="{{ 'background-color: ' + arrThemes[0]['spotColour'] }}"></button>

or in more civil way using NgStyle
<button [ngStyle]="{'background-color': arrThemes[0]['spotColour']}"></button>

A: use ngStyle tag to dynamically add styles
<button *ngFor="let item of arrThemes " [ngStyle]="{'background-color': item.spotColour }"></button>

A: you can use ngStyle angular directive for that.
like below
<button [ngStyle]="{'background-color': arrThemes[0]['spotColour']}"></button>


text:
Q: React redux not able send post data to mapStateToProps from react component I am new to react and redux. I am trying to make a post request using react-redux, react-thunk and axios.
Here is the scenario - I have Gmail login in my react-native app. If the user is new I am trying to save the user in the database.
I have setup redux for that but I can't send post data to mapDispatchToProps. The problem is I have data in Gmail component but not able to use that data in mapDispatchToProps.
How to use this post data in mapDispatchToProps?
Thank you in advance
here is the code
userActions.ts
import axios from 'axios'
import { ADD_USER, GET_USER, INITIATE_REQUEST, REQUEST_FAILURE, User , UserActionTypes } from '../types/userTypes'

export const addUser = (user : User) : UserActionTypes => {
    return {
        type: ADD_USER,
        payload : user
    }
}

export const postUser = (user : User) => {
    return(dispatch : any ) => {

        dispatch(initiateRequest)
        axios.post(`${URL}users`, user ).then(data => {
            console.log(data.data)
            dispatch(getUser(data.data))

        }).catch(err => {
            console.log(err)
            dispatch(failure(err))
        })
    }
}

userReducer.ts
const userReducer = (state = initialState, action : UserActionTypes) => {
    switch(action.type){
        case ADD_USER : {
            return {
                ...state,
                loading : false,
                users : action.payload,
                error : ''
            }
        }

        default : return state
    }

}

GmailComponet.ts
const GmailLogin : React.FC<props> = ({userData, fetch, post}) => {

   const signIn = async () => {
                // other gmail login code
                if(user) {
                   console.log("new user")
                    // add to database
                    let data = {
                        name : String(user.displayName),
                        email : String(user.email),
                        photo : String(user.photoURL),
                        uid : String(user.uid)
                    }
                    console.log(data)
                    post(data)
                }
            }
        };

    const mapStateToProps = (state : any ) => {
        return {
            userData : state.user
        }
    }

    const mapDispatchToProps = (dispatch : any) => {
        return {
            fetch: () => dispatch(getUsers()),
            post : () => dispatch(postUser()) // error here
        }
    }

    export default connect
    (mapStateToProps, mapDispatchToProps)
     (GmailLogin)

A: I have resolved the issue. The dispatch actions are basically our actions in userActions.ts file. So basically this action accepts a parameter that we can use for posting data
const mapDispatchToProps = (dispatch : any) => {
    return {
        fetch: () => dispatch(getUsers()),
        postUser : (user : User) => dispatch(postUser(user))
    }
}


text:
Q: Excel VBA assigning cells to cells (inserting cell value to each row according to another worksheet) I have two worksheets in Excel, the first contains list of companies (row: company name, city, street, phone number, email, etc.), the second sheet contains list of all cities in a given country with the districts (row: city, district). I need to add name of appropriate district to each row in the first sheet, according to the data from the second worksheet.
Please suggest some solution. Thanks.
The data structure of the sheets are the following:
Sheet 1 (simplified):
Company name | Street name | City | Phone number
A-B Finance Ltd | Carl-Zeiss-Strasse 5 | Alsdorf | +49 18 4514 8451
LR Munchen Ltd | Christ-König-Strasse 85 | Monschau | +49 18 0181 1584
Finance Master Ltd | Castorstrasse 2 | Herrieden | +49 15 8451 2154
Sheet 2:
City | District
Alsdorf | Aachen
Herrieden | Ansbach
Monschau | Aachen
As a result I need to get this in Sheet 1:
Company name | Street name | City | Phone number | District
A-B Finance Ltd | Carl-Zeiss-Strasse 5 | Alsdorf | +49 18 4514 8451 | Aachen
LR Munchen Ltd | Christ-König-Strasse 85 | Monschau | +49 18 0181 1584 | Aachen
Finance Master Ltd | Castorstrasse 2 | Herrieden | +49 15 8451 2154 | Ansbach

A: First you need a way to match the data in both sheets, e.g. a list of streets for each district.
If this information is not provided then no program can help you.
As soon as you have this, the code should be straight forward:

*

*loop through each row in first sheet

*match information from sheets (this information is missing in your explanation)

*add information from second sheet to first sheet

I can add some code if you provide more information about your data structure.


text:
Q: aspnet webapi bind query string to object <HttpGet()>
Public Function Search(<FromUri()> ByVal name As Name) As HttpResponseMessage
  // get params from complex type
  // or check for model validation
  name.firstName;
  name.lastName;
End Function

Public Class Name
 <Required()>
 Public firstName As String
 <Required()>
 Public lastName As String
End Class

/api/abc/search?firstName=jack&lastName=daniels

I am trying to send a comlex type as a query parameter but name is always null even though I am using fromUri attribute. What am I missing?
EDIT: I am also using Required() attribute from System.ComponentModel.DataAnnotations .

A: I found the problem. I was missing the Property keywords on my fields.
Public Class Name
 <Required()>
 Public firstName As String
 <Required()>
 Public lastName As String
End Class

So, it worked with the following change.
Public Class Name
 <Required()>
 Public Property firstName As String
 <Required()>
 Public Property lastName As String
End Class

The problem solved. I think, without properties, the class does not expose its fields, so I cant read them from uri.


text:
Q: AppleScript: Press "Q" every 1 second after idle for X amount of time in application "Roblox" I am looking for a script that would press "Q" every second when idle for a certain amount of time in an application. I have never coded before and have several issues with code (below) that'd I have no idea how to fix
Here is the code I've tried:
repeat 52 times
    repeat 52 times
        delay 0.5
        tell application "Roblox"
            set currentTab to do
            script ("q") in front window
        end tell
        delay 0.5
    end repeat
end repeat

It errors with:

error "The variable do is not defined." number -2753 from "do"

A: I do not have Roblox, so I can not help you with anything Roblox application specific. However, the following example AppleScript code does in one repeat loop, as I fail to see the need for two  repeat loops, it sends a keystroke to the frontmost application, in this case Roblox.
repeat 2704 times
    tell application "Roblox" to activate
    delay 0.5
    tell application "System Events" to keystroke "q"
    delay 0.5
end repeat


text:
Q: Can anybody explain why using \multicolumn changes the width of the four-column tabular environment? The following example typesets five tabular environments. All five tabulars share the same definition,
\begin{tabular} { | p{1.67cm} |  p{1.67cm} | p{1.67cm} | p{8.0cm} |}

However, the overall widths of the five tabulars differ considerably, depending on how various \multicolumn statements are employed. Can somebody explain why this is happening?
\documentclass[preview,border=100pt]{standalone}
\setlength{\tabcolsep}{0.2cm}
\begin{document}

\begin{tabular} { | p{1.67cm} |  p{1.67cm} | p{1.67cm} | p{8.0cm} |}\hline
\multicolumn{4}{|c|}{ HEAD}\\\hline\hline
\multicolumn{2}{|c|}{A}& C & D\\\hline
A & B & C & D\\\hline
\end{tabular}

\bigskip
\begin{tabular} { | p{1.67cm} |  p{1.67cm} | p{1.67cm} | p{8.0cm} |}\hline
\multicolumn{4}{|c|}{ HEAD}\\\hline\hline
\multicolumn{2}{|c|}{A}& C & D\\\hline
\multicolumn{1}{|c|}{A} & \multicolumn{1}{|c|}{B}  & \multicolumn{1}{|c|}{C}  & \multicolumn{1}{|c|}{D} \\\hline
\end{tabular}

\bigskip
\begin{tabular} { | p{1.67cm} |  p{1.67cm} | p{1.67cm} | p{8.0cm} |}\hline
\multicolumn{4}{|c|}{ HEAD}\\\hline\hline
\multicolumn{2}{|c|}{A}& C & D\\\hline
\end{tabular}

\bigskip
\begin{tabular} { | p{1.67cm} |  p{1.67cm} | p{1.67cm} | p{8.0cm} |}\hline
\multicolumn{4}{|c|}{ HEAD}\\\hline\hline
\multicolumn{3}{|c|}{A} & D\\\hline
\end{tabular}

\bigskip
\begin{tabular} { | p{1.67cm} |  p{1.67cm} | p{1.67cm} | p{8.0cm} |}\hline
\multicolumn{4}{|c|}{ HEAD}\\\hline\hline
\multicolumn{4}{|c|}{A}\\\hline
\end{tabular}
\end{document}

A: If every cell is re-specified by a \multicolumn then the original column specification in the tabular is not used at all. That is the case in all your examples, so the only effective column specifications are c which will use the natural width of the text of the cells in each column.

A: The key to understanding what's going on is to appreciate fully the meaning of the fact that \multicolumn directives take three arguments:

*

*Arg 1: the number of columns to which the directive applies. This number can be as small as 1 and as large as n, where n is the total number of columns.

*Arg 2: The column type -- observe the singular form of the word "type" -- to be used for the combined column. It's important to realize that this column type completely overrides the underlying column type (or types) that is specified via \begin{tabular}{...}.

*Arg 3: The contents of the combined column.
For the sake of completeness, I'll note that whereas the p column type has a fixed width, columns of type l, c and r have no ex ante fixed width. Instead, their widths will be that of the material they contain.
Let's apply this to each of the five tabular environments. First, a picture (slightly modified from your code, mainly to ease cross-referencing) to establish the five different widths:

*

*In the first tabular (with header HEAD1), there are cells in each of the four columns without \multicolumn statements. The overall width of each cell is therefore governed by the width of the associated p column type (1.67cm for the first three columns, and 8cm for the final column).

*In the second tabular, the material in columns 1 and 2 is never without a \multicolumn statement. In both data rows, the c column type is employed by the \multicolumn statements. Hence, LaTeX never gets to apply the "underlying" p column type for either of the first two columns. That's why the width of the second tabular is less than that of the first.
Observe that the widths of the first two columns are given by the widths of the underlying letters (A and B, respectively) plus 2\tabcolsep; the combined width of the first two columns is therefore the sum of the widths of the letters A and B plus 4\tabcolsep plus \arrayrulewidth.

*In the third tabular, there are only three "effective" columns, as there are no cells with separate material for the first two columns. The width of the effective first column is therefore given by the sum of the widths of the letters A and B plus 2\tabcolsep.

*The fourth tabular contains effectively just two columns. The underlying p column types of the first three columns are never used. Only the fourth column's underlying "p" type gets any use.

*The fifth and final tabular effectively contains just one column, whose column type is c. Observe that the four underlying p column types are never used. That's why the fifth tabular is so much narrower than the first four are.
The thing to remember is that \multicolumn is quite powerful -- and far more powerful than one might at first give it credit. In particular, it's important to realize that the consequences of the fact that the column type specified in the second argument of \multicolumn overrides the underlying column types completely.

\documentclass[preview,border=100pt]{standalone}
\setlength{\tabcolsep}{0.2cm}
%%\usepackage{array}
\begin{document}

\begin{tabular}{|p{1.67cm}|p{1.67cm}|p{1.67cm}|p{8.0cm} |}
\hline
\multicolumn{4}{|c|}{HEAD1}\\
\hline\hline
\multicolumn{2}{|c|}{AB} & C & D\\
\hline
A & B & C & D\\ % all four underlying column types get used in this row
\hline
\end{tabular}

\bigskip
\begin{tabular}{|p{1.67cm}|p{1.67cm}|p{1.67cm}|p{8.0cm}|}
\hline
\multicolumn{4}{|c|}{HEAD2}\\
\hline\hline
\multicolumn{2}{|c|}{AB} & C & D\\ % "p" column type is used only in columns 3 and 4
\hline
\multicolumn{1}{|c|}{A} & \multicolumn{1}{|c|}{B}  &
\multicolumn{1}{|c|}{C} & \multicolumn{1}{|c|}{D} \\
\hline
\end{tabular}

\bigskip
\begin{tabular}{|p{1.67cm}|p{1.67cm}|p{1.67cm}|p{8.0cm}|}
\hline
\multicolumn{4}{|c|}{HEAD3}\\
\hline\hline
\multicolumn{2}{|c|}{AB} & C & D\\
\hline
\end{tabular}

\bigskip
\begin{tabular}{|p{1.67cm}|p{1.67cm}|p{1.67cm}|p{8.0cm}|}
\hline
\multicolumn{4}{|c|}{HEAD4}\\
\hline\hline
\multicolumn{3}{|c|}{ABC} & D\\ % "p" column type is used only in column 4

\hline
\end{tabular}

\bigskip
\begin{tabular}{|p{1.67cm}|p{1.67cm}|p{1.67cm}|p{8.0cm}|}
\hline
\multicolumn{4}{|c|}{HEAD5}\\
\hline\hline
\multicolumn{4}{|c|}{ABCD}\\ % "p" column type isn't used anywhere
\hline
\end{tabular}
\end{document}


text:
Q: set Foreground color of element inside Selected Row of DataGrid I have a DataGridTemplateColumn defined as below. I need to change the Foreground property of both textblocks to White if the row is selected
<DataGrid.Columns>
<DataGridTemplateColumn  Header="User" Width="240" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Margin="10,3,0,0" Foreground="#1c72c7" >
                        <Run Text="{Binding FullName, Mode=OneWay}" />
                </TextBlock>
                <Label Padding="0,0,0,0"  Margin="0,0,0,3">
                    <TextBlock Foreground="#1c72c7"  Margin="10,0,0,0" TextDecorations="Underline" Text="{Binding DisplayName}" />
                </Label>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

I already have a RowStyle defined to change the background color of the row as follows
 <DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static SystemColors.HighlightColor}" />
    </Style.Resources>

</Style>

A: You should modify the Style for each individual TextBlock, and add the behavior as you'd like, as so:
 <Style x:Key="FirstTextBlockStyle" TargetType="TextBlock">
    <Setter Property="Foreground" Value="Black" />
    <Style.Triggers>
       <DataTrigger Binding="{Binding IsSelected,
             RelativeSource= {RelativeSource
                                AncestorType={x:Type DataGridRow}}}"
             Value="True">
           <Setter Property="Foreground" Value="White" />
        </DataTrigger>
     </Style.Triggers>
 </Style>


text:
Q: Merge data frames while keeping length of one and values of other in R I want to merge two data frames: X with length 10 (for example) and Y with length 3 but with similar row names. I only want to retain the length of X but with the values of B in the 3 corresponding rows and the other 10 - 3 = 7 values set to zero.
For example,
X<-data.frame(c(1,2,3,4,5,6,7,8,9,10))
rownames(X)<-c("a","b","c","d","e","f","g","h","i","j")
Y<-data.frame(c(20,30,40))
rownames(Y)<-c("d","f","h")

gives me these data frames
    X             Y
a   1         d   20
b   2         f   30
c   3         h   40
d   4
e   5
f   6
g   7
h   8
i   9
j   10

and I want this now
    Z
a   0
b   0
c   0
d   20
e   0
f   30
g   0
h   40
i   0
j   0

Can this be done easily?

A: We can use match to find the positions of the row names of Y that are found in X. The values of Y are put into a vector and concatenated with 0. We use the nomatch argument to fill in 0 when there is no match. This returns z as a vector:
Z <- c(unlist(Y, use.names=FALSE), 0)[match(row.names(X), row.names(Y), nomatch=4L)]
Z
[1]  0  0  0 20  0 30  0 40  0  0

To get a data.frame
Z <- data.frame(Z)

A: dplyr have nice option for left_join. Code of it it's easy to read and explain.
X<-data.frame(V1 = c(1,2,3,4,5,6,7,8,9,10),
              KEY = c("a","b","c","d","e","f","g","h","i","j"),
              stringsAsFactors = F)

Y<-data.frame(V2 = c(20,30,40),
              KEY = c("d","f","h"),
              stringsAsFactors = F)

library(dplyr)

XandY <- X %>%
  left_join(Y, by = "KEY") %>%
  mutate(Z = ifelse(is.na(V2), 0, V2))

I lefted all of columns in XandY to show you all computation and results.
> XandY

   V1 KEY V2  Z
1   1   a NA  0
2   2   b NA  0
3   3   c NA  0
4   4   d 20 20
5   5   e NA  0
6   6   f 30 30
7   7   g NA  0
8   8   h 40 40
9   9   i NA  0
10 10   j NA  0


text:
Q: Is it possible to know from which package a procedure has been called? Suppose that I have 2 packages : A and B.
In package A, I call a procedure in package B.
In procedure of packcage B, is it possible to know that procedure has been called from package A ?

Thank you very much for these informations. It was very instructive.
I appreciate.

A: You can use procedure called who_called_me from the Oracle supplied package OWA_UTIL
http://download.oracle.com/docs/cd/B25221_04/web.1013/b25598/psutil.htm#i1006497

A: You may be able to parse the text returned by the DBMS_UTILITY.FORMAT_CALL_STACK() function.
Edit: I tried creating some test packages. I have a procedure in the XX_TESTA package calling another in the XX_TESTB package. The procedure in XX_TESTB simply prints the text returned by DBMS_UTILITY.FORMAT_CALL_STACK() to output. This is the resulting text:
----- PL/SQL Call Stack -----
  object      line  object
  handle    number  name
416fe0e68         5  package body APPS.XX_TESTB
415182f10         5  package body APPS.XX_TESTA
416e9b448         3  anonymous block

A: You could pass the name through as a parameter?
Using....
$$PLSQL_UNIT

From:  http://awads.net/wp/2006/08/03/heres-a-quick-way-to-get-the-line-number-in-plsql
EDDIE@XE> CREATE OR REPLACE PACKAGE my_pkg
  2  IS
  3     PROCEDURE my_proc;
  4  END;
  5  /

Package created.

EDDIE@XE> CREATE OR REPLACE PACKAGE BODY my_pkg
  2  IS
  3     PROCEDURE my_proc
  4     IS
  5     BEGIN
  6        DBMS_OUTPUT.put_line ('Line number: ' || $$plsql_line);
  7        DBMS_OUTPUT.put_line (   'Unit: '
  8                              || $$plsql_unit
  9                             );
 10     END;
 11  END;
 12  /

Package body created.

EDDIE@XE> exec my_pkg.my_proc;
Line number: 6
Unit: MY_PKG