Pooling imputed, still not analysed datasets in MICE

Question: I need to do a Multiple Imputation on a dataset with several missing values, and I need to do it with mice, because later I'll have to compare the results with those of imputations ran with other programs.
My colleague obtained a completa dataset by running a MI on the incomplete dataset, with 5 iterations, and then taking the 5 imputed datasets and manually calculating mean values. Se essentially he pooled manually. I'm far from an expert so I don't know if this operation is valid.
Anyways, in MICE so far I could run the imputation (again, with maxit=5), using the function "imp<-mice(eco)", where "eco" is the incomplete dataset. So I obtained the 5 imputed datasets, stored in the object "imp", of class "MIDS". Now I just need to pool the 5 completed datasets to obtain a unique complete one, i don't wanna run analyses on the 5 datasets and then pool the results. Can that be done? If I got it right from the manual, it seems that MICE allows you to pool only after you ran some analysis on the imputed datasets. The analysis is repeated on each dataset and the results are stored in an object of class "MIRA". I tried to run the function "pool()" on "imp" but it can't be done because imp is of class "mids" and you can only pool mira objects.
The manual also says that to pool you need a variance/covariance relation, and in the example given there they run a linear regression and then they pool the results of the regression. But I doubt if it's what I need. I'm confused
Answer: A major point of multiple imputations is to do separate analyses on each of the imputed data sets, so that you can get both pooled estimates of things like regression coefficients and an estimate of the errors in the coefficients. Averaging the imputed data sets first is not the correct use of this approach. And don't limit yourself to so few imputations; with modern computers there's no reason not to do 100 or more. See Stef van Buuren's Flexible Imputation of Missing Data for further information; he developed the mice package
Comment: @ShawnHemelstrand thanks for noting the broken link. I fixed it; please look at it. Comments on your [related question](https://stats.stackexchange.com/q/588111/28500) describe a couple of reasons why you can't just proceed with analyzing the pooled data together. If your model types aren't handled directly, [this page](https://stats.stackexchange.com/q/476829/28500) outlines how to do the pooling yourself, with a link to a [review](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2727536/) on the topic.
Comment: +1 for not limiting yourself to few imputations. This [paper](https://link.springer.com/article/10.1007%2Fs11121-007-0070-9) shows that we usually need more than we think we do.
Comment: But why is it incorrect to do it this way? I am having a lot of difficulty finding any information as to what the actual cost is of pooling your data first and then running the stats tests. For things like mixed models, it seems to create a ton of additional issues, namely a lack of functionality for necessary and often new functions for `lmer`/`glmer` objects because many libraries simply don't know how to handle `mids`/`mira` objects. Also this link seems to return a 404 error.
Comment: Thanks EdM for the advice
Answer: iris.mis is the data with missing values
imputed_Data <- mice(iris.mis, m=5, maxit = 50, method = 'pmm', seed = 500)
    summary(imputed_Data)

Here is an explanation of the parameters used:
 m  – Refers to 5 imputed data sets
 maxit – Refers to no. of iterations taken to impute missing values
 method – Refers to method used in imputation. we used predictive mean matching.
check imputed values
imputed_Data$imp$Sepal.Width

Also, if you wish to build models on all 5 datasets, you can do it in one
 go using with() command. You can also combine the result from these models
and obtain a consolidated output using pool() command.
build predictive model
fit <- with(imputed_Data,lm(Sepal.Width ~ Sepal.Length +
                                          Petal.Width))

combine results of all 5 models
summary(pool(fit))


Showing attribute ( Manufacture, Size, Color ) on magento checkout success page

Question: actually i do this for retrieve my order details on magento checkout success page
<?php
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_details = Mage::getModel('sales/order')->loadByIncrementId($order_id);
$shipping_address_data = $order_details->getShippingAddress();
?>

                <?php echo $this->__('Item Description') ?>
                <?php echo $this->__('Manufacture') ?>
                <?php echo $this->__('Color') ?>
                <?php echo $this->__('Size') ?>
                <?php echo $this->__('Qty') ?>
                <?php echo $this->__('Unit Price') ?>

        <?php foreach($order_details->getAllVisibleItems() as $item): ?>

                <?php echo $item->getName() ?>
                <?php echo $item->getManufacture() ?>
                <?php echo $item->getSize() ?>
                <?php echo $item->getColor() ?>
                <?php echo round($item->getQtyOrdered(), 0) ?>
                <?php echo Mage::helper("core")->currency($item->getPrice()) ?>

        <?php endforeach ?>

        <?php echo "
" . $shipping_address_data['country_name']; ?>

All is work fine except size, color, manufacture, and country name ( not showing )
Actually what's wrong with the code, anyone have a suggestion ?
Thanks
Answer: $item is not  give whole product data,it is give how may product item was ordered and it product some product name ,qty etc.
If you want get product ,then you will need to load product by item product id.
     $_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$item->getSku());
       echo $_product->getManufacture() ;
        echo  $_product->getSize(); //size optionid
        echo  $_product->getColor(); //color otion id
echo $_product->getAttributeText('color');
echo $_product->getAttributeText('size'); // size optionlabel

Comment: what type of product used?? configurable
Answer: use getAllItems instead of getAllVisibleItems
 <?php
      foreach($order_details->getAllItems () as $item):
        echo "
";print_r($item->getData());die;
      endforeach;
 ?>

print your result and check if you are getting the attributes value
Comment: just got it [product_options] => "attributes_info";a:2:{i:0;a:2:{s:5:"label";s:5:"Color";s:5:"value";s:5:"Print";}i:1;a:2:{s:5:"label";s:4:"Size";s:5:"value";s:2:"38" and then i am not sure to echo-ing it with this format @user3558854


Communication between different subnets with different masks

Question: I was wondering if there is any way to communicate between two networks with different mask. For example:
Network 1: 192.168.0.0 / 29
Network 2: 192.168.0.8 / 28 (which takes from the last possible position after Network 1)
This would be the network: http://i.cubeupload.com/zsCVlj.png
I can't seem to make this work and I wonder if this is either possible, or I'm messing something up.
Thanks!
Comment: It's going to be really hard to tell you what you have messed up if you tell us exactly nothing about it what you have done and what has (not) happened. And it is also not easily possible to tell you what you have to do as long as it is unclear how the routers are connected.
Comment: I'm sorry, I meant that I tried to ping a computer from Network 1 to Network 2 and it failed. It was due to wrong configuration on the network 2
Answer: Network 2 would have to be 192.168.0.16/28 in this instance, which would leave an unused /29 between Network 1 and Network 2. You can't just start a subnet wherever you feel like it.
You should probably use something like this online CIDR calculator to double-check the validity of your subnets.
Comment: You were totally right... I was just starting to try different masks and I messed up with the Network 2's IP, now I changed it to 192.168.0.16/28 and I can ping computers from the other network successfully. Thank you :)
Answer: Or instead you should use
<code>Network 1:  192.168.0.16/29 -- 192.168.0.17 - 192.168.0.22 useable 192.168.0.23 broadcast
Network 2:  192.168.0.0/28 -- 192.168.0.1 - 192.168.0.14 useable 192.168.0.15 broadcast
</code>
This will leave NO unused address space.
Comment: That's true as well! Thank you for your observation!


Combining Count and Round

Question: I calculate proportionate holiday by:
Count(Distinct Case When Workday NOT IN ('Saturday', 'Sunday')
AND hours > '0' then workday END) * Holidays / 5

I want to round every value in that column to nearest half and found that SELECT ROUND(2.2 * 2,0) / 2 is doing the rounding job.
Now i just doesnt get it together. As far as i can see Select Round expression gives me a scalar but i want to get every value in my column be rounded.  Round(expression above, * 2.0) / 2 is not working (underlines everything red).
Comment: Does that top expression even work?  It looks like the parenthesis end in the middle of the `WHEN...THEN` portion of the `CASE`.  Is this some kind of twisted SQL version of Duff's Device?
Comment: Put that expression into a derived table (subquery with an alias), give the result an alias, and round the result.
Comment: you are right, a parenthesis wasnt copied. edit done. thanks.
Answer: Try a separate Update?
Count(Distinct Case
When Workday NOT IN ('Saturday', 'Sunday')
AND hours > '0'
then workday
END) * Holidays / 5 as RoundThis

Update TableName
Set RoundThis = Round(RoundThis * 2.0) / 2

Or use variables
Answer: Assuming you've got an expression that compiles, this should do the trick:
ROUND( 2 * CAST(/*equation*/ AS DECIMAL), 0) / 2;
Note: You should probably cast to decimal before dividing by 5 however.
EDIT: Spelling out what works on my system:
ROUND(2 * (
  CAST(
    COUNT(Distinct Case When Workday NOT IN ('Saturday', 'Sunday')
    AND hours > '0' then workday END)
  AS DECIMAL) * Holidays / 5
), 0) / 2

Is this giving you an error or just the wrong result?
Comment: thanks. unfortunately this is not working, not even when i try the functions (Round and Cast) seperatly on the expression.
Comment: @ruedi Updated answer with the full column formula.

Combining Count and Round


Create a list with values from 1 to 'n' without a for-loop

Question: I have this function that receives an integer as a param. Its purpose is to return the sum of all the even numbers squared of a list.
For example, if n = 7 -> returns 56.
private static int myFunction (int n) {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);

        return list.stream().filter( x -> x % 2 == 0)  //Even numbers
                            .map(x -> x * x)           //Squared
                            .reduce(0, (x,y) -> x + y);//Sum
}

What I would like to do, without a for-loop, is to have something like this:
List<Integer> list = Arrays.asList(1,...,n);

As an example in Haskell you can create a list from 1 to n with this ' .. ' :
listToN :: Int -> [Int]
listToN n = [1 .. n]

Returns: [1,2,3,4,5,6,7] if n == 7
Comment: `IntStream.rangeClosed(1,7)`?
Answer: Seems like you are looking for IntStream.rangeClosed(1,7).
And btw don't use reduce if there is a dedicate method for that (which does exactly what you do via reduce)
IntStream.range(1, n)
            .filter(x -> x % 2 == 0)
            .map(x -> x * x)
            .sum();

Comment: Simpler and faster: `IntStream.range(0, (n+1)/2) .map(x -> 4 * x * x) .sum()` or potentially even faster: `4 * IntStream.range(0, (n+1)/2) .map(x -> x * x) .sum()`
Comment: @Holger :) indeed


GWT + PHP, manage JSON

Question: I'm trying to connect GWT with a PHP back-end; I successfully loaded some data in the front-end using the provided tutorial: https://developers.google.com/web-toolkit/doc/latest/DevGuideServerCommunication#DevGuideHttpRequests ; now I'm trying to send data from GWT to PHP using the same piece of code provided, but I don't know how I can modify it. In the Java GWT class I've done
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
    builder.setHeader("Content-Type", "application/json");
    try {
          Request request = builder.sendRequest("{\"data\":\"hello\"}", new RequestCallback() { ...

And then in the php script
echo json_decode($_POST);

But the error is "[INFO] [testapp] -
Warning:  json_decode() expects parameter 1 to be string, array given in C:\xampp\htdocs\TestApp\TestApp.php on line 25"
Can anyone provide a working example of this situation? Or link me some tutorial or document that talk more about how to use GWT with PHP? There is not so much in the official site...
Answer: echo json_decode($HTTP_ROW_POST_DATA);

or
echo json_decode(file_get_contents("php://input"))

See http://php.net/manual/en/reserved.variables.httprawpostdata.php and http://php.net/manual/en/wrappers.php.php (the latter should be preferred)
Answer: Try this:
<?php
echo json_decode($_POST['data']);

Because you want to decode your data parameter, not all posted parameters.
Comment: it gives me "Undefined index: data" because with sendRequest I can only give a string, not an index: in fact I use this parameter to pass the JSON.
Answer: sendRequest takes data and send data as array. you have to use json_decode(parse_str($_POST['data'])) to receive Request data
Comment: it still gives me 'undefined index:data...' using json_decode(parse_str($_POST['data'])) in backend: maybe the mistake is in
builder.sendRequest("{\"data\":\"hello\"}", new RequestCallback() { ...
Comment: first u can test which data is coming using **print_R($_POST);**
Comment: ok, u can send parameters like this **builder.sendRequest("?data=hello",.............**
Comment: GWT:
Request request = builder.sendRequest("?data=hello",...
PHP:
echo json_decode(print_r($_POST['data']));
RESPONSE:
>>Undefined index: data
Comment: use **print_r($_POST);**  not echo json_decode(print_r($_POST['data']));

GWT + PHP, manage JSON


Erro na criação da tabela SQL Server com Entity Framework

Question: Exclui uma tabela do meu projeto direto no Management Studio. Agora quando executo a aplicação está retorno este erro:

<code>system.data.sqlclient.sqlexception: Nome de objeto 'dbo.ContasPagarParcelas' inválido.
</code>

Não consigo recriar a tabela. Estou utilizando Entity Framework.
Comment: Você removeu a tabela do banco de dados mas não removeu do contexto do EF. Caso tenha duvida de como fazer isso, poste em sua pergunta o código do seu contexto, onde você define o DbSet da tabela que removeu.
Comment: Rodrigo, na verdade quero que a tabela seja recriada. Exclui direto no banco para ver o comportamento que o Entity teria ao executar o sistema novamente. Acreditava que a tabela seria recriada novamente.
Comment: Pelo que entendi na sua reposta, remover do contexto seria no caso de não utilizar mais está tabela, correto ?.
Comment: Voce deve usar CodeFrist, e deve fazer o migration, certo? se você cria migrations, apague os arquivos de migração, e mande criar um novamente. Se não funcionar, no seu banco de dados tem uma tabela com o histórico de migrações, você deve apagala
Comment: Rodrigo, consegui resolver como suas orientações. Muito obrigado.
Comment: òtimo, fico feliz. Se você puder clicar na setinha laranja do meu comentario, que fica ao lado esquerdo, eu agradeço, pois pontua minha ajuda. vlw!
Comment: Rodrigo, desculpe não encontro a setinha laranja.
Comment: Quando você passa o mouse sobre a minha mensagem, do lado esquerdo aparece uma triangulo, só clicar nele.
Comment: Coloquei, como resposta, ai você pode clicar no V, que fica ao lado esquerdo da resposta, desta forma obedecemos o fluxo do site.
Answer: Voce deve usar CodeFrist, e deve fazer o migration, certo? se você cria migrations, apague os arquivos de migração, e mande criar um novamente.
Se não funcionar, no seu banco de dados tem uma tabela com o histórico de migrações, você deve apagala


How to use gt/le operator in aurelia slickgrid with Odata

Question: I want to send my own operator in odata request and not use the aurelia slickgrid inbuilt "eq" operator.
This is my column definition
{
                id: 'LockoutEndDateUtc', name: 'Status', field: 'LockoutEndDateUtc', minWidth: 85, maxWidth: 95,
                type: FieldType.boolean,
                sortable: true,
                formatter: Formatters.multiple,
                params: { formatters: [this.StatusFormatter, Formatters.checkmark] },
                filterable: true,
                filter: {
                            collection: [
                                { value: 'le ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'True' },
                                { value: 'gt ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'False' }
                            ], //['', 'True', 'False'],
                            model: Filters.singleSelect,//multipleSelect//singleSelect,
                        }
            }

This is the UI

This is how the request filter looks like..
$filter=(LockoutEndDateUtc%20eq%20le%202022-06-28T12%3A59%3A25Z)

If i remove %20eq from the above request, everything else works. So my question is how to i remove %20eq. Or how do i send my own gt, le in the request.
Answer: You can't really do that on a boolean filter (you could however do it on a date filter with operator) and I don't think I've added any ways to provide a custom filter search the way you want to do it, but since you're using OData, you have a bit more control and you could change the query string yourself. To be clear, it's not at all recommended to change the OData query string, it's a last solution trick and at your own risk, but for your use case it might be the only way to achieve what you want.
prepareGrid() {
    this.gridOptions = {
      // ...
      backendServiceApi: {
        service: new GridOdataService(),
        process: (query) => this.getCustomerApiCall(query),
      } as OdataServiceApi
    };
  }
}

getCustomerApiCall(query: string) {
  let finalQuery = query;
  // in your case, find the boolean value from the column and modify query

  // your logic to modify the query string
  // untested code, but it would probably look similar
  if (query.includes('LockoutEndDateUtc%20eq%20true')) {
    // calculate new date and replace boolean with new date
    finalQuery = query.replace('LockoutEndDateUtc%20eq%20true', 'LockoutEndDateUtc%20le%202022-06-28T12%3A59%3A25Z');
  }
  return finalQuery;
}

Another possible solution but requires a bit more work.
If I'd be using a regular grid, without backend service and without access to the query string, I would probably add an external drop down outside of the grid and also add the date column and then control filters in the grid by using dynamic filtering. You can see a demo at Example 23, the principle is that you keep the column's real nature (date in your case) and filter it, if you want something like a "below today's date" then add an external way of filtering dynamically (a button or a drop down) and control the filter dynamically as shown below (from Example 23)
Comment: it is unless you use an older version of Aurelia-Slickgrid, the code is all in [Example 23](https://github.com/ghiscoding/aurelia-slickgrid/blob/master/src/examples/slickgrid/example23.ts), also note that I added a "code" link in every Examples at the top right corner to make it easier to look at the associated code. Also remember that `aureliaGrid` is async, you need to use the event to wait for it to be available or use `instances.bind="aureliaGrid"` like in Example23
Comment: that is indeed very old and most probably none of the thing I mentioned (except modifying the query string) would work with that version, you should think about upgrading eventually since I don't support older version.
Comment: If I remember correctly 3.x exports as ES2015 and 4.x as ES2018 as for the other difference well you're just missing out on new features like Composite Editor (Example 30), internally I moved 90% of the internal code to an external lib Slickgrid-Universal so I could reused code in Angular-Slickgrid/Aurelia-Slickgrid and made some pieces optional (OData/GraphQL) so it's smaller builds... Anyway, I added full migration guides for all major versions, see [Migration 3.x](https://github.com/ghiscoding/aurelia-slickgrid/wiki/Migration-to-3.x), the upgrade to 3.x is bigger than to 4.x
Comment: I used the first solution, so added into the inhouse module we have which is based on aurelia-slickgrid. Yes, i understand that this is not the best solution, especially when more than one team use the same module. In your second solution. How do i access the `this.aureliaGrid.filterService.updateFilters(filters);` . Because `aureliaGrid.filterService` is not accessible from outside.
Comment: I am on "aurelia-slickgrid": "^2.18.2", But thanks, I will check it.
Comment: Is 2.23.1 ok to use? I can try to jump to 3.12.1 but i have a feeling that other things might break.


Different iterator for for loop in one code

Question: I am creating function, which takes a vector of operators( different matrices). Operators can be provided in different ordering ( from the smallest to biggest or other way around).
I need to create for loop based on ordering
for(auto tr = operators.begin(); tr != operators.end() ; ++tr )

or
 for(auto tr = operators.end(); tr != operators.begin() ; --tr )

content inside of loop stays same
is there any way how to do this automatically? maybe based on some help input parameter?
Comment: In the second example, don't you mean `rbegin()` and `rend()` instead of `end()` and `begin()`?
Answer: You can support this by having your function consume a pair of iterators (a "range") instead of a complete matrix or vector.  For example:
template <typename Iterator>
void print(Iterator begin, Iterator end) {
    for(auto tr = begin; tr != end; ++tr)
        ; // ...
}

This way, you can pass any sort of range in: forward, reverse, or others.  This is how much of the STL is designed.
If you use a std::vector for example, you'd invoke the above like so:
std::vector<int> vec;
print(vec.begin(), vec.end()); // forward
print(vec.rbegin(), vec.rend()); // reverse

Answer: Although, technically, an end() iterator can often be decremented and dereferenced safely, you are relying on specific properties that not all iterators are guaranteed to have.
A number of standard containers [some introduced in C++11 do not] have both forward iterators (which iterate through elements in order) and reverse iterators (which iterate over elements in the opposite order).    The counterparts of begin() and end() are rbegin() and rend() respectively.


Monic Factors in $\mathbb Q[x]$ of a Monic $f \in \mathbb Z[x]$ are also in $\mathbb Z[x]$

Question:
The claim is that if $f \in \mathbb Z[x]$ is monic and has a factorization, say $f = pq$ with $p,q \in \mathbb Q[x]$ such that $p, q$ are also monic, then $p, q$ are in $\mathbb Z[x]$.

The text cited Gauss's lemma but I am not seeing how.  Suppose that $R$ is a unique factorization domain, and $F$ its field of quotients; Gauss's lemma says that, if $f \in R[x]$ is primitive, reducibility over $F$ is equivalent to reducibility over $R$.  However, the statement does not say that the factorizations are the same.
The premise that $f$ is monic suggest that the content $c(f) = 1$.  Thus, I attempted a proof by contradiction.  What happens if the factors are not in $\mathbb Z[x]$, but here is the problem.  Since each rational number has infinitely many factors, how do I know what $c(p), c(q)$ equal to?
Comment: I think that if you go through the proof of Gauss' Lemma, you'll see why the alleged factorization over the rationals is in fact a factorization over the integers.
Answer: Assume that a polynomial $f\in \mathbf{Z}[x]$ that does not factor in ${\bf{Z}}[x]$ has a proper factorization $f=gh$ in ${\bf{Q}}[x]$. Then multiplying both sides of $f=gh$ by the product of the least common multiples of the denominators of the coefficients of $g$ and $h$ for example gives us a positive integer $n$ such that $nf=g_1h_1$ where $g_1$ and $h_1$ are both in ${\bf{Z}}[x]$. Let $n_0$ be the smallest positive integer such that ${n_0}f=g_1h_1$, where $g_1$ and $h_1$ are both in ${\bf{Z}}[x].$ If $n_0 =1$, there is nothing to prove. So assume that $n_0 > 1$ and let $p$ be a prime divisor of $n_0$. We contend that either $p$ divides ${\it every}$ coefficient of $g_1$, or that $p$ divides ${\it every}$ coefficient of $h_1$. Assume that this is not so, and for $g_1(x)={{\sum}^{m}_{i=0}}{a_i}x^i$, and $h_1(x)={{\sum}^{n}_{i=0}}{b_i}x^i,$ let $k$ be the smallest positive integer for which $p$ does not divide $a_k$, and $l$ be the smallest positive integer for which $p$ does not divide $b_l$. Then since $p$ divides $n_0f$, if must divide the coefficient $${{\sum}^{k}_{i=0}}{a_i}{b_{(k+l)-i}}.$$ This forces us to conclude that $p$ divides ${a_k}{b_l}$ which is impossible since $p$ is a prime and since $p$ does nor divide both $a_k$ and $b_l$. So, we have factorization $({n_0}/p)f={g'_1}{h'_1}$ where $g'_1$ and $h'_1$ are both in ${\bf{Z}}[x]$. This in turn contradicts our choice of $n_0$ as being the smallest positive integer for which a factorization as above is possible. Thus the factorization $f=gh$ was a factorization in ${\bf{Z}}[x]$ to begin with, and so a factorization of an irreducible polynomial $f(x)\in{{\bf{Z}}[x]}$ is not possible in ${\bf{Q}}[x].$ This argument applies to monic polynomials as well.
Comment: We can replace $\bf Z$, and $\bf Q$ by an arbitrary unique factorization domain $R$ and its field of fractions $k$. Instead of relying on the well ordering axiom, we can simply divide out all the prime divisors of $n_0$ in the above argument to get a factorization $f = gh$ in $R[x]$ after a finite number of steps.


devenv Start Debugging is greyed out, and run says Attach

Question: So I use 4coder, which doesn't come with its own debugger. I compile via a batch file and
I'm trying to use devenv which visual studio provides, to debug. However, like the title says, Start Debugging is greyed out, and run says Attach. I'm following the Handmade Hero tutorial and he's able to debug just fine.
I'm guessing it has no way of knowing I'm using C++, so how do I tell it?
These aren't the problem, but I thought I'd at least give some context on how I'm calling it.
Here's my batch files:

d:\Handmade\misc\env.bat
@echo off
call "C:\Program Files\Microsoft Visual Studio\2022\Preview\Common7\Tools\VsDevCmd.bat" -arch=x64 -host_arch=x64 -no_logo
set path=d:\Handmade\misc;%path%

d:\Handmade\misc\debug.bat
@echo off
devenv d:\Handmade\code\%1%

CommandLine
D:\>debug main.cpp

Answer: Okay so I found it out myself. If I target the built exe, and pass the project folder as the second parameter, it works.
@echo off
devenv d:\Handmade\build\main.exe d:\Handmade\code\%1%


Tkinter Python: Bar Gauge?

Question: I am trying to find an effective way to create a bar gauge in Tkinter. I've been using labels inside a frame and changing the background color to indicate the level, but this is extremely inefficient as it involves ten if statements, each with ten lines of code, for each gauge. Would anyone be kind enough to point me in the right direction for how to do this?
Thanks in advance.
Comment: Its unclear what you are asking for but it sounds like a for loop and some functions would work better
Answer: from the sounds of it you are simple after a progressbar, there are two such widgets in tkinter, one is part of ttk and the other is tix, they function much the same but the styling is different, and both of them can be linked to an IntVar and simply setting the value of the IntVar sets the progressbar.
1) ttk.Progressbar
see here
2) tix.Meter
see here
Comment: Thank you for the suggestion but the Progressbar does not really have the functionality that I was look for. I actually went with @Joran Beasley's suggestion and used for loops to change the appropriate labels to the appropriate color. Thanks...

Tkinter Python: Bar Gauge?


Usable frameworks for MySQL, PHP, HTML, JS

Question: For some years I used to code on PHP, MySQL and JS. And recently I opened for my self Twitter Bootstrap, and ready-to-use HTML templates. I feel that there are many other frameworks which can be usable for me.
There are something like 'Fundation" (I did not understand what it is), HTML5 boilerplate...
Could you point me into the usable names?
Comment: Do you want frontend frameworks (HTML, JS, CSS) or backend frameworks (MySQL, PHP). What do you want to build? There is a huge amount of frameworks and they span over a vast variety of needs.
Comment: Hi, @Merguez I need for both. Is there any article gathering them and explaining main points of those?
Comment: I still need to know, what you are trying to achieve. Do you want to build a webapplication (which calls for a mature JS MVC framework) or a more backend oriented "normal" website with some kind of self-build CMS?
Comment: @Merguez, I have to depend on the technologies available for the moment. I see that my question is too general to have any usable answer?
Answer: Let's try:

http://www.phpframeworks.com/ Check this for some common PHP Frameworks
http://todomvc.com/ Check this for some common JS MVC Frameworks
Choosing the right front-end framework

Search deeper in Stackoverflow for more specific discussions about the topics. There are plenty of questions about choosing the right framework for your needs and things like that.
Every framework has its own pros and cons. Fitting them all into one post is impossible and answers are there to be found in the www.
A note to MySQL: There are no specific MySQL frameworks I know of, but what i think you meant was an abstraction for your requests to the database. This abstraction layer is already included in most PHP frameworks mentioned above (if not in all).
Hope this helps you.
Comment: Thank you, for such detailed answer and the links you've provided. Looks like you've got my intention.


Xtk : Can't display label map

Question: I slightly changed demo #11 to load my images instead of the demo's.
I can load my MRI image just fine, see Demo. It also works if I load my label map as the main volume.
window.onload = function() {
    // create and initialize a 3D renderer
    var r = new X.renderer3D();
    r.init();

    // create a X.volume
    var volume = new X.volume();

    // Attach the single-file dicom in .NRRD format
    // this works with gzip/gz/raw encoded NRRD files but XTK also supports other
    // formats like MGH/MGZ
    volume.file = '1123_N3.nii.gz';

    // we also attach a label map to show segmentations on a slice-by-slice base
    // volume.labelmap.file = '1123_seg.nii.gz';

    // add the volume
    r.add(volume);

    // the onShowtime method gets executed after all files were fully loaded and just before the first rendering attempt
    r.onShowtime = function() {
        //
        // The GUI panel
        //
        // (we need to create this during onShowtime(..) since we do not know the
        // volume dimensions before the loading was completed)
        var gui = new dat.GUI();

        // the following configures the gui for interacting with the X.volume
        var volumegui = gui.addFolder('Volume');

        // now we can configure controllers which switch between slicing and volume rendering
        var vrController = volumegui.add(volume, 'volumeRendering');

        // configure the volume rendering opacity
        var opacityController = volumegui.add(volume, 'opacity', 0, 1).listen();

        // and the threshold in the min..max range
        var lowerThresholdController = volumegui.add(volume, 'lowerThreshold', volume.min, volume.max);
        var upperThresholdController = volumegui.add(volume, 'upperThreshold', volume.min, volume.max);

        // the indexX,Y,Z are the currently displayed slice indices in the range [0 - (dimensions-1)]
        var sliceXController = volumegui.add(volume, 'indexX', 0, volume.range[0] - 1);
        var sliceYController = volumegui.add(volume, 'indexY', 0, volume.range[1] - 1);
        var sliceZController = volumegui.add(volume, 'indexZ', 0, volume.range[2] - 1);
        volumegui.open();

        // and this configures the gui for interacting with the label map overlay
        var labelmapgui = gui.addFolder('Label Map');
        var labelMapVisibleController = labelmapgui.add(volume.labelmap, 'visible');
        var labelMapOpacityController = labelmapgui.add(volume.labelmap, 'opacity', 0, 1);
        labelmapgui.open();

    };

    // adjust the camera position a little bit, just for visualization purposes
    r.camera.position = [120, 80, 160];

    // showtime! this triggers the loading of the volume and executes r.onShowtime() once done
    r.render();
};

However if I add the label map to my volume, volume.labelmap.file = '1123_seg.nii.gz';, the loading fails and the volume never shows, see Broken Demo. The only error in the console is the following:

TypeError: b.e.c[0].c[Math.floor(...)] is undefined

Any idea as to what might be wrong? How am I supposed to debug such errors?
Comment: I get the error: `Uncaught TypeError: Cannot read property 'C' of undefined` in the console.
Comment: I get the same as @ReCaptcha
Comment: Have you tested this with any other files? I'm playing around with this stuff as well at the moment, and some files just don't seem to load while others load perfectly fine. Haven't figured out a pattern unfortunately...
Comment: The links you have given don't work for me (pages never load)
Comment: @Fresh : demo.html works, but you need to be patient because you're downloading a 3D volume from my server. On my computer it loads in about ten seconds, but if you live far away I suppose it can take longer.
Comment: @Fresh what browser do you use? I've only tested with firefox.
Comment: @DavidBasalla : can you confirm that demo.html works for you? Let me know if you find anything useful!
Comment: @static_rtti I've only tried loading "Broken Demo" using Chrome.
Comment: yup, demo.html works fine for me, I'm on Ubuntu and Firefox
Comment: hmm... I've come across the same problem now. I'm basing my tests on Xtk Lesson 13. When I use the same files as in the tutorial, everything loads fine. However when I specify my own custom file as volume.file but still use the same label map and color table as from the tutorial, I get the same error (TypeError: b.e.c[0].c[Math.floor(...)] is undefined). So maybe it has something to do with a mismatch between volume.file and volume.labelmap.file?
Comment: @DavidBasalla : the mismatch theory makes sense, but my files are supposed to match...
Comment: Mmm yeah, unfortunately I'm only guessing at this point. I'm actually going to work on this (ie using custom files and label maps) over the next couple of weeks, so will let you know if I find anything else
Comment: @DavidBasalla : Thanks! Any additional info would be great.
Answer: Javascript libraries like this are usually minified for production ready versions. It's nearly impossible to debug minified javascript code, but you can see one of the method names in the callstack is .parse, which indicates right away that it's having an issue parsing your labelmap file.
Most javascript libraries will also include a -debug version that is not minified. I can't seem to find one for xtk, but here's the process for creating a debug version for yourself:

Clone the latest xtk project:
git clone https://github.com/xtk/X.git
Update google closure (the source is not included):
cd X/lib/
git clone https://github.com/google/closure-library
mv closure-library google-closure-library
I created a demo.html file in the X directory, but you can probably put it anywhere and set it up like:

Now you can debug, and you should see your error:
Uncaught TypeError: Cannot read property '_texture' of undefined parser.js:1205
X.parser.reslice parser.js:1205
X.parserNII.parse parserNII.js:258
(anonymous function)

From here you should be able to hunt down your issue.  Looks like a texture is missing.

Xtk : Can't display label map


how to set page icon to Jfilechooser dialog

Question: i am going to create an applet jar which has a JFileChooser open dialog. and i want to change its icon.
frame = parentFrame;
ImageIcon icon = new ImageIcon("com/biztree/docmntui/client/applet/favicon.gif");
frame.setIconImage(icon.getImage());

and then
int returnVal = fileChooser.showOpenDialog(frame);

it works fine when i run it as applet.
but when i trying to run it in GWT web page its shows java default icon.
Answer: new ImageIcon("com/biztree/docmntui/client/applet/favicon.gif");

The String based constructor for an ImageIcon interprets the string as a File path.  I doubt that would work with GWT.  It is probably expecting to deal with the resource by URL.  To get an URL, do something like:
URL favIconUrl =
    this.getResource("com/biztree/docmntui/client/applet/favicon.gif");

Use the URL instead of the String in the ImageIcon constructor.


Identificar vários números numa variável

Question:
Crie um programa que dado um conjunto de temperaturas de 8 cidades portuguesas, identificadas por um  n.º de ordem, indique  quais  as  que  têm  temperatura  superior  à média do país.

O meu problema está em identificar essas cidades através do seu número...
É possível identificar esse número de ordem através de uma só variável?
Por exemplo, a pessoa escreve o nº de ordem (que corresponde a uma cidade)
e no ecrã aparece os números de ordem se a temperatura da cidade for mais alta que a media do pais.
Só tenho isto
//var
float temperatura;
int nordem,i;

//codigo
for(i=1;i<=8;i++)
{
    cout<<"Introduza o nº de ordem: ";
    cin>>nordem;

    cout<<"Introduza a temperatura dessa cidade: ";
    cin>>temperatura;

        if(temperatura>16){
        nordem
    }

}cout<<"As seguintes cidades estão acima da média: "<<nordem<<"\n";

system("pause");

}
Answer: Array
Não é possível guardar vários valores em uma variável escalar como deseja. É possível guardar em uma variável multi valorada. Um vetor é o tipo mais óbvio para fazer isso. Um vetor pode ser guardado em uma só variável, mas só pode guardar vários valores nele porque ele é composto por várias variáveis.
E sim, cada elemento do vetor é um variável individual. Então não há a menor chance de guardar tudo em uma só a não ser com algum truque possível se tiver algumas restrições.
Se optar por um vetor basta adicionar o número de ordem sempre que atender a condição e depois navegue pelo vetor em um laço posterior.
Booleano
Na verdade pode fazer um vetor com um elemento para cada cidade, aí só guarda se a cidade atende o filtro ou não. Ou seja é uma operação booleana.
Aí dá para usar um truque e até usar uma variável. Se você garante que terá no máximo 8 cidades pode criar uma variável do tipo char (com um unsigned int é possível até 32 cidades, na maioria das arquiteturas). Aí você guarda se a cidade atende ao critério apenas com um bit.
Então a posição do bit é a posição do índice do que seria seu vetor e o bit ali indica se aquela cidade tem temperatura acima da média ou não.
Claro que isso só funciona se as cidades tiverem o número de ordem em sequência, de preferência de 0 a 7, mas dá para fazer mesmo começando de um número maior. Também seria possível se puder normalizar para uma sequência através da matemática.
Teria que usar o operador de bit para gerar os bits nos lugares corretos.
String
Ainda tem a opção de fazer uma string com todos os valores separados por algum caractere ou com tamanho fixo. Tecnicamente ainda é só um valor, mas você dará uma semântica para esse valor que se comportará como se fossem vários. Acho gambiarra demais e principalmente nesse caso não vejo necessidade.


Partial sum of ${A \choose i} {B\choose n-i}$, when $B=-1$?

Question: It's easy to see that
$$ \sum_i {A\choose i} {B\choose n-i} = {A+B\choose n} $$
since when we choose $n$ things out of $A+B$, some ($i$ of them) are in the $A$ and the rest are in the $B$.

Is there any reasonable formula for
$$ \sum_{i< I} {A\choose i} {B\choose n-i} = {A+B\choose n}, $$
i.e. we have a bound on how many of them are from the $A$ side?
Is the $B=1$ case any easier? (That being my real question.)

EDIT: I totally misasked this question, and have hopefully fixed it here: Partial sum over $M$, of ${m+j \choose M} {1-M \choose m+i-M}$?
Comment: For $B=1$, maybe you want to take a look at [Pascal's rule](http://en.wikipedia.org/wiki/Pascal%27s_rule).
Comment: Did you mean $B=1$ in the title?
Comment: The formula holds for all integer $i$. (According to Knuth in *Concrete Mathematics*)
Comment: In the first question, you didn't mean to include the right-hand side, did you?
Answer: For B=1 this is rather easy:
${1 \choose j}$ is $1$ if $j$ is $0$ or $1$, and is $0$ for any other value of $j$.  So your first expression becomes $ {A\choose n-1} {1\choose 1} + {A\choose n} {1\choose 0} = {A+1 \choose n} $
or as Fabian says, Pascal's rule
$$ {A\choose n-1} + {A\choose n} = {A+1 \choose n}. $$
Your second expression depends on $I$.  If $I \le n-1$ then it gives a sum of 0; if $I = n$ and $i \lt I$ it give a sum of  ${A\choose n-1}$, and if $I \gt n$ it gives a sum of ${A+1 \choose n}$.


Rails 5.2.3 to 6.0.0 upgrade dependency hell

Question: I ran bundle update rails to update my app to 6.0, and got this very confusing output. Updating these gems in the gemfile does not have any impact. I can't make heads or tails of this error, and it feels like a catch 22. This is the output:
Bundler could not find compatible versions for gem "actionpack":
In Gemfile:
activerecord-session_store (~> 1.1, >= 1.1.3) was resolved to 1.1.3, which depends on
  actionpack (>= 4.0)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  formtastic (~> 3.1) was resolved to 3.1.5, which depends on
    actionpack (>= 3.2.13)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  inherited_resources (>= 1.9.0) was resolved to 1.11.0, which depends on
    has_scope (~> 0.6) was resolved to 0.7.2, which depends on
      actionpack (>= 4.1)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  inherited_resources (>= 1.9.0) was resolved to 1.11.0, which depends on
    actionpack (>= 5.0, < 6.1)

rails (= 6.0.0) was resolved to 6.0.0, which depends on
  actionpack (= 6.0.0)

devise (~> 4.2) was resolved to 4.7.1, which depends on
  responders was resolved to 3.0.0, which depends on
    actionpack (>= 5.0)

Bundler could not find compatible versions for gem "activemodel":
In Gemfile:
carrierwave (~> 2.0, >= 2.0.2) was resolved to 2.0.2, which depends on
  activemodel (>= 5.0.0)

rails (= 6.0.0) was resolved to 6.0.0, which depends on
  activemodel (= 6.0.0)

Bundler could not find compatible versions for gem "activerecord":
In Gemfile:
activerecord-session_store (~> 1.1, >= 1.1.3) was resolved to 1.1.3, which depends on
  activerecord (>= 4.0)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  kaminari (>= 0.15) was resolved to 1.1.1, which depends on
    kaminari-activerecord (= 1.1.1) was resolved to 1.1.1, which depends on
      activerecord

rails (= 6.0.0) was resolved to 6.0.0, which depends on
  activerecord (= 6.0.0)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  ransack (>= 1.8.7) was resolved to 2.3.0, which depends on
    activerecord (>= 5.0)

Bundler could not find compatible versions for gem "activesupport":
In Gemfile:
bullet (~> 6.1) was resolved to 6.1.0, which depends on
  activesupport (>= 3.0.0)

carrierwave (~> 2.0, >= 2.0.2) was resolved to 2.0.2, which depends on
  activesupport (>= 5.0.0)

jbuilder (~> 2.0) was resolved to 2.9.1, which depends on
  activesupport (>= 4.2.0)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  kaminari (>= 0.15) was resolved to 1.1.1, which depends on
    activesupport (>= 4.1.0)

rails (= 6.0.0) was resolved to 6.0.0, which depends on
  activesupport (= 6.0.0)

stripe_event (~> 2.3) was resolved to 2.3.0, which depends on
  activesupport (>= 3.1)

Bundler could not find compatible versions for gem "rails":
In Gemfile:
rails (= 6.0.0)

invisible_captcha (~> 1.0) was resolved to 1.0.0, which depends on
  rails (>= 4.2)

mini_backtrace (= 0.1.3) was resolved to 0.1.3, which depends on
  rails (>= 2.3.3)

Bundler could not find compatible versions for gem "railties":
In Gemfile:
activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  railties (>= 4.2, < 5.3)

activerecord-session_store (~> 1.1, >= 1.1.3) was resolved to 1.1.3, which depends on
  railties (>= 4.0)

devise (~> 4.2) was resolved to 4.7.1, which depends on
  railties (>= 4.1.0)

factory_bot_rails (~> 4.8, >= 4.8.2) was resolved to 4.11.1, which depends on
  railties (>= 3.0.0)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  inherited_resources (>= 1.9.0) was resolved to 1.11.0, which depends on
    railties (>= 5.0, < 6.1)

activeadmin (~> 1.4.3) was resolved to 1.4.3, which depends on
  jquery-rails (>= 4.2.0) was resolved to 4.3.5, which depends on
    railties (>= 4.2.0)

rails (= 6.0.0) was resolved to 6.0.0, which depends on
  railties (= 6.0.0)

sass-rails (~> 5.0.6) was resolved to 5.0.7, which depends on
  railties (>= 4.0.0, < 6)

web-console (~> 3.0) was resolved to 3.7.0, which depends on
  railties (>= 5.0)

My Gemfile looks like this:
source 'https://rubygems.org'
ruby '2.5.0'

gem 'rails', '6.0.0'
gem 'pg', '~> 0.18.3'
gem 'iodine', '~> 0.7.38'
gem 'sass-rails', '~> 5.0.6'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails'
gem 'therubyracer', '~> 0.12.3'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'figaro', '~> 1.1', '>= 1.1.1'
gem 'less-rails', '~> 4.0.0'
gem 'autoprefixer-rails'
gem 'devise', '~> 4.2'
gem 'mini_magick', '~> 4.5', '>= 4.5.1'
gem 'carrierwave', '~> 2.0', '>= 2.0.2'
gem 'fog-aws', '~> 3.5', '>= 3.5.2'
gem 'aws-sdk', '~> 2'
gem 'activeadmin', '~> 1.4.3'
gem 'friendly_id', '~> 5.1'
gem 'pagy', '~> 3.7', '>= 3.7.2'
gem 'activerecord-session_store', '~> 1.1', '>= 1.1.3'
gem 'sprockets', '3.7.2'
gem 'aasm', '~> 5.0'
gem 'redis', '~> 4.1', '>= 4.1.3'
gem 'sidekiq', '~> 6.0', '>= 6.0.4'
gem 'local_time', '~> 2.1'
gem 'stripe', '~> 5.11'
gem 'stripe_event', '~> 2.3'
gem 'lockbox', '~> 0.2.4'
gem 'mailgunner', '~> 2.4'
gem 'rack-attack'
gem 'invisible_captcha', '~> 1.0'

group :development do
  gem 'web-console', '~> 3.0'
  gem 'letter_opener', '~> 1.7'
  gem 'bullet', '~> 6.1'
end

group :development, :test do
  gem 'byebug'
  gem 'spring'
  gem 'spring-commands-rspec'
  gem 'factory_bot_rails', '~> 4.8', '>= 4.8.2'
  gem 'faker', '~> 1.6', '>= 1.6.6'
  gem 'minitest', '~> 5.8', '>= 5.8.4'
end

group :test do
  gem 'minitest-reporters', '1.0.5'
  gem 'mini_backtrace',     '0.1.3'
  gem 'guard-minitest',     '2.3.1'
  gem 'database_cleaner', '~> 1.7'
end

group :production do
  gem 'newrelic_rpm'
end

What does the error mean? Where do I start? Do I do bundle update first, and then bundle update rails? Or vice versa? This is like battling a hydra.
Comment: `actionmailer` is part of Rails. Your version of ActiveAdmin depends on `actionpack (>= 5.0, < 6.1)` so you can start by upgrading ActiveAdmin.
Comment: This process can be a nightmare, worse than a hydra because fire doesn't help. I'd start by bumping the Ruby version to 2.6.6+.  Then drop all the `~>` version requirements, the only versions you probably need to keep are the Ruby and Rails ones. That will tell bundler to use the latest versions of everything, this might break a bunch of things but it should get you past the initial `bundle` call. You'll also want to review all the upgrade guides for everything and I hope your test suite is good.
Comment: I've recently found myself in a very similar position trying rails 4 to 5. Any tips?
Comment: i just updated my op. i'm confused, though. if i have my rails gem at `6.0.0` and try to update `activerecord-session_store`, i get an error that says rails is locked at `5.2.3`. if i leave the rails gem at `5.2.3` and try to update `activerecord-session_store`, i get `Bundler attempted to update activerecord-session_store but its version stayed the same`. this feels like a catch 22 or something?
Comment: @muistooshort sorry to bother you again, but i'm confused by your message. this is like a catch 22. which part of this error do i start with first? i can't make heads or tails of it.
Answer: I managed to get past this error by adding the following to my Gemfile
gem 'sassc', '~> 2.1.0'

After that, running bundle install returned this:
You have requested:
  sassc ~> 2.1.0

The bundle currently has sassc locked at 2.4.0.
Try running `bundle update sassc`

...so I ran bundle update sassc and then bundle install. Everything seems to have updated normally, so far at least.
This is apparently a known issue with sassc, mentioned here and here.
However, my bundler was getting stuck on the sassc update. Hopefully someone else can provide more insight on the other gems


How to prove $G$ is Eulerian

Question: We know that a Eulerian graph has vertices all are even. But how can we prove the sufficiency of it i.e. if a connected graph $G$ has vertices all are even, then how can we prove the graph $G$ is Eulerian.
Comment: Find a cycle in $G$ and remove it and use induction the components of the remaining graph, then put things together to construct an eulerian trails.
Comment: Also connectivity is required.
Answer: HBM's comment here is exactly to the point.  I will elaborate on it.
First observe that if we pick any vertex $g\in G$, and then follow any path from $g$, marking each edge as it is used, until we reach a vertex with no unmarked edges, we must be at $g$ again. For let $\def\I#1{\operatorname{in}(#1)}\I x$ by the number of times the path enters vertex $x$ and $\def\O#1{\operatorname{out}(#1)}\O x$ be the number of times the path leaves $x$ again. If we end at some vertex $h\ne g$, we have $\I h = \O h + 1$.  But each entry and each exit marks one edge incident to $h$. So $\I h + \O h = 2\cdot\I h -1$ of $h$'s edges are marked.  But $2\cdot\I h -1$ is odd and by hypothesis $h$ has even degree.  So there is still an unmarked edge incident to $h$, contradicting our hypothesis that $h$ has no unmarked edges.  On the other hand, if we end at $g$, then we have $\I g = \O g$ and there is no contradiction.  So it is easy to find a cycle in $G$: pick any vertex $g$ and go from vertex to vertex until you finish again at $g$; you cannot get stuck.
Having found this cycle $C$, there are either no unmarked edges, in which case $C$ is itself an Eulerian cycle of $G$, or else there is some vertex $v$ of $C$ which is incident to an unmarked edge.  (If there are unmarked edges, but none incident to vertices of $C$, then $G$ must be disconnected.) Then we can find another cycle $C'$ of $G$, containing only unmarked edges, starting and ending at $v$, the same way that we found $C$ itself.  Then we can merge $C$ and $C'$ into a single cycle as follows:
Say that $C$ was $g-g_1-g_2-\cdots-v-g_k-\cdots -g_n-g$
and $C'$ was $v-h_1-\cdots-h_n-v$. Then we can merge $C$ and $C'$ into the single cycle $g-g_1-g_2-\cdots-v-h_1-\cdots -h_n-v-g_k-\cdots-g_n-g$.
In this way we can repeatedly find a new cycle and then merge it into the older one, until there are no unmarked edges remaining.  At that point we have a single cycle that traverses all the edges of $G$, and we are finished.

How to prove $G$ is Eulerian


Sort nodes by latest comments on it

Question: I am using D7. I want to sort the nodes by the comment post date on it.
Like
Node a created on Jan 03
Node b Created on Jan 05
Normally i can sort it either asc or desc.
What i want is a node with latest comment will be in top of my views.
I am looking for a views3 solution.
Is it possible ?
Comment: In Drupal almost everything you can think of is possible! The only question remains HOW?
Answer: "Last comment time" is sort.

Then use 'Sort descending'
Comment: How to sort nodes by count of posted comments..  using EQF ?
Answer: Add the comment table in a relationship, "Last comment time" should just show up.
Answer: The first step would be to add the Comments of the node relationship. You can find this under the Comment section in the Relationships block in the Views UI (when the base table of your view is {node}). You will now be able to add the Comment: Post date as a filter and make it sort by desc which should do the trick for you.
Depending on your use-case, you can then consider doing the following:

Making the relationship "required" if you wan't to exclude nodes that don't have comments on them as yet.
Set Use aggregation: Yes if you'd like to just show only the most recent comment of a node and not any other i.e. nodes don't repeat themselves.
Answer: Import this view:
$view = new view;
$view->name = 'newcomments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'newcomments';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'newcomments';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['hide_empty'] = 0;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: Content: Updated/commented date */
$handler->display->display_options['fields']['last_updated']['id'] = 'last_updated';
$handler->display->display_options['fields']['last_updated']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['last_updated']['field'] = 'last_updated';
$handler->display->display_options['fields']['last_updated']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['external'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['trim'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['last_updated']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['last_updated']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['html'] = 0;
$handler->display->display_options['fields']['last_updated']['element_label_colon'] = 1;
$handler->display->display_options['fields']['last_updated']['element_default_classes'] = 1;
$handler->display->display_options['fields']['last_updated']['hide_empty'] = 0;
$handler->display->display_options['fields']['last_updated']['empty_zero'] = 0;
$handler->display->display_options['fields']['last_updated']['date_format'] = 'long';
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['external'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['trim'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['html'] = 0;
$handler->display->display_options['fields']['comment_count']['element_label_colon'] = 1;
$handler->display->display_options['fields']['comment_count']['element_default_classes'] = 1;
$handler->display->display_options['fields']['comment_count']['hide_empty'] = 0;
$handler->display->display_options['fields']['comment_count']['empty_zero'] = 0;
$handler->display->display_options['fields']['comment_count']['format_plural'] = 0;
/* Sort criterion: Content: Updated/commented date */
$handler->display->display_options['sorts']['last_updated']['id'] = 'last_updated';
$handler->display->display_options['sorts']['last_updated']['table'] = 'node_comment_statistics';
$handler->display->display_options['sorts']['last_updated']['field'] = 'last_updated';
$handler->display->display_options['sorts']['last_updated']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'newcomments';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$translatables['newcomments'] = array(
  t('Master'),
  t('newcomments'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('Updated/commented date'),
  t('Comment count'),
  t('.'),
  t(','),
  t('Page'),
  t('Block'),
);

Sort nodes by latest comments on it


join three tables by SQL and Php

Question: I have these 3  tables in mysql database (also i didn't know it's completely normalized or not?
or is there any better way to design this tables to get this query?)
create table T_Users(
     id int
     name varchar (50)
     picture varchar (11)
);
create table T_Groups(
     id int
     name varchar (50)
     admin_id int
);
create table T_Group_Users(
     u_id int
     g_id int
);

Now I Want to get all of groups that a specified user joined, with all of members of this groups with them detail(name and picture)
And create an array like this by Php (this is an example):
$groups = [ // Groups user by id = 1 joined 'em
        [
            'id' => 1,
            'name' => 'G_1',
            'member' => [
                ['name' => 'R', 'picture'=>''],
                ['name' => 'S', 'picture'=>'14.jpg'],
                ['name' => 'X', 'picture'=>'']
            ]
        ],
        [
            'id' => 5,
            'name' => 'G_3',
            'member' => [
                ['name' => 'T', 'picture'=>'11.jpg'],
                ['name' => 'S', 'picture'=>'14.jpg']
            ]
        ]
    ]

(specified user determined by id, u_id is foreign key T_Users And g_id is foreign key T_Groups)
Comment: @emineminems I don't understand where I should place id ?
this query just return `false`. tables are not empty
Comment: if table are not empty , then it should gives the result with appropriate id.
Comment: @mohit-kumar No the query have  bug in `T_Groups.g_id = T_Groups`
T_Groups haven't g_id
Comment: Typo `ON T_Groups.id = T_Group_Users.g_id`
Answer: If you just want ids, you can do:
select g_id, group_concat(u_id)
from t_group_users gu
group by g_id
having sum(u_id = ?) > 0;

This returns each group on a row with a list of the ids of the users in the group.
If you want the names, you an join in the appropriate tables.
EDIT:
To get the names and other information:
select g.id, g.name,
       group_concat(u.name, ':', u.picture)
from t_group_users gu join
     t_users u
     on gu.u_id = u.id join
     t_groups g
     on gu.g_id = g.id
group by g.id, g.name
having sum(u.name = ?) > 0;

Here ? is for the parameter that has the name.
Comment: `SELECT t_groups.*, member FROM t_groups
        Left JOIN t_group_users ON t_groups.id = t_group_users.g_id where t_group_users.u_id = 1
        (SELECT t_users.* FROM t_users
        Left JOIN t_group_users ON t_group_users.g_id = t_groups.id) AS member` This Not work but i think that i want is something like this....

join three tables by SQL and Php


C# HTTPS Post with certificate

Question: I need help setting up a HTTP Post in C# with Certificate.
I'm receiving an error:
"The underlying connection was closed: An unexpected error occurred on a send'.
Thank you.
The Net framework is 4.5
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = TrustCertificate;
byte[] bytes = new ASCIIEncoding().GetBytes(transaction);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlString);
request.ClientCertificates.Add(new X509Certificate());
request.Method = "POST";
string str = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + pwd));
request.Headers["Authorization"] = "Basic " + str;
request.ContentType = "text/xml";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string str2 = reader.ReadToEnd();
response.Close();
reader.Close();
return str2;

Comment: As you fixed the protocol to TLS 1.2 are you sure the endpoint can handle it?
Comment: i am now receiving this error
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
Comment: i've tried to removed ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; and still receiving same error. i am using vs 2012
Answer: The error can have a few reasons. Here is my list for diagnostics.

Use a browser (that uses the Windows Certificate Store - IE or Chroms) for GET requests, or Fiddler for all other HTTP verbs (POST, ...) to call the endpoint.
Ensure the server certificate is valid (NotBefore & NotAfter) and not revoked. The browser will show errors and provide details.
Check the TLS/SSL version on client and server matches. IISCrypto (the name is confusing) shows the platform configuration (Windows SCHANNEL) on both, client and server. Additionally there is a nice PowerShell script that opens connections with all TLS/SSL versions. If you don't have access to the server  but it is publicly available you an you check what TLS versions are supported by using https://www.ssllabs.com/ssltest/analyze.html
Last but not least ensure the client and the server can negotiate a cipher suite. IISCrypto and https://www.ssllabs.com/ssltest/analyze.html can show the supported cipher suites too.

EDIT
Checking with firefox, the certificate is OK, not self-signed (DigiCert):

Running a get request against the provided URL with TLS 1.2:
try {
  var urlString = "https://www.viewmyrecord.com/";
  ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  var request = (HttpWebRequest) WebRequest.Create(urlString);
  request.ClientCertificates.Add(new X509Certificate());
  request.Method = "GET";

  using (var response = (HttpWebResponse) request.GetResponse()) {
    Console.WriteLine(response.StatusCode);
  }
} catch (Exception ex) {
  Console.ForegroundColor = ConsoleColor.Red;
  Console.WriteLine(ex.ToString());
  Console.ResetColor();
}

Works from here:
Comment: Thank you. I will check it.
Comment: The 3rd party says that they only allow a public certificate authority (CA) and does not accept self-signed certificates. However, when i checked our SSL (www.viewmyrecord.com), it says "Self-signed".
Comment: @MaKristelMirabel What's the current state?
Comment: Hi,
I'm having difficulty connecting to Surecripts' E-Prescription (https://smr-staging.surescripts.net/erx/{PortalName}/{Version}?id=
{MessageID})
I have already installed certificate (p7b file).

Does anyone here knows HTTPS Post with client certificate? or have previous experience with Surescripts Network?

I really need help.
my email address: firstname.lastname@example.com
Comment: The WebRequest has a property that can be set. Look here https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.clientcertificates?view=netframework-4.8
Comment: Hi @Daniel,

Can you help me with this project? Our company is willing to pay. Thank you.
Comment: @MaKristelMirabel Contact my by mail info[at]lennybacon[dot]com
Comment: Thank you. Will email you before the end of the day. :)

C# HTTPS Post with certificate


Change Tracking Structure

Question: We are looking to implement Optimistic locking in our WCF/WPF application. So far the best way I've come up with doing this is to implement a generic Optimistic which will store a copy of the original and any changes (so it will store two copies: the original and modified) of any value object that can be modified. Is this the best way of doing it?
For example: a UserVO will be wrapped by the generic as a Optimistic. When a change is made to the Optimistic, the change will be made to the modified copy stored in the Optimistic while the original also stored in the Optimistic will remain intact. The main issue seems to be that it will use up twice the space and hence bandwidth.
Thanks
EDIT The solution needs to be database independent, and it would be useful to be able to specify an conflict resolution policy per value object. (eg. A user object might try and merge if the updated rows weren't changed, but a transaction object would always require user intervention).
Answer: If you are using SQL server you can use a timestamp column. The timestamp column is changed anytime a row is modified. Essentially when your updating the DB you can check if the timestamp column is the same as when the client first got the data, if so no one has modified the data.
Edit
If you want to minimize the bandwidth, you could emulate the timestamp concept by adding a version number on each object. So for example:

Client 1 requests object, sever returns Object V1
Client 2 requests object, server returns Object v2
Client 1 modifies object sending it back to server as V1
Server compares the version and see's v1=v1 so it commits the change
Server increments the version of the object so now its v2
Client 2 modifis object sending it back to server as v1
Server compares the version and see's v1!=v2 so it performs whatever your policy is

For configuring your policy, you could define in a configuration a specific object that will handle Policy failures depending on the type of root object. You could whip up a IOptomisticCheckFailurePolicy interface, and you could probally use one of the DI libraries like structure map to create the object when you need it (Although you could just as easily load it up using reflection)
Answer: One way of implementing optimistic locking logic is to base it on a last modified timestamp of a row.  So the update will look as follows:
UPDATE .... WHERE id = x AND last_updated = t
x: record id.
t: the last updated timestamp of the row when it was loaded from the database (i.e. before modifications).
Note that one of the fields that must be updated directly or indirectly is the timestamp to be set to now (or UtcNow).
This way the update will fail in case the record was modified in the background.  Once the update failed, you can issue further queries to detect the cause of the failure.  For example,

Record has been deleted.
Record has been modified.

This simple approach provides row level optimistic locking, it is not column based and has no conflict resolution.
Comment: if your using MS SQL use a timestamp column it automaticly changes the timestamp when the row is modified.
Comment: My answer is DBMS agnostic.  So you either use some feature in the underlying DBMS to update the timestamp or do it yourself.  No disagreement there :)
Answer: Have you looked at the Microsoft Sync Framework?

Change Tracking Structure


How do I get verbose messages to appear in the output of Start-Transcript?

Question: When using Start-Transcript verbose output is not captured in the transcript. For example:
Start-Transcript
Write-Verbose "This is a test of verbose output"
Stop-Transcript

Results in:
**********************
Windows PowerShell transcript start
Start time: 20170829110436
Username: xx\xx
RunAs User: xx\xx
Machine: SGC340 (Microsoft Windows NT 6.1.7601 Service Pack 1)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 19596
PSVersion: 5.0.10586.117
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0.10586.117
BuildVersion: 10.0.10586.117
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 220.127.116.11
**********************
Transcript started, output file is C:\Users\xx\Documents\PowerShell_transcript.xx.EbGyj9PE.20170829110436.txt
PS C:\Users\xx> Write-Verbose "This is a test of verbose output"
PS C:\Users\xx> Stop-Transcript
**********************
Windows PowerShell transcript end
End time: 20170829110447
**********************

How do you capture Verbose output in a transcript?
Answer: As discussed in this issue, verbose output does not appear because the default setting of $VerbosePreference is 'SilentlyContinue'. If you change it to 'Continue' verbose output appears.
Equally if you had a script that made use of Start-Transcript, you could add [cmdletbinding()] to the top of your script and then execute it with the -Verbose switch to have Verbose messages both visible and in the transcript.
Note that running Start-Transcript -Verbose does not enable the logging of Verbose messages in the transcript (it just enables the Verbose output of the cmdlet itself).
Comment: Setting `$VerbosePreference` to `SilentlyContinue` will also enable the output to the terminal. Is there a way to only get the messages appear in the transcript, but still hide them in the terminal?
Comment: I don't think that would be possible via `Start-Transcript` as it just captures whatever output appears in a session.


Groovy: Find duplicates in Multiple arrays

Question: I have three arrays as below and need to find the maching/duplicate in all of these
`def Ids_AS =[04-04350, 21-005676, REGU-132644681]
def Ids_AO= [ 04-04350, 04-04356, REGU-132644681]
def Ids_AV= [ 04-04350, AB-132644681, REGU-132644681]`
println(IdsResultMissingOnSolrOutPut_AS.intersect(IdsResultMissingOnSolrOutPut_AV))

I used intersect but it is getting applies on 2 arrays/list only
Another Case: Need to handle empty array like below and it should match the rest of remaining instead of returning null or error
`def Ids_AS =[04-04350, 21-005676, REGU-132644681]
def Ids_AO= [ 04-04350, 04-04356, REGU-132644681]
def Ids_AV= []`

is there way to find duplicates on multiple arrays? Please help
Answer: Just do the intersection for the third array
def duplicates = Ids_AS.intersect(Ids_AO).intersect(Ids_AV)

If you want to get clever, and you have many, you can make a list of your lists, and then use inject (fold) to intersect them all against each other
def all = [Ids_AS, Ids_AO, Ids_AV]

def duplicates = all.inject { a, b -> a.intersect(b) }

Both methods will result in
['04-04350', 'REGU-132644681']

For the second question, sort the list of lists so the longest one is first, and then ignore empty lists
def duplicates = all.sort { -it.size() }.inject { a, b -> b.empty ? a : a.intersect(b) }

Comment: Bundle of thanks, This worked for me


Linux LVM: Expanding vg to match "expanded" physical disk

Question: I have a volume group that was created out of a 30Gb drive and a logical volume inside it with an ext3 filesystem.
Now the disk has magically "grown" another 30Gb to 60Gb (that is, I changed the physical device attached to the virtual machine...). Parted recognized the change and asked to fix itself (which I did).
How do I make the volume group expand (or "fix" itself) to match the new 60Gb drive?
Answer: Rather than creating a new partition you could have also changed the partition size in the partition table to match the new size and then run pvresize.
Comment: Interesting! I think this is Linux-specific; there is a [man page](http://linux.die.net/man/8/pvresize) for pvresize available online.
Comment: `# pvresize /dev/sdX; lvextend --resizefs -l +100%FREE /dev/my_vg_name/my_lv_name`
Answer: Actually, I think I got the answer on this one. Having come from HP-UX where LVM is native - and there are no partitions, I forgot something: on PC-based systems, LVM considers a partition to be a "physical device", not the entire disk as is natural in HP-UX LVM.
Thus, when the "disk" was expanded from 30Gb to 60Gb, the partition table tool (parted) saw it - and repaired the "damage" nicely.
However, the "physical disk" that LVM used never changed as the partition never changed size. The proper way to expand the filesystem involved was to:

Expand the volume group (using vgextend) to include the new partition.
Expand the logical volume (using lvextend) to encompass the rest of the
space in the new volume group.
Expand the filesystem (in this case, by using resize2fs) to match the new space in
the logical volume.

That did it for me.


drupal module for uploading to s3

Question: originally posted on stackexchange.  Didn't get any replies.  Then I recently found out there's a specific drupal stackexchange so here i am reposting.  TIA!
I have a drupal site and I plan to serve static site files directly from s3 (rewrite). I need to provide a way for the content manager to upload his images directly to s3 from the drupal admin UI so he doesn't have to send it to me to upload via s3cmd or the aws console. Can anyone recommend a module or method for this?
I've tried s3fs however mounting a fuse s3 filesystem and serving from it was painfully slow. If it worked drupal would think the files are all local and i'd be set.
I found this but not sure if it will get the job done for me: https://drupal.org/project/storage_api
I need a module that would allow the drupal admin UI user to graphically browse for a file (image for instance) to upload to the s3 bucket i intend to serve from.
Comment: You shouldn't repost, instead try migrating your previous post if that option is availble.
Comment: I know.. but it's not.  it would be nice if it can be moved but that option isn't there.  Which left me no other option but to post here.  Still no replies though.  I am having some luck with the storage_api.  I was able to get the module installed and the s3 bucket configured.  not much documentation so i have to go by trial and error.  attempting to get files uploaded to s3 via the admin ui and served directly from s3 after.
Comment: I voted that your question on stackexchange would be closed and hopefully it will be migrated to this site instead=)
Answer: storage_api is the right module for seamlessly transferring data such that the user's upload lands first on the servers local filesystem and by rules can have it automatically propagate to any number of containers (S3, Cloud Files etc..)  And even more you can control the priority in which the files are served from the site simply by ordering them in prefered manner.  the URLs will change automatically. pretty slick.
Answer: Here is a good blog post about using S3 as a media storage for Drupal: http://davidcsonka.com/blog/how-use-amazon-s3-store-your-drupal-website-files
Also, you may consider SaaS solutions, such as Filepicker, Cloudinary or Uploadcare. The latter has an open-source module for Drupal integration: https://github.com/uploadcare/uploadcare-drupal
Comment: I think I'm ok with storage_api.  The only problem is with the dynamic files generated by drupal css/js etc.  Currently the only setting i can see for destination of these files is on the localdisk.  There's no way of choosing a storage class instead.

drupal module for uploading to s3


Servlet esta dando erro 404

Question: Estou tentando criar uma aplicação de postagens, começei a estudar agora o Java Web e toda vez que vou executar o servlet no Apache 8 o aparece uma página de erro 404.
meu servlet
 package app.web4.servlets;

 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;

 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import app.web4.model.Post;

 @WebServlet(name="post", urlPatterns="/user/post")
 public class postServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public postServlet()
{

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

    createPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    createPost(request, response);
}

private void createPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String postText = request.getParameter("postText");
    String userName = "";

    if (request.getUserPrincipal() != null) {
        userName = request.getUserPrincipal().getName();
    }

    try {
        Post post = new Post(postText, userName);

        List<Post> posts = (List<Post>) getServletContext().getAttribute("posts");

        if (posts == null) {
            posts = new ArrayList<>();
            posts.add(post);
            getServletContext().setAttribute("posts", posts);
        }else {
            posts.add(post);
            getServletContext().setAttribute("posts", posts);
        }

        request.setAttribute("posts", posts);

        request.getRequestDispatcher("/WEB-INF/view/home.jsp").forward(request, response);

    } catch (Exception e) {
        throw new NumberFormatException("Houve algum erro com o seu post");
    }
}
 }

a chamada que eu faço a ele através do arquivo NewPost.jsp

    <form action="post" method="POST" class="form-inline">
        <input name="postText" type="text"
            class="form-control mb-2 mr-sm-2 mb-sm-0"
            placeholder="What's on your mind?">
        <button type="submit" class="btn btn-primary">Post</button>
    </form>

Testei com servlets mais simples, que só iriam levar para uma página com um " oi", porem da o mesmo erro 404.
Alguma ideia?
Comment: A action deve apontar para o servlet e não `action="post"`
Comment: Quando eu uso o action="post" ele envia para o url correto do servlet, mas apresenta 404. Quando eu vou no eclipse e mando executar o Servlet diretamente, da o mesmo erro.
Answer: A url para a sua Servlet é /user/post.
De acordo com o javadoc do @WebServlet, as propriedades value e urlPatterns que servem pra mapear a URL da Servlet.
O name é apenas o nome da Servlet.

    <form action="/user/post" method="POST" class="form-inline">
        <input name="postText" type="text"
            class="form-control mb-2 mr-sm-2 mb-sm-0"
            placeholder="What's on your mind?">
        <button type="submit" class="btn btn-primary">Post</button>
    </form>

Se você estiver usando JSP na view:
<form action="${pageContext.request.contextPath}/user/post" method="POST" class="form-inline">
    ...
</form>

Comment: Quando faço isso ele envia direto para localhost:8080/user/post e não localhost:8080/TwitterWeb4/user/post.

também falaram para eu tentar "user/post" na chama.da, mas ai me chama um  localhost:8080/user/user/post.
Comment: Eu editei a minha resposta, vê se resolve o seu problema.

Servlet esta dando erro 404


What should my reverse DNS be for my inhouse email server?

Question: So I have an inhouse exchange server for the domain visaustralia.com.
(email addresses are firstname.lastname@example.com)
And when checking the reverse DNS of my static IP address with http://www.whatsmyip.us/reversedns.php I get
vis1247147.lnk.telstra.net

Which is likely from my ISP (telstra).
What do they need to change it to? visaustralia.com? I tried calling them but after a total of 6 hours in the phone with different people and waiting to be transferred, no one could help me and they didnt even seem to understand what I needed.
Do I need to request them to add a PTR record? Or what would be the terminology of what they need to do and to what setting?
Comment: Most ISPs don't really like to do that. It has multiple reasons, mainly relating to their internal administration, and because such ip ranges are for home users. If you want a revdns entry for your server, use their server hosting solutions (which is more costly, of course, but in this case you will be able to reach competent people relatively fast).
Answer: You can contact your ISP (telstra) to set PTR record or Reverse DNS record for your mail server IP address.
PTR Hostname can be any FQDN based on your domain visaustralia.com.
For Example: mail.visaustralia.com
Ideally, you should set PTR record to FQDN you have set at outgoing mail server for domain visaustralia.com
Comment: Well I'm not sure if that is the FQDN or how to check the outgoing mail server, but our online exchange server is remote.visaustralia.com/exchange.
Answer: What's the FQDN on your Send Connector? That's what you should set the PTR record to.
Comment: Well I'm not sure if that is the FQDN or where to check the send connector, but our online exchange server is remote.visaustralia.com/exchange.


Grupo opcional não está sendo capturado

Question: Tenho um enorme arquivo de registros que eu quero transformar em uma tabela. O arquivo se parece com isto:
********************
SemprePresente1=09/2019
SemprePresente2=987456
Um monte de coisas
Que não preciso
Opcional=698,00
Mais coisas que não preciso
********************
SemprePresente1=06/2019
SemprePresente2=123658
Um monte de coisas
Que não preciso
********************
SemprePresente1=09/2019
SemprePresente2=987699
Um monte de coisas
Opcional=9999,00
Mais coisas que não preciso

Eu consigo capturar os dois primeiros grupos, mas não o terceiro, que é opcional, usando a seguinte regex:
^[\*].+?SemprePresente1=(\d\d\/\d\d\d\d).+?SemprePresente2=(\d{6}).+?((:?Opcional=)[\d,]+)?[^\*]+

Eu preciso de algo assim:
09/2019;987456;698,00
06/2019;123658;
09/2019;987699;9999,00

Entretanto, usando o padrão de substituição \1;\2;\4\n no Notepad++ eu só consigo isto:
09/2019;987456;
06/2019;123658;
09/2019;987699;

Por que não estou conseguindo capturar o grupo opcional? Aparentemente, o padrão está combinando com o registro inteiro, sem "invadir" o próximo.
Answer: Você pode usar esta regex:
^[\*].+?SemprePresente1=(\d{2}\/\d{4}).+?SemprePresente2=(\d{6})(?:(?!Opcional=)[^\*])+(Opcional=(\d+,\d+))?[^\*]+

Veja aqui ela funcionando no regex101.com.

Fiz algumas alterações na sua regex. Basicamente, usei os quantificadores {2} e {4}, que são respectivamente, "2 ocorrências" e "4 ocorrências". Ou seja, \d{4} é o mesmo que \d\d\d\d.
Outro detalhe é que :? quer dizer que o caractere : é opcional, ou seja, pode ou não ter o caractere : na string. Acho que você tentou na verdade usar (?: para criar um grupo de não-captura.
De qualquer forma, a regex não funciona porque o grupo opcional (contendo a string "Opcional") era pulado. Primeiro a regex cai no .+? logo depois do trecho "SemprePresente2", e como esse quantificador é "preguiçoso", ele tenta pegar a menor quantidade possível de caracteres. Ou seja, a regex ainda não "andou" caracteres o suficiente para chegar no "Opcional" (pois ela está logo depois do número correspondente a "SemprePresente2"), mas já tenta verificar esse trecho nesta posição da string.
Mas como esse trecho é opcional, a regex tenta verificar primeiro se não tem essa parte, e só depois, se não der certo, ela volta e tenta ver se essa parte opcional existe. Então primeiro ela pula esse grupo e verifica a expressão que vem depois.
E depois do grupo "Opcional" temos [^\*]+, e por padrão os quantificadores são "gananciosos" e tentam pegar a maior quantidade possível de caracteres. No caso, ele pega vários caracteres que não são *, ou seja, ele avança até encontrar um *, e não volta mais para verificar o grupo opcional.
Você pode ver esse comportamento aqui: use as setas do teclado para acompanhar os passos que a regex faz (veja a partir do passo 68 do primeiro match).

A solução foi, antes do grupo opcional, usar um lookahead negativo (o trecho entre (?!...)), que verifica se algo não existe à frente. O "truque" do lookahead é que ele só vê o que está na frente, e depois volta para onde estava e continua verificando a regex.
No caso, o trecho é (?:(?!Opcional=)[^\*])+, ou seja, primeiro eu vejo se não tem o trecho "Opcional=" à frente, e depois eu verifico se o caractere seguinte não é *. E faço isso várias vezes (graças ao quantificador +). Isso garante que o grupo opcional só será verificado quando realmente tivemos certeza que ele existe (ou, caso não exista, a regex acaba chegando em um * e encerra).
Depois do lookahead, temos o trecho Opcional=(\d+,\d+), que pega o número que você precisa. Repare que mudei a expressão também, pois você estava usando [\d,]+, que apesar de funcionar, também pode pegar coisas inválidas como ,,,, e 2,2,3,4 (veja).
Fazendo a substituição por \1;\2;\4\n no Notepad++, obtive:
09/2019;987456;698,00
06/2019;123658;
09/2019;987699;9999,00

Para mais detalhes sobre os quantificadores "preguiçosos" e "gananciosos", veja esta resposta.
Lembrando também que, por padrão, o ponto não considera as quebras de linha, então você deve habilitar esta opção no Notepad++, para que sua regex funcione (já que ela usa .+ para pegar trechos entre linhas diferentes).
Comment: Muito obrigado! Não só resolveu meu problema, como a explicação detalhada me ajudou a entender o que estava fazendo errado.

Grupo opcional não está sendo capturado


How to get object entries from nlohmann json

Question: I've tried to search how to get object entries from JSON using JSON for Modern C++, but I couldn't find and answer.
I have JSON like this:
{
  "Command": "cmd",
  "Data": {"time": 200, "type":1},
  /* ... */
}

And I want to ask how to get object with key Data, how to store it and how to access its elements (count of elements and keys in data can change depending on command).
Comment: In this case, `Data` is an object, not an array
Answer: You can read a json file into a json object like that:
std::ifstream jsonFile("commands.json");
nlohmann::json commands;
jsonFile >> commands;

To retrieve the "Data" object (and print the number of elements it contains):
nlohmann::json data = commands["Data"];
std::cout << "Number of items in Data: " << data.size() << std::endl;

And finally to loop over all keys and values in "Data":
for (auto it = data.begin(); it != data.end(); ++it)
{
    std::cout << it.key() << ": " << it.value() << std::endl;
}

Comment: Yes, exactly. If this was helpful, you should accept the answer and ask new, specific questions when needed.
Comment: Thank you for your answer. It is very useful for me, but is there in this library function to copy obiect with key "data" to other nlohmann::json object. (Sorry if it is silly question, but I'm using this library for first time).
Comment: You're welcome.
Yes, of course this is possible. If "otherObject" is your json object you want to copy "data" to, simply use otherObject["data"] = data;
Comment: But can i just make object json and do object = otherObject['data']? And thank you for help.
Comment: With `nlohmann::json object = otherObject["data"];`, "object" will still reference to to the original data. If you want to copy it, use `nlohmann::json copy; copy["data"] = otherObject["data"];`
Comment: Ok, so in object, there will be only array of objects from josn where key is "data", without Commant etc. ?
Comment: Thank you very much for solving my problem


Como alimentar um JSON usando "for" JavaScript

Question: Eu tenho um json no JavaScript:
var cards = [
 {
    name: "Opção 1",
    img: "images/opcao1.jpg",
    id: "1"
 },
 {
    name: "Opção 2",
    img: "images/opcao2.jpg",
    id: "2"
 },
 {
    name: "Opção 3",
    img: "images/opcao3.jpg",
    id: "3"
 }
        ];

Minha dúvida é, como eu poderia editar ou adicionar itens a esse json usando for? O uso do for seria por que eu recebo via Ajax valores para serem alimentados.
Comment: Deixa eu ver se eu entendi. Você quer fazer um lopping com FOR para varrer seu Ajax? Seria isso?
Comment: Na verdade eu quero preencher com mais valores, criando o indice 4, 5, 6 etc
Answer: O que você tem é um array, não um JSON. JSON é a apenas a forma de notação de objetos baseado em JavaScript. Dizer que você tem um JSON significa que você tem uma string com a notação JSON:
const meuJSON = '{"nome": "Usuário"}'.
Para alimentar seu array, você só precisa fazer push nele. O Ajax do jQuery (de acordo com sua tag) já converte o JSON recebido para objeto, exemplo:

var cards = [{
  userId: 0,
  id: 0,
  title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
}]

$.getJSON('https://jsonplaceholder.typicode.com/posts/1')
  .done(function(data) {
    console.log('dados recebidos do ajax:', data)
    cards.push(data)
    console.log('meus cards com o ajax:', cards)
  })
  .fail(function() {
    console.log('Ops! Um erro aconteceu')
  })

Comment: Obrigado pela resposta, mas no seu código se entende que o json que vou receber é da mesma estrutura do array. o JSON que recebo é que estrutura totalmente diferente, por isso a minha dúvida de como setar determinar valor do JSON recebido a uma posição especifica do array


What is virtual pitch?

Question: From what I understand, virtual pitch is a concept that is supposed to account for the "missing fundamental" phenomenon. Specifically,

A harmonic sound is said to have a missing fundamental when its overtones suggest a fundamental frequency but the sound lacks a component at the fundamental frequency itself. The brain perceives the pitch of a tone not only by its fundamental frequency, but also by the periodicity implied by the relationship between the higher harmonics. Source: https://en.m.wikipedia.org/wiki/Missing_fundamental

Can someone explain what virtual pitches are and how this explains why the missing fundamental phenomenon occurs?
Answer: When a person hears a combination of sounds which are at many precise or nearly-precise multiples of a common frequency, and are not common multiples of a higher frequency, the person will often perceive a at that common frequency, whose timbre will be influenced by the combination of frequencies above it.  This effect can be experienced even if the amplitude of sound at the common frequency itself is zero.
Note that it is possible to perceive multiple simultaneous distinct tones which
are multiples of a common frequency if the individual tones themselves have a
distinct harmonic signature.  For example, if one hears the following
combination of frequencies (amplitudes expressed linearly)
Freq 1000 2000 3000 4000 5000 6000 7000 8000 9000 10k
     1.0  1.5  0.33 0.75 0.20 0.50 0.14 0.38 0.11 0.30

one would likely perceive a combination of harmonically-rich sounds at 1000Hz and 2000Hz.  Although all the frequencies are multiples of 1,000Hz, those which
are also multiples of 2,000Hz would be much louder.  If instead one had heard
the following combination of frequencies:
Freq 1000 2000 3000 4000 5000 6000 7000 8000 9000 10k
     0.0  0.5  0.33 0.25 0.20 0.17 0.14 0.12 0.11 0.10

one would perceive a single harmonically rich sound at 1,000Hz even though there is no frequency content there, because there is no other higher frequency whose multiples are more dominant than the other multiples of 1,000Hz.
In cases where sounds are subjected to harmonic distortion, the process will add spectral content at frequencies which are sums and differences of multiples of the original frequencies.  If the 1000Hz example above were distorted, for example, because all multiples of the original frequencies are also multiples of 1,000Hz, the process would generate spectral content at 1,000Hz.  Power chords on a guitar use this principle, since the three strings have pitches in a 2:3:4 ratio, thus generating a fundamental an octave below the lowest string.  Although virtual pitch is enhanced by electronic distortion, such distortion is not required.  Some pipe organs have 2 2/3' and 1 3/5' stops whose pipes are one third and one fifth the length of the principle 8' stop; some add a 1 1/7' stop which is one seventh the length.  If one starts playing a melody line using those stops in combination with the 8' stop, and then turns off the 8' stop, the melody may be perceived as continuing at its original pitch even without any frequency content there.  On some organs, especially those with the 1 1/7' stop, it's possible to hear the appropriate pitch without having to be led to it, but with just the 2 2/3' and 1 3/5' stops the effect doesn't work as well.
Comment: @Dave: I suspect that's the case, but lack the expertise to pass judgment on such claims.  Sensory perception is weird in many ways, and many sensory processes "almost" fit certain nice easy physical models but have anomalies that suggest the processes behind them are probably quite different from what the models would suggest.
Comment: "such distortion is not required" -- one way to look at it is that the distortion is occurring in our ears (http://music.stackexchange.com/questions/26834/does-our-hearing-generate-neural-signals-for-harmonics)
Answer: When presented with a (relatively) complex pitched sound, beyond just frequency extraction, your brain does additional processing to identify harmonic patterns, i.e. sets of frequencies where all of them are integer multiples of some fundamental frequency.  This is an important part of our pitch perception.  Because of this complex processing there is not always an obvious relationship between the spectral content of a given sound, and the pitch that a listener assigns to it.
There are techniques to combine sounds (combination tones and others) such that listeners will assign a lower pitch to the resulting combination than either of the individual sounds; the fundamental of the pitch of the combined sound is not physically present.  This "missing fundamental effect" is somewhat surprising since for most sounds, it is the frequency of the lowest harmonic that determines the perceived pitch.
"Virtual pitch" seems to be a term coined by some music theorists in their attempts to describe some features of (musical) sound perception, e.g. degree of consonance, and is consistent with the well known missing fundamental phenomenon.  This theory includes the idea that the brain attempts to assign a "virtual pitch" to sounds, by looking for relationships between the spectral components.  To my knowledge this term only applies to ideas that build upon those originally presented by Terhardt in the 1970's, i.e. it reflects a particular school or approach to this kind of analysis.

What is virtual pitch?