How to addClass Url Parmeter

Question: It doesn't work.
help.
example url: .../list.html?cate_no=800
jquery
$(document).ready(function() {
        $.urlParam = function(name){
            var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
            if (results==null) {
               return null;
            }
            return decodeURI(results[1]) || 0;
        }
        var id = $.urlParam('cate_no');
        $(id).addClass("active");
});

html

ex

ex

I would like to addClass active with the parameter value of the current address window.
It doesn't work.
Comment: I think the problem is here `var id = $.urlParam('cate_no');`, this would return something like `800` so when you do `$(id)` it would be `$(800)` but it should be `$(#800)` so change it to `$("#"+id)`. Also you might wanner read https://stackoverflow.com/a/79022/2943218
Answer:
Use the URL searchParams
To make your life easier do not have anything that is going to be used in a JavaScript selector start with a number or contain special characters

$(function() {
  const url = new URL("https://www.exaplen.com/product/list_journal.html?cate_no=c700");  // new URL(location.href);
  const id = url.searchParams.get("cate_no");
  $(`#${id}`).addClass("active");
});
a { text-decoration:none;}
a.active { text-decoration:underline; color: green; }

ex

ex

If possible just use hash - no script needed at all:

a {
    background-color: #00A087;
}
a:target {
   background-color: #F37736;
}

Click one of these

Click one of these

How to addClass Url Parmeter


Flexible Content Element: section element inside another section element

Question: I am creating an FCE for my article content.
I created sections so that I can create every article sub element multiple times in a page and every thing works fine except an image slider.
Here is my mapping :

The difference between other elements and image slider is it contains a section element inside it.
When I add and save content to image slider it simply disappear.
Rendering output shows html elements till the subsection 'Content set'.
How can I get the slider to work?
Answer: You have bad maping set:
<code>Image slider -> div (outer)
Content set -> div (inner)
Container -> li (outer)
Image -> img (outer)
</code>
Comment: my markup for slider is :

. If I map as u said ,when each time I add a container set in the backend will result in replication of .


Proving this sequence converges

Question: Prove the sequence $A_n = \frac{1}{n+1}+ \frac{1}{n+2}+\ldots+ \frac{1}{2n}$ converges to a limit $a$ with $0 \leq a \leq 1$.
Some help would be greatly appreciated been stuck on this for a day or so now.
Answer: Hint:
Write $$A_n = \frac{1}{n\left(1+\frac{1}{n}\right)}+\frac{1}{n\left(1+\frac{2}{n}\right)}+\dots+\frac{1}{n\left(1+\frac{n}{n}\right)} = \frac{1}{n}\sum_{k=1}^n\frac{1}{1+\frac{k}{n}}$$
and use theorems on Riemann sums to relate it to the integral $\int_0^1 \frac{dx}{1+x}$.
Comment: we havent started Riemann Sums yet. Is there a way we can do this using epsilon proofs?
Answer: If
$A_n
=\sum_{k=n+1}^{2n} \frac1{k}
$,
$\begin{array}\\
A_{n+1}-A_n
&=\sum_{k=n+2}^{2n+2} \frac1{k}-\sum_{k=n+1}^{2n} \frac1{k}\\
&=(\sum_{k=n+2}^{2n} \frac1{k}+\frac1{2n+1}+\frac1{2n+2})
-(\frac1{n+1}+\sum_{k=n+2}^{2n} \frac1{k})\\
&=(\frac1{2n+1}+\frac1{2n+2})-(\frac1{n+1})\\
&=\frac1{2n+1}-\frac1{2n+2}\\
&<\frac1{2n}-\frac1{2n+2}\\
&=\frac12(\frac1{n}-\frac1{n+1})\\
\end{array}
$
Since
$A_{n+1}-A_{n}
=\frac1{2n+1}-\frac1{2n+2}
> 0
$,
the $A_n$ are increasing.
Summing,
$\begin{array}\\
A_{N+1}-A_1
&=\sum_{n=1}^N (A_{n+1}-A_n)\\
&< \sum_{n=1}^N \frac12(\frac1{n}-\frac1{n+1})\\
&=\frac12(1-\frac1{N+1})\\
&< \frac12
\end{array}
$
Therefore
$A_{N+1}
<A_1+\frac12
= 1
$.
Since the
$A_N$ are increasing and bounded,
they converge.
(I seem to have answered this
or a variation of this
a number of times recently.)
Comment: This looks vaguely familiar to what I was trying to attempt. I was stuck somewhere in the middle. Thanks @martycohen
Comment: This cancellation of common terms in sums occurs a lot. I have gotten (through practice) quite comfortable doing this. For a more complicated example, see here: http://math.stackexchange.com/questions/1165393/if-s-k-mn-sum-i-n1knm-frac1i-show-that-for-k-ge-2m1-s

Proving this sequence converges


Acessar dispositivo via CMD

Question: Como acessar as pastas internas do android usando o comando do cmd CD.
ex:
Meu computador\Redmi 4X\Armazenamento interno
Answer: Isso não é possível
mas é possível acessar as pastas do android pelo Explorer, iniciando um serviço
FTP no Aparelho com android.
recomendo usar este app: https://play.google.com/store/apps/details?id=com.alphainventor.filemanager
ao abrir o app, vá em "Acesso a partir de um PC"
depois clique em Iniciar, vai aparecer um link ftp na tela
depois vá no menu executar do windows e digite "explorer" dê um espaço e cole
o link ftp e dê enter. aí você terá acesso às pastas do seu celular pelo PC
Answer: É possível acessar com o ADB.

Se sua inteção for fazer backup de arquivos (fotos, videos, saves de jogos, etc.), podes usar o adb backup -f <file_name> [-[no]apk] <package_name>.
Se quiseres instalar um aplicativo, use: adb install [android app].apk.
Para reiniciar o aparelho: adb reboot.
Para reiniciar o aparelho em modo recovery: adb reboot recovery.
Para copiar um arquivo do computador para o aparelho: adb push [pasta no computador / nomedoarquivo.extensão] [Pasta no aparelho]
Para copiar um arquivo do aparelho para o computador: adb pull [pasta no computador / nomedoarquivo.extensão] [Pasta no computador] (Se o diretório não for especificado, o arquivo irá para a pasta do executável ADB ou para a /home.)

Fonte: https://www.androidpit.com.br/adb-drivers-android-windows
Comment: Esse link pode ser uma boa sugestão, mas sua resposta não terá validade se um dia o link deixar de funcionar. Além disso, é importante para a comunidade ter conteúdo aqui no site mesmo. Seria melhor incluir mais detalhes na sua resposta. Um resumo do conteúdo do link já ajudaria bastante! Saiba mais sobre o assunto neste item do nosso FAQ da Comunidade: [Queremos respostas que contenham somente links?](http://meta.pt.stackoverflow.com/q/42/74)
Comment: Tendo o ADB e drivers instalados, você executa os comandos pelo cmd.
Comment: Ok. Vou editar  a resposta. Desculpe o inconveniente.

Acessar dispositivo via CMD


If time reverses the Wide Sense Stationary(WSS) preserves or not?

Question: If $X(t)$ is WSS with autocorrelation $R_{X}(\tau)$ then is $Y(t)=X(-t)$ WSS? How to find Cross Correaltion of $X(t)$ and $Y(t)$ too? And, can we say they are jointly WSS?
Answer: A process $X_t$ is WSS when ($K_{XX}$ is an autocovariance function):
$$
\forall\tau\in\mathbb{R}: \mathbb{E}[X_t]=\mathbb{E}[X_{t+\tau}]
$$
$$
\forall t_1,t_2\in\mathbb{R}:K_{XX}(t_1, t_2)=K_{XX}(t_1-t_2,0)
$$
$$
\forall t\in\mathbb{R}:\mathbb{E}[|X_t|^2] < \infty
$$
You can note, that this definition is symmetric with respect to substitution $t\rightarrow -t$, so inverted process is WSS if and only if the original one is WSS.


ML.NET - ForecastBySsa

Question: I'm evaluating and testing ForecastBySsa and I'm not really impressed with the result.
1) Example from Microsoft
https://learn.microsoft.com/en-us/dotnet/api/microsoft.ml.timeseriescatalog.forecastbyssa?view=ml-dotnet
The example show a time series of 5 data points, repeated 3 times with values 0,1,2,3,4.
The forecasted next five values are:
// Forecasted values: // [1.977226, 1.020494, 1.760543, 3.437509, 4.266461]
Hmm... Why 1.97? Far from zero. And overall - not that good?
2) Testing with airline passenger data dataset
Testing the algorithm with data from:
http://rstudio-pubs-static.s3.amazonaws.com/311446_08b00d63cc794e158b1f4763eb70d43a.html
And get the following forecast
Click here to see forecast!
Questions:
a) Anyone having good forecasting results using ML.NET ForecastBySsa?
b) Anyone having a good example with some real dataset and parameters etc?
/Erik
Comment: In order to identify the issue with Airline forecast , it would be helpful if you share your code. Otherwise it is not possible to identify the issue.
Answer: you should set the parameter windowSize to 13, not 12. Because 13 is a complete cycle.
Answer: the example is incomprehensible as the meaning of the input parameters are not explained. The predicted data are bad, it is not absolutely clear how to improve them. In the example there is this piece of code, but what does it mean? The results do not improve anyway. Seen thus always unusable.
<code>// Update with new observations.
        forecastEngine.Predict(new TimeSeriesData(0));
        forecastEngine.Predict(new TimeSeriesData(0));
        forecastEngine.Predict(new TimeSeriesData(0));
        forecastEngine.Predict(new TimeSeriesData(0));
</code>
the only article with more information is this, hopefully it will help
https://github.com/dotnet/machinelearning-samples/blob/main/samples/csharp/end-to-end-apps/Forecasting-Sales/README.md

ML.NET - ForecastBySsa


Bashrc configuration: Unexpected EOF

Question: I was doing my first bashrc configuration, i searched online for examples and i tried to do this but it gives me those errors:
I removed the colors code for a better reading.
bash: /home/filippo/.bashrc: line 228: syntax error near unexpected token `)'
bash: /home/filippo/.bashrc: line 228: `    fi')$BYellow$PathShortcut$Color_Off'\$ "; \'
HISTCONTROL=ignoreboth

shopt -s histappend

HISTSIZE=1000
HISTFILESIZE=2000

shopt -s checkwinsize

[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
    color_prompt=yes
    else
    color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

if [ -f ~/.git-prompt.sh ]; then
    . ~/.git-prompt.sh
fi

if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

Color_Off="\[\033[0m\]" # Text Reset

Time12h="\t"
Time12a="\@"
PathShort="\W"
PathFull="\w"
NewLine="\n"1
Jobs="\j"

export PS1=$BGreen'\u@\h'$Color_Off'$(git branch &>/dev/null;\
if [ $? -eq 0 ]; then \
    echo "$(echo `git status` | grep "nothing to commit" > /dev/null 2>&1; \
    if [ $? -eq 0 ]; then \
        # @4 - Clean repository - nothing to commit
        echo "'$Green'"$(__git_ps1 " (%s)"); \
    else \
        echo "$(echo `git status` | grep "to be committed" > /dev/null 2>&1; \
        if [ $? -eq 0 ]; then
            echo "'$IPurple'"$(__git_ps1 " {%s}"); \
        else \
            # @5 - Changes to working tree
            echo "'$IRed'"$(__git_ps1 " {%s}"); \
        fi)
    fi) '$BYellow$PathShort$Color_Off'\$ "; \
else \
    # @2 - Prompt when not in GIT repo
    echo " '$BIBlue$PathShort$Color_Off'\$ "; \
