text:
Q: How to choose a batch for train_on_batch? I was reading into how the train_on_batch function in Keras works. My understanding is that it only trains on a single batch. Someone on here said that if you feed in 10 images, and your batch size is 2, your network will only train on two images. Which two images in particular, just the first two? Once the batch is chosen, does the training work the same as in fit?
For context, I'm trying to reproduce the function from scratch.

A: fit() - Trains the model for a fixed number of epochs (iterations on a dataset) whereas
train_on_batch() - Runs a single gradient update on a single batch of data.
Please find more details on both model functions terminologies in this link.
You can get some more understanding with this answer.


text:
Q: Group array by nested dependent array element I have an array store Task information. Each task has also an array of taskId that it is depending on.
Input
let inputArr = [
    {
        id: 1,
        dependOnTasks: [2, 3]
    },
    {
        id: 2,
        dependOnTasks: [3]
    },
    {
        id: 3,
        dependOnTasks: []
    },
    {
        id: 4,
        dependOnTasks: [5]
    },
    {
        id: 5,
        dependOnTasks: []
    },
    {
        id: 6,
        dependOnTasks: [5]
    }
]

The expected output is grouping all the depending task into one array for displaying into the UI.
Output
[
    [
        {
            id: 1,
            dependOnTasks: [2, 3]
        },
        {
            id: 2,
            dependOnTasks: [3]
        },
        {
            id: 3,
            dependOnTasks: []
        }
    ],
    [
        {
            id: 4,
            dependOnTasks: [5]
        },
        {
            id: 5,
            dependOnTasks: []
        },
        {
            id: 6,
            dependOnTasks: [5]
        }
    ]
]

I have made a function to do it but seem I was thinking wrong by hard-coded it. Hope someone can help me archive it right way using pure JavaScript/TypeScript or Underscore since we have already used in the project.

Noted: TaskId will be random string like "5878465507b36e1f9c4c46fe"

A: // will contain the groups (results).
var result = [];

// will serve as a holder of the already treated indexes of inputArr.
var indexCache = [];

// insert obj into a group, insert its dependencies and the object that depend on it as well.
function insertWithDependencies(obj, group){
    // insert this obj into this group
    group.push(obj);

    // First: look for the objects it depends on
    obj.dependOnTasks.forEach(function(id){
        for(var i = 0; i < inputArr.length; i++){
            // if the object in this index is already treated, then ignore it
            if(indexCache.indexOf(i) != -1) continue;
            // if this object is a dependency of obj then insert it with its own dependencies.
            if(inputArr[i].id == id){
                var o = inputArr[i];
                indexCache.push(i); // cache this i as well
                insertWithDependencies(o, group);
            }
        }
    });

    // Then: look for the objects that depends on it
    for(var i = 0; i < inputArr.length; i++){
        // if the object in this index is already treated, then ignore it
        if(indexCache.indexOf(i) != -1) continue;
        // if this object depends on obj then insert it with ...
        if(inputArr[i].dependOnTasks.indexOf(obj.id) != -1){
            var o = inputArr[i];
            indexCache.push(i); // cache i
            insertWithDependencies(o, group);
        }
    }
};

// while there is element in the inputArr that haven't been treated yet
while(inputArr.length != indexCache.length){
    // the group that will hold the depending tasks all together
    var group = [];

    // look for the first untreated object in inputArr
    var i;
    for(i = 0; i < inputArr.length; i++)
        if(indexCache.indexOf(i) == -1)
            break;
    var obj = inputArr[i];

    // cache its index
    indexCache.push(i)

    // insert it along its dependencies
    insertWithDependencies(obj, group);

    // push the group into the result array
    result.push(group);
}

ANOTHER WAY:
Here is an optimised way to do it, but the data inside inputArr will be lost afterwards. It won't use the indexCache to see if an index is already treated or not but instead it will make all treated items null in inputArr. So if you don't care or won't use inputArr afterwards, use this instead:
var result = [];
function insertWithDependencies(obj, group){
    group.push(obj);
    obj.dependOnTasks.forEach(function(id){
        for(var i = 0; i < inputArr.length; i++){
            if(!inputArr[i]) continue;
            if(inputArr[i].id == id){
                var o = inputArr[i];
                inputArr[i] = null;
                insertWithDependencies(o, group);
            }
        }
    });
    for(var i = 0; i < inputArr.length; i++){
        if(!inputArr[i]) continue;
        if(inputArr[i].dependOnTasks.indexOf(obj.id) != -1){
            var o = inputArr[i];
            inputArr[i] = null;
            insertWithDependencies(o, group);
        }
    }
};

function findNotNull(){
    for(var i = 0; i < inputArr.length; i++)
        if(inputArr[i]) return i;
    return -1;
}

var index;
while((index = findNotNull()) != -1){
    var group = [];

    var obj = inputArr[index];
    inputArr[index] = null;
    insertWithDependencies(obj, group);

    result.push(group);
}

console.log(result);

A: If you don't care about the order of the tasks in the same group. Using union and find to implement a disjoint set might be an option.
Util data structure:
function UnionFind(n) {
  this.parent = [...Array(n+1).keys()]
}

UnionFind.prototype.find = function(x) {
  if (this.parent[x] === x) {
    return x
  }
  const ret = this.find(this.parent[x])
  this.parent[x] = ret
  return ret
}

UnionFind.prototype.union = function(x, y) {
  let x_rep = this.find(x)
  let y_rep = this.find(y)
  if (x_rep !== y_rep) {
    this.parent[x_rep] = y_rep
  }
}

Dumb data source:
let inputArr = [
    {
        id: 1,
        dependOnTasks: [2, 3]
    },
    {
        id: 2,
        dependOnTasks: [3]
    },
    {
        id: 3,
        dependOnTasks: []
    },
    {
        id: 4,
        dependOnTasks: [5]
    },
    {
        id: 5,
        dependOnTasks: []
    },
    {
        id: 6,
        dependOnTasks: [5]
    }
]

Driver program:
let len = inputArr.length
let uf = new UnionFind(len)

// iterate through all tasks to group them
inputArr.forEach(entry => {
  entry.dependOnTasks.forEach(depsId => {
    uf.union(entry.id, depsId)
  })
})

// reiterate to retrieve each task's group and group them using a hash table
let groups = {}
inputArr.forEach(entry => {
  const groupId = uf.find(entry.id)
  if (!groups.hasOwnProperty(groupId)) {
    groups[groupId] = [entry]
    return
  }
  groups[groupId].push(entry)
})

let result = Object.keys(groups).map(groupId => groups[groupId])
console.log(JSON.stringify(result, null, 2))

