How to align several different Material UI select components?

Question: i am trying to align different Material UI select components in my application.
in the image you can see that the components are not aligned.
how can i give these components the same style, so that they line up next to each other.
This is the code that i'm using for the button that is not on the same line as the other components(see image):
import React, { useEffect, useState, FunctionComponent, useRef, useCallback } from 'react'
import { Toolbar, Snackbar, Box, Grid, TextField, Select, MenuItem, Button, FormControl, InputLabel, Checkbox, Input, ListItemText } from '@material-ui/core'
import { RouteComponentProps } from '@reach/router'
import { useStyles } from '../Common/Style.css'
import ChartElement from '../Components/Chart'

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
    PaperProps: {
        style: {
            maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
            width: 250,
        },
    },
};

                            <FormControl className={classes.formControl}>
                            <InputLabel id="demo-mutiple-checkbox-label">kerk</InputLabel>
                            <Select
                                labelId="demo-mutiple-checkbox-label"
                                id="demo-mutiple-checkbox"
                                multiple
                                value={personName}
                                onChange={onChangeKerk}
                                input={<Input />}
                                renderValue={(selected) => (selected as string[]).join(', ')}
                                MenuProps={MenuProps}
                            >
                                {churches.map((name) => (
                                    <MenuItem key={name} value={name}>
                                        <Checkbox checked={personName.indexOf(name) > -1} />
                                        <ListItemText primary={name} />
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>

this is the code that i'm using for the buttons that are on one line with the others(see image):
                            <TextField
                            id="Startdatum"
                            label="Startdatum"
                            onChange={onChangeStartDatum}
                            defaultValue={startDatum}
                            type="date"
                            InputLabelProps={{
                                shrink: true,
                            }}
                        />
                        <TextField
                            id="Einddatum"
                            label="Einddatum"
                            onChange={onChangeEindDatum}
                            defaultValue={eindDatum}
                            type="date"
                            InputLabelProps={{
                                shrink: true,
                            }}
                        />
                        <FormControl className={classes.formControl}>
                            <InputLabel htmlFor="age-native-simple">Maanden</InputLabel>
                            <Select
                            native
                            value={currentOption}
                            onChange={onChangeFixedDate}
                            inputProps={{
                                name: 'age',
                                id: 'age-native-simple',
                            }}
                            >
                            <option value={"All"}>All</option>
                            <option value={"3 months"}>3 months</option>
                            </Select>
                        </FormControl>

update after adding grids to code:
<Grid justify="center" alignItems="center" direction="row">
            <Toolbar className={classes.toolbar}>
                <Grid item lg={6} md={12} xs={12}>

{"DASHBOARD"}

                </Grid>

                <Grid item lg={1} md={12} xs={12}>
                    <FormControl className={classes.formControl}>
                        <Select
                            labelId="demo-mutiple-checkbox-label"
                            id="demo-mutiple-checkbox"
                            multiple
                            value={churchName}
                            onChange={onChangeChurch}
                            input={<Input />}
                            renderValue={(selected) => (selected as string[]).join(', ')}
                            MenuProps={MenuProps}
                        >
                            {churches.map((name) => (
                                <MenuItem key={name} value={name}>
                                    <Checkbox checked={churchName.indexOf(name) > -1} />
                                    <ListItemText primary={name} />
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>
                </Grid>
                <Grid item lg={12} md={12} xs={10}>
                    <TextField
                        id="Startdatum"
                        label="Startdatum"
                        onChange={onChangeStartDatum}
                        value={startDatum}
                        type="date"
                        InputLabelProps={{
                            shrink: true,
                        }}
                    />
                    <TextField
                        id="Einddatum"
                        label="Einddatum"
                        onChange={onChangeEindDatum}
                        value={eindDatum}
                        type="date"
                        InputLabelProps={{
                            shrink: true,
                        }}
                    />
                </Grid>
                <Grid item lg={8} md={12} xs={12}>
                    <FormControl className={classes.formControl}>
                        <InputLabel htmlFor="age-native-simple">Maanden</InputLabel>
                        <Select
                            native
                            value={currentOption}
                            onChange={onChangeFixedDate}
                            inputProps={{
                                name: 'age',
                                id: 'age-native-simple',
                            }}
                        >
                            <option value={"All"}>All</option>
                            <option value={"3 months"}>3 months</option>
                        </Select>
                    </FormControl>
                </Grid>
                {/*<Button id="refresh" onClick={onClick} variant="contained" color="primary">
                            ↺
                        </Button>*/}
            </Toolbar>
        </Grid>

My components now look like this:(see image)

after some adjustment to the width en height, i still can't get the component on the left in lign with the others. Any idea how to fix this?
Answer: You have imported the <Grid> element, but you are not using it. Why not? Surround the items you want to align into a <Grid> element, and pass the justify, alignItems and direction attributes. Example code snippet that will align items both vertically and horizontally:
<Grid justify="center" alignItems="center" direction="row">
     --- your code and components go here---
</Grid>

The complete documentation for the <Grid> element can be found here, on the Material UI website:
https://material-ui.com/components/grid/
You can additionally specify the total relative width of each element by passing the item attribute into the <Grid> element, relative for different viewports (large, medium and small):
<Grid item lg={6} md={12} xs={12}>
      --- your code and components go here---
</Grid>

Comment: after adding the grids to my code and some adjustment to the width en height, i still can't get the component on the left in lign with the others. Any idea how to fix this? ( i updated the question with my current code en image)
Comment: It might be helpful to wrap all the `` items into a `` object.


Missing User-agent directive! Found Allow - what does this mean?

Question: I ran my site through http://www.frobee.com/robots-txt-check and it came back with a few errors.
Here is my robots.txt file:
<code>User-agent: *
Disallow: /admin/

# Allowable Index
Allow: /*?p=
Allow: /blog/
Allow: /catalog/seo_sitemap/category/
Allow: /catalogsearch/result/

# Directories
Disallow: /404/
Disallow: /app/
Disallow: /cgi-bin/
Disallow: /downloader/
Disallow: /includes/
Disallow: /js/
Disallow: /lib/
Disallow: /magento/
Disallow: /media/
Disallow: /pkginfo/
Disallow: /report/
Disallow: /skin/
Disallow: /stats/
Disallow: /var/

# Paths (clean URLs)
Disallow: /index.php/
Disallow: /catalog/product_compare/
Disallow: /catalog/category/view/
Disallow: /catalog/product/view/
Disallow: /catalogsearch/
Disallow: /checkout/
Disallow: /control/
Disallow: /contacts/
Disallow: /customer/
Disallow: /customize/
Disallow: /newsletter/
Disallow: /poll/
Disallow: /review/
Disallow: /sendfriend/
Disallow: /tag/
Disallow: /wishlist/

 # Files
 Disallow: /cron.php
 Disallow: /cron.sh
 Disallow: /error_log
 Disallow: /install.php
 Disallow: /LICENSE.html
 Disallow: /LICENSE.txt
 Disallow: /LICENSE_AFL.txt
 Disallow: /STATUS.txt

 # Paths (no clean URLs)
 Disallow: /*.js$
 Disallow: /*.css$
 Disallow: /*.php$
 Disallow: /*?p=*&
 Disallow: /*?SID=
 Disallow: /*?*
</code>
The errors I get are 'Missing User-agent directive! Found Allow' and 'Missing User-agent directive! Found Disallow'. I'm not sure why?
Thanks
Answer: In robots.txt empty lines are used to separate multiple directives. Just remove or comment the empty lines and you should be fine.
Comment: You could comment the empty lines out (`#`) if you like to keep the visual separation.


Java else part is not getting executed

Question: I am having a piece of if-else code to check if a string is displayed, to my surprise the Else part is not getting executed at all.
For eg: If the error string is shown, the IF part works fine. In cases where the error string is not shown, the Else part is not getting executed. Kindly help
if(getErrText.length() > 0) {
    System.out.println(getErrText + " For "+ readerIterator);
} else {
    System.out.println(" Error is not displayed - Err Cell" + " For "+ readerIterator);
}

Comment: Check what gets returned when you call `getErrText.length()`. Make sure to trim the `getErrText` string if necessary.
Comment: Just add System.out.println("'" + getErrText + "'" ); before the if-statement and see what is inside of it when you think the else part should be executed.
Comment: Does the program continue executing when the "else" part is not executed? Or does the program throw an exception when the "else" part is not executed?
Answer: When I make a few assumptions,
public static void main(String[] args) {
  String getErrText = ""; // <--------------- To trigger else.
  String readerIterator = "Yes it is"; // <-- To display a message.
  if (getErrText.length() > 0) { // <-------- else means that getErrText **must** be ""
    System.out.println(getErrText + " For "
        + readerIterator);
  } else {
    System.out.println("Error is not displayed "
        + "- Err Cell For " + readerIterator);
  }
}

Output is
Error is not displayed - Err Cell For Yes it is

As I would expect.
Edit
As per comment(s), your actual problem is likely to be one of
// trim() the String!
if (getErrText != null && getErrText.trim().length() > 0) {
  // as before...
}

or silently swallowing your exception. Please don't do that.
try {
  getErrText = toSearch.errorCell.getText();
  getErrText = (getErrText != null) ? getErrText.trim() : "";
}catch(Exception e){
  e.printStackTrace();
}

Comment: Thankyou It worked cool ! I did an Exception catch and designed as you suggested. cool !
Answer: You are probably enclosing this within a block where error is set which is why your getErrText length is always greater than zero.
Could you please add your enclosing code for getting the error text please

In case you else is not getting executed, print the if part of your code and debug.
If both your if and else dont get executed, then the flow is not reaching your if-else at all for those scenarios .
Comment: try{

             getErrText = toSearch.errorCell.getText();

            }catch(Exception E){

            }
Comment: Change your if to System.out.println(":"+getErrText + ": For "+ readerIterator) and see what it prints when you are expecting it to be of zero length
Answer: To find out your problem, print the error on your else:
System.out.println(" Error is not displayed - Err Cell" + " For "+ readerIterator+" The getErrText is ["+getErrText+"]);

Comment: It would be empty there. Look at the if test.
Comment: Empty has length 0. If it was anything but empty the getErrText would be shown.
Comment: And the if block would be entered (not the else).
Comment: You are saying that the length HAS to be zero. Makes sense.

Java else part is not getting executed


Core Update to 8.9.4 Removed Block Visibility Options?

Question: Recently updated core from 8.9.2 to 8.9.4, in doing so the options to place blocks on specify pages is now gone?
Comment: Those don't look like the normal options from core.
Comment: @4k4 Yes! Thank you for that, I spent way too much time tearing apart configs trying to hunt it down.
Answer: I still see it
"Drupal core 8.9.4"
Comment: I recommend that this issue be closed because it is a duplicate of https://drupal.stackexchange.com/questions/296372/block-visibility-role-section-is-missing/296378#296378


Irrational meter - why the mark of a triplet in 4 half notes

Question: Can someone please explain to me why the mark of a triplet in this 4 half notes? I understood how to play it but from what i read you can only write triplets on 3 notes like 3 eighths 3 quarters etc...
See picture
Comment: @Artelius -- a time signature is not a fraction, and _irrational time signature_ has an entirely different meaning than _irrational number_.
Comment: There are whole, half, quarter etc. notes, but nothing that shows third. So, to me, the 4/3 time signature is somewhat pointless, as to show 'proper' notes, they need to have the 'triplet' sign. I reckon it could be written out in standard form and make more sense.
Comment: Because there is no notehead shape that alone depicts 1/3 note. there's 1/2, 1/4,1/8, but no 1/3. Same reason as triplets themselves.
Comment: I'm fairly certain that there are better ways to show what needs playing rather than use irrational meters. Judging by the question, I'm not alone.
Comment: My comment was tongue in cheek. Music and mathematics go hand in hand, though, and I think this is somewhat of an unfortunate (dare I say, irrational?) terminology. Also, in my view a time signature _is_ a fraction (but it is not _just_ a fraction). As a fraction it indicates how many whole notes fit in a bar. Of course it has other, perhaps more important meanings.
Comment: hi Tim thanks but why they need to have the triplets signs?
Comment: so from your answer, I get that stating the time signature 4/3 is not enough for this? I mean if I saw sheet music like that I would understand from the time signature alone the way I should play it. that is why I am confused.
Comment: I don't see what's irrational about it? Any fraction of two integers is _by definition_ a rational number. But now, I'd love to see sqrt(2) used in a time signature...
Comment: @Artelius - maybe not hand in hand. 6/8 =3/4?
Comment: @Tim what? 3/4 of a whole note fits a 3 4 measure. 3/4 of a whole note fits in a 6 8 measure. (Or, a half note and quarter note, if you prefer.) That was my point. 3 4 and 6 8 time have a different beat of course so it is not just about fractional values.

Also further to the topic of irrational numbers, the golden ratio is supposed to have inherent beauty; I wonder what could be done with some multiple of 1.618 beats per measure...
Answer: The problem is, that tuplet just means some note length modification takes place. Mathematically you require a standard fraction with numerator and denominator and there seem to be different opinions which of those to put into the tuplet bracket.
Wikipedia suggest under Tuplet Notation a full fraction representation in the form 2:3 for exotic cases, but I have never seen one.
So counting the note values and looking at the current time signature may be necessary for resolution.
Answer: To answer your last question:  the use of 'triplet' indicator is allowable for any length note. It tells you to play the three marked notes so that each takes up 1/3 the meter-time that would have normally been covered by two of the notes in question.  Thus, in quarter time meter,   a one-beat triplet is written with eighth notes (normally two per quarter note), a two-beat triplet is written with quarter notes, etc.
The use of anything other than 2,4,8,16 as the denominator of the designated meter is highly discouraged, especially among those of us who have to perform the piece.
Comment: For one thing, you can also have _non_-triplet (or other tuplets but 3) notes in such a bar. But even if you don't have them in the bar, it can be an effect to put single 4/3 bar in a piece in 4/4 – writing the same thing without an irrational signature would require two awkward tempo-change marks.
Comment: So if it was 6/5 time signature and there were 5 half notes i would but the number 5 benith the notes? Even if it does not makes sense :-)?
Comment: "highly discouraged" – that seems a bit of a fogyish attitude, no? Normal odd time signatures like 5/4 were probably also highly discouraged at some point, but I'd argue that it's very much a good thing that they eventually become widespread for where it makes sense. Sure you _could_ denote that all in 4/4 with silly incompletely meters, but with a 5/4 signature it can get more directly to the musical intention. I don't see why that would be fundamentally different with irrational signatures.
Comment: @leftaroundabout  It is different because there are no symbols for **notes** that have anything other than 2^(-k) duration.  Thus no point in an N/3 time signature.
Comment: Um, yes there are such symbols: _tuplets_.
Comment: Ummm, no, that is a deviation from the actual note symbol which requires the "3" indicator.  Why would you write   4/3 time and then go ahead and write some half-notes with a "3" over them?  Other than composer-wanking, it serves no purpose.
Answer: According to 4/2 (four two) time signature bottom number 2 is a relative value of the Whole note representing two Half notes that are equal to a Semibreve or a Whole note. Upper number says how many of the bottom numbers, so there are four Half notes in a bar and Half note becomes the Beat unit which is equivalent to one beat thus Whole note is 2 beats long.
Triplet is the most common type of Tuplet is a group of notes played in the space of other notes basically two of the same rhythmic value.
Since every measure here is made up of 4  standard Half notes, two Triplet groups can be played in which a total of six Triplet Half notes
can be found in a Bar.
So 4/3 is not considered as a regular time signature used in Western music where 3rd note(doesn't exist) gets the beat, it tells simply there are 4 of the Triplet Half notes in the bar indicated by 3 implying an
incomplete 4/2 bar with 2 triplet half notes missing to be played at a faster pace than the 2nd Bar that makes it an irrational measure.


Group Recyclerview Items that getting from a Json

Question: I am getting a Json output from the server.
This is my Json look like
{
  "feed": [
    {
      "order_no": "70000004",
      "quotation_no": "abc004a"
    },
    {
      "order_no": "70000003",
      "quotation_no": "abc003a"
    },
    {
      "order_no": "70000001",
      "quotation_no": "abc001a"
    },
    {
      "order_no": "70000001",
      "quotation_no": "abc001b"
    }
  ]
}

I know how to populate this in a recyclerview. But what I want is grouping this json using order_no and populate. For example there are two 70000001. So i only need to show one 70000001 order no.
This is my custom row .xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/white">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:layout_marginTop="2dp"
        android:background="@color/white">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#dbdbda"
            android:orientation="vertical">

            <TextView
                android:id="@+id/parent_list_item"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:paddingTop="10dp"
                android:text="Parent Title"
                android:textColor="@color/primaryColorText"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/parent_q_item_one"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:paddingTop="2dp"
                android:text="Q Title"
                android:textColor="@color/secondaryColorText"
                android:textSize="12sp" />

            <TextView
                android:id="@+id/parent_q_item_two"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:paddingTop="2dp"
                android:text="Q Title"
                android:textColor="@color/secondaryColorText"
                android:textSize="12sp" />

        </LinearLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>

After grouping, I need to show only one order_no in parent_list_item (70000001) and under that I need to show one quotation_no in the first text view and second quotation_no in the second text view under same order_no
My adapter class
public class OrderQuatationHistory extends RecyclerView.Adapter<OrderQuatationHistory.ItemViewHolder> {

    private LayoutInflater layoutInflater;
    private ArrayList<OrderHistoryData> orderHistoryDataArrayList;

    public OrderQuatationHistory() {
    }

    public OrderQuatationHistory(Context context) {
        orderHistoryDataArrayList = new ArrayList<>();
        layoutInflater = LayoutInflater.from(context);
    }

    public void setOrderHistoryList(ArrayList<OrderHistoryData> orderHistoryDataArrayList) {
        this.orderHistoryDataArrayList = orderHistoryDataArrayList;
        notifyItemRangeChanged(0, orderHistoryDataArrayList.size());
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.custom_order_history_p_row, parent, false);
        ItemViewHolder itemViewHolder = new ItemViewHolder(view);
        return itemViewHolder;
    }

    @Override
    public void onBindViewHolder(ItemViewHolder holder, int position) {
        OrderHistoryData orderHistoryData = orderHistoryDataArrayList.get(position);
            holder.orderNo.setText(orderHistoryData.getOrderNo());
            holder.quotationNo.setText(orderHistoryData.getQuotationNo());
    }

    @Override
    public int getItemCount() {
        return orderHistoryDataArrayList.size();
    }

    public static class ItemViewHolder extends RecyclerView.ViewHolder {
        private TextView orderNo,quotationNo;

        public ItemViewHolder(View itemView) {
            super(itemView);
            orderNo = (TextView) itemView.findViewById(R.id.parent_list_item);
            quotationNo = (TextView) itemView.findViewById(R.id.parent_q_list);
        }
    }
}

Comment: I would maybe go with filtering the list before passing it to adapter/recycler view. Maybe some Map, or better with some For loop. Maybe not that good option, but in the future it would be much easier to update and handle (if you need multiple, group by something else, sort by name, sort by date)
Comment: You're creating it with ArrayList size of zero, so it calls getItemCount to know how many times it will run onBindViewHolder. Since size equal to zero it returns no view. BaseAdapter works this way so I think RecyclerView.Adapter is similar.
Answer: Try this... For avoiding of duplicate value,you can use this Method.
ArrayList<Integer> jSonOrder=new ArrayList();

int order_no= assigned values that you have retrieved from JSon.
   if (!jSonOrder.contains(order_no)) {
     jSonOrder.add(order_no);
   }


ORA-1691: unable to extend lob segment

Question: Estou fazendo uma carga de um banco oracle para outro banco e no momento da transferência dos arquivos de uma tabela de Anexo ocorreu este erro após algum tempo: ORA-1691.
Lendo um pouco vi que tem relação com espaço de armazenamento mas não sei como verificar o tamanho atual nem o que solicitar a equipe de infra. Seria "aumentar o tablespace"? Mas para quantos MB devo pedir esse aumento?
Tem como consultar isso via select no banco sem ser owner?
Answer: Para saber o tamanho de uma tablespace é necessário saber o tamanho dos arquivos de dados que constituem esta tablespace.
Para isto podemos utilizar as seguintes querys para verificar o tamanho de um banco de dados.
— Tamanho do banco
select sum(bytes) / 1024 / 1024 / 1024 tamanho_GB from dba_segments;

— ou
select sum(bytes) /1073741824  TAMANHO_GB from dba_segments;

— Tamanho por Tablespace
select tablespace_name, sum(bytes) / 1024 / 1024 / 1024 tamanho_GB from dba_segments group by tablespace_name;

Comment: Valeu Dante vou fazer um teste aqui e retorno já.
Comment: Preciso de alguma permissão especial para executar este select? Executei tanto na origem quanto no destino mas diz que a tabela dba_segments não existe.
Comment: Só precisa ser o Owner do banco...
Comment: Não sou owner. Vou entrar em contato com o suporte

ORA-1691: unable to extend lob segment


Add filter buttons to datagrid column headers

Question: I have a working datagrid and I'm exploring ways to add a filter button to my header columns much like how the new Excel does it. The rough sketch below demonstrates the desired functionality. Ideally the button would appear in the top right, if clicked once it would show an itemBox (or something more appropriately) and if clicked again it would close the itemBox.

So far I've been trying to add a button (step 1) to the Connection Status column but its not coming up.
<DataGridTemplateColumn Header="ConnectionStatus" MinWidth="33">
                    <DataGridTemplateColumn.HeaderStyle>

                    </DataGridTemplateColumn.HeaderStyle>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Ellipse Height="15" Width="15" StrokeThickness="2" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource OnlineStatusConverterStyle}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

My question is how do i set up my headers in order to get a button to show up?
Answer: I would use DataGridColumn.HeaderTemplate. You can make a reusable DataTemplate and leave the Header property for the actual content. Here's a quick example I threw together:
<DataGrid>
    <DataGrid.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>

                <ContentControl Content="{Binding}" VerticalAlignment="Center"/>
                <ToggleButton Name="FilterButton" Grid.Column="1" Content="▼" Margin="2, 1, 1, 1" Padding="1, 0"/>
                <Popup IsOpen="{Binding ElementName=FilterButton, Path=IsChecked}" PlacementTarget="{Binding ElementName=FilterButton}" StaysOpen="False">
                    <Border Background="White" Padding="3">
                        <TextBlock>Some Filters Here</TextBlock>
                    </Border>
                </Popup>
            </Grid>
        </DataTemplate>
    </DataGrid.Resources>

    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Column 1" HeaderTemplate="{StaticResource HeaderTemplate}"/>
        <DataGridTemplateColumn Header="Column 2" HeaderTemplate="{StaticResource HeaderTemplate}"/>
    </DataGrid.Columns>
</DataGrid>

Comment: I love the template approach. Now, do I make different templates for each of the columns? this is because some columns will have different filters.
Comment: @user2529011 Hmm, I don't think so. I would try to keep one header template and then use code or bindings to customize the `Popup`, since that's the only thing that's changing and everything is will be consistent. For example, you can use the `Popup.Opened` event and then change `Popu.Child` dynamically.
Comment: I like this method. Okay, this is enough to get me going. Again, thanks so much.


Radon space and Polish space.

Question: This should be simple but could not understand. This refers to the link:
http://en.wikipedia.org/wiki/Polish_space
where it mentions that: Lusin spaces, Suslin spaces, and Radon spaces are generalizations of Polish spaces.
I did not understand why it is said as generalization. Would you please point out what I am missing.
Answer: If $P$ and $Q$ are possible properties of some class $\mathscr{C}$ of mathematical objects, we say that $P$ generalizes $Q$ if every object with property $Q$ also has property $P$. In other words, the class of objects in $\mathscr{C}$ having property $Q$ is a subclass of the class of objects in $\mathscr{C}$ having property $P$. Unless the properties are actually equivalent, this means that there are objects in $\mathscr{C}$ that have $P$ but not $Q$: the property $P$ characterizes a larger, more general class of objects than does the property $Q$.
Here the objects are topological spaces. Let $\langle X,\tau\rangle$ be a topological space.

$\langle X,\tau\rangle$ is Lusin if there is some topology $\tau'\subseteq\tau$ such that $\langle X,\tau'\rangle$ is Polish; if $\langle X,\tau\rangle$ is already Polish, then we can take $\tau'=\tau$, so every Polish space is automatically a Lusin space.
$\langle X,\tau\rangle$ is Suslin if there are a Polish space $\langle Y,\tau'\rangle$ and a continuous surjection $f:Y\to X$. If $\langle X,\tau\rangle$ is already Polish, we may take $Y=X$ and $\tau'=\tau$, so every Polish space is automatically a Suslin space.
Finally, every Suslin space is known to be a Radon space, meaning that every finite Borel measure on it is inner regular, and we've already seen that every Polish space is Suslin, so every Polish space is Radon.

Thus, the properties of being Lusin, Suslin, or Radon are more general than the property of being Polish: every Polish space is Lusin, Suslin, and Radon, but there are Lusin (Suslin, Radon, resp.) spaces that are not Polish. A result that is true of all Lusin spaces, for instance, is more general than one that is true merely of all Polish spaces, because it holds also for the Lusin spaces that are not Polish.
Comment: @Creator: You're very welcome.
Comment: I think, there is a mistake in Wikipedia. A space $X$ is called Lusin if there is a bijective continuous map $f : Y \to X$ from a Polish space $Y$. Equivalently, $X$ is Lusin if there is a **stronger** topology $\tau' \supseteq \tau$ on $X$ under which $X$ is Polish.

Radon space and Polish space.


Let $K$ be an $o$-symmetric body, that covers $X$. Does it imply $\operatorname{conv}(X)\subset X+K$?

Question: The question is inspired by the answer (and a comment) of daw at Covering of a polytope by balls with midpoints at the vertices
Let $K\subset \mathbb R^n$ be an $o$-symmetric ($K=-K$) convex body. Does $X\subset K$ imply $\operatorname{conv}(X)\subset X+K$? We already know, that it's true, if $K$ is an euclidean ball or ellipsoid.
Comment: Please revise the title of your question as it is math-only. Titles like this are discouraged for technical reasons - see [Guidelines for good use of $\rm\LaTeX$ in question titles](http://meta.math.stackexchange.com/a/9730).
Comment: Ok, thank you, i'm sorry. I've edited it.
Answer: Here is a counterexample. Take $K$ to be the unit $1$-ball in $\Bbb{R}^3$:
$$K = \{(x, y, z) : |x| + |y| + |z| \le 1\},$$
and
$$X = \{e_1, e_2, e_3\} = \{(1, 0, 0), (0, 1, 0), (0, 0, 1)\},$$
respectively. Note that $x \in X + K$ if and only if $\|x - e_i\|_1 \le 1$ for $i = 1, 2, 3$.
If we consider the point $x = (1/3, 1/3, 1/3)$, then we see that $\|x - e_i\| = \frac{4}{3} > 1$ for all $i$, so $x \in \operatorname{conv} X \setminus  (X + K)$, proving the conjecture false.
Comment: Thank you :) So, the claim is false in general :(
Comment: @Jochen Yep. But, if you're interested in making this a trilogy, you could consider the least $\lambda_n \ge 0$ such that $X \subseteq K \implies \operatorname{conv} X \subseteq X + \lambda_n K$ for all symmetric bodies $K$ and $X \subseteq \Bbb{R}^n$ ($n$ is fixed). I suspect it will be helpful to remember Caratheodory's theorem: any element of $\operatorname{conv} X$ is a convex combination of at most $n + 1$ elements.
Comment: Using the same idea, one can find counterexamples for $p<2$ close to $2$: Take $K$ be the unit $1$-ball in $\mathbb R^n$, $x=(1,\dots 1)/n$, and let $n\to\infty$.


Argument of (5,-5) in polar co-ordinate

Question: I am trying to convert $\ [5,-5]   $ into polar form.I determined the argument of this co-ordinate.
it is $\ \theta = \tan^{-1} \frac{-5}{5}= \frac{-\pi}{4}$.
As the co-ordinate is fourth-quadrant.So,its range should be $\ \frac{3\pi}{2} \lt \theta \lt 2\pi $ So,I modify it like this,
argument z $ \ = 2\pi-\frac{\pi}{4}=\frac{7\pi}{4} $.But the answer is $\ \frac{-\pi}{4} $
I don't know what i have done wrong.
Comment: it's basicaly the same
Comment: $\tan^{-1}$ is many-valued. The possible values of $\tan^{-1}(-1)$ are $-\frac{\pi}{4}+k\pi$ for integral $k$. One of your values uses $k=0$, the other uses $k=2$.
Comment: You have done nothing wrong. Check to see if there were additional instructions which specified a particular range for the answer, or whether you were advised to use a specific formula for finding the argument.
Comment: @SakethMalyala:  You need a range of $2\pi$ for the answer, not a range of $\pi$.  What is the angle of $(-3,3)?$
Comment: OOPS sorry i wasn't paying attention @RossMillikan
Answer: It is just a question of which representation is desired.  $\frac {-\pi}4$ and $\frac {7\pi}4$ represent the same direction.  Presumably whoever made the answer key expects arguments to be in the range $(-\pi,\pi]$ or $[-\pi,\pi)$and you are expecting arguments to be in the range $[0,2\pi)$.  They both work.
Comment: so.that means my answer is correct?

Argument of (5,-5) in polar co-ordinate


How to understand $E_0(\log f(x;\theta)-\log f(x;\theta_0)) \leq 0$ but $E_0(f(x;\theta)-f(x;\theta_0)) \geq 0$ in MLE?

Question: This problem is about maximum likelihood estimation. Let $f\left(x;\theta\right)$
be a parametric density function with unknown parameter $\theta$,
and denote $\theta_{0}$ the true value. By Jensen's inequality, we
have $E_{0}\left\{ \log f\left(x;\theta\right)-\log f\left(x;\theta_{0}\right)\right\} \leq0$,
where $E_{0}$ indicates that the expectation is under the true density
function $f\left(x;\theta_{0}\right)$. In general, we do not have
$E_0\left\{ f\left(x;\theta\right)-f\left(x;\theta_{0}\right)\right\} \leq0$ (c.f. the counter example below). This looks counter-intuitive for me. I thought the true density $f(x;\theta_0)$ should be the maximum in the sense that $E_0\left\{ f\left(x;\theta\right)-f\left(x;\theta_{0}\right)\right\} \leq0$. How to understand this? Why is $\log$ transformation indispensable?
Counter-example of $E_0\left\{ f\left(x;\theta\right)-f\left(x;\theta_{0}\right)\right\} \leq0$:
Consider a binary distribution. Let $\pi_{1}$ and $\pi_{2}=1-\pi_{1}$ be true distribution of $X\in\left\{ 0,1\right\} $,
and denote $p_{1}$ and $p_{2}=1-p_{1}$ a generic distritbuion of
$X$. Here $\pi_1=\Pr(X=0)$ and $p_1=\Pr(X=0)$. The expectation $E_{0}\left\{ f\left(x;\theta\right)-f\left(x;\theta_{0}\right)\right\} $
herein is
\begin{eqnarray*}
\pi_{1}\left(p_{1}-\pi_{1}\right)+\pi_{2}\left(p_{2}-\pi_{2}\right) & = & \pi_{1}\left(p_{1}-\pi_{1}\right)+\left(1-\pi_{1}\right)\left(\pi_{1}-p_{1}\right)\\
 & = & \left(2\pi_{1}-1\right)\left(p_{1}-\pi_{1}\right).
\end{eqnarray*}
In order to force $E_{0}\left\{ f\left(x;\theta\right)-f\left(x;\theta_{0}\right)\right\} >0$,
we simply need $\pi_{1}>1/2$ and $\pi_{1}<p_{1}\leq1$.
Comment: What does MLE have to do with this? The maximum-likelihood estimate of $\theta_0$ is $\hat{\theta}$ where $\hat{\theta}$ is the number for which $f(x;\theta)$, regarded as a function of $\theta$ (with $x$, the data, being fixed) has maximum value. It is the statistician's fondest hope that $\hat{\theta}$ is close to $\theta_0$. So how does $\hat{\theta}$ relate to the question asked here?
Comment: @DilipSarwate As an extreme estimator, the probability limit of MLE $\hat{\theta}$ is the solution of the minimization problem $\min_{\theta} E_0(\log f(x;\theta)-\log f(x;\theta_0))$.
Comment: The conjecture is wrong. I have found a counter-example in discrete case.
Answer: The Kullback-Leibler Information inequality holds for the logarithms of any two densities, irrespective of whether one of them is the "true" density describing some population. Therefore, it is equally true that
$$E_1\left\{ \log f\left(x;\theta_0\right)-\log f\left(x;\theta_1\right)\right\} \leq0$$
where I have indexed by $1$ the "other" density. We should view these as likelihood functions of the $\theta$'s treated as random variables, not as densities of $X$. This inequality simply states (in totally unscientific terms) that,  when you take the expectation of a concave function of "yourself" w.r.t "yourself" you obtain a value that is greater or equal than when you take the expectation of the same concave function of "yourself" w.r.t to "anybody else". This is a direct mathematical result holding under its specific premises - it is not a mathematical formulation of some intuitive truth.
As for the deeper intuition regarding "true" and "not true" densities: A density describes the allocation of probabilities among the population.  Assume we deal with discrete random variables, where the density actually gives the probabilities. So "average density" would mean "average probability". What kind of intuition can be attached to "average probability of the elements of a population/sample"? I don't see any - so to expect that this "average probability" should be greater when we sum-product the true density with itself compared to when we sum-product any other density with the true one, also bears no intuition. Why should in general hold that ($f(x)$ is the "true" density)
$$ \sum_i \left[f(x_i)\right]^2 - \sum_i f(x_i)g(x_i) >?0$$
Comment: @ Alecos Papadopoulos Thanks for your answer. It clarified a lot. The right thing I shall expect is not $E_0(f(X;\theta_0))\geq E_0(f(X;\theta))$, because as you said $E(f(X;\theta))$ is only the average "height" of the function $f(X;\theta)$. Given sample $X_1,\ldots, X_n$, what I should expect is that $f(X_1,\ldots,X_n;\theta_0) \geq f(X_1,\ldots,X_n;\theta)$ as $n\rightarrow \infty$.
When the samples are iid, $f(X_{1},\ldots,X_{n};\theta)=\prod_{i=1}^{n}f\left(X_{i};\theta\right)$.
Comment: ...As a monotone transformation, we expect that $\sum_{i=1}^{n}\log f\left(X_{i};\theta_{0}\right)\geq\sum_{i=1}^{n}\log f\left(X_{i};\theta\right)$.
By the LLN, we then can expect $E_{0}\left(\log f\left(X;\theta_{0}\right)\right)\geq E_{0}\left(\log f\left(X;\theta\right)\right)$. Things make better sense now.


Haystack raises "cannot import name 'MODEL_TO_ENCODING' from 'tiktoken.model"

Question: i am trying to build a Q&A System using haystack. I am following this tutorial.
When I try to import certain modules. e.g.:
from haystack.document_stores import ElasticsearchDocumentStore

I get:
ImportError: cannot import name 'MODEL_TO_ENCODING' from 'tiktoken.model' (c:\Users\xxx\AppData\Local\Programs\Python\Python311\Lib\site-packages\tiktoken\model.py)

Tried reinstalling haystack in iteration (big, medium large). Tried different devices.
Is this a problem with the library itself?
OS is windows.
Tried reinstalling the library, tried running python with and without venv.
Answer: The current fix is to pin the tiktoken version that is installed to the following:
pip install tiktoken>=0.3.2,<0.5.0"
There was a tiktoken release 0.5.0 a few hours ago that had a breaking change causing a problem with Haystack just as you reported. Pinning the installed version of tiktoken to any earlier version solves it.
The team behind Haystack is preparing a patch release as we speak so if you install Haystack in a fresh environment in a few hours it should automatically install the patch version 1.20.1 and the error should be gone.
Comment: `pip install farm-haystack==1.20.1` is the solution to this issue now that there is a new Haystack release.


Parameter learning of Markov random field

Question: Given a Markov random field $\mathcal{G} = (\mathcal{V},\mathcal{E})$, the corresponding density function to which is expressed by
$f(x) \propto \prod_{x\in\mathcal{V}} \psi_u(x) \prod_{(x_i,x_j)\in\mathcal{E}} \psi_p(x_i,x_j; \theta)$
where $\psi_u$ is the unary potential and $\psi_p$ is the pairwise potential.
Now assume $\psi_u$ is known, the structure of the MRF and the functional form of $\psi_p$ (which is Gaussian) are also given, is there any efficient method to estimate the common hyper-parameter $\theta$ for all the pairwise potentials?
MCMC is a good option, however, it's too costly in my case. I prefer some methods of computing the point-estimate of $\theta$.
Answer: Firstly, I don't know why you use the term hyperparameter as this is heavily used in Bayesian statistics.
Nonetheless, If $\Theta$ represents the parameters of a Gaussian MRF model (Covariance), then since you know its structure you can simply use the ML method as described in section 17.3.1 of book "The Elements of Statistical Learning: Data Mining, Inference, and Prediction" by Hastie et al. The problem is posed as a convex optimization one, in notation
$$logdet\Theta-trace(S\Theta)$$
$$ s.t. \quad \Theta \ge 0 \quad (property \ of \ covariance \ matrix)$$
The trick is to partition the sample covariance matrix $S$ into a $p-1 \times p-1$ matrix and a row, also leverage the known zeros in the Inverse Covariance $\Theta^{-1}$ since conditional independence implies zero entries in $\Theta^{-1}$.
The algorithm is described in section 17.1 p634. Computational cost is negligible, $\hat{\Theta}$ is calculated in $p$ rounds as it does not involve matrix inversions.
If you find this information relevant to your problem and you do not have access to the referred book, let me know i can provide you the algorithm.
Alternatively another method, known as Iterative Proportional Scaling,  is described in the book of Lauritzen. I can't tell you much about this approach I find it personally way too difficult to digest it, not to mention implementing it.
Hope that helps.
Comment: The Element of Statistical learning by Hastie et al. is freely available (by the authors): http://www.stanford.edu/~hastie/local.ftp/Springer/OLD/ESLII_print4.pdf
Comment: Thanks a lot for answering the question! I'm sorry that I was not clear enough. $\theta$ is the same for all the pairwise potential functions, so I don't want to solve the inverse covariance estimation problem. I think there is a simple way. What's more, the unary potential $\psi_u$ may not be Gaussian.


Merge MySQL Dump with Existing Table

Question: A user of a WordPress site with a Form plugin accidentally delete ALL of the entries for a specific form.
I went into the daily backup and I have a .sql file which has all of the data for the table that the form info is stored.
Now I need to merge that back into the database, but the dump uses INSERT INTO and stops immediately with an error because most of the entries already exist.
I tried using "ON DUPLICATE KEY UPDATE id=id", but it ignored everything.
I've been searching here and on Google for a couple hours without any kind of solution.
The basic of the dumps is:
LOCK TABLES `wp_frm_items` WRITE;
INSERT INTO `wp_frm_items` (`id`, `item_key`, `name`, `description`, `ip`, `form_id`, `post_id`, `user_id`, `parent_item_id`, `updated_by`, `created_at`, `updated_at`) VALUES (2737,'jb7x3c','Brad Pitt','a:2:{s:7:\"browser\";s:135:\"Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25\";s:8:\"referrer\";s:38:\"http://mysite/myform/\r\n\";}','192.168.1.1',6,0,NULL,NULL,NULL,'2013-06-30 15:09:20','2013-06-30 15:09:20');
UNLOCK TABLES;

ID #2737 exists, so I either want to ignore it or just update the existing table.
Seems like there would be an easy way to import data from a MySQL dump into an existing database.
ps. I'm trying to do this in phpMyAdmin
Answer: If the data has not changed for those rows, you can use REPLACE instead of INSERT.
If you want to skip rows, one possibility is to use a temporary table. Load the rows there and  DELETE those rows that have a id that exists in the old table.
DELETE FROM my_new_temptable AS temp WHERE temp.id IN (SELECT id FROM wp_frm_items)

Then just insert the remaining rows into wp_frm_items.
Or you can move the new rows to a temporary table before restoring from the dump and copy them from there back into original table. There are many possibilities.
Also, many SQL tools have table merging capabilities.

Merge MySQL Dump with Existing Table


Problem with openCV Mat "Sizes of input arguments do not match"

Question: Mat newMask = Mat::zeros(mask.size(), mask.type());

for (int i=0; i< 3; i++){
    Mat tray = Mat::zeros(mask.size(), mask.type());
    inRange(mask,i+1, i+1, tray);
    cv::erode(tray, tray, getStructuringElement(MORPH_RECT, cv::Size(5, 5)), cv::Point(-1, -1));
    newMask += tray;
}

That method should work?
I get a crash:

Sizes of input arguments do not match)
  The operation is neither 'array op
  array' (where arrays have the same
  size and the same number of channels),
  nor 'array op scalar', nor 'scalar op
  array' in function 'arithm_op'

At the line below:
newMask += tray;

Comment: Does it crash there if you remove one or both of the middle lines i.e. inRange and/or cv::erode?
Comment: if crash on this line "newMask += tray;". when I comment two previous I get another kind of crash
Answer: The channel numbers of your images are different. Thats the reason. You can simply change your code like this:
Mat newMask = Mat::zeros(mask.size(), mask.type());

cvtColor(newMask,newMask,CV_BGR2GRAY);
    for (int i=0; i< 3; i++){
        Mat tray = Mat::zeros(mask.size(), mask.type());
        inRange(mask,i+1, i+1, tray);
        cv::erode(tray, tray, getStructuringElement(MORPH_RECT, cv::Size(5, 5)), cv::Point(-1, -1));
        newMask += tray;
    }

You can also check this link which is mentioned the same problem.
Answer: Thanks Yunus,
now this code:
+ (Vec3f)getFeats:(Mat&)mask {
    Mat newMask = Mat::zeros(mask.size(), mask.type());

    cvtColor(newMask,newMask,COLOR_BGR2GRAY);
        for (int i=0; i< 3; i++){
            Mat tray = Mat::zeros(mask.size(), mask.type());
            inRange(mask,i+1, i+1, tray);
            cv::erode(tray, tray, getStructuringElement(MORPH_RECT, cv::Size(5, 5)), cv::Point(-1, -1));
            newMask += tray;
        }

    vector<vector<cv::Point> > contours;
    findContours( newMask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE );

    vector<float> v;
    for( int i = 0; i< contours.size(); i++ ){
        v.push_back(cv::contourArea(contours[i])/(mask.size[0]*mask.size[1]));
    }

    sort(v.begin(), v.end(), std::greater<float>());
    return Vec3f(v[0], v[1], v[2]);
}

crash on last line:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)


Particular solution of reducible to homogeneous equation

Question: Verify that $y=x-5$ is a particular solution of the equation $$\frac{dy}{dx} = \frac{2y+6}{x+y+1}\ .$$ This is when $y'=1$ but this is not given as a condition in the question. How would you write the answer to this question and why should $y'=1$?
Comment: Either I am underestimating this problem, or you are over thinking it?
Comment: They ask you to verify : so, replace $y$ by $x-5$ in the rhs and you kow that if $y=x-5$, $y'=1$.
Comment: @Mathmo123. It seems that the edit changed radically. Cheers :)
Comment: Sorry - it was my fault it was like that in the first place!!
Comment: I think it should be like this, otherwise $y=x-5$ is not a solution...
Answer: that is to verify when $y=x-5$ the equality is held.
Left side: $$\frac{dy}{dx}=\frac{d}{dx}(x-5)=1$$
Right side: $$\frac{2y+6}{x+y+1}=\frac{2(x-5)+6}{x+x-5+1}=\frac{2x-4}{2x-4}=1\quad(x\ne2)$$


For which values of a, b, c, d do $\theta_{a,b}$ and $\theta_{c,d}$ commute?

Question: In Sets and Groups by Green a question 5 from the chapter 3 reads:

Write $\theta_{a,b}$ for the map of the preceding exercise [which is $\theta(x)=ax+b=\theta_{a,b}$]. Prove $\theta_{a,b}\theta_{c,d}=\theta_{ac,ad+b}$, for any real numbers a, b, c, d. For which values of a, b, c, d do $\theta_{a,b}$ and $\theta_{c,d}$ commute?

I've done the prove and I'm interested in the last part of question. The answer reads "ad+b=bc+d". I've came up with "when a=c and b=d". Is it wrong?
Answer: Note that
$$
\theta_{a, b}\theta_{c, d} = \theta_{ac, ad+b}\\
\theta_{c, d}\theta_{a, b} = \theta_{ca, cb + d}
$$
We want these to be equal. Well, $ac = ca$ always, so the only thing we need is for the two second parameters, $ad + b$ and $bc + d$, to be equal. This will happen if $a = c$ and $b = d$, but there are other cases too, like
$$
\theta_{1, b}\theta_{1, d} = \theta_{1, d}\theta_{1, b}
$$
no matter what $b$ and $d$ are (which is to say, $(x+b)+d = (x+d)+b$).
It is, of course, paramount to point out that
$$
\theta_{p, q} = \theta_{s, t}\iff (p = s\,\land\,q = t)
$$
so the only way that the two composed maps above can be equal is if the parameters are equal.


Ie 6, 7 and 8(Compatibility mode) issues

Question: We have a site that works fine with any latest browser including ie8.
But it has lots of issues with ie6, ie7 and ie8(Compatibility mode).
We are using following doctype
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

So it is not using quirck mode.
Before i start digging into individual issues, just want to known if i am missing something or doing something wrong to go ie in some different mode other than standard?
I tried to find list of known issues with ie6 and ie7 when using w3c standards but didn't find much useful, but found just enough to confuse me.
Any known site where i can find known issues with old ie's when using w3c standards?
Answer: Here is one link that has a few fixes I used to use: http://hublog.hubmed.org/archives/001515.html
Answer: There are more conflicts and non-implementations than one should ever have to know. If you write standards-compliant websites, your websites will not work in IE6 or IE7. Most people special case IE6 and IE7 with special stylesheets to fix the breakage.
The IE6 PNG fix is especially common.
Answer: Here's a good overview of IE related CSS bugs.
Also, if you're not doing it already I strongly suggest you use a CSS reset (here's an example of one CSS reset there are others out there e.g. YUI CSS Reset) - bringing all browsers down to the same baseline and then working up will elminate a lot of inconsistencies without having to track them down individual and hunting for causes if they later appear.
Answer: By specifying what type of HTML document you are using at the top of your document you are taking the browser out of quirks mode. Now, the newer browsers are much more standards compliant and therefore easier to code with. Here are some tips that might help you out:

Use DIV instead of TABLE for layout
Watch out for Document Object Model or DOM differences between browsers
Here is a site with CSS compatibility info: http://www.quirksmode.org/css/contents.html
Run your code through W3C's Validator
Instead of W3C's free validator, consider purchasing a HTML validator which you can run on your machine. In my opinion a programmer wouldn't run a C# program without compiling, and web development shouldn't be done without some sort of validation program. It will save you oodles of time.

Sorry I can't post more links. Stack overflow will only allow me to post one.
Answer: To find out whether you are correctly picking up Standards Mode, enter:
javascript:alert(document.compatMode)

in the browser's address bar whilst your page is loaded. If you get 'CSS1Compat' you're sorted. If you get 'BackCompat', you're in quirks. This can happen in IE when you've put some stray bytes before the <!DOCTYPE declaration, for example a spurious <?xml declaration.

I tried to find list of known issues with ie6 and ie7

It would be quite long. Yes, even in Standards Mode. Anything in particular?


load paragraph in graphql

Question: i have a content type with "artist" and i have a paragraph type with "album" name. in album i have two field 1. name 2. release date.
i create a field with "field_album" name in "artist" content type that this field reference to paragraph. now i want write a query that show artist name and all albums with name and release date.
I create this query to load artist but i cant load paragraph.
<code>    query{
  nodeQuery(filter: {conditions:[{field:"title",value: ["artistname"], operator: EQUAL}]}){
    count
    entities {
      ...on NodeArtist{
        nid
        title
      }
    }
  }
}
</code>
Answer: for load paragraph query must like this
<code>query{
  nodeQuery(filter: {conditions:[{field:"title",value: ["artistname"], operator: EQUAL}]}){
    count
    entities {
      ...on NodeArtist{
        nid
        title
        fieldAlbum {
          entity{
            ... on ParagraphAlbum {
              fieldName
              fieldReleaseDate
            }
          }
        }
      }
    }
  }
}
</code>
https://github.com/drupal-graphql/graphql/issues/676#issuecomment-423912937

load paragraph in graphql


Mongo query Limit not showing in operation

Question: I`m using MongoDB.Driver for .NET to query Mongo(Version 3.0.11).  This is my code to query a field  and limit the query to 200 documents.
BsonDocument bson = new BsonDocument();
bson.Add("Field", "Value");
BsonDocumentFilterDefinition<ResultClass> filter      = new BsonDocumentFilterDefinition<ResultClass>(bson);
FindOptions                               queryOptions    = new FindOptions() { BatchSize = 200 };
List<ResultClass> result = new List<ResultClass>();
result.AddRange(myCollection.Find<ResultClass>(filter, queryOptions).Limit(200).ToList());

My issue is that when I check the database`s current operations, the operation query field shows only :

{ Field : "Value" }

Which is different from the query using "AsQueryable" below:
List<ResultClass> result = myCollection.AsQueryable<ResultClass>().Where(t => t.Field == "Value").Take(200)

Query operation using "AsQueryable"

{ aggregate: "CollectionName", pipeline: [ { $match: { Field:
  "Value" } }, { $limit: 200 } ], cursor: {} }

Why can't I see the limit in the query using Find?Is the limit being handled in the client side instead of the server?
I need to limit this in the server side but I can't use the second query because the field searched needs to be a string which can't be done using AsQueryable.
Answer: Using limit in the first piece of code executes the limit on a cursor object, which is still serverside until you actually request the document by invoking ToList(). At which point only 200 documents will go over the wire to your application.
It looks like the AsQueryable is executing an aggregation pipeline which will show up in currentOp, but both are essentially the same.
I'm not sure if there is a performance impact for either one though


Avoid recursivity with generic method to set class properties c#

Question: I follow to explain my problem in a much bigger class with an smaller easy to follow exact example.
I got quite a big class, with a lot of properties of different types, getting and setting their respective class variable.
public class Foo() {
    int property1 { get => _property1 ; set => _property1 = value;}
    string property2 { get => _property2 ; set => _property2 = value;}
    Vector3 property3 { get => _property3 ; set => _property3 = value;}
    bool property4 { get => _property3 ; set => _property4 = value;}
}

I put 4 properties in the example, but in the real example there are a lot.
I need to apply a logic in the set of all the properties, depending on property4 boolean, so instead of writting the same code in all the setters of my properties, I tried to make a generic method to be called in all of them.
So, I made a an enum:
public enum properties {
    property1,
    property2,
    property3,
    property4
}

So that I can set my properties with a method that involves reflection, taking the property type as an argument:
public void setLogic<T>(properties property, T value) {
    //irrelevant code
}

So my setters turn to be:
public class Foo() {
    int property1 { get => _property1 ; set { setLogic(properties.property1 , value) };}
    string property2 { get => _property2 ; set { setLogic(properties.property2 , value) };}
    Vector3 property3 { get => _property3 ; set { setLogic(properties.property3 , value) };}
    bool property4 { get => _property4 ; set{ _property4 = value) };}
}

My problem comes when in my setLogic() the property setter is called recursively producing a stack overflow. So I solved the topic with a boolean controlled from setLogic() that controlls where the setter is being called from.
So now my properties turn to be:
public class Foo() {
    int property1 {
        get => _property1;
        set {
            if (!_calledFromSetLogic)
                setLogic(properties.property1 , value);
            else {
                _property1 = value;
                _calledFromSetLogic = false;
            }
        }
    }
    string property2 {
        get => _property2;
        set {
            if (!_calledFromSetLogic)
                setLogic(properties.property2 , value);
            else {
                _property2 = value;
                _calledFromSetLogic = false;
            }
        }
    }
    Vector3 property3 {
        get => _property3;
        set {
            if (!_calledFromSetLogic)
                setLogic(properties.property3 , value);
            else {
                _property3 = value;
                _calledFromSetLogic = false;
            }
        }
    }
    bool property4 { get => property4; set{ _property4 = value) };}
}

The code works fine, but the setter bool control to avoid recursivity throws away all the possible cleannes brought by the SetLogic() generic method. On the other hand I cannot set the class variables in the setLogic method because I access the properties with reflection, so to set the new value in the logic I cannot avoid the recursive set without the boolean (property.SetValue() from the reflection class sets the new value calling the set once again, so infinite loop).
If I dont do this, I have to paste the setLogic() method, instead of been generic, copy pasted for each of the properties in the set, which is not very clean code neither.
Is there not a clean solution for this, where the setter can be passed as an argument, or a generic method that avoids infinite recursive set?
I was thinking of something like
private setLogic<T>(Action<> setterMethod, T value) {
    //so that the property involved might be already in the setter?
}

or other kind of setLogic with the generic class properties that avoids the infinite loop, of whom a cannot think of.
Hope I made myself understood.
Comment: My recommendation would be to back the property with a private field, and set that field in your setLogic function instead of calling the property setter. Alternately, check if the new value is the same as the existing value prior to calling the setter. Alternately, and I recommend this mainly because the only supplied reason for writing the code this way is cleanness, go back to using the first snippet - it is the cleanest of all of the available options in terms of standardization.
Comment: +1 for check if the new value is the same in the setter. Regarding "go back to using the first snippet" I explain why the required logic in the setter and not being able to access the private variables because I access the properties with reflection, makes not possible to use the first simple snippet, that would be the desirable thing
Comment: I'm sorry, I re-read the question now and can see why that was not a useful suggestion - post-work brain had me misinterpreting. I am glad Jeff E was better able to comprehend the reasoning behind the question.
Comment: Reflection is a very slow way to set a property value, as compared to setting it directly - and you haven't made clear for what purpose you are setting the properties in this way; as-is, the first code snippet is most definitely the cleanest, and you're "duplicating" code anyways by calling setLogic in all of the setters, just duplicating it a different way. In any case, you should include the setLogic function because as it stands this question lacks a lot of clarity and lacks a key component to determining why this is causing recursion.
Comment: The question is long. I tried to make clear what make the recursion here: (property.SetValue() from the reflection class sets the new value calling the set once again, so infinite loop). If there is any doubt on that or I can give any further explanation I will be glado to.
Comment: Regarding reflection being slow, the concren of this question is not eficiency, is to write clean/compact code. With the scenario I explained, I have to check setter with boolean so setters get long if there are lots of them. With no generic method, I have to write the exact same set logic code in all the setters. In both cases code gets long and repeated with exact same patterns so the question is if there could be any other more compact way for the code of this scenario
Answer: Are you able to just use a ref parameter to set the field directly?:
int property1
{
    get => _property1;
    set => setLogic(ref _property1, value);
}

private void setLogic<T>(ref T field, T value)
{
    field = value;
}

I commonly use this pattern when implementing INotifyPropertyChanged:
private int _someProperty;
public int SomeProperty
{
    get => _someProperty;
    set => SetProperty(ref _someProperty, value);
}

private void SetProperty<T>(ref T field, T value, [CallerMemberName] propertyName = "")
{
    if (!field.Equals(value))
    {
        field = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Comment: fck i was exactly writing this. I think this is the good way. As MVVM light setter.
Comment: This answer solves exactly the problem I exposed. Thanks a lot for the nailed anwer!! However, what I set is not a private variable, I get and set another property from a nested class so y get a compilation error when I try to pass that by reference: "a property or indexer may not be passed as an out or ref parameter". From here on I will try to figure out the best solution. Anyhow I am glad to be aware of this pattern for cleaner code :)
Answer: You could make use of the [CallerMemberName] attribute and a Dictionary<string, object> to store the properties in. This won't incur the same performance penalties reflection would.
For example...
class Foo : PropertyChangeNotifier
{
    public int property1 { get { return Get<int>(); } set { Set(value); } }
    public string property2 { get { return Get<string>(); } set { Set(value); } }
    public Vector3 property3 { get { return Get<Vector3>(); } set { Set(value); } }
    public bool property4 { get { return Get<bool>(); } set { Set(value); } }

    protected override void OnSet<T>(string property, T value)
    {
        // do something meaningful.
    }
}

...and the base class...
abstract class PropertyChangeNotifier
{
    private readonly Dictionary<string, object> properties = new Dictionary<string, object>();

    protected T Get<T>([CallerMemberName] string property = null)
    {
        return (T)properties[property];
    }

    protected void Set<T>(T value, [CallerMemberName] string property = null)
    {
        OnSet(property, value);
        properties[property] = value;
    }

    protected abstract void OnSet<T>(string property, T value);
}

Comment: Thanks for the answer, +1 for the proposal and for the // do something meaningful


auto.arima doesn't calculate AIC values for the majority of models

Question: I have manually discovered that the best model for my time series is the next one (AIC = 244.9):

But auto.arima function tells me that the best model is (0,1,0) with AIC = 247.93:

If I look at the trace I see:

Why can't auto.arima calculate AIC values for the majority of the models and returns Inf?
Answer: This is probably explained in the documentation. Looking the source code I found that Inf is reported when the likelihood of the model turns out to be infinity or when the lowest root in the polynomials of the model are lower than 1.01.
When the AR polynomial is close to be non-stationary or when the MA polynomial is close to be non-invertible, then the model is rejected by setting an infinite value for the AIC related to that model.
Inf * is reported when the ARIMA model couldn't be fitted and an error was returned by stats::arima.
For example, the following reports a value of the AIC equal to Inf
for the model ARIMA(2,1,2):
x <- diff(log(AirPassengers), 12)
auto.arima(x, ic="aic", seasonal=FALSE, allowdrift=FALSE, trace=TRUE)
# ARIMA(2,1,2)                    : Inf
# ARIMA(0,1,0)                    : -428.4098
# ... ... ...
# ARIMA(3,1,3)                    : -447.2594
# ARIMA(3,1,2)                    : -446.4202
# Best model: ARIMA(3,1,3)

Fitting this particular model, we can see that the MA polynomial is close to be non-invertible, that's why auto.arima sets a large value to the AIC
in order to make sure that this model is not chosen:
fit <- arima(x, order=c(2,1,2))
fit
# Coefficients:
#          ar1     ar2      ma1      ma2
#       0.2336  0.4912  -0.6445  -0.3554
# s.e.  0.2514  0.1824   0.2776   0.2761
AIC(fit)
# [1] -450.962

However, we can see that the MA polynomial is close to be non-invertible, that's why auto.arima sets a large value to the AIC in order to make sure that this model is not chosen:
# Roots of the AR polynomial (stationary)
abs(polyroot(c(1,-coef(fit)[c("ar1", "ar2")])))
# [1] 1.208756 1.684228
# Roots of the MA polynomial (the first is close to unity, < 1.01)
abs(polyroot(c(1,coef(fit)[c("ma1", "ma2")])))
# [1] 1.000013 2.813392

Comment: +1, Excellent, I would also add that if the optimization algorithm fails or produces error then auto.arima excludes the model from being considered. [The rationale here is that any model that is difficult to fit is probably not a good model for the data.](http://www.jstatsoft.org/v27/i03/paper)


show that the projection $f: X\rightarrow X$ is an equivalence relation

Question: Let X be a set and let $f: X\rightarrow X$ be a projection.
We define a relation on X such that $x \sim y$, means that there exist a natural numbers m and n such that $f^m(x)=f^n(y)$
($f^m$ means $f \circ f\circ ... \circ f$ $m$ times)
I´m suppose to show that this is equivalence relation. And I started doing this

$x\sim x$ $\space$  $f^m(x)=f^n(x)$ for all $x\in X$
If $x\sim y$ then $y\sim x$ $\space$   $f^m(x)=f^n(y) \Rightarrow f^m(y)=f^n(x)$
if $x\sim y$ and $y\sim z$ then $x\sim z$ $\space$ $f^m(x)=f^n(y) $ and  $f^m(y)=f^n(z)$ than  $f^m(x)=f^n(z)$

But than I though this might not be true if m does not equal n.
And im not really sure how to show this if m and n are not equal, so if anyone has some idea about it, it would help alot
Answer: The fact that $f$ is a projection doesn't seem to be useful.
For reflexity:
$$ \forall x \in X, \quad x = x \iff f^0(x) = f^0(x) \implies x \sim x $$
For symmetry if $x, y \in X$ are such that $x \sim y$ then there exists $n, m$ such that $f^n(x) =f^m(y)$. Then $f^m(y) = f^n(x)$ thus $y \sim x$.
For transitivity if $x \sim y$ and $y \sim z$ then there exists $n, m, k, l$ such that $f^n(x) = f^m(y)$ and $f^k(y) = f^l(z)$. Then $f^{kn}(x) = f^{km}(y) = f^{mk}(y) = f^{ml}(z)$ therefore $x \sim z$.
I think you're missing the fact that the $m$ and $n$ in the definition of $\sim$ are not fixed.


Should potentially multicollinear variables be dropped

Question: I did correlation analysis for a set of variables and calculated the VIFs. For a couple of independent variables, the VIF is less than 4, however the correlation coefficient with other input variables is >0.7. Should I omit the variables based on the VIF / correlation coefficient?
Comment: Is there any meaning behind these independent variables?  If the underlying theory that you are working with is based on these variables I would keep them.  If you are doing model selection, I would just look at the performance of your model with and without the variables, take a look at the  residuals and see how well the model fits.  Also check the coefficients in your model to check for any tell-tale signs of multicollinearity such as large coefficients with alternating signs.
Answer: There are a lot of different threshold values used for VIF - some workers are concerned at values as low as 4.0 (2.5 is the lowest I have seen - see http://statisticalhorizons.com/multicollinearity). So there are certainly researchers who would not consider your situation to be of concern.
Should you still think that the multicollinearity is a real problem in your case, it isn't necessary to go straight to dropping variables, for example, see this answer to a previous overlapping question: Applying Generalized Linear Model to a data with high collinearity


Differential forms and line integral in rotation group SO(3)

Question: My major is mechanical engineering. Recently, I am working on some subject involving three-dimensional finite rotations. More specially, the necessary and sufficient conditions for an applied torque/moment be conservative in the finite rotation range. I have tried to read some math books, but I got more confused. The following is the description of the background.
In mechanics, an externally torque generally exhibits unusual property of configuration-dependent, which means the torque varies from its initial value $\mathbf M_0$ to its current value $\mathbf M$ when moving along a curve lying on SO(3) staring form the identity $\mathbf I$ to the current position $\mathbf R$. In other words, the current counterpart $\mathbf M$ can be viewed as a $\mathbf explicit function$ of the rotation $\mathbf R \in SO(3) $.
Let $\mathbf \delta \omega$ be the spatial spin (an element which belongs to the tangent space of SO(3) at the base point $\mathbf R$, i.e., $\mathbf \delta \omega \in T_{R}SO(3)$). Then the virtual work done by the torque over the spin is given by
$$\delta W = \mathbf M \cdot \delta \omega$$
where $\delta W $ is a real number, and "$\cdot$" means dot product.
In mathematics, $\mathbf M$ is an element of cotangent space of SO(3) at the base point $\mathbf R$, i.e., $\mathbf M \in T^{*}_{R}SO(3)$.
On the other hand, if the rotation vector (axis-angle representation) $\mathbf \psi = \psi_{i} \mathbf e_{i}$ was used to parameterize the rotation manifold, $\mathbf R = exp(\hat \psi)$, then we can express the torque as $\mathbf M=\mathbf Q \mathbf M_0$ explicitly, where $\mathbf Q=\mathbf Q(\psi)$ is the transformation matrix relating the initial and current values of the torque.
We also can represent the virtual rotation by $\mathbf \delta \psi$, the variation of rotation vector $\mathbf \psi$, $\mathbf \delta \psi \in T_{I}SO(3)$. The relation between $\mathbf \delta \omega$ and $\mathbf \delta \psi$ is given by $ \delta \omega = \mathbf L \delta \psi$, where $\mathbf L= \mathbf L(\psi)$ is the tangential operator, $\mathbf L:T_ISO(3)\to T_RSO(3)$. Thus, the virtual work can be rewritten as
$$ \mathbf \delta W = \mathbf L^T \mathbf M \cdot \delta \psi$$
My questions are:

Which expression of the virtual work is a differental 1-form in SO(3) and why?
How to calculate the line integral of the virtual work over a curve lying on SO(3) in terms of a differential 1-form?

Thank you very much!
EDIT 1: In the above description, the spin $\mathbf \delta \omega$ is not a differential, since there does not exist a variable from which the spin can be derived. It comes from the variation of the orthogonality condition of rotation matrix, $\mathbf \delta(\mathbf R \mathbf R^T=\mathbf I)=0$,  $\mathbf \delta \mathbf R=\widehat (\delta\omega) \mathbf R$.
However, the variation $\mathbf \delta \psi$ of rotation vector is a differential.
Comment: I'm having some trouble parsing, but adding to Ted's comment, the differential one-form is the collection of all $\mathbf{M}$, viewed as a function on $SO(3)$ whose value at each point $p$ is an element of the cotangent space $T_{p}^{*}SO(3)$. It appears that $\mathbf{R}$ is some representation of a path in $SO(3)$; if that's right, the virtual work done "at time $t$" is $$\delta W = \mathbf{M}(\mathbf{R}(t)) \cdot \mathbf{R}'(t)\, dt,$$and the work is the integral over the parameter interval of $\mathbf{R}$.
Comment: Ok, thanks a lot.
Comment: As it stands, neither is a differential form, but rather an output when you apply the desired differential form to a tangent vector $\delta\omega$ as you move along your curve. But you want the first choice, moving along a path in the group. To compute an actual line integral, you'll need either coordinates or an understanding of how to express $\mathbf M$ explicitly as a function of the orthonormal frame $(e_1,e_2,e_3)\in SO(3)$.
Comment: I don't have time to write out a more detailed comment/response right now, but regarding your earlier comment, a line integral is *always* well-defined independent of parametrization of the curve; it's independent of *path* when the $1$-form is exact (or the force field conservative). But, yes, there's an invariant way to write $1$-forms on any Lie group. (I do not understand how you're thinking of parametrizing the rotation manifold. Care to elaborate?)
Comment: @JinsongYang You appear to be confusing differential 1-forms with differentials of 0-forms. So, a 0-form f is just a scalar-valued function on a manifold (in this example, SO(3)), and its differential df is indeed a 1-form. But, not all 1-forms arise in this way. For example, $\omega = \frac{-y}{x^2+y^2}\ dx + \frac{x}{x^2+y^2}\ dy$ is a differential 1-form defined on $\mathbb{R}^2 \backslash\ \{\vec{0}\}$, but it is not the differential of any 0-form on that set (Consider its integral over $S^1$). $\mathbf{M}$ *is* a 1-form.
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Also, on this site we use MathJaX to format our maths. [Here](http://meta.math.stackexchange.com/q/5020/145141) you can find a basic tutorial.
Comment: Thank you very much, Ted. I have updated my question. And yes, we can express $\mathbf M$ explicitly as a fucntion of the rotation vector $\mathbf \psi$. You mean we can calculate the line integral on the manifold SO(3) as vector calculus in terms of a set of local coordinates. Does there exist a way of coordinate-free to deal with the line integral? Since if a torque is conservative, then the line integal should be path-independent regardless of the local coordinates (the choice of parameterizations).
Comment: Thank you for your explanation, Andrew. $\mathbf R$ is the rotation matrix. In computational mechanics, several parameterizations of finite rotation were often considered, e.g., rotation matrix, rotation vector (axis-angle), quaternions, Euler angles.
Comment: Continued. Your equation is definitely right. However, in most of these parameterizations, the "differential" of the rotation parameter is not a true differental, since there does not exist such a variable from which the "differential" of the parameter can be derived. Consequently, the expression of the virtual work in terms of such rotation parameter cannot be integrated. Here comes my question 1, $\mathbf \delta \omega $ is not a differential, then is $\mathbf \delta W= \mathbf M \cdot \delta \omega$ still a differenrial 1-form?
Comment: Thank you for your time, Ted. In the context of computational mechanics, paramterizations of rotation manifold play important roles in both  theoretical and computational aspects. For instance, if the rotation vector (axis-angle) $\mathbf \psi=\psi_{i}\mathbf e_{i}$ was used,  the rotation matrix can be computed with Rodrigues formula $\mathbf R = I + {sin(\psi) \over \psi}  \hat  \psi+{(1-cos(\psi)) \over \psi^2}  \hat \psi ^{2} $. We can deal with finite rotation with only three components of rotation vector and get some other benifits.
Comment: Continued. The Rodrigues formula is a closed expression of exponential map $exp(\cdot):so(3)\to SO(3)$, $\mathbf R = exp(\hat \psi)$.
Comment: Continued. In fact, given any differential 1-form, if its exterior derivative is not 0, then it is not the differential of a 0-form (The one given above does have $d\omega = 0$, it just generates $H^1_{dR}(\mathbb{R}) \backslash\ \{\vec{0}\}$ and hence is not the exterior derivative of any 0-form). I'll post an answer on how to compute $\int_{[\mathbf{R}]} \mathbf{M}$ later. You'll need a coordinate patch on SO(3), a parameterization of $\mathbf{R}$ in the parameter space (or in SO(3) and you can pull it back to the parameter space), and then the integral is given by @AndrewD.Hwang 's post
Comment: Continued. Note $H^1_{dR}(SO(3)) = 0$ (https://topospaces.subwiki.org/wiki/Homology_of_real_projective_space and Universal Coefficients), so $\mathbf{M}$ is a differential of a 0-form ("has a scalar potential function") if and only if $d\mathbf{M} = 0$ as a differential 2-form.
Comment: Extra thought. (If $\mathbf{M}$ has a scalar potential function, you could use it to evaluate the line integral (!))
Answer: $\vec{r}: [0,2\pi] \times [0,\pi] \times [0,2\pi] \to \mathbb{R}^4$ given by $$\vec{r}(\psi,\theta,\phi)=\cos(\frac{\phi + \psi}{2})\cos(\frac{\theta}{2})c\hat{t}+\cos(\frac{\phi - \psi}{2})\sin(\frac{\theta}{2})\hat{i}+\sin(\frac{\phi - \psi}{2})\sin(\frac{\theta}{2})\hat{j}+\sin(\frac{\phi + \psi}{2})\cos(\frac{\theta}{2})\hat{k}$$ is a parametrization of $SO(3)$ by the angles yaw ($\psi$), pitch ($\theta$), and roll ($\phi$) https://pasteboard.co/JeFt2eK.png. (Actually, it is a parametrization of half of $S^3$, but, as long as we stay inside the coordinate patch, it will suffice. Note $S^3$ is a double cover, and the universal cover, of $SO(3)$; this is a single "sheet" in the covering space.) (Note $\hat{t}$ is the unit vector in the ''time direction'' and $c$ is the speed of light, converting time dimensions to space dimensions. You do not actually include $c$ in your calculations, $c\hat{t}$ is just heuristic for indicating a fourth spatial dimension.) (I forget which of the standard parametrizations -- rotation matrix, rotation vector (axis-angle), quaternions, Euler angles, etc. -- this is, but you probably know it off the top of your head. I suppose it is the quaternion parametrization.)
We need $\mathbf{R}$ to be oriented to do the integral (a change of orientation only changes the sign of the integral's value); call the oriented path $[\mathbf{R}]$. Parametrize $\mathbf{R}$ in $SO(3)$ by the path $\gamma: [a,b] \to SO(3)$, consistent with the orientation of $[\mathbf{R}]$. Pull $[\mathbf{R}]$ to $[\mathbf{R}^*]$ in $[0,2\pi] \times [0,\pi] \times [0,2\pi]$ and $\gamma$ back to $\gamma^*: [a,b] \to [0,2\pi] \times [0,\pi] \times [0,2\pi]$, with $\gamma(t) = \vec{r}[\gamma^*(t)]$ the desired parametrization of $\mathbf{R}$ in $SO(3)$, consistent with the orientation of $[\mathbf{R}]$. Now, suppose we extend $\mathbf{M}$ to a neighborhood of $S^3$ in $\mathbb{R}^4$ and write $\mathbf{M}(ct, x, y, z) = $ $\mathbf{M}_1(ct, x, y, z)d\{ct\} + \mathbf{M}_2(ct, x, y, z)dx + \mathbf{M}_3(ct, x, y, z)dy + \mathbf{M}_4(ct, x, y, z)dz$, then pull the restriction of this to $S^3$ back via $\vec{r}$ to be $\mathbf{M}^*(\psi,\theta,\phi) \in T^*([0,2\pi] \times [0,\pi] \times [0,2\pi])$ via formulas like $\displaystyle \mathbf{M}_1[\vec{r}(\phi,\theta,\psi)] \ \left(\frac{\partial \{ct\}}{\partial \psi}d\psi + \frac{\partial \{ct\}}{\partial \theta}d\theta+ \frac{\partial \{ct\}}{\partial \phi}d\phi\right)$; alternatively, we could write $\mathbf{M}^*(\psi,\theta,\phi) = \mathbf{M}^*_1(\psi,\theta,\phi)d\psi + \mathbf{M}^*_2(\psi,\theta,\phi)d\theta + \mathbf{M}^*_3(\psi,\theta,\phi)d\phi$ directly. Next, take $\gamma^{*'}(t)$ and $\mathbf{M}^*[\gamma^*(t)]$.
Then $$ \int_{[\mathbf{R}]} \mathbf{M} = \int_a^b \langle \mathbf{M}^*[\gamma^*(t)]\ |\ \gamma^{*'}(t)\rangle\ dt$$, where $\langle\ |\ \rangle$ denotes the action of a differential 1-form on $[0,2\pi] \times [0,\pi] \times [0,2\pi]$ on a tangent vector to $[0,2\pi] \times [0,\pi] \times [0,2\pi]$, is the work done by the torque along the path https://en.wikipedia.org/wiki/Torque#Relationship_between_torque,_power,_and_energy; one could turn the RHS over to a talented Calc II student, in principle.
Here is a Mathematica notebook that does an example; you should only have to change the formulas in the top lines, where $\gamma^*(t)$ and $\mathbf{M}$ are defined, then drag down to "Evaluation $\to$ Evaluate Notebook" to do any reasonable computation you desire. (There could be a teensy problem if your path "leaks out of" or "wraps around" the coordinate patch; you would then just have to break your integral into "sub-integrals" over portions of the oriented path contained entirely in the coordinate patch to do the full integral.)
Comment: OT: @JinsongYang Where do you study mechanical engineering (if I may ask politely)? This is way beyond anything the standard MSOE student would be expected to understand/do by most of their professors, I should think
Comment: That was super-fun, and very much in the spirit of Bullo and Lewis https://www.amazon.com/Geometric-Control.../dp/B07ZKTDN9X/. It was the idea of being able to problems like that that got me into differential topology in the first place.
Comment: (I see now why Bullo and Lewis encode generalized forces in Lagrangians as differential forms instead of vector fields: it completely removes the dependence on a Riemannian metric [which is, in a way, exactly what differential forms were designed to do]. It seemed to meaninglessly change the formalism from to what the reader was used to me at first, but now I see it is exactly the correct thing to do. Insert aikido "whetstone analogy" speech here; having a problem to do at exactly the correct level of difficulty/resistance makes concepts clear more than 100 pages of exposition.)
Answer: (I think I've edited the first answer enough; we'll try another answer for the potential function solution.)
Here is a Mathematica notebook that does the same example using a potential function to compute the integral. Many special thanks to @Michael_E2 on mathematica.stackexchange.com for posting this answer to "help" with the technical details of computing a potential function as a function in Mathematica. It is still caveat emptor for the user to make sure the exterior derivative of $\mathbf{M}$ is 0; recall that part of what makes this work is that $SO(3)$ is a "de Rham cohomology sphere" (see the comments above the first answer).
Here is a Mathematica notebook that uses the DifferentialForms.m package https://library.wolfram.com/infocenter/MathSource/482 to compute the integral directly and using an antiderivative (there's a kludge on the HomotopyOperator I'm not sure why I need).


How to monitor hosts with foreman when there's only one-way traffic allowed?

Question: I am currently setting up a PoC with foreman to monitor the configuration of some hosts. This works great.
I am wondering, how could I monitor hosts in our DMZ? Where only one way traffic is allowed (local to DMZ)? I would prefer to see the host status on the same foreman web interface.

Is there a way to have some kind of a master/slave setup? Where the master would periodically collect slave data and display it in the web interface?
Have any of you tried something similar?
Answer: I managed to achieve this by reverse proxying to a Nginx server in our non-dmz environment. If you need any help on the configuration, feel free to @ me


Calculate the possible permutations given a length and possible characters

Question: I'm trying to calculate the number of permutations possible given a set of characters for example : 'a','b' and a length for example 2.
from itertools import product
mystr = 'ABC'
prodlen = 3
products = list(product(mystr,repeat=prodlen))
print(products)

but that's printing:
[('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'B', 'A'), ('A', 'B', 'B'), ('A', 'B', 'C'), ('A', 'C', 'A'), ('A', 'C', 'B'), ('A', 'C', 'C'), ('B', 'A', 'A'), ('B', 'A', 'B'), ('B', 'A', 'C'), ('B', 'B', 'A'), ('B', 'B', 'B'), ('B', 'B', 'C'), ('B', 'C', 'A'), ('B', 'C', 'B'), ('B', 'C', 'C'), ('C', 'A', 'A'), ('C', 'A', 'B'), ('C', 'A', 'C'), ('C', 'B', 'A'), ('C', 'B', 'B'), ('C', 'B', 'C'), ('C', 'C', 'A'), ('C', 'C', 'B'), ('C', 'C', 'C')]

instead what I need is: A, B, AA, BB, AB, BA and I need the total number of those permutations. The number should go as high as the example below:
17  131072
16  65536
15  32768
14  16384
13  8192
12  4096
11  2048
10  1024
9   512
8   256
7   128
6   64
5   32
4   16
3   8
2   4
1   2
Total = 262142

Comment: See [this](http://www.mathwords.com/p/permutation_formula.htm)
Comment: Looks like `2^n`
Comment: Also, what happens when `mystr='AABC'`? Do you count the As twice or only once?
Comment: It would be only once and I need the number because it will be part of a condition in my algorithm to limit the amount of iterations
Answer: Seems like you want
mystr='AB'
u=len(set(mystr))
r = 17
s={}
for i in range(1,r+1):
    s[i] = u**i

{1: 2,
 2: 4,
 3: 8,
 4: 16,
 5: 32,
 6: 64,
 7: 128,
 8: 256,
 9: 512,
 10: 1024,
 11: 2048,
 12: 4096,
 13: 8192,
 14: 16384,
 15: 32768,
 16: 65536,
 17: 131072}

Comment: just `sum(s.values())`
Comment: Yes this is what I need, now I guess I can just add a counter and sum it all to get the total?
Answer: If what you want is to determine how many ways k characters can be chosen from a set of n characters with replacement, then for each of k characters you have n choices. This amounts to n^k, because you have n options for each of k choices. If you want the total number of such combinations with at most k characters, you want something like this:
my_string = 'ab'
n = len(set(my_string))
k = 17
p = sum([n**(i+1) for i in range(k)])  # 262143

Comment: but I need it to grow depending on the characters and the length I'm providing, for example: characters `abcde` and length `5` or `ab` and length `17` which should give me `131072`
Comment: If `ab` length 17 gives you 131072, I can only imagine that what you're talking about isn't actually permutations. Does this also mean that `abcde` length 5 should give you 3125?
Comment: No `abcde` should give me `3905` since you can create not only the initial combinations of length 5 but also the other length `4,3,2,1`
Comment: So you want the number of all combinations from that set of characters with a length of _at most_ 5? and in that case why does 17 give you 131072? shouldn't it give you a way higher number?
Comment: Yes my bad it should be `262142`
Comment: Edited to exclude duplicate characters, per your recent comment on the question
Comment: what's the difference between `len(s)` and `len(set(my_string))` both are giving me `262142` as the total for `ab` and `17`
Comment: @gabb `len('aaa')` is 3, `len(set('aaa'))` is 1 because `set('aaa')` is `{'a'}`. It just creates a set from the characters, which by definition does not include duplicates.


Making boxplots of hourly data in R

Question: I have air temperature measurements from two fixed locations measured at hourly intervals. The code below is a random set of numbers used to represent the format of my data:
set.seed(1)
RandData <- rnorm(8760*2,sd=10)
Locations <- rep(c('UK','France'),each=8760)

Date = seq(from=as.POSIXct("1991-01-01 00:00"),
              to=as.POSIXct("1991-12-31 23:00"), length=8760)

Final <- data.frame(Loc = Locations,
                    Doy = as.numeric(format(Date,format = "%j")),
                    Tod = as.numeric(format(Date,format = "%H")),
                    Temp = RandData)

I can plot the variation in temperature as a funtion of day of year with the following code:
require(lattice)
xyplot(Temp~Doy | Loc, data = Final, col = "black", type = "l")

This would show the annual pattern of the data. However, what I would like to do is to produce boxplots of the variation in temperature for different times of the day. So, for the example above I would like two figures, one for each country and each figure should be composed of box plots showing the variation in temperature at 00:00, 01:00... and so on, referring to Final$Tod. How can this be achieved?
Many thanks for your help.
Answer: Something like this?
library(ggplot2)
ggplot(Final, aes(x = as.factor(Tod), y = Temp)) + geom_boxplot()  + facet_wrap(~ Loc)

Answer: library(robustbase)
adjbox(Final$Temp[Final$Loc=="UK"]~Final$Tod[Final$Loc=="UK"])

Boxplots are a visualization tool, so i'll give you a visual advice.
What you have is essentially functional data so you
want (for visualization reasons) to use a box-plot tool that
acknowledges that. Try the functional boxplot function in the
fda package.
Comment: Yes (+1), this is much easier to visualize than the many box plots as well. I will have to re-read to make sure, but I believe Tukey (in EDA) actually suggests to not use the box's like this anyway, but to connect the lines for the summary statistics (see [this similar question](http://stats.stackexchange.com/a/18826/1036)). Of course using functional boxplots is a better replacement for identifying outliers as well.

Making boxplots of hourly data in R


CORS policy Error with Bearer Token Request

Question: I am building a react application postAPI using bearer token.
I already stored bearer token in localStorage and try to receive data for below code.
However, it is returning me CORS policy error. I am able to receive data from postman using Authorization tab. It is not working for a Header tab along with Authorization Bearer token though.
Could you help me how I can resolve this issue? I usually open cors policy from the server, but this is actually from a third party api.
I have tried no-cors, but you can't send headers with no-cors mode.
Access to fetch at 'https://d9u7x85vp9.execute-api.us-east-2.amazonaws.com/engine' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

const postAIMove = async () => {

    const fetchOptions = {
        method: "POST",
        withCredentials: true,
        credentials: "include",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": `Bearer ${localStorage.getItem("authToken")}`,
        },
        body: JSON.stringify({board})
    }

  const res = await fetch(`${API_URI}/engine`, fetchOptions)

Answer: CORS is about browser security. A request in postman works, because postman ignores invalid Access-Control-Allow-Origin headers.
You need to add your host http://localhost:3000 to the list of allowed hosts for that resource. This can only be done if you have control over the configuration of the webserver.
Comment: I realized this third party api has dev server for the localhost cors. Thank you so much for your help guys
Comment: Can it be done by adding "Access-Control-Allow-Origin": "http://localhost:3000" in the headers?
Comment: I believe you need to add the protocol as well (`http://`)
Comment: Sorry I tried adding "Access-Control-Allow-Origin": "http://localhost:3000", but not working.
Comment: Are you adding this on the client-side (in your above code) or on the server-side? Because it will only affect anything if the server sets this as a response header.