fi)'

Comment: Try shellcheck.net. You have unbalanced quotes somewhere.
Comment: Consider using setting `PROMPT_COMMAND` to the name of a function that builds your `PS1` value incrementally, rather than trying to stuff arbitrary code into a single string.
Answer:
 *) return;;

return: can only `return' from a function or sourced script
To locate more errors run your script with:
bash -x script.sh

Comment: `.bashrc` *is* sourced, although the exit status doesn't seem to be used to set `$?`.

Bashrc configuration: Unexpected EOF


How can I use all space available in a Grid?

Question: I have a horizontal ListView and I want it to use all available horizontal space. I cannot get it to work and I assume I am missing something fundamental. The button in the code below should stretch all the way up.
This is the XAML:
<Window x:Class="tt.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:tt"
    Title="MainWindow" Height="250" Width="200">

<Grid Background="Blue">
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <ListView ItemsSource="{Binding MyData}" VerticalAlignment="Bottom">
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid Margin="5" Background="AliceBlue">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Button>xx</Button>
                        <TextBlock Grid.Row="1" Text="{Binding}" Margin="20"/>
                        <TextBlock Grid.Row="2" Text="{Binding}" Margin="20"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListView>
    </ScrollViewer>
</Grid>
</Window>

This is the code (providing the data):
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public ObservableCollection<String> MyData { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        MyData = new ObservableCollection<string>() {
            "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"
        };
        DataContext = this;
     }
}

Answer: It is snapped to the bottom because of this line:
<ListView ItemsSource="{Binding MyData}" VerticalAlignment="Bottom">

If you want the scrollviewer to fill the entire window, try this instead:
 <ListView ItemsSource="{Binding MyData}" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch">


SCCM Remote Control: Can you have multiple connection to same host?

Question: Is it possible via the remote control feature of SCCM 2012 R2 SP1 to have more than one connection to a client?  I.e. If two or three support staff want to remote into the same client at the same time to help each other.
Can this be done via a configuration change?
Comment: If SCCM client is on the support computers, you could always remote the tech's computer which is remoting the client.
Answer: As useful as that would be, unfortunately the remote control feature within SCCM only allows one active connection.  You'll get the following message if you try to remote control a host which already has an active connection:

I've double checked the Client Settings for remote tools and there is no feature to extend the allowed amount.


Detecting encoding before opening a file

Question: I got a file with an unknown character encoding. Running file -bi test.trace returns text/plain; charset=us-ascii but using
(with-open-file (stream "/home/*/test.trace" :external-format :us-ascii)
 (code-to-work-with-file))

gives me an exception:
:ASCII stream decoding error on
#<SB-SYS:FD-STREAM for "file /home/*/test.trace"   {10208D2723}>:

  the octet sequence #(194) cannot be decoded.    [Condition of type SB-INT:STREAM-DECODING-ERROR]

How can I detect the encoding of a file before opening it?
I can open the file with emacs,less and nano just fine so it seems to be a miss-detection of the encoding or a difference in what file and sbcl think an encoding should look like.
I currently avoid this problem by forcing every file to have a utf8 encoding with vim +set nobomb | set fenc=utf8| x file-path. But even after this file still thinks it is an us-ascii encoding. Additional this is not a valid permanent solution, rather a dirty hack to make it work.
Comment: "How can I detect the encoding of a file before opening it?" You have use the specification, convention or agreement from wherever it came from. An encoding cannot be detected because there always multiple valid answers based on the sequence of byte values. Besides the current contents of a file is only one sample of the contents. If you just want to avoid exceptions and allow some bytes to be misinterpreted, you can use CP437. You can improve your guess by trying all the hundreds of encodings, seeing which don't give exceptions and comparing the interpretations. ┬
Comment: @TomBlodget this is not the answer I was hoping for but consequently the answer I was looking for if there is no true detection mechanism that works. Post this as an answer and I'll accept it.
Answer: As pointed in prorgammers stackexchange in here,

Files generally indicate their encoding with a file header. There are
  many examples here. However, even reading the header you can never be
  sure what encoding a file is really using.

I looked for trace files in my system and found this one but this not have any funny thing
2016-06-22 13:10:07 ☆ |ruby-2.2.3@laguna| Antonios-MacBook-Pro in ~/learn/lisp/stackoverflow/scripts
○ → file -I resources/hello.trace
resources/hello.trace: text/plain; charset=us-ascii
2016-06-22 13:11:50 ☆ |ruby-2.2.3@laguna| Antonios-MacBook-Pro in ~/learn/lisp/stackoverflow/scripts
○ → cat resources/hello.trace
println! { "Hello, World!" }
print! { concat ! ( "Hello, World!" , "\n" ) }
So With this code I can read it:
CL-USER> (with-open-file (in "/Users/toni/learn/lisp/stackoverflow/scripts/resources/hello.trace" :external-format :us-ascii)
           (when in
    (loop for line = (read-line in nil)
         while line do (format t "~a~%" line))))
println! { "Hello, World!" }
print! { concat ! ( "Hello, World!" , "\n" ) }
NIL

or even in chinese or whatever it was:

we can read the ascci character like this
CL-USER> (format nil "~{~C~}" (mapcar #'code-char '(194)))
"Â"

Or any other strange character so it seems that can be characters with accents I add this to the file:
 println! { "Hello, World!" }
print! { concat ! ( "Hello, World!" , "\n" ) }
Â
patatopita

and I get the same error:
:ASCII stream decoding error on
for "file /Users/toni/learn/lisp/stackoverflow/scripts/resources/hello.trace"
  {1003994043}>:
the octet sequence #(195) cannot be decoded.
   [Condition of type SB-INT:STREAM-DECODING-ERROR]
So at this point you can work with contitions and restarts, to change the character, there is an option, I not specialist in this kind of code but there could be a restart with
Restarts:
 0: [ATTEMPT-RESYNC] Attempt to resync the stream at a character boundary and continue.
 1: [FORCE-END-OF-FILE] Force an end of file.
 2: [INPUT-REPLACEMENT] Use string as replacement input, attempt to resync at a character boundary and continue.
 3: [*ABORT] Return to SLIME's top level.
 4: [ABORT] abort thread (#<THREAD "repl-thread" RUNNING {10050E0003}>)

Input-replacement, if not try wit european like latin-1 or ISO....
CL-USER> (with-open-file (in "/Users/toni/learn/lisp/stackoverflow/scripts/resources/hello.trace" :external-format :latin-1)
           (when in
    (loop for line = (read-line in nil)
         while line do (format t "~a~%" line))))
println! { "Hello, World!" }
print! { concat ! ( "Hello, World!" , "\n" ) }
¬
patatopita
NIL

And it should work, good luck
so let's read with european charset


Nginx not loading index

Question: I am attempting to serve all static content on nginx and php files on my apache server.
server {
        listen   80;
    root /var/www/tb/;
    index index.php index.html index.htm;

    server_name  37.*;

    location / {
            try_files $uri $uri/ /index.php @forward;
            #limit_req zone=one burst=1 nodelay;
    }

    location @forward {

            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://myip
    }

Unfortunately when I navigate to my website's url then I am shown the directory index instead of index.php(or a 403 if i disable autolisting.
If I append the url with http://myurl/index it works though. but http://myurl does not.
Comment: index.php exists ONLY on the remote server. Not on the nginx server.
Answer: This directive:
try_files $uri $uri/ /index.php @forward;

Will:

check whether the url is a file, and if it is serve it
check whether the url is a directory, and if it is serve the directory index (index.php index.html index.htm)
check whether the file /var/www/tb/index.php exists, and if it does use that
And finally, proxy the remote server

Steps 2 and 3 are not wanted, so simply remove them. In this way if the request maps exactly to a file it is served, and if not the request is handled by the @forward location block.
The complete config based on the question is therefore:
root /var/www/tb/;
server_name  37.*;

location / {
        try_files $uri @forward;
}

location @forward {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://myip
}

Note that there's no need to define the index directive since it's not going to be used.

Nginx not loading index


Importing third party javascript to vuejs

Question: I want to import this javascript code in my vuejs

It's a ladesk live agent code. When I paste it on my vuejs template I always get an error

All I want is to apply it like this I import the code the use it on the template like this:

here' my entire script on a single page and underneath this script were I deploy the third party javascript.

I'm also having an error. some of my methods didn't work when I deploy it
Comment: don't put script tags in templates - the error tells you the problem -
Comment: I tried to remove the tags still have an error
Comment: sorry, that's not what I meant - you need to run that code **outside** of `
Comment: okay is there anyway for me to put it on a specific page?...
Comment: are you using .vue files? you could put it in the main script tag in that case ... otherwise there's always the `created` hook
Comment: yes I'm using .vue files..
Comment: I also edit my query and added other details
Answer: Did you added the script code inside the <template></template> tags?
If yes, then you have to remove the code from <template></template> and place it after the ending of template.
Answer: You can import the script inside the index.html file under the head tag.
Answer: I just create a function and put the live agent script on it


How to set RibbonToolTip as global Tooltip

Question: I want to use RibbonToolTip outside the Ribbon for TextBox.
The long way is:
<TextBox Text="{Binding Name}">
  <TextBox.ToolTip>
    <RibbonToolTip Title="{DynamicResource nameTitle}" Description="{DynamicResource nameDescription}"/>
  </TextBox.ToolTip>
</TextBox>

I want to use something like this instead
<TextBox Text="{Binding Name}" ToolTipTitle="{DynamicResource nameTitle}" ToolTipDescription="{DynamicResource nameDescription}"/>

I can set the RibbonToolTip with

but how to set Title and Description.
Is there any way without deriving a new class from TextBox to create new dependency objects for ToolTipTitle and ToolTipDescription?
<TextBox ToolTip.Title="Name" ...

does also not work because ToolTip is not typed.
Answer: The answer is attached properties.
public class ExToolTip : DependencyObject
    {
        public static readonly DependencyProperty TitleProperty = DependencyProperty.RegisterAttached("Title", typeof(string), typeof(ExToolTip), new PropertyMetadata("", OnTitleChanged));

        public static string GetTitle(DependencyObject o)
        {
            return (string)o.GetValue(TitleProperty);
        }

        public static void SetTitle(DependencyObject o, string value)
        {
            o.SetValue(TitleProperty, value);
        }

        private static void OnTitleChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement fe = o as FrameworkElement;
            if (fe != null)
            {
                if (fe.ToolTip == null)
                {
                    fe.ToolTip = new RibbonToolTip();

                }
                RibbonToolTip rtt = fe.ToolTip as RibbonToolTip;
                if (rtt != null)
                {
                    rtt.Title = (string)e.NewValue;
                }
            }
        }

        public static readonly DependencyProperty DescriptionProperty = DependencyProperty.RegisterAttached("Description", typeof(string), typeof(ExToolTip), new PropertyMetadata("", OnDescriptionChanged));

        public static string GetDescription(DependencyObject o)
        {
            return (string)o.GetValue(DescriptionProperty);
        }

        public static void SetDescription(DependencyObject o, string value)
        {
            o.SetValue(DescriptionProperty, value);
        }

        private static void OnDescriptionChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement fe = o as FrameworkElement;
            if (fe != null)
            {
                if (fe.ToolTip == null)
                {
                    fe.ToolTip = new RibbonToolTip();

                }
                RibbonToolTip rtt = fe.ToolTip as RibbonToolTip;
                if (rtt != null)
                {
                    rtt.Description = (string)e.NewValue;
                }
            }
        }
    }