note: if id is random string in your case, simply change this.parent to hash map, and if you care about the order(as there're dependency trees), consider using topological sort instead.

A: The solution is straightforward,

*

*Initialize empty group list

*For each task find if there is a group in the group list with id or id of any dependent tasks

*If not add a new group with task id and dependent tasks

var input = [
    { id: 1,  dependOnTasks: [2, 3]   },
    { id: 2,  dependOnTasks: [3]  },
    { id: 3,  dependOnTasks: [] },
    { id: 4,  dependOnTasks: [5] },
    { id: 5,  dependOnTasks: [] },
    { id: 6,  dependOnTasks: [5] }
];

var groups = [];

for (var i = 0; i < input.length; i++){
  var group = findGroup(groups,input[i]);
  if (!group){
    group = {ids : []};
    group.ids.push(input[i].id);
    groups.push(group);
  }

  if (group.ids.indexOf(input[i].id) === -1){
    group.ids.push(input[i].id);
  }

  for (var j = 0; j < input[i].dependOnTasks.length; j++){
    if (group.ids.indexOf(input[i].dependOnTasks[j]) === -1){
      group.ids.push(input[i].dependOnTasks[j]);
    }
  }
}
document.write(groups[0].ids + '
');
document.write(groups[1].ids + '
');

function findGroup(groups,task){
  for (var i = 0; i < groups.length; i++){
    var group = groups[i];
    if (group.ids.indexOf(task.id) !== -1){
      return group;
    }

    for (var j = 0; j < task.dependOnTasks.length; j++){
      if (group.ids.indexOf(task.dependOnTasks[j]) !== -1){
        return group;
      }
    }
  }
  return null;
}

A: You can try with my code

var inputArr = [
    {
        id: 1,
        dependOnTasks: [2, 3]
    },
    {
        id: 2,
        dependOnTasks: [3]
    },
    {
        id: 3,
        dependOnTasks: []
    },
    {
        id: 4,
        dependOnTasks: [5]
    },
    {
        id: 5,
        dependOnTasks: []
    },
    {
        id: 6,
        dependOnTasks: [5]
    }
]

// make matrix graph
var map = {};
for (var i = 0; i < inputArr.length; i++) {
    var task = inputArr[i];
    map[task.id] = map[task.id] || {};
    for (var j = 0; j < task.dependOnTasks.length; j++) {
        var dependId = task.dependOnTasks[j];
        map[dependId] = map[dependId] || {};
        map[task.id][dependId] = true;
        map[dependId][task.id] = true;
    }
}

var groupTasks = [];

for (var key in map) {
    var group = groupTasks.filter(function(e) {
        return e.indexOf(key) >= 0;
    })[0]

    if (!group) {
        group = [key];
        groupTasks.push(group);
    }

    for (var dependKey in map[key]) {
        if (group.indexOf(dependKey) == -1) {
            group.push(dependKey);
        }
    }
}

var result = groupTasks.map(function(group) {
    var tasks = [];
    group.forEach(function(id) {
        var task = inputArr.filter(function(e) { return e.id == id })[0];
        tasks.push(task);
    });
    return tasks;
})

console.log(JSON.stringify(result, null, 4));

redpajama_set_name: RedPajamaStackExchange


text:
Q: I wish to create a drop down select list with option items that can trigger http Get and refresh the page I wish to create a drop down select list with option items that can trigger http Get and refresh the page.
I wish to run some code in the controller action when an option in the drop down is clicked.
I used the Html.DropdownlistFor() helper but I could not manipulate it thus.
Here is the code so you can understand me better,
var olist = db.ItemPackagingUnits.Where(i => i.ItemName.Equals(item.ItemName.ToUpper().Trim()));

         <select>
               @foreach(var oitem in olist)
               {
                  <option value ='@oitem.UnitOfMeasurementName'>@oitem.UnitOfMeasurementName</option>
               }
         </select>

I hope I have given enough information on what I wish to achieve. DoSales is an action in the Restaurant Controller which has both Get and Post parts but I only wish to call the get part and refresh the page at the same time (or else I would have used Ajax or JSon) when the user clicks on any of the options in the drop down that was generated. Thank you.

A: Yes it worked! Thanks Mario J Vargas! Here are the code and javascript!
var olist = db.ItemPackagingUnits.Where(i => i.ItemName.Equals(item.ItemName.ToUpper().Trim()));

     <select onchange ="myFunc(this)">
           @foreach(var oitem in olist)
           {
              <option value ='/Restaurant/DoSales?ItemName=@item.ItemName&PackagingUnit=@oitem.UnitOfMeasurementName&recalulatePrice=true'>@oitem.UnitOfMeasurementName</option>
           }
     </select>


text:
Q: Combinatorial proof of fibonacci I need to proof this expression combinatorially
$f_{2n+1}= \sum_{i \geq 0} \sum_{j\geq 0} \binom{n-i}{j} \binom{n-j}{i}$ for all $n \geq 0$. As $f_1 = 1, f_2=2$
I dont know how to start combinatorial argument to this problem .I tried to use induction but it's hard to get the inductive result

A: What  follows is  not a  double  counting proof.  It nonetheless  uses
combinatorial methods to arrive at the answer.
Observe that the generating function of the Fibonacci numbers is
$$\frac{z}{1-z-z^2}.$$
so that we have $F_0 = 0$ and $F_1 = F_2 = 1.$
 We seek to evaluate
$$\sum_{p=0}^n \sum_{q=0}^n {n-p\choose q} {n-q\choose p}
\\ = \sum_{p=0}^n \sum_{q=0}^n
{n-p\choose n-p-q} {n-q\choose n-p-q}.$$
Note that  on the first line the binomial coefficient ${n\choose  k} =
n^{\underline{k}}/{k!}$ starts producing non-zero values when $p\gt n$
and $q\gt n.$ This is not desired here, hence the upper limits. On the
second line we  use the convention that ${n\choose k}  = 0$ when $k\lt
0,$ which is  also the behavior when residues are  used. Continuing we
find
$$\sum_{p=0}^n \sum_{q=0}^n
[z^{n-p-q}] (1+z)^{n-p} [w^{n-p-q}] (1+w)^{n-q}
\\ = [z^n] (1+z)^n [w^n] (1+w)^n \sum_{p=0}^n \sum_{q=0}^n
z^{p+q} (1+z)^{-p} w^{p+q}  (1+w)^{-q}
\\ = [z^n] (1+z)^n [w^n] (1+w)^n
\sum_{p=0}^n z^p w^p (1+z)^{-p} \sum_{q=0}^n
z^q w^q (1+w)^{-q}.$$
Here the coefficient extractor controls the range and we may
continue with
$$[z^n] (1+z)^n [w^n] (1+w)^n
\sum_{p\ge 0} z^p w^p (1+z)^{-p}
\sum_{q\ge 0} z^q w^q (1+w)^{-q}
\\ = [z^n] (1+z)^n [w^n] (1+w)^n
\frac{1}{1-zw/(1+z)} \frac{1}{1-zw/(1+w)}
\\ = [z^n] (1+z)^{n+1} [w^n] (1+w)^{n+1}
\frac{1}{1+z-zw} \frac{1}{1+w-zw}.$$
Now we have
$$\frac{1}{1+z-zw} \frac{1}{1+w-zw}
\\ = \frac{1-w}{1+z-wz} \frac{1}{1+w-w^2}
+ \frac{w}{1+w-wz} \frac{1}{1+w-w^2}.$$
We get from the first piece treating $z$ first
$$[z^n] (1+z)^{n+1} \frac{1-w}{1+z-wz}
= [z^n] (1+z)^{n+1} \frac{1-w}{1-z(w-1)}
\\ = (1-w) \sum_{p=0}^n {n+1\choose n-p} (w-1)^p
= - \sum_{p=0}^n {n+1\choose p+1} (w-1)^{p+1}
\\ = 1 - \sum_{p=-1}^n {n+1\choose p+1} (w-1)^{p+1}
= 1 - w^{n+1}.$$
The contribution is
$$[w^n] (1+w)^{n+1} \frac{1-w^{n+1}}{1+w-w^2}
= [w^n] (1+w)^{n+1} \frac{1}{1+w-w^2}.$$
The second piece yields
$$[z^n] (1+z)^{n+1} \frac{w}{1+w-wz}
= \frac{1}{1+w} [z^n] (1+z)^{n+1} \frac{w}{1-wz/(1+w)}
\\ = \frac{w}{1+w}
\sum_{p=0}^n {n+1\choose n-p} \frac{w^p}{(1+w)^p}
= \sum_{p=0}^n {n+1\choose p+1} \frac{w^{p+1}}{(1+w)^{p+1}}
\\ = -1 +
\sum_{p=-1}^n {n+1\choose p+1} \frac{w^{p+1}}{(1+w)^{p+1}}
= -1 + \left(1+\frac{w}{1+w}\right)^{n+1}
\\ = -1 + \frac{(1+2w)^{n+1}}{(1+w)^{n+1}}.$$
The contribution is
$$[w^n] (1+w)^{n+1}
\left(-1 + \frac{(1+2w)^{n+1}}{(1+w)^{n+1}}\right)
\frac{1}{1+w-w^2}.$$
Adding the first and the second contribution we find
$$[w^n] (1+2w)^{n+1} \frac{1}{1+w-w^2}
\\ = \underset{w}{\mathrm{res}}\; \frac{1}{w^{n+1}}
(1+2w)^{n+1} \frac{1}{1+w-w^2}.$$
Setting $w/(1+2w)=v$ or $w=v/(1-2v)$ so that $dw = 1/(1-2v)^2 \; dv$
we obtain
$$\underset{v}{\mathrm{res}}\; \frac{1}{v^{n+1}}
\frac{1}{1+v/(1-2v)-v^2/(1-2v)^2} \frac{1}{(1-2v)^2}
\\ = \underset{v}{\mathrm{res}}\; \frac{1}{v^{n+1}}
\frac{1}{(1-2v)^2+v(1-2v)-v^2}
\\ = \underset{v}{\mathrm{res}}\; \frac{1}{v^{n+1}}
\frac{1}{1-3v+v^2}.$$
We have our answer:
$$\bbox[5px,border:2px solid #00A000]{
[v^n] \frac{1}{1-3v+v^2} = F_{2n+2}.}$$
It  remains  to  prove  that the  coefficient  extractor  returns  the
Fibonacci number as  claimed. The OGF of  even-index Fibonacci numbers
is
$$\sum_{n\ge 0} F_{2n} z^{2n} = \frac{1}{2} \frac{z}{1-z-z^2}
+ \frac{1}{2} \frac{(-z)}{1+z-z^2}
= \frac{z^2}{1-3z^2+z^4}.$$
This implies that
$$\sum_{n\ge 0} F_{2n} z^{n} = \frac{z}{1-3z+z^2}.$$
Therefore
$$F_{2n+2} = [z^{n+1}] \frac{z}{1-3z+z^2}
= [z^n] \frac{1}{1-3z+z^2}$$
as required.

A: We shall use tessellations of a $1 \times n$ grid with (singleton) squares and dominoes to give a combinatorial proof. But first a quick lemma.
Lemma: A $1 \times m$ grid can be tessallated with $j$ dominoes and $m-2j$ squares in $\binom{m-j}{j}$ ways. ($m \geq j$)
Proof: We will show this using a one-one correspondence. Let $ \{a_1,\cdots,a_j \} $ be a $j-$set of  $[m-j]$ (of which there are clearly $\binom{m-j}{j}$. Now place dominoes at $ a_1,a_2+1, \cdots ,a_j+j-1$ and fill the rest of the grid with squares. It is easily shown that these configurations and sets are bijective.
Now to prove the stated formula, first observe that $F_{2n+1}$ is the number of tessellations of a $1 \times (2n+1)$ grid with  squares and dominoes.
Alternatively, such a configuration will have $k$ dominoes and $2n-2k+1$ squares. Observe that there will always be an odd number of squares and we consider the position of the "middle" square. There will be $j$ dominoes to the left of this square and $i$ squares to the right. ($i+j=k$).
To the left there are $j$ dominoes and $n-k$ squares, by the lemma there are $\binom{n-i}{j}$ ways to arrange these and similarly to the right there are $i$ dominoes and $n-k$ squares, by the lemma there are $\binom{n-j}{i}$ ways to arrange these.
So
\begin{eqnarray*}
F_{2n+1} = \sum_{i=0}^{n} \sum_{j=0}^{n-i} \binom{n-i}{j} \binom{n-j}{i}.
\end{eqnarray*}
In a nut shell this formula gives the number of tessellations of a $1 \times (2n+1)$ grid graded by the number of dominoes to the left and right of the central square.


text:
Q: Can we set separate retention policy for a specific List item that is already uploaded in SharePoint 2016? I need to programatically set a separate retention policy for specific files that are already uploaded in a document library in SharePoint 2016 on Prem version.
Is it possible to do so?
Let me know the solution for the above scenario.

A: Yes, it's doable. On the library settings you turn your head to "Information management policy setting".

THERE ARE 4 PLACES WHERE YOU CAN DEFINE RETENTION POLICIES IN
  SHAREPOINT:

*

*Site Collection

*Content Type

*Document Library

*Folder

Reference: How to set up retention and deletion policies for files and folders in SharePoint


text:
Q: Best way to import data in Python? XML? I am very new to python and want to make a script for a spreadsheet I use at work. Basically, i need to associate an address with multiple 5 digit reference codes. There are multiple addresses with a corresponding group of reference codes.
i.e:
Address:
1234 E. 32nd Street,
New York, NY, 10001
Ref #'s
RL081
RL089
LA063
Address 2:
etc....

I need my script to look up a location by ref code. This information is then used to build a new spreadsheet (each row needs an address and the address is looked up using a ref code). What is the best way to use this info in python? Would it be a dictionary? Should I put the addresses / ref codes into an XML type file?
Thanks
Edit (clarification):
Basically, I have those addresses and corresponding ref codes (they could be in a plain text document, I could organize them in a spreadsheet, or whatever so python can use them). The script I'm building needs to use those ref codes to enter an address into a new spreadsheet. Basically, I input a half complete spreadsheet and the script fills in the addresses based on the ref code in each row.

A: Import into what?
If you have everything in a spreadsheet, Python has a very good CSV reader library. Once you've read it in, the challenge becomes what to do with it.
If you are looking at a medium term solution, I'd recommend looking at using SQLite to set up a simple spreadsheet that can manage the information in a more structured way. SQLite scales well in the beginning stages of a project and it becomes a trivial case to insert into a fully-fledged RDBMS like PostGreSQL or MySQL if it becomes neccessary.
From there it becomes a case of writing the libraries you need to manipulate your data, and present it. In the initial stages this can be done using the command line but by using an SQL database this can be exposed through a webpage for multiple people down the line without worrying about managing data integrity.

A: I prefer to use JSON over XML for storing data that will later be used in python. The json module is fairly robust and easy to use. Since you will be performing lookups I would definitely loading the information as a python dictionary. Since you'll be querying by ref codes you'll want to use those for keys and have the address as the value.

A:
I need my script to look up a location by ref code

Since this is the only requirement you've stated, I would recommend using a dict where keys are ref codes and values are addresses.
I'm not sure why you are asking about "file types".  It seems you already have all this information stored in a spreadsheet - no need to write a new file.


text:
Q: how to get value of dropdown into a mysql query in php I hope someone can help me with this question.
I am trying to get the value of dropdown menu and inject it into Mysql query.
Here is my code:
<form method=post onchange="putSomethingHere">
<select name="myvalue">
  <option value="7225">7225</option>
  <option value="7226">7226</option>
  <option value="7227">7227</option>
</select>
</form>

<?php
if($dbhandle){

  $q = mysqli_query($dbhandle, "
SELECT rfqlogs.id
     , customers.customer
     , contacts.Name
     , constructions.construction
     , grades.grade
     , rfqlogs.dueDate
     , rfqlogs.rcvDate
     , rfqlogs.proccess
     , rfqlogs.scope
     , status.status
     , rfqlogs.priority
  FROM rfqlogs
  JOIN contacts
    ON rfqlogs.contid = contacts.cont_id
  JOIN grades
    ON rfqlogs.gradeId = grades.grd_id
  JOIN customers
    ON rfqlogs.custId = customers.cust_id
  JOIN constructions
    ON rfqlogs.constId = constructions.id
  JOIN status
    ON rfqlogs.status = status.id
 WHERE rfqlogs.id='myvalue'
");
?>

A: You need to separate both the script that outputs the form and the script that handles the form submission. You could merge both in the same file but for a basic implementation, let's use separated files.
Let's call form.php the script that outputs the form (the whole HTML structure is not included).
<form method="post" onchange="putSomethingHere" action="handler.php">
  <select name="myvalue">
    <option value="7225">7225</option>
    <option value="7226">7226</option>
    <option value="7227">7227</option>
  </select>
</form>

The script that handles the form submission (i won't review your SQL, it's supposed to be functional):
<?php
  // $dbhandle definition goes here
  $myvalue = isset($_REQUEST['myvalue']) ? $_REQUEST['myvalue'] : false;
  // You can check whether `myvalue` was sent in the request or not, then take the required action.
  // validate and sanitize $myvalue here, use intval() if `myvalue` must always be an integer or mysqli_real_escape_string() in case it's an string.
  if($dbhandle){
    $q = mysqli_query($dbhandle, "SELECT rfqlogs.id, customers.customer,
      contacts.Name, constructions.construction, grades.grade,
      rfqlogs.dueDate, rfqlogs.rcvDate, rfqlogs.proccess,
      rfqlogs.scope, status.status, rfqlogs.priority
      FROM rfqlogs
      INNER JOIN contacts ON rfqlogs.contid = contacts.cont_id
      INNER JOIN grades ON rfqlogs.gradeId = grades.grd_id
      INNER JOIN customers ON rfqlogs.custId = customers.cust_id
      INNER JOIN constructions ON rfqlogs.constId = constructions.id
      INNER JOIN status ON rfqlogs.status = status.id
      WHERE rfqlogs.id='$myvalue'");
?>

PD: You can use both $_REQUEST and $_POST this case.

A: You can do so using $_POST :
Try this :
<form method="post" onchange="putSomethingHere">
<select name="myvalue">
<option value="7225">7225</option>
<option value="7226">7226</option>
<option value="7227">7227</option>
</select>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $myvalue= $_POST["myvalue"];
}
if($dbhandle){

$q = mysqli_query($dbhandle, "SELECT rfqlogs.id, customers.customer,
contacts.Name,
constructions.construction, grades.grade, rfqlogs.dueDate, rfqlogs.rcvDate,
rfqlogs.proccess,
rfqlogs.scope, status.status, rfqlogs.priority
FROM rfqlogs
INNER JOIN contacts ON rfqlogs.contid = contacts.cont_id
INNER JOIN grades ON rfqlogs.gradeId = grades.grd_id
INNER JOIN customers ON rfqlogs.custId = customers.cust_id
INNER JOIN constructions ON rfqlogs.constId = constructions.id
INNER JOIN status ON rfqlogs.status = status.id
WHERE rfqlogs.id='".$myvalue."' ");
?>

A: $_POST["myvalue"];

This should do the trick. The php $_POST global variable holds all variables that has been sent from your form.
So by replacing the array key, you can get any variable you want.


text:
Q: How do i share data between different lambdas? So i need some help with lambda here.
I built 5 lambdas process my products with a few external apis, like check prices, get better images and so on.
Each lambda right now has a json file with all my Rds connection string's. And im on my way of moving other processes i do with crons/jobs with lambda as well but i am worried that i will end up copying and pasting that data and if i add one more rds i will need to edit all my lambdas.
What is the best way to share that information?
I thought about S3 but i feel is not that safe to have all my databases access there.
Any ideas?

A: Amazon recommends using SSM Parameter Store to store variables (replacing environment variables) for Lambda (and other services). SSM Parameter Store supports encryption / descryption. Perfect for storing your DB credentials in one location that can be shared (within the same region).
Here are a couple of links to get you started:
SSM Parameter Store
The right way to store secrets

A: We use DynamoDB to share data. One more good thing about DynamoDB is Lambda can subscribe to DynamoDB stream and update the data as it changes.
If you have 5 different lambda's then you can subscribe to the DynamoDB stream and update whenever data in DynamoDB changes.
More on DynamoDB Streams and Lambda Trigggers:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.html
Hope it helps.


text:
Q: Typescript unknown extends T deferred type I saw this code in a library code, my confusion is around unknown extends CustomTypes[K], my understanding is this is a deferred type and unknown is always assignable to CustomTypes[K], so my question is how this type is actually used, particularly in which case it resolve to false. Some example can be helpful.
/**
 * Extendable Custom Types Interface
 */

type ExtendableTypes =
  | 'Editor'
  | 'Element'
  | 'Text'

export interface CustomTypes {
  [key: string]: unknown
}

export type ExtendedType<
  K extends ExtendableTypes,
  B
> = unknown extends CustomTypes[K] ? B : CustomTypes[K]

A: You are probably supposed to augment the interface CustomType through Declaration Merging. When multiple interfaces of the same name exist, they are merged together.
// declared somewhere in the library
export interface CustomTypes {
  [key: string]: unknown
}

// declared somewhere in your code
export interface CustomTypes {
    Editor: number
}

The type of the property Editor in CustomTypes is now number instead of unknown.
ExtendedType checks if a property's type was augmented and returns the new type.
type Result1 = ExtendedType<'Editor', string>
//   ^? Result1: number

Passing 'Editor' and string to ExtendedType will return number now.

Playground


text:
Q: Can copy/move constructors be inherited by using-declaration in c++17? struct B {
  B(int) {}
  B(B const&) {}
};

struct D: B {
  using B::B;
};

int main(void) {
  B b(5);
  D d(b); // error
  return 0;
}

c++14 explicitly excludes copy/move constructors from inherited constructors in 12.9 [class.inhctor]/p3.

For each non-template constructor in the candidate set of inherited
  constructors other than a constructor having no parameters or a
  copy/move constructor having a single parameter, a constructor is
  implicitly declared with the same constructor characteristics unless
  there is a user-declared constructor with the same signature in the
  complete class where the using-declaration appears or the constructor
  would be a default, copy, or move constructor for that class.

But I could not find any detailed descriptions in c++17. clang/gcc show that copy/move constructors of base class are not inherited. Can someone provide where it is explained in the standard? Thanks.

A: The new wording is in [over.match.funcs]/8:

A constructor inherited from class type C ([class.inhctor.init]) that has a first parameter of type "reference to cv1 P" (including such a constructor instantiated from a template) is excluded from the set of candidate functions when constructing an object of type cv2 D if the argument list has exactly one argument and C is reference-related to P and P is reference-related to D. [ Example:
struct A {
  A();                                  // #1
  A(A &&);                              // #2
  template<typename T> A(T &&);         // #3
};

struct B : A {
  using A::A;
  B(const B &);                         // #4
  B(B &&) = default;                    // #5, implicitly deleted

  struct X { X(X &&) = delete; } x;
};

extern B b1;
B b2 = static_cast<B&&>(b1);            // calls #4: #1 is not viable, #2, #3, and #5 are not candidates
struct C { operator B&&(); };
B b3 = C();                             // calls #4

— end example ]

In your example, B's inherited copy constructor is excluded from the set of candidates (that constructor has a first parameter of type reference to const B, the argument list has exactly one argument - b, and B and D are reference-related).

A: The passage you quote does not in fact prevent inheritance of copy constructors in C++14. Consider this instead:
B(B const&, int = 42) {}

This is a copy constructor, but it has two parameters. The passage only excludes a copy constructor with a single parameter. And when you supply both arguments, you can in fact initialize a D object with this constructor.
g++ error messages provide some insight.
note:   an inherited constructor is not a candidate for initialization from an expression of the same or derived type

Aha! A quick search in the draft standard finds this

A constructor inherited from class type C (class.inhctor.init) that has a first parameter of type "reference to cv1 P" (including such a constructor instantiated from a template) is excluded from the set of candidate functions when constructing an object of type cv2 D if the argument list has exactly one argument and C is reference-related to P and P is reference-related to D.


text:
Q: Calculating standard error from mcmc output (WinBUGS, JAGS etc...) I am looking to apply the concept of type M and S errors to a network meta-analysis I'm working on, hoping to use the following function developed by Andrew
retrodesign <- function(A, s, alpha=.05, df=Inf, n.sims=10000) {
  z <- qt(1-alpha/2, df)
  p.hi <- 1 - pt(z-A/s, df)
  p.lo <- pt(-z-A/s, df)
  power <- p.hi + p.lo
  typeS <- p.lo/power
  estimate <- A + s*rt(n.sims,df)
  significant <- abs(estimate) > s*z
  exaggeration <- mean(abs(estimate)[significant])/A
  return(list(power=power,
              typeS=typeS, exaggeration=exaggeration))
}

Where A is your hypothesized true effect and s is the standard error of your estimate. The code for NMA calculates basic parameters which in my case is the mean difference between each active treatment and placebo. These are then used to calculate all the remaining pairwise comparisons. My question is an embarassingly simple one, and is really just meant to make sure I am not making a huge error:
Am I right to calculate the standard error for a comparison based on the SD of the mcmc results for that parameter (e.g. sd/sqrt(n))? Or do I just use the SD of the estimate in lieu of the standard error?

A: The standard error is just the standard deviation of the parameter samples, but you may want to make sure that's what you want to use. Since you're conducting Bayesian analysis you shouldn't do classical hypothesis testing with your results (since those tests are meaningless in this context). Instead, use the sample of parameters to perform Bayesian hypothesis testing, which is actually much easier and more intuitive.
As an example, if you're wanting to find the probability a parameter $\theta$ is positive (i.e., $\Pr(\theta>0|D)$), simply calculate $$\frac1N \sum_{i=1}^N I(\theta^{[i]} > 0),$$ where $N$ is the number of sampling iterations, $\theta^{[i]}$ is the $i$th sample of $\theta$, and $I$ is an indicator function. In R, this is equivalent to sum(theta > 0) / N.
This is one of the main benefits of Bayesian analysis (which comes at the "cost" of needing to specify priors over variables). Rather than relying on asymptotic distributions of parameters to perform hypothesis tests that may not be a good approximation, you estimate the actual distributions of parameters (which depend on prior assumptions and the data) and use those to conduct inference directly.


text:
Q: I don't want to add duplicate data into my redux store array I want to add unique data into my store array, but seems to stuck while adding the data and duplicate data is getting pushed into array. I am using typescript.
So my slice function looks like this.
const initialState = {
  dropDownData:{
  programs: [],
  years: []
 }
}

const slice = createSlice({
  name:"filterSlice",
  initialState: initialState,
  reducers:{
     updateProgram:(state, action) => {
 state.dropDownData.programs = [...state.dropDownData.programs, action.payload];
   }
 }
});

I am calling this reducer function in this way: dispatch(updateProgram(program))
So the program i am getting is in the form of array.
But I don't need duplicate data from the program array.
So how to update my reducer function.

A: Instead of this:
state.dropDownData.programs = [...state.dropDownData.programs, action.payload];
Use this:
state.dropDownData.programs = [...(new Set([...state.dropDownData.programs, action.payload]))];
Approach:

*

*The javascript Set allows one to retain only unique elements from the parameter.

*Thus, when a new Set is created with elements from existing two arrays, the Set will keep only the unique elements.

*Next, we need to use the ... spread-operator to transform the Set back into an array.


text:
Q: "ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetVisible" doesn't work always I have created 2 sheets. Sheet1 has the message
Now the code shud become hidden but this fails to happen always. Sometimes  remains visible and Sheet1 remains hidden. Why is it so?
sorry I forgot to mention one imp detail. The  sheet contains a button. When the button is pressed it brings up the input box. Now the problem is when I choose option 1 to view the list and then press the button and select option 4 and click on ok, it clses the workbook but it doesn't hide the tracker and make Sheet1 visible even after the changes u recommended. I have uploaded the sheet pls take a look thanks

A: Make sure the visible worksheet is selected before saving:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim ws As Worksheet
        ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetVisible
        ThisWorkbook.Activate
        Worksheets("Sheet1").Select
        For Each ws In ActiveWorkbook.Worksheets
            If ws.Name <> "Sheet1" Then
                ws.Visible = xlVeryHidden
            End If
        Next ws
    ThisWorkbook.Save
    Application.DisplayAlerts = True
End Sub


text:
Q: Generating an ID from primary key sequence without adding a row I have the following two tables where I store users and their addresses. I have a problem relating to the order in which I receive and can save data from the user. At first the user will supply only the address and then get directed to an external service. To open this service I need to supply my internal user ID. The service verifies their email address and sends me the response.
CREATE TABLE IF NOT EXISTS public."user"
(
    id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
    email character varying COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY (id),
    CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE (email)
)

CREATE TABLE IF NOT EXISTS public.adresses
(
    id integer NOT NULL DEFAULT nextval('address_id_seq'::regclass),
    address character varying COLLATE pg_catalog."default" NOT NULL,
    "userId" integer,
    CONSTRAINT "PK_bec464dd8d54c39c54fd32e2334" PRIMARY KEY (id),
    CONSTRAINT "FK_35472b1fe48b6330cd349709564" FOREIGN KEY ("userId")
        REFERENCES public."user" (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)

*

*Can I generate the user ID from the sequence in some other way than entering an email in to the table and in the end enter both the ID and the email at the same time?

*Can I save the address in the addresses table referencing a foreign key which has not yet been added to users?

A: To answer this question, I did the following (all of the code below is available on the fiddle here):
CREATE SEQUENCE user_id_seq;
CREATE SEQUENCE address_id_seq;

and the tables:
CREATE TABLE user_
(
    id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
    email character varying COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY (id),
    CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE (email)
);

and
CREATE TABLE address
(
    id integer NOT NULL DEFAULT nextval('address_id_seq'::regclass),
    address character varying COLLATE pg_catalog."default" NOT NULL,
    user_id integer,
    CONSTRAINT "PK_bec464dd8d54c39c54fd32e2334" PRIMARY KEY (id),
    CONSTRAINT "FK_35472b1fe48b6330cd349709564" FOREIGN KEY (user_id)
        REFERENCES user_ (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);

We use PostgreSQL's RETURNING clause with a Common Table Expression (CTE - aka the WTIH clause).
A simple example:
WITH insert_user AS
(
  INSERT INTO user_ (email) VALUES ('user1@example.com')
  RETURNING id
)
SELECT *  FROM insert_user;

Result:
id  email
1   user2@example.com

So, we can see that we can obtain the id from the INSERT statement withing the CTE.
Now, we take this a step further as follows:
BEGIN TRANSACTION;
WITH insert_user AS
(
  INSERT INTO user_ (email) VALUES ('user1@example.com')
  RETURNING id
)
INSERT INTO address (address, user_id)
SELECT '1, Long Street, Somewhere', (SELECT id FROM insert_user)
COMMIT;

We use a transaction - just in case there's a problem in the step from the first INSERT to the second.
SELECT * FROM user_;
and
SELECT * FROM address;

Results:
id  email
2   user2@example.com
and
id         address            user_id
1   1, Long Street, Somewhere       2

We see that the user_id of 2 is in the address table - having come from the INSERT into the  user_ table in the CTE.
You have to INSERT a value for the email of the user because of the NOT NULL constraint in the user_ table definition! You can remove the constraint, but I see little point in this.
A few points to note:

*

*you use CHARACTER VARYING - PostgreSQL's TEXT data type is better suited for this.

*COLLATE pg_catalog."default" is redundant - if not specified, the collation will be the default.

*you use quoted identifiers, i.e. "userId" - far better to use PostgreSQL's recommended naming convention and turn this into user_id - i.e. snake_case!

*you have the most bizarre names for constraints that I have ever seen!
CONSTRAINT "PK_bec464dd8d54c39c54fd32e2334" PRIMARY KEY (id),
and
CONSTRAINT "FK_35472b1fe48b6330cd349709564" FOREIGN KEY ("userId")... REFERENCES...
The only rationale for this is that it's taken from some other system that gives these horrible names. Far better to have address_pk_id or something similar (i.e. meaningful). An error message stating that constraint "PK_bec464dd8d54c39c54fd32e2334" has been violated isn't going to tell anyone much! Plus, transmitting that over a phone call is going to be difficult - much better to use a simple name to which users can relate.
To answer the questions:
1st question:

*

*Can I generate the user ID from the sequence in some other way than entering an email in to the table and in the end enter both the ID and the email at the same time?
You could do the following:
SELECT nextval('user_id_seq');

Result:
nextval
      3

and then INSERT that into the address table along with an address. But, what's the point? You have to have some way of relating a given user to a given address - and you do this by wrapping your SEQUENCE value within a transaction - first from the INSERT into the user_ table and then using that value from the RETURNING clause to create the address.
2nd question:

*

*Can I save the address in the addresses table referencing a foreign key which has not yet been added to users?
No! The whole point of FOREIGN KEYs is so that you can't insert anything into the address table that doens't have a valid user_id back in the id field of the user_ table.
You could drop the constraints and have some ghastly procedural mess to keep track of what had and hadn't been INSERTed where and when - but again, why? You database will do all the work of keeping track of all this if you let it!


text:
Q: Not getting the 'Zend Amf endpoint' mesage on dreamhost but OK on my localserver I've been working with Zend Amf for few months and everything is fine on my localserver (and was fine on my test server hosted by dreamhost) until recently. Now every time I try to access the gateway via the URL (i.e. http://hostname/gateway/) instead of the 'Zend AMF endpoint' message should be getting, the browser simply prompts me to download an application/x-amf file.
I have checked my code for any leading or trailing spaces (made sure all my PHP didn't have an endtag). Checked the PHP version..it's 5.2..updated Zend to 1.10.7.
I was hoping that this wasn't interfering with my remote flash calls but that doesn't seem to be working as well. Flex doesn't even report a fault code.
Is there any specific PHP settings I should be checking?

A: Not really fixed anything but my Zend AMF IS working and the prompt to download an application/x-amf file is perfectly fine. My problem was more of a database inconsistency and the fact that my OpenAuth login system broke.


text:
Q: When can you call yourself good at language X? This goes back to a conversation I've had with my girlfriend. I tried to tell her that I simply don't feel adequate enough in my programming language (C++) to call myself good. She then asked me, "Well, when do you consider yourself good enough?"
That's an interesting question. I didn't know what to tell her. So I'm asking you.
For any programming language, framework or the like, when do you reach a point were you sit back, look at what you've done and say, "Hey, I'm actually pretty good at this."? How do you define "good" so that you can tell others, honestly, "Yeah, I'm good at X".
Additionally, do you reach these conclusions by comparing what others can do?
Additional Info
I have read the canonical paper on how it takes ten-thousand hours before you are an expert on the field. (Props to anybody that knows what this paper is called again)
I have also read various articles from Coding Horror about interviewing people. Some people, it was said, "Cannot function outside of a framework." So they may be "good" for that framework, but not otherwise in the language. Is this true?

A: On a related note, while I think the Software Craftsmanship movement is an excellent idea to help standards improve in our discipline, I've seen a lot of people describe themselves as software craftsmen, which seems a little arrogant to me in most cases.
It's up to your peers to decide whether or not you are good at something (or a craftsman); I'm sure Einstein and Feynman didn't wander round early in their careers saying "look at me, I'm a genius!" Similarly, it's up to your peers to decide whether you are good or not.
Stackoverflow is a useful tool to decide whether you are competent. Pick some questions in your area of supposed expertise. Answer them (or if they've already been answered, answer them in your head without peeking at the posted answers). Did you think of the best answer? Did you miss anything? Were you just plain wrong?

A: You can't call yourself good at X.  Only other people can.

A: There's a few good answers to this already, so I'll just contribute this:

A: Since there is no standardized programming test that you can take that will allow everyone to agree that you are a good programmer, it's up to you to determine whether you call your self that or not.
I find that it has to do with your confidence level.  If you FEEL you are good at something then you should be able to say it.  At somepoint you'll complete a project that pushed you and that feeling will change from 'not yet' to 'I am'.

A: I know this is a pretty hard question. I did two subjects with where I mainly programmed in C++ and got high distinctions in both. I wouldn't consider myself good at C++. In fact, if I was applying for a job, I would leave it off my resume and just write C instead. The whole language just isn't my thing.

A: I think you can call yourself good at something when you develop the required knowledge to be able to look at yourself as if from another person's perspective, and then determine if you are good. In other words, you should have strong "meta" skills.
For example, I'm a hobbyist writer, and when looking at my own writing I can tell:

*

*what aspects of it are good and why

*what aspects of it are bad and why

*what do I need to do to improve the bad ones, and why

*which bad aspects are specific to the written piece, and which are a symptom of my abilities

*what are the elements that other people may criticize, and why

*which criticisms are not relevant to my specific piece, even if others may voice them, and why

etc. etc.
Because of this I feel that I'm qualified to decide if I'm good at writing or not. The same applies to X.

A: One is good at something only when they can confidently and correctly say they can do it.
If you want to say you're good at C++, for example, you ought to be able to say, with confidence and justification, that given a general problem using C++, you can solve it.
This provides a distinction from being cocky, which would be to confidently say you can do something without sufficient justification; and experienced, which would be to say you can do something because you have done it in the past.

A: Since good is very subjective, I would say you are good exactly when you are confident that you are great.

A: You can claim you are "good" at something once you have been doing it long enough that you've long since forgotten how to do anything else.

A: The only time you can be sure if you're good at something is when you're sure you're bad at it.
John Cleese spoke about this:
At 9:00
http://www.youtube.com/watch?v=zGt3-fxOvug

A: Everytime I thought I was good at programming in a particular language, six months later I was convinced that at that time I sucked at it, and now i was good at it.  So I guess it is a relative term.  Maybe it would be better to call yourself "good enough to do Y" where Y is a particular project in that language.

A: When you can look at the source code of something like boost (in c++. or boost equivalent in another language) and NOT BE afraid of it.

A: When you start imagining how a software you are looking was written in that language.

A: You know you're good at it when you like what you're doing (and it's not just a trivial task).
You know you're bad (yet) when you keep swearing randomly while you code.

A: I often don't say that I'm good at X, but rather that I'm a quick learner and haven potential to be good at X.

A: Not sure about "good", but I say I "know" a language when it's not my knowledge of the language, but rather my understanding of the problem (or problem domain), that prevents me from implementing a piece of software to solve that problem.

A: I think the article you were looking for was Teach Yourself Programming in 10 years by Peter Norvig  refers to requiring about 10,000 hours to become good at something.  In addition I've seen it pop up in other places like "The Element" by Ken Robinson and on a lifehacker blog talking about reducing the number of hobbies you have.

A: I'm going to take part of this question to be asking 'what are some criteria to evaluate my competence at a programming language'
I've found this matrix to be pretty useful in that regard. Most of the items are actually more about being a competent programmer in general, but once you get down the the Programming, Experience, or Knowledge headings you'll see some that depend on language used.
Of course, as with any somewhat-arbitrary divisions into categories it isn't perfect. But I think it is pretty useful nonetheless. It can give you at least some idea of where you are and where you should go.


text:
Q: Targeting m and m/ I'm trying to target www.mydomain/m and www.mydomain/m/ for redirecting.
I used to serve mobile-friendly pages out of /m/ directory on my server, using the subdomain m.mydomain.com
I no longer do so and now redirect those requests to the main site, which works fine.
However, a request for /m or /m/ now results in an infinite loop of redirects.
The redirects from the old m.mydomain.com are quite complex, and I need to retain the /m directory on the server.
I have tweaked the relevant parts of .htaccess (in both mydomain.com, m.mydomain.com) by commenting out the directives, but of course, that breaks the main redirects I'm trying to do, and it didn't fix the problem.
This is what the /m directory .htaccess has, and successfully redirects traffic to the main site:
redirect 301 / https://www.example.com/
So I'm now trying to just target the requests that produce infinite loops, that is, /m and /m/ and redirect them to the homepage, i.e. www.mydomain.com
I've tried (in the mydomain root .htaccess):
RewriteCond %{REQUEST_URI} "^\/m$" [NC]
RewriteRule ^ https://www.example.com/ [R=301,L]
and
RewriteCond %{REQUEST_URI} "^\/m\/$" [NC]
RewriteRule ^ https://www.example.com/ [R=301,L]
I expected these would target the /m and /m/ requests, and redirect to the home page, but the infinite loop continued for both.

A: Add this rules in /m/ directory .htaccess
RewriteEngine On
RewriteRule (.*) https://www.example.com/ [R=301,L]

Add this rules in top of your mydomain root .htaccess
RewriteEngine On
RewriteRule ^m\/$ https://www.example.com/ [R=301,L]
RewriteRule ^m$ https://www.example.com/ [R=301,L]

A: Thanks JarekBaran. Your suggestion got me closer, but not quite there. I still needed to redirect all the old pages from /m directory to their new locations (same directory name, same file name).
This is what eventually worked:
In root .htaccess:
RewriteCond %{REQUEST_URI} !^/m$ [NC]
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

In /m directory .htaccess:
RewriteCond %{REQUEST_URI} !^m$ [NC]
RewriteRule (.*) https://www.intmath.com/$1 [R=301,L]

This now redirects the old m.example.com/directory/page to www.example.com/directory/page, and there is no infinite loop for www.example.com/m


text:
Q: Why is actix-session not correctly assigning values? I am newbie to Rust, and I am developing a Rust HTTP API with Actix Web. In order to maintain the session between requests, I wanted to use the official-provided package Actix Session, currently, this is my implementation on main.rs:
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let session_secret_key = CookieKeyHelper::generate();

    let server = HttpServer::new(move || {
        App::new()
            .wrap(Cors::permissive())
            .wrap(
                SessionMiddleware::builder(
                    CookieSessionStore::default(),
                    session_secret_key.clone(),
                )
                .cookie_secure(false)
                .build(),
            )
    // [...]
    })

And in some places I'm calling it:
      // [...]
          return match token_result {
            Ok(token) => {
                println!("Received token: {:?}", token);
                println!("Access token: {:?}", token.access_token().secret());
                session
                    .insert::<StandardTokenResponse<EmptyExtraTokenFields, BasicTokenType>>(
                        "token", token,
                    )
                    .unwrap();
                session
                    .insert::<AuthorizationCode>(
                        "auth_code",
                        AuthorizationCode::new(query["code"].to_string()),
                    )
                    .unwrap();
      // [...]

No errros are raised, but then, when I try to read the session values with session.entries(), it is always empty {}.
What am I doing wrong here?
Thanks in advance!! :)


text:
Q: Outlook HTML signature using VML - sends as converted image Whilst trying to get a background-image working in a  in Outlook, I tried using VML which works great:

my signature content

However, when sending this signature from Outlook to a mac, the VML area and the HTML content inside it appear to be converted to a image?
Any ideas?

A: Found it here:
http://grabalife.com/2011/05/19/using-mailchimp-and-background-images-in-your-table-cells/
(not wrapping your HTML content in VML)


text:
Q: How to estimate variance components with lmer for models with random effects and compare them with lme results I performed an experiment where I raised different families coming from two different source populations. Each family was assigned one of two treatments. After the experiment I measured several traits on each individual.
To test for an effect of either treatment or source as well as their interaction, I used a linear mixed effect model with family as random factor, i.e.
lme(fixed=Trait~Treatment*Source,random=~1|Family,method="ML")

so far so good,
Now I have to calculate the relative variance components, i.e. the percentage of variation that is explained by either treatment or source as well as the interaction.
Without a random effect, I could easily use the sums of squares (SS) to calculate the variance explained by each factor. But for a mixed model (with ML estimation), there are no SS, hence I thought I could use Treatment and Source as random effects too to estimate the variance, i.e.
lme(fixed=Trait~1,random=~(Treatment*Source)|Family, method="REML")

However, in some cases, lme does not converge, hence I used lmer from the lme4 package:
lmer(Trait~1+(Treatment*Source|Family),data=DATA)

Where I extract the variances from the model using the summary function:
model<-lmer(Trait~1+(Treatment*Source|Family),data=regrexpdat)
results<-VarCorr(model)
variances<-results[,3]

I get the same values as with the VarCorr function. I use then these values to calculate the actual percentage of variation taking the sum as the total variation.
Where I am struggling is with the interpretation of the results from the initial lme model (with treatment and source as fixed effects) and the random model to estimate the variance components (with treatment and source as random effect). I find in most cases that the percentage of variance explained by each factor does not correspond to the significance of the fixed effect.
For example for the trait HD,
The initial lme suggests a tendency for the interaction as well as a significance for Treatment. Using a backward procedure, I find that Treatment has a close to significant tendency. However, estimating variance components, I find that Source has the highest variance, making up to 26.7% of the total variance.
The lme:
anova(lme(fixed=HD~as.factor(Treatment)*as.factor(Source),random=~1|as.factor(Family),method="ML",data=test),type="m")
                                      numDF denDF  F-value p-value
(Intercept)                                1   426 0.044523  0.8330
as.factor(Treatment)                       1   426 5.935189  0.0153
as.factor(Source)                          1    11 0.042662  0.8401
as.factor(Treatment):as.factor(Source)     1   426 3.754112  0.0533

And the lmer:
summary(lmer(HD~1+(as.factor(Treatment)*as.factor(Source)|Family),data=regrexpdat))
Linear mixed model fit by REML
Formula: HD ~ 1 + (as.factor(Treatment) * as.factor(Source) | Family)
   Data: regrexpdat
    AIC    BIC logLik deviance REMLdev
 -103.5 -54.43  63.75   -132.5  -127.5
Random effects:
 Groups   Name                                      Variance  Std.Dev. Corr
 Family   (Intercept)                               0.0113276 0.106431
          as.factor(Treatment)                      0.0063710 0.079819  0.405
          as.factor(Source)                         0.0235294 0.153393 -0.134 -0.157
          as.factor(Treatment)L:as.factor(Source)   0.0076353 0.087380 -0.578 -0.589 -0.585
 Residual                                           0.0394610 0.198648
Number of obs: 441, groups: Family, 13

Fixed effects:
            Estimate Std. Error t value
(Intercept) -0.02740    0.03237  -0.846

Hence my question is, is it correct what I am doing? Or should I use another way to estimate the amount of variance explained by each factor (i.e. Treatment, Source and their interaction). For example, would the effect sizes be a more appropriate way to go?

A: One common way to determine the relative contribution of each factor to a model is to remove the factor and compare the relative likelihood with something like a chi-squared test:
pchisq(logLik(model1) - logLik(model2), 1)

As the way that likelihoods are calculated between functions may be slightly different, I typically will only compare them between the same method.


text:
Q: Conversion between angle with axis & angle with axial plane Let's imagine in 3D space I have three angle, $\theta_x$,$\theta_y$,$\theta_z$ respectively with X-axis, Y-axis, Z-axis.
Just like $\alpha,\beta,\gamma$ here:

I also have $\theta_{xy},\theta_{yz},\theta_{zx}$ angle respectively with plane-XY, plane-YZ, plane-ZX.
Just like r,$\theta$,$\sigma$ here:

What are relation between them?

A: Let's name a unit vector $v$ with these angles, so
$$
v = \pmatrix{x \\y\\z}
$$
with $x^2 + y^2 + z^2 = 1$. The assumption on the axis-angles says that
$$
\cos \theta_x = x\\
\cos \theta_y = y\\
\cos \theta_z = z
$$
What about $\theta_{xy}$? The angle between $v$ and the $xy$-plane is ... well, that depends. Suppose that $z > 0$. Then the angle is somewhere between $0$ and $\pi/2$, right? What if $z < 0$ --- is the angle between $-\pi/2$ and $0$? Or is it again in the interval $[0, \pi/2]$?
I'm going to assume the first case. Let's start with $z > 0$. Then the angle $\theta_z$ from $v$ to the $z$-axis is $\arccos(z)$, and so the angle from $v$ to the $xy$-plane is $\pi/2$ minus this, i.e., $\theta_{xy} = \pi/2 - \theta_z$.
Now let's look at the case $z < 0$. I'm going to assume that this produces an angle $\theta_{xy}$ that's in the interval $[-\pi/2, 0]$. When $\theta_z = \pi/2$, we want $\theta_{xy} = 0$; when $\theta_z = \pi$, we want $\theta_{xy} = -\pi/2$. Because we know they're linearly related, we see that $\theta_{xy} + \theta_z = \pi/2$, hence $\theta_{xy} = \pi/2 - \theta_z$.
Aha! The same formula applies in both cases, so we have
$$
\theta_{xy} =\pi/2 - \theta_z\\
\theta_{xz} =\pi/2 - \theta_y\\
\theta_{yz} =\pi/2 - \theta_x
$$


text:
Q: How to access downloaded sound in IsolatedStorage via URI (WP7)? I basically downloaded a file name custom.mp3 into my isolatedstorage and I can see it via isolatedstorage explorer....
The question here is... How can I access the particular custom.mp3 via URI?
So far I got this.. but I wonder why it is not working:
alarm.Sound = new Uri("isostore:/custom.mp3", UriKind.Absolute);

A: Your path is wrong. Nothing else is wrong with your code. Post the code you're using for saving the mp3 file in the first place, if you want further help.

A: For easier reading, the code to store the MP3 goes something like this..
string alarmfile = "custom.mp3";
isolatedStorageFileStream = new IsolatedStorageFileStream(alarmfile,FileMode.Create,isolatedStorageFile);
long songfilelength = (long) e.Result.Length;
byte[] songbyte = new byte[songfilelength];
e.Result.Read(songbyte, 0, songbyte.Length);
isolatedStorageFileStream.Write(songbyte, 0, songbyte.Length);
isolatedStorageFileStream.Flush();

A: Only files packaged in the XAML can be used as alarm sound:

Remarks
The Sound URI must point to a file packaged in the application's .xap
file. Isolated storage is not supported. When the alarm is launched,
the sound is played quietly and then gradually increases in volume.
There is no way to modify this behavior.

From:
Alarm.Sound Property


text:
Q: gdb breakpoint won't set I'm trying to debug C++ code using gdb. Particularly, I want to check if a certain variable (viscosities[j]) is not NAN and within certain bounds (eta_min and eta_max). I'm doing it using the following code:
if (!crash)
    {
        if (viscosities[j]>=eta_min && viscosities[j]<=eta_max)
            {}
        else
            {
                std::cout<<"viscosities[j]: "<<viscosities[j]<<"  ";
                crash = true;
            }
    }

(I need the variable crash because the code part of a loop, it's initialized to 0 before the loop starts).
In gdb, I'm trying to set the breakpoint using the following command:
break nz.cc:238

(line 238 is one with the cout statement)
However, the breakpoint is instead set to line 246:
Breakpoint 3 at 0xaeeb09: file /home/lev/aspect/aspect/source/material_model/nz.cc, line 246. (2 locations)

and the compiler never stops at line 238. I verified the line number through vi and made sure to rebuild the executable. Can anyone please give me an idea of why this might be happening? Thanks in advance!
UPD: solved by disabling optimization during executable compilation


text:
Q: Como transitar entre janelas? Estou criando um sistema simples apenas para aprender um pouco sobre a biblioteca tkinter.
Porém, empaquei bem aqui.
A ideia é criar várias páginas no mesmo código (eu sei que o correto seria modularizar o código, mas por se tratar de um projeto pequeno, tudo junto irá servir). Porém, eu gostaria de poder apertar um botão e assim ficar viajando de uma página para outra.
Por exemplo, eu executo o programa e então me é mostrado a Página 1.

Ao clicar no botão "Página 2", eu deveria ir para a página 2. Onde lá deveria ter um botão "Voltar" que me leve de volta a Página 1.

E esse processo deveria ocorrer com qualquer página que eu queira criar.
Eu quero pedir essa ajuda, pois todos os códigos que eu encontrei eram muito confusos e/ou não trabalhavam com páginas isoladas separadamente onde o botão iria chamá-las.
Código:
from tkinter import *
import sys

janela1 = Tk()
b1 = Button(janela1, text="Janela 2")
b1.grid()
b2 = Button(janela1, text="Janela 3")
b2.grid()
janela1.geometry("200x100")
janela1.mainloop()

sys.exit()

janela2 = Tk()
b3 = Button(janela2, text="Voltar")
b3.grid()
janela2.geometry("200x100")
janela2.mainloop()

janela3 = Tk()
b4 = Button(janela3, text="Voltar")
b4.grid()
janela3.geometry("200x100")
janela3.mainloop()

A: Para isso existe o Tkinter.Frame e com o método pack para exibir o frame que deseja e usando o pack_forget (pode usar o forget_grid se for tabalhar com grids) para ocultar (remover), exemplo bem simples:
from tkinter import *

root = Tk()

frame1 = Frame(root)
frame2 = Frame(root)

def go_home():
    frame2.pack_forget()
    frame1.pack()

def go_second():
    frame1.pack_forget()
    frame2.pack()

root.title("páginas")

btn_page2 = Button(frame1, text="Página 2", command=go_second)
btn_page2.pack()

btn_home = Button(frame2, text="inicial", command=go_home)
btn_home.pack()

frame1.pack()

root.mainloop()

Também existe o método raise que tem o equivalente em python como frame.tkraise(), que irá mudar a ordem dos frames adicionados no root, nesse caso ambos frames sempre estarão lá (nesse caso não achei documentado em Python, assim que encontrar vou tentar produzir um exemplo).


text:
Q: How to add Doxygen Comments for "C" variables with long type names
  I have a code

   static const guint8 variable;

when I put a documentation

/**
 * \var static const guint8 variable;
 * \brief This is a variable
 */
static const guint8 variable;

I do not get any output in the generated documentation. However, when the same thing is done with a simple variable decleration:

/**
 * \var int someothervar;
 * \brief This is some other variable
 */
int variable;

it does work
is that I am making some mistake in the usage ?
Thanks for any help in advance,
- elechi

A: For extracting static variables you should set EXTRACT_STATIC to YES.
If the documentation is in front of the variable, you do not need (and should not use) \var
Either set EXTRACT_ALL to YES or add a comment with a @file command in your code to document the file itself.


text:
Q: Making a draw/paint app I'd like to include a simple draw feature on my app. A friend told me I can't use canvas because I need to control the frame buffer and not redraw the entire screen every for every frame. He suggested I find a openGL 2d engine. I've searched around and I've only found Rokon which doesn't have any documentation and the examples aren't quite what I need.
Any suggestions?

A: I don't really understand what the problem is?
If you simply wish to redraw some portion of the canvas you can use invalidate(rect).
http://developer.android.com/reference/android/view/View.html#invalidate()

A: Just create a custom veiw by extending the view class. in this custome view override the onDraw method. Android itself takes care of the pixels that have been changed and calling invalidate only refreshes the pixels that have been marked dirty


text:
Q: Hot to partially render a voxel object? I do have 3D array[250][150][250] which represents human body (basically it is a voxel object). Each element contain values from 0 to 255, where 255 means that an elements is empty and should be ignored and 0-254 represent different organs (like skin, lung and etch) hence should be drawn. In my program I writing the data of elements that should be drawn in 2 txt files (vertices.txt and indices.txt). vertices.txt contain x,y and z coordinates of all voxel vertices that should be drawn and indices.txt contain all indices.
I am able to render whole body with all organs that is not the problem.
Example from vertices.txt:
193 68 0 // coordinates of a voxel
193 68 1
193 69 0
193 69 1

Example from indices.txt:
4 5 7 4 6 7  // face of a voxel. Each face is represented by 2 triangles. Hence, we need 6 indices.
2 3 7 2 6 7
0 4 6 0 2 6

My problem is that I do not know how to render a specific part of a body (For example: lets say that I want to render only lungs). How can I do that? Do I have to create indices.txt and vetices.txt for each individual organ (basically making each organ as a separate mesh)?
EDIT: Code that is responsible for writing into vertices.txt and indices.txt.
void writePhantomDataToThefile(std::ofstream& verticies_out_file, std::ofstream& indicies_out_file)
{
    verticies_out_file.open(vertices, std::ofstream::out | std::ofstream::trunc);
    indicies_out_file.open(indices, std::ofstream::out | std::ofstream::trunc);

    unsigned elements = 0;

    for (int z = 0; z < zMax; z++)
    {
        for (int y = 0; y < yMax; y++)
        {
            for (int x = 0; x < xMax; x++)
            {
                if (phantom->voxel[x][y][z] == emptyVoxel) // empty voxel is 255
                {
                    continue;
                }
                else
                {
                    if ((x != 0 && x != (xMax - 1)) && (y != 0 && y != (yMax - 1)) && (z != 0 && z != (zMax - 1)) &&
                        (phantom->voxel[x + 1][y][z] != emptyVoxel) && (phantom->voxel[x - 1][y][z] != emptyVoxel) && (phantom->voxel[x][y + 1][z] != emptyVoxel) &&
                        (phantom->voxel[x][y - 1][z] != emptyVoxel) && (phantom->voxel[x][y][z + 1] != emptyVoxel) && (phantom->voxel[x][y][z - 1] != emptyVoxel))
                    { // this part of code skips elements if is surrounded by elements != 255
                        continue; // basically right now I am drawing the skin of a body
                    }

                    verticies_out_file << x << " " << y << " " << z << std::endl;
                    verticies_out_file << x << " " << y << " " << z + 1 << std::endl;
                    verticies_out_file << x << " " << y + 1 << " " << z << std::endl;
                    verticies_out_file << x << " " << y + 1 << " " << z + 1 << std::endl;
                    verticies_out_file << x + 1 << " " << y << " " << z << std::endl;
                    verticies_out_file << x + 1 << " " << y << " " << z + 1 << std::endl;
                    verticies_out_file << x + 1 << " " << y + 1 << " " << z << std::endl;
                    verticies_out_file << x + 1 << " " << y + 1 << " " << z + 1 << std::endl;

                    if (x != 0 && x != (xMax - 1))
                    {
                        if (phantom->voxel[x - 1][y][z] != emptyVoxel)
                        {
                            indicies_out_file << (elements * 8) << " " << (elements * 8 + 2) << " " << (elements * 8 + 3) << " "
                            << (elements * 8) << " " << (elements * 8 + 1) << " "<< (elements * 8 + 3) << std::endl; // left face
                        }
                        if (phantom->voxel[x + 1][y][z] != emptyVoxel)
                        {
                            indicies_out_file << (elements * 8 + 4) << " " << (elements * 8 + 5) << " "<< (elements * 8 + 7) << " "
                            << (elements * 8 + 4) << " "<< (elements * 8 + 6) << " " << (elements * 8 + 7) << std::endl; // right face
                        }
                    }
                    else
                    {
                        if (x == 0)
                        {
                            indicies_out_file << (elements * 8) << " " << (elements * 8 + 2) << " "<< (elements * 8 + 3) << " "
                            << (elements * 8) << " "<< (elements * 8 + 1) << " "<< (elements * 8 + 3) << std::endl; // left face
                        }
                        if (x == (xMax - 1))
                        {
                            indicies_out_file << (elements * 8 + 4) << " "<< (elements * 8 + 5) << " "<< (elements * 8 + 7) << " "
                            << (elements * 8 + 4) << " " << (elements * 8 + 6) << " " << (elements * 8 + 7) << std::endl; // right face
                        }
                    }

                    if (y != 0 && y != (yMax - 1))
                    {
                        if (phantom->voxel[x][y - 1][z] != emptyVoxel)
                        {
                            indicies_out_file << (elements * 8 + 1) << " " << (elements * 8 + 5) << " "<< (elements * 8 + 4) << " "
                            << (elements * 8 + 1) << " " << (elements * 8) << " "<< (elements * 8 + 4) << std::endl; // bottom face
                        }
                        if (phantom->voxel[x][y + 1][z] != emptyVoxel)
                        {
                            indicies_out_file << (elements * 8 + 2) << " " << (elements * 8 + 3) << " " << (elements * 8 + 7) << " "
                            << (elements * 8 + 2) << " " << (elements * 8 + 6) << " " << (elements * 8 + 7) << std::endl; // top face
                        }
                    }
                    else
                    {
                        if (y == 0)
                        {
                            indicies_out_file << (elements * 8 + 1) << " " << (elements * 8 + 5) << " " << (elements * 8 + 4) << " "
                            << (elements * 8 + 1) << " " << (elements * 8) << " " << (elements * 8 + 4) << std::endl; // bottom face
                        }

                        if (y == (yMax - 1))
                        {
                            indicies_out_file << (elements * 8 + 2) << " " << (elements * 8 + 3) << " " << (elements * 8 + 7) << " "
                            << (elements * 8 + 2) << " " << (elements * 8 + 6) << " " << (elements * 8 + 7) << std::endl; // top face
                        }
                    }

                    if (z != 0 && z != (zMax - 1))
                    {
                        if (phantom->voxel[x][y][z - 1] != emptyVoxel)
                        {
                            indicies_out_file << (elements * 8) << " " << (elements * 8 + 4) << " " << (elements * 8 + 6) << " "
                            << (elements * 8) << " " << (elements * 8 + 2) << " " << (elements * 8 + 6) << std::endl;  // front face
                        }

                        if (phantom->voxel[x][y][z + 1] != emptyVoxel)
                        {
                            indicies_out_file << (elements * 8 + 1) << " " << (elements * 8 + 5) << " " << (elements * 8 + 7) << " "
                            << (elements * 8 + 1) << " " << (elements * 8 + 3) << " " << (elements * 8 + 7) << std::endl; // back face
                        }
                    }
                    else
                    {
                        if (z == 0)
                        {
                            indicies_out_file << (elements * 8) << " " << (elements * 8 + 4) << " " << (elements * 8 + 6) << " "
                            << (elements * 8) << " " << (elements * 8 + 2) << " " << (elements * 8 + 6) << std::endl;  // front face
                        }

                        if (z == (zMax - 1))
                        {
                            indicies_out_file << (elements * 8 + 1) << " " << (elements * 8 + 5) << " " << (elements * 8 + 7) << " "
                            << (elements * 8 + 1) << " " << (elements * 8 + 3) << " " << (elements * 8 + 7) << std::endl; // back face
                        }
                    }

                    elements++;
                }
            }
        }
    }

    verticies_out_file.close();
    indicies_out_file.close();
}

Mesh.cpp
#include "Mesh.h"
#include <iostream>
#include <sstream>
#include <fstream>

Mesh::Mesh()
{
    loaded = false;
}

Mesh::~Mesh()
{
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &ibo);
}

void Mesh::loadVertices(std::string fileName)
{
    int item = 0, n = 0, x = 0, y = 0;
    std::ifstream is(fileName, std::ifstream::binary);

    if (is) {
        is.seekg(0, is.end);
        int length = is.tellg();
        is.seekg(0, is.beg);

        char* buffer = new char[length];

        is.read(buffer, length);

        is.close();

        for (unsigned int i = 0; i < is.gcount(); i++)
        {
            switch (buffer[i])
            {
            case '\r':
                break;
            case '\n':
            {
                vertices.push_back(glm::vec3(y, item, x));
                n = 0;
                item = 0;
                break;
            }
            case ' ':
            {
                n++;
                if (n == 1)
                {
                    x = item;
                }
                else
                {
                    y = item;
                }

                item = 0;
                break;
            }
            case '0': case '1': case '2': case '3':
            case '4': case '5': case '6': case '7':
            case '8': case '9':
                item = 10 * item + buffer[i] - '0';
                break;
            default:
                std::cerr << "Bad format\n";
            }
        }

        delete[] buffer;
    }
}

void Mesh::loadIndices(std::string fileName)
{
    int item = 0;
    std::ifstream is(fileName, std::ifstream::binary);

    if (is) {
        is.seekg(0, is.end);
        int length = is.tellg();
        is.seekg(0, is.beg);

        char* buffer = new char[length];

        is.read(buffer, length);

        is.close();

        for (unsigned int i = 0; i < is.gcount(); i++)
        {
            switch (buffer[i])
            {
            case '\r':
                break;
            case '\n':
            {
                indicies.push_back(item);
                item = 0;
                break;
            }
            case ' ':
            {
                indicies.push_back(item);
                item = 0;
                break;
            }
            case '0': case '1': case '2': case '3':
            case '4': case '5': case '6': case '7':
            case '8': case '9':
                item = 10 * item + buffer[i] - '0';
                break;
            default:
                std::cerr << "Bad format\n";
            }
        }

        delete[] buffer;
    }
}

bool Mesh::loadOBJ()
{
    loadVertices("Phantom Data/FA_vertices.txt");
    loadIndices("Phantom Data/FA_indices.txt");

    initBuffers();

    return (loaded = true);
}

void Mesh::draw()
{
    if (!loaded) return;

    glBindVertexArray(vao);
    glDrawElements(GL_TRIANGLES, indicies.size(), GL_UNSIGNED_INT, nullptr);
    glBindVertexArray(0);
}

void Mesh::initBuffers()
{

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), NULL);
    glEnableVertexAttribArray(0);

    glGenBuffers(1, &ibo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicies.size() * sizeof(GLuint), &indicies[0], GL_STATIC_DRAW);

    glBindVertexArray(0);
}


text:
Q: Shaded/Repackaged jar as a dependency We have a situation where we need one application to be able to connect to to two versions of kafka(0.7.2 and 0.10.0+) and act as a router. I'm trying to omit using two runtimes here as we need this to be stupid fast, so want to prevent additional serialization/deserialization when sending data between runtimes.
To do this, i've tryied to repackage the old kafka driver from package kafka to old.kafka like so:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>kafka-router</artifactId>
        <groupId>org.deer</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>old-kafka</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <kafka.version>0.7.2</kafka.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.1.1</version>
                <executions>
                    <execution>
                        <id>unpack</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.apache.kafka</groupId>
                                    <artifactId>kafka_2.9.2</artifactId>
                                    <version>${kafka.version}</version>
                                    <type>jar</type>
                                    <overWrite>false</overWrite>
                                    <outputDirectory>${project.build.directory}/classes</outputDirectory>
                                    <includes>**/*.class,**/*.xml</includes>
                                </artifactItem>
                            </artifactItems>
                            <includes>**/*.java</includes>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>true</overWriteSnapshots>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.2</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <relocations>
                                <relocation>
                                    <pattern>kafka.</pattern>
                                    <shadedPattern>old.kafka.</shadedPattern>
                                </relocation>
                            </relocations>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

I'm using dependency plugin to unpack kafka classes to target/classes & shade plugin to repackage them. The reason for this is that the final jar should act as if it is a kafka driver jar(it has no other transitive dependencies, therefore it can't cause some mismatch using kafka instead of old.kafka. But that's not really the point here, just trying to prevent out-of-topic questions.
The main problem here is that when i look at the jar that has been installed to .m2, it looks correct(having the old.kafka package):

But when i try to use this jar as dependency like so ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>kafka-router</artifactId>
        <groupId>org.deer</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>router-app</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.deer</groupId>
            <artifactId>old-kafka</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

... and reference it in a class like so ...
package org.deer.test;

import old.kafka.producer.ProducerData;

public class TwoKafkaDriversExample {

    public static void main(String[] args) {
        new ProducerData();
    }
}

... the import it self is not working. I have a suspicion that the shaded jar is missing something maven-related, but haven't noticed anything. Another possible though is that shade plugin or asm doesn't like the bytecode that scala classes are generating.

A: Ok, so i've been able to figure this out. The import error is a problem with intelij, for some reason it doesn't see the repackaged classes. But the maven does, with using correct constructor and adding scala-lang dependency(it was complaining about missing Seq class) i was able to build this.

Full example uploaded on github - https://github.com/Marssmart/kafka-router


text:
Q: iOS Login with cancel and success on storyboard This is my first iOS app and at this moment I'm struggling with Acccount / Login transitions on my storyboard.
What I'm trying to do is, If there is no logged user, display the login, otherwise display the account menu (Edit profile, My savings, and Logout).
Actually I'm achieving with this code on my AccountMenuViewController:
- (void)viewDidLoad
{
    [super viewDidLoad];

    if (![self isLogged]) {
        [self presentLoginView];
    }
}

#pragma mark - Login methods
- (BOOL)isLogged
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    return [[defaults objectForKey:@"loggedIn"] boolValue];
}

- (void)presentLoginView
{
    [self performSegueWithIdentifier:@"LoginSegueId" sender:self];
}

When the user touch "Cancel login" I'm trying to redirect to my MainView, I've make a segue but the Tab Bar is not displayed.
And when the login is ok, Close the login view.
I want to know your advices and tips, What are the best practices with this scenario?
This is my Storyboard.

A: First you should either make the login screen your rootViewController and just push to main view if
[self isLogged]==YES

or have the Login presented in a model fashion with the main view as a root, that way instead of a segue you can just dismiss it and the main view will be present underneath. you can also have the main view push the login and just hide the nav bar and use 'cancel login' as a sort of '< back' button that you would see on the nav bar by using the popViewController method..... also you can simplify the method:
- (BOOL)isLogged
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    return [[defaults objectForKey:@"loggedIn"] boolValue];
}

can be :
- (BOOL)isLogged
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    return [[NSUserDefaults standardUserDefaults] boolForKey:@"loggedIn"];
}

hope i helped!


text:
Q: Как обобщить алгоритм работы с данными через EntityFramework? Мне кажется что логику получения данных, добавления и удаления можно как-то обобщить, так как по сути они все выполняют одно и тоже действие только с разными данными, да еще и таблиц будет достаточно много. Можно ли что-то придумать для данного примера?
public interface IDataRepository
{
    IQueryable<Manufacturer> GetManufacturers();
    IQueryable<Product> GetProducts();
    void Add(Product product);
    void Add(Manufacturer manufacturer);
    void Remove(Product product);
    void Remove(Manufacturer manufacturer);
}

public class EFDataRepository : IDataRepository
{
    private readonly WarehouseDbContext _context;

    public EFDataRepository(WarehouseDbContext context)
    {
        _context = context;
    }

    public IQueryable<Manufacturer> GetManufacturers() => _context.Manufacturer;

    public IQueryable<Product> GetProducts() => _context.Products;

    public void Add(Manufacturer manufacturer)
    {
        _context.Manufacturer.Add(manufacturer);
        _context.SaveChanges();
    }

    public void Add(Product product)
    {
        _context.Products.Add(product);
        _context.SaveChanges();
    }

    public void Remove(Manufacturer manufacturer)
    {
        _context.Manufacturer.Remove(manufacturer);
        _context.SaveChanges();
    }

    public void Remove(Product product)
    {
        _context.Products.Remove(product);
        _context.SaveChanges();
    }

}

A: Придумал вот такое решение:
public interface IDataRepository
{
    void Add<T>(T entity) where T : class;
    void Remove<T> (T entity) where T : class;
    IQueryable<T> GetData<T>() where T : class;
}

public class EFDataRepository : IDataRepository
{
    private readonly WarehouseDbContext _context;
    public EFDataRepository(WarehouseDbContext context)
    {
        _context = context;
    }
    public void Add<T>(T entity) where T : class
    {
        _context.Set<T>().Add(entity);
        _context.SaveChanges();
    }
    public void Remove<T>(T entity) where T : class
    {
        _context.Set<T>().Remove(entity);
        _context.SaveChanges();
    }
    public IQueryable<T> GetData<T>() where T : class => _context.Set<T>();
}


text:
Q: Cannot resolve symbol length I want to retrieve a list of images from SQLite.
This is my 'getImage()' method
    public List<byte[]> getImage(int i) {
    List<byte[]> list = new ArrayList<>();
    String selectImage = "SELECT VocabImage FROM Vocab WHERE VocabTopic =" + i;
    Cursor c = database.rawQuery(selectImage, null);
    if(c.moveToFirst())
        do{
            list.add(c.getBlob(c.getColumnIndex("VocabImage")));
        }while(c.moveToNext());

    c.close();
    return list;
}

This is my java class where I want to call my getImage() method. But there is an error saying that it cannot resolve symbol 'length' in (data.length) in the BitmapFactory line. Anyone has any idea how to solve this? Thank you.
 Intent intent = getIntent();

 int topicId = intent.getIntExtra("SelectedTopicId", 1);

 databaseAccess.open();

 List<byte[]>data = databaseAccess.getImage(topicId);

 Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);

 imageView.setImageBitmap(image);

A: Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);

change to
Bitmap image = BitmapFactory.decodeByteArray(data.get(position), 0, data.get(position).length);  // pass position for which you want length.

A: you need to change like this: list.get(0).length for get image at index 0.


text:
Q: Django 1.5.1 "'STDOUT_LINE' is not defined" when running tests When I run tests in Django for my applications I have the following exception
.......NameError: global name 'STDOUT_LINE' is not defined
There're only 9 test methods in the test case.
What may cause this problem, may be someone already faced this kind of problem?
Verbose output
$ : ./manage.py test profile
/Users/sultan/.virtualenvs/yoda/lib/python2.7/site-packages/nose/util.py:14: DeprecationWarning: The compiler package is deprecated and removed in Python 3.x.
  from compiler.consts import CO_GENERATOR

nosetests --verbosity 1 profile --verbosity=2 --with-snot --with-xtraceback --with-coverage --cover-package=profile
/Users/sultan/.virtualenvs/yoda/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:53: RuntimeWarning: SQLite received a naive datetime (2013-04-22 11:19:12.808338) while time zone support is active.
  RuntimeWarning)

Creating test database for alias 'default'...
Test page to create order ... ok
Test with anonymous user, index page should give a login form ... ok
Test with anonymous user, index page should give a login form ... ok
Test drivers list ... ok
Test operators list ... ok
Test if login works ... ok
Test if user logged in as manager will be redirected to /manager page ... ok
Test if user logged in as operator will be redirected to /operator page ... NameError: global name 'STDOUT_LINE' is not defined

Update tests for urls
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.core.urlresolvers import reverse

from profile.tests.factories import UserFactory
from profile.models import ROLE_OPERATOR, ROLE_USER
from profile.models import ROLE_ADMIN, ROLE_DRIVER, ROLE_MANAGER

class TestUrls(TestCase):
    """ Test common project wide urls """

    def setUp(self):
        self.user = UserFactory.create(role=ROLE_USER)
        self.admin = UserFactory.create(role=ROLE_ADMIN, is_superuser=True)
        self.driver = UserFactory.create(role=ROLE_DRIVER)
        self.manager = UserFactory.create(role=ROLE_MANAGER)
        self.operator = UserFactory.create(role=ROLE_OPERATOR)

    def get(self, url, follow=True):
        return self.client.get(url, follow=follow)

    def login(self):
        self.client.login(username=self.manager.username, password='pass')

    def test_index_page_login(self):
        """ Test with anonymous user, index page should give a login form """
        res = self.get(reverse('profile:index'))
        self.assertContains(res, 'Login')
        self.assertEqual(res.status_code, 200)

    def test_login(self):
        """ Test if login works """
        res = self.get(reverse('profile:login'))
        res2 = self.get(reverse('profile:login'), follow=False)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res2.status_code, 302)

    def test_operator_redirect(self):
        """
        Test if user logged in as operator
        will be redirected to /operator page
        """
        self.login()
        res = self.get(reverse('profile:index'))
        self.assertTrue('/operator' in res.request['PATH_INFO'])

    def test_manager_redirect(self):
        """
        Test if user logged in as manager
        will be redirected to /manager page
        """
        self.login()
        res = self.get(reverse('profile:index'))
        self.assertTrue('/manager' in res.request['PATH_INFO'])

    def test_references_page(self):
        """ Test references """
        self.login()
        res = self.get(reverse('profile:reference'))
        self.assertEqual(res.status_code, 200)
        self.assertTemplateUsed('profile/reference.html')

    def test_list_drivers(self):
        """ Test drivers list """
        self.login()
        res = self.get(reverse('profile:drivers'))
        self.assertEqual(res.status_code, 200)
        self.assertTemplateUsed('profile/driver_list.html')

    def test_list_operators(self):
        """ Test operators list """
        self.login()
        res = self.get(reverse('profile:operators'))
        self.assertEqual(res.status_code, 200)
        self.assertTemplateUsed('profile/operator_list.html')

    def test_error500(self):
        """ Test with anonymous user, index page should give a login form """
        res = self.get(reverse('profile:error500'))
        self.assertEqual(res.status_code, 200)

    def test_create_order_page(self):
        """ Test page to create order """
        res = self.get(reverse('profile:new_order'), follow=False)
        self.assertEqual(res.status_code, 302)

        self.login()

        res = self.get(reverse('profile:new_order'))
        self.assertEqual(res.status_code, 200)

A: Problem solved it was because of assertion failed at
def test_operator_redirect(self):
    """ Test if user logged in as operator will be redirected to /operator page """
    self.login(self.operator)
    res = self.get(reverse('taxi:index'))
    self.assertTrue('/operator' in res.request['PATH_INFO'])

So I changed self.login method and it worked though this error appears again if self.assertTrue fails
def login(self, user):
    self.client.login(username=user.username, password='pass')


text:
Q: Dask - Create empty array to fill and save it I want to create a huge (>100GB) dask array and then fill it with values that I compute. Then I want to save it as an hdf5 file. I have chosen  This is my code:
import dask.array as da

size = 100000
chunks = 50000
file_path = "..."

# calculate entries
A = da.zeros(shape=(size, size), chunks=(chunks, chunks))
for i in range(size):
    for j in range(size):
        A[i,j] = compute_value(i,j)

# store in FS
f = h5py.File(file_path)
dset = f.create_dataset('/data', shape=A.shape, chunks=(chunks, chunks), dtype='f8')
da.store(A, dset)

I get the error at the assignment A[i,j]:
NotImplementedError: Item assignment with <class 'tuple'> not supported

Note that this array is too big to fit into RAM. Therefore it should somehow save the array as all zeros and then update this saved matrix with the computed values.
What is the proper way of doing this in dask?
Thanks for your help!

A: It worked saving the matrix first in the hdf5 format and then changing the values. Here's the code:
size = 100000
chunks = 5000
file_path = "..."

A = da.zeros(shape=(size, size), chunks=(chunks, chunks))
with h5py.File(file_path, 'w') as f:
    dset = f.create_dataset('/data', shape=A.shape, chunks=(chunks, chunks), dtype='f8')
    da.store(A, dset)
    for i in range(size):
        for j in range(size):
            dset[i,j] = random.randint(0,101)

This can be loaded and used later, e.g. as follows:
with h5py.File(file_path, 'r') as f:
    A = da.from_array(f["/data"], chunks=(chunks, chunks))
    x = da.linalg.solve(A, b)
    res = x.compute()


text:
Q: Does RSA encryption affect export compliance? I am using https://github.com/ideawu/Objective-C-RSA this library to encrypt some data using a public key.
Current live app is already using https for all calls. I am confused as to how will my answers on export compliance change on version update?
Also, do I need to add export compliance documentation on itunes connect?
Additional details:

*

*I am using only encryption from the library.

*Then the encrypted string is sent to server. The backend server is responsible for decryption using private key.

*The encryption is NOT for authentication purpose. It is used send sensitive data to server

A: Turns out my use case was falling under the money transactions category. As per the export guidelines, this category is allowed to use cryptographic algos.
All I had to do is mark "Yes" to the below questions during submission.
As per FAQ on iTunes Connect:

Does your product qualify for any exemptions provided under category 5 part 2?
(v) your app is specially designed and limited for banking use or 'money transactions.' The term 'money transactions' includes the collection and settlement of fares or credit functions.


text:
Q: I can't find the user and sum i have a problem, i need to add the debt of a user
controller:
 public function cliente($id){

        // $nota = App\Nota::find($id);

        //Aquí valida si existe sino redirije al 404
        $datos = [
            'category_name' => 'datatable',
            'page_name' => 'multiple_tables',
        'registro' => Registro::find($id),

        ];

        $cliente = \App\Models\User::findOrFail($id);

        return view('cliente', compact('cliente'))->with($datos);
    }

blade.php

Debt Sum:

 {{ $registro->user_id->sum('deuda') }}

Database:

i need to add the field "deuda" of the user, the relationship is in user_id with the users table
the error that I get is: Trying to get property 'user_id' of non-object
help pls

A: It's better to calculate sum of the registrations in your controller:
 public function cliente($id){

        // $nota = App\Nota::find($id);

        //Aquí valida si existe sino redirije al 404
        $datos = [
            'category_name' => 'datatable',
            'page_name' => 'multiple_tables',
            'registro' => Registro::find($id),
        ];

        $cliente = \App\Models\User::findOrFail($id);

        $sum = Register::where('user_id', $cliente->id)->sum('deuda');

        return view('cliente', compact('cliente','sum'))->with($datos);
    }

and in your view use sum variable

Debt Sum:

 {{ $sum ? $sum : 0 }}