404 errors with Nginx

Question: I'm trying to test nginx on Dreamhost following the instructions in the wiki, but going to any page except for the front page results in a 404 error: http://wiki.dreamhost.com/Nginx#Drupal.
Certain things are assumed, and from that assumption I cannot tell if they apply to what I'm trying to do or not. I'm guessing its some kind of clean URL based error.
For example, /home/YOURUSER/nginx/example.com/drupal.conf; my path is /home/YOURUSER/example.com/drupal.conf.
I'm assuming at this point that is not the issue.  I've tried various things including just putting in what appears to be the bare minimum to no effect:
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?q=$1 last;
}

Any pointers would be helpful.  I'd like to get this working with Boost.
I also attempted to use this: http://wiki.nginx.org/Drupal#Not_So_Simple.
Disabling clean URLs allows me to log in, and Drupal states that clean URLs are not enabled.
Comment: DreamHost changed its site knowledge base to this new URL: https://help.dreamhost.com/hc/en-us/articles/216431827
Answer: This is what I use (with Drupal 6 and Boost), most is self explanatory but I added additional comments here and there:
server {
        listen          80;
        server_name     IP.NR example.com www.example.com;  # Multiple hostnames seperated by spaces
        root            /path/to/drupal; # Replace this
        charset         utf-8;
        access_log  /var/log/nginx/example.com.access.log  combined;
        error_log   /var/log/nginx/example.com.error.log;

        index  index.php;

        if ($host ~* (^example.com|www.example2.com)) { # Redirect to www.example.com
                rewrite ^(.*)   http://www.example.com$1 permanent;
        }

    ## 6.x starts
        location / {
                #rewrite ^/(.*)/$ /$1 permanent; # remove trailing slashes - disabled
                try_files $uri @cache;
        }

        location @cache {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page  405 = @drupal;
                add_header  Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header  Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header  X-Header "Boost Citrus 1.9";
                charset         utf-8;
                try_files   /cache/normal/$host${uri}_$args.html /cache/$host${uri}_$args.html @drupal;
        }

        location @drupal {
                ###
                ### now simplified to reduce rewrites
                ###
                rewrite ^/(.*)$  /index.php?q=$1 last;
        }

        location ~*
        (/\..*|settings\.php$|\.(htaccess|engine|inc|info|install|module|profile|pl|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(Entries.*|Repository|Root|Tag|Template))$
        {
                deny all;
        }

        location ~* /files/.*\.php$ {
                return 444;
        }
        location ~* /themes/.*\.php$ {
                return 444;
        }

        location ~ \.php$ {
                try_files $uri @drupal;           #check for existence of php file
                fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
                include /etc/nginx/conf.d/php_fpm; # Includes config for PHP-FPM (see below)
        }

        location ~ \.css$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
            }
                error_page 405 = @uncached;
                #access_log     off;
                expires         max; #if using aggregator
                add_header      X-Header "Boost Citrus 2.1";
            try_files   /cache/perm/$host${uri}_.css /cache/$host${uri}_.css $uri =404;
        }

        location ~ \.js$ {

                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                    return 405;
                }
                error_page 405 = @uncached;
                #access_log  off;
                expires  max; # if using aggregator
                add_header X-Header "Boost Citrus 2.2";
            try_files /cache/perm/$host${uri}_.js /cache/$host${uri}_.js $uri =404;
        }

        location @uncached {
                #access_log  off;
                expires  max; # max if using aggregator, otherwise sane expire time
        }

        location ~* /files/imagecache/ {
                #access_log         off;
                try_files $uri @drupal;  #imagecache support - now it works
        }

        location ~* /files/backup_migrate/ {
                deny all;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
                #access_log  off;
            expires          14d;
            try_files $uri = 404;
        }

        location ~* \.xml$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.4";
                charset utf-8;
                types { }
                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

        location ~* /feed$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.5";
                charset utf-8;
                types { }

                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

#        error_page  404              /index.php;

        # redirect server error pages to the static page /50x.html
        #
#        error_page   500 502 503 504  /50x.html;
#        location = /50x.html {
#            root   html;
#        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}

        location /server-status {
                stub_status on;
                access_log off;

        }

     }

I'm using PHP-FPM (which is included in PHP 5.3 but I'm using 5.2) so I also include this file (...conf.d/php_fpm)
        fastcgi_pass   127.0.0.1:9000;    #php-fpm listening on port 9000
        fastcgi_index  index.php;
        fastcgi_param  QUERY_STRING   $query_string;
        fastcgi_param  REQUEST_METHOD     $request_method;
        fastcgi_param  CONTENT_TYPE   $content_type;
        fastcgi_param  CONTENT_LENGTH     $content_length;

        fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
        fastcgi_param  REQUEST_URI        $request_uri;
        fastcgi_param  DOCUMENT_URI   $document_uri;
        fastcgi_param  DOCUMENT_ROOT      $document_root;
        fastcgi_param  SERVER_PROTOCOL    $server_protocol;

        fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
        fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

        fastcgi_param  REMOTE_ADDR        $remote_addr;
        fastcgi_param  REMOTE_PORT        $remote_port;
        fastcgi_param  SERVER_ADDR        $server_addr;
        fastcgi_param  SERVER_PORT        $server_port;
        fastcgi_param  SERVER_NAME        $server_name;

        # PHP only, required if PHP was built with --enable-force-cgi-redirect
        fastcgi_param  REDIRECT_STATUS    200;

        fastcgi_connect_timeout         60;
        fastcgi_send_timeout            180;
        fastcgi_read_timeout            180;
        fastcgi_buffer_size             128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size   256k;
        fastcgi_temp_file_write_size    256k;
#   fastcgi_intercept_errors        on;

Just ask if you have any questions about specificities.
Answer: Even though it seemed odd, I created a nginx/site.com and put the .conf there.  I am accustomed to .htaccess, but apparently this file does not belong even in the same dir so in the end it was just a silly mistake with where I put the .conf.

404 errors with Nginx


How alter page content before printing?

Question: In my project, I am using "Printer-friendly pages" module in order to add print button to my project.
for example when a user is in "checkout/5/review" page, print module create a page with "print/checkout/5/review" address.
this process works fine but I want to alter the created page for printing "print/checkout/5/review"
I tested hook_page_alter but it doesn't work.
Answer: The print friendly module uses the theme system to output your print friendly page. So you need to do this on theme layer using a preprocess function. Use THEMNAME_preprocess_page or THEMENAME_preprocess_print in your template.php. Check the theme_hook_suggestions for more options. From the module
 $variables['theme_hook_suggestions'] = array();
 187   $variables['theme_hook_suggestions'][] = "print__node__{$type}";
 188   $variables['theme_hook_suggestions'][] = "print__node__{$type}__{$nid}";
 189   $variables['theme_hook_suggestions'][] = "print__{$format}";
 190   $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}";
 191   $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}__{$nid}";

Comment: can I do this via module ?
Comment: Yes, you can put a preprocess in a custom module.

How alter page content before printing?


Question about Universal Mapping Property