With this class I can easily write:
<TextBox Text="{Binding Text}" ExToolTip.Title="title" ExToolTip.Description="Description" />


Is there a good example of a subgroup of an infinitely generated abelian group that is not isomorphic to a quotient of that group?

Question: Whilst I understand the classification of the finitely generated abelian groups, this had me wondering whether there is a subgroup $H$ of a general (necessarily infinitely generated) abelian group $G$ such that $H$ is not isomorphic to any quotient $G/N$ of $G$.
Comment: To complete Eric's answer; exercise: for an abelian group $H$, there exists an overgroup $G$ such that $H$ is not isomorphic to a quotient of $G$ if and only if $H$ is non-divisible.
Answer: For a very simple example, let $G=\mathbb{Q}$ and $H=\mathbb{Z}$.  Since $\mathbb{Q}$ is divisible (for any $x\in\mathbb{Q}$ and any nonzero integer $n$, there exists $y\in\mathbb{Q}$ such that $x=ny$), any quotient of $\mathbb{Q}$ is also divisible, so $\mathbb{Z}$ is not isomorphic to any quotient of $\mathbb{Q}$.
Comment: D'oh, yep, thank you!


Are there ways to solve this algebraic equation by division

Question: I know I can find solution for These equations using subtraction
$3x+2y=14.....(\text{i})$
$4x+3y=20.....(\text{ii})$
My question is can I divide $(\text{i})$ by $(\text{ii})$ to get values of $x$ and $y$ ?
Comment: Try dividing them to see what you get. Remember that the idea of solving such a system using subtraction is to eliminate one of the variables.
Comment: Those are not equations. An equation means that you have a LHS and RHS and an equality sign between them.
Comment: Are you asking this question "randomly" ?
Answer: Yes, eliminatiion by division always works. But you also need to separately consider the case that the eliminated variable $=0.\,$ Let's compare eliminating vs. isolating $x$ then dividing for the system
$$\begin{align} a x + b y = c\\
 d x + e y = f \end{align}$$
Eliminating $x$ we obtain the equation $\ (bd-ae)\, y = cd-af$
Isolating $x$ and dividing we obtain $\  \ a/d = (by-c)/(ey-f)$
Clearing denominators shows that the latter is equivalent to the former, assuming that $d\neq 0$ (which we can assume wlog). Note that $\,ey-f = dx\neq 0\,$ by $\,d,x\neq 0$.
Answer: Your equations can be written as
$$3x=14-2y $$
$$4x=20-3y $$
$x=0$ yields to a contradiction.
we can assume $x\ne 0$.
by division, we get
$$\frac {3x}{4x}=\frac {14-2y}{20-3y}=\frac {3}{4} $$
thus
$$4 (14-2y)=3 (20-3y )$$
or
$$y=60-56$$
You can finish.
Comment: @user951215 Such division always works (and is equivalent to standard elimination) - see my answer.
Comment: I am pretty clear now tnx @ salahamam
Comment: Tnx sir I am satisfied by your answer @ Bill Dubuque


CSS Transition get laggy with many DOM Elements

Question: While programming my web application, which contains a table, which can get pretty big, i noticed that my CSS Transitions get pretty laggy after a while.
After testing that with JSFiddle, i noticed that this also does happen with just a basic example. http://jsfiddle.net/tLjmkdto/1/
HTML

<button onclick="animateme()">Animate</button>
<button onclick="spamme()">Spam</button>

CSS
.animate {
    width: 600px;
    height: 200px;
    border: 1px solid black;
    transition: width 1000ms ease-in-out;
}

.closed.closed {
    width: 10px;
}

JS
function animateme() {
    var anim = document.querySelector(".animate");
    if(anim.className == "animate closed") {
        anim.className = "animate";
    } else {
        anim.className = "animate closed";
    }
}

function spamme() {
    var spam = document.querySelector(".animate");
    for (i = 0; i < 30000; i++) {
        var div = document.createElement("div");
        var node = document.createTextNode(i);
            div.appendChild(node);
        spam.appendChild(div);
    }
}

Smooth with no Elements
Laggy with many Elements
So i want to know if there is a way to get this animation smooth. I'm using Dart and Polymer if that helps.
Comment: i didnt animate 30k Nodes. I only animated the bordered Div. But the animation is laggy because there are 30k divs.
And as i do have an pretty big table in my web app, I have that laggy effect on my page.
Comment: Why do you need 30,000 nodes?
Answer: you know that animation is shrinking all the divs in the container right? that 's a pretty expensive operation. you might be able to work around this by actually having the 30,000 divs in a container that doesnt animate, but has a "clip view" superimposed that does animate to show/hide what is beneath it. This way the size of the 30k divs doesnt change, but you should get the same visual effect. Not 100% certain that this will result in a perfectly smooth animation, but this was too long for a comment :)
Comment: The 30k Divs are in a seperate container, so they do not get animated.
Comment: @Azael your fiddle begs to differ. it doesnt matter if they are in a "separate" container if resizing the parent container causes the 30k divs to resize too.
Comment: yeah in my web app they are in a seperate container, but not inside the same parent. But still the animation is pretty slowly
Comment: @Azael as i said separate container means nothing if the animation results in resizing those divs. The strategy in my post is the only way i can think of that would prevent those from resizing when you hide them. can you make a fiddle that demonstrates the hierarchy you have better?
Comment: http://jsfiddle.net/tLjmkdto/2/ Thats pretty close to my web app. Above is a collapseable Panel and below is a huge table. I know I use extremly many DOM Elements in this case, but since my web app has more complex Elements (Polymer Elements) i think this is pretty realistic.


Show $\sum _{n=1}^{\infty }f_{n}\cos \left( n\theta \right) $ converges

Question: I am having trouble proving the third part of the problem.
"Show if $0 < \theta < 2\pi $, $\left| \sum _{n=1}^{p}\sin \left( n\theta \right) \right| < \cos ec\dfrac {\theta } {2}$; and deduce that, if $f_{n}\rightarrow 0$ steadily(synonym for monotonically), $\sum _{n=1}^{\infty }f_{n}\sin \left( n\theta \right) $ converges for all real values of $\theta$, and that $\sum _{n=1}^{\infty }f_{n}\cos \left( n\theta \right) $ converges if $\theta$ is not even multiple of $\pi$.
Here is where i got upto, to see that the inequality holds i used Lagrange's trigonometric identity in the LHS and the result follows.
Once that is assumed to hold, $\sum _{n=1}^{\infty }f_{n}\sin \left( n\theta \right) $ just follows from  Dirichlet's test of convergence.
I am unsure how to show the last one i assume the problem is some how related to Abel's inequality or Dirichlet's test of convergence, any help would be much appreciated.
Comment: @leo I guess Hardy meant $\operatorname{cosec}$.
Comment: What is $ec$?..
Answer: We can use Abel's transform: for $N\in\mathbb N$ and $n\geq 0$ we have, denoting $s_j(\theta):=\sum_{k=0}^j\sin(n\theta)$
\begin{align*}
\left|\sum_{j=1}^{N+n}f_j(\theta)\sin(j\theta)-\sum_{j=1}^Nf_j(\theta)\sin(j\theta)\right|&=\left|\sum_{j=N+1}^{N+n}f_j(\theta)\sin(j\theta)\right|\\
&=\left|\sum_{j=N+1}^{N+n}f_j(\theta)(s_j(\theta)-s_{j-1}(\theta))\right|\\
&=\left|\sum_{k=N+1}^{N+n}f_k(\theta)s_k(\theta)-\sum_{k=N}^{N+n-1}f_{k+1}(\theta)s_k(\theta)\right|\\
&\leq \left|f_{N+1}(\theta)s_N(\theta)\right|+\left|f_{N+n}(\theta)s_{N+n}(\theta)\right|\\
&+\sum_{j=N+1}^{N+n}\left|(f_k(\theta)-f_{k+1}(\theta))s_k(\theta\right|\\
&\leq \frac 1{|\sin\frac {\theta}2|}(|f_{N+n}(\theta)|+|f_{N+1}(\theta)|\\
&+\sum_{j=N+1}^{N+n}|f_k(\theta)-f_{k+1}(\theta)|),
\end{align*}
and now the monotone convergence to $0$ of $f_n(\theta)$ gives the result.
Comment: @Hardy There was a typo, hope it's fixed now.
Comment: We have a sum of the form $\sum_k a_k b_k$, we know that the sequence $\{s_n=\sum_{k=1}^nb_k\}$ is bounded and we know that $a_k$ is monotone, so after Abel's transform we will have a sum of the form $\sum_k (a_k-a_{k+1}s_k$. The last sum involves terms on which we have hypothesis.
Comment: i do n't follow the first line in your solution how is $\left|\sum_{j=1}^{N+n}f_j(\theta)\sin(j\theta)-\sum_{j=1}^{N+n}f_j(\theta)\sin(j\theta)\right|=\left|\sum_{j=N+1}^{N+n}f_j(\theta)\sin(j\theta)\right|$ ?
Comment: Thanks very much for that. Just one last thing how did u know that Abel's transform is needed here. This is so i can recognize such problems myself.
Answer: As pointed by Davide Giraudo, the key is Abel's transform. I'll try to write an answer clearer for you.
Fix $\theta \in \mathbb{R}$. Let $S_n = \sum_{k=1}^n \sin(n\theta)$ for all $n \in \mathbb{N}$. Using Abel transform you have, for $p \in \mathbb{N}_{\geq 1}$ :
$$\sum_{n=1}^p f_n \sin(n\theta) = \sum_{n=0}^p f_n (S_n-S_{n-1}) = (f_p S_p - f_1 S_0) - \sum_{n=1}^{p-1} (f_{n+1}-f_n) S_n.$$
Since you proved that $(S_p)_p$ is bounded, you have
$$\lim_{p\to +\infty} f_p S_p=0.$$
Now we show that the $\sum_{n=1}^{+\infty} (f_{n+1}-f_n) S_n$ is absolutely convergent. This is because
$$\sum_{n=1}^{+\infty} |f_{n+1}-f_n| \cdot |S_n| \leq \sup_n(S_n) \sum_{n=1}^{+\infty} (f_n-f_{n+1}) = \sup_n(S_n) f_1.$$
Comment: $\theta \mod 2\pi \neq 0$ involve the series with $\cos$. I let you deal with this case.
Comment: Firstly thank you very much for your reply i do think it is easier for me to follow. I suspect though there is a mistake somewhere as it seems to me that you proved this for all values of $\theta$ where as the question states it should only converge when $\theta$ is not even multiple of $\pi$. Am i overlooking or misunderstanding anything here.


A problem on outer measure and Lebesgue measure I need some help with

Question: Let $X$ be a set that is Lebesgue measurable. Let $Y$ be another set, and define $X \triangle Y$ to be their symmetric difference. Given this information we also have that $\mu^{\ast}(X \triangle Y) = 0$. I want to show that $Y$ is also Lebesgue measurable and $\mu(X) = \mu(Y)$. Here the $\mu^{\ast}$ is the outer measure. The help would be greatly appreciated for this problem!!
Comment: Hint: Use the definition of symmetric difference and additivity.
Comment: Hmm, I am still not sure. Mainly because outer measure is not countably additive. Maybe using Carotheodorys criterion would help?
Comment: Intuitively speaking, if the symmetric difference is null, that means all the "important stuff" is in the intersection - that the stuff in just X or just Y is null. Using that fact, try to describe the measure of just the set X or just the set Y. Do you see it?
Comment: Oh I gotcha. Thanks.
Answer: We have $Y=Y\cap X \cup (Y \setminus X)$ and $X=Y\cap X \cup (X \setminus Y)$.  Since $\mu^*(X\Delta Y)=0$ we claim that $\mu^*(Y \setminus X)=0$ and  $\mu^*(X \setminus Y)=0$ which follows $\mu(Y \setminus X)=0$ and  $\mu(X \setminus Y)=0$. Hence $Y \setminus X$ and $X \setminus Y$ are Lebesgue measurable. Since $X$ is Lebesgue measurable we deduce that $X \setminus (X \setminus Y)=X \cap Y$ is Lebesgue measurable which implies that $(X \cap Y) \cup (Y \setminus X)=Y$ also is Lebesgue measurable. Finally we get $\mu(Y)=\mu((Y \cap X) \cup (Y \setminus X))=\mu((X \cap Y))+\mu(Y \setminus X)=\mu((X \cap Y))=\mu((X \cap Y))+\mu(X \setminus Y)=\mu(X).$


Transitivity of parallel lines

Question: I cam across a question (in my textbook) about proofs with parallel lines.  The question is: Prove that the property that || is transitive implies that for any point P and line l, there is at the most 1 line through P that is parallel to the line l.
In other words the question is asking me to prove that (P is on q & P is on s & l||q & l||s) --> q = s, using the transitive property.
I know that the transitivity property tells me that l||m & m||n --> n||l, but I am not sure how to do this proof.
Any hints or solutions would be much appreciated!! :)
Thank you in advance
Comment: The notation in your second paragraph is messed up.  On the left side, you have q,s,n but on the right side you have m and n.  Once you correct this, you should be able to see the solution.
Comment: @Ted After correcting it, I can see that q || s, but I can't think of the next step
Comment: q||s, but they both go through P, so ...
Answer: Let's say it is not true.
take 2 lines a and b with p on them, both parallel to l. than a||l and b||l, because of symmetry of ||, l||b. because of transitivity a||b. a||b and p on both a and b, a=b.
Answer: You want to show that the transitivity of parallelism is equivalent to the Playfair's Axiom.  It's explained perfectly here:
http://www.mathteacherctk.com/blog/2011/10/is-parallelism-an-equivalence-relation/
Michael

