Why Walrasian budget set is not compact for p=0?

Question: I know that budget set is defined as $B(p,b) = \{x \in R_+^n: p.x \leq b \}$.
If $p \geq 0$ and $b \geq 0$, this budget set is called Walrasian budget set or the competitive budget set.
I also know that if $p>>0$, then Walrasian budget set is compact.
But why do we need the assumption that $p >> 0$? Why is not it compact for some $p_i = 0$?
Answer: If all $p_i > 0$, then each $x\in B(p, b)$ has $x_i \leq b_i / p_i$ for each $i$. The set $B(p, b)\subset \mathbb{R}^n$ is then closed and bounded, and thus compact. If some $p_i = 0$, then the projection $\pi_i:B(p, b) \to \mathbb{R}$ on to the $i$th coordinate is the noncompact set $\mathbb{R}^+$, so $B(p, b)$ itself is noncompact.
Comment: No. Take $n = 0$ and $p = 0$, for example. Then $B(p, b)$ is $\mathbb{R}^+$ itself, since $p.x = 0$ for all $x\in \mathbb{R}^+$.
Comment: $\mathbb{R}^+$ is not bounded.
Comment: So if I understand it correctly, the main reason is that I cannot divide by 0 and hence it is not closed? I am really bad at Mathematical analysis... Thank's a lot!
Comment: Yes, you are right.
But then I do not understand, why it is not compact... I think it is bounded and also closed. Could you give me some hint? I do not know what is wrong with my way of thinking...
Comment: I have never thought that I am so stupid as I really am. :D Thank you for your patience with me.
Comment: You don't have to apologize. Glad it worked out.


where is the nomination flag in ice stun request packet?

Question: ref to this WebRTC - TURN and ICE functions
it mentions that:
"Regular Nomination The checks continue until there is at least one valid candidate pair. The controlling agent picks from the valid pairs and sends a second STUN request on that pair with a flag to tell the peer that this is the one that is nominated for use.
Aggressive Nomination The nomination flag is sent with every STUN request, once the first check succeeds ICE processing for that media stream is finished and a second STUN request is not needed."
here is the stun packet which I capture by wireshark, but it seems that there are no a flag named nomination flag, can somebody tell or any documents to ref, thanks
Answer: Your link to the wireshark trace isn't actually linked in your question.
But, I suspect this is the ICE extension to STUN for the USE-CANDIDATE attribute discussed in the ICE RFC 8455
7.1.2.  USE-CANDIDATE

   The controlling agent MUST include the USE-CANDIDATE attribute in
   order to nominate a candidate pair (Section 8.1.1).  The controlled
   agent MUST NOT include the USE-CANDIDATE attribute in a Binding
   request.

8.1.1.  Nominating Pairs
   Once the controlling agent has picked a valid pair for nomination, it
   repeats the connectivity check that produced this valid pair (by
   enqueueing the pair that generated the check into the triggered-check
   queue), this time with the USE-CANDIDATE attribute
   (Section 126.96.36.199.4).  The procedures for the controlled agent are
   described in Section 220.127.116.11.

20.1.  STUN Attributes
   IANA has registered four STUN attributes:

      0x0024 PRIORITY
      0x0025 USE-CANDIDATE
      0x8029 ICE-CONTROLLED
      0x802A ICE-CONTROLLING

Comment: correct. The other post is a bit unclear, nominated is a internal state of the ICE agent and the on-the-wire signaling use the use-candidate attribute.


Melhor forma de fazer uma Action que não retorna dados

Question: Estou fazendo uma chamada ajax para alterar um objeto. A chamada não precisa retornar nada. Apenas o código http 200 (OK) ou 500 (erro).
Estou usando o seguinte código na action mas não sei se é o melhor:
return new EmptyResult();

Qual a melhor forma de fazer uma Action que não retorna dados?
Answer: É usando ActionResult mesmo. O problema é que EmptyResult não retorna nada mesmo, nem código de requisição:
public ActionResult MinhaActionSucesso()
{
   // Antes do MVC5
   return new HttpStatusCodeResult(200);

   // MVC5+
   return new HttpStatusCodeResult(HttpStatusCode.OK);
}

public ActionResult MinhaActionErroInterno()
{
   // Antes do MVC5
   return new HttpStatusCodeResult(500);

   // MVC5+
   return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}

Veja mais sobre as enumerações HttpStatusCode aqui.
Veja mais sobre o HttpStatusCodeResult aqui.
Answer: Para o ASP.NET MVC o EmptyResult funciona bem. Mas se a a função da sua ação é só ser chamada por AJAX (i.e., basicamente uma API), então você também pode usar o um ApiController (ASP.NET Web API), e na sua ação você retorna this.Ok() ou this.InternalServerError() (o tipo de retorno do método seria IHttpActionResult), deixando mais clara a sua intenção:
public class TestController : ApiController
{
    public IHttpActionResult Get()
    {
        if (algumaCondicaoBoa)
        {
            return this.Ok();
        }
        else
        {
            return this.InternalServerError();
        }
    }
}


SSIS 2012 incremental load for 200-300 tables

Question: My project started 2 months ago, and already I'm transferring over 100 tables on each process I run to the Data Warehouse.
I'll probably reach 200-300 tables pretty soon and do not believe my current development approach will scale.
I still have 3 weeks' versions (product dev sprints), and tables are still changing their structure (data types, column names, new columns etc) which gives me a real headache, so I ignored it for the first few weeks.
How did I ignore it?

Truncated all the tables before i take them to the ODS (Operational Data Store)/MRR layer
Took all the data from the source system fully to the MRR layer
Created only the dimensions "incremental" table (which still changes every week with new columns and changed data types)
Dynamically creating and populating the staging tables and the warehouse tables.

Now my model has started to form, so I have to take care of the incremental loads

It seems easy since I have updatetime for each record, but I also have deletions in my source system, how can I approach this ?
I've considered CDC, but this will be time consuming as I have to put it table by table
Any solutions for someone who starts with 100-200 tables?
Comment: How does the Agile approach allow for fundamental design changes? because that's what you're faced with here - a lot of back end development which has no visibility to users. I've never seen this addressed in the Agile projects that I've seen.
Answer: I follow a style similar to your "ignore it" design for as long as possible. Full refresh keeps your design agile and can go as fast as 1 million rows per minute.
When this eventually runs out of legs, and there are deletions in the source system, I delete all my data back for a date range (e.g. 3 months) as agreed with the data experts.  You may have to break that delete into chunks e.g. day by day.  I also try to fully refresh such data e.g. each weekend (as often the data experts are misinformed).
Comment: Thanks Mike,

unfortunatly , since this is OEM , we can't have the actual "data experts" to approve any misinformed data.
and the system analysts always want to hold the stick on both end , to have everything always on and always updated "as possible" (without allowing anything as "impossible"  if you know what i mean .. )
 :)
i think i'll have to go CDC for the deletions , i whish someone would create this automation that does the ODS layer for me ..   much simpler, but i guess i'd have to pay him ....   :)

thanks again


Bokeh: Use TextInput as a filter on a 'string column'

Question: I have displayed data in a DataTable and want to filter its content with a TextInput widget, similar to TextInput Example.
I tried it with a combination of BooleanFilter and CDSView:
import random
import string
import pandas as pd

from bokeh.io import show
from bokeh.models import TextInput, ColumnDataSource, CustomJS, Column, BooleanFilter, CDSView, TableColumn,\
    DataTable

def random_str():
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20))

data = dict(options=[random_str() for _ in range(500)])
df = pd.DataFrame(data=data)
source = ColumnDataSource(data=data)

text_filter = BooleanFilter(booleans=[True] * df.shape[0])
view = CDSView(filter=text_filter)

columns = []
for col in list(df.columns):
    columns.append(TableColumn(field=col, title=col))
data_table = DataTable(source=source, columns=columns, height=500, width=300, view=view)

# Setting initial values
text_input = TextInput(value="", title="Enter filter")
callback = CustomJS(args=dict(source=source, text_filter=text_filter),
                    code="""
    text_filter.booleans = Array.from(source.data['options']).map(t => t.includes(cb_obj.value));
""")
text_input.js_on_change("value", callback)

show(Column(text_input, data_table))

I hoped that it would show only those rows including text written in the widget after pressing Enter, but nothing happens.
What can I change to get this to work? Thank you in advance.
Answer: oh my, I cannot believe I forgot this inside the callback:
source.change.emit();

With it everything is fine.


Como fazer efeito slide com jquery e js

Question: Bom, utilizando jquery e js, eu queria fazer um slide onde meu php iria puxar muitas divs, e o limite será de 8 divs, por exemplo, se clicar no botão next, irá avançar para outras divs que não cabem na página, e se clicar no botão prev, vai voltar. Como posso fazer isso?
http://prntscr.com/7yktnp
HTML:

Título

<button id="next">Next</button>
<button id="prev">Prev</button>

Comment: esse efeito é chamado de *carousel* ou *slideshow* [esse exemplo do Bootstrap](http://getbootstrap.com/examples/carousel/) é bem fácil de adaptar
Comment: Já deu para ter uma base, muito obrigado.
Comment: Em http://www.w3schools.com/bootstrap/bootstrap_carousel.asp se ensina como fazer um carousel, bem detalhadamente. No caso, é usado bootstrap.
Answer: O nome desse efeito se chama Slideshow: Como exemplo, tem o modelo do bootstrap. Para funcionar é preciso inserir o arquivo css e o js da versão que pretende utilizar.
Aqui tem um modelo funcionando: http://getbootstrap.com/examples/carousel/
Você também pode fazer o efeito manualmente a partir de um efeito de transição do jQuery, o que requer mais trabalho e conhecimento, como também pode utilizar um plugin como esse o jQuery Cycle: http://jquery.malsup.com/cycle/
Há muitos outros plugins que permitem fazer esse efeito. Faça uma pesquisa no google pelas palavras: Carousel, Slideshow, slidebox, slide gallery, slider que terá alguns exemplos, tem alguns que são pagos e outros gratuitos, não esqueça de ler os termos de uso. Recomendo analisar também o suporte para as versões mobiles, pois alguns deles não fluem com o movimentos touchs. Boa sorte.

Como fazer efeito slide com jquery e js


Failing to install certbot on debian jessie

Question: I've followed the instructions at https://certbot.eff.org/all-instructions/#debian-8-jessie-nginx but cannot install certbot:

sudo apt-get -t jessie-backports install certbot
Reading package lists... Done E: The value 'jessie-backports' is invalid for
APT::Default-Release as such a release is not available in the sources

Hints appreciated
Comment: Same issue here. Went off of https://backports.debian.org/Instructions/#index2h2: ``deb http://ftp.debian.org/debian jessie-backports main``. Ran ``aptitude install python-certbot-apache -t jessie-backports`` after adding to /etc/apt/sources.list. Got ``E: The value 'jessie-backports' is invalid for APT::Default-Release as such a release is not available in the sources`` printed twice.
Comment: Please run "apt-get update" after changing the sources list and before installing the package.
Comment: Using the instructions for OS releases without a package since that is probably the only thing I can do in this situation.
Answer: did you follow instructions above that to enable backports? You need to add

deb http://ftp.debian.org/debian jessie-backports main

to your /etc/apt/sources.list
Comment: I couldn't comment below the main post. Thought I would try the obvious.
Comment: The error message on my end quoted above was the same after adding the line you mentioned. I don't think the problem is on Sue's end.
Comment: Fair enough. Maybe others will bring up a different fix.
Comment: I had enabled backports, so that isn't the answer.
Comment: Yes I did that . and apt-get update   I get this error
Answer: Had the error message above.
Running apt-get update (per the instructions) after adding the jessie-backports repository solved the problem for me
Answer: If you are using Digital Ocean, they replace the APT sources with their own mirror. You can add backports support by adding this to your /etc/apt/sources.list
deb http://mirrors.digitalocean.com/debian jessie-backports main
deb-src http://mirrors.digitalocean.com/debian jessie-backports main

Answer: Add this to your /etc/apt/source.list
deb http://mirrors.digitalocean.com/debian jessie-backports main
deb-src http://mirrors.digitalocean.com/debian jessie-backports main

run apt-get update after that run
sudo apt-get install python-certbot-apache -t stretch

simple change sudo stretch-backports to stretch
Answer: Add this to your /etc/apt/source.list
deb http://mirrors.digitalocean.com/debian stretch main
I am running this in a docker and jessie-backports no longer exists, and stretch-backports does not contain the files.  They have been moved to stretch
Comment: Jessie is still in LTS. Why should someone upgrade to stretch?


adding dynamic data to sublcassed QAbstractTableModel

Question: for testing purposes a have function that asks for input and displays it in a QListView
display data.
this works fine with one dim.data
I want to extend the script to display two-dimensional data
the incoming data should be inserted in the first row till column 3, and proceeds on the next rows (same operation) so the model contains the data in this form
 input_values = [[1,2],
                 [1,2]]....

so far I implemented that the input_data is added into the first row, but the script stops running before it starts adding the data into the second row. I just get this info
Process finished with exit code -1073740791 (0xC0000409)
What is cousing this behavior and how to fix that ?
    def thread_data_add(self, data):
        if len(self.model.input_data[0]) <= 1:
            self.model.input_data[0].append(data)
            self.model.layoutChanged.emit()

        elif len(self.model.input_data[0]) > 1:
            self.model.input_data.append([])
            self.model.input_data[1].append(data) #crashes here !!! need crash report
            self.model.layoutChanged.emit()

full code
#!/usr/bin/env python

"""

"""

import threading
import sys
import logging

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg

class ViewModel(qtc.QAbstractTableModel):

    def __init__(self, input_data=None):
        super().__init__()
        self.input_data = input_data or [[]]
        #

    def data(self, index, role): # parameter index, role are needed !
        """

        :param index: Instance of QModelIndex Class  / set automatically
        Model indexes refer to items in models,
         contain all the information required to specify their locations in those models

        :param role: what type should be returned
        :return: data as a string
        """
        if role == qtc.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            text = self.input_data[row][column]
            return text

    def rowCount(self, index):
        return len(self.input_data)

    def columnCount(self, index):
        return len(self.input_data[0])

    def getData(self):
        print(self.input_data)
        # todo how to show list data

class MainWindow(qtw.QWidget):

    core_signal = qtc.pyqtSignal(str)

    def __init__(self):
        super().__init__()

        # View
        table_view = qtw.QTableView()
        self.model = ViewModel()
        table_view.setModel(self.model)

        # widgets
        self.start_thread_button = qtw.QPushButton("start Thread")
        self.test_button = qtw.QPushButton("display data")

        # layout
        qvboxlayout = qtw.QVBoxLayout()
        qvboxlayout.addWidget(table_view)

        qvboxlayout.addWidget(self.start_thread_button)
        qvboxlayout.addWidget(self.test_button)
        self.setLayout(qvboxlayout)
        self.show()

        # self.logger = self.default_logger()

        # function

        self.start_thread_button.clicked.connect(self.start)
        self.test_button.clicked.connect(self.model.getData)

    def lambda_thread_data_add(self, data):
        if len(self.model.input_data[0]) <= 1:
            self.model.input_data[0].append(data)
            self.model.layoutChanged.emit()
            # self.model.input_data.append([])
        elif len(self.model.input_data[0]) > 1:
            self.model.input_data.append([])
            self.model.input_data[1].append(data) #crashes here !!! need crash report
            self.model.layoutChanged.emit()

    def thread_data_add(self, data):
        if len(self.model.input_data[0]) <= 1:
            self.model.input_data[0].append(data)
            self.model.layoutChanged.emit()
            # self.model.input_data.append([])
        elif len(self.model.input_data[0]) > 1:
            self.model.input_data.append([])
            self.model.input_data[1].append(data) #crashes here !!! need crash report
            self.model.layoutChanged.emit()

    def start(self):
        # starts thread
        # Setting thread.daemon = True will allow the main program to exit before thread is killed.
        threading.Thread(target=self._execute, daemon=True).start()
        self.core_signal.connect(self.thread_data_add)

    def _execute(self):
        while True:
            user_input = input("type in: ")
            self.core_signal.emit(user_input) # transmit data

    def default_logger(self,level=logging.DEBUG, save_path='beispiel.log'):
    # create logger
        custom_logger = logging.getLogger(__name__)
        custom_logger.setLevel(level)

        # was reingegeben werden soll
        formatter = logging.Formatter('%(asctime)s;%(message)s;%(filename)s;%(lineno)d', "%Y-%m-%d %H:%M:%S")
        file_handler = logging.FileHandler(save_path)
        file_handler.setFormatter(formatter)
        custom_logger.addHandler(file_handler)

        stream_handler = logging.StreamHandler()
        custom_logger.addHandler(stream_handler)

        return custom_logger

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = MainWindow()
    sys.exit(app.exec_())

Comment: Well, besides the fact that using shell input is not a very good idea for a GUI based program, clearly you have to add the data properly. In the way you're doing it, you are adding a *string* to a list, so the resulting list would be something like `[[1,2,3,4],
 [1,2,3,4], 'text', 'some other text']`; do a `print(self.model.input_data)` after `append()` and you'll see. So, the problem is that, obviously, when you try to read the contents in `data()` it will result in a serious problem. Find a better way to add the data and ensure that the columns in the "array" are always correct.
Answer: The issue you are getting is an IndexError since the data is not being added uniformly (whole row at a time), it is being added one column, or cell, at a time. As a result, when starting the next row with the 3rd input, there is no data for the 2nd column in that row yet. You don't necessarily have to change the way you are inserting data, just catch the error and supply an empty string or None value.
def data(self, index, role):
    if role == qtc.Qt.DisplayRole:
        try:
            text = self.input_data[index.row()][index.column()]
        except IndexError:
            text = None
        return text

Additionally, make sure you are accessing the correct index of input_data in thread_data_add(), which would be the last index [-1] since you are appending data.
def thread_data_add(self, data):
    if len(self.model.input_data[-1]) < 2:
        self.model.input_data[-1].append(data)
    else:
        self.model.input_data.append([data])
    self.model.layoutChanged.emit()

Comment: thanks works very well,  I don 't quite understand the reason behind the changes in the data method,  so after the first row is populated wich contains 4 columns, a second row is added,  data is been added into the first colum of the second row, and with try/except the empty columns of the second row are been populated first with None typ "data"  and then changed with the incoming data, correct ?
Comment: Yes that's right. And the reason the first row was not throwing an error with the first entry is because `columnCount()` returns the length of the first row, `len(self.input_data[0])`. If it had `return 2` instead then the very first data entry would have also resulted in an error.


Tableau: Hiding values in a chart with two dual axis

Question: I have a chart with dual x-axis and dual y-axis.
My table currently looks like this:

Since there is 2 dual axis in my chart it is showing

Blue x Depth
Blue x Shapes
Orange x Depth
Orange x Shapes

I want to hide the Orange x Shapes portion of my chart. Is there a way to do this? Possibly filter it out from the view? I tried to right click the legend to hide or exclude "Square, Orange" and "Triangle, Orange" but the option isn't available.
Edit: Here is a workbook with dummy data dummy workbook
Thank you!
Comment: Just a warning. Usually having 4 axis combined into one chart leads to more complexity than its worth, and there turns out to be a simpler way to get the same desired, or similar, effect. But I'd be curious to see some sample data to see if you've found a good use case for a quad axis chart.
Comment: A little bit of sample data would help.
Comment: Sample data is useful, but to have any idea of what you're trying to accomplish, will need a tableau workbook also in this case.
Comment: Thank you, I added a workbook with the dummy data
Answer: I posted the same question in Tableau Community and a solution with screenshots has been posted:
Solution
The basic steps to solve this is to

In the Data Source tab, Union the data with itself which creates a column called [Table Name].
Create Two Calculated columns:
Orange 2 -> if [Table Name] = "Dummy Data" then [Orange]
Shape 2 -> if [Table Name] = "Dummy Data1" then [Shapes]
In the sheet/chart, replace Orange with Orange 2 and Shape with Shape 2
In the Depth mark, add Table Name to Details


Getting the image URL from a field_image on a node

Question: So I have this Node:
object(Drupal\node\Entity\Node)[1862]
  protected 'values' =>
    array (size=17)
      'vid' =>
        array (size=1)
          'x-default' => string '7' (length=1)
      'langcode' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=1)
                  'value' => string 'en' (length=2)
      ... (more fields)
      'field_image' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=5)
                  'target_id' => string '1' (length=1)
                  'alt' => string '' (length=0)
                  'title' => string '' (length=0)
                  'width' => string '150' (length=3)
                  'height' => string '120' (length=3)

Now the field_image has an array with x-default and some basic image data. How do I show the image, or create a link to the image inside the Twig template?
Comment: Oh I see, `url()` wants a route. How about `url_from_path(node.field_image.0.entity.uri.value)`?
Comment: Don't have time to check but maybe as simple as `url(node.field_image.0.entity.uri)` ([relevant issue](https://www.drupal.org/node/2073811))
Comment: @Clive I tried this and gives me this error: `Recoverable fatal error: Object of class Drupal\Core\Field\FieldItemList could not be converted to string`

so I tried it with this:

`url(node.field_image.0.entity.uri.value)`but then it just tells me this: `Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("Route "public://image.png" does not exist.")`
Comment: Errr...I would guess it needs to be done in a preprocess hook then, unless there's a Twig helper function to convert `FieldItemList`s into a string representation (which I can't find)
Comment: Hmm `url_from_path()` seems to generate this: `http://mywebsite.local/public%3A//image.png` so it seems to be urlencoding and appending the exact value to the url
Comment: Out of ideas off the top of my head I'm afraid, will try to have a look later on today
Comment: Seems like I will need `file_create_url()` [see](https://api.drupal.org/api/drupal/core%21includes%21file.inc/function/file_create_url/8) but there's no Twig function for it :/
Comment: There [will be](https://www.drupal.org/node/2308187) :)
Comment: Ah! Thanks :) I'll just patch it until it's in core then
Answer: Here is an update version of for this answer after 8.0.x. This base on @joelpittet comment.
{{ file_url(node.field_image.entity.fileuri) }}

Comment: ... image styles are now available in Twig Tweak - https://www.drupal.org/project/twig_tweak
Comment: Please note, that you will get the url of the "unstyled" original image and not the image style specific url (e.g. thumbnail). Aside from VladimirM's answer there is no way to get the correct styled image url in twig. At least currently...
Comment: The File class has a `url()` method, so you can simply call `entity.url()` rather than passing `entity.fileuri` to `file_url()`
Comment: I don't believe that is allowed - when I tried calling `url()` i got a twig error: `Calling url method on a Drupal\file\Entity\File object is not allowed.` Drupal docs say to use the `file_url()` method too: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates#s--file-urluri
Comment: You should use the *file_url_generator* service in a hook or maybe a custom field formatter. See https://www.drupal.org/node/2940031. `file_create_url()`  and other methods are now deprecated. IMHO you shouldn't be using template files. Just use simple variables and avoid to drill down like this.
Answer: I don't know about Twig, but you get the file URI with $node->field_image->entity->getFileUri() in PHP, and the you need to call file_create_url() on that:
file_create_url($node->field_image->entity->getFileUri())

I don't know if that is possible in twig. If it's not possible, you can always calculate it in preprocess and add as a new variable.
Comment: We are trying to get file_create_url() into core but lack of interest has made the issue stale.  https://www.drupal.org/node/2168231
Though if that got in it should be {{ file_url(node.field_image.entity.fileuri) }}
Answer: If someone needed a styled image:
$styled_image_url = ImageStyle::load('large')->buildUrl($node->field_image->entity->getFileUri());

Comment: This is a great answer. Note that in your *.theme* or *.module* file you'll want to add this to the top: `use Drupal\image\Entity\ImageStyle;`
Comment: I ran into an issue with https, where Safari won't show the image as it uses the IP instead. You may want to add `$relative = file_url_transform_relative($styled_image_url);` to ensure it's relative. [API here](https://api.drupal.org/api/drupal/core%21includes%21file.inc/function/file_url_transform_relative/8.2.x)
Answer: None of the above twig solutions worked for me (perhaps those worked for older 8.x versions but not for 8.5 version
{{ file_url(node.field_image['#items'].entity.uri.value) }}

NOTE: should be working for Drupal 8.5+
Comment: I think its bad that these kind of things get deprecated after a while. Upgrading Drupal should keep those working! This works for me in Drupal 8.6, thanks.
Comment: {{ file_url(node.field_image['#items'].entity.uri.value) }}

Worked fine for me in my 8.8.2 version. Thanks
Answer: This is the way if you want to get the image URL with the associated image style for any image field in a twig template:
First install the Twig Tweak module
Then set the image URI as a variable.
With the URI, you can use a twig tweaks pattern to get the path with whatever image style you want. See below:
{% set image_uri = content.field_feature_row_image['#items'].entity.uri.value %}

Twig Tweak v2.4+ offers file_url filter to extract file URL from an entity.

And as of Twig Tweak v2.6 you can use file_uri filter in conjunction with image_style.

Answer: What ended up working for me in D8 is:
$imageUrl = $node->get('field_image')->entity->uri->value;

Using kint($node->get('field_image')->entity) and looking through the array was very helpful

Then in my twig file I used:

Comment: what if there is not image inserted and we have set default value.
Answer: So I've found out the answer with the help of Clive.
Getting the image URI in a template file is done using
node.field_image.0.entity.uri.value. Provide a Twig extension for file_create_url(), closed as fixed on January, 2015, made possible to use file_url() in a template file.
{{ file_url(node.field_image.0.entity.uri.value) }}

Answer: I'm always using a helper function
  /**
   * Get the Image URI.
   *
   * @param \Drupal\Core\Entity\Entity $entity
   * @param $fieldName
   * @param bool $imageStyle
   * @return mixed
   */
  public function getImageUri(\Drupal\Core\Entity\Entity $entity, $fieldName, $imageStyle = FALSE) {
    $imageField = $entity->get($fieldName)->getValue();
    if (!empty($imageField[0]['target_id'])) {
      $file = File::load($imageField[0]['target_id']);
      if ($imageStyle) {
        return ImageStyle::load($imageStyle)->buildUrl($file->getFileUri());
      }

      // Original URI.
      return file_create_url($file->getFileUri());
    }
  }

Answer: you can get the url directly by using field_image.entity.url
Answer: I would highly recommend using the Twig Tweak module to get the URL from an image field in your twig template. Once you have installed the module you can then use various methods for extracting the URL from the image field. The following worked for me:
{{ node.field_main_image.0 | file_url }}

I set the background image of a
 with the following:

...

Make sure to add style for width and height or you won't see if it's working
IF THIS DOES NOT WORK FOR YOU, or if you want to learn all about the other great things twig tweak can do, reference this cheat sheet. This helpful document will save you a ton of time. I wish I knew about it earlier.
Answer: Gosh, it actually took my ages to find out why my resulting URLs didn't work. The all 404'ed. You need to create a derivate first if it doesn't already exist.
So for example when you add an image style later, after the original image was uploaded, then there's no styled image file yet (the image derivate). It needs to be created first.
Replace field_MYIMAGE and MYSTYLE as you need.
$original_image = $node->field_MYIMAGE->entity->getFileUri();
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('MYSTYLE');

$destination = $style->buildUri($original_image);
if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}

$url = $style->buildUrl($original_image);

I wish this would happen automatically.
Answer: To Get image attribute like URI, alt, title etc use the syntax like below template wise
In node twig template
{{node.field_name.entity.fileuri}}

In field twig template
{{content.field_name.entity.fileuri}}

In other field twig template
{{element['#object'].field_name.entity.fileuri}}

Note: Also check twig_tweaks module cheat sheet for detail related to twig related issue.
Answer: This adds a drupal image style and the image alt test
{{ file_url(content.field_featured_image|field_target_entity.field_media_image.entity.uri.value| image_style('featured_image')) }}" alt="{{ content.field_featured_image|field_target_entity.field_media_image.alt }}

Answer: I'll probably thank me in the future:
content.field_name['#items'][0]|file_uri|image_style('style_name')

(with Twig Tweak)
Answer: somewhat related, here is what I used (thanks to all previous answers to get me there) to get an image file URL from a media entity's image field in twig:
{% set media_img_url = file_url(content.field_media_image.0['#item'].entity.uri.value) %}

now I can use this variable in my twig template
{{ media_img_url }}

Answer: You can use the url() method that is on the File class as a shortcut so:
{{ file_url(node.field_image.entity.fileuri) }}

can be shortened to:
{{ node.field_image.entity.url }}

This works in preprocess functions but triggers a Twig_Sandbox_SecurityError when called in a twig template.
If you receive Twig_Sandbox_SecurityError you can tell twig to allow url in your settings.php file as mentioned in this Stackoverflow post
See documentation on File::Url() https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%21File.php/function/File%3A%3Aurl/8.6.x
Answer: Just noting: use file_uri, not file_url.
{{ node.field_image|file_uri|image_style('content_header') }}


Apache2 virtual host reverse proxy rewrite asset links

Question: I have a web application running on port 8080 on my server:
myip:8080/app
I have the following config in my httpd.conf
<VirtualHost *:80>
 ServerName subdomain.mydomain.com
 ServerAlias mydomain.com
 ProxyPass /app http://localhost:8080/app/
 ProxyPassReverse /app http://localhost:8080/app/
</VirtualHost>

This works fine and makes the app available at subdomain.mydomain.com/app
Now I'm struggling to make it available at subdomain.mydomain.com (without the /app). I first tried
<VirtualHost *:80>
 ServerName subdomain.mydomain.com
 ServerAlias mydomain.com
 ProxyPass / http://localhost:8080/app/
 ProxyPassReverse / http://localhost:8080/app/
</VirtualHost>

and also added
ProxyHTMLURLMap /app/ /

but both don't seem to work. The main page loads, but all javascript and CSS links still point to /app/... which returns the main html page instead of the asset.
What am I missing? Am I on the right track or is there a completely different (better) way to achieve this?
The application is a Tapestry web application in Tomcat 7 on Ubuntu 12.04.
Any insights on performance would be interesting too.
Answer: ProxyPassReverse works only on  HTTP headers (e.g.: 301 redirects).
To enable HTML rewrite, you need to enable it via:
ProxyHTMLEnable On
ProxyHTMLURLMap /app/ /

However, modern web applications can easily understand what is going on from the HTTP request made by reverse proxies, and no additional tuning at the proxy level is usually necessary in this case.
Keep in mind thatmod_proxy_html add some overhead in processing those requests.
Comment: Can you please clarify what you mean by "understand what is going on"?  Are they emitting only relative links, or rebasing the links to / instead of /app based on some information that's sent in the proxy request?  Whether a web app will do that is going to be highly dependent on how it's built.
Comment: Both approaches are better than nothing, but the second one is more robust than simply outputting relative links.
I understand that such behaviour is unreachable without using specific technologies (e.g.: MVC architecture with a single application entrypoint for every request), but hey, we are in 2014.
Answer: Giovanni's answer brought me on the right track. I needed to add
ProxyHTMLEnable On

or more precisely (for my version of mod_proxy_html) the equivalent
SetOutputFilter INFLATE;proxy-html;DEFLATE

However I decided to use it in combination with a rewrite (since I couldn't get the Tapestry event links to work any other way):
<VirtualHost *:80>
 ServerName subdomain.mydomain.com
 ServerAlias mydomain.com
 ProxyRequests Off
 ProxyPreserveHost On
 SetOutputFilter INFLATE;proxy-html;DEFLATE
 ProxyPass / http://localhost:8080/app/
 ProxyPassReverse / http://localhost:8080/app/
 ProxyHTMLURLMap /app/ /
 ProxyPassReverseCookiePath /app /
 RewriteEngine on
 RewriteRule ^/app/(.+) /$1 [R,L]
</VirtualHost>

I also needed to adapt the cookie path (ProxyPassReverseCookiePath /app /) for my Tomcat session cookie to work.
Answer: Your web application at myip:8080/app probably has a lot of absolute paths in HTML and JS beginning with /app/... which cannot all be caught and rewritten by mod_proxy_html.
I would suggest to first try to get your app running at different local URLs like myip:8080/blah.
Fire up the developer toolbar of your browser and check the network tab for files that are still getting requested at /app/... and fix them until they work at both URLs (/blah and /app).
The goal should be that all your links in your app are relative, i.e. specified as

instead of something like this

Also check out the <base> tag for a way to override the default base URL.


what is the garbage collection logic in Survivor memory. - Is this based on the time which objects are created or based on usage freequency

Question: Garbage collector collects objects after 8 pass between survivor1 and surviovor2. The 8 is not fixed this can be less also according to the heap size. My question what is the removal logic after 8 passes. Is that based on creation time ,I mean deletes old objects or based on usage frequency based I mean less frequently used get garbage collected first. If there is frequency based what is the min limit.
Comment: Why do you think there has to be some additional logic? You already described the logic completely, objects are promoted after surviving eight (or whatever configured number) passes. Nothing else.
Answer: Objects get moved to the other survivor space if they are still live. Promotion to old generation/tenured is based on the number of survived gc cycles. (and liveness of course)
Should add here that if the other survivor space is too small, the oldest objects will prematurely be promoted to old gen/tenured space.
Answer: Survivor spaces are provided to give objects more chance to be collected before they get promoted to the old generation (thus reducing the load on the collector for the old gen.)
Objects that are still live in the eden space when a minor GC occurs are mostly copied to the 'to' survivor space, along with any objects that are still referenced in the 'from' survivor space. Large objects that won't fit in the survivor space are copied directly to the old gen (this tenuring).  How many times an object is copied between survivor spaces before being tenured is controlled by the tenuring threshold. The value of this has an initial and maximum value, which are 7 and 15 by default (in JDK 8).  These can be set explicitly via command line flags -XX:InitialTenuringThreshold=n and -XX:MaximumTenuringThreshold=n.
The JVM will adjust the tenuring threshold within the initial and maximum values. An additional flag, -XX:TargetSurvivorRatio=n (default 50) can be used to modify the percentage of survivor space used a collection.
To answer your specific question, the tenuring of objects is based on lifetime not frequency of access.


What is the correct way of accepting the null hypothesis in a coin flip simulation program?

Question: I am new to statistics so please bear with my question. There are some similar questions to mine but I didn't get the clear answer after reading them. I have a program that simulates the coin tossing situation. The user enters a guess and the program determines whether the user's guess is correct or not. Each user's guess will be considered as the null hypothesis. For example the user enters: the number of getting heads in 1000 coin flips is 400 if the probability of each single flip is 0.5. Then based on calculating the lower and upper critical values with the significance value of 0.05, the program informs the user whether their guess is correct or not. To code my program, I can think of the following way:
The program receives the number of flips from the user which is 1000 in this example and then does the 1000 flips for 100 separate times and after all experiments are done, the program calculates the mean of heads:
$mean = \frac{1}{100} \sum_{i=1}^{100} a_i$
where each a(i) is the number of heads in each 1000 flips. Eventually if the calculated mean is between lower and upper critical values, the user's guess is failed to reject, otherwise it is rejected.
Now I wonder if this way is the correct one?
Thanks.
Comment: You never accept the null hypothesis: you either reject it or fail to reject it.
Comment: @RobertIsrael Thanks... It is edited now.
Answer: Too long for a comment.
User's guess 400 Heads in 1000 coin tosses is not a null-hypothesis. Hypothesis testing tests parameter of a statistical model; in your case you model coin tosses by Bernoulli random variables, $\sim Ber(\theta)$, there $\theta$ is probability of getting Heads; or you can model number of Heads in 1000 tosses by Binomial random variable, it does not really matter what you model, because you are testing a value of $\theta$ again.
Possible null-hypotheses are $\theta=0.4$ or $\theta = 0.5$.
That said, please formulate what you want to do correctly. In hypothesis testing framework, you define null-hypothesis and significance level, and compute threshold values; then you run experiment ($100 \, 000$ coin tosses), and if the number of Heads is out of threshold values you reject null-hypothesis.


Adding same observations from 2 different groups. Plyr or tapply?

Question: Looking to create a function.
I would like to add the number of occurrences of an observation up within a given group (ex 5, 5 occurrences 2 times). The same numbers of Days within a Week by Business are to be summed. The summed values will be in a new row 'Total-occurrences.'
tapply or plyr works its way into this, however I'm stuck on a few nuances.
Thanks!
14X3 matrix

Business           Week        Days
A                **1**         3
A                **1**         3
A                **1**         1
A                  2           4
A                  2           1
A                  2           1
A                  2           6
A                  2           1
B                **1**         1
B                **1**         2
B                **1**         7
B                  2           2
B                  2           2
B                  2           na

**AND BECOME**

10X4 matrix

Business            Week       Days      Total-Occurrences
A                 **1**        3         2
A                 **1**        1         1
A                   2          1         3
A                   2          4         1
A                   2          6         1
B                 **1**        1         1
B                 **1**        2         1
B                 **1**        7         1
B                   3          2         2
B                   2          na        0

Comment: What is your question?
Comment: Apologies, it's to create a function which creates a new row 'Total-Occurrences.'

I want to add the total occurrences of the same 'Days' up per given Business & Week.
Answer: If I understand your question correctly, you want to group your data frame by Business and Week and Days and calculate the occurences of each group in a new column Total-Occurences.
df <- structure(list(Business = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor"),
Week = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L,
1L, 2L, 2L, 2L), .Label = c("**1**", "2"), class = "factor"),
Days = structure(c(3L, 3L, 1L, 4L, 1L, 1L, 5L, 1L, 1L, 2L,
6L, 2L, 2L, 7L), .Label = c("1", "2", "3", "4", "6", "7",
"na"), class = "factor")), .Names = c("Business", "Week",
"Days"), class = "data.frame", row.names = c(NA, -14L))

There are certainly different ways of doing this. One way would be to use dplyr:
require(dplyr)

result <- df %.%
  group_by(Business,Week,Days) %.%
  summarize(Total.Occurences = n())

#>result

#   Business  Week Days Total.Occurences
#1         A **1**    1                1
#2         A **1**    3                2
#3         A     2    1                3
#4         A     2    4                1
#5         A     2    6                1
#6         B **1**    1                1
#7         B **1**    2                1
#8         B **1**    7                1
#9         B     2    2                2
#10        B     2   na                1

You could also use plyr:
require(plyr)

ddply(df, .(Business, Week, Days), nrow)

note that based on these functions, the output would be slightly different than what you posted in your question. I assume this may be a typo because in your original data there is no Week 3 but in your desired output there is.
Between the two solutions, the dplyr approach is probably faster.
I guess there are also other ways of doing this (but im not sure about tapply)


Uncaught TypeError: users.map is not a function .. mapping on function doesn't work

Question: When i first write the map function , the code  works fine. but all on a sudden this line throwing error . Then ifi comment the users.map line the code works just fine, then uncomment it , till that works fine. But when i reload the page the error again show up to console and nothing works
import { useEffect, useState } from 'react';
import './App.css';

function App() {
  const [users, setUsers] = useState({});
  useEffect(() => {
    fetch("http://localhost:5000/users")
      .then(res => res.json())
      .then(data => setUsers(data))
  }, [])
  console.log(users);

  const handleAddUser = (event) => {
    event.preventDefault();
    const name = event.target.name.value;
    const email = event.target.email.value;
    const user = { name, email };
    // post data
    fetch('http://localhost:5000/user', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(user),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('Success:', data);
      })
  }

  return (

Own API {users.length}

      <form onSubmit={handleAddUser}>
        <input type="text" name='name' placeholder='name' required />
        <input type="text" name='email' placeholder='email' required />
        <input type="submit" value="add user" />
      </form>

        {users.map(user =>
{user.name}
)}

  );
}

export default App;

Comment: Why is the users default value an object? `const [users, setUsers] = useState({});` <--
Comment: `.map` is for [Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), but you initialize it to be `{}`
Answer: This is because users is an object not an array, therefore trying to map over it will result in an error. Try either turning it into an array or map over the object's keys.

Option 1: Changing to an Array
const [ users, setUsers ] = useState([])

Then you can use the map
{ users.map( user =>
{user.name}

Option 2: Stick with an Object
{ Object.keys(users).map( key =>
{users[key].name}

Comment: Arrays are technically objects in JS, but could you add a snippet of code to clarify what you mean?
Comment: straight forward explanation would be, object doesn't have `.map` method. While array does have one. Please refer to the mdn documentation for further details


How would you interpret this question focusing on problem solving?

Question: The first step of problem solving is to understand what the problem is asking, that is where I am stuck.

One of the legs of a right triangle has length 4 cm. Express the length of the altitude perpendicular to the hypotenuse as a function of the length of the hypotenuse.

This is the picture I first came up with, since a is perpendicular to h. But the answer is $4\sqrt{h^2-16}/h$.
This means they do not really want $a$, as that would seem to be half $h$.
I need a fourth opinion here, I have asked others and no luck here.
Comment: your picture is wrong $b=4$ is not necessaryly true. $a=h/2$ holds only for b=4.
Comment: Compare $a/4$ and $b/h$.
Answer: Note that $b=\sqrt{h^2-16}$. Also, by similar triangles (or using the sine of the angle at the bottom left corner),
$$\frac{a}{4}=\frac{\sqrt{h^2-16}}{h}.$$
Remark: The reason you say that $a$ is half of $h$ is that your picture has $b$ almost the same length as the bottom side, so the whole picture looks like a square. But it need not be. The side $b$ could be a lot bigger or smaller than $4$.
Comment: Yeah that clarifies things greatly, I realized that a more rectangle looking shape would make a non-perpendicular.
Answer: Their formula does yield $h$. The area of the triangle whose sides are $4$, $b$, and $h$ is $\frac12(ah)$. That area is also $\frac12(4b)=2b$. Thus, $\frac12(ah)=2b$, $ah=4b$, and $h=\frac{4b}a$. Now use the Pythagorean theorem to find $b$ in terms of $h$, and you have their answer.


How to convert JSON strings with different content but in same structure to C# objects?

Question: ı have a Xamarin Forms project. In a part of this project, I need to retrieve data from database in a form of JSON string however this data may change in number of roots and values and root names. All retrieved strings are in same structure however, All information in strings are different.
An example string:(In original it is a single line.)
{
    "20Pr": {
        "20Pr": {
            "AA": "0:0:0",
            "EE": "1:0:4",
            "Comp": 0,
            "ASE": "0:0:0",
            "PES": "1:0:0",
            "PLD": "0:0:4",
            "ASET": "0:0:0"
        },
        "22Bp Cache": {
            "AA": "0:0:0",
            "EE": "1:0:1",
            "Comp": 0,
            "ASE": "-",
            "PES": "1:0:0",
            "PLD": "0:0:1",
            "ASET": "-"
        },
        "21SSL Fail": {
            "AA": "0:0:0",
            "EE": "1:0:1",
            "Comp": 0,
            "ASE": "-",
            "PES": "1:0:0",
            "PLD": "0:0:1",
            "ASET": "-"
        }
    },
    "40godown": {
        "43Sw & DB": {
            "AA": "0:0:0",
            "EE": "1:24",
            "Comp": 0,
            "ASE": "-",
            "PES": "1:1:4",
            "PLD": "0:0:1:0",
            "ASET": "-"
        },
        "40goown": {
            "AA": "0:0:0",
            "EE": "1:24",
            "Comp": 0,
            "ASE": "0:0:0",
            "PES": "1:0:4",
            "PLD": "0:2:0",
            "ASET": "0:0:0"
        }
    }
}

Only the AA,EE,Comp,ASE,PES,PLD,ASET are constant but their values are not constant.
Is it possible to create C# objects from changing JSON strings without having information about names as "40godown"?
Comment: It really depends on how you want this to work, but a custom deserializer with JSON.NET would work. Each child object child be deserialized to the same object type since the structure doesn't change but you could create dictionaries/whatever other data structure you need to contain the sets of objects. Are we always talking one parent then multiple children or could there be additional levels of nesting etc?
Comment: Yes, It always have one parent and multiple children and there are consequtive 6 or 7 parents like this. To illustrate, in the sample string in question, "20Pr" and "40godown" are parents and each have 3 children. @Charleh
Answer: Assuming you have defined a class Thing that has AA, EE,..., ASET properties, you can deserialize that JSON into Dictionary<string, Dictionary<string, Thing>> without loosing information.
var data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Thing>>>(json);

Comment: @Charleh Newtonsoft.Json is 10 years old. Obviously it isn't something new. I'm programming for 40 years, almost every day I learned something new and I'm still learning. I don't understand programmers who refuse learning new things.
Comment: You know I actually saw someone manually parsing JSON recently in .net ... I told them about deserialization and they told me they didn't have time to learn anything new.


Identifying Period Type

Question: I've attached a music excerpt that's been stumping me. Is the attached passage a parallel period or a contrasting period? The rhythmic repetition makes it seem parallel, but the chord progression and melody seem contrasting.
Comment: Did you really attach a _music expert_ or did you in fact attach a _music excerpt_?
Comment: TBH, attaching a music expert would be a bit redundant.
Comment: Please add the title and composer of the piece in case someone else is studying it, too.
Answer: TL;DR
With allowance for the interpretive aspect of music analysis ...
I would label this a parallel period.
The ambiguity
The problem, of course, lies in the ambiguity in the definitions of parallel and contrasting periods. For example:

In a parallel period, the melodies in both phrases begin similarly. In a contrasting period, the phrases begin differently. (Source: Music Theory for the 21st-Century Classroom by Robert Hutchinson, "13.3.4 Parallel and Contrasting Periods")

This is easy when the parallel phrases begin identically, which is often the case. However, the definition doesn't explain how similar or how contrasting. Thus, the answer depends on how heavily one weighs the parallel aspects of the phrase against the contrasting ones.
Interpretation
Here's my own informal definition.

In a parallel period, the consequent phrase begin such that the listener is likely to recall or associate it with the antecedent. In a contrasting period, the consequent phrase is intended to present a wholly new idea.

For my own purposes, at least, this way of looking at it makes the phrase in question parallel. Even with the harmonic contrast, the rhythm is enough to bring the listener clearly back to the antecedent phrase, which I interpret as the composer's intent. I would expect a contrasting phrase to be "more contrasting" than this one.
Opposing view
My own definition could be used to make the opposite point. Given the harmonic change, perhaps the composer's intent is to highlight the contrast between the two phrases — specifically by adding just enough parallelism to reference the antecedent phrase, but not enough to make the phrases "genuinely" parallel.
This again comes back to the idea that the label depends on the interpreter's prioritization of the parallel aspects versus the contrasting ones. I give more weight to the parallel in this particular case (though reserve the right to analyze another seemingly similar phrase differently). But an interpreter giving more weight to the contrast wouldn't be wrong.
... And thus begins many a debate among music theorists.
The ultimate test
When in doubt, listen to the passage. This is the essential arbiter of music theory questions: how do you, the theorist, hear the passage. If the antecedent phrase recalls for you the consequent, it's parallel; if the antecedent phrase sounds like it's own entity, then it's contrasting.
Comment: @ToddWilcox Thanks, and thanks for the suggestion. Added.
Comment: This answer is very good. I wonder if it would help to suggest that form is often better heard with the ear rather than seen on the page. The asker might listen to a performance of the piece and ask themselves if they *hear* parallelism or not.

Identifying Period Type


Meaning of "polynomially larger"

Question: For example
Is $n$ polynomially larger than $\frac{n}{\log n}$? Than $n \log n$?
Is $n^2$ polynomially larger than $\frac{n}{\log n}$? Than $n \log n$?
I am trying to understand the difference because apparently the first line isn't, but the second is (Master Theorem).
Comment: Possibly relevant. [Link 1](http://programmers.stackexchange.com/questions/158754/what-does-it-mean-when-we-say-that-some-function-is-polynomially-bigger-smaller). [Link 2](http://math.stackexchange.com/questions/1109742/master-theorem-how-is-n-log-n-polynomially-larger-than-n-log-4-3). [Link 3.](http://www.dartmouth.edu/~matc/DiscreteMath/IV.6.pdf).
Comment: It says it doesn't apply to $T(n) = 2T(n/2) + n \log^2 n.$ and yet the answer does appear to be $\Theta(n \log^3 n)$
Answer: "Polynomially larger" means that the ratio of the functions falls between two polynomials, asymptotically. Specifically, $f(n)$ is polynomially greater than $g(n)$ if and only if there exist generalized polynomials (fractional exponents are allowed) $p(n),q(n)$ such that the following inequality holds asymptotically:
$$p(n)\leq \frac{f(n)}{g(n)}\leq q(n)$$
For the first problem, we have the ratio is equal to $\log(n)$. It is not the case that there exist polynomials $p(n),q(n)$ such that $p(n)\leq \log(n)\leq q(n)$ asymptotically, because no polynomial is a lower bound for $\log(n)$. Thus it is not polynomially bounded. $n\log(n)$ is the same (even the same quotient if taken in the other order).
For the second problem, we have the ratio is equal to $n\log(n)$. It is the case that $n\leq n\log(n)\leq n^2$ asymptotically, so it is polynomially bounded and therefore $n^2$ is polynomially larger. $\frac{n^2}{n\log(n)}=\frac{n}{\log(n)}$, and we have that (asymptotically) $$n^\frac{1}{3}\leq \frac{n}{\log(n)}\leq n$$
Comment: So I suppose it is easy to just have $n^{\text{huge number}}$ for the upper bound in practice, hard part is seeing if lower bound exists. How do I know that $n / \log(n) \geq n^{1/3}$?
Comment: That can be rearranged to give $n^{2/3}\geq\log(n)$ which can be shown a number of ways. It is not too hard to show that $\log(n)\leq n^c$ for every $c>0$ (asymptotically)
Comment: So basically the quotient of the larger over the smaller function needs to be greater than $n^k$ for $k>0$, is that right?
Comment: It needs to fall between two (generalized) polynomials. I added a formal statement. Notably fractional exponents are allowed (and generally count as polynomials for complexity theory)
Comment: If I have $n / \log(n) \geq n^k$ then $n/n^k  \geq  \log(n)$ implies $n^{1-k} \geq \log(n)$, so I suppose this means $1-k>0$ is sufficient, or $1>k$? Any $k$ less than $1$ will satisfy the lower bound?
Comment: Yup! I just picked one-third.
Comment: @StellaBiderman You said:

It is not the case that there exist polynomials $p(n), q(n)$ such that $p(n) \leq \log n \leq q(n)$. If you set $p(n) = n^0, q(n) = n$, then this inequality will be true. right?
Comment: @Drupalist Yes, that is true. However that doesn't count in this context. Notice that Aruka's first comment says "larger than $n^k$ for $k > 0$."

Meaning of "polynomially larger"


Problems with Views Load More module loading via AJAX

Question: I tried to add the Views Load More module to my semantic view but it doesn't load all of the view fields (e.g. image, etc.) when I use it with ajax. Can someone give me a hint why?
Here you can see the view:
http://www.mustxhave.com/testing
The site runs Drupal 7.43 and Views Load More v1.5. The view output is standard, no .tpl theming for this view.
Answer: Your problem is the image path not the load more module.
I inspected the image in your view and found that it is being requested from this URL:
http://www.mustxhave.com/mustxhave/sites/all/themes/simpnews/images/xyz-300x500.jpg
which is wrong.
Removing musthave from the URL will fix the image path.
http://www.mustxhave.com/sites/all/themes/simpnews/images/xyz-300x500.jpg
This may be caused by one of these:

Check the view settings for the image field.
Check settings.php file for base_url variable value.
Check if have Rewrite Base in the .htaccess file.
Comment: thanks but this was not the issue. Please have a look at the view output. Now i have made it so far, that the image is shown with ajax too but the field"social buttons" from the addthis module still not showing. Please click on "show more" then you will see that the loaded content is not the same then the usally shown content. But i dont understand why this field is not shown with ajax + load more
Answer: I think issue in your case is of jQuery, as you are getting the error of jQuery is not Defined. Please see my attached screenshot.
Try to remove jQuery (jQuery) from addThis js file, there is also one extra semicolon in end of file.
Comment: Thanks for that. I tried to delete the hole addthis.js but the toolbar buttons are not appearing either. Maybe you can explain me exactly what i have to change in this file?


Chomsky normal form complexity

Question: How to prove that the complexity of transforming any context-free grammar without epsilon productions to chomsky normal form is $ O(N^2) $ , because I found this in 2 articles, but without proof
Comment: Welcome to maths.stackexchange! It might be useful to give some extra context, such as the articles that mention this, or any attempts you have made at proving the statement.
Answer: As far as I know, this is textbook stuff so the proofs are obviously not found in articles. However if I remember correctly, you get to Chomsky normal form by first replacing any terminals in something like
$$A \rightarrow BCst$$
by some extra nonterminal symbols
$$A \rightarrow BCST$$
$$S \rightarrow s$$
$$T \rightarrow t$$
and then in the second step you replace longer rules like
$$A\rightarrow BCD$$
with again additional nonterminals
$$A\rightarrow BA'$$
$$A'\rightarrow CD$$
I think it is easy to see that each replacement step only needs $O(n)$ of work per rule, so you end up with $O(n^2)$, since the number of rules is clearly bounded by $n$.
Comment: n is the number of productions ? I don't understand it correctly. We have N productions , so why replacement for each production needs $ O(n) $ ?
Comment: n usually is some size representing the encoding of the grammar. There may be a huge number of productions (still bounded by n) or a production giving a huge number of symbols (again bounded by n), we need to account for both.
Comment: so, let's assume that n is number of productions. If all productions is A -> X , where length of X is constant C , so we need for each production (C-1) replacement and the overall complexity will be n(C-1)   assuming that we changed all terminals to nonterminals. C is constant, so $ O(n) $ ?

Chomsky normal form complexity


Silex: routing variable assignment issue

Question: I recently wrote a post about request forwarding in Silex, which used a blog example to explain sub requests in Silex.
I use a slightly modified version of this example for a domain controller.
The path to the domain endpoint = /product/domain
A domain can also have a webhosting package attached to it.
The url path for this endpoint would be /product/domain/(id)/webhosting/
You can fetch info about a webhosting package by using the url path.
The url path for this endpoint would be /product/domain/(id)/webhosting/(id)
To handle these sub requests, I have a method called forwardRequest, which has no parameters in it's method signature, but uses func_get_args to keep it dynamic.
Unfortunately this doesn't work as Silex uses the named parameters in your route to call your method. So if you have /product/domain/domain_id/webhosting/webhosting_id, your method should have a signature of method($domain_id, $webhosting_id), which is a PITA if you want to forward multiple endpoints through one method. If you have additional /product/domain/domain_id/emailhosting and /product/domain/domain_id/dns endpoints, you have to create a method for each in order to forward the request.
Does anyone have a solution in which I can use only 1 method to forward all these sub requests?
Note: I'm using PHP 5.3.
Answer: The part of silex that decides which arguments to pass to the controller is called the "controller resolver". The default controller resolver uses reflection. You can override the controller_resolver service with a custom implementation though.
Defining a custom controller resolver that wraps the existing one but replaces the arguments with a single one, the request:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;

class RequestArgumentControllerResolver implements ControllerResolverInterface
{
    protected $resolver;

    public function __construct(ControllerResolverInterface $resolver)
    {
        $this->resolver = $resolver;
    }

    public function getController(Request $request)
    {
        return $this->resolver->getController($request, $controller);
    }

    public function getArguments(Request $request, $controller)
    {
        return [$request];
    }
}

Extend the existing controller resolver with the newly defined decorator:
$app['controller_resolver'] = $app->share($app->extend('controller_resolver', function ($resolver, $app) {
    return new RequestArgumentControllerResolver($resolver);
}));

Note: This is just one way of doing it. You don't have to decorate, you can also replace the resolver completely if you like. And obviously this is just a very basic example of only passing a single arg to the controller, you can do something more sophisticated.
Comment: Thanks, this example pointed me in the right direction and helped solve my problem.


Server not powering on after upgraded to Intel Xeon E5-2695 v2

Question: Have a ProLiant DL360p Gen8. Old CPUs were E5-2670. Upgraded HP latest ROM
Server does not power on any more. See amber LED light on the CPU in the Systems Insight Display.
As far as I know this CPU is supported on this server. What am I missing?
Comment: Can power on after putting old CPUs back.
Comment: Have you updated all firmware using the SPP?
Comment: I downloaded SP99341.exe and followed the instructions
Comment: You need to get that special firmware to go to v2 CPUs on Gen8 servers - https://serverfault.com/a/774990/13325
Answer: Ah I remembered this one, it'd dropped out of my memory sorry, just remembered. There was an extra step you need to do when going from v1 Xeons to v2's - HPE made a service advisory for it, you need to download the ISO file, put it on a USB stick and run it with the v1 Xeon's in it, only then will you be able to go to v2's - here's the link, it was a bit of a pain but it worked fine; https://support.hpe.com/hpsc/doc/public/display?docId=c03911173
Comment: Sounds promising! Will test it out.
Comment: Yeah, sorry I forgot about it, we had to do it to loads of BL460c's at the time, it was a few years ago and I"m getting old - I'm sure it'll sort out the problem


Truth table, clarification of $2^n$ row rule?

Question: My question is about truth tables and specifically why there is $2^n$ rows for $n$ inputs in a truth table?
I understand that there's a finite amount of states a variable can be in, here it's 2 - true (1) and false (0). What I don't understand is why is it growing exponentially, is there some intuitive explanation I'm missing?
When I write it out, I understand that in every column is exactly n true(1) states and n false(0) states. So, the $2^n$ certainly works, but I'd like to understand why and how it works.
Can anyone help out? Thanks!
Comment: I apologize if I wasn't clear enough, but I meant to say the total sum of all entries is 2n because n true(1) states + n false(0) states = 2n states.
Answer: It's a counting problem. It is based on the following:
Product Rule: If one even can occur in $k$ different ways, and a second event can occur in $m$ different ways, then the number of ways in which both events can occur is $km$.
That is, there are $k$ possible outcomes for the first event, and $m$ for the second, so there are $km$ total possible combinations of outcomes.
The truth table has one row for every possibility. Each variable has two possible outcomes: true or false. If there are $n$ different variables, then you have two possibilities for each, and the number of total combinations is the product of the number of possible outcomes for each. That amounts to a product of $2$ with itself, $n$ times, or $2^n$.
Inductively: one variable has $2$ possible outcomes. Assume that $k$ variables have $2^k$ possible outcomes. How many possible outcomes are there for $k+1$ variables? There are $2^k$ ways in which you can have outcomes in which the last variable is false, and another $2^k$ ways in which you can have outcomes in which the last variable is true. So there is a total of $2^k+2^k = 2(2^k) = 2^{k+1}$ different possible outcomes.
Answer: It's because each input can either be in 2 states: on (true) or off (false). Also, in each truth table, there are $n$  inputs. So, we have $2^n$ total rows for this truth table.
However, if we had a different kind of table where each input could be in 3 different states (left, right, center), then the total number of outcomes would be $3^n$.
Hence, you always want to take the number of states possible (2 for truth tables) and raise that to the power of how many inputs you have.
Hope this helps.
Comment: Thanks for the good will to answer, yes, that is correct... But that's just an application of the rule, I'm more interested in why and how the rule works. Mr. Arturo Magidin captured the essence of my question, if you are interested in what I meant.
Answer: While Arturo Magidin is certainly correct in his answer, there is another simple way to illustrate this. That is through an analogy to decimal numbers via binary numbers.
Just like decimal numbers goes from $k$ digits to $k + 1$ digits (e.g. from $999$ to $1000$) when the combinations in the first $k$ digits are exhausted, so does binary (e.g. from $111$ to $1000$ in binary notation), so the construction of binary numbers is quite the same as the decimal numbers that we all feel well at home with.
The difference for binary numbers is in the number of possibilities for each digit. For decimal numbers we have $10$ such possibilities, $0$ through $9$, and thus we have that there is $10^3 = 1000$ possible combinations ($000$ through $999$) of $3$ decimal digits; in binary numbers there is only $0$ and $1$. Just as we intuitively see that with $3$ decimal digits we can create all the combinations up to $10^3 - 1 = 999$ it holds true that for a three digit binary number you can create all the combinations up to $2^3 - 1 = 7$ (or $111$ in binary notation), accounting for a total of $2^3$ combinations including $000$.
Now, for every row in a truth table you can form a binary number by representing it as a string of ones and zeroes. Therefore, according to the above reasoning, if you have $n$ columns in your truth table you must have $2^n$ rows to cover all possible combinations.
Comment: As an upshot of this, if you assign all 0s to all atomic variables in the first row, then all 0s except for the last atomic variable which you make a 1, and so on, you can enumerate the rows of a truth table via binary numbers.


In mixed effects linear model(MEM), does random effects take variance from fixed effects?

Question: I have a question regarding mixed linear effects model. For example, now I have 100 patients, and each patient has generated 10 to 30 eggs. So the dataset has 2500 rows (one egg per row). The response variable 'mature' is a binary one, 1 means this egg matures and 0 means not mature. We are interested in a variable called 'genotype' which is a trait per patient. So all the rows of same patient will have same genotype, but different patient could have same genotypes. There are 9 different genotypes. We also have some covariates, age and BMI.
So I want to see if genotypes associate with maturation of eggs. I know several options:

Logistic regression: This one works but it assumes all eggs are independent, but we know eggs from same patient relate to each other.
Generalized Mixed effects model: Similar to 1 but add a random effects of patient. I am confused about this one because I worried that the random effects(patient) would take away variation which could be explained by genotype, because genotype is the same to certain patient. I am not sure about this.

So this is my question: can I use Generalized Mixed effects model in this case to check relationship between genotype and egg maturation? If I can, which means the random effects is not designed to take away variance which should go to any fixed effects, how should I test the coefficient on genotype in this case, anova? If not, what is the best solution to this question? Aggregate the data to one patient one row and do Generalized linear model with beta distributed response (maturation rate), and put number of eggs per patient as weight?
Thank you for any input.
Answer: First, a comment: a logistic regression is totally fine for both your cases 1 and 2, and I think the question is whether to include person-level intercepts, and whether they are random or fixed effects, rather than what distribution the response should have. You've got a collection of binary random variables so you can't be wrong to say each one is Bernoulli distributed.

Let $y_{ij}$ be the measurement for egg $j$ from person $i$, where $i = 1, \dots, m=1000$ and $j = 1, \dots, n_i \leq 30$, and let $x_i \in \mathbb R^{11}$ give the person-level covariates for the 9 genotypes along with age and BMI.
It seems that you're comparing the following two models:
$\newcommand{\ilogit}{\text{logit}^{-1}}$
$$
P(y_{ij} = 1) = \ilogit(\mu + \alpha_i + x_i^T\beta) \tag{M1}\label{1}
$$
where $\alpha \sim \mathcal N(0, \sigma^2_\alpha I_m)$ is a random intercept, and
$$
P(y_{ij} = 1) = \ilogit(\mu + x_i^T\beta) \tag{M2}\label{2}
$$
where now there is no person-level effect at all. Also really these are both conditioned on $x_i$ but I'm omitting that for simplicity.
$\ref{1}$ allows for correlation between eggs for a particular person, while $\ref{2}$ ignores this and says that when $x = 0$ we should predict the same thing for everybody, rather than having a unique baseline prediction per person.
Without even going to the statistics of the model, is $\ref{2}$ really reasonable? This should be your main concern. We know in general that there's variation in stuff like this between people, so scientifically I think $\ref{2}$ is probably a bad model. You want to model the things you know, and if one of those things is that the eggs from a given person are likely to be correlated, then you should explicitly account for this.
Now statistically, here's a heuristic way to picture what adding $\alpha$ does to your model. Our linear predictor is $\eta = \mu\mathbf 1 + X\beta + Z\alpha$ and
$$
Z = \mathbf 1_{n_1} \oplus \dots \oplus \mathbf 1_{n_m}
=\left(\begin{array}{ccccc}1 & 0& 0 & \dots & 0 \\
1 & 0 & 0& \dots & 0 \\
\vdots & \vdots & \vdots &  \dots & \vdots \\ 0 & 1 & 0 & \dots & 0 \\ 0 & 1 & 0 & \dots & 0 \\ \vdots & \vdots & \vdots &  \dots & \vdots \\ 0 & 0 & 0 & \dots & 1 \\ 0 & 0 & 0 & \dots & 1 \end{array}\right).
$$
If we were doing a fixed effects linear regression, we could picture this as follows: in order to estimate $\beta$, first we project $y$ into the space orthogonal to $Z$. This means we're effectively centering each person's egg measurements. Then for each coefficient $\beta_j$ we look at what is explained by that variable after we've further made $y$ orthogonal to the other 10 predictors.
With our random intercept the idea is similar, although because of the shrinkage we no longer exactly have orthogonal projections. But I think it's fair to still think of $Z\alpha$ as effectively centering each person, and i think that gives us a better measurement of the fixed effect trends, because otherwise we might be thinking there's a trend when it's really just caused by a (partial) correlation between age, say, and the baseline.
Maybe a succinct way to answer the question in your title is that adding a predictor will increase the variance explained, but a fixed effect like age attempts to describe the part of the data orthogonal to the other predictors, so we sometimes get a much clearer picture by deliberately removing variation.
As to whether the $\alpha_i$ should be treated as random or fixed, I don't think anyone would argue that they make sense as a fixed effect, so I'm not going to discuss that further.

Update
In response to your comments: regarding your question 1, I go through the math of what i'm talking about here. By adding an additional predictor you probably will indeed explain more of total variation and $R^2$ will probably increase. But that isn't necessarily good or bad. What matters for a single predictor is the explained variation after the other predictors are accounted for, and that's what I show in that linked answer of mine. So adding $Z$ we are now forcing age to only explain the part of the variation that is not explained by the other predictors, which now includes a person-level intercept. But in cases like this that can be a good thing.
Here's an example: we've got a linear regression with two predictors, a continuous x and a binary grp. In this case it turns out that x is correlated with grp in that when grp=2, x is larger. But y is actually only a function of grp.
Here's what the data look like. You can see that within a group there's no relationship between x and y, but due to the correlation between x and grp if we just do the model y ~ x then the slope will be significant, i.e. we will think we've learned something. But really x is confounded with grp, and once we've accounted for grp, as we do when we look at the residuals of the model y ~ grp, we see then that x explains basically nothing of the remaining variation.

That's why it's so important to include person-level intercepts if you think there's a reason for them to be there: if you don't include them you may be inviting confounding between your other predictors and the group level effects which are still there, just unmodeled. This can lead you to have confounded effects appear significant which would be a pretty serious mistake if it could have so easily been avoided.
Here's the code for the example:
set.seed(123)
dat <- data.frame(
  grp=rep(1:2, each=25),
  x=rnorm(50, rep(c(0,10), each=25))
)
dat$y <- dat$grp + rnorm(50, 0, .25)

summary(m.full <- lm(y~., data=dat))
summary(m.x <- lm(y~x, data=dat))

par(mfcol=c(1,2))
plot(y~x, data=dat, col=ifelse(dat$grp==1, "red", "blue"), pch=19, main="Original Data")
legend("topleft", c("group 1", "group 2"), col=c("red", "blue"), pch=19, bty="n")
legend("bottomright", "regression line for y~x", bty='n', lwd=2)
abline(m.x, lwd=2)

m.grp <- lm(y~grp, data=dat)
resid.grp <- resid(m.grp)

plot(resid.grp ~ x, data=dat,col=ifelse(dat$grp==1, "red", "blue"), pch=19, main="Residuals of y ~ grp versus x")
legend("bottom", c("group 1", "group 2"), col=c("red", "blue"), pch=19, bty="n")
legend("top", "resid ~ x", bty="n", lwd=2)
abline(lm(resid.grp ~ dat$x), lwd=2)

par(mfcol=c(1,1))

Comment: Thank you very much for your detailed answer! Two questions: 1. When you are saying 'beta is estimated after making y orthogonal to Z', if I understand this right, does it mean that the part of variance in y which could be explained by Z or age individually, now will be explained by Z? So are we underestimating age's effect in this case? This is what I worried.
Comment: Sorry the second question is, if use fixed effect for patient, does this use a lot more degrees of freedom and lower the power of this model?
Comment: @LiSun i've just added an update to better explain what i mean by that orthogonalizing
Comment: @LiSun regarding your second comment, fixed effects do indeed use more degrees of freedom because they're not shrunk. I don't really work with power computations so i don't want to answer that without some more thought and say something wrong but i suspect you're right. I personally generally prefer random effects when appropriate because they have better predictive ability. The estimates are much more stable for groups with small numbers of observations and i often have factors with lot of levels, and you can make predictions for levels you never saw when training which is pretty neat
Comment: Thank you very much for your patience and nice presentation of your answer. I totally agree with you about your opinion. However, what if, in your example, there is only 1 possible 'x' value in each 'grp'? Which is the case in my study, 1 patient('grp') could have only 1 genotype('x'). In this case, the 'real effects' of x could be attributed to grp, because they are perfectly correlated now. So my question is in this case, what should I do.
Comment: @LiSun you're very welcome, I'm glad this is helpful. If i'm understanding your question correctly, it seems like you're describing something like the extreme case where you have say 10 patients and for each one you measure a different genotype. Then i think you have patient and genotype effects confounded and you won't be able to separate the two without making assumptions on those effects. Unfortunately when you have confounding like that i think sometimes you may not be able to salvage the experiment, and the best you can do is know to avoid it in the future
Comment: Thank you. Yes you are right, the patient effects and genotype are confounded because genotype is specific to patient. However, genotype has much less levels (3). So I am thinking we just need a model where each patient is an observation, not each egg. So the response becomes a probability or binomial with different n (but known) to each patient, instead of just 0 and 1. In R, glm function can actually take a matrix with 2 columns (first one is number of success and second one is number of failure), this seems to fit. But I don't know  for sure if this is working this way.


prevent ?DeleteDocument URL option for Domino

Question: I store attachments in a Notes document and based upon the field value of a parent document I would prevent that users could user the ?DeleteDocument URL option somehow.
https://www.ibm.com/support/knowledgecenter/en/SSVRGU_9.0.1/basic/H_ABOUT_DOMINO_URL_COMMANDS_4332.html
The user is registered as Author on the document containing the attachments.
What options do I have?
Comment: ACL- Remove the "delete documents" rights on the DB and implement your own soft delete function. I normally set a Field "Deleted" to the current timestamp and filter all relevant views with ... & deleted=""  .. So the authors are still able to move things into trash...
Answer: I've implemented this in two ways.
Like umeli wrote, in the ACL remove the "delete documents" rights from people, but finesse this by allowing servers to retain deletion rights.
In a CRM database I set the Database Script QueryDocumentDelete routine to assign 'continue' the value 'False'.  If the user is in the Notes Client, then give them a dialog with something like "Please raise a Support Request with a justification to delete this document".  Operations could then set the form field to 'Garbage' and server automation would delete the document on schedule.
In an SaaS application a soft-delete similar to the technique umeli suggests was implemented.


htaccess para web.config

Question: Mudei o meu site para a plataforma Windows Azure e o servidor deles é IIS e o meu antigo era apache então as rotas configuradas no htaccess não estão funcionando, preciso saber como faço para converter isto:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

php_value short_open_tag off

RewriteCond %{HTTP_HOST} ^meusite\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.meusite\.com\.br$

Em web.config(parecido com xml) para funcionar no IIS
Comment: Você pode usar um covnersor online para testar: [Link](http://cbsa.com.br/tools/online-convert-htaccess-to-web-config.aspx)
Comment: Legal, mas ele converte apenas o `RewriteRule`
Answer:
A conversão pelo URL Rewrite (você pode instalar no seu IIS local e gere a saída pelo arquivo .htaccess) fica em um arquivo web.config dessa forma, baseado no seu .htaccess da questão:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Nesse link também possui vários estilos de arquivos (.htaccess), que você pode se basear para que seu sistema funcione no seu IIS do Windows Azure e nesse link um outro exemplo prático do assunto.
Referências:

IIS HOME
Translate .htaccess Content to IIS web.config
Microsoft Azure
Comment: Nossa deu certo, valeu! eu até tinha conseguido de uma forma parecida mas estava dando erro na hora de encontrar os arquivos css e imagens, mas do seu jeito deu certo!
Comment: @SilvioAndorinha legal ... !!! :)

htaccess para web.config


Rolling a die six times in a row

Question:
How many ways are there of rolling a die six times in a row such that:
(a) there are exactly four consecutive $3$'s somewhere?
(b) there are at least four consecutive $3$'s somewhere? (my approach:
take complement)
(c) there are more $3$'s than $4$'s?

Part (a) attempt: should I consider the four $3$'s as one block? This would mean that the possibilities would be $R_1 R_2 R_3 R_4, R_2 R_3 R_4 R_5, R_3 R_4 R_5 R_6,$ This would mean that there are three ways to roll four consecutive 3's.
Part (b) attempt:
Case 1: four consecutive $3$'s: From part (a) there are $3$ ways
Case 2: five consecutive $3$'s: $R_1 R_2 R_3 R_4 R_5, R_2 R_3 R_4 R_5 R_6$ $\rightarrow$ So there are $2$ ways
Case 3: six consecutive $3$'s: There is only one way to do this since we are rolling the die six times in a row.
Adding all these cases: $3+2+1=6$ ways.
Comment: In counting the number of ways of obtaining exactly four consecutive threes, keep in mind that each of the remaining positions in the sequence can be filled in five ways (one of the other possible outcomes of a die roll).  For at least four consecutive threes, I suggest using the [Inclusion-Exclusion Principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle).
Answer:
How many ways are there of rolling a die six times in a row such that there are exactly four consecutive threes?

We need to consider cases, depending on whether the string of consecutive threes begins with the first roll, second roll, or third roll.  Let $R_i$, $1 \leq i \leq 3$, be the event that the string of exactly four consecutive threes begins with roll $i$.
$|R_1|$:  There must be a three in each of the first four positions.  The fifth position must be filled with a number other than $3$, which can occur in five ways.  The sixth position can be filled by any of the six possible outcomes of a die roll.  Hence, there are $5 \cdot 6$ ways to have exactly four consecutive threes in six rolls of a die if the string of four consecutive threes begins in the first position.
$|R_2|$:  There must be a three in each of the four middle positions.  Thus, the first and last rolls must be filled by a number other than $3$.   Thus, there are $5^2$ sequences of six die rolls in which there are exactly four consecutive threes beginning in the second position.
$|R_3|$:  By symmetry, $|R_3| = |R_1|$ since the four consecutive threes must occupy the last four positions, which means the second position cannot be a $3$ and the first position can be any of the possible outcomes for a die roll.
Hence, the number of ways of rolling a die six times so that there are exactly four consecutive threes is
$$|R_1| + |R_2| + |R_3| = 5 \cdot 6 + 5^2 + 5 \cdot 6 = 30 + 25 + 30 = 85$$

How many ways are there of rolling a die six times in a row such that there are at least four consecutive threes?

Let $R_i$ be the event that there are four consecutive threes beginning in the $i$th position, where $1 \leq i \leq 3$.  Notice that the word exactly was not used in the description of $R_i$.
Observe that to have five consecutive threes, there are two possibilities:

There must be four consecutive threes beginning in the first position and four consecutive threes beginning in the second position.
There must be four consecutive threes beginning in the first position and four consecutive threes beginning in the third position.

To have six consecutive threes, there must be four consecutive threes beginning in the first position and four consecutive threes beginning in the second position and four consecutive threes beginning in the third position.
Thus, the set of events in which at least four consecutive threes are rolled is
$R_1 \cup R_2 \cup R_3$.  By the Inclusion-Exclusion Principle,
$$|R_1 \cup R_2 \cup R_3| = |R_1| + |R_2| + |R_3| - |R_1 \cap R_2| - |R_1 \cap R_3| - |R_2 \cap R_3| + |R_1 \cap R_2 \cap R_3|$$
$|R_1|$:  Each of the first four positions must be filled with a $3$.  The remaining two positions can each be filled in six ways.  Hence, $|R_1| = 6^2$.  By symmetry,
$|R_1| = |R_2| = |R_3|$.
$|R_1 \cap R_2|$:  Each of the first five positions must be filled with a $3$.  The remaining position can be filled in six ways.  Hence, $|R_1 \cap R_2| = 6$.  By symmetry, $|R_1 \cap R_2| = |R_2 \cap R_3|$.
$|R_1 \cap R_3|$:  Each of the six positions must be filled with a $3$.  Hence, $|R_1 \cap R_3| = 1$.
$|R_1 \cap R_2 \cap R_3|$:  Each of the six positions must be filled with a $3$.  Hence, $|R_1 \cap R_2 \cap R_3| = 1$.
Therefore, by the Inclusion-Exclusion Principle, the number of ways of rolling a die six times and obtaining at least four consecutive threes is
$$|R_1 \cup R_2 \cup R_3| = 6^2 + 6^2 + 6^2 - 6 - 1 - 6 + 1 = 96$$

How many ways are there of rolling a die six times in a row such that there are more threes than fours?

By symmetry, there are an equal number of outcomes with more threes than fours as there are with more fours than threes.  Thus, the number of outcomes in which there are more threes than fours can be found by subtracting the number of outcomes in which the number of threes and the number of fours are equal from the total number of outcomes, then dividing the result by two.
Comment: I obtained the same answers when doing this question.

Rolling a die six times in a row


General theorem to cover arguments by simple function approximation

Question: A standard technique for proving facts about integrals is to argue through each stage of the integral's definition. For example:
Let $(\Omega, \mathcal{F}, \mu)$ be a measure space. Suppose one wants to prove that the integral is linear. That is, for measurable $f$ and $g$, and $\alpha, \beta \in \mathbb{R}$ we have
$$\int (\alpha f + \beta g) d\mu = \alpha \int f d \mu + \beta \int g d\mu.$$
One first considers the case in which $f$ and $g$ are indicator functions. One then considers simple $f$ and $g$ and uses the integral's linearity. One then considers $f,g \geq 0$, approximates by simple functions and uses the monotone convergence theorem. And, finally, one proves the general case by decomposing $f$ and $g$ into positive and negative parts.
This sort of argument is so ubiquitous that David Williams, in his book Probability with Martingales, refers to it as the "standard machine". (It is used in the proofs of many other classical results. Two that come to mind now are the change of variable theorem and Fubini's theorem.)
Question: Is there a general theorem that one can appeal to instead of making the standard machine argument again and again?
(If so, and this is not a mathematical question so much as a sociological one, why do textbooks prefer to repeat the standard machine argument instead of appealing to the general theorem?)
I believe I can partially explain why the argument works. For example, the collection of measurable functions is exactly the set of simple functions, closed under pointwise limits; the simple functions are dense in $L^{p}$ space; etc. But, still, it would be nice to have a theorem that covers all (or most) cases in which one is tempted to argue with the standard machine, and I don't know of one.
Comment: Have a look at the monotone class theorem (for functions).
Comment: @saz Thank you, that's helpful. I'm not sure that settles the question though. Don't monotone class arguments require one to rehearse what is essentially the standard machine? Would it be sufficient, in the example given of linearity, to demonstrate the result for indicator functions and then state, "the general result follows immediately from the monotone class theorem"?
Comment: The monotone class theorem (for functions)  requires the functions to be **bounded** (and on the other hand, the class of sets needs only to be a $\pi$ system).  So, although related to the "standard machine", it does NOT replace it directly.
.
Answer: It is a nice question.

Short Answer: The "standard machine" argument is a schema of proof with several small variations on the conditions. Capturing all those variations would result either in several theorems or having to define a complex condition to cover all the variations where we use to apply the the "standard machine" argument.
That is why in the books the authors prefer to have  the "standard machine" argument as a proof schema and not capture it as general theorem.

Let us explore the answer in more detail.
A good way to do it is by trying to have a "standard machine" theorem to replace the usage of the "standard machine" argument.
Consider the following "standard machine" theorem:

Theorem 1: Let $(\Omega, \mathcal{F}, \mu)$ be a measure space. Let $S$ be a set of measurable functions. Suppose the four following four conditions holds for $S$:

If $f$ is the indicator function of a set in $\mathcal{F}$, then $f \in S$

If $f, g \in S$,  then, for any $\alpha , \beta \geq 0$, $\alpha f + \beta g \in S$.

If $\{f_n\}$ is a pointwise increasing sequence of positive functions in $S$ and $f_n$ converges monotonically to a measurable function $f$, then $f \in S$.

For any $f$ measurable function, if $f^+ , f^- \in S$, then $f \in S$.

Then, all measurable functions are in $S$.

This theorem is correct and it can be proved in a standard way (using the "standard machine" argument).
BUT, it is NOT as useful as it may seem at a first sight. To understand this point, consider, for instance,  proving that the integral is linear. The theorem does not apply because the integral is not defined on the set of all measurable functions (consider, in the Real line Lebesgue measurable space, the function $f= -1\chi_{(-\infty,0)}+ 1\chi_{[0,\infty)}$).
What went wrong? When we apply the "standard machine" argument to prove that the integral is linear, the conclusion we get is the the integral is linear on the set of measurable functions with finite integrals. So we restrict ourselves to a certain class of measurable functions, namely those of finite integrals. This restriction of having finite integral makes the proof work.
Of course, the class of measurable functions to which we need to restrict the "standard machine" argument depends on what we want to prove. It may be the class of measurable functions "having finite integral" or "being finite a.e." or "being bounded" or etc...
Now we face two paths: either we have maybe six or seven slightly different versions of the "standard machine" theorem or we write a version "restricted" to a generic class $C$ of measurable functions.  Let us try the second path.

"Theorem 2": Let $(\Omega, \mathcal{F}, \mu)$ be a measure space. Let $C$ be a set of measurable functions and  let $S \subseteq C$. Suppose the four following four conditions holds for $S$:

If $f \in C $ is the indicator function of a set in $\mathcal{F}$, then $f \in S$

If $f, g \in S$,  then, for any $\alpha , \beta \geq 0$, $\alpha f + \beta g \in S$.

If $\{f_n\}$ is a pointwise increasing sequence of positive functions in $S$ and $f_n$ converges monotonically to a function $f \in C$, then $f \in S$.

For any $f$ measurable function, if $f^+ , f^- \in S$, then $f \in S$.

Then, $S=C$.

Now, we can use this "theorem" to prove the linearity of the integral. Let $C$ be the set of measurable functions with finite integral and let $S$ be a maximal subset of $C$ such that the integral is linear on $S$. We prove that $S$ satisfies conditions 1 to 4 and we get the conclusion $S=C$, which means that the integral is linear on $C$.
Unfortunately, "Theorem 2" is not a theorem, it is not true. Consider the Real line Lebesgue measurable space. Let $C$ to be the set of measurable functions which are either linear or has the form $\alpha\chi_{[0,1]}$ (where $\alpha \in \mathbb{R}$). Let $S$ be the set  measurable functions of the form $\alpha\chi_{[0,1]}$ (where $\alpha \in \mathbb{R}$). We have that $S\subseteq C$ and the four conditions hold but it is not true that $S=C$.
We clearly that the issue in "Theorem 2" is that there was no condition imposed on class $C$. "Theorem 2" was too general to be true. If we want to correct it we need now to find the adequate restrictions that need to be imposed. Those restriction should be enough weak to preserve results like theorem 1 and other cases where we correctly apply the "standard machine" argument, but must also be enough strong to rule out the pathological counterexample (as the one just presented above).
Anyway, the final result will be a theorem more complex to use than the "standard machine" argument, because in the theorem you would first have to define $C$ and $S$, prove the $C$ satisfies the restrictions, and prove that $S$ satisfies the 4 conditions. Then, you could evoke the theorem to get the result.
Conclusion: The "standard machine" argument is a schema of proof with several small variations on the conditions. Capturing all those variations would result either in several theorems or having to define a complex condition to cover all the variations where we use to apply the the "standard machine" argument.
That is why in the books the authors prefer to have the "standard machine" argument as a proof schema and not capture it as general theorem.
Comment: Thank you! This is very helpful.


Equivalence between trace and Euclidean norm

Question: In the paper "On best approximate solutions of linear matrix equations", there is a very small equivalence I don't know where it comes from.
Let $A$ be a matrix (either real or complex), and $\|A\|$ be "the sum of the squares of the moduli of the elements of $A$" (sic; I believe it's the Euclidean norm of $A$), and $tr(\cdot)$ is the trace operator. I want to prove that $\|A\| = tr(A^{*}A)$.
I attempted to check this with $A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \\ \end{bmatrix}$, but $\|A\| = 30$ and $tr(A*A) = 29$.
What am I doing wrong? I think $*$ is the matrix multiplication operator, but it could also be the generalized inverse.
Comment: As Bye_World wrote in now-deleted answer, the notation $A^*A$ means the product of the conjugate-transpose of $A$ and of $A$ itself.
Answer: It's not $A*A$, it's $A^*A$ where $A^*$ is the transpose of $A$.  If you calculate $\operatorname{tr}(A^*A)$ (called the Frobenius norm$^\dagger$) you'll find that it equals $\|A\|$.
$^\dagger$: Technically this is the square of the Frobenius norm.