Question: Now I seem to understand the construction of the tensor product of $R$-Modules by defining $$F_R(M \times N) := \bigoplus_{(m,n) \in M \times N} R\delta_{(m,n)}$$
and constructing the submodule $D$ in a manner such that $\otimes: M \times N \to M \otimes N = F_R(M \times N)\, / \, D$ is bilinear and thus by the universal mapping property, we can find $\ell \circ M = B$ where $M: (m,n) \to \delta_{(m,n)}$, $B: M \times N \to P$, $P$ being some $R$-module. And since we can show that $D \subseteq \ker{\ell}$ and $\ell$ is linear, then given $\otimes$, we may essentially disregard the submodule $D$ and have $\ell \circ \otimes = B$ and thus the tensor product admits a unique linear map $\ell$.
Now my question is as follows:
Does someone have a proof of why there exists a property such that this linear map must exist, I understand how everything works if this property is true. But why and when is it true?
My other question is why is it necessary to construct the tensor product at all? Why can't we just construct $F_R$ and use the linear map from it to $P$? Is it because we want the properties that come along with modding out $D$?
Comment: Is $R$ commutative? Otherwise I don't see how $M\otimes_RN$ is an $R$-module. Have you *tried* to prove the universal property? That is, given any bilinear $f:M\times N\to P$, it can be factored through $\otimes$, and that the map $M\otimes N\to P$ is uniquely determined by $P$? The free module on $M\times N$ is way too big, it has way too much redundancy in it (look how big $D$ is!), and one would have to forget the purpose of $\otimes$ in the first splace: as a universal way station between two modules and their bilinear targets, and to extend scalars with "pretend" multiplication.
Comment: @blue Yes, $R$ is commutative. I do not know how to prove existence, but I do know how to prove uniqueness..
Answer: I'll assume $R$ is commutative so $M\otimes_RN$ is an $R$-module.
The elements of $M\otimes_RN$ look like sums of pure tensors of the form $m\otimes n$ with $m\in M,n\in N$, modulo the relations that describe bilinearity of the $\otimes$ symbol. The $R$-module structure of the tensor product is defined by $r(m\otimes n)=rm\otimes n$ (which equals $m\otimes rn$). In order to construct this module formally, we have to quotient the free module on the Cartesian product as we do.
One checks the map $\otimes:M\times N\to M\otimes_RN$ given by $(m,n)\mapsto m\otimes n$ is bilinear. Suppose we have any other bilinear map $f:M\times N\to P$ and we want to find out if it can be factored as
$$M\times N\xrightarrow{\otimes}M\otimes_RN\xrightarrow{\tilde{f}}P.$$
Necessarily $\tilde{f}(m\otimes n)=f(m,n)$, so $\tilde{f}$ is uniquely determined by $f$. One also checks that the map defined by this equality (namely $\tilde{f}(m\otimes n)=f(m,n)$) is a well-defined $R$-module morphism.
Why not just use the free module on the Cartesian product? Because it's big, unwieldy, it has too much redundancy. We want things as tight as possible; it's a sort of "minimal information needed to specify" situation. Any $R$-module homomorphism is determined by where it sends the elements in a chosen generating set. The generating set of $F_R(M\times N)$ is all of $M\times N$, and the information of $f(m,n)$ for all $(m,n)\in M\times N$ is way, way more information than we need. Somehow we need to make it tighter in order to remove all of the ugly redundancy. The tensor product achieves that; any bilinear map $f:M\times N\to P$ is determined by where it sends the elements of a generating set of the module $M\otimes_RN$.
Indeed, if one wants to find a universal "way station" through which all bilinear maps factor through, one needs this $R$-module to be generated by the images of all the $(m,n)\in M\times N$, and hence contain their sums as well, but must be subject to bilinearity since the map from $M\times N$ to this way station needs to be bilinear. This exactly characterizes what $M\otimes_RN$ is!
The tensor product, and its universal property, is extremely useful. Multilinear maps become linear maps, hom spaces can be rearranged with tensor-hom adjunction, scalars can be extended.
Comment: @AnthonyPeter No problem. The real issue is not linearity of $\tilde{f}$, which is inherent, but its *well-definedness*. A tensor may have two different representations as sums of pure tensors, and $\tilde{f}$ is defined by the representation of a tensor as a sum of pure tensors, so we need to check it doesn't depend on *which* representation. Since all distinct representations of a tensor as sums of pure tensors come from using the bilinearity relations for the symbol $\otimes$, it suffices to check $$f((m'+m)\otimes n)=f(m'\otimes n+m\otimes n)$$ and the same on the other side of $\otimes$.
Comment: And also $f(rm\otimes n)=f(m\otimes rn)$, but that wouldn't fit in by above comment because of character limits.
Comment: Wonderful answer and exposition. I understand everything except why it is that $\tilde{f}$ is guaranteed to be linear.
Comment: @AnthonyPeter In order to define a linear map it suffices to define where a generating set is sent to. Since pure tensors are a generating set for $M\otimes_RN$, and we've defined where $\tilde{f}$ sends pure tensors $m\otimes n$, we extend with linearity to define $\tilde{f}$ on all of $M\otimes_RN$. Defining a linear map by simply specifying where it sends generators is a rather ubiquitous practice in mathematics.
Comment: Fair enough. Thank you. I don't quite have the maturity for these things yet, being a sophomore in high school. Excuse the inherent ignorance.


Which of the following is true about $f(x)$?

Question: If $f(x)=x+\sin x$, then which of the following is true about $f(x)$?
$1.f(x)$ is uniformly continuous on $\mathbb{R}$.
$2.f(x)$ has bounded variation on  $\mathbb{R}$.
$3.f(x)$ does not have bounded variation on bounded intervals of $\mathbb{R}$.
My attempt:Since $f'(x)=1+\cos x$ is bounded on $\mathbb{R}$ so $f(x)$ is uniformly continuous on $\mathbb{R}$
$3$rd is false because $$TV(f)_a^b=\int_a^b|f'(x)|dx\leq2(b-a)<\infty$$
Is this argument correct?
About $2$nd I have no idea.
Thanks
Answer: To show a function is not a Bounded variation, especially this function has a valid derivative defined, then you can just compute the $L^1$ norm of the derivative. Typically, we have $W^{1,1}(I)\subset BV(I)$ with $I\subset R$ is bounded or unbounded. Moreover, you could take the following definition, it is also in wiki that you suggest,
$$\|u\|_{BV(R)}= \sup\left\{\int_R u\,\phi'\,dx,\,\,\phi\in C_c^1(R),\,\,|\phi\|\leq 1\right\}$$
Noticing that if your function $u$ is actually have a weak derivative, in your case you have derivative in classical sense is even better, you can integration by parts and have
$$\int_R u\phi'\,dx=-\int_R u'\,\phi\,dx$$
and hence
$$\|u\|_{BV(R)}= \sup\left\{\int_R u\,\phi'\,dx,\,\,\phi\in C_c^1(R),\,\,|\phi\|\leq 1\right\}=\sup\left\{-\int_R u'\,\phi\,dx,\,\,\phi\in C_c^1(R),\,\,|\phi\|\leq 1\right\}= \int_R |u'|dx$$
In your case, the last term is infinite and hence it is not $BV$.
Be careful that in general a function is not $W^{1,1}$ can be $BV$, just take $\chi_{[0,1]}$. It has bounded variation in $R$ but it is not $W^{1,1}(R)$
Answer: $\int_{\mathbb{R}}|1+cosx|\geq\sum_{k=1}^{\infty}\int_{-\pi+2k\pi}^{\pi+2k\pi}|1+cosx|dx\geq\sum_{k=1}^{\infty}\int_{-\pi+2k\pi}^{\pi+k2\pi}1dx=+\infty$
Comment: Which result you have used to prove that it does not have bounded variation on $\mathbb{R}$?I do not understand your solution.
Comment: I'm sorry, what is your definition of BV-function?
Comment: See this http://en.wikipedia.org/wiki/Bounded_variation
Comment: Here I can see the definition only on a bounded interval $[a,b]$.
Comment: Yes this argument works only for bounded intervals.
Comment: I extended the definition in the obvious way, but maybe it doesn't make sense. The point is that it is not clear what does bounded variation on $\mathbb{R}$ means.
Comment: It is not an argument, it is a definition.


Price is not correct when edit order in back end magento

Question: I have a problem when editing an order in the back-end of Magento. In the front end,  I have custom price when add Product to cart. Price is good in back end ( show and correct in order) but when I click edit order, the price is not correct in Item order. I have seen it get the default price of product. I try to catch event sales_quote_save_before and try code
$quote = $observer->getEvent()->getQuote();
foreach ($quote->getAllItems() as $item)
{
 $item->setCustomPrice($price);
 $item->setOriginalCustomPrice($price);
}

but I only set custom price for each item in order, I can not set Subtotal and row Subtotal for order. could you tell me how to do that? Thank so much
Answer: You can programmatically set subtotals and other related attributes as following:
$order = Mage::getModel('sales/order')->setIncrementId($reservedOrderId)->setStoreId($storeId); // if saving new one

$order = Mage::getModel('sales/order')->loadByIncrementId('10012345');    //if loading product
$order->setSubtotal($sub_total)
$order->setBaseSubtotal($base_sub_total)
$order->setTaxAmount($some_tax_price)
$order->setGrandTotal($grand_total)
$order->setBaseGrandTotal($base_grand_total);

Do note that if you make changes in this manner then some reports might not calculate the order(s) correctly (such as dashboard)
Answer: Can try following solution -
Can create solution via Magento module
1)
config.xml, need add block with event sales_convert_order_item_to_quote_item - like
<adminhtml>
    <events>
        <sales_convert_order_item_to_quote_item>
            <observers>
                <orderpricesfromoldorder_old_prices>
                    <type>singleton</type>
                    <class>Magefast_OrderPricesFromOldOrder_Model_Observer</class>
                    <method>salesEventOrderItemToQuoteItemPrices</method>
                </orderpricesfromoldorder_old_prices>
            </observers>
        </sales_convert_order_item_to_quote_item>
    </events>
</adminhtml>

2) Observer file with function/method - like
public function salesEventOrderItemToQuoteItemPrices($observer)
{

    /** @var $orderItem Mage_Sales_Model_Order_Item */
    $orderItem = $observer->getEvent()->getOrderItem();
    $quoteItem = $observer->getEvent()->getQuoteItem();
    // Do not import giftmessage data if order is reordered
    $order = $orderItem->getOrder();
    if ($order && $order->getReordered()) {
        return $this;
    }

    // mage::log($orderItem->getData('price'));
    // mage::log($quoteItem->getProduct()->getData('price'));

    if ($orderItem->getData('price') && $orderItem->getData('price') != '') {

        $quoteItem->setCustomPrice($orderItem->getData('price'));
        $quoteItem->setOriginalCustomPrice($orderItem->getData('price'));
    }

    return $this;
}

You can check Magento Core module - Mage_GiftMessage
So, when will edit Order via Adminpanel - prices will same.
but be carefull with low prices :)
Answer: Adding to Magefast's solution, I've found that you also need to setCustomPrice() on the parent item when working with Configurable products. The quote will contain both the simple + configurable product, you want to make sure both rows get updated with the custom price.
Observer Method:
public function setCustomPriceForItem($observer)
{
    $quoteItem = $observer->getQuoteItem();
    $orderItem = $observer->getOrderItem();

    $session = Mage::getSingleton('customer/session');

    if ($session != null && !$session->getReordered() && $orderItem->getOriginalPrice() != $orderItem->getPrice()) {
        $quoteItem->setCustomPrice($orderItem->getPrice());
        $quoteItem->setOriginalCustomPrice($orderItem->getPrice());

        //also update the price on the parent item
        if ($parentQuoteItem = $quoteItem->getParentItem()) {
            $parentQuoteItem->setCustomPrice($orderItem->getPrice());
            $parentQuoteItem->setOriginalCustomPrice($orderItem->getPrice());
        }
    }

    return $this;
}

Also see https://magento.stackexchange.com/questions/62422/getting-quote-cart-items-programatically-shows-duplicate-skus-for-both-the-con


Como saber se a aplicação está sendo executada em ambiente de desenvolvimento ou de produção?

Question: Preciso verificar se a aplicação está sendo executada no meu computador (Windows 10) ou no servidor (Windows server) para saber se obtenho as credenciais do usuário de forma específicas em cada plataforma.
Procurando na internet achei algumas opções utilizando Environment.OSVersion, porém não estou conseguindo diferenciar se o Windows é versão desktop (10, 11) ou server:
using System;

public class Program
{
    public static void Main()
    {
        OperatingSystem os = Environment.OSVersion;

        Console.WriteLine("OS Version: " + os.Version.ToString());
        Console.WriteLine("OS Platoform: " + os.Platform.ToString());
        Console.WriteLine("OS SP: " + os.ServicePack.ToString());
        Console.WriteLine("OS Version String: " + os.VersionString.ToString());
        Console.WriteLine();

        // Get Version details
        Version ver = os.Version;
        Console.WriteLine("Major version: " + ver.Major);
        Console.WriteLine("Major Revision: " + ver.MajorRevision);
        Console.WriteLine("Minor version: " + ver.Minor);
        Console.WriteLine("Minor Revision: " + ver.MinorRevision);
        Console.WriteLine("Build: " + ver.Build);
        Console.ReadLine();

    }
}

O resultado tem sido só "Windows".
Answer: Você pode determinar se está em um Windows Server pela função IsOS do shlwapi.h:
using System.Runtime.InteropServices;

static class OS
{
    public static bool IsWindowsServer()
    {
        return OS.IsOS(OS.OS_ANYSERVER);
    }

    const int OS_ANYSERVER = 0x1D;

    [DllImport("shlwapi.dll", SetLastError=true, EntryPoint="#437")]
    private static extern bool IsOS(int os);
}

E para chamar:
if(OS.IsWindowsServer()) {
    ///
}

Answer: Isso não é possível, até porque precisaria definir o que é ambiente de desenvolvimento e o que é produção. O que é para você pode não ser para outra pessoa.
Inclusive o sistema operacional não determina se o ambiente é de produção ou não, só você sabe disso, talvez. E se mudar o local onde é a tal da produção?
Você pode verificar se é um Windows Server, mas aí não estaria determinando se é produção ou não, a não ser por uma convenção sua hoje, não de outras pessoas ou sua em outra momento ou situação, é um conceito errado. E se for rodar no Linux? tentar verificar qual é o sistema operacional é um critério, mas ficaria algo assim:

Se você definir que o ambiente de desenvolvimento é quando está rodando em modo debug, aí já tem uma solução, mas é a deteção deste modo apenas. Se não puder fazer assim não tem jeito.
Para facilitar pode criar uma função que retorne isto:
public static bool IsDebug() {
    #if DEBUG
        return true;
    #else
        return false;
    #endif
}

A forma de compilação determinará o que retornar. Será inclusive bem eficiente, ainda que isso não seja relevante para o caso.
Se na verdade quiser executar algo apenas se for um modo debug aí pode usar o atributo Conditional("DEBUG") em algum método restrito. Exemplo:
[Conditional("DEBUG")]
public void Foo() {}

Ainda pode verificar com o método Debugger.IsAttached().
Existem algumas outras técnicas mais sofisticadas dependendo do tipo de aplicação (exemplo) ou se você quiser fazer um arquivo de configuração que tenha essa informação, e aí você mantém arquivos diferentes em locais diferentes, mas essencialmente é problema da sua aplicação cuidar disto e o critério é seu do que é produção e o que é desenvolvimento, passaria não ser de como resolver como o que a linguagem e a BCL do .NET entrega para você. Essa solução é muito mais adequada que tentar verificar em qual sistema operacional está rodando.
Coloquei no GitHub para referência futura.
Comment: Debugger.IsAttached foi o suficiente para resolver o problema, obrigado Maniero!


Are limit superior and limit inferior defined for $z_n$ being a complex sequence?