Transitivity of parallel lines


OpenVPN won't start as a service with config file

Question: I've got OpenVPN working good with my config file if I run it from CLI:
openvpn server.conf

But if I try to start it as a service it starts just fine, won't error out, but it will not load my conf file since there is no resulting tun device in ifconfig.
I have AUTOSTART set to all in /etc/init.d/openvpn:

But a quick ifconfig shows it's not started. I know it's not loading my conf file since the log file is not created, but no errors from OpenVPN.

This is on Ubuntu 16.04.3, fresh clean install of OpenVPN.
EDIT
As per comments below I have tried multiple times also with systemctl, it just errors out:

I know the conf file works since I can run it from CLI as openvpn server.conf and it works.
EDIT2
Logs:
Jan 11 14:31:37 cloud systemd[1]: firstname.lastname@example.com: Unit entered failed state.
Jan 11 14:31:37 cloud systemd[1]: firstname.lastname@example.com: Failed with result 'exit-code'.
Jan 11 16:06:07 cloud systemd[1]: Starting OpenVPN connection to server...
Jan 11 16:06:07 cloud ovpn-server[4726]: OpenVPN 2.3.10 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [MH] [IPv6] built on Jun 22 2017
Jan 11 16:06:07 cloud ovpn-server[4726]: library versions: OpenSSL 1.0.2g  1 Mar 2016, LZO 2.08
Jan 11 16:06:07 cloud ovpn-server[4726]: daemon() failed or unsupported: Resource temporarily unavailable (errno=11)
Jan 11 16:06:07 cloud ovpn-server[4726]: Exiting due to fatal error
Jan 11 16:06:07 cloud systemd[1]: firstname.lastname@example.com: Control process exited, code=exited status=1
Jan 11 16:06:07 cloud systemd[1]: Failed to start OpenVPN connection to server.
Jan 11 16:06:07 cloud systemd[1]: email@example.com: Unit entered failed state.
Jan 11 16:06:07 cloud systemd[1]: firstname.lastname@example.com: Failed with result 'exit-code'.
Jan 12 09:55:35 cloud systemd[1]: Starting OpenVPN connection to server...
Jan 12 09:55:35 cloud ovpn-server[12133]: Current Parameter Settings:
Jan 12 09:55:35 cloud ovpn-server[12133]:   config = '/etc/openvpn/server.conf'
Jan 12 09:55:35 cloud ovpn-server[12133]:   mode = 1
Jan 12 09:55:35 cloud ovpn-server[12133]:   persist_config = DISABLED
Jan 12 09:55:35 cloud ovpn-server[12133]:   persist_mode = 1
Jan 12 09:55:35 cloud ovpn-server[12133]:   show_ciphers = DISABLED
Jan 12 09:55:35 cloud ovpn-server[12133]:   show_digests = DISABLED
Jan 12 09:55:35 cloud systemd[1]: email@example.com: Control process exited, code=exited status=1
Jan 12 09:55:35 cloud systemd[1]: Failed to start OpenVPN connection to server.
Jan 12 09:55:35 cloud systemd[1]: email@example.com: Unit entered failed state.
Jan 12 09:55:35 cloud systemd[1]: firstname.lastname@example.com: Failed with result 'exit-code'.

Comment: You appear to have the same solvable problem as https://askubuntu.com/q/747023/778746
Comment: Not sure why you are messing with `init.d`. Have you tried `systemctl start email@example.com`?
Comment: Check `/etc/default/openvpn` and please as @multithr3at3d stated, don't change init files.
Comment: I've done that also, it errors out. I will post what it does above.
Comment: Can you post text rather than screenshots please.
Comment: And post the rest of the error logs, too.
Comment: Those are the only error logs, I'm not sure why the screenshots won't work? If you click it, they come up large.
Comment: The logs are truncated in the last screenshot; can you post the entire error message? Try `journalctl -u email@example.com -e` for the last 1000 lines, and try to post the entire log from when it starts to when it fails.
Comment: I have added the full logs
Comment: That worked thank you, you can post as the answer and I'll accept it.
Answer: This problem is the same as another posted on Ask! Ubuntu. The fix:

What I have found to work is to comment out the LimitNPROC line in /lib/systemd/system/openvpn@.service.
Answer: When I tried to run my server config I found that it was unable to reassign same port thus I reboot server and got fixed the issue.
ubuntu@VPNSERVER:/etc/openvpn$ sudo openvpn server.conf
Fri May 28 18:09:18 2021 OpenVPN 2.4.4 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Apr 27 2021
Fri May 28 18:09:18 2021 library versions: OpenSSL 1.1.1  11 Sep 2018, LZO 2.08
Fri May 28 18:09:18 2021 ECDH curve prime256v1 added
Fri May 28 18:09:18 2021 Outgoing Control Channel Encryption: Cipher 'AES-256-CTR' initialized with 256 bit key
Fri May 28 18:09:18 2021 Outgoing Control Channel Encryption: Using 256 bit message hash 'SHA256' for HMAC authentication
Fri May 28 18:09:18 2021 Incoming Control Channel Encryption: Cipher 'AES-256-CTR' initialized with 256 bit key
Fri May 28 18:09:18 2021 Incoming Control Channel Encryption: Using 256 bit message hash 'SHA256' for HMAC authentication
Fri May 28 18:09:18 2021 TUN/TAP device tun1 opened
Fri May 28 18:09:18 2021 TUN/TAP TX queue length set to 100
Fri May 28 18:09:18 2021 do_ifconfig, tt->did_ifconfig_ipv6_setup=0
Fri May 28 18:09:18 2021 /sbin/ip link set dev tun1 up mtu 1500
Fri May 28 18:09:18 2021 /sbin/ip addr add dev tun1 10.8.0.1/24 broadcast 10.8.0.255
Fri May 28 18:09:18 2021 Could not determine IPv4/IPv6 protocol. Using AF_INET
Fri May 28 18:09:18 2021 Socket Buffers: R=[212992->212992] S=[212992->212992]
# ===>>>>>  blow line was error that I found <<<<<<<===== #
# Fri May 28 18:09:18 2021 TCP/UDP: Socket bind failed on local address # [AF_INET][undef]:1122: Address already in use (errno=98)
Fri May 28 18:09:18 2021 Exiting due to fatal error
Fri May 28 18:09:18 2021 Closing TUN/TAP interface
Fri May 28 18:09:18 2021 /sbin/ip addr del dev tun1 10.8.0.1/24

   **ubuntu@VPNSERVER:/etc/openvpn$ sudo reboot**

In your case OPenVpn status and restart command could be like
systemctl status firstname.lastname@example.com
 systemctl restart email@example.com


Calculate $\sum_{n\geq 1} \frac{1}{5^{n}+2}$

Question:
Calculate $$\sum_{n\geq 1} \frac{1}{5^{n}+2}$$

My approach: I know by the ratio test that the series converges.

However, how can I calculate the sum?
Comment: How do you conclude that you do not generally have a clean closed form? I saw the problem on an internet page as a serial hard problem.
Comment: Where did you come across this problem? These sorts of sums tend not to have clean closed forms.
Comment: This has a closed form (in terms of q-digamma function). See this: https://www.wolframalpha.com/input/?i=Sum+of+1%2F%285%5E%28n%29%2B2%29+from+n%3D1+to+infinity+
Comment: _Most_ things don't have a clean closed form; there's no reason to expect that this does. I believe some similar constants have been proved transcendental, though I'm not 100% certain.
Answer: Without special functions, we can make approximations. Let us write the infinite summation as
$$S_p=\sum_{n=1}^p \frac 1{5^n+2}+\sum_{n=p+1}^\infty \frac 1{5^n}\frac1{1+2\times 5^{-n}}$$ and write
$$\frac1{1+2\times 5^{-n}}=\sum_{k=0}^\infty (-1)^k \,2^k \times 5^{-nk}$$ Summing from $k=0$ to $k=6$ for example
$$\left(
\begin{array}{cc}
p & S_p \\
 1 & \color{red}{0.18976287}954938663595977935271628162746328531817419 \\
 2 & \color{red}{0.18976287877266}367299681638975331866450032235521123 \\
 3 & \color{red}{0.1897628787726615593}3180851573757063300425936308525 \\
 4 & \color{red}{0.1897628787726615593263284}9366930907000585425941698 \\
 5 & \color{red}{0.1897628787726615593263284796045}6167280726135887333 \\
 6 & \color{red}{0.189762878772661559326328479604525648}62133819307056 \\
 7 & \color{red}{0.189762878772661559326328479604525648529106}83382480 \\
 8 & \color{red}{0.189762878772661559326328479604525648529106597707}69 \\
 9 & \color{red}{0.18976287877266155932632847960452564852910659770708}
\end{array}
\right)$$
Comment: @Ramanujan. Thank you !
Comment: This's a interesting answer!


'fopen' fails if the file opened in Visual Studio

Question: I have the following code:
FILE *fp = fopen( srcFile.filename.c_str(), "rt");

srcFile happens to be the solution's main.cpp file, and thus is opened in the solution. fopen returns NULL most of the time (but not when I step into it, which is weird).
However, when I close main.cpp in Visual Studio, the code works. Even when the file is opened in Notepad++.
Is there a workaround?
PS: I tagged it as C, but the file is compiled as C++, IDK if it changes anything.
Answer: I think that this may have to do with the working directory (folder) being different when running within Visual Studio. If this is the case then using an absolute path to the file ("C:\folder\other-folder\file.txt") instead of a relative path ("file.txt") should make it work.
Answer: Let C print the errormessage:
FILE *fp = fopen( srcFile.filename.c_str(), "rt" );
if( !fp )
{
  perror( srcFile.filename.c_str() );
  exit( 1 );
}

Comment: "Permission denied". This seems logical, since my explanation was that Visual Studio locks the file.


Why do I get the error 'The provided information does not map to an AD object id.' when executing New-AzRoleAssignment using a Service Principal?

Question: Using Powershell in an Azure DevOps pipeline, I am trying to assign the key vault's principal the role Storage Account Key Operator Service Role to a storage account.
Command Line
The command line is run after I connected Azure with the service principal:
$credentials = New-Object -TypeName System.Management.Automation.PSCredential($servicePrincipalApplicationId, $clientSecret)

Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant $tenantId

Here is the command line that I execute :
New-AzRoleAssignment -ApplicationId $keyVaultServicePrincipalId -ResourceGroupName $resourceGroupName -ResourceName $storageAccountName -ResourceType "Microsoft.Storage/storageAccounts" -RoleDefinitionName "Storage Account Key Operator Service Role"

Where:

$keyVaultServicePrincipalId is the pre-registered principal ID for Key Vault. Its value is cfa8b339-82a2-471a-a3c9-0fc0be7a4093.
$resourceGroupName is the name of the resource group in which the storage is located. Its value is accountsmanager-test-global-rg.
$storageAccountName is the name of my storage account. Its value is accountsmanagertest.

Service Principal
Here are the permission of the service principal under which the command is run:

The command is run as a Service Principal that has the Owner role in the subscription:

The resource group created in that subscription is also owned by that Service Principal:

Question
When I run the command, I get the following error:
New-AzRoleAssignment: The provided information does not map to an AD object id.

Why do I get the error The provided information does not map to an AD object id. when executing the command New-AzRoleAssignment?
Answer: I can also reproduce this on my side, there are two issues.

1.In your command, the ResourceType should be Microsoft.Storage/storageAccounts, not Microsoft.Storage/storageAccount.
2.In the API permission of your AD App related to the service principal used in the DevOps servcie connection, you need to add the Application permission Directory.Read.All in Azure Active Directory Graph, not Microsoft Graph.

After a while to take effect, it will work fine.
Comment: I was avoiding the Legacy permissions, but it works. Great answer :)


How can I make gitosis distinguish between two users with the same username

Question: I have a gitosis system that seems to be working correctly except for a common problem we run into where I can't distingush permissions between two users who have the same username, but different hosts.
For example:
email@example.com 's SSH key is in the key folder.
And so is firstname.lastname@example.com 's SSH is also in the key folder.
These two jsmith's are two different people on two different computers. However, when I configure them in the gitosis.conf file with the usernames jsmith@computer or jsmith@machine, it seems like each user just gets the same permission.
Can gitosis not distinguish the full username (name and host)? If not, how do I deal with multiple users accessing our system with common usernames? Thanks for any help.
Answer: Well, I finally figured out what my difficulty was.
Gitosis doesn't care what you name the key files in the keydir. So, even though I have two keys that both have username@host1 and username@host2 I can name those files username_host1 and username_host2 in the keydir. Heck, I could call them raspberry and apple. Then I just need to use the filenames I defined in the gitosis.conf.
Since no one answered, maybe no one else has this issue, but I figured I should report in case someone else stumbled on this difficulty.
Comment: if you run into clashing usernames often, you might want to consider modifying your policy from (fi)(lastname) to (fi)(mi)(lastname) ... *shrug*
Comment: We regularly use external contractors, and I have no control over their usernames, so any solution for this type of thing should allow for username collisions. Gitosis does, I just didn't know how to implement it.


Select no php reconhece apenas uma variável

Question: Preciso buscar datas no banco de dados e compará-las com as datas geradas por um for. Se forem iguais, ficam vermelhas.
Já consegui pegar os valores por um Select e armazená-los num array usando outro for, faço a comparação e ele imprime os valores que passei pro array, porém apenas uma das datas fica em vermelho.
Fiz o teste e apenas a com maior valor de ID (referente as datas que são buscadas no banco e armazenadas no array) está sendo comparada e "pintada" de vermelho. Já fiz o teste trocando os ids (pois o banco só possui duas datas a serem comparadas mesmo) e a que fica com o ID maior sempre fica vermelha.
Segue o código abaixo. Acredito que o problema pode estar no modo de comparação ou até mesmo na forma como o banco seleciona os dados.
for($i=0;$i<=$nr_dias;$i++){
    $query = "SELECT * FROM expedientes_diferenciados";
    if ($result = $conexao->query($query)) {
        /* fetch object array */
        $k=0;
        while ($obj = $result->fetch_object() and $k<2) {
                $diaind=$obj->data;
                $array1[$k]= date("d-m-Y", strtotime($diaind));
                $motivo[$k] =$obj->motivo;
                $k++;
    }}

    $dia = date("d-m-Y",mktime(0,0,0,date("m"),date("d")+$i,date("Y")));
    $dia_sql = date("Y-m-d",mktime(0,0,0,date("m"),date("d")+$i,date("Y")));
    $semana=$dias_semana[date("D",mktime(0,0,0,date("m"),date("d")+$i,date("Y")))];
    $lock_cafe="";$lock_almoco="";$lock_jantar="";

    //Condicionais
    $b=0;
    while($b<2){
        if($semana=="Sábado" or $semana=="Domingo" or $dia==$array1[$b]) {
            $cor = "red";
            $msg_expediente = "Sem expediente
";
            echo $array1[$b];
        }
        else{
            $msg_expediente = "Expediente normal
";
            $cor = "white";
        }
        $b++;
    }
}

Comment: mano você tem ideia, de que você está resetando a variavel $k=0 e $b=0 pelo loop do seu for inicial.. você deveria declarar estás duas variáveis fora do laço FOR. e você também não esta incrementando $k em lugar nenhum para ele chegar ao valor 2. você também deve colocar as comparações entre () dentro do seu while.. ex: while(($obj = $result->fetch_object())) AND ($a>2))
Answer: $query = "SELECT * FROM expedientes_diferenciados";
if ($result = $conexao->query($query)) {
    /* fetch object array */
    $k=0;
    while ($obj = $result->fetch_object() and $k<2) {
            $diaind=$obj->data;
            $array1[$k]= date("d-m-Y", strtotime($diaind));
            $motivo[$k] =$obj->motivo;
            $k++;
}}

Este bloco pode estar FORA do primeiro FOR, até por questão de performance, como são 2 campos, não afeta muito, mais imagina com 200000 ou mais, ele vai recuperar a cada laço do for, e não é dependende dos valores do loop
Dentro do segundo while, tem que haver um foreach, para ele percorrer os dados do array1, ai o if deve comparar esses valores, senão na segunda volta do while, os valores da volta 1 são sobrepostos, ai sempre a saída desse segundo while é o do ultimo valor percorrido....


SMO 2004 Question 21

Question: Let $\frac{1}{a_1}$, $\frac{1}{a_2}$, $\frac{1}{a_3}$.... be a sequence of positive numbers defined by: $$a_1=1, a_{n+1}=a_n+\frac{1}{a_n}$$ Find the integer part of $a_{100}$.
This question was given in the Singapore Mathematics Olympiad in 2004 and it doesn't follow any of the typical recursion functions. Does anyone know how to even start approaching this question and what kind of motivation would make you use such an approach?
Comment: See also [this question](https://math.stackexchange.com/questions/887408/does-the-recursive-sequence-a-1-1-a-n-a-n-1-frac1a-n-1-converge).
Comment: BTW, research brings out this tighter inequality which can potentially give the integral part of $a_n$ for a much bigger $n$. https://artofproblemsolving.com/community/c6h1167601p5587849
Answer: This was given in a competition? I am quite surprised, since it is a very classical problem. Let us define $b_n$ as $a_n^2$. Then
$$ b_{n+1} = b_n + 2 + \frac{1}{b_n} $$
easily leads (by induction) to $b_n\geq 2n-1$. By plugging back this approximation in the above recursion, we get $b_n \leq 2n-1+\left(\frac{1}{1}+\frac{1}{3}+\ldots+\frac{1}{2n-3}\right)$. In particular $a_{100}$ is bounded between $\sqrt{199}$ and
$$ \sqrt{199+H_{198}-\frac{H_{99}}{2}}\leq \sqrt{205}, $$
so $\lfloor a_{100}\rfloor = \color{red}{14}.$
Comment: How did you get b_n is less than or equal to 2n-1?
Comment: @Mattew Tan
$b_{n}>2+b_{n-1}\implies b_n>2(n-1)+b_1=2n-1\\b_n=b_{n-1}+2+\cfrac 1{b_{n-1}}<b_{n-1}+2+\cfrac 1{2n-3}, \\ \cdots \\ b_2<b_1+2+\cfrac 1{2\cdot 2-1},\\ \text{add above and cancel out }b_{n-1} \text{ to } b_2, \text{ to arrive at the 2nd inequality.}$
Answer: The growth rate of this sequence can be approximately modeled by the differential equation $y' = \frac {1}{y}$
$a_n\approx \sqrt{2n}\\
a_{100}\approx 14.14$
Comment: In numerical algorithms for (P)DE we usually replace $\frac{d}{dx}$ with the forward difference operator. Here we are (reasonably) doing the opposite (since the associated DE is very simple to solve), but how to be sure such approximation does not change the leading term of the asymptotic behaviour of $a_n$ (and ultimately leads to the same value for $\lfloor a_n\rfloor$)?

SMO 2004 Question 21


Processing - Set X/Y Zero Coordinates To Center of Display Window

Question: I'm trying to use latitude and longitude coordinates to plot a map in Processing. Is there a way to set the zero coordinates of the X and Y axis to the center of the display window.
Or does anyone know how to convert spherical coordinates to cartesian?
Thanks
Comment: If it's a 2D map, yes, `translate(width*.5,height*.5);` at the start of your `draw()` loop is the easiest option. Tom's formula is converting [spherical coordinates](http://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates) to cartezian(x,y,z) which is handy if you want to plot lat lon coordinates on a 3D sphere.
Comment: @George Profenza Ah thanks, that makes more sense now!
Answer: I'll assume you have spherical coordinates of r, radius; theta, horizontal angle around Z-axis starting at (1,0,0) and rotating toward (0,1,0); and phi, vertical angle from positive Z-axis toward negative Z-axis; that being how I remember it from back when. Remember that angles are in radians in most programming languages; 2*pi radians = 180 degrees.
<code>x = r * cos(theta) * sin(phi)
y = r * sin(theta) * sin(phi)
z = r * cos(phi)
</code>
Comment: Thanks for your answer - I'd love to understand this but my maths is a bit weak at the moment. I found a solution with the translate() method.


Is it possible to do calculations like percentage in Views

Question: I am using Views module.
The view has three columns.
In the third column, I want a calculated percentage using the first two columns of the view.
Comment: Assuming your first 2 columns correspond to 2 fields of a node (for each row), you could use the math_field module which does NOT (repeat NOT) require the dangerous PHP filter. For more details, refer to my answer at  http://drupal.stackexchange.com/questions/183045/how-do-i-multilply-two-database-table-fields-create-a-new-one-with-this-multipl/183052#183052
Answer: You can use global php to acheive this (not recommended)
The best way to do it is by using this hook_views_pre_render(&$view) in your theme template file or in your custom module.
Answer: If it's based on some rules, try using Computed Field and you can define the values via PHP code. Alternatively use Views PHP which allows you to directly use PHP inside views which may be useful for calculating percentage using the first two columns of your view.
Comment: i do not want to use views php.I wil try using computed fields module.thanks.
Comment: @kenorb: You are also correct. But using php in views is major issue for performance right.....
And to change single field value may be we can go for hooks that provided by views rather than usinb other contrib module.
Comment: @AAjayKumarReddy If Views has caching on that page, field won't be re-calculated anyway, so it'll be quick in the same way. Secondly using PHP won't make the performance worse than the standard field which running a lot of other functions to call (e.g. field formatters).
Comment: @kenorb read the answer to this and the comments [What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc?](http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args)
Answer: You can use Global:Math Expression in views to perform mathematical operations.
You would need tokens if you want to use your fields to perform calculations.
It is pretty simple to calculate percentage using this.
For example, to calculate percentage using two fields [field1] and [field2],
you can do it like
<code>[field1]*100/[field2]</code>
I hope its clear.


Uniform convergence help

Question: Is this true ? please tell me how they got here, this is to prove the uniform convergence of the function (point wise limit is the function zero):
$$\text{for }x \in [0,\pi], \sup\left|\sin(x)^n\left(1-\sin(x)^n\right)\right|=\frac1{4^n}$$
Comment: What is $\sin(x)^n$? $\sin(x^n)$ or $(\sin(x))^n$?
Answer: No, it is not true. Take $x=\arcsin\left(\sqrt[n]{\frac12}\right)$. Then$$\sin^n(x)\bigl(1-\sin^n(x)\bigr)=\frac14.$$
Comment: thank you ! that's what i got but i saw it in the textbook and i doubted my result
Comment: If my answer was useful, perhaps that you could mark it as the accepted one.
Comment: can you please tell me if the sequence converges uniformly ?
Comment: I can tell you that it **doesn't** converge uniformly, since it converges pointwise to the null function, but $\sup\bigl\lvert\sin^n(x)\bigl(1-\sin^n(x)\bigr)\bigr\rvert=\frac14$.

Uniform convergence help


Can I make fields visible only if image attach has an image

Question: Is it possible to use CCK to add a conditional to the image attach module form where unless I have selected an image to use for a content node, certain fields are not visible?
Currently I do not have any operations available for my image attach field in my content type definition where configure and remove are available for all other fields.
Answer: This would be really simple in your theme, e.g. node-foo.tpl.php for the content-type foo, that has a field "video"
<?php if(!empty($field_video[0]['view'])): ?>

     <?php print $field_video[0]['view'] ?>

     <?php print $field_some_other[0]['view'] ?>
     <?php print $field_the_other_one[0]['view'] ?>
<?php endif; ?>

Some notes on style and best practices:
I prefer the if/endif in templates, others prefer the if() {}. Technically little difference, I think elseif; is more readable in HTML.
Technically it is not correct to simply print a value, but one should use drupal_render(). I personally still prefer print, because of its transparancy and simplicity. Drupal_render(), however, registers what it has "rendered" and allows you to drupal_render($node) at the end, to render all unrendered fields; very usefull if you decide to add fields later on, whithout having to change the entire template every time you do so. Drupal_render is not available in the tpl.php, but in the preprocessing: as sayd, a lot less transparent and slightly more complex.
Dont! Ever! print the $field_foo[0]['value'], always the ['view'] part: the first is unescaped and may (will!) contain XSS injections and the likes.
The strange nested array ($field_foo[0]['value']) is a result of the multiple-fields option in Drupal. A better way would be to always iterate over each field and never just render, hardcoded, the first ([0]) item. However, for reasons of readability, simplicity and transparancy, I prefer to hardcode the indexes in my template. Others (rightfully) disagree with me on this.
Comment: IMHO, there's nothing wrong with hardcoding the first ([0]) item as long as you're reasonably sure that the field will be single-value in the foreseeable future. Wrapping it in a foreach would be premature optimization (which is of course the root of all evil :-)).
Comment: "as long as you can be reasonable sure that" is fine indeed. However, your site should not break (as in: trow warnings, errors, open up sec.holes) either :)


Copula - Correlation Help

Question: I need some help with copula.
I am using the copula with either the multinormal or the student t kernel. I thought before that when I input in my correlation matrix, if I simulate enough random variates, and then take the correlation of those random variates, the resulting correlation matrix would converge to my input. This was not the case.
I am now informed that I need to adjust my correlation matrix before input to arrive at my target correlation matrix.
Can anybody share some light on this.
Answer: While I have yet to find the reason why, I think you need to perform a Cholesky-decomposition to your correlation matrix. The chol(X) function in R should do the trick, where X is your correlation matrix.
Bear in mind, I think I also read somewhere that if your correlation matrix is not positive definite the output of Cholesky-decomposition may not be unique. You can check using the function is.positive.definite(X) from the matrixcalc package.
Source: page 19

Copula - Correlation Help


I am unable to get "configure webhook " option within google chat

Question: As per the official documentation it lies inside chat room option. But its not available there.
Comment: Do you have a workspace account or is it a gmail.com one when you try to configure the webhook?
Comment: I have a personal gmail.com account, i guess "Enable webhook" option will only be enabled when i have a workspace account. So, i will create one then make this work ...thanks :)
Answer: Enable Webhook, the option can only be visible if you have a google workspace account. It's not available on the personnel's Gmail account.
Answer: The Configure webhook option is indeed available only for Workspace users so you will have to use a Workspace account in order to set it up.
As for the documentation, I have taken the opportunity to file this report in order to improve the documentation regarding this.
I suggest you star it as all the updates will be posted there.


Norm of an multiplication operator

Question: Let $C(\mathbb{R})$ be the vector spaces of all continuous maps on  $\mathbb{R}$. Then let $C_0(\mathbb{R})\subset C(\mathbb{R})$ with all maps $g(x)$ that go to $0$ as $x\rightarrow\pm\infty$.

Fix a $f\in C(\mathbb{R})$ and define $M_f:C(\mathbb{R})\rightarrow C(\mathbb{R})$ with $M_f(g)=g(x)*f(x)$. Suppose that $f$ is such that $M_f(C_0(\mathbb{R}))\subset C_0(\mathbb{R})$ and $M_f|_{C_0(\mathbb{R})}$ is bounded.
  1. Why is f bounded?
  2. Compute $||M_f||$?

To 2. I know that if the operator would just be defined on $[0,1]$ we have that $||M_f||=||f||_\inf$. Isn't it the same for this operator as well?
Thank you for your help!!
Answer: For $x \in \def\R{\mathbf R}$, $\def\eps{\varepsilon}\eps > 0$, let $g_{x,\eps}$ denote the function
$$
  g_{x,\eps}(t) = \begin{cases} 0, & t \le x-\eps\\
                              \frac{t-x+\eps}{\eps}, & x-\eps \le t\le x\\
                              \frac{x+\eps-t}{\eps}, & x \le t \le x+\eps\\
                                0, & t \ge x + \eps
                  \end{cases}
$$
Then $g_{x,\eps} \in C_0(\R)$ has support in $[x-\eps, x+\eps]$ and $\def\norm#1{\left\|#1\right\|}\norm{g_{x,\eps}}_\infty = 1$. As $M_f$ is bounded on $C_0(\R)$, we have
$$ \def\abs#1{\left|#1\right|}\abs{f(x)} = \abs{f(x)g_{x,\eps}(x)} \le \norm{fg_{x,\eps}}_\infty = \norm{M_fg_{x,\eps}}\le \norm{M_f} $$
Hence, $f$ is bounded with $\norm{f}_\infty \le \norm{M_f}$. On the other hand, we have
$$ \norm{M_fg}_\infty = \norm{fg}_\infty\le \norm f_\infty \norm g_\infty$$
giving $\norm{M_f}\le \norm f_\infty$. That is $\norm{M_f} = \norm f_\infty$.

Norm of an multiplication operator


Twitter Bootstrap 3 Inline Form with labels

Question: After searching everywhere i couldnt see exactly how i can design an inline form that has the following design: (using bootstrap 3 classes instead of css customizations when possible)
When the user has a wide screen:
 Form-Legend

     LabelFieldA: InputFieldA   LabelFieldB: InputFieldB   LabelFieldC: InputFieldC   <Submit Button>

When the user has a smaller screen:
Form-Legend

    LabelFieldA: InputFieldA   LabelFieldB: InputFieldB

    LabelFieldC: InputFieldC   <Submit Button>

The idea is that the design initially puts all the fields in one line and if it doesnt fit the controls would jump to the next line, but maintaining the Label + Field together.
Also if there is a way so the spacing between each Label + Input is greater than the spacing between the Label and its Field.
And lastly if there is a way of having more vertical margin between the Label + Field when it jumps to the next line.
Answer: Option #1 : fixed columns
You can use a structure mixing col-xs-12, col-sm-6 and col-lg-3 to get 1, 2 or 4 columns. Inside your form-group, remember to fix label/input sizes with col-xs-4 and col-xs-8 :

  <form class="form form-inline" role="form">

    <legend>Form legend</legend>

      Field A

        <input type="text" class="form-control" id="InputFieldA" placeholder="InputFieldA">

      Field B

        <input type="text" class="form-control" id="InputFieldB" placeholder="InputFieldB">

      Field C

        <input type="text" class="form-control" id="InputFieldC" placeholder="InputFieldC">

    <button type="submit" class="btn btn-default col-xs-8 col-xs-offset-4">Submit Button</button>

  </form>

You still need a few CSS :
// get a larger input, and align it with submit button
.form-inline .form-group > div.col-xs-8 {
    padding-left: 0;
    padding-right: 0;
}
// vertical align label
.form-inline label {
    line-height: 34px;
}
// force inline control to fit container width
// http://getbootstrap.com/css/#forms-inline
.form-inline .form-control {
    width: 100%;
}
// Reset margin-bottom for our multiline form
@media (min-width: 768px) {
  .form-inline .form-group {
    margin-bottom: 15px;
  }
}

You can add as many inputs as you want.

Bootply
Option #2 : fluid columns
To be able to not care of the number of fields per row, you can use this structure :

  <form class="form form-inline form-multiline" role="form">

    <legend>Form legend</legend>

      Field A
      <input type="text" class="form-control" id="InputFieldA" placeholder="InputFieldA">

      Very Long Label For Field B
      <input type="text" class="form-control" id="InputFieldB" placeholder="InputFieldB">

      F. C
      <input type="text" class="form-control" id="InputFieldC" placeholder="InputFieldC">

      Very Long Label For Field D
      <input type="text" class="form-control" id="InputFieldD" placeholder="InputFieldD">

      Very Long Label For Field E
      <input type="text" class="form-control" id="InputFieldE" placeholder="InputFieldE">

      Field F
      <input type="text" class="form-control" id="InputFieldF" placeholder="InputFieldF">

      <button type="submit" class="btn btn-default">Submit Button</button>

  </form>

And a few CSS lines to fix margins :
.form-multiline .form-group {
    margin-bottom: 15px;
    margin-right: 30px;
}
.form-multiline label,
.form-multiline .form-control {
    margin-right: 15px;
}

Bootply
Comment: Isnt there a way so i wouldnt have to foresee the number of items it will fit in each row? Also if i try to make the Submit Button smaller it disaligns from the rest of fields
Comment: For submit button : make col + offset + push equal to 12 : `col-xs-8 col-xs-offset-4`, or `col-xs-4 col-xs-offset-8`, etc... To get an automatic grid, see my edit.
Comment: You sir, are a wizard :). The second option was just what i was looking for. As a note, i saw that the 'form' class is not present in bootstrap 3. Also now i have to set custom css widths for the controls, as the col-xs classes uses % widths that dont work in your 2º bootply. I will use the second example with some changes: http://www.bootply.com/117291 suggestions?
Comment: Suggestions about ? You seems to follow the right ptah ! I would just avoid the double `col-xs-offset-1` (in fact, I would use `col-sm-offset-1` instead, to get more space on mobile devices). And you shouldn't use `control-label` if you want your labels to float near your inputs.
Comment: Thanks, the offset is meaningful when combined with the rest of the our web. I used control-label so i could style them specifically, in case we end having some extra label next to an input or replacing one (for readonly info fields)
Comment: I copied one of the form groups and pasted it into my form, yet it still appears on different lines. Why?
Comment: Great answer.  Any ideas for if you want to make a double column (ie a textarea) with the first solution?  Ideally the label would line up and the right side of the text box would as well.  Simply changing to xs-12 and 2, 10 column widths gets you close but it's not exact.
Answer: The same as option #1 from @zessx, but without overriding CSS. This one also aligns labels to the right to increase space between label-control pairs. Class "media" is there to add top margin without creating a custom class, but in general case it is better to have a custom one.

    <legend>Form legend</legend>

        Field A

            <input type="text" class="form-control" id="InputFieldA" placeholder="InputFieldA">

        Field B

            <input type="text" class="form-control" id="InputFieldB" placeholder="InputFieldB">

        Field C

            <input type="text" class="form-control" id="InputFieldC" placeholder="InputFieldC">

        <button type="submit" class="btn btn-default col-xs-8 col-xs-offset-4">Submit Button</button>

Bootply
Answer: I would propose something completely different, wrap the labels and fields inside inline divs:

  Label:input

This way, when they are about to break, they break in pairs, labels+inputs.
Answer: Alright I played with the grid system and this is as close as I could get to your setup.

    <form role="form" class="form-horizontal">

            Email

                <input type="password" class="form-control" id="inputPassword" placeholder="Password" />

            Password

                <input type="password" class="form-control" id="inputPassword" placeholder="Password" />

        <button type="submit" class="btn btn-default">Submit</button>
    </form>

This has two fields only. You might want to change the col classes to fit your layout.
jsFiddle
Comment: But in your example if i adjust the width of the window the 2º label + input doesnt jump to the line below. Take into account that it could have 3, 4 or even more pairs of labels + input that have to adjust to one or more lines depending on the available width.
Comment: As as I said you will have to adjust the `col` classes to fit the number of elements. You won't be able to create something so dynamic with bootstrap only. You will have to resort to some JavaScript or custom CSS in order to achieve that.
Comment: My closest attempts where with http://getbootstrap.com/css/#forms-inline instead of col classes as you dont have to define the number of elements there will be in each row...the problem is getting the labels + input together after jumping to the next row and aligning them in following rows correctly
Answer: You can try below
Working here- http://www.bootply.com/117807

First Name

<input type="text">

Last Name

<input type="text">

Contact

<input type="text">

Answer: The simplest way is to put both label and text input in cols div. Hope this will save time for all others :)

   City

     <asp:TextBox data-toggle="tooltip" pbpo-validation-type="required" title="City" runat="server" ID="textbox_city" CssClass="form-control input-sm" ClientIDMode="Static" placeholder=""></asp:TextBox>


Beginner trying to use jQuery in a custom location, but not sure where to insert the code

Question: At the moment, I'm working on a website that requires an on-mouse over effect where the things that are going to be displayed is an image. I figure that the best way to go about this is by using jQuery.
Being a beginner at Drupal, I've noticed that all of the content in this website is generated from database calls. I was wondering if there was a module or a way to see how these calls are made so that I may be insert the correct code at the right place.
Answer: If you are customising a theme, I would add a custom jquery script you have written. In your themes template.php you can then simply call the .js file from within the theme folder.
For example you could add this to your template.php file:
<code>drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME') . '/js/jquery.custom.js');
</code>
in the jquery.custom.js file you could have something like this:
<code>(function($) {

 $(document).ready(function() {

  // hover effect
  $(".hover_effect").hover(function() {
    //add effects here
  }

 });

}(jQuery));
</code>
Comment: Does this mean that in addition to what's being called at the moment, I will have to create a custom jquery script to enable this?
Comment: Well, you'd have to write the effect you'd want i guess, or customise an existing script. You'd still have to include it though. If you are going to add other effects, having your own seperate .js file makes sense. You could also instead of calling it all the time create a template file for that content type and include it there..
Comment: This makes a lot of sense!

Rather than just trying and pin-point the time of execution (which is taking me forever to figure out), develop something that is called whenever that object is instantiated.

Thanks for the guidance, tecjam!


Bare Json response of a WCF service in c#

Question: I have made a WCF service in .NET 4 platform, that when I hit it with a jquery ajax POST it returns JSON.
The issue that I have is that I would prefer if the json response of the POST is not wrapped in the name of the Method with the Result suffix.
In detail:
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
 ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    Person GetInfo(string id);
}

[AspNetCompatibilityRequirements(RequirementsMode
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service: Iservice
{
    public Person GetInfo(string id)
    {
           ...
           return new Person();
    }
}

public class Person
{
  public string FirstName;
  public string LastName;

  public Person(){
   FirstName = "Jon";
   LastName = "Doe";
  }
}

web.config
<system.serviceModel>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
   <behaviors>
     <serviceBehaviors>
       <behavior name="ServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="true"/>
       </behavior>
     </serviceBehaviors>
     <endpointBehaviors>
       <behavior name="EndpBehavior">
         <webHttp/>
       </behavior>
     </endpointBehaviors>
   </behaviors>
   <services>
     <service behaviorConfiguration="ServiceBehavior" name="Service">
       <endpoint address="" binding="webHttpBinding"
           contract="IService" behaviorConfiguration="EndpBehavior"/>
     </service>
   </services>
 </system.serviceModel>

jquery:
var myparameters = JSON.stringify({ id: $('#id').val()});
            $.ajax({
                type: "POST",
                url: "/Service.svc/GetInfo",
                data:myparameters,
                contentType: "application/json",
                dataType: "json",
                success: function (response) {
                      ...
                    }
                }
            });

With the BodyStyle = WebMessageBodyStyle.Wrapped the response a get in my javascript code is:
{"GetInfoResult" : {"FirstName":"Jon", "LastName":"Doe"}}

But when I change it to WebMessageBodyStyle.Bare and everything else remains the same, a 500 internal server error occurs.
Is it possible to return Bare json in my POST response without the Method+Result wrapper? If yes what am I doing wrong?
Thanks in advance
Answer: I think that WebMessageBodyStyle.Bare expects also a "bare" request, and you are sending an object from your javascript code, something like this : {id:'value'}  that will be translated as :
public class DTObject{
  public string Id { get; set; }
}

And your operation method expects only a string as parameter.
Try to make only your response "bare" like this WebMessageBodyStyle.WrappedRequest.
[Edit]
http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webmessagebodystyle.aspx


Filter views on Current user OR Administrator

Question: I have a total of 770 users, 760 with the custom role of "certified provider", 10 with the role of "certified administrator".
Using views, and relationships I am able to allow the certified provider to each see only their own created nodes. But I need the "certified administrator" to see ALL nodes from ALL providers.
I have a relationship of Content:Author, and filter of User:Current.
I have read everything I can get my hands on to figure out what to do  and where to go next.
Have tried to follow https://stackoverflow.com/questions/20840490/drupal7-filter-view-based-on-current-users-roles
But haven't been able to get the filter values to work.
Any help would be greatly appreciated.
Comment: How about just remove the filter of User:Current?
Comment: @Jimmy Ko When I remove the filter `User:Current`, then all the nodes are visible to all users.
Answer: When dealing with multiple roles, make sure the access control module has all the correct control settings. In Admin->structure->Content Type->Access Control I had the "View any **Content Type** content" checked. As soon as I removed that, the suggestion by @Jimmy Ko, worked, Thanks Jimmy.
 Easy to overlook when you have 3 different places where the content type is limited.


Meaning of Exact Transformation and $K$-Automorphism in the context of Ergodic Theory/Mixing

Question: I am reading MAGIC$010$ Ergodic Theory course. In this course's lecture $4$ notes, it is mentioned that
$1)$ Let $T$ be an exact transformation of the probability space $(X,B,μ)$ .Then $T$ is strong-mixing.
$2)$ Let $T$ be a $K$-automorphism of the probability space $(X,B,μ)$.  Then $T$ is strong-mixing.
I understand what strong mixing, automorphism and transformation mean but I do not know what "Exact transformation" and "$K$-Automorphism" mean in this context. The author has not defined $K$ anywhere else so I'm not sure if that is a variable. Can someone clear this up? Thanks!
I can attach the link to the notes if required.
Comment: For those interested, the lecture notes can be found [here](https://personalpages.manchester.ac.uk/staff/Charles.Walkden/magic/).
Answer: These definitions can be found in this article, page 11.
$\ $

Definition: A transformation $T$ of $(X, \mathcal B, \mu)$ is exact if $\cap^{\infty}_{n=0}T^{-n}\mathcal B$ consists entirely of null sets and sets of measure $1$.

$ \ $

Definition: An invertible measure-preserving transformation $T$ of $(X, \mathcal B, \mu)$ is said to be $K$ (for Kolmogorov) if there is a sub-$\sigma$-algebra $\mathcal F$ of $\mathcal B$ such that:

$\cap_{n=1}^{\infty}T^{-n}\mathcal F$ is the trivial $\sigma$-algebra up to sets of measure $0$ (i. e. the intersection consists only of null sets and sets of full measure).

$\vee_{n=1}^{\infty}T^n\mathcal F = \mathcal B$ (i.e. the smallest $\sigma$-algebra containing $T^n \mathcal F$ for all $n>0$ is $\mathcal B$).

I would not worry that much about these, since they do not appear anywhere else in Charles' lecture notes for Ergodic Theory.
Comment: I actually wanted to prove that a transformation is Ergodic but it was claimed that proving that transformation is Strong-Mixing is actaully easier (even though it is a stronger claim)
Comment: Wikipedia article for $K$-Automorphisms also mentions that $F\subset TF$. Is that redundant?
Comment: @Anvit Fhew, you got me there! I would not be able to say stright away; maybe asking another question about this would be the most sensible thing to do, as I don't know the answer for this.


How can I get labels from data generator?

Question: I try to generate data for my conditional VAE and I need labels, but after generating data when I want to get labels I got this error:
def gen_batch(BATCH_SIZE):
    labels = torch.randint(0, 8, (BATCH_SIZE,)).long().to(device)
    theta = (np.pi/4) * labels.float().to(device)
    centers = torch.stack((torch.cos(theta), torch.sin(theta)), dim = -1)
    noise = torch.randn_like(centers) * 0.1

    return centers + noise, labels

def data_gen(BATCH_SIZE):
    #8 gaussians
    while 1:
        yield gen_batch(BATCH_SIZE)
train_loader,train_labels = data_gen(args.batch_size)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-3bc469737639> in <module>
----> 1 train_loader,train_labels = data_gen(args.batch_size)

ValueError: too many values to unpack (expected 2)

how can I fix that?
Comment: try `next(data_gen(args.batch_size))`
Comment: data_gen() is a generator function and it returns a generator object
Comment: Yep the error is saying that you're trying create a tuple from a single object - generator object. Try with next. I wonder- couldn't you just yield gen_batch without a loop
Comment: @Goion can you post your comment as an answer (for future generations' sake)?
Answer: The exception was raised, because the data_gen() is a generator function, and such a function returns only a single object called a generator object, which cannot be unpacked like you tried to do. A generator object is an iterator that generates and returns data on demand and for that iterators support a special method called __next__, that returns only a single element at a time. However, you do not usually call this method directly. You either pass an iterator to the next built-in function, or you use it, for example, in a for loop that will call next() behind the scenes. Also, the important thing to remember is that after you have exhausted an iterator, you cannot use it again, and if you want to do that, you simply need to create a new one. In your case, though, you cannot exhaust your iterator, because you have an infinite while loop in the data_gen function. Here's an example:
def data_gen(BATCH_SIZE):
    #8 gaussians
    while 1:
        yield gen_batch(BATCH_SIZE)

gen_obj = data_gen(args.batch_size)
train_loader, train_labels = next(gen_obj)
# or:
gen_obj = data_gen(args.batch_size)
for train_loader, train_labels in gen_obj:
    # this is only an example and the for loop
    # will never end, because in
    # your case the generator is infinite
    pass


Is my limit proof ok? , with $f(x)^2$

Question: Thank you for your time!
I would like to check if my proof is ok here:
Prove: Let $\lim_{x\to\infty} f(x)= 4$. Prove that for every $M>0, x>M$, $15.5 < [f(x)]^2 < 16.5$.
So, I said that: $-\sqrt{15.5} < f(x) < \sqrt{16.5}$
$ |f(x)-L| < \epsilon$,
I chose $\epsilon = 0.05$, and than $-0.05 < f(x)-4 < 0.05$
From here, $3.95 < f(x) < 4.05$ and $15.6025 < [f(x)]^2 < 16.4025$
So $15.5 < [f(x)]^2 < 16.5$
Is that legit?
Thanks a lot!
Comment: Edited to use MathJax.
Comment: Welcome to Mathematics Stack Exchange.  This would be easier to read with [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).  I took the liberty of changing some tags
Comment: Not clear. It seems to me that you misunderstood the definition. I don't think it is correct to say "for every $M$...". It should be for every $\epsilon >0$, there exists an $M>0$ ...
Comment: This is the question... Thank you Tanner for helping me with MathJax!
Answer: I suspect the question should read, prove that if $\lim_{x\to\infty} f(x) = 4$ then there exists a number $M$ such that for all $x > M$,
$$15.5 < f(x)^2 < 16.5.$$
With this understanding, by definition of the concept of limit, for every $\varepsilon > 0$ there exists $M$ (dependent on $\varepsilon$) such that when $x > M$, $|f(x) - 4| < \varepsilon$.  That means,
$$ 4-\varepsilon < f(x) < 4 + \varepsilon.$$
Now you can square the inequality provided all terms are positive;  that will be the case if $\varepsilon$ is small enough, and so,
$$16 - 8 \varepsilon + \varepsilon^2 < f(x)^2 < 16 + 8 \varepsilon + \varepsilon^2.$$
Now just choose $\varepsilon$ so small that the left extreme is greater than $15.5$ and the right extreme is less than $16.5$.  For example $\varepsilon = 0.01$.  Then with the corresponding $M$ the required statement is true.
Of course you can get many different values for $M$ but your are only asked to show one exists.  Once you have on, any larger $M$ would also work.  Some smaller $M$ might also work depending on how finely you chose the first one.
Comment: Thank you so much! I will definitely try out this way!
The question indeed says that there exists an M>0 such that for every x>M, we have the statement. So yes, I do need to find an epsilon in this case. Thanks again!

Is my limit proof ok? , with $f(x)^2$


C++ recursion for connectivity graph

Question: I haven't implemented anything yet, but I was thinking of using recursion to identify all cells in a grid that are 'actively connected' to a given cell, i.e., cells that are 'active' and directly connected by virtue of sharing a face with the (active) cell in question or more distantly/indirectly connected by sharing a face with one of its (active) neighbors. The disconnections come about because some of the cells in the grid maybe deemed 'inactive' (by whatever definition). My idea/pseudo-code is as follows:
//Call function to traverse connections
traverse_connections(cell);

//Traverse function definition
bool traverse_connections(cell) {
  //Check if cell is inactive or traversed - base case
  if (current cell is inactive or traversed) {
     return true;
  }
  //-Mark cell then move on to its neighbors
  Mark cell as traversed and add it to the list of 'actively connected' cells;
  bool ok = true;
  for(neighbor_cell in neighbors of cell) {
     ok &= traverse_connections(neighbor_cell);
  }
  return ok;
}

I think this covers the base case, marks the cell, then moves on to do the same for its neighbors, its neighbors' neighbors, and so on. Does this look OK? Are there any obvious gaps I am missing? Would appreciate if anyone with expertise in graph connectivity and recursion can weigh in. I am also having trouble coming up with an iterative equivalent. Any ideas on that would be much appreciated too.
Thanks in advance!
Answer: This solution will not work, because it mixes up the concepts of "traversed" and "active/connected". The two are orthogonal: for example, a cell may be inactive and traversed, or active and not traversed. The if statement at the top of your pseudocode returns true for both, which is incorrect.
You should keep a table that marks cells traversed separate from the table that marks cells active. You need to make sure that a cell is marked traversed before going into the recursive call, otherwise the solution may be too slow, or even run out of stack.
Finally, the solution does not need to be recursive: you can accomplish what you need by a straightforward Breadth-first search, which can be done with a queue instead of recursion.
Comment: Thanks for your comment. I think I need to use BFS for a graph with cycle. Looked it up. Wasn't too hard actually.
Answer: The way you are marking the cells at the moment will most likely cause you problems. For example if one of these cells you are marking has neighbouring cells which need to be traversed later then they may go untraversed.
If you look into the A* (A-Star) algorithm it should give you a good idea of graph traversal. UCS (uniform cost search) is also another algorithm which uses graph traversal.
Comment: Thanks for the response, but I did some research on this and like @dasblinkenlight mentioned, I think what I need is a BFS for a graph with cycles. Haven't looked at the A* approach though, so I can't comment on whether it would've worked or not.

C++ recursion for connectivity graph


Are there terms to distinguish between the different levels of Drupal Core?

Question: "Core" seems to cover over a multitude of things, encompassing all the modules that ship with the Drupal code base.  But there seem to be levels of "core"-ness, and I'm wondering if there is official terminology to distinguish between these. For example:

There is the code that is not part of any module.  Does "core" include this officially?  It's not clear to me.
There are required modules: without these (at least in Drupal 7) you can't really build a Drupal site.
There are all the default modules that are part of Core.  You can turn many of these off without a problem, but they're still considered "core".
There are modules that are turned off by default (PHP Filter) and which may even be considered a bad practice to use under normal circumstances (PHP Filter, again).

If I were naming these levels, I might call them

The Drupal Kernel
Deep Core Modules
(Normal) Core Modules ("Core Modules" would include 2 and 4 as well)
Outer Core Modules

But it seems like Dries may have an official terminology already.  Is there such a thing?
Comment: You ask some very interesting questions :)
Comment: I just noticed on the page I linked to, the sentence "This would make Drupal's ***actual core*** (the group of required modules) far lighter and a better choice for apps that don't need content management, for instance."  It seems others are grasping for ways to make this distinction as well.  I'm not sure that "actual core" is an accurate way of expressing it, though, as it implies the other core modules are somehow pretending to be part of core, imposters or something.
Comment: _Actual core_ could simply mean _current core_.
Answer: I'm not aware of any official definition of the various levels.
I will however, referring to your suggestions, explain a bit about what levels there are.

The Drupal Kernel is actually a component in Drupal 8, which is a Symfony Kernel
"Deep Core Modules" could be the include files that are not even modules. Some files, for example database.inc, bootstrap.inc and module.inc are so fundamental that core cannot function without them. (There are some more .inc files however that reasonably could become modules, I don't know why they are not)
Core modules then, core parts that are written in the same style as contrib modules, but are still so fundamental that core wouldn't work without them. There's a system module that manages a lot of low level administrative functionality. The node module is (in D7) still required. Field sql storage cannot be turned of either.
Outer Core Modules, are all the other things that are shipped with core because they are commonly used, but not necessary for Drupal to function. The forum, taxonomy terms, the user interface for the field system etc.

Again, I'm not familiar with any official terminology, other than all of it being "Core". When people work on core, I only hear references to the individual "components" of core, as specific in the Drupal issue queue.
When I hear "actual core", I think of levels 1 - 3.
Comment: So you've heard "actual core" used often?
Comment: No, not until you've pointed the phrasing out. Hadn't noticed the choice of word either in the issue you've linked to, even though I've read it before.
Comment: Just as the Linux kernel is comprised of many files, if Dries asked me to define these terms ;) I'd consider the Drupal core to include database.inc, bootstrap.inc and module.inc as long as those are essential for Drupal's functioning.
Answer: If you can't turn the module off, it's Actual Core. If you can, it's Extended Core.
Comment: -1 because you make it sound like this is official in some way, yet you have no references.
Comment: "Can't" meaning you're not allowed to, or meaning you break Drupal by doing so?