How to access VPN server itself over a VPN set up with RAS?

Question: I created a split-tunnel VPN connection to a remote server (suppose name is ABC), so I could access both the Internet and resources on the remote network simultaneously from the client.
I can access the Internet fine, but I'm having trouble accessing the ABC server itself. The problem is that if I use the public IP which the VPN is connected to, it doesn't get routed over the VPN so I can't access secure resources. Of course, I can manually run a "route add" command to force traffic for that public IP over the VPN gateway, but I'm tired of doing that every time I connect the VPN.
When I run "route print", it looks like the only addresses it will forward by default over the VPN are in the range 192.168.1.0 - 192.168.1.100.
The question, therefore, is might the VPN server ABC be reachable on an address in that range, or can I set it up to have an address on that range so it is reachable through the VPN? Perhaps I can add some static address translation on the "Internal" VPN interface?
Comment: Does the VPN server in fact have an "internal" ip address assigned to it or does it only have a "public" ip address assigned to it?
Comment: The IPV4 routing shows 3 interfaces: Loopback, LAN 2, and Internal.  They all have IP addresses assigned, but the "Internal" IP is very close to the public IP, instead of being on the subnet "192.168.1.0/24".
Comment: I had everything working fine, with the ability to type "\\my.domain.com\" into explorer to access file shares, but this only worked when I manually ran a "route add" to ensure traffic to the IP resolved for "my.domain.com" is routed through the VPN gateway.  Windows simply can't figure out that traffic to the VPN server should be sent through the VPN gateway.
Comment: Seems to be a problem with Windows Server 2008.  With the Server's firewall completely off, I still cannot access file shares through the VPN gateway, even though I can connect to remote desktop over it.  Meanwhile, if I instead manually add a route to force traffic to the public IP to go over the VPN gateway, then somehow the file sharing works (with the firewall both on and obviously when off).  http://social.technet.microsoft.com/Forums/nl/winserverNIS/thread/835347a7-b0c9-4786-9339-5b73cf0e3dcb
Comment: Here is proof it's a windows problem.  When I run "Advanced Port Scanner" on the server, with absolutely no configuration changes (firewall off too), I get different results if I scan loopback (127.0.0.1) and public IP (not revealing) versus if I scan the VPN interface's IP (192.168.1.200).  When scanning 127.0.0.1 or the public IP, it shows 5 open ports including 445, but when I scan 192.168.1.200, port 445 is no longer listed.  WTF.
Comment: I found a solution involving installing a "Microsoft Loopback Adapter".
Answer: It was definitely a problem with Server 2008.
A workaround is to install a "Microsoft Loopback Adapter".
First of all, check the range of IPs you have assigned to your RRAS VPN Server and the network mask associated with it.  For example, I assigned mine the range 192.168.1.0-192.168.1.255, which results in an auto-generated network mask of 255.255.255.0.
The address of the VPN Server itself and all its shares will take on the first valid address in that range, so in this case it becomes 192.168.1.1.  Because of this BUG IN SERVER 2008, the ports for file sharing aren't open.  Here is where the Loopback Adapter comes in to play.  Once installed, you just give it an IP address like 192.168.1.2, and then use that address to access the shares.  Although it refers to the same machine as 192.168.1.1, it does not exhibit the bug that blocks the file sharing ports.
When finished, you must make sure your firewall is allowing communication to that IP address on the file sharing ports, because "Local Subnet" won't cut it (it would refer to your public IPs local subnet).  You'll have to manually add exceptions for 192.168.1.2 ports 129 and 445.  Note that even with the firewall OFF, that BUG prevents any communication with those ports on the VPN servers IP 192.168.1.1, which is why we have to use the loopback adapter to get around it.
To install the Loopback Adapter, go to Device Manager, right click first node which is your computer and choose "Add legacy hardware".  Alternatively, open control panel and type "add hardware" in the search box, and you'll see a result under Device Manager for "Install drivers for older devices with Add Hardware Wizard".
Next, choose "Install the hardware that I manually select from a list (Advanced)", then choose "Network Adapters" (next), then choose "Microsoft" as the manufacturer, then "Microsoft Loopback Adapter" from the Network Adapter list.
Once installed, you must configure it.  Go to it's IPV4 properties and give it an IP address in the range of local addresses for your RRAS VPN Server, which I mentioned I just used 192.168.1.2 (one number above the VPN server itself).  Also, give the loopback adapter a subnet mask that matches your VPN's address range (e.g. 255.255.255.0).  Leave the default gateway and DNS servers blank.
That's it.  Now you can access file shares on the loopback adapter's address from the remotely connected client.


When long dividing decimals 26/2.5 in 2:40-3:30 of this video why do we continue calculating for the quotient instead of stopping at 10 r10?

Question: Now we have a remainder that isnt 0 or over the divisor, why dont we put r10 to the end of the quotient and be done??wHY IS 10 R10 WRONG? No, we add a trailing zero and it leaves us winding up at 10.4, which I know IS right. But WHY don't we stop when we have 10 r10 at 2:40 in this video. And on a test why's this wrong?
VIDEO (https://www.youtube.com/watch?v=2PU5JshO0xA&index=7&list=PL45A96B834415F332Since)
Comment: An integer and remainder is technically correct. If you're asked to calculate $10\over3$, and write 3 remainder 1, that's equivalent to telling us $10=3\times3+1$. But, that's sort of like writing $\sqrt{9}$ as the answer to 'find the square root of 9' - the marking scheme for a test will probably want you to simplify the answer as much as possible. Similarly, writing the answer as integer and remainder isn't a form we'd call simplified as it just tells us $\frac{a}{b}=bd+r$, and so you should go for exact answers.
Comment: How do we know when wehave exact answers compared to a answer like 10 r10? i though it was ok to hve remainders.. how do we just pick n choose when we make our answer into a decimal?
Comment: Generally - answers with remainder are for when you're beginning to learn to do division, and that is what initially is taught in schools. But as you go further with the subject, these answers are no longer useful and you're required to give the answer in decimal or fractional form (you'll find that outside of tests, you'll be after these more when you're making calculations in general).
Comment: How do we know when we have to find exact answers compared to a answer like 10 r10? i thought it was ok to have remainders in the answer(which it's not here).. how do we know for sure when to add that trailing zero and not add r10 to the end of the problem but continue solving the problem?
Comment: In general - don't leave remainders in answers as it's actually not ok. The only time you leave remainders is when the questions says it's ok to do so.
Comment: Ohh so with all remainders i can keep soving the problem and find the decimal form of the answer instead of putting remainder x?
Comment: Yes. I haven't watched the video, so it might've already told you, but there are cases where you can have repeating decimals, and so you stop at that point once you realise that. You would then have a recurring decimal as your answer.
Comment: oh ok, i was just confused on why we added a trailing zero and continued solving the problem even after we had a remainder to put at the end of the answer thanks! im gonna rewatch the vid and learn how to thouroughly divide decimals.
Comment: one more time. so the gist is anytime we ave a remainder thats greater than zero we keep on solving the problem by adding trailing zeroes to the dividend so we can bring down those zeroes to the remainder so we can divide our divisor by or remainder and find the exact answer, but we stop once we know we hit repeating decimals.. is this conclusion right and does this apply with the majority division problems involving decimals?
Comment: I'd advise asking a separate question about long division if you have problems understanding it - I don't quite see what you mean by 'adding trailing zeroes' because I don't think that's what you do
Comment: watch 2:30-330 of the vid please
Comment: basically we do not keep remainders greater than zero and add that remainder to our answer. Instead we compute remainders and figure out the next step in the equation until we have a remainder of zero?
Comment: Ah I see what you meant by 'trailing zeroes'. Yes because $10=10.00000000000...$ for example.
Comment: shuri i see yur into coding as well, i see your into coding as well you should join my group https://www.facebook.com/groups/w3develops/
Answer: The original problem was to solve
$\begin{array}{rlcc}
   2.5\overline{)26}
\end{array}$,
which got changed to solving
$\begin{array}{rlcc}
   25\overline{)260}
\end{array}$.
$10\; R\; 10$ conveys the information that $260 = 10 \times 25 + 10$.
But it would take some work to find that $26 = 10 \times 2.5 + 1$; that is, the answer to the original problem is $10 \; R \; 1$.
The bigger problem is that $10\; R\; 10$ and $10\; R\; 1$ are not numbers.
The notation $\begin{array}{rlcc}
   2.5\overline{)26}
\end{array}$
provides a framework in which that value of the fraction $\dfrac{26}{2.5}$ can be converted into an improper fraction. The equivalent problem,
 $\begin{array}{rlcc}
   25\overline{)260}
\end{array}$,
and its solution, tells us that
$\dfrac{26}{2.5} = \dfrac{260}{25} = 10\dfrac{10}{25}$; which is much more useful.


Black and white 3D scatterplot?

Question: For any $i \in \{1,2,\ldots, 9801\}$, we have 3 dimensional vectors $\mathbf{a}_i$ and $\mathbf{b}_i$ that take values in $\mathbb{R}^3$, where $\mathbf{a}_i = (a_{i,1}, a_{i,2}, a_{i,3})$ and $\mathbf{b}_i = (b_{i,1}, b_{i,2}, b_{i,3})$.
For any $i$, the difference between the vectors $\mathbf{a}_i$ and $\mathbf{b}_i$ is that:

For $\mathbf{a}_i$, the first two components are found empirically, but the third component $a_{i,3}$ is defined analytically as a function of the first two components $a_{i,1}$ and $a_{i,2}$. In other words, $\mathbf{a}_i = \big(a_{i,1}, a_{i,2}, f(a_{i,1}, a_{i,2})\big)$.
But for $\mathbf{b}_i$, all of the components are found empirically.

For all $i \in \{1,2,\ldots, 9801\}$, the figure below depicts $\mathbf{a}_i$ by red dots, and $\mathbf{b}_i$ by black dots.

My problem here is that I am unhappy with the use of multiple colours as I have to stick to black and white for compatibility with non-colourful printers.
My question is: How can I distinguish these two surfaces using only black and white?
Other input:

The number of dots are $9801 = 99 \times 99$ for each surface
Comment: Care you share the formula for a, to facilitate answers with examples?
Answer: I suggest you to plot the two surfaces as:

One surface is dark grey.
The other is light grey.

Then add transparency to both of them.
The 3D mesh surface would imply that you are using linear interpolation for values of $\mathbf{a}_i,\mathbf{b}_i \in \mathbb{R}^3$ that do not exist in your set of $9801$ points. Is this a problem?
If that's not a problem, then I think your problem is solved (unless I am missing something).
If that is a problem, then you may try the same, but try to see if you can draw dots with transparency.

Black and white 3D scatterplot?


Can Adjusting the Truss rod of the guitar crack the neck?

Question: I wonder if anyone can help me here.
I bought a used guitar from Ebay and it looked fine at first sight.
The action needed adjusting and I tune to Eb so I decided to adjust the truss-rod.
I turned it clockwise a couple of times and it felt like it came loose so I thought, "Well, the Truss-Rod is broken". And I can't adjust this guitar :o/
I then looked at the neck and I could see a crack right behind the locking nut.
I really don't think it could have been me as I didn't turn the rod tight of nothing like that but I wanted to check if it's possible to crack a neck by adjusting the truss-rod.
Here's a picture of the damage:

Hope someone can help.
Answer: You can cause damage by turning the truss rod too tight, but normally a few quarter turns one way or the other will be just fine.
That photo looks like the guitar has been dropped and the head has hit the ground.
So possibly you tightening the truss rod has just forced a damaged neck to split further.
Answer: That does not look like damage that might be caused by overtightening the truss rod, but perhaps improperly tightening the truss rod broke loose a poorly repaired broken headstock. When tightening a truss rod, the guitar neck should be clamped into the desired amount of back stress and then tighten the truss rod just enough to hold the neck in the desired shape. Many a truss rod has been broken by trying to tighten and straighten the neck without first clamping the neck into the desired shape. To better understand the correct technique, I recommend reading Dan Erlewine's book on guitar maintenance and repair.
Answer: Probably turned the truss rod too fast, turn like 1/4 then wait like 30 minutes to an hour for it to set it then to it again, the wood takes time to set in so going to fast will put to much pressure


How to add custom named colors to Material-UI Theme

Question: I would like to add a named color to my theme such as warn
import React from 'react'
import { MuiThemeProvider } from '@material-ui/core/styles'
import createMuiTheme from '@material-ui/core/styles/createMuiTheme'

const theme = createMuiTheme({
  palette: {
    primary: { main: '#30b5c8', warn: { main: '#000000' } },
    secondary: { main: '#fadc35' },
    warn: { main: '#ff9100', light: '#ffa733', dark: '#b26500' },
  },
})

export default ({ children }) => {
  return <MuiThemeProvider theme={theme}>{children}</MuiThemeProvider>
}

However, the warn property of this object is ignored by material-ui. Is it possible to add this color/property?
Material-ui's palette once rendered
  {
    common: { black: '#000', white: '#fff' },
    type: 'light',
    primary: {
      light: '#7986cb',
      main: '#3f51b5',
      dark: '#303f9f',
      contrastText: '#fff'
    },
    secondary: {
      light: '#ff4081',
      main: '#f50057',
      dark: '#c51162',
      contrastText: '#fff'
    },
    error: {
      light: '#e57373',
      main: '#f44336',
      dark: '#d32f2f',
      contrastText: '#fff'
    },
    grey: {
      '50': '#fafafa',
      '100': '#f5f5f5',
      '200': '#eeeeee',
      '300': '#e0e0e0',
      '400': '#bdbdbd',
      '500': '#9e9e9e',
      '600': '#757575',
      '700': '#616161',
      '800': '#424242',
      '900': '#212121',
      A100: '#d5d5d5',
      A200: '#aaaaaa',
      A400: '#303030',
      A700: '#616161'
    },
    contrastThreshold: 3,
    getContrastText: [Function: getContrastText],
    augmentColor: [Function: augmentColor],
    tonalOffset: 0.2,
    text: {
      primary: 'rgba(0, 0, 0, 0.87)',
      secondary: 'rgba(0, 0, 0, 0.54)',
      disabled: 'rgba(0, 0, 0, 0.38)',
      hint: 'rgba(0, 0, 0, 0.38)'
    },
    divider: 'rgba(0, 0, 0, 0.12)',
    background: { paper: '#fff', default: '#fafafa' },
    action: {
      active: 'rgba(0, 0, 0, 0.54)',
      hover: 'rgba(0, 0, 0, 0.08)',
      hoverOpacity: 0.08,
      selected: 'rgba(0, 0, 0, 0.14)',
      disabled: 'rgba(0, 0, 0, 0.26)',
      disabledBackground: 'rgba(0, 0, 0, 0.12)'
    }
  }

Comment: I would suggest to look  at this [answer](https://stackoverflow.com/questions/50069724/how-to-add-multiple-material-ui-palette-colors)
Comment: I do not see the same theme result as what you are showing (https://codesandbox.io/s/theme-palette-pm4hb). The palette you're showing doesn't even include your customizations to `primary` and `secondary`. You seem to be looking at the default theme rather than the theme created by your code.
Comment: Ah yes indeed Ryan. Very good point. I had not realised this.
Answer: You need the function createPalette, you can see the  definition here. Sadly that function is not exposed, so, you had two ways to do what you want:

Get out that function and use it.
Make it the variants of colors with this website and with that result choose wisely every lighten and generate contrastText with the function getContrastRatio located in '@material-ui/core/styles'.


Array com inputs e um dado específico!

Question: só aqui mesmo pra resolver certas coisas.
Estou quebrando a cabeça para fazer esse loop mas não consegui ainda.
Como eu faço para colocar o destaque nessa array() sendo que somente 1 dessas fotos será marcada com o valor 1.
$fotos = $this->input->post('fotos[]');
$destaque = $this->input->post('destaque[]');

$foto = array();

foreach ( $fotos as $item => $value){
    array_push($foto, array(
        'idFoto' => $id,
        'img' => $value
        'destaque' => $
    ));
}

O resultado que espero é algo assim:
array(
array(idFoto => 1,
img => 1.jpg,
destaque => Null),

array(idFoto => 2,
img = 2.jpg,
destaque => 1), //Nesse caso o radio foi checado

array(idFoto => 3,
img => 3.jpg,
destaque => Null)
);

No caso do html eu faço o input de várias fotos e uma delas eu seleciono como destaque.
Comment: O destaque é um _array_ também? O que tem na variável `$destaque`? é o índice de algum elemento do _array_ `$fotos`?
Comment: $destaque vem de um radio e se checado grava um valor 1 mas é somente um das fotos vai conter o valor 1. no caso eu me esqueci de colocar o colchete ai...mas o colchete não é a questão...
Comment: No caso *destaque* é o ID da foto ou o índice do array? Pode dar um exemplo do resultado final que você espera?
Comment: @JacielPlacidino cada foto tem um _radio button_?
Comment: Pra ficar mais fácil, você pode fazer um `var_dump` das variáveis `$fotos` e `$destaque` e/ou também postar o HTML referente ao formulário, colocando essas informações no corpo da pergunta clicando em [editar](http://pt.stackoverflow.com/posts/82275/edit) logo abaixo da sua pergunta.
Comment: @KaduAmaral sim pra cada foto tem um radio destaque[].
Comment: @JacielPlacidino, tente assim em cada rádio coloque o `value` com um número de `0` incrementando um a cada foto, `0,1,2,3,...` e ali no loop coloque assim `'destaque' => ($destaque == $item ? 1 : 0)`.
Answer: Use o foreach para alterar o 'status' do destaque quando o idFoto combinar com o valor do $destaque. Fiz um exemplo com array no Ideone, mas deixei aqui apenas o loop.
O resultado é o destaque = 1, apenas no array de índice 1( correspondente a foto idFoto 2)
foreach( $fotos as $n => $foto )
{
    if( $foto['idFoto'] === $destaque /* 2 */ )
    $fotos[$n]['destaque'] = 1;
}

Output
Array(
    [0] => Array(
            [idFoto] => 1
            [img] => 1.jpg
            [destaque] =>
        )

    [1] => Array(
            [idFoto] => 2
            [img] => 2.jpg
            [destaque] => 1
        )

    [2] => Array(
            [idFoto] => 3
            [img] => 3.jpg
            [destaque] =>
        )
)

Answer: Um exemplo de como fazer tipo de implementação é da seguinte forma:
Formulário
<form>
   <?php
      for($i=0;$i<5;$i++){
   ?>
   <input type="text" name="foto[<?=$i?>]"><input type="radio" name="destaque" value="<?=$i?>">

   <?php
      }
   ?>
</form>

PHP
<?php
   // Fotos é um array
   $fotos = $this->input->post('fotos');
   // Destaque é o número do índice da foto que será o destaque
   $destaque = $this->input->post('destaque');

   $foto = array();

   foreach ( $fotos as $item => $value){
       array_push($foto, array(
           'idFoto' => $id,
           'img' => $value
           'destaque' => intval($item == $destaque)
       ));
   }

?>

A expressão $item == $destaque verifica se o índice do elemento atual no loop é igual ao número do destaque que retornará true ou false
a função intval transformará o resultado boolean em numérico 1 ou 0.

Array com inputs e um dado específico!


Android Studio HAXM Not installed

Question: HAXM is not getting installed after installing also.
In my BIOS, I have enabled VT-X this is also not working any suggestions or help would be helpful.
I'm using Lenovo ThinkPad x220(intel(R) CORE TM i5-2520M CPU @ 2.50 GHz).
Comment: i m using windows 7 os
Answer: HAXM and Hyper-V can't work at the same time. Try unchecking Hyper-V and Windows Hypervisor Platform under Search bar -> Turn Windows Features on or off. Also, try installing HAXM from their repository https://github.com/intel/haxm/releases/tag/v7.6.5 instead of going through Android Studio. That worked for me.
Windows Features Hyper-V unchecked

Android Studio HAXM Not installed


How to name this ninth chord?

Question: C-E♭-G-B-D
How should this chord be named?

This chord has a root of C. It is used similarly to Cm(maj7) in G major
(think Great Pumpkin Waltz by Vince Guaraldi's B section: G Cm(maj7) G [this chord])
Should it be Cm(maj9)? Cm(maj7/9)? Something else?
Answer: The most concise way would be Cm(maj9) since the maj9 suggests both a major 9th and a major 7th in addition to the base triad of Cm.
What's most important, in my opinion, is labeling it with C as a root. I can certainly imagine some people viewing this as an E♭ augmented chord with major seventh and an add6 in the bass, but this would destroy its obvious function as (in this case) some type of IV in the Guaraldi example.
Comment: I completely agree with Cm(maj9). I do not understand why (and actually doubt that) Cm(maj7/add9) is clearer. 'add9' is used to indicate that there's no 7 in the chord; otherwise 9 (or maj9) implies a 7, as is the case here.
Comment: @MattL. Maybe I've just played with too many people that don't know what a maj9 is... But thanks, I'm glad to hear that others don't find this confusing!
Comment: @MattL agreed, add2, add9 should mean those tones added to a plain triad not a seventh chord. Same with sus4 or sus2. IMO that should mean the third is not present or else the 'sus' doesn't make much sense.
Answer: Cm(maj7) is a chord used often enough to be included in the list of 'seventh' chords. So, Cm(maj9) should be sufficient to mean C Eb G (B D).
Were it Cmaj 7, it would comprise C E G B; Cmaj9 would be C E G B D. So, for me, there is no confusion involved calling it Cm(maj9), as the '9' part usually automatically includes a 7. If it's dominant 9, that'll be b7 and ordinary 9, if it's maj9, it'll be ordinary 7 and ordinary 9. If it's #9, it will have to say '#9'. Same goes for b9.

How to name this ninth chord?


Affix não para corretamente no rodapé

Question: Estou tentando criar um Affix com o Bootstrap mas estou tendo problemas para ele parar corretamente no rodapé.
Ele buga, e a classe .affix-bottom não fica aplicada corretamente. Quando passo do offset bottom rodando o scroll ele para normal, mas  se eu desço arrastando a barra de rolagem ele não para.
E também na hora de voltar para cima, ele fica aplicado o position:relative que impossibilita a classe .affix de funcionar corretamente na subida.
Demonstração
Answer: Tinha um erro no css, corrigido .affix-bottom.{ para .affix-bottom{.
Corrigido
PS.: Desculpe a falta de atenção, mas eu fiquei a manhã toda brigando com essa "bobeira".

Affix não para corretamente no rodapé


C incompatible pointer to integer array

Question: Trying to do a rank based voting algorithm. Rank tells order of voter preference. For example if rank is 0, this is the first choice of the voter. I'm trying to save the order of names to the array but it doesn't work.
Error is at the ranks[rank] = name;
<code>bool vote(int rank, string name, int ranks[])
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(name, candidates[i]) == 0)
        {
            ranks[rank] = name;
            printf("rank was successfuly recorded");
            return true
        }
    }

    // TODO
    return false;
}

</code>
Comment: `name` is a string, `ranks[rank]` is an `int`. What do you expect the assignment to do?
Comment: Maybe what you want is `ranks[rank] = i;`?
Comment: It's not a syntax error.
Comment: thats a good idea, i will try it thanks barmar
Answer: Your are trying to store a String value in int array.
Either change the type of ranks array to String or change type of name to int.

C incompatible pointer to integer array


A binomial identity question.

Question: I need to calculate
$$\sum_{k=1}^{n}\binom{k}{m_1}\binom{m_2}{k}(-1)^k$$
where $1\leq m_2 \leq m_1 \leq n$. Any help or tips on how to proceed?
Thanks in advance.
Comment: Probably want $m_1\leq m_2,$ because the sum is zero when $m_1>m_2.$
Comment: Note that
$$(1-(1+x))^{m_2}=\sum_{k=0}^{m_2}\binom{m_2}{k}(-1)^k(1+x)^k$$
$$=\sum_{m_1=0}^{m_2}\sum_{k=0}^{m_1}\binom{k}{m_1}\binom{m_2}{k}(-1)^kx^{m_1}$$
Comment: Please do not edit to change the question after you get an answer. If you have a new question, please make a new post.
Answer: Hint: $$\binom{m_2}{k}\binom{k}{m_1}=\binom{m_2}{m_1}\binom{m_2-m_1}{k-m_1}$$

A binomial identity question.


Converting/adding support for multiple instances of a jQuery plugin

Question: I've forked the filamentgroup daterangepicker* which seems to be no longer maintained, in order to include some posted fixes and address the issue of it only supporting a single datarangepicker on a page.
I've read the how to docs on setting up a jquery plugin and for setting up a jquery widget. But the issue with widget is that if you pass multiple elements to the widget it will create a separate widget for each element. One feature of the daterange picker is to pass 2 input fields to supply as the start and end of a single daterange. So the multiple elements treated separately is not useful in this case.
So is there other best practices beside using $.widget to convert an existing plugin to allow having mutiple uses of it on a page.
I'm guessing that the vars defined in the plugin closure just need to be not there unless they are static values used for all instances, the instance specific vars would need to be associated with the selector passed in via a data attribute or an id that the plugin keeps an indexed array of? Am I on the right track? missing something else beside just the vars defined?
Any pointers or examples for how to add support for multiple instances of a jquery plugin are appreciated.
*the origin code is from - http://filamentgroup.com/examples/daterangepicker_v2/
on git - https://github.com/filamentgroup/jQuery-UI-Date-Range-Picker/blob/master/js/daterangepicker.jQuery.js
Comment: Is that first link a git repo? Just clicking it I get a Forbidden error.
Comment: sorry @Jared I corrected the link, seems it was a redirected url
Comment: I still have the same problem. Are you required to be logged in to get to that link?
Comment: I changed the link again. The new link is the example page; in the example's green headerbar is the link that has the details
Answer: One aspect of best practice would be to invoke the plugin on empty containers (divs/spans) and to generate the two date fields on initialisation.
That way, you could create as many datespan widgets as you need with a single statement and with minimum effort in preparing the HTML.
This tutorial provides arguably the best plugin pattern available. It's an awkward cuss right up to the moment you realise it's super-cool.


Pegar primeiro elemento da linha e ultimo

Question: Tenho uma li e queria pegar os elementos que estão escritos MARCADO abaixo.
Porém usei o nth-of-type, funciona para pegar o 4 elemento sempre, porém não consegui fazer pegar o próximo.
Alguém conseguiria me ajudar a pegar sempre 1 depois do primeiro item onde está escrito marcado?

 ul li&:nth-of-type(1){color: red;}
 ul li&:nth-of-type(4n){color: red;}

number MARCADO

number

number

number MARCADO

number MARCADO

number

number

number

number MARCADO

number MARCADO

number

number

number

number MARCADO

number MARCADO

number

Answer: Tente utilizar o :nth-child assim:

ul li:nth-child(1) {
  color: red;
}
ul li:nth-child(4) {
  color: red;
}
ul li:nth-child(5) {
  color: red;
}
ul li:nth-child(9) {
  color: red;
}
ul li:nth-child(10) {
  color: red;
}
ul li:nth-child(14) {
  color: red;
}
ul li:nth-child(15) {
  color: red;
}

number MARCADO

number

number

number MARCADO

number MARCADO

number

number

number

number MARCADO

number MARCADO

number

number

number

number MARCADO

number MARCADO

number

Comment: Essas LI's podem ser cadastráveis, ou seja, podem ter milhoes de li's.
Aí não ocnseguiria fazer assim.
Comment: Qual é o padrão ? se você deseja uma sim/outra não você pode usar `ul li:nth-child(2n){
    color: red;
}
`
Comment: Se não tiver um padrão certo e somente houver uma marcação no texto indicando que ela deva possuir tal configuração acredito que você terá que verificar o valor com javascript e adicionar o css
Answer: para o seu caso, você precisa pegar a cada 5 elementos, e não a cada 4 elementos, desta forma você também vai fazer um seletor para o elemento anterior (5n - 1)

ul li:nth-of-type(1){color: red;}
ul li:nth-of-type(5n - 1){color: red;}
ul li:nth-of-type(5n){color: red;}

number MARCADO

number

number

number MARCADO

number MARCADO

number

number

number

number MARCADO

number MARCADO

number

number

number

number MARCADO

number MARCADO

number

Comment: Obrigado, funcionou!!


Tabs: invalidating cache tags does not lead to a rebuild of the tabs

Question: I have a custom route defined with a custom access check. Apart from some more checks one of the rules for accessing the path is that a specific custom entity exists. The access check does the following:
  public function access(AccountInterface $account) {
    if ($entity_does_not_exist) {
      return AccessResult::forbidden()->addCacheTags(['my_unique_cache_tag']);
    }
  }

In my custom entity class I defined the postSave and postDelete methods to invalidate this tag every time an entity is created or deleted:
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage, $entities);
    foreach ($entities as $entity) {
      \Drupal::cache('render')->invalidate('my_unique_cache_tag');
    }
  }

  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);

    if (!$update) {
      \Drupal::cache('render')->invalidate(ParliamentPeriodCCController::getCacheTag('my_unique_cache_tag');
    }
  }