Question: All the definitions of limit superior and limit inferior I have seen (even in the books about complex analysis) define them for a real sequence only.
What could stop us from defining it as follow for a complex sequence?
$$\limsup\limits_{n\to\infty} z_n := \lim_{n\to\infty}\Big(\sup\{|z_k|:k \geq n\}\Big)$$
$$\liminf\limits_{n\to\infty} z_n := \lim_{n\to\infty}\Big(\inf\{|z_k|:k \geq n\}\Big)$$
Comment: Nothing is stopping you (but note that all you're doing is defining the limsup of $z_n$ to be the limsup of the real sequence $|z_n|$.  Perhaps the more important question is, what might motivate this definition, beyond generalization for its own sake?
Comment: Since the complex numbers do not form an *ordered* field, it doesn't really make sense to talk about sup or inf or limsup or liminf of complex sets or sequences.
Answer: This feels like a poor generalization of these properties.  One of the most valuable properties of the lim sup and lim inf is: 1) they always exist and 2) when they're equal, the sequence is convergent and converges to the limsup and liminf.
Worse, they don't even generalize, in the sense that we'd have for the constant real sequence $a_n = -1$ that $\limsup a_n = 1$ and $\liminf a_n = 1$, which is clearly not the limit of $a_n$.
Comment: @Ruslan: There isn't one.  This is why we don't normally define limsup and liminf for complex sequences.
Comment: Indeed. So what would be the correct generalization?
Answer: Those notions, as far as I can tell, cannot be smoothly generalized to the complex plane in an interesting way.
However, if you get a kick out of it, I think the generalization you're looking for is:
$$\limsup z_n = \sup \limits_{||u||=1} \limsup \pi_u(z_n)$$
Where $u\in \mathbb{R}^2$, and $\pi_u$ is the projection of a complex point on the linex generated by $u$, that is, if you think of a complex number $z$ as a vector in $\mathbb{R}^2$, $\pi_u(z) = u\cdot z$.
Note that in this case, since you're looking at projections on lines in all directions, $\liminf z_n = -\limsup z_n$. You could limit lines to be "left to right" and eliminate this problem (and then it would be a true generalization of the real case), but this seems rather arbitrary, and won't be, for example, a generalization of the "pure imaginary case".
What I would define if you want a more useful general notion, is something like "diameter of limit", akin to $\limsup x_n-\liminf x_n$ in real sequences, which could be defined as the supremum of distances between limits of $(z_n)$, or in a very similar manner to the definition above using projections as
$$\lim \mbox{diam } z_n = \sup \limits_{||u||=1} \left( \limsup \pi_u(z_n) - \liminf \pi_u(z_n)\right)$$
This is a more geometrically intersting quantity - it's a true gerneralization of $\lim \mbox{diam }$ as would be defined on reals and when it's $0$, the sequence converges (because it converges in all directions).


Erro ao fechar Forms

Question: Tenho o seguinte trecho de código para fechar minha aplicação.
private void frmAgent_FormClosing(object sender, FormClosingEventArgs e)
{

    if (MessageBox.Show("Deseja realmente fechar o sistema?", "Atenção!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
    {
        Application.Exit();
    }
    else
    {
        e.Cancel = true;
    }

Mas quando clico para fechar e clico em sim ele cai no if, executa o trecho Application.Exit(); e retorna para inicio do método abrindo o MessageBox novamente. Se eu clicar em sim novamente, aí sim ele fechar o form. Alguém já viu isso ?
Answer: Altere seu código como o exemplo abaixo
        if (MessageBox.Show("Deseja realmente fechar o sistema?", "Atenção!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
        != DialogResult.Yes)
        {

            e.Cancel = true;
        }

Ao usar Application.Exit(); é disparado o método FormClosing e gera um loop.
No exemplo acima isso é evitado.
Comment: Jota, muito obrigado pela atenção.
Comment: Dessa vez esse está fechando o winform, mas infelizmente o processo não é finalizado ao fechar a aplicação. O que pode estar ocorrendo ?
Answer: Faz todo o sentido acontecer isto já que o Application.Exit() conforme demostra a documentação dispara o evento que vai executar seu frmAgent_FormClosing. Quando chega neste método já se sabe que a aplicação está saindo, não precisa dizer que é para sair. Não precisa fazer mais nada. Isto deve resolver.
private void frmAgent_FormClosing(object sender, FormClosingEventArgs e) {
    if (MessageBox.Show("Deseja realmente fechar o sistema?", "Atenção!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) {
        e.Cancel = true;
    }
}

Coloquei no GitHub para referência futura.
Se você tiver que fazer algo mais, pode fazer mas se só queria fazer a confirmação, não precisa dizer para fechar, o fluxo normal se você não dizer que é para cancelar é fechar.
Antes de usar alguma coisa sempre leia o manual.
Comment: Gostaria de saber qual é o erro aqui para ter um -1?

Erro ao fechar Forms


Javascript JSON.parse(jsonEmTexto) funciona no Linux mas não no Windows. Como resolver?

Question: Olá, pessoal. Eu tenho uma página HTML que usa AngularJS para exibir um JSON que é passado usando o encodeURI(). No Linux eu consigo passar esse JSON sem problemas, mas quando a mesma página função é feita no Windows, dá erro de formatação de JSON.
O código abaixo é JavaScript.
Aqui estou enviando o JSON usando o encodeURI().
var modalPath = path.join('file://', __dirname, 'paginas/etiqueta/verEtiqueta.html?ETiqueta=' + encodeURI(objProduto));
                    var win = new BrowserWindow({
                        width: screen.width,
                        height: screen.height
                    });
                    win.on('close', function() {
                        win = null
                    });
                    win.loadURL(modalPath);
                    win.show();

Aqui estou recebendo o JSON pegando o parâmetro pela URL e usando decodeURIComponent() para isso.

            var x = location.search.substring(10);
            var xx = decodeURIComponent(x);
            var objetoOriginal = JSON.parse(xx);

No linux a variável objetoOriginal recebe valor da variável xx e retorna um objeto normal, já no Windows a variável objetoOriginal não recebe valor e o console retorna erro de formatação de JSON.
Para não deixar a pergunta muito extensa, deixo o "JSON" que a variável xx recebe apos o decodeURIComponent(x) retornar o valor, resultado que a variálvel xx  nesse link http://pastebin.com/JwnAEqC5
Answer: Bom para quem tiver com esse problema a solução é usar a função eval do javaScript, bom basicamente como o JSON que estou passando e muito longo em alguns casos o JSON.parse() pode não funcionar
// X recebe o JSON da URL cortando fora o inicio que serio o parametro '?Rparametro=' deixando apenas o encodo do JSON
var x = location.search.substring(10);
var objetoOriginal = eval('(' + decodeURIComponent(x) + ')');

no console se usarmos o comando typeof
typeof objetoOriginal
retorna o tipo da variável como sendo objeto.


Why ws4j online demo values and source code demo values differ, especially the lesk value?

Question: I am trying to find the similarity between two words (for example "home" and "house") using lesk.
I executed the demo code for finding lesk value given here and I also found the value using online ws4j demo here
Both of them give different values i.e.
Values by executing demo code given in ws4j :
WuPalmer    = 0.4
JiangConrath    = 0.08467941109843881
LeacockChodorow = 1.1349799328389845
Lin     = 0.16528546101187536
Resnik      = 1.1692001183611416
Path        = 0.1111111111111111
Lesk        = 0.0
HirstStOnge = 0.0

Values by online demo:
wup( home#n#8 , house#n#10 ) = 1.0000
jcn( home#n#8 , house#n#10 ) = 12876699.5
lch( home#n#8 , house#n#10 ) = 3.6889
lin( home#n#8 , house#n#10 ) = 1.0000
res( home#v#1 , house#v#2 ) = 9.0735
path( home#n#8 , house#n#10 ) = 1.0000
lesk( home#n#8 , house#n#10 ) = 1571
hso( home#n#8 , house#n#10 ) = 16
Why is so huge difference between these two when they both use same ws4j??
Is there any problem with the demo code ??
Answer: String word1="house";
String word2="home";
RelatednessCalculator wup = new WuPalmer(db);

List<POS[]> posPairs = wup.getPOSPairs();

double maxScore = -1D;
for(POS[] posPair: posPairs) {
List<Concept> synsets1 = (List<Concept>)db.getAllConcepts(word1, posPair[0].toString());
List<Concept> synsets2 = (List<Concept>)db.getAllConcepts(word2, posPair[1].toString());

for(Concept ss1: synsets1)
{
    for (Concept ss2: synsets2) {

        Relatedness relatedness = wup.calcRelatednessOfSynset(ss1, ss2);
        double score = relatedness.getScore();
        if (score > maxScore) {
                 maxScore = score;
        }
         p1=ss1.getPos().toString();
         p2=ss2.getPos().toString();
    }
}} if (maxScore == -1D) {
maxScore = 0.0;}
System.out.println("sim('" + word1 +" "+ p1 +"', '" + word2 +" "+ p2+ "') =  " + maxScore);

Comment: Try using dis code ... it might solve ur problem ! :)
Comment: If this way used for calculating WuPalmer (e.g. "avocado" and "fruit") this returns values greater than 1 where this measure supposed to return 1 as a highest value, any solution please
Answer: Home and House, both are in the same synset. So for wup and jcn, the value seems right. Which version of JDK do you use ? Try this link -
http://maraca.d.umn.edu/cgi-bin/similarity/similarity.cgi?word1=home&senses1=all&word2=house&senses2=all&measure=wup&rootnode=yes
It'll also give you the same result.
Use home#n#1 and house#n#1 in online version, it will give the result like your compiler.
Answer: For one thing, ws4j does show inconsistency between its online demo and the last stable release (v1.0.1). You could find related issue at here.
However, for your case, it is because the "mfs" flag (which stands for the Most Frequent Sense) is set to true at default in the ws4j library. When this flag is true, the similarity calculation will only perform on the most frequent senses of each word; when it is false, similarity calculation will be computed on all sense combination. Basically it is equal to @Pranav 's answer.
It is expectable that the computation burden will be greatly increased when mfs is set to false. So I guess that's the reason the author set it to true as default.
If you want to set the mfs value to false in your code, simply use:
WS4JConfiguration.getInstance().setMFS(false);


Angular-UI and Bootstrap-UI together

Question: I'm very new to AngularJS. Please let me know how can I use BOTH Angular-UI and Bootstrap-UI in the same page (application).
OR
How can I use just the Angular-UI (which I supposed to be the parent of bootstrap-UI) but having Bootstrap-UI functionality?
UPDATE ( Solution )
I'm not allowed to answer my question so, I put the solution here...
angular.module('app', ['ui','ui.bootstrap']);
Answer: UI Bootstrap (AngularJS) and Twitter Bootstrap (Components and JavaScript) can be used together on a single project, but the behavior may be slightly different for some elements. This is not recommended, since it will be redundant.
You can also look into making of AngularStrap.
AngularStrap is a set of native directives that enables seamless integration of Bootstrap 3.0 into your AngularJS 1.2 application.
For more information, please refer:-
http://mgcrea.github.io/angular-strap/
Answer: This is bootstrap definition in angular controller:
var myModule = angular.module('App', ['ui.bootstrap']);

 myModule.controller('Monitor', function($scope) {

 }

 myModule.$inject = ['$scope'];

All bootstrap sources you add to header (wrapper) like in jQuery.
Comment: It works like this:

angular.module('app', ['ui','ui.bootstrap']);

...just as simple ;)

Thank you anyway Steff

Angular-UI and Bootstrap-UI together


Evaluate or Simplify $\int_{a}^{+\infty} \frac{\exp(-bx)}{x+c} Ei(x) dx$

Question: I am stuck trying to evaluate or simplify this integrale  :

$$I_{a,b,c} = \int_{a}^{+\infty} \frac{\exp(-bx)}{x+c} Ei(x) dx $$

with $a,b,c \in \mathbb{R}_+^*$.
and $ Ei(x) =\int_{-\infty}^{x} \frac{\exp(t)}{t}  \mathbb{d}t $ : The Exponential integral function
I already found this result:
$$\int\exp(-bx) \  Ei(x) = \frac{1}{b} \left[Ei((1-b)x)-\exp(-bx)\ Ei(x) \right] $$
but I can't see if it useful.
Any Hint ?
Comment: How about first doing the special case $\int_1^\infty \mathrm{Ei}(x) dx/(x+1)$...???
Comment: @jack:Have a look to E1-Transform. As if your integral is related to that transform. Maybe the link can be helpful to you. http://www.m-hikari.com/ijcms-password2008/13-16-2008/aghiliIJCMS13-16-2008-3.pdf
Comment: @GEdgar in that case the integral does not converge.
Comment: I should ask for special case $\int \mathrm{Ei}(x)dx/(x+1)$, since the original is asking for an indefinite integral of $\exp(-bx)\mathrm{Ei}(x)/(x+c)$.
Comment: @jack: $\text{Ei}(x)$ should not be $\int_{-\infty}^x\dfrac{e^t}{t}dt$ when $x>0$ and should be for example $\gamma+\ln x+\int_0^x\dfrac{e^t-1}{t}dt$ instead, as $\int_{-\infty}^x\dfrac{e^t}{t}dt$ diverges when $x>0$ .
Answer: By using the expression $\text{Ei}(x)=\gamma+\ln x+\int_0^x\dfrac{e^t-1}{t}dt$ mentioned in http://people.math.sfu.ca/~cbm/aands/page_230.htm,
$\int_a^\infty\dfrac{e^{-bx}\text{Ei}(x)}{x+c}dx$
$=\int_a^\infty\dfrac{e^{-bx}}{x+c}\left(\gamma+\ln x+\int_0^x\dfrac{e^t-1}{t}dt\right)~dx$
$=\gamma\int_a^\infty\dfrac{e^{-bx}}{x+c}dx+\int_a^\infty\dfrac{e^{-bx}\ln x}{x+c}dx+\int_a^\infty\dfrac{e^{-bx}}{x+c}\int_0^x\dfrac{e^t-1}{t}dt~dx$
$=\gamma\int_a^\infty\dfrac{e^{-bx}}{x+c}dx+\int_a^\infty\dfrac{e^{-bx}}{x+c}\int_1^x\dfrac{1}{t}dt~dx+\int_a^\infty\dfrac{e^{-bx}}{x+c}\int_0^x\dfrac{e^t-1}{t}dt~dx$
$=\gamma\int_a^\infty\dfrac{e^{-bx}}{x+c}dx+\int_a^\infty\int_1^x\dfrac{e^{-bx}}{t(x+c)}dt~dx+\int_a^\infty\int_0^x\dfrac{(e^t-1)e^{-bx}}{t(x+c)}dt~dx$
$=\gamma\int_a^\infty\dfrac{e^{-bx}}{x+c}dx+\int_1^a\int_a^\infty\dfrac{e^{-bx}}{t(x+c)}dx~dt+\int_a^\infty\int_t^\infty\dfrac{e^{-bx}}{t(x+c)}dx~dt+\int_0^a\int_a^\infty\dfrac{(e^t-1)e^{-bx}}{t(x+c)}dx~dt+\int_a^\infty\int_t^\infty\dfrac{(e^t-1)e^{-bx}}{t(x+c)}dx~dt$
$=\gamma\int_a^\infty\dfrac{e^{-bx}}{x+c}dx+\int_1^a\int_a^\infty\dfrac{e^{-bx}}{t(x+c)}dx~dt+\int_0^a\int_a^\infty\dfrac{(e^t-1)e^{-bx}}{t(x+c)}dx~dt+\int_a^\infty\int_t^\infty\dfrac{e^te^{-bx}}{t(x+c)}dx~dt$
$=\gamma\int_{a+c}^\infty\dfrac{e^{-b(x-c)}}{x}dx+\int_1^a\int_{a+c}^\infty\dfrac{e^{-b(x-c)}}{tx}dx~dt+\int_0^a\int_{a+c}^\infty\dfrac{(e^t-1)e^{-b(x-c)}}{tx}dx~dt+\int_a^\infty\int_{t+c}^\infty\dfrac{e^te^{-b(x-c)}}{tx}dx~dt$
$=\gamma e^{bc}E_1(b(a+c))+\int_1^a\dfrac{e^{bc}E_1(b(a+c))}{t}dt+\int_0^a\dfrac{(e^t-1)e^{bc}E_1(b(a+c))}{t}dt+\int_a^\infty\dfrac{e^{bc}e^tE_1(b(t+c))}{t}dt$
$=\gamma e^{bc}E_1(b(a+c))+e^{bc}E_1(b(a+c))\ln a+e^{bc}E_1(b(a+c))\int_0^a\dfrac{e^t-1}{t}dt+\int_a^\infty e^{bc}e^tE_1(b(t+c))~d(\ln t)$
$=e^{bc}E_1(b(a+c))\text{Ei}(a)+\int_{\ln a}^\infty e^{bc}e^{e^t}E_1(b(e^t+c))~dt$


How to solve: If $x+y=8$, what is the max of $x^y$?

Question: Now, I was bored, and decided to do some math for fun. After a while, I came up with this:$$\text{Given }x+y=8\text{, what is }\max(x^y)\\\text{where }x,y\gt0$$which I thought that I might be able to do. Here is my attempt at doing so:
Right away we can see that $y=8-x$ which implies that we can rewrite $x^y$ as $x^{8-x}$.
Now, letting some function $p(x)=x^{8-x}$, we can see that $p'(x)=-x^{7-x}(x+x\ln(x)-8)$ and now, to find the maximum, we need to set this to $0$. Now, here's a quick explanation of why I am setting $p'(x)$ equal to zero:

In mathematics, the derivative shows the "sensitivity" of the change of a function's output with respect to the output. This is basically a change in $y$ over a change in $x$ of a function (if you remember $\frac{\Delta y}{\Delta x}$ from your Algebra I class), but applied infinitely. The reason we set the derivative equal to $0$ is because at the maximums and minimums of a function, the change of the function's output at that point will be $0$, therefore the derivative is $0$. Now back to the question.

We have that $\lim_{x\to0^+}p'(x)=0$ (because $\lim_{x\to0^-}p'(x)$ does not exist), although we have that that is actually the minimum of $p(x)=x^{8-x}$, since ($p(0)=0$) but we have 2 equations we can solve:$$-x^{7-x}=0\text{ or }x+x\ln(x)-8=0$$which since we already established that $x=0$ is a minimum of our function, we need to find the solution to our non algebraically solvable boi$$x+x\ln(x)=8$$which this is how I did so:$$x+x\ln(x)=8\implies x^xe^x=e^8\\\implies xe=e^{8/x}\\\implies\dfrac1xe^{8/x}=e\\\implies\dfrac8xe^{8/x}=8e\\\implies\dfrac8x=W(8e)\\\implies\dfrac8{W(8e)}=x$$which we can rewrite as$$x=e^{W(8e)-1}$$meaning that our maximum is at$$e^{(W(8e)-1)(8-e^{W(8e)-1})}\approx280.904556713$$which, for any $x+y=\alpha$ where $x,y,\alpha\ge0$, we can write the max of $x^y$ as$$\max(x^y)=e^{(W(\alpha e)-1)(\alpha-e^{W(\alpha e)-1})}$$however, my question is:
Is my solution correct, or what would I do to get the correct solution?
Comment: Your solution is correct. Btw, YouTube channel BlackPenRedPen did a video on exactly the same problem as yours. He used the same solution method as you.
Comment: Correct. According to [Desmos](https://www.desmos.com/calculator/h4dbdbplfh) at the very least.
Comment: @Divide1918 Oh, he did? I must've not watched that one yet.
Answer: Your calculations are correct. You should argue that, since $f(x)= x^{8-x}$ is continuous in $[0,8]$ and differentiable in $(0,8)$, the global maximum/minimum will exist (Weierstrass theorem) and will occur either at point where $f' =0$ or at the boundary.
Since you have established that the derivative vanishes at a single point $x_0 \in (0,8)$, and that $f(0) = 0$, $f(8)=1$, $f(x_0) \approx 280$, you can conclude that $f(x_0)$ is the global maximum and zero is the global minimum (also, $f$ attains a local minimum at $x=8$).
Answer: Almost correct. It's indeed enough to find maximum for function $x^{8 - x}$ on $(0, 8)$. From calculus, if differentiable function attains maximum on an interval, then it's derivative in this point is $0$, so solving $\left(x^{8-x}\right)' = 0$ is the way to go, and you solved it correctly.
What remains is to show that it's actually a maximum. It's simple: for example, you can say that if $x$ is close to $0$, then $x^{8 - x}$ is also close to $0$, and if $x$ is close to $8$, then $x^{8 - x}$ is close to $1$. But as if $x = 4$ then $x^{8 - x} = 4^4 > 1$, function has a larger value inside the interval than near borders, thus it has a global maximum in an inner point of the interval, and in this point derivative is $0$. As there is only $1$ point with zero derivative, it has to be global maximum.
Counterexample why it's important to check that derivative's zero is actually maximum: function $f(x) = x^3 - x^2$ on interval $(-1, 5)$ has two zeroes of derivative: $x = 0$ and $x = 3/2$, but neither is maximum on this interval: the former is only local maximum, while the later is minimum.
Comment: +1 But maybe use $(-1,2)$ instead of $(-1,5)$. It's the same situation, but easier to observe if you look at the graphic.


How do I use GZIP to optimize the size of my web service messages?

Question: Is this done at the code level, perhaps through JAX-WS handlers? Or is it done through some configuration at the app server?
I've read something about web compression in general, it appears that just as the message is about to head to the wire, compression is applied. Clients should be able to accept a GZIP MIME type for them to be able to decompress the message.
I'd like to find out who's supposed to apply that compression and how it's done.
Comment: It's the app server, if that server handles HTTP. Otherwise it's the webserver. Search for gzip deflate and $appserver name. For example: http://viralpatel.net/blogs/enable-gzip-compression-in-tomcat/
Answer: It can be done either by code or by configuring the server to do it on the fly. How it's done with server configuration varies widely depending on the server. For Apache, the tool to use is mod_deflate. The instructions when using JBoss are here.
To do it in code, you need to:

compress the data with gzip
set the content-length header to the length in bytes of the compressed response
include the following header in the response:
Content-encoding: gzip

The request should include the header:
Accept-encoding: gzip

More info can be found in Wikipedia.


What does $ a \pmod b$ mean?

Question: I am having little trouble in what a$mod$b means.
I under stand that if $a\equiv b\pmod n$, then n divides (a-b). But I do not understand what does it mean by $b\pmod n$. One the thing I can think of is the equivalence class of $b$. So I want to reduce $b$ to the positive lowest value in the class.
Can someone help me in lighten up the matter for me please!
Thanks!
Comment: Particularly in Computer Science, $a\bmod{b}$, for positive $b$, is the remainder when $a$ is divided by $b$. So mod in this sense is a binary *function*. In Mathematics, $a\equiv b\pmod{m}$ is a ternary *relation*.
Answer: The integers form a ring under usual addition and multiplication with $n\Bbb{Z}$ the only ideals, for any $n \in \Bbb{Z}$.  The integers modulo $n$, $\Bbb{Z}_n$ is a ring isomorphic to the quotient group $\Bbb{Z}/n\Bbb{Z}$.  The quotient ring is the set of all equivalence classes $k + n\Bbb{Z},\ k \in \Bbb{Z}$.  There are only $n$ equivalence classes.  Since $\Bbb{Z}/n\Bbb{Z}$ is a ring you can work with equivalence classes like ring elements.  So $a + n\Bbb{Z} = b + n\Bbb{Z} \iff (a - b) + n\Bbb{Z} = n\Bbb{Z} = 0$ (notice that the equiv. class $0 + n\Bbb{Z}$ is the additive identity ($0$) for the quotient ring.  Also notice that $c + n \Bbb{Z} = 0 \iff c \in n\Bbb{Z}$, thus $(a-b) + n\Bbb{Z} = 0$ iff $(a-b) \in n\Bbb{Z}$ iff $n$ divides $a-b$, and there's your original definition.
Firstly, use "b \pmod{m}" in $\LaTeX$.  Then $b \pmod m$ means usually to take the remainder when dividing by $m$, and interchangeably the resulting congruence class.  So if $b = 0$, then $b \pmod m = 0 = 0 + m \Bbb{Z}$, if $b > 0$, $b \pmod m = \text{remainder}(b/m) = b + m \Bbb{Z}$.  The remainder is, you said it, the smallest positive integer in the congruence class, and is a representative of the class meaning, given remainder $b'$, all you need to do to find the other elements of the class is look at $b' + m \Bbb{Z}$.  If $b < 0$, for instance $-5$, then $-5 \pmod 3 = 1$, by convention, as $-5 = -1(3) + (-2)$ and $-2 \in \Bbb{Z}_3$ is $1$.  Or look at the remainder through the definition of the division algorithm, then the remainder is always positive.  In conclusion, $b \pmod m$ interchangeably means the smallest positive integer in the congruence class of $b$ in the integers under modulo $m$ arithmetic, the remainder when doing the standard division algorithm, or the congruence class itself.  Which interpretation to pick or when they are interchangeable will be clear from the context.  Unless the context is badly written, then switch material.
Comment: This is correct, but this is the proof of modulus thing. What I want to know is the meaning of $b (mod m)$. This is clearly a equivalence class. But when I use it in problem solving context such as cryptography (exponentiation), what this suggests!
Comment: @user3001408 edited my post

What does $ a \pmod b$ mean?


No free lunch theorem proof

Question: Assume that learning algorithm $A$ is fixed. Let $D = \{(x_1,y_1),...,(x_N,y_N)\}$, $F$ is set of a data-generating functions(meaning $f \in F$ then $f(x_i) = y_i$ and that functions in $F$ are consistent with the data )and $h:X\rightarrow Y$ is a classifier trained by the algorithm $A$. $L(f(x),y) $ is 1/0-loss function. Then i want to show that $\frac{1}{|F|}\sum_{f \in F}E[L(f(q),h(q))] = \frac{1}{2}$ where $q$ is a test point such that $x_i \neq q$ for all $i$.
My attempt $E[L(f(q),h(q))] = E[I_{f(q) \neq h(q) }(q)] = P(\{f(q) \neq h(q))$ where $I_{f(q) \neq h(q) }(q)$ is an indicator function. How should i evaluate $P(\{f(q) \neq h(q)\})$? My intuition says that $P(\{f(q)\neq h(q)\}) = \frac{1}{2}$, but i cant come up with a formal argument for that.
Any help is apperciated.
Update:
Could i argue that if $h$ just makes a random-guess then the probability that the guess is correct is $\frac{1}{2}$ so therefore $P(\{h(q) \neq f(q)\}) = \frac{1}{2}$ and then the claim follows.
Update2:
If i think the problem this way: for all $f \in F$ there exists a classifier $h$ which is trainable by the algorithm $A$. I still need the fact that how good the classifier $h$ is, which is quite hard to find out
Update3
I assume that data-generating functions $f$ are equally likely and that $h$ is fixed. I still think how i define probability of goodness of $h$ given $f$.
Comment: I think this can only work with more assumptions on $A,F,L$. If $F$ contains just a single function $f$, and $L$ outputs $0$ unless $f(x)$ is very close to $y$, then the average in the question will probably be close to $0$.
Comment: I am downvoting for asking a question from homework without proper attribution of the question
Comment: yeah me too, but none is provided O: (its a homework)
Comment: $A$ is a deterministic procedure, which outputs always the same hypothesis function $h$ for the training set $D$, but i think we need to assume something about $F$.
Comment: I told every assumption at the question.
Answer: For the usual set-up of the No Free Lunch theorem there's less here than meets the eye. The domain ${\cal X}$ is discrete, ${\cal F}$ is the (finite) set of all (deterministic) functions from ${\cal X}$ to $\{0,1\}$ such that $f(x_i)=y_i$ for data in the training set. That is, for every $x$ not in the training set, ${\cal F}$ contains exactly as many functions with $f(x)=1$ and $f(x)=0$, and that's why better-than-chance prediction is impossible.
In the question as given it's not clear what is random in the expectation, but the basic argument will be the same whatever it is.  If you want the average performance of $h$ over all possible test data (or, equivalently, over a random sample of test data drawn with equal probability from all possibilities), then you will be accurate exactly half the time with a binary $Y$. This is true regardless of your algorithm for choosing $h$: whatever $h$ is, for any given $x$ either $h(x)=1$ or $h(x)=0$ and each option is wrong exactly half the time.
The No Free Lunch theorem isn't actually very useful because we never actually care about the average performance with equal weight on all possible test data. It's mainly interesting because it shows you can't possibly have a proof that an algorithm A_1 is uniformly better than another algorithm A_2 (only that it's better on  some interesting subclass of problems)
Comment: since we sum over all the data-generating functions $f$ and the classifier $h$ is fixed then the test point should be chosen randomly?
Comment: So for example if $X$ contains $K$ points and we choose $N$ for the training set. Then there is $K-N$ points left for the test set. So therefore probability that we choose point $q \in X$ is $\frac{1}{K-N}$ since points are equally likely.
Answer: Your question is pretty ill-posed as stated, but answerable with some additional assumptions. In this answer, I will give a "mathematically formal" version of the (correct, +1) argument given by @Thomas Lumley above, while highlighting what assumptions are used and when.
First, I will denote $h:=h_A(D)$ to make it clear that it is the classifier learned by algorithm $A$ from sample $D$. Next, I'll assume that $Y = \{0,1\}$ and that $q$ is a fixed point in $X$ (not random) which is different from all $x_i$.
So, with these assumptions, the quantity you want to compute is
$$\frac{1}{|F|}\sum_{f \in F}\mathbb P\big[f(q)=1-h_A(D)[q]\mid D\big] \tag1 $$
(Note the conditional probability here : the classifier $h_A$ is a function of the sample $D$ so the probability is conditional on it.)
Now, let $U$ be the uniform distribution over the set of functions $F$ (that is, for any $f\in F, \mathbb P(U=f)=1/|F|$). $(1)$ is now given by :
$$\mathbb E_{f\sim U}\left[\mathbb P(f(q)=1-h_A(D)[q]\mid D)\right]\tag2 $$
But now notice that conditional on $D$, $1-h_A(D)[q] $ is a constant : it is either $1$ or $0$. This is where we need the additional assumption stated in @Thomas Lumley's answer above that $F$ is the set of all deterministic functions $X\to Y$ that agree with the sample $D$.
(Here, since you assume that $|F|$ is finite, that also implies that $|X|$ is finite, which is again a common assumption for some versions of the NFL theorem, as explained by Thomas).
With this extra assumption, it follows from the law of total expectation that
$$\begin{align}&\quad\ \, \mathbb E_{f\sim U}\left[ \mathbb P(f(q)=1-h_A(D)[q])\mid D\right]\\
&=\mathbb E_{f\sim U}\left[\mathbb P(f(q)=1)\mid h_A(D)[q]=0, D\right]\cdot\mathbb P(h_A(D)[q]=0\mid D)\\
&+\mathbb E_{f\sim U}\left[\mathbb P(f(q)=0)\mid h_A(D)[q]=1, D\right]\cdot\mathbb P(h_A(D)[q]=1\mid D)\\
&=1/2\cdot\mathbb P(h_A(D)[q]=0\mid D)+1/2\cdot\mathbb P(h_A(D)[q]=1\mid D)\\
&=1/2\end{align}$$
which implies the desired result.
Answer: Let $q \in X$ be a fixed test point and let $h$ be a classifier trained by the fixed learning algorithm $A$. Notice that $1_{\{f(q) \neq h(q)\}}(q) = (\frac{f(q)-h(q)}{2})^2$ since $f(x)^2=h(x)^2 = 1$ for all $x \in X$. Then we have that $\frac{1}{|F|}\sum_{f \in F}E[L(f(q),h(q))] = \frac{1}{|F|}\sum_{f \in F} E[1_{\{f(q) \neq h(q) \}}(q)] = \frac{1}{|F|}\sum_{f \in F} (\frac{f(q)-h(q)}{2}) ^ 2 = \frac{1}{2|F|}\sum_{f \in F}(1-h(q)f(q)) = \frac{1}{2}$
since $\sum_{f \in F}f(q) = 0$.
Comment: I think this may be wrong since $h(q)\sum_{f \in F}f(q)$, but $h(q)$ depends also on $f$ since $f$ generates the dataset and then its trained by the algorithm which outputs $h$ meaning that $A_{D(f)} = h$.

No free lunch theorem proof


Some numbers are arranged together. Horizontally, they are equal difference series. Vertically, they are equal difference series. What series is this?

Question: $$
\begin{matrix}
4 & 6 & 8 & 10 & 12 & 14 & 16 \\
6 & 9 &12 & 15 & 18 & 21 & 24 \\
8 & 12 & 16 & 20 & 24 & 28 & 32 \\
10 & 15 & 20 & 25 & 30 & 35 & 40 \\
12 & 18 & 24 & 30 & 36 & 42 & 48 \\
14 & 21 & 28 & 35 & 42 & 49 & 56 \\
16 & 24 & 32 & 40 & 48 & 56 & 64 \\
18 & 27 & 36 & 45 & 54 & 63 & 72 \\
20 & 30 & 40 & 50 & 60 & 70 & 80 \\
\end{matrix}
$$
These numbers are equal difference series horizontally and equal difference series vertically. What sequence is this?
You can continue to extend the arithmetic sequence to the right or downward. All the composite numbers are on these arithmetic sequences. All prime numbers are not on these arithmetic sequences.
The characteristics of its distribution are as follows: the statistical range is doubled, and the expanded part and the unexpanded part are composed of some identical arithmetic sequences. Using the principle of inclusion and exclusion, it can be calculated that the quantities of different elements in these two parts are similar.
Similarly:
Twin primes can also form such an arithmetic sequence. The numbers on the arithmetic sequence are all non twin primes, while the numbers not on the arithmetic sequence are all twin primes. Its distribution characteristics are exactly the same as prime numbers. It can also be considered that the number of twin primes in the two intervals before and after the expansion of the statistical range is approximately the same.
No one may believe this view, as long as the statistics to a large number, we will see this distribution characteristics. For example, expand the statistical scope to $10000000000$.
Comment: Resembles a 2 dimensional multiplication table, with rows at the top and columns on the left removed.
Comment: Your question would be much easier to decipher if you formatted it with
[MathJax](https://math.stackexchange.com/help/notation).  Specifically, search
for the keyword : Arrays, in [this article](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).  Please edit your question, formatting the data into a table.
Answer: On non twin primes
After adding 1 and 3 to each natural number in the natural number set n within 10, a pair of new numbers with 1 and 3 bits can be formed. If the pair of numbers are twin primes, the corresponding elements in the n set are put into the a set, otherwise they are put into the B set. If two new numbers 41 and 43 are formed by adding the numbers 1 and 3 after the number "4" in the n set, which are a pair of twin primes, "4" will be put into the a set. In this way, four numbers 1, 4, 7 and 10 should be put into set a according to this rule, while the remaining numbers 2, 3, 5, 6, 8 and 9 should be put into set B according to this rule. Obviously, a and B are complementary sets, and can refer to four pairs of twin primes (11-13, 41-43, 71-73, 101-103) and six pairs of non twin primes (21-23, 31-33, 51-53, 61-63, 81-83, 91-93) with 1 and 3 in natural number 109, respectively. In fact, after any element in B set is filled with bits 1 and 3, at least one of the two new numbers formed is a composite number.
Twin primes have complements or sets similar to complements. This set can indirectly refer to non twin primes, which makes it possible to screen out twin primes.
So how to find the elements in B set, that is, the non twin primes?
Group 1:
3、6、9、12、15......
14、27、40、53、66......
25、48、71、94、117......
36、69、102、135、168......
47、90、133、176、219......
...............................................
Group 2
6、13、20、27、34......
15、32、49、66、83......
24、51、78、105、132......
33、70、107 、144、181......
42、89、136 、183、230......
...............................................
Group 3
12、23、34、45、56......
23、44、65、86、107......
34、65、96、127、158......
45、86、127 、168、209......
56、107 、158、209、260......
...............................................
Group 4:
2、 5、 8、 11、14......
9、 22、35、48、61......
16、39、62、85、108......
23、56、89、122、155......
30、73、116、159、202......
...............................................
Group 5:
8、17、26、35、44......
17、36、55、74、93......
26、55、84、113、142......
35、74、113、152、191......
44、93、142、191、240......
...............................................
Any one of the five groups of bidirectional arithmetic sequence is followed by bits 1 and 3 to form two new numbers, which must not be a group of twin primes. However, the integer numbers that are not on the five two-way arithmetic sequence will form two new numbers by adding bits 1 and 3 after them, which must be twin prime numbers.
For example, the first number 3 in the first group is added with bits 1 and 3 respectively to form two numbers 31 and 33. Obviously, this is not a group of twin primes. The integer number 4, which is not on the five groups of two-way arithmetic sequence, is filled with bits 1 and 3 respectively to form 41 and 43, which are a group of twin prime numbers.
Here we only study the twin primes and non twin primes with 1 and 3.

Some numbers are arranged together. Horizontally, they are equal difference series. Vertically, they are equal difference series. What series is this？


Maximal ideal and invertible element

Question: I must be prove the following result: Let $R$ a commutative ring with unity, then
\begin{equation}
\bigg (a\in R\;\text{is invertible}\bigg) \Longleftrightarrow \bigg(a\in I,\text{when}\;I\subseteq R\;\text{is not maximal}\bigg).
\end{equation}
My attempt: ($\Rightarrow$) Let $a\in R$ invertible, then $R=(a)$. Indeed, if it were not $1\notin(a)$, then $a$ would not be invertible. Therefore $R=(a)$, then $a\in(a)$ which is not maximal. (Correct?)
$(\Leftarrow)$ For this implication I know I must use the Krull-Zorn Lemma, which states that every proper ideal of $R$ is contained in a maximal ideal.
Could someone help me complete the proof? Thanks!
Comment: @JackJ.: if "$a$  is not contained in any maximal ideal " then $a\in I=R \implies 1\in I\implies \:\exists\:b\in R \::ab=1\in I$.
Comment: For $1^{st}$ part: If $a\in R$ is invertible  and $a\in I$ then $1\in I\implies I=R$ is not maximal.
Comment: Thanks for your anser, if $a\in I$, then $a^{-1}\in I$?
Comment: Since $I$ is an ideal so we have for $a\in I$ and $r\in R\implies ar\in I$. So take $a^{-1}=r$.
Comment: Ok! Sorry! Could you help me too for the second implication?
Comment: Is "$a\in I$, when $I\subseteq R$ is not maximal" supposed to mean "$a$ is not contained in any maximal ideal?"
Comment: I'm not understanding anything, sorry
Comment: So, if $a\in I\subseteq R$, where $I$ is not maximal, then or $I=R$, then $a$ is invertible, or $I\subset R$, then exist $J$ maximal such that $a\in I\subset J$, then $a\in J$ absurd! Correct?
Answer: The proof for $(\Rightarrow)$ is correct. For the implication $(\Leftarrow)$, suppose that for every ideal $I$ of $R$, if $a \in I$ then $I$ is not maximal. Now, if $a$ is not invertible then the ideal generated by $a$ is a proper ideal of $R$ and hence, by Krull-Zorn Lemma, we have that $(a) \subseteq \mathfrak{m} $ for some maximal ideal $\mathfrak{m}$ of $R$ which contradicts our hypothesis thus, $a$ is invetrible.

Maximal ideal and invertible element


Jetpack compose - Having two text that fill parent and align from start like table view

Question: I want to have table view like this in compose. I used Columns with row in this way. But the thing is I can not make text fill all parent even by wight and text alignment from start they did not pos from start.

But result is nit aligned from start.
Column {
pairs.forEach {
        Row {
               Text(it.first, Modifier.weight(1f).background(Color.Blue), textAlign = TextAlign.Start)
               Text(it.second, Modifier.weight(1f), textAlign = TextAlign.Start)
           }
      }

Every thing seems fine with this code but result is here:

I put background color as blue to see that if really text fill parent or not. But seems that it will not fill parent and weight is not woking here.
Comment: Your code should work. Which version are you using?
Answer: For compose version 1.0.0-alpha04, its works fine, but for version 1.0.0-alpha05, Instead of TextAlign.Start we need to give TextAlign.Justify to get the expected result.
As per doc
/**
 * Stretch lines of text that end with a soft line break to fill the width of
 * the container.
 *
 * Lines that end with hard line breaks are aligned towards the [Start] edge.
 */
Justify,

/**
 * Align the text on the leading edge of the container.
 *
 * For Left to Right text ([ResolvedTextDirection.Ltr]), this is the left edge.
 *
 * For Right to Left text ([ResolvedTextDirection.Rtl]), like Arabic, this is the right edge.
 */
Start,

But I am not sure why TextAlign.Start it's working in aplha4 and aplha5


Fetching HTML data from page behind a (non-compulsory) login screen for use in Yahoo! Pipe

Question: I have tried to use the Fetch Page module in Yahoo Pipes to grab the content of the page below to no avail:
Example link
The problem being, when you first visit the page in your browser, you are presented with the option to login, and this is the page that the Yahoo! Pipes Fetch Page module fetches. However, upon refreshing the page within your browser, the login screen is replaced with a page containing a table, which contains the information I'm looking to extract.
Is there a way to bring up the "second" page, maybe using YQL, or some form of script within another webpage, that fetchess the HTML from the page containing the data, so I can use that in my Pipe?
Any help on this would be appreciated.
Answer: The target page sets a browser cookie for session tracking/validation  and Yahoo Pipes or YQL cannot handle them.
You will need to ask about using cURL on a PHP webserver or the Google App Engine to fetch the data because cURL also has the ability to store any cookies sent to it and if needed reply with custom ones.


.NET Core - Classe configurada no container com AddSingleton() precisa ser um Singleton?

Question: Uma aplicação Web API em .NET Core consome uma DLL em .NET Standard. A DLL possui uma classe Foo que depende da classe Bar:
class Foo
{
    private readonly IBar bar;

    public Foo(IBar bar)
    {
        this.bar = bar;
    }
}

Bar não é um Singleton (não possui construtor privado e nem .GetInstance()), mas deve possuir apenas uma instância compartilhada por toda a aplicação:
class Bar : IBar
{
    public int Contador {get; set;}
}

Para tanto, o container da Web API está configurado da seguinte forma:
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IBar, Bar>();
}

Agora uma aplicação Web em .NET Framework 4.6.1 também precisa consumir essa DLL. Essa aplicação não possui configuração de container. Seguem as questões:

Ao instanciar a classe Foo, como garantir que a classe Bar injetada se comporte como Singleton? A classe Bar deveria ter sido implementada como Singleton desde o início?
Classe injetada via AddSingleton() precisa ser um Singleton?
A configuração da classe Bar no container da Web API, caso fosse um Singleton, ficaria conforme abaixo?

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IBar, Bar.GetInstance()>();
}
Answer:
Para que a classe Bar se comporte como singleton basta você usar o método AddSingleton na hora de configurar os serviços da API. Você não precisa criar GetInstance na classe ou construtores privados isso é cuidado automaticamente pelo framework.

A classe injetada via singleton pode ser uma classe "normal". Não precisa seguir o padrão Singleton como se estivesse fazendo na mão. Crie o construtor público com quaisquer dependências que precisem ser resolvidas ou não e os métodos que ela contém. O tempo de vida do objeto será definido quando você for configurar o serviço utilizando os diferentes métodos: AddSingleton, AddScoped, AddTransient

Para adicionar como singleton, faça: services.AddSingleton<IBar, Bar>();. Uma instância única dessa classe será criada durante todo o tempo da aplicação.
Comment: obrigado pelas respostas! Entendi que não é necessário que uma classe seja Singleton para ser configurada pelo AddSingleton() no container, o próprio container se encarrega de tratar uma classe comum como Singleton. Além disso, um ponto importante da dúvida, é como a Web Application, sem possuir um container IoC, pode fazer referência à DLL e manter o comportamento de Singleton da classe Bar? A Web API possui um IoC container, mas a Web Application não.
Comment: Você não pode usar o padrão Singleton pra tentar sincronizar informações entre duas aplicações diferentes. Cada dll vai rodar dentro do escopo da aplicação, não pode acessar de fora. Só se você tivesse outra aplicação no meio fazendo esse controle.
Comment: São duas aplicações (Web Application e Web API) acessando uma Class Library (DLL em .NET Standard), cada uma no seu contexto, uma não tem nada a ver com a outra. Eu não quero que elas compartilhem informações entre si. Eu quero saber como fazer para que a Web Application possa usar a DLL e que a classe Bar se comporte como Singleton, mesmo sem ter um container IoC na Web Application.
Comment: Se o projeto Web App não possui um IoC como nos projetos de Web Api, você pode usar qualquer um dos vários pacotes que existem para gerenciar a injeção de dependência. (SimpleInjector, por exemplo) Aí varia do framework escolhido a forma de implementação, mas via de regra, não deve fugir muito de como é feito no projeto da API. Use o método que te permita registrar o objeto como singleton no framework que você escolheu pra gerenciar as dependencias. Caso não queira usar um framework nesse projeto, você pode criar uma classe wrapper no padrão singleton normal que devolva a classe `Bar`
Comment: Humm acho que estamos chegando no ponto! Poderia dar um exemplo de como seria essa classe wrapper?
Comment: Claro, segue o código no pastebin: https://pastebin.com/kMCQqP3J
A classe bar continua uma classe "normal", sem o padrão singleton, podendo ser usada no IoC da API pelo `AddSingleton`. Ela se comporta como singleton na API porém precisa de "ajuda" para se comportar como singleton sem ajuda do framework de injeção de dependência. O modo de fazer isso é usando uma classe wrapper.
Da uma pesquisada sobre classe wrapper. A grosso modo, seria uma classe que expõe métodos que estão implementados em outro lugar.
Comment: Obrigado @Leandro Battochio! Acho que isso resolve a questão! Só uma observação, a classe wrapper deve implementar a interface IBar para que possa ser injetada no construtor da classe Foo. O que acha?
Comment: A classe wrapper não precisa ter todos os métodos da classe `Bar`. Somente devolver uma única instância da `Bar` não é suficiente? O que você pode fazer, para ter certeza de que a classe wrapper seguirá o contrato da interface, é alterar o tipo da variavel `mInstance` de `Bar` para `IBar`. Deste modo vai usufruir da abstração da interface como eu acho que você quer. Você pode definir métodos na classe Wrapper se quiser chamar algum método de `IBar` mas adicionar alguma lógica antes do método original, por exemplo. Troque também o `GetInstance` para `IBar`.


Separate MIDI Drumtrack to edit each part individually

Question: I am using REAPER and Addictive Drums 2 and usually compose full MIDI drum tracks. When I want to edit the individual sounds of the drum kit, AD2 is not very helpful. Of course, I can EQ and compress every component of my virtual drum kit in the plugin directly, but the editing options in AD2 are very limited.
What I'm trying to achieve is an individual track for every component of the kit (so one for kick, snare, each tom, each cymbal, hi-hat...) to be able to compress and EQ them with my preferred VSTs.
Can I somehow split my full drum track into separate tracks by "pitch" of the notes, or do I need to separate them manually? Maybe there's an option to use a VST on just one MIDI channel, so other components are not affected?
I'd also like to know, if I separate my drum track and use the AD2-plugin on every single track, wouldn't that be too much to handle for my DAW?
Answer: Here's how it works, generally speaking:

One MIDI track which has your complete drum score, with the VST plugin applied to it.
Any number of tracks, each of which receive a different output (channel) from your MIDI track.

So the basic sound is provided by the VST plugin, but you can add the necessary plugins on a component-by-component (or track-by-track) basis.
You can get started with this link to enable individual outputs in AD2. It doesn't have Reaper listed on how to create the send/receive, but I've done the same thing with Superior Drummer so I know it works (and that you'll easily find more info if you get stuck).
Answer: Here's how you can do this:
1) create a new track for each piece of the drum kit and insert an empty midi region of the length of the drum part.
2) go to the full midi drum track and open it in the piano roll editor. Right click on the keyboard note on the left to select all midi events on that note.
3) copy all the events for a single note and paste to one of the new new tracks. Each set of events for a single note goes to a separate track. You might want to save after each copy paste.
4) don't delete the original full kit midi track, just hide it.
5) if you think your system can handle it, you can now put an instance of AD2 on each new midi track and play. If it chokes up then you can either freeze the tracks and just unfreeze the one you want to work on for effects or you can print all the tracks to audio tracks one at a time if necessary and then it's like you have a drum kit recording. You could take all your cymbal midi notes and paste them to one track to make faux overheads if you want.
I don't know AD2 at all but a lot of higher end virtual drum instruments will let you return separate audio to individual audio returns for separate external processing. I know the full version of BFD does this, so you might check the manual and see if you can do this without separating out all the midi. The above is just s worse case that will definitely work.
Comment: Frederick's answer is better than mine and I've upvoted his. I'll leave mine here in case someone has the same question about a drum plugin that doesn't have separate outputs.
Comment: Both are quite helpful, now everyone has the option of two different approaches, thank you :)


Needing Excel help on deleting with multiple criteria

Question: I am trying to figure out a way to have my Excel delete everything with an "N" in the second column, but ALSO delete all of the instances in column one where there is a duplicate number that contains an "N" at some point.
I would want the entire row of the first two numbers deleted because they both had an "N". I would also want both instances of 8573217 deleted because one of them contained an "N".
Is there a way to do this with a formula or a macro?
Comment: What do you mean by "delete all of the instances in column one" in some circumstances. What "instance" has to mean in your case? Do you find a fancy word for a cell, or is it something I miss?
Comment: Is my next understanding/supposition correct? If there is an "N" in a cell of second column, that **entire row will be deleted"", but the value of the cell in column "A:A" on that deleted row should be memorized prior to delition. Then, looking in column A:A for all values being the same with memorized cell and also **delete that rows where such occurrences appear**. Would be that correct? If not, can you better elaborate your need?
Answer: EDIT: Criteria Formula Simplified
You can use the Advanced Filter and copy/to another location
For example (with the first table data entry in Column1 in cell A7)
Criteria Formula:
=COUNTIFS(Table5[Column1],A7,Table5[Column2],"N")=0

Advanced Filter Dialog

Implemented
Answer: I propose you to create a new column, which enters N for each value where there is such an entry, having a N, this can be achieved using a countifs() formula.
Then, create a macro which removes all rows having N in that new column.
Comment: But, such a column already exists. Besides its existence witch is clear, do you understand anything else from the 'interesting description' of the need?


Difference of derivative and slope of secant line

Question: Let $f \colon [x_0,x_1] \to \mathbb{R}$ be smooth and $|f^{\prime \prime}(x)|\leq L$ for some $L \in \mathbb{R}^+$. I want to have an estimation of the form
$$
\left| f^\prime(x) - \frac{f(x_1)-f(x_0)}{x_1-x_0} \right| \leq K(x_0,x_1,L) \,.
$$
Any idea for a suitable $K$? Or do I need more assumptions for that?
Comment: Can you give more details? an initial idea that comes to mind is a linear growth bound. i.e. $K=L(1+|x_0|+|x_1|)$ which may not be a good bound for your purposes, need more information.
Answer: Let $f: [x_0, x_1] \to \mathbb{R}$ be smooth, and $|f^{\prime \prime}(x)|\leq L$ for some $L \in \mathbb{R}^+$. We want to estimate the difference:
$\bigg| f^\prime(x) - \frac{f(x_1)-f(x_0)}{x_1-x_0} \bigg|$.
First, let's apply the mean value theorem to f on the interval $[x_0, x_1]$. There exists a point $c_1 \in (x_0, x_1)$ such that:
$f^\prime(c_1) = \frac{f(x_1) - f(x_0)}{x_1 - x_0}$.
Now, let's apply the mean value theorem to $f'$ on the interval $[x, c_1]$, where $x \in [x_0, x_1]$. There exists a point $c_2 \in (x, c_1)$ such that:
$f^{\prime\prime}(c_2) = \frac{f^\prime(c_1) - f^\prime(x)}{c_1 - x}$.
Since $|f^{\prime\prime}(x)| \leq L$, we have:
$\bigg|\frac{f^\prime(c_1) - f^\prime(x)}{c_1 - x}\bigg| = |f^{\prime\prime}(c_2)| \leq L$.
Multiplying both sides by $|c_1 - x|$, we get:
$|f^\prime(c_1) - f^\prime(x)| \leq L|c_1 - x|$.
Substituting the expression for $f^\prime(c_1)$, we have:
$\bigg| \frac{f(x_1)-f(x_0)}{x_1-x_0} - f^\prime(x) \bigg| \leq L|c_1 - x|$.
In this case, the estimation for the difference is:
$\bigg| f^\prime(x) - \frac{f(x_1)-f(x_0)}{x_1-x_0} \bigg| \leq L(x_1-x_0)$.
You might have to check for some special cases (e.g. $c_1=x_0$).
Does that make sense, I'm fairly new to Math.


Retrieve Multiple Images Using PHAsset

Question: I'm trying to retrieve over 1,000 images from the user's camera roll with PHAsset but it ends up crashing or taking a long time if it's just thumbnails. Here is my function where I retrieve the images...
func retrieveImages(thumbnail: Bool) {

    /* Retrieve the items in order of modification date, ascending */
    let options = PHFetchOptions()
    options.sortDescriptors = [NSSortDescriptor(key: "modificationDate",
        ascending: false)]

    /* Then get an object of type PHFetchResult that will contain
    all our image assets */
    let assetResults = PHAsset.fetchAssetsWithMediaType(.Image,
        options: options)

    let imageManager = PHCachingImageManager()

    assetResults.enumerateObjectsUsingBlock{(object: AnyObject!,
        count: Int,
        stop: UnsafeMutablePointer<ObjCBool>) in

        if object is PHAsset{
            let asset = object as! PHAsset
            print("Inside  If object is PHAsset, This is number 1")

            var imageSize: CGSize!

            if thumbnail == true {
                imageSize = CGSize(width: 100, height: 100)

            } else {
                imageSize = CGSize(width: self.cameraView.bounds.width, height: self.cameraView.bounds.height)

            }
            /* For faster performance, and maybe degraded image */
            let options = PHImageRequestOptions()
            options.deliveryMode = .FastFormat
            options.synchronous = true

            imageManager.requestImageForAsset(asset,
                targetSize: imageSize,
                contentMode: .AspectFill,
                options: options,
                resultHandler: { (image, _: [NSObject : AnyObject]?) -> Void in
                    if thumbnail == true {
                        self.libraryImageThumbnails.append(image!)
                        self.collectionTable.reloadData()
                    } else {
                        self.libraryImages.append(image!)
                        self.collectionTable.reloadData()

                    }
            })

            /* The image is now available to us */

            print("enum for image, This is number 2")

            print("Inside  If object is PHAsset, This is number 3")
        }
        print("Outside If object is PHAsset, This is number 4")

    }

}

Please tell me if any more information is needed. Thank you!
Comment: Yes, 1000 images might take up a lot of memory... What's the question?
Comment: @jtbandes How would I retrieve these 1000 images like Instagram does?
Comment: lazy load, load up 30 images in memory at a time, when user scrolls load the next set, remove the previous.
Comment: @Shubhank How would I do this?
Answer: Generally you don't want to be loading tons of full-size or screen-sized images and keeping them in memory yourself. For that size, you're only going to be presenting one (or two or three, if you want to preload for screen-transition animations) at a time, so you don't need to fetch more than that at once.
Similarly, loading hundreds or thousands of thumbnails and caching them yourself will cause you memory issues. (Telling your collection view to reloadData over and over again causes a lot of churn, too.) Instead, let the Photos framework manage them — it has features for making sure that thumbnails are generated only when needed and cached between uses, and even for helping you with tasks like grabbing only the thumbnails you need as the user scrolls in a collection view.
Apple's Using Photos Framework sample code project shows several best practices for fetching images. Here's a summary of some of the major points:

AssetGridViewController, which manages a collection view of thumbnails, caches a PHFetchResult<PHAsset> that's given to it upon initialization. Info about the fetch result (like its count) is all that's needed for the basic management of the collection view.
AssetGridViewController requests thumbnail images from PHImageManager individually, only when the collection view asks for a cell to display. This means that we only create a UIImage when we know a cell is going to be seen, and we don't have to tell the collection view to reload everything over and over again.

On its own, step 2 would lead to slow scrolling, or rather, to slow catch-up of images loading into cells after you scroll. So, we also do:

Instead of using PHImageManager.default(), we keep an instance of PHCachingImageManager, and tell it what set of images we want to "preheat" the cache for as the user scrolls.
AssetGridViewController has some extra logic for keeping track of the visible rect of the scroll view so that the image manager knows to prepare thumbnails for the currently visible items (plus a little bit of scroll-ahead), and can free resources for items no longer visible if it needs to. Note that prefetching doesn't create UIImages, just starts the necessary loading from disk or downloading from iCloud, so your memory usage stays small.
On selecting an item in the collection view (to segue to a full-screen presentation of that photo), AssetViewController uses the default PHImageManager to request a screen-sized (not full-sized) image.
Opportunistic delivery means that we'll get a lower-quality version (basically the same thumbnail that Photos has already cached for us from its previous use in the collection view) right away, and a higher quality version soon after (asynchronously, after which we automatically update the view).
If you need to support zooming (that sample code app doesn't, but it's likely a real app would), you could either request a full-size image right away after going to the full-screen view (at the cost of taking longer to transition from blown-up-thumbnail to fullscreen image), or start out by requesting a screen-sized image and then also requesting a full-sized image for later delivery.
Comment: the apple link is still using old swift :(
Answer: In CellForRowAtIndexPath use the PHImageManager's RequestImageForAsset method to lazy load the image property on your UIImageView.

Retrieve Multiple Images Using PHAsset


Como enviar variáveis para outra page, no Windows Phone 8?

Question: Tentei seguir esse método, mas ocorre um erro na MainPage, dizendo que o NavigationService não existe no contexto atual.
Na BlankPage, o mesmo erro ocorre no NavigationContext.
Como posso solucionar isso? Preciso importar alguma biblioteca, assim como é no Android?
Pelo que entendi, esse método é para enviar strings. Como envio variáveis do tipo int e double?
Segue o código:
MainPage.xaml:

<Grid>
    <TextBlock x:Name="helloMessage" Margin="10,132,10,0" TextWrapping="Wrap" Text="Hello" VerticalAlignment="Top" FontSize="26.667" FontFamily="Segoe UI Light"/>
    <Button x:Name="sayHelloButton" Content="Say Hello!" HorizontalAlignment="Stretch" Margin="10,64,10,0" VerticalAlignment="Top" Click="sayHelloButton_Click"/>
    <TextBox x:Name="nameField" Margin="10,10,10,0" TextWrapping="Wrap" Text="Enter your name..." VerticalAlignment="Top" Height="39"/>
    <Button x:Name="button_GoToPage" Content="Go to page" HorizontalAlignment="Right" Margin="0,159,10,0" VerticalAlignment="Top" Click="button_GoToPage_Click"/>
</Grid>

MainPage.xaml.cs:
    using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace MyApp
{
    public sealed partial class MainPage : Page
    {

        string texto1 = "Hello World!";

        public MainPage()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }

        private void sayHelloButton_Click(object sender, RoutedEventArgs e)
        {
            helloMessage.Text = "Hello, "+nameField.Text+"!";
        }

        private void button_GoToPage_Click(object sender, RoutedEventArgs e)
        {

            NavigationService.Navigate(new Uri("/BlankPage.xaml?msg=" + nameField.Text, UriKind.Relative));
;       }
    }
}

BlankPage.xaml:
<Page
x:Class="MyApp.BlankPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid>
    <AppBarButton x:Name="appBarButton" HorizontalAlignment="Left" Icon="Back" Label="" Margin="-10,-2,0,0" VerticalAlignment="Top" Click="appBarButton_Click"/>
    <TextBlock x:Name="textName1" Margin="10,98,10,492" TextWrapping="Wrap" Text="(vazio)" FontSize="32" HorizontalAlignment="Center"/>

</Grid>

BlankPage.xaml.cs:
    using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace MyApp
{
    public sealed partial class BlankPage : Page
    {

        public BlankPage()
        {
            this.InitializeComponent();
            /// Manter página armazenada em cache, mesmo utilizando o botão voltar
            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string msg = "";

            if (NavigationContext.QueryString.TryGetValue("msg", out msg))

                textName1.Text = msg;
        }

        private void appBarButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.GoBack();
        }
    }
}

Answer: Você pode usar o System.IO.IsolatedStorage (para uma aplicação Windows Phone Silverlight) ou Windows.Storage.ApplicationData.Current.LocalSettings. (para uma aplicação Windows Phone).
Ambas podem ser usadas em qualquer página. Sei que parece estranho você incluir as informações que precisa passar de uma página para outra em um destes Storage, que são de acesso global da aplicação, mas tive esta mesma dúvida sua no passado e me recomendaram esta maneira.
Para uma aplicação "Windows Phone"
Acessar o localSettings:
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

Exemplo para adicionar um bool:
localSettings.Values["saveLogin"] = true;

ou
localSettings.Values.Add("saveLogin", true);

Ler a informação:
var value = localSettings.Values["saveLogin"];

Para verificar se ela existe:
if(localSettings.Values.ContainsKey("saveLogin"))

Para uma aplicação "Windows Phone Silverlight"
Exemplo para adicionar um bool:
IsolatedStorageSettings.ApplicationSettings.Add("saveLogin", false);
IsolatedStorageSettings.ApplicationSettings.Save();

E para obter a informação salva, já em outra página:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
bool saveLogin = (bool)settings["saveLogin"];

Para verificar se a informação existe antes de acessá-la:
IsolatedStorageSettings.ApplicationSettings.Contains("saveLogin")

Naturalmente, você pode fazer o mesmo com int e double. Usei bastante este recurso neste pequeno projeto, se quiser dar uma olhada melhor.
Comment: O Visual Studio apresenta esse erro: "O nome "IsolatedStorageSettings" não existe no contexto atual."
Comment: @EdeiltonSO, deve ser porque sua aplicação não está marcada como uma aplicação  "Windows Phone Silverlight". Vou editar minha resposta.
Comment: Muito obrigado, o primeiro método funcionou perfeitamente! :D


Set node to flagged by default

Question: I'm using flags on my site as a way of filtering content through views, when a user views a certain node content type, I have a rule setup which resets the value of my flag and sets it against that user for that node, the views will reference this information and change their output accordingly.
The problem I have at the moment is what happens when anonymous users enter the site for the first time, they have no flag set, and thus none of the views show anything, until they travel to one of these special nodes.
What I'm looking for is: is it possible to set a flag to a default value, so that everyone has this node tagged until it gets changed?
Answer:
You need to use another flag to identify anonymous visits.
Flag value is always boolean , true or false. So you cannot have a default value to identify whether it's visited by anonymous.

What you can do is use a rule

Check visitor is anonymous
If yes set a flag called "anonymous_visit" to that particular node
Use above information in your views to display nodes

Above rule sets flag on view of a node, If you want to add flag by default to a content then your rule event should be on node create add xx flag to node...
You can also use flag api with node api hooks to achieve above.. See flag api below example..
Flagging or Unflagging an item
You use the $flag->flag() method to either flag or unflag an item. Example:
<code><?php
$flag = flag_get_flag('bookmarks') or die('no "bookmarks" flag defined');
// Flag node #456:
$flag->flag('flag', 456);
// Unflag node #456:
$flag->flag('unflag', 456);
?>
The signature of this $this->flag() method is:

<?php
function flag($action, $content_id, $account = NULL, $skip_permission_check = FALSE)
?>
</code>
Comment: At the moment my system already sets the flag whether or not they are logged in, but I'm looking for something that I can trigger the moment they first arrive at the site. What rule event would you suggest using to 'check visitor is anonymous'?
Comment: User visits a page or a node ..
Comment: Theres an event for when a user travels to a node, but unless I'm missing the obvious, there doesn't appear to be one for other types of pages. I've managed to set up a basic working example although I'm a little afraid it's very archaic way of doing it. I've set up the rule event 'When Drupal is initialised' and then set up conditions to check if the user has any node flagged, if not, it retrieves the entity by id and sets the flag for them. It appears to work, but I'm concerned the 'Drupal is initialised' is going to run all the time

Set node to flagged by default


Como faço para colocar uma imagem que vai rolar por cima do background e em baixo do texo?

Question: Estou aprendendo HTML sozinho (fazendo pesquisas e cursos gratuitos na internet), me deparei com o seguinte problema:
Eu tenho uma imagem de fundo que foi corretamente aplicada, porém não estou conseguindo adicionar outra imagem corretamente, ela está cortada (coloquei uma foto de como ficou), que ficará em baixo do texto e irá rolar junto com o Scroll da página, e que fique à cima do background.

Obs.: Meu estilo está sendo editado em outro arquivo chamado estilo.css, e não diretamente no HTML.
Obs.: Sou bem iniciante no html e css.
Segue o meu código CSS:
@charset "utf-8";

body {
    background-image: url("../_imagens/fundo1.jpg");
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed;
    color: rgba(250, 250, 250, 0.8);
}

h1 {
    text-align: center;
}

div.logo {
    background-image: url("../_imagens/logoktg.png");
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: scroll;
}

Segue o código do html:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Ka-Tet Gaming</title>
    <link rel="stylesheet" href="_css/estilo.css"/>

            <hgroup id="titulo">

Seja Bem Vindo ao Site da KTG!

Time Range 1 da PlayerLink.

            </hgroup>

Comment: A imagem que você quer colocar é esse do logo ?
Comment: Sim, é ela sim. Eu atualizei o post e os códigos, pois consegui colocar a imagem, mas não consegui ajustar ela.
Answer: Pelo jeito o que lhe falta é saber quais propriedade deveria usar.
Para isso recomendo fortemente o seguinte roteiro de estudo:

Entenda a propriedade display do css
Ex: Qual diferença entre inline e block ?
Entenda a propriedade float do css
Com o conhecimento de sobre display + float vc já será capaz de construir um layout completo para um página.
Entenda a propriedade position do css
Com o conhecimento de sobre display + float+ position vc já será capaz de construir um layout completo idenpendente se for para web, celular, tv...

Vou tentar fazer uma analogia para tentar ajuda:
Um site é igual a uma casa.
HTML é igual a um parede sem reboco
CSS é igual a reboco+decoração
Javascipt é igual a  rightec
HTML + CSS  + Javascrip  se complementão
Comment: Mas estudar CSS não iria atrapalhar o meu conhecimento em HTML?
Pergunto isso por que a maioria das pessoas que são programadores, dizem que se eu quero estudar programação,  devo começar por HTML, como falei, sou bem iniciante em programação, por isso estou cometendo bastante erros kkk
Mas obrigado por já ter me falado que se eu aprender o que passou, vou saber consertar esse erro que estou tendo. Agradeço de verdade !!
Comment: fiz um update  na resposta
Comment: Entendi, muito obrigado pela ajuda!!


Problema ao gerar ssh key no git lab

Question: Gente estou tentando gerar um ssh key para usar no meu gitlab mais fica dando esse erro
Estou usando o git bash para gerar o key utilizando esse comando : ssh-keygen oque pode estar acontecendo?
Comment: qual foi o caminho percorrido para você gerar a ssh key?
Comment: tente usar esse comando para gerar sua ssh key `ssh-keygen -o -t rsa -b 4096 -C "email@example.com"`. Como você está no windows, após ter gerado, use esse comando para copiar sua SSH key `cat ~/.ssh/id_ed25519.pub | clip`. Após ter copiado, tente colar sua nova SSH e verifique se deu certo!
Comment: @LeonardoTheodoro segui esses passos https://bigdataagronegocio.wordpress.com/2017/03/11/tutorial-de-instalacao-e-configuracao-do-gitlab-no-windows/
Comment: @LeonardoTheodoro continua dando erro me salva hahahaha por favor
Comment: The form contains the following errors:
Fingerprint has already been taken
Fingerprint cannot be generated
Key type is forbidden. Must be RSA, ECDSA, or ED25519
Answer: Remove o Usuario@Usuario-PCdo final, porque isso não pertence a chave ssh.
Segue os passos da documentação: https://git-scm.com/book/pt-br/v1/Git-no-Servidor-Gerando-Sua-Chave-P%C3%BAblica-SSH
Que ela vai servir para qualquer sistema operacional e quando repositório.
Comment: O link que você enviou da documentação possui o `Usuario@Usuario-PC` no exemplo mostrado.
Comment: Mas isso não interfere, isso não precisa colocar, a indentificaçao do computador.
Comment: Realmente é desnecessário, já vi com e sem dependendo da situação. Mas será que tirar nesse caso resolve o problema dele...
Comment: eu sempre uso sem no Gitub e Bitbucket, não lembro se no GitLab é assim?
Answer: Já existe um fingerprint cadastrado.Então você precisa excluir o outro e também é bom tirar espaços desnecessários só para garantir, assim: Exemplo

Problema ao gerar ssh key no git lab