My problem is that my custom route is used as a secondary tab in my_module.links.task.yml. What I found out so far is that the tabs are rendered in a block which really gets my unique cache tag (as I see in cache_render table - this is why I defined  \Drupal::cache('render') above - \Drupal::cache() did not work neither) but it seems it never gets invalidated. When I enter a page where the secondary tab was not created because no entity exists it is still not shown when I create the entity afterwards. But when I delete the entry for the block from cache_render it is rendered correctly.
Answer: Two suggestions to improve caching:

Even if you don't want to make a decision to allow or deny access you can return a neutral result to add cache metadata.

The custom cache tag can be replaced by the list tag ENTITY_TYPE_list, which is invalidated automatically when entities are added or deleted.

The resulting code:
  public function access(AccountInterface $account) {
    if ($entity_does_not_exist) {
      return AccessResult::forbidden()->addCacheTags(['my_entity_list']);
    }
    return AccessResult::neutral()->addCacheTags(['my_entity_list']);
  }

postDelete() and postSave() are no longer necessary.
Comment: Thank you very much - this is cool!!!


Fazer redirecionamento para página anterior: PHP vs. JavaScript

Question: Qual é a maneira mais vantajosa para fazer o usuário voltar para a página anterior. Por exemplo, no frond-end ficaria assim:
Voltar

Já no back-end seria algo semelhante a isso:
<a href="<?php echo $_SERVER['HTTP_REFERER']; ?>">Voltar

Qual é a abordagem mais adequada?
Existem abordagens melhores?
Quais alternativas mais seguras existem para fazer isso no back-end?
Comment: No front-end, pois é quando os dados já foram gerenciados no banco e recebeu uma resposta de que está tudo okay (ou não).
Comment: @EdwardRamos Como assim? Ambos os redirecionamentos da pergunta são no frontend, a única diferença é que o primeiro utiliza a API `history` do navegador e a segunda define a URL com base nos dados da requisição recebida pelo PHP.
Answer: Importante salientar que as suas duas soluções fazem o redirecionamento no frontend. Não é porque tem um trecho de PHP ali que ele faz no backend; o PHP só será responsável por gerar o HTML entregue pela resposta HTTP.
Primeira regra do desenvolvimento web? Você não fala sobre desenvolvimento web. Segunda regra do desenvolvimento web? Você não fala sobre desenvolvimento web. Terceira regra do desenvolvimento web? Jamais confie nos dados da requisição HTTP recebida.
A sua segunda opção, talvez não saiba, é inteiramente baseada em um dado da requisição HTTP que o PHP está tratando, referente ao cabeçalho HTTP Referer. A própria documentação do PHP, que já deve ter lido, te alerta sobre ele:

HTTP_REFERER
O endereço da página (se houver) através da qual o agente do usuário acessou a página atual. Essa diretiva é informada pelo agente do usuário. Nem todos os browsers geram esse header, e alguns ainda possuem a habilidade de modificar o conteúdo do HTTP_REFERER como recurso. Em poucas palavras, não é confiável.

Partes destacadas por minha conta. Resumindo, não há justificativas para você deixar sua aplicação dependente de algo que pode não estar definido e, quando está, pode não ser confiável.
Por outro lado, você tem uma API para gerenciamento de histórico estável, gerenciado pelo próprio navegador. Seu usuário está em um navegador, sua intenção é que ele volte a página anterior, ninguém melhor para te dizer qual é esta página que o próprio navegador.
Fora isso, a API history do navegador é compatível com as alterações que a própria aplicação pode querer fazer no histórico. A aplicação pode, por exemplo, fazer uso de history.pushState para definir pontos no histórico para estados da própria página e permitir que o usuário queira navegar entre tais estados com as ferramentas do navegador. A título de exemplo, pode ser desejado que após aberto um modal na tela o botão Voltar do navegador feche-o fazendo com que o usuário retorne ao estado anterior, que era a página com o modal fechado. Nesses casos, seu link para voltar estaria condizente com o comportamento da própria aplicação. Com o link definido com PHP o usuário seria redirecionado independente dos estados internos da página.
Portanto, utilize window.history.back(), ele é suportado por 97.04% dos navegadores atuais, conforme Can I Use.
Comment: @rcs Como assim usar sessões? Não entendi a relação entre a sessão e o redirecionamento para a página anterior.
Comment: Aí depende exclusivamente dos requisitos do sistema. Fazer redirecionamento no frontend ou no backend são coisas bem distintas.


Interpretation of VAR results on R

Question: I am trying to run VAR on the first differences of XLE and Brent futures. Prior to this I have already tested that the series in levels are I(1) and are not cointegrated.
Below are my results using VAR in the VARS package in R and I'm not really sure what I should be looking at - could someone shed some light on the interpretation please? Many thanks!
<code>> Diff1VAR<-VAR(data.frame(XLE.Diff1,Brent.Diff1),type=c("const"),p=2)
> summary(Diff1VAR)

VAR Estimation Results:
=========================
Endogenous variables: XLE.Diff1, Brent.Diff1
Deterministic variables: const
Sample size: 175
Log Likelihood: 470.915
Roots of the characteristic polynomial:
0.3968 0.3968 0.3812 0.3514
Call:
VAR(y = data.frame(XLE.Diff1, Brent.Diff1), p = 2, type = c("const"))

Estimation results for equation XLE.Diff1:
==========================================
XLE.Diff1 = XLE.Diff1.l1 + Brent.Diff1.l1 + XLE.Diff1.l2 + Brent.Diff1.l2 + const

                Estimate Std. Error t value Pr(>|t|)
XLE.Diff1.l1    0.024898   0.101310   0.246    0.806
Brent.Diff1.l1 -0.043074   0.073885  -0.583    0.561
XLE.Diff1.l2    0.087136   0.100689   0.865    0.388
Brent.Diff1.l2  0.045034   0.070635   0.638    0.525
const           0.005842   0.004818   1.212    0.227

Residual standard error: 0.06313 on 170 degrees of freedom
Multiple R-Squared: 0.01663,    Adjusted R-squared: -0.006507
F-statistic: 0.7188 on 4 and 170 DF,  p-value: 0.5802

Estimation results for equation Brent.Diff1:
============================================
Brent.Diff1 = XLE.Diff1.l1 + Brent.Diff1.l1 + XLE.Diff1.l2 + Brent.Diff1.l2 + const

                Estimate Std. Error t value Pr(>|t|)
XLE.Diff1.l1    0.254914   0.137533   1.853   0.0655 .
Brent.Diff1.l1  0.069256   0.100301   0.690   0.4908
XLE.Diff1.l2    0.275127   0.136690   2.013   0.0457 *
Brent.Diff1.l2 -0.099845   0.095890  -1.041   0.2992
const           0.005070   0.006541   0.775   0.4394
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.0857 on 170 degrees of freedom
Multiple R-Squared: 0.07946,    Adjusted R-squared: 0.0578
F-statistic: 3.669 on 4 and 170 DF,  p-value: 0.006809

Covariance matrix of residuals:
            XLE.Diff1 Brent.Diff1
XLE.Diff1    0.003985    0.003544
Brent.Diff1  0.003544    0.007344

Correlation matrix of residuals:
            XLE.Diff1 Brent.Diff1
XLE.Diff1      1.0000      0.6551
Brent.Diff1    0.6551      1.0000
</code>
Comment: What are you looking for? Are you conducting a descriptive / explanatory / predictive study?
Answer: Recall that VAR is a reduced form model and as such its coefficients are difficult to interpret. You could refer to impulse-response functions (IRF) and forecast error variance decomposition (FEVD) to see how the variables develop and affect each other. You could test for Granger causality as well.
Note that the model's $R^2$ is very low (adjusted $R^2$ is even negative) and the $F$-statistic is not statistically significant. Hence, a model including only an intercept in each equation could be superior to your current model. This should not come as a big surprise since oil price (or changes in oil price, as in this model) is notoriously difficult to predict. I would be more surprised if a VAR model was successful here.
Comment: Thanks @Richard, I am trying to conduct a predictive study. What do you mean by a model that includes only an intercept in each equation, and how do I do that?
Comment: I mean $y_t=\beta_0+\varepsilon_t$, the simplest possible model.
Comment: Hi @Richard, i'm sorry if my questions sound really silly but what are we looking for here in a VAR result? My understanding is that we are looking for how the variables interact, so I should look at the correlation scores between XLE.diff1 Brent.diff1, assuming that the F-stat is statistically significant and R-squared is high. Are these the only results that should be of concern when i look at the results? Also, do you know of any VAR or VECM walkthroughs online that I can read more on? Very much appreciated!
Comment: Correlation scores? What is that? Also, what you look for in the model depends almost entirely on what you intend to use the model for. Since you mentioned your goal is prediction, you could test for Granger causality that is intimately related to prediction. It would show whether one variable is useful when predicting the other. You could also conduct a forecasting exercise by having a rolling window within your original sample, specifying and estimating your model there, and checking how well its forecasts match the actual realized values. Done properly that would be an honest evaluation.

Interpretation of VAR results on R


solve: $ \frac {d^2y}{dx^2} + 5\frac{dy}{dx} = 15x^2$

Question: $$ \frac {d^2y}{dx^2} + 5\frac{dy}{dx} = 15x^2 $$
It's solution is
$$y = y_{h} + y_{p}$$
where $y_{h} $ is the solution for homogenous equation and $y_{p} $ is the particular solution
For homogenous solution:
It's auxiliary equation is
$$m^2 + 5m = 0$$
on solving for m,
$$m = 0, -5$$
so, $$y_{h} = C_{1} + C_{2} e^{-5x}$$
here
$$R = 15x^2$$
so it's particular solution should be :
$$y_{p} = K_{2}x^2 + k_{1}x + k_{0}$$
on differentiating with respect to x
$$y\prime _{p}= 2xk_{2} + k_{1}$$
again
$$y\prime\prime_{p} = 2k_{2}$$
using all above values in the initial equation gives
$$2k_{2} + 10xk_{2} + 10k_{1} = 15x^2$$
But using this method I am unable to proceed for the value of all unknown especially $k_{0}$
The given answer is:
$$y = C_{1} + C_{2}e^{-5x} + x^3 + \frac{3x^2}{5} - \frac{6}{25}x$$
Comment: Choose $k_0$ at your desire: any additive constant will vanish on the left hand side of the given equation.
Comment: @fwd for terms $x^n , y_{p} = K_{n} x^n + k_{n-1}x^{n-1} + ..... k_{0}$ isn't it?
Comment: you're right @AbhilekhGautam.
Answer: HINT
Notice the proposed equation is equivalent to a first order ODE:
\begin{align*}
y'' + 5y' = 15x^{2} & \Longleftrightarrow y' + 5y = 5x^{3} + c_{0}\\\\
& \Longleftrightarrow \exp(5x)y' + 5\exp(5x)y = 5\exp(5x)x^{3} + c_{0}\exp(5x)\\\\
& \Longleftrightarrow [\exp(5x)y]' = 5\exp(5x)x^{3} + c_{0}\exp(5x)\\\\
& \Longleftrightarrow \exp(5x)y = 5\int\exp(5x)x^{3}\mathrm{d}x + \frac{c_{0}}{5}\exp(5x) + c_{1}\\\\
& \Longleftrightarrow y = 5\exp(-5x)\int\exp(5x)x^{3}\mathrm{d}x + \frac{c_{0}}{5} + c_{1}\exp(-5x)
\end{align*}
Can you take it from here?
Comment: Yes, you can. It is a just a matter of preference. But I advise you to integrate once before tackling the problem. In general, if you have an equation of the form $y' + ay = P(x)$, where $P$ is a polynomial of degree $k$ and $a\neq 0$, then one particular solution is also a polynomial of degree $k$.
Comment: I think I can do this from here, Cannot it be done in the way I did it?
Answer: $$\frac {d^2y}{dx^2} + 5\frac{dy}{dx} = 15x^2$$
$$v' + 5v = 15x^2$$
Where $v=y'$-
Try $v_p=Ax^2+Bx+C$ for the particular solution.
Comment: Thank you @Fakemistake .................


Inequality from AMM problems section

Question: This is Problem 12024 of AMM.
It asks to show that if $x,y,z$ are positive reals, and $xyz=1$, then $(x^{10}+y^{10}+z^{10})^{2}\geq 3(x^{13}+y^{13}+z^{13})$.
I could show it for the particular case of $z=1$, when it becomes a one variable polynomial inequality.
For the general problem, I thought about homogenizing, by multiplying the right side by $(xyz)^{\frac{7}{3}}$, but couldn't make progress.
Comment: I would Substitute $$x=\frac{a}{b},y=\frac{b}{c},z=\frac{c}{a}$$
Comment: I appreciate that you waited until after the submission period to ask this question. (I can also appreciate wanting to know a solution before the solution is published in $x$ many more months --- I remember anxiously waiting to see how some contest problems were done, back in the day).
Comment: yes, it seems $x\geq 20$ months these days.
Comment: This is very similar to https://math.stackexchange.com/questions/2732128/prove-this-inequality-by-abc-1, maybe it could help.
Answer: We'll prove that
$$\left(a^{10}+b^{10}+c^{10}\right)^2\geq3(a^{14}+b^{14}+c^{14}),$$ where $abc=1,$  for which it's enough to prove that
$$(x^5+y^5+z^5)^2\geq3xyz(x^7+y^7+z^7)$$ for positives $x$, $y$ and $z$.
Indeed, let $x=\min\{x,y,z\}$, $y=x+u$ and $z=x+v$.
Hence, $$\left(x^5 + y^5 + z^5\right)^2-3xyz\left(x^7 +y^7 + z^7\right)=$$
$$=(u^2-uv+v^2)x^8+8(-u^3+2u^2v+2uv^2-v^3)x^7+$$
$$+4(5u^4-17u^3v+50u^2v^2-17uv^3+5v^4)x^6+$$
$$+8(11u^5-20u^4v+25u^2v^2+25u^2v^3-20uv^4+11v^5)x^5+$$
$$+2(63u^6-79u^5v+50u^4v^2+100u^3v^3+50u^2v^4-79uv^5+63u^6)x^4+$$
$$+4(24u^7-21u^6v+5u^5v^2+25u^4v^3+25u^3v^4+5u^2v^5-21uv^6+24v^7)x^3+$$
$$+2(21u^8-12u^7v+10u^5v^3+25u^4v^4+10u^3v^5-12uv^7+21v^8)x^2+$$
$$+(10u^9-3u^8v+10u^5v^4+10u^4v^5-3uv^8+10v^9)x+(u^5+v^5)^2\geq$$
$$\geq\left((u^2-uv+v^2)x^2-8(u+v)(u^2-3uv+v^2)x+4(5u^4-17u^3v+50u^2v^2-17uv^3+5v^4)\right)x^6.$$
Let $u^2+v^2=tuv$.
Hence, $t\geq2$ and it remains to prove that $$(t-1)(5t^2-17t+40)-4(t+2)(t-3)^2\geq0,$$ which is true because
$$(t-1)(5t^2-17t+40)-4(t+2)(t-3)^2=$$
$$=t^3-6t^2+69t-112=t(t-3)^2+60t-112\geq0.$$
Id est, it's enough to prove that
$$x^{14}+y^{14}+z^{14}\geq x^{13}+y^{13}+z^{13},$$ where $x$, $y$ and $z$ are positives such that $xyz=1$, or
$$x^{42}+y^{42}+z^{42}\geq (x^{39}+y^{39}+z^{39})xyz,$$ which is true by Muirhed because
$$(42,0,0)\succ(40,1,1).$$

Inequality from AMM problems section


Erro "'object' does not contain a constructor that takes 1 arguments"

Question: Queria saber por que está acontecendo esse erro.
Eu criei uma classe que extende outra, mas quando chamo o construtor dela (classe pai) gera um erro.
Ali fala que não existe um construtor com 1 parâmetro, mas como podem ver na segunda imagem, existe sim.
Comment: Provavelmente a classe que você está tentando herdar não foi reconhecida... Tenta mudar o nome da classe que você está criando ou verifique se está faltando alguma referência ou inclusão do using dos namespaces usados.
Comment: Estaria aparecendo erro nela, e eu não conseguiria ver a  "definição" dela (Peek Definition), já importei tudo certinho.
Answer: No seu código:
class MySQLConnection : MySqlConnection

No código da superclasse:
public sealed class MySqlConnection : DbConnection, IDisposable, ICloneable

Basicamente, você não deveria herdar de MySqlConnection. Não há porque fazer isso e aquele sealed na declaração da classe diz que é proibido herdar dela.
Não sei o que você está tentando fazer, mas seja o que for, você não deveria tentar herdar de MySqlConnection.
Além disso, ter duas classes cujo nome só difere em maiúsculas/minúsculas é uma péssima prática de programação, pois é muito confuso.
Comment: Ah, claro, nem tinha percebido esse modificador lá, vlw.


Retornar View usando View Data ASP .NET MVC

Question: sou iniciante em ASP Net e estou em fase de "estudos", queria saber porque meu código está dando erros de atributos. Estou usando um método POST para mandar os atributos para uma VIEW. Segue em anexo imagem do problema.
View da minha HOME:
@model PostGetModel.Models.Pessoa
@{
    ViewBag.Title = "Index";
}

<form action="/Home/Lista" method="post">
    <fieldset>
        <legend>Pessoa</legend>

            Código da pessoa

            <input type="number" value="3" id="IdPessoa" name="PessoaId"/>

            Nome da pessoa

            <input type="text" value="@Model.Nome" id="Nome" name="Nome" />

            Twitter da pessoa

            <input type="text" value="@Model.Twitter" id="Twitter" name="Twitter" />

<input type="submit" value="Enviar" />

    </fieldset>
</form>

JPG do meu problema.

Essa é minha primeira pergunta no Stack OverFlow, estou grato por fazer parte dessa comunidade e se alguém puder me ajudar. Mil desculpas se não expliquei direito. Qualquer coisa dou um EDIT.
Comment: Bem vindo Breno. Algumas melhorias que pode fazer na pergunta: coloque a mensagem do erro e não a imagem, coloque o fonte da controller e não a imagem. Prefira sempre texto, quando este for possível.
Comment: Breno assim que fizer as correções que o George mencionou podemos ajudar. Estou aguardando e te ajudo.
Comment: Por favor não use imagens para mostrar códigos, leia https://pt.meta.stackoverflow.com/a/5485/3635, então após isto o que for mensagem de erro e código transforme em texto e edite sua pergunta.
Answer: Uma maneira mais interessante, seria você passar os dados para o model e recupera-lo na View.
Exemplo:

Preencha sua lista, ou seus dados no model;
Depois, retorne os valores para dentro da View, return View(obj);;
Na view, referencie o @model para o modelo de dados criado no controlador;
Nos componentes, utilize o Razor, como por exemplo um TextBox
@Html.EditorFor(model => model.propriedade.

Conheça mais sobre Razor.
Answer: Ocorreu esse erro pois o campo IdPessoa está nulo.
Para resolver esse problema:
1) Realizar um bind da Model com o campo IdPessoa:
     <input type="number" value="3" value="@Model.IdPessoa" id="IdPessoa" name="PessoaId"/>

2) Eu alteraria no Action Lista para receber a como parâmetro a Model:
     public ActionResult Lista(Pessoa model)

Answer: O Name da tag input deve ser igual ao parâmetro no Controller.
Aqui está "PessoaId"
<input type="number" value="3" id="IdPessoa" name="PessoaId"/>
E no Controller está "idPessoa".


Migrating input formats causes errors

Question: I am trying to write custom migrations to migrate my Drupal 7 website to Drupal 8. I am currently using Drupal 8.6.7 and Drupal 7.61 for a copy of the production website.
So far I have set up the D8 website with composer (docroot is path/to/web) (https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies )
I have always used Drush for maintenance actions on the D7 site
and I am using Drush 9 for most of the actions including the migrations on the D8 site.
I have installed the most relevant modules in the D8 site so that I can start the migration,
most notably all the D8 equivalents of the modules I used in the text formats/filters as well as migrate_plus, migrate_tools and migrate_upgrade.
The migration files are generated with the Drush command:
drush @dev migrate-upgrade "$LEGACYDB" "$LEGACYURL" --configure-only --migration-prefix=osn_custom_

So far I have successfully migrated the users and their roles so I have some knowledge on how migrations work.
The problem I am currently working on is the migration of a custom content type called 'classified'. This type has a default Drupal 7 body field and a field 'field_image'. So quite ordinary.
When I use the default generated migration file, it looks like everything is migrated, but the text is not visible. After research I found this is caused by the fact that the input format is set to the D7 code (in my case 2 aka 'full html') while there is no filter code in D8 that is called '2'.
(src: https://www.drupal.org/docs/8/upgrade/known-issues-when-upgrading-from-drupal-6-or-7-to-drupal-8#d7_to_d8 ).
I decided that I might as well convert 2 to 'basic html' and use the D8 configuration and not migrate the D7 text filters at all.
I created a migration lookup plugin with a static map that converts all D7 codes to the preferred D8 code.
It might work well, but I am running into the problem that I can't get the migration plugin to work with the migration of the 'classified' migration configuration. So I decided to simplify it and set the format to a default value 'basic_html'.
Here is what I tried in the migrate_plus.migration.osn_custom_d7_node_classified.yml
The code snippets below only show the body configuration, because the other field configurations are generated with the drush command and not altered.
body: body

the default. Content is migrated, input format is set to '2'.
According to this: https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/migrate-process-overview#nested
and this: https://medium.com/drupal-stories-an-insiders-view/migrate-api-custom-drupal-to-drupal-migration-3bab05da4686
and this: https://www.phase2technology.com/blog/drupal-8-migrations
it should be done like this:
  'body/format':
    plugin: default_value
    default_value: basic_html

  'body/value': body

However, this results in the following error:

[error]  InvalidArgumentException: Placeholders must have a trailing
  [] if they are to be expanded with an array of values. in
  /path/to/dev/web/core/lib/Drupal/Core/Database/Connection.php).
[error]  Placeholders must have a trailing [] if they are to be
  expanded with an array of values.
  (/path/to/dev/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:783)

I have no clue what is wrong and what I should do instead. I also don't know how to debug this to find out what it's expecting.
Can someone please give me some pointers?
Comment: Try to take a look here, https://www.drupal.org/project/drupal/issues/2639556
Comment: Yes! That works. Thank you @Jdrupal ! I will answer this question to help others avoid spending days figuring this out.
Comment: I'm glad to hear it worked :)
Answer: Thanks to @Jdrupal I finally found the solution in this link.
  body:
    plugin: sub_process
    source: body
    process:
      value: value
      format:
        plugin: default_value
        default_value: basic_html

(sorry I can't seem to get the mention appropriately formatted)
Comment: This worked for me too (thanks!), with one change. According to [the d.o Migrate Process Plugins documentation](https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/list-of-core-migrate-process-plugins), `iterator` has been deprecated and replaced with `sub_process`.
Comment: Thanks. I kept finding all sorts of other methods, but this is what worked for me.

Migrating input formats causes errors


Developing a custom virtual keyboard for Windows 10

Question: I would like to create a custom virtual keyboard for touch on Windows 10.  I am primarily a c# developer but if Windows 10 Dev is anything like the previous version, I'll probably have to revert back to C/C++.  I want to be able to define everything, shape, regions, and data that it spits out when keys are pressed.
Windows 10 has a keyboard selection menu (see picture), I would like it to integrate with this so that it can be used with the native keyboard interfaces.

I'm an experienced programmer of business applications but I have no idea where to start with this.  I saw this article for a Windows 7 keyboard but I'm hoping that things have changed for Windows 10.
My questions are:

Is it possible to create a custome virtual keyboard that integrates natively?
How do I integrate it with the Windows 10 Virtual Keyboard selector (pictured)?
Where do I start?

Any help/direction/words of wisdom would be appreciated.
Update: I think maybe I haven't explained it very well.  I want to build a virtual keyboard that isn't in the same shape as a normal one and essentially works like a shortcut keyboard.  You tap a key and it insert a preset snippet of text in to the context window.  And is selectable from the virtual keyboard options pictured (blue bit).
Comment: Would this [Keyboard Layout Manager](http://www.klm32.com/index.html) or [MS Keyboard Layout Creator](https://msdn.microsoft.com/en-us/goglobal/bb964665.aspx?f=255&MSPPError=-2147217396) help?
Comment: @Mottie: I don't believe so.  From what I understand that just allowed you to make custom layouts for physical keyboards.  What I'm looking to do is define an entire new keyboard layout.  Kind of like how the split keyboard has a different layout to the standard one.
Answer: Update:
I just tried using the Keyboard Layout Manager... OMG, so much easier to use than MSKLC, and it works on Windows 10; but I was still seeing the "Unavailable input method" message.

Actually, I just added a custom layout using MS Keyboard Layout Creator.
Changing the layout also modifies how the physical keyboard maps keys.
The trick is you can develop a new layout on Windows 10, but you can't use the "Build DLL and Setup Package" method on Windows 10 because the program needs .NET frameworks 2.0. I tried installing v2.0 on my system, but it just would not do it. I was able to build the files on a Windows 8.1 system.
Steps to take:

Download & install MS Keyboard Layout Creator on a Windows 8.1 or older systemv
Make sure .NET Framework 3.5 (includes .NET 2.0 and 3.0) or older is installed
Design your layout; before saving, make sure to remember what base language is set.
Project > Validate Layout
Project > Build DLL and Setup Package
A folder containing the following structure will be created ("mylayout" will be the name you chose)
<code>mylayout
 |_ amd64
 |  |_ Mylayout.dll
 |_ i386
 |  |_ Mylayout.dll
 |_ ia64
 |  |_ Mylayout.dll
 | wow64
 |  |_ Mylayout.dll
 |_ Mylayout_amd64.msi
 |_ Mylayout_i386.msi
 |_ Mylayout_ia64.msi
 |_ setup.exe
</code>
Install the appropriate file
The custom keyboard should now show up as a dropdown in the virtual keyboard, if not select "Language preferences".
You should now be on the "Country or Region" page. From here if the keyboard is based on a language, the language will show up here, or it may be added in an existing language (e.g. "English (United States)")... click on the language, then select "Options".
You should see your custom keyboard added here. If not, select "Additional date, time & regional settings", then "Change input methods". Then click on the "Options" in the custom language. It should let you preview the layout from here.

Caveat: Initially, I chose a base "UK" layout & a Gaelic language option showed up. This did add an option to the virtual keyboard language selector, but on the second time around I started with a base US Dvorak layout and the selection would not show up for me. In the control panel input method section, I saw a "Unavailable input method" message. I'm not sure how to get around that issue.
Maybe you'll have better luck.
Comment: I was right this doesn't do what I'm after.  I think maybe I haven't explained it very well.  I want to build a virtual keyboard that isn't in the same shape as a normal keyboard and essentially works like a shortcut keyboard.  You tap a key and it insert a preset snippet of text in to the context window.  And is selectable from the virtual keyboard options pictured above.
Comment: I have a feeling that this isn't doing quite what I'm after but I'll give it a go and report back.
Comment: Does MS Keyboard Layout Creator support to create for mobile?


SSH banner: asking for confirmation

Question: It's standard practice to put a banner on SSH login notifying the user that a system belongs to somebody, "you may be subject to prosecution" etc. However, this banner scrolls past harmlessly.
Is there any way of requiring the user answer the question, "Do you accept? y/N" before they can proceed?
(This question isn't about the legal or practical value of having the banner or the confirmation step, just whether it's technically possible)
Comment: You can add a simple bash script in /etc/profile so that it will execute on each login for all users & store the answer in some file along with their username, timestamp.
Answer: Based on serverliving.com's comment, I solved this by writing a file <code>/etc/profile.d/confirm.sh</code> saying:
<code>#!/bin/bash

if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
        while true; do
                read -p "Do you accept the terms and conditions? [y/N] " yn
                case $yn in
                        [Yy]* ) break ;;
                        [Nn]* ) exit 1 ;;
                esac
        done
fi
</code>
This fires on any SSH session, but not on non-SSH sessions. The major downside is that it doesn't fire on non-interactive shells that ignore profile, for example:
<code>$ ssh somehostname ls
</code>
The exact wording of the prompt is up to you of course, and the message only makes sense following a copy of the terms being agreed to.

SSH banner: asking for confirmation


XSD key with multiple fields

Question: I have structure like this:
<parent>
    <name>p1</name>
    <child>
        <name>c3</name>
        <name>c1</name>
    </child>
</parent>
<parent>
    <name>p2</name>
    <child>
        <name>c1</name>
        <name>c2</name>
    </child>
</parent>

What I want is to have another section which values should be validated againts first section. So that
<parent name="p1">
    <child name="c3" />
</parent>

or
<parent name="p2">
    <child name="c2" />
</parent>

should be valid, but neither
 <parent name="p1">
    <child name="c2" />
 </parent>

nor
<parent name="p2">
    <child name="c4" />
</parent>

I was thinking about using key with multiple fields
<xs:key name="k">
    <xs:selector xpath="tns:parent" />
    <xs:field xpath="tns:name" />
    <xs:field xpath="tns:child/tns:name" />
</xs:key>

but is seems that this approach can never work because key fields should be unique.
Is it possible to do this with XML Schema 1.0?
Comment: dup: http://stackoverflow.com/questions/891324/xsd-key-keyref-hierarchical-key-structure
Answer: Correct, the multiple child/name elements within the parent definitions are the problem. Too bad XML Schema doesn't allow XPath parent steps, since you could then select on the child name:
<xs:key name="pcdef">
  <xs:selector xpath=".//tns:parent/tns:child/tns:name"/>
  <xs:field xpath="../../tns:name" />
  <xs:field xpath="." />
</xs:key>

XSD key with multiple fields


What's the highest number of points without winning the Premier League?

Question: In the 2018-19 Premier League season, Liverpool finished 2nd with 97 points. Has any team ever got more points than this without winning the league?
Answer: According to Wikipedia, it is:

Most points in a season without winning the league: 97, Liverpool (2018–19)

It's not surprising since the record for most points is 100, only three higher (by Manchester City, the previous season).


Finding the exact value of the sine of the angle between a line and a plane

Question:
I have done part (a). For part (b), I know the principle of how to do it, I tried to use the cross product to find the exact value of the sine of the angle.
So I found PQ which is $$\begin{pmatrix}7-2\\-1-1\\2-6\end{pmatrix}$$
$$=\begin{pmatrix}5\\-2\\-4\end{pmatrix}$$
Then I do the cross product between $$\begin{pmatrix}5\\-2\\-4\end{pmatrix}$$ and $$\begin{pmatrix}5\\-3\\-1\end{pmatrix}$$ which the normal vector for the plane equation given
and using $$||{\bf a} \times {\bf b}|| = ||{\bf a}|| \, ||{\bf b}|| \sin \theta,$$ I got the answer to be $\sqrt (490)/\sqrt (490)$ which makes $sin\theta =1$ but the answer states that  $sin\theta = \sqrt 7/3$. Where did I go wrong?
Thank you and sorry in advance for any wrong tags and title labelling.
Comment: Please check calculations
Comment: I checked it 3 times @ArchisWelankar, which part did I go wrong? the cross product?
Comment: The determinant
Answer: Use the scalar product to find the cosine of the angle between $PQ$ and the normal. The angle between the line and the plane is $90 -$ this, so the sine of the required angle is the same as the cosine you obtain from the scalar product. You don't need to use cross product at all.
Comment: Why to run away from vector product
Comment: You can use vector product if you want, but you will obtain the sine of the angle between the plane normal and PQ. You would then have the cosine of the required angle, so you would have to calculate the sine of that...
Comment: We want sine not cosine
Comment: I know, but the angle between the line PQ and the normal is the complementary angle to the angle between the line PQ and the plane.
Answer: See the determinant is $-10i+15j-5k$ so its $\sqrt{350}$ and rhs is $\sqrt{45\times 35}.sin\theta=\sqrt{1575}.sin\theta$ so $$\sqrt{\frac{350}{1575}}=sin\theta$$ solving you get $sin(\theta)=\sqrt{7}/3$. Thats all
Answer: The angle angle between line $PQ$: $(5, -2, -4)$  & the normal  to the plane:$(5, -3, -1)$ is given by using dot product as $$\cos^{-1}\left(\frac{(5, -2, -4)\cdot (5, -3, -1)}{|5, -2, -4||5, -3, -1|}\right)=\cos^{-1}\left(\frac{35}{\sqrt {45}\sqrt{35}}\right)=\cos^{-1}\left(\frac{\sqrt 7}{3}\right)$$
hence the angle between plane & the line $PQ$ $$\theta=\frac{\pi}{2}-\cos^{-1}\left(\frac{\sqrt 7}{3}\right)$$$$=\color{red}{\sin^{-1}\left(\frac{\sqrt 7}{3}\right)}$$
or $$\sin\theta=\frac{\sqrt7}{3}$$
Answer: You are using cross product instead of dot/scalar product. It should be:
$$ a . b = ||a||~||b|| sin \theta $$
$$ sin\theta = \frac{a.b}{||a||~||b||} = cos\alpha $$
$\theta$ is the angle between the line PQ and the plane.
$\alpha$ is the angle between the line PQ and the normal to the plane, (5,-3,-1).
$$ sin\theta = \frac{(5,-2,-4).(5,-3,-1)}{||(5,-2,-4)||.||(5,-3,-1)||} $$
$$ = \frac{35}{\sqrt{45} ~.~ \sqrt{35}} $$
$$ = \frac{7~.~5}{\sqrt{9}\sqrt{5} ~.~ \sqrt{7}\sqrt{5}} $$
$$ \implies sin\theta = \sqrt{7}/3 $$


How to setup squid only cache specific domains?

Question: For example, I want squid to cache HTTP contents only for *.archive.ubuntu.com, which is blocked by firewall, and don't cache for other domains.
And, only LAN (192.168.0.0/16) users can access the cached contents, but all users are allowed to access non-cached contents.
User-IP              Dest-Domain                    acl             Expect
----------------     -----------------------       ------      -------------------------
192.168.0.0/16       *.archive.ubuntu.com          allow       Cache Proxy, Fast
192.168.0.0/16       *.other                       allow       Pass Proxy, Slow
Other                *                             allow       Pass Proxy, Slow

Answer: This is a bit of a dodge, but if you only care about auto-cacheing debian/ubuntu packages, try approx:
apt-get install approx

This requires that the clients be configured to download package lists from your proxy server, instead of the usual ubuntu servers but if you already use configuration management software like puppet or cfengine this is easy.
Your sources.list file would look something like this:
deb  http://my.proxy.tld:9999/ubuntu/  lucid  lucid main restricted universe multiverse
deb http://my.proxy.tld:9999/ubuntu-security/ lucid-security main restricted universe multiverse
...

And your approx.conf file like:
ubuntu http://us.archive.ubuntu.com/ubuntu
ubuntu-security http://security.ubuntu.com/ubuntu
...

Comment: apt-cacher-ng is another good apt repository proxy.


Two 'correct' (?) methods for differentiation and integration.

Question: So in my book of formulas there are two rules (among others) for differentation:
x^n goes to nx^(n-1)
and
ln x goes to 1/x
the corresponding rules for integration are:
x^n goes to (x^(n+1)/n + 1) + c
and
1/x goes to ln|x| + c
When I differentiate 1/x^3 I do so as follows:
1/x^3 = x^-3 so dy/dx 1/x^3 = -3x^-4.
Why when I integrate -3/x^4 can I not just do the following:
-3/x^4 = -3x^-4 so integral of -3/x^4 = -3* 1/-3 x^(-4+ 1) + c = x^-3 + c = 1/x^3 + c
Why must the answer be ln |-3/x^4|?
Comment: The fourth rule says that $\int x^{-1}dx=\ln |x|+c.$ It doesn't say $\int x^{-2}dx=\ln x^2+c.$ In only applies when the exponent is $-1.$ For that reason the third rule holds only if $n\ne -1.$ In other case you would have to divide by zero, which is not defined.
Comment: It is $\displaystyle\int \dfrac{-3}{x^4}dx=x^{-3}+c.$ Why do you say that the answer must be $\ln|-3x^{-4}|?$
Comment: I agree with what @mfl says but if one looks at the forth rule (in bold) [which is writen in the Cambridge booklet MF9] it suggests differently and that is the crux of my question. I doubt Cambridge is wrong so what am I missing?
Answer: The "rules" for differentiation are
\begin{align}
\frac{d}{dx} x^n &= nx^{n - 1}, \\
\frac{d}{dx} \log x &= \frac1x
\end{align}
I put the word "rules" in quotation marks because these are not
arbitrary rules that someone decided upon; they're simply facts that
inevitably result from the definition of differentiation.
One thing you cannot do with the rules is simply replace $x$
with some other expression (such as $x^4$) on both sides of the equation.
For example, suppose I know that $\frac{d}{dx} x^2 = 2x$, and I
wish to differentiate $x^6$.
I also know that $x^6 = \left(x^3\right)^2$.
So I might be tempted to write $2\left(x^3\right)$ and say
that this is the derivative of $x^6$. But that would be wrong.
Integration is just as uncooperative with naive substitution, if not more so.
It is true that
$$\int x^2 \; dx = \frac{x^3}{3} + C.$$
But you cannot just replace $x$ by $x^3$ in the functions on the left and right:
$$\int \left(x^3\right)^2 \; dx \neq \frac{\left(x^3\right)^3}{3} + C.$$
Similarly, while it is true that
$$
\int \frac1x \; dx = \ln \lvert x \rvert + c,
$$
this most emphatically does not mean that you can simply replace
the $x$ in $\frac1x$ with $x^3$ to get $\frac{1}{x^3}$ and then
have the logarithm of a multiple of any power of $x$ on the right.
Your book almost certainly never told you to do that.

As an aside, there are legitimate ways to substitute functions of $x$ into an
integral and get true equations as a result,
but they require you to change the variable of integration (the $dx$
in the integral) as well as the function being integrated.


Behat\Laravel can't find submit

Question: I'am trying to test my Laravel app by Behat.
There is a homepage with fields for name, email and "Register" button. I'm trying to press button in behat-test, but I have an error Fatal error: Call to a member function press() on null (Behat\Testwork\Call\Exception\FatalThrowableError)
My HTML:

    <title>Registration</title>

        <form action="/thanks" name="register">

Please, enter your name and e-mail

<input name="name" type="text" value="name">

<input name="email" type="text" value="e-mail">

<input name="registerButton" type="submit" value="Register">

        </form>

My FeatureContext function:
/**
 * @When I press the :submit
 */

public function iPressTheSubmit($submit) {
    $element=$this->getSession()->getPage()->findButton($submit);
    $element->click();
}

Scenario:
Scenario: Register Test
Given I am on the homepage
When I press the "registerButton"
Then I should be on "/thanks"

Output:

Scenario: Register Test                    # features/regpage.feature:4
      Given I am on the homepage               # FeatureContext::iAmOnHomepage()
      When I press the "registerButton" submit # FeatureContext::iPressTheSubmit()
        Fatal error: Call to a member function press() on null (Behat\Testwork\Call\Exception\FatalThrowableError)
      Then I should be on "/thanks"            # FeatureContext::assertPageAddress()
  --- Failed scenarios:
      features/regpage.feature:4
     1 scenario (1 failed)
     3 steps (1 passed, 1 failed, 1 skipped)

behat.yml:
default:
    extensions:
         Laracasts\Behat:
            # env_path: .env.behat
         Behat\MinkExtension:
            default_session: laravel
            base_url: localhost:8000
            laravel: ~
Comment: Fatal error is because the element is not found and the findButton returns null and you are trying to press on null. use a wait condition to wait for element that throws exception if the element is not found. have you tried $this->getSession()->getPage()->pressButton('yourButton');  ?
Answer: I fixed it with 2 steps:
 1. Setting APP_KEY parameters in .env and .env.behat files
 2. Fixing FeatureContent file like this:
 /**
 * @When I press the :arg1
 */
public function iPressThe($arg1)
{
    $element=$this->getSession()->getPage()->find('named', array('id_or_name', $arg1));
    $element->press();
}

Answer: Doesn't Behat parse the PHP docblock above your custom FeatureContext methods?
@When I press the :submit looks like its using jQuery selector syntax which Behat may not be used-to or using. Have a look at similar examples in the base FeatureContext class.

Behat\Laravel can't find submit


Puppet could not retrieve information from plugin source

Question: Every time I run puppet, I get this error.

err: /File[/var/lib/puppet/lib]: Failed to retrieve current state of resource: Could not retrieve information from source(s) puppet://puppet/plugins
Answer: The reason this error comes up is you have pluginsync enabled, and you don't have any plugins to sync.  pluginsync is enabled by default in the Ubuntu packages. Unfortunately, due to the design of puppet, the error message is a bit imposing, and throws up some pink in your otherwise green --test output.
There are two options:

Disable pluginsync on every client: edit /etc/puppet/puppet.conf and set pluginsync=false.
Create at least one plugin.

The easiest workaround is to create a single lib directory under a module of your choosing. Even an empty plugin is enough to cause the error to go away.
(Answer found in this bug report.)
Answer: Check the log file on the server if there any clues, but most likely it's caused by a misconfigured fileserver.conf for puppetmaster.
Comment: Thanks, but I actually posted the question in order to more widely publicise the correct answer. :)


Google classroom authentication based on Domains

Question: Presently i am working on google classroom API to integrate classroom into my .NET product.My problem is when i execute this method it asking authentication for first time but when i execute this code next time it directly log in as previous log in credentials.Even i change the client_secret.json of another(2nd) domain  also it directly login as 1st domain authenticated user.My requirement is when i change the client_secret.json file dynamically in code at run time it will directly log in as domain user of this client_secret.json file rather than previous domain user of client_secret.json file.Is this possible?
    If yes How can i achieve this.Please any one help on this.
private ClassroomService getservice()
    {
        using (var stream =
          new FileStream(Server.MapPath("client_secret.json"), FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
               System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                   CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        }
        var service = new ClassroomService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        return service;k
    }

Comment: possible duplicate of [How to implement OAuth in google classroom](http://stackoverflow.com/questions/32070888/how-to-implement-oauth-in-google-classroom)
Comment: Thank you for your reply @Eric Koleda.But my requirement is different.I need to switch between two users,admin directly log in as authenticated user based on their client_secret.json file  change in run time.How can i achieve this
Answer: The client_secret.json file holds application-specific credentials, not user- or domain-specific credentials. Changing the client_secret.json file is not the correct way to log in/out users. Instead, you'll need to use a FileDataStore with a different path.


IIS 7.5 using Classic ASP converts a boolean value to a string in the local language

Question: I have a Classic ASP application running on a workstation with a Danish version of Windows 7 with IIS 7.5.
The problem: When the application writes a boolean as a string, it will write "True" or "False" on an English server. However, on my Danish installation, it will write out "Sand" and "Falsk".
The desired solution: What I need is to know which specific setting on my workstation/iis/configuration determines which language it writes out a boolean value to make sure it will always write out booleans in English.
I have tried the following already:

Set the LCID to 2057 (en_GB) for the ASP configuration of IIS.
Changed settings in Control Panel to English

Regional settings
Number and currency formatting
Language for non-Unicode programs

Changed the culture settings for ASP.NET in IIS
Restarted the workstation.

The following are not possible resolutions, so please don't suggest those:

Changing any code in the application.
Re-installing my workstation with an English version of Windows 7.
Changing the language of my Windows 7 installation (not possible because I am not using Ultimate and do not wish to upgrade)

Any suggestions will be appreciated. Thanks.
Comment: I'm unsure about what to do with this question. I got good suggestions, but not the answer. Am I supposed to most useful answer anyway?
Comment: "choose the" fell out of my sentence above.  Am I supposed to choose the most useful answer anyway?
Answer: I don't know that the old OLEAUT regional settings hack applies, but I think it's worth a try - see what you get.
http://support.microsoft.com/kb/271587
SetVarConversionLocale should be set to 2, and the default regional settings set to US English.
If that doesn't work, and you can't change code in your application, run a virtual machine with a US English OS. You didn't specifically exclude that :)
Comment: Microsoft state that the problem is only for Windows 2000 and that it was corrected in SP2 for Windows 2000, so I don't think that particular problem snugg back into Windows 7. The virtual machine idea is actually not all bad :)
Comment: The binary that includes support for the registry setting was included in Windows 2000 SP2. (that's the "fix" they're talking about, they're not saying "this problem goes away") I assume support for the registry setting has been carried forwards; as I said, it's worth a try.
Comment: Ahh okay, that makes sense. Unfortunately adding those registry keys didn't make any difference. I tried all of them and tried setting them to both 1 and 2 without any different result. I ran an iisreset in between.
Answer: When you change regional settings in the control panel, you are doing this for your user profile; but IIS worker process usually run in other user contexts, depending on the configuration of the application pool(s). You should try changing the regional settings for those account(s).
Comment: I checked which application pool the website is using. I changed that application pool to identify itself as my own user account. I also tried with Network Service and "ApplicationPoolIdentity". It didn't work.Thanks for the suggestion, though-
Answer: NOTE: I have also posted this solution to : https://stackoverflow.com/questions/15760035/boolean-values-in-local-language/44321629#44321629
Hi,
I was "caught" too with this "issue".
Indeed, this is not an issue :
THE PROBLEM (EXAMPLE)
I had the same problem when using a boolean data in a SQL Statement.
On my French server, my SQL statement was the following :
<%
'Set my boolean value
Dim myBoolean
myBoolean = True

'Set my SQL Statement
Dim MySQLStatement
MySQLStatement = "SELECT * FROM MyTable WHERE MyBooleanField = " & myBoolean
'=> Here, as MySQLStatement is a STRING, the boolean data was "converted/rendered" as a localized string. So that leads to this output :
'=> SELECT * FROM MyTable WHERE MyBooleanField = Vrai
'Obviously, that SQL Statement is incorrect, because the SQL Engine does NOT understand what is the "Vrai" word - It should be "True" instead.
%>

THE EXPLANATIONS :

It does not matter which regional settings are set on your Windows System : Nothing happens to the underlying data. A boolean data type is STILL a BOOLEAN, in English, or French, or German, Russian, Thai, ..or any language you want.
The fact is that the data is simply being RENDERED as a localized STRING (like dates).

THE SOLUTION
After a lot of reading over forums threads, the solution is not to change regional settings on the Windows system, nor changing Registry keys, nor changing Session.LCID, ...
The absolute and code-only solution is to convert the Boolean value (True|False) to an Integer (0|1). Then, this Integer will be safely usable in a string, and will remain (0|1).
Here is the safe way to use/convert/render a Boolean value in a non-localized form : Use an Integer value.
<%
'Set my boolean value
Dim myBoolean
myBoolean = True

'Set my SQL Statement
Dim MySQLStatement
MySQLStatement = "SELECT * FROM MyTable WHERE MyBooleanField = " & BoolToInt(myBoolean)
'=> Here, as MySQLStatement is a STRING, and as the boolean data was previously "converted/rendered" as an integer, we got this correct SQL Statement :
'=> SELECT * FROM MyTable WHERE MyBooleanField = 1
'This SQL Statement is correct, as the SQL Engine DOES understand that 1 is a boolean.

'This Function Returns an INTEGER value based on a BOOLEAN value
Function BoolToInt(v)
    '@param     v        Boolean    The Input Boolean Value to be converted to an Integer
    '@return    i_OUT    Integer    The Output Integer Value (0|1)

    'Convert the input value to a Boolean
    Dim b_v : b_v = CBool(v)

    'Define the Output Integer value
    Dim i_OUT

    'If the Input Boolean value is a "True" boolean value (in any language)
    if (b_v) then
        i_OUT = CInt(1)
    'If the Input value is a "False" boolean value (in any language)
    else
        i_OUT = CInt(0)
    end if

    'Return
    BoolToInt = i_OUT

End Function 'BoolToInt
%>

I really hope it save your day !


$o(G)=p^n$. Then $\exists N_i\le G$ s.t. $N_{i-1} \supset N_i$, $N_i \unlhd N_{i-1}$ and $N_{i-1}/N_i$ is abelian

Question: This is problem 12, p. 91, in Topics in Algebra by Herstein. I am not sure of my solution and I cannot find solutions online. I would be glad if someone on here could tell me if it's correct and if there are simpler solutions (without invoking Sylow if possible, as I haven't studied it yet).

If $o(G)=p^n$, $p$ a prime number, prove that there exist subgroups $N_i, i=0,1,\dots,r$ (for some $r$) such that $$G=N_0 \supset N_1 \supset N_2 \supset \cdots \supset N_r = (e)$$ where $N_i$ is a normal subgroup of $N_{i-1}$ and where $N_{i-1}/N_i$ is abelian.

My solution. The commutator subgroup of $G$, $G'$, is normal and of course the group $G/G'$ is abelian. Also, $G' \not = G$ (Claim)
(proof of Claim) For suppose there is no proper normal subgroup of $G$ such that the quotient group is abelian. It can be shown that $G$ has a normal subgroup of order each power of $p$ up to $p^n$; in particular there is $H \unlhd G$ of order $p^{n-1}$, making $G/H$ a subgroup of order $p$, which is necessarily cyclic and thus abelian, a contradiction. (end of proof)
So we can set $N_1=G'$. Since $G'$ too has order a power of $p$, we can repeat this procedure. It will eventually stop because $G$ is finite. $\square$
Comment: The group $S_3$ has a normal abelian subgroup of order $3$ (which is its commutator subgroup), yet $Z(S_3)=1$.
Comment: In your proof, you are using a theorem that is stronger than what you are trying to prove. (Also, you are basically using induction, so spell it out.) That's not a good idea. Here's a better one: $N_G(H)>H$ whenever $H$ is a proper subgroup of a $p$-group $G$. Thus every maximal subgroup is normal in $G$ and thus has index $p$, so the factor group is certainly abelian.
Comment: Herstein's book should cover that property at some point because it is quite fundamental. Otherwise see here: https://math.stackexchange.com/questions/234426/if-h-is-a-proper-subgroup-of-a-p-group-g-then-h-is-proper-in-n-gh
Comment: No, this does not show that the centre of $G$ is non-trivial. Something stronger than the exercise asks you to prove is actually true: there are subgroups $N_i$ with these properties which are all normal in $G$. See here: https://math.stackexchange.com/questions/3276373/let-g-be-a-p-group-g-pr-prove-that-g-contains-a-normal-subgroup-o/3276421?noredirect=1#comment6737992_3276421
Comment: @the_fox but why does it not follow from my construction?
Comment: @the_fox Do you think my solution is correct then?
Comment: @the_fox yes, I use the fact that every subgroup of a p-group is normal, but I also have to show that $N_{i-1}/N_i$ is commutative so it's not a stronger theorem altogether? (is it?) And I understand what you are hinting, but I don't know how to show that $N_G(H) > H$. What elements $x \not \in H$ commute with $H$?
Comment: What basic theorems about $p$-groups has Herstein covered up to that point?
Comment: @the_fox Basically, only the fact that p-groups have non trivial centers. The rest is in the exercises, without solutions. (it's quite frustrating) For me it was easier to prove that every subgroup of a p-group is normal than your latest claim about $N(H)$, so that's why I used that in my solution.
Comment: It is not true that every subgroup of a $p$-group is normal.
Comment: @the_fox you're right. I proved that a p-group has a normal subgroup of order $p^k$ for each $k$. I hope that's true at least! Can you give me a hint for proving that $N(H)>H$?
Answer: Herstein is really asking you to prove that $p$-groups are solvable. Here's one way to do it (assuming the only thing you know about $p$-groups is that they have non-trivial centres).
Argue by induction on $k$, where $|G|=p^k$, the base case $G=C_p$ being evidently true. Now suppose you have proved the claim for all $p$-groups of order $p^{k-1}$. You know already that $Z(G)>1$, so choose an element $g$ of order $p$ in $Z(G)$
and let $N_1 = \langle g \rangle$ (since $g$ commutes with everything, $\langle g \rangle$ is normal in $G$). Consider the group $G/N_1$. The inductive hypothesis gives you subgroups $N_2/N_1$, ...,$N_k/N_1 = G/N_1$ such that $N_i/N_1$ is normal in $N_{i+1}/N_1$ and $N_{i+1}/N_1\big/N_i/N_1$ is abelian.
The series $1, N_1, \ldots, N_k =G$ has the desired properties. To see that $N_i$ is normal in $N_{i+1}$ use the Correspondence Theorem. To see that $N_{i+1}/N_i$ is abelian, use the fact that $N_{i+1}/N_1\big/N_i/N_1$ is abelian and apply the Third Isomorphism Theorem.
Comment: A very similar proof shows that a p-group has a normal subgroup of order $p^k$ for each $k$. I had proved that in a previous exercise, so that's why I used it, instead of repeating your argument.


How can standard logistic regression model fractional response variable while denominator is available?

Question: I have X and Y variables, as well as a cluster variable (State). X and State are derived from Database A, while Y and State are derived from Database B.
X is a sentiment score ranging between -1 and 1, while Y is a yes or no (0 or 1) response.
In Database A, I aggregate X into average-X by state, while in Database B, I aggregate Y into percentage-Y by state. Then I combine the two datasets as follows:

In the combined data structure, my new outcome is percentage-Y, while I do have the numerator and denominator that give rise to percentage-Y.
I have heard that from here - "The most natural way fractional responses arise is from averaged 0/1 outcomes. In such cases, if you know the denominator, you want to estimate such models using standard probit or logistic regression".
It seems since I do have the denominator information, I can avoid using the Fractional outcome regression and just stick with the standard Logistic regression.
However, how exactly can I model a logistic regression based on the denominator information?
Comment: see http://stats.stackexchange.com/questions/164120/interesting-logistic-regression-idea-problem-data-not-currently-in-0-1-form/164127#164127
Answer: First note that if you know the percentage and the denominator, then you also know the numerator.  So, for example, if you know for a specific class (in your example, the class is state) that the ratio of positive to negative classes in a class is $0.6$, and the denominator of the ratio is $10$, then you immediately know that there are

6 positive (y = 1) cases in that class.
4 negative (y = 0) cases in that class.

With this information you can, in principle, create a new dataset expanding your grouped data.  In this example you would end up with

6 rows for the class with $y = 1$.
4 rows for the class with $y = 0$.

Now you can use this new dataset to fit a logistic regression.
In practice, you simply observe that each row in this imaginary expanded data set contributes one term to the loss function
$$ L = \sum_i y_i \log(p_i) + (1 - y_i) \log(1 - p_i) $$
and each of the expanded rows in a class where $y = 1$ contributes the same amount, with the same thing holding for the rows where $y = 0$.  So, instead of actually physically creating the expanded data set, we can just apply integer weights to the terms in our loss function
$$ L = \sum_i w_i y_i \log(p_i) + w_i' (1 - y_i) \log(1 - p_i) $$
where the $w$s and $w'$s are the number of positive and negative cases in each class.
Comment: In the imaginary expanded dataset, we expand the rows by different values of y, but what should fill up the X values? Just the average?
Comment: @KubiK888 Sorry for the late reply, I missed your comment.  In the example I gave, I was thinking of state as being a predictor, in which case the predictor is constant across the group and there is not real issue.  If the predictor is on constant, then yes, you can infer the average, or some other summary statistic.  There are also multi-level/hierarchical generalized linear models, which better deal with this kind of situation.
Comment: Maybe I am not making it clear with my example... But I have thought about multilevel analysis as well. But I am not sure if and how I can incorporate into this analysis. My understanding is I need individual-level data that contains X, Y, and State variables all in one dataset. But I don't have that luxury. The individual data came from two different datasets: dataset A has X and State; and dataset B has Y and state. I then compressed each by State and combine the two datasets by the state variable in order to assess relationship between X and Y.


NullPointerException ao usar o setText para um TextView no fragment

Question: Estou criando um fragment onde tenho em uma parte o mapa e em outra um objeto do Retrofit, onde pego data e hora de um servidor.
O erro ocorre dentro da chamada onResponse do Retrofit, onde tento setar o TextView com a data e hora obtidos do meu servidor.
O mesmo ocorre quando carrego uma imagem do servidor e tento jogar ela dentro de um ImageView criado no próprio fragment.
Esse é o meu código:
@BindView(R.id.oi) TextView dataHora;

@Override
public void onCreate(Bundle bundle) {
    LayoutInflater inflater = (LayoutInflater)getLayoutInflater();
    View v = inflater.inflate(R.layout.activity_mapa, null);
    super.onCreate(bundle);
    getMapAsync(this);
    ButterKnife.bind((Activity) getContext());
}
    @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    centralizaImagem(googleMap);

    circuloNoMapa();

    Call<List<AppSync>> calldata = (Call<List<AppSync>>) new RetrofitInicializador().getServices().lista();
    calldata.enqueue(new Callback<List<AppSync>>() {
        @Override
        public void onResponse(Call<List<AppSync>> call, Response<List<AppSync>> response) {
            AppSync objeto = response.body().get(0);

            String url = objeto.getUrl();
            String fileDate = objeto.getFileDate();
            String fileTime = objeto.getFileTime();

            dataHora.setText(fileDate + " - " + fileTime + " GTM") ;

            convertido = new ImageView(getContext());

            Picasso.with(getContext())
                    .load(url)
                    .into(convertido);

           convertido.setDrawingCacheEnabled(true);
           convertido.buildDrawingCache();
           Bitmap bitmap= Bitmap.createBitmap(convertido.getDrawingCache());

            configuraBmpMapa();

        }

        @Override
        public void onFailure(Call<List<AppSync>> call, Throwable t) {
            Log.e("ERRO RETROFIT", t.getMessage() );
        }
    });

}

private void configuraBmpMapa() {
    LatLngBounds newarkBounds = new LatLngBounds(
            new LatLng(LATITUDE_MINIMA, LONGITUDE_MINIMA),       // South west corner
            new LatLng(LATITUDE_MAXIMA, LONGITUDE_MAXIMA));      // North east corner

    GroundOverlayOptions newarkMap = new GroundOverlayOptions()
            .image(BitmapDescriptorFactory.fromResource(R.drawable.oi))
            .positionFromBounds(newarkBounds);

    GroundOverlay imageOverlay = mMap.addGroundOverlay(newarkMap);
}

Essa é a mensagem de erro:
FATAL EXCEPTION: main
Process: com.tabatabaesso.exercicio2, PID: 9585
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
     at com.tabatabaesso.exercicio2.MapaFragment$1.onResponse(MapaFragment.java:102)
     at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
     at android.os.Handler.handleCallback(Handler.java:789)
     at android.os.Handler.dispatchMessage(Handler.java:98)
     at android.os.Looper.loop(Looper.java:164)
     at android.app.ActivityThread.main(ActivityThread.java:6541)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Esse é o .xml para o texto:
<FrameLayout
    android:id="@+id/frame_datahora"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.1">
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/oi"
    tools:text="02/09/99 - 11:00 GTM"
    android:textAlignment="center"
    android:textSize="16sp"/>
</FrameLayout>

Agradeço desde já a ajuda!
Answer: O bind de views em fragments é diferente do de activities, de acordo com a documentação. Você deveria invocar:
@Override
public void onCreate(Bundle bundle) {
    LayoutInflater inflater = (LayoutInflater)getLayoutInflater();
    View v = inflater.inflate(R.layout.activity_mapa, null);
    super.onCreate(bundle);
    getMapAsync(this);
    ButterKnife.bind(this, v);
}

Recomendo a ler também sobre o Binding Reset.
Comment: Aliás, muito obrigada pela ajuda! :)


What is the geometrical interpretation to $AX = 0$ when $det(A) = 0$?

Question: I read the first chapter of hoffman and from there I know that algebraically how to find the infinite solutions to $AX=0$ when $det(A)=0$.
However I am interested in seeing the geometric intuition behind it.
Assume that $A$ is a $2 \times 2$ matrix then  $$A=\begin{bmatrix}a & b \\c&d \end{bmatrix}$$
If the $\det(A) = 0$ then assume that the second row is a multiple of the first row so $(c,d) = k(a,b)$.
This doesn't help me to see as to there will exist a solution at the first place(geometrically) or if this doesn't happen then why is the solution unique(geometrically)?
Edit 1:
When I am doing $AX = 0$ I am trying to find the solution to my question :
When does the two lines $ax_1 + bx_2 = 0 $ and $cx_1 + dx_2 = 0$ meet. They always meet at the point $(0,0)$. Now the two lines can be coincident(if they are linearly dependent) or they can only meet at $(0,0)$ (in which case they are linearly independent). Now if they are coincident then the two lines lie on top of each other and so they have infintely many points satisying their equations.
Are there any other possible cases?
Comment: This is an awesome series on linear algebra, see the video on determinants. https://youtube.com/playlist?list=PL0-GT3co4r2y2YErbmuJw2L5tW4Ew2O5B
Comment: you may find it helpful to think in terms of two lines in the plane which may either intersect at a unique point, be parallel, or be coincident.
Comment: Why would the lines be parallel? The two lines always intersect at (0,0) ?
Answer: What you describe in the edited question is one perfectly good geometric interpretation of the matrix equation. It can serve you well -- but will serve you better if you avoid thinking of it as "the" geometric interpretation that you need to hold on to in all cases.
In particular, as you work your way through linear algebra, you will learn that a particularly strong idea is to view the matrix not as two independent linear equations, but as a representation of a linear transformation between two abstract two-dimensional vector spaces. You have a wide choice of expressing such as transformation using different coordinate systems when writing down as a matrix -- and if you switch to a different coordinate system for the output of the linear transformation the two apparently-separate equations into a mixture and the lines you're imagining now cease to have individual significance. Conversely, when you have a matrix to start with, it can often make it easier to "see the forest for trees" to forget about its individual elements for some time and just think of it as some linear transformation -- in many cases you'll be able to understand better what the matrix does by switching coordinates to one where the matrix is simpler.
(The lines in your current picture are simply the preimages of the output coordinate axes, when mapped backwards through the linear transformation. If you use a different output coordinate system, its axes will come from different locations in the input space. (However, beware that this connection doesn't generalize directly to higher dimensions, so that way of thinking is not any "ultimate truth" either)).