CSS: -ms-filter not working on IE in angular 4

Question: Filters are not working in IE browser using angular 4.
Here my code for css code:
.style{-ms-filter: grayscale(50%); -ms-filter: brightness(70%);}

Comment: IE 8 and above version
Answer:
The modern definition of css filter doesn't work in IE8. IE8 does have the older, proprietary MS filters, but those are not the same.
You can't have 2 properties to a selector a row with the same name. That's not how CSS works. In this case, the second -ms-filter will override the first one, so that only brightness(70%) is used.
The solution, according to MSDN, is to use commas to separate multiple values.

Aside from that, apparently neither the old MS versions nor the newer standard versions are supported by IE10 and IE11, so you're out of luck in any version.
You can use
.style {filter:gray}

in IE8 to set the gray scale to 100%, but I haven't found any equivalent for brightness, sorry.


Mudar a cor da linha do DataGridView

Question: Gostaria de saber como faço para mudar a cor de uma linha toda do DataGridView. Tenho um código abaixo, porém ele só mudar a cor de uma coluna específica, e eu gostaria que ele mudasse a cor de todas as colunas da mesma linha.
DataGridView.CurrentRow.Cells[0].Style.BackColor = Color.Yellow;

Answer: Utilize o dataGridView1.CurrentRow.DefaultCellStyle e deixe o dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect que é a seleção completa da linha:
dataGridView1.DataSource = new object[]
{
    new {Id = 1, Nome = "A"},
    new {Id = 2, Nome = "B"},
}
.ToList();

// configuração que marca a linha completa.
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.Update();
dataGridView1.Select();
// configuração do estilo da linha
dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Yellow;

Referencias:

DataGridView.SelectionMode Propriedade
DataGridView.DefaultCellStyle Propriedade

Mudar a cor da linha do DataGridView


What OTK abbreviation stands for?

Question: I've heard about it when someone was talking about drum mic positions, but I'm not sure. Is it something like overhead mic position?
Comment: My guess would be "Over the Kit", but I've never directly heard that phrase before.
Comment: @Tetsujin I think it's partly a recent fad and partly a slight change to the concept of a "crotch mic", which I've heard of before.
Comment: I've never heard the term either, in 40 years of engineering [on & off]. Maybe I just live a sheltered life ;)
Comment: I saw it in this video and it sound like overhead. Look how channel is named. https://youtu.be/jrfF1XMdpc8
Answer: OTK? On the kick. Not in front or inside, but actually 'on the kick'. Mounted on the rim of the bass drum.
Comment: Technical: in front picks up the resonant head. Inside picks up the 'thud'. OTK with a clamp can be moved around to pick up what sounds best, without resorting to a mic stand as the first example needs.
Comment: That's a plausible answer, @Tim, but do you have any backup for it?
Comment: Is there any technical or practical reason to mic the kick this way?
Comment: I think that this otk setting will pick a lot of sound from other elements of kit like snare and cymbals. Is this right? I've seen a video in which OTK channel in daw sounded like it was overhead. That's the video: https://youtu.be/jrfF1XMdpc8
Comment: Any source for this?
Comment: @Ronx Yeah looks like it's a different take on the idea of a crotch mic. Sorta like LCR (left, center, right) miking for drums.
Comment: Everything I've seen on this suggests this answer is incorrect. There are so many bad things about rim mounted drum mics it's hard to know where to start.
Comment: @LaurencePayne - 'recording lounge' drum mixing 303 was one place. OTK - Rode NT2 right in front of the rim of the kick. Which may or may not actually be *mounted* on the rim, but would certainly be in line with the rim/circumference of the head. Some rim mounts transfer sound not required, so it could easily be on a small stand. Wasn't easy to find info on 'otk'.
Answer: At least one person in a podcast defines it as "over the kick". This looks like an automatic transcription that has no punctuation and I have quoted it exactly (emphasis mine):

anyway okay so here's a mic that I was talking about earlier the otk over the kick Mike so this Mike is literally over the kick drum like maybe an inch or two over the kick drum either facing down at the kick drum facing the snare sometimes facing the floor tom sometimes it's more at the rim of the kick drum have to experiment the place in a little bit I tend to like somewhere around the middle of the kick drum facing the snare kind of equidistant between like floor tom rack Tom and snare sort of where those sort of have a middle point somewhere around the center of the kick drum underneath the ride cymbal somewhere in there and this is what that might sounds like this is a really interesting Mike

Source: https://www.listennotes.com/podcasts/recording-lounge/episode-111-drums-in-a-small-21KrG0ePJaI/
If you look at the table and picture closely on this site:
https://www.recordingloungepodcast.com/blog/episode-93-drum-mixing-303-additional-info
you'll see that there is a mic that looks like the OTK mic boomed in from the hi hat side over the batter side rim of the kick.
This video goes with that site and the OTK mic is pointed out at around 6:10:

I suspect this is partly a batter side kick mic for picking up articulation and/or kind of a crotch mic that gets a nice central image of the kit.
Comment: I guess it may be the good idea if you have only 2 mics to put one as overhead and one as OTK aaato gather the entire spectrum of sounds, well entire for what's possible with 2 mics of course hehe.

What OTK abbreviation stands for?


Sets with Hausdorff-Measure 0

Question: The $\alpha$-Dimensional Hausdorff-Measure of a Set A is defined as $H^\alpha (A)=\inf_{A\text{ is countable covering}}\sum_{A'\in A} diam(A')^\alpha$. It is easy to show, that for every set $E\subseteq\mathbb{R}^d$ there exists a unique $\beta\in \mathbb{R}$, so that $H^\alpha(E)=0$ for $\alpha>\beta$ and $H^\alpha(E)=\infty$ for $\alpha < \beta$. This $\beta$ is called the Hausdorff-Dimension $dim(E)$ of E. It is easy to show, that $dim(\mathbb{R}^d)=d$ and $H^d(\mathbb{R}^d)=\infty$. I  wonder if there is any Set A with $dim(A)=\alpha$ and $H^\alpha(A)=0$.
Does anybody have an idea how to approach this?
Answer: (See Ullrich's link for corrected definition of Hausdorff measure.)
Another (softer) approach.  For $n=1,2,3,\dots$ let $A_n \subseteq \mathbb R$ be a set with Hausdorff dimension $1-\frac{1}{n}$.  Then I claim that
$$
A := \bigcup_{n=1}^\infty A_n
$$
satisfies $\dim A = 1$ but $H^1(A) = 0$.  Indeed, for $s\ge 1$ we have $s>1-\frac{1}{n}$ for all $n$ and therefore
$$
H^s(A) \le \sum_n H^s(A_n) = \sum_n 0 = 0 .
$$
But for $s<1$ there exists $n_0$ so that $1-\frac{1}{n_0} > s$ and therefore
$$
H^s(A) \ge H^s(A_{n_0}) = \infty.
$$
Comment: Do you know a way to get $A_n$ with the required dimension that's much easier/softer than constructing an appropriate Cantor set? (Meant as a question, not a snipe. Yes, constructing _that_ Cantor set will be simpler than the one I did...)
Comment: It is hard to imagine something simpler than a two-part self-similar set.
Answer: Your definition of Hausdorff measure is wrong; the actual definition is a little more complicated. See https://en.wikipedia.org/wiki/Hausdorff_measure .
But what you've defined, something that's sometimes called the Hausdorff "content", is sufficient to give a correct definition of the Hausdorff dimension; the Hausdorff content vanishes if and only if the Hausdorff measure vanishes.
Yes, for $0<\alpha\le d$ there exists $A\subset\Bbb R^d$ with $\dim(A)=\alpha$ and $H^\alpha(A)=0$. Take $d=1$ for (relative) simplicity. The construction is like the construction of the middle-thirds Cantor set, except that at each stage we remove the middle something, not necessarily the middle third.
In particular: Suppose that $\delta_n>0$ is such that $\delta_0=1$ and $$\delta_{n+1}<\frac12\delta_n.$$There exist compact sets $K_n\subset\Bbb R$ with $K_0=[0,1]$, $K_{n+1}\subset K_n$, and such that $K_n$ is the union of $2^n$ disjoint closed intervals $I_1^n,\dots,I_{2^n}^n$, each of length $\delta_n$. We're going to set $K=\bigcap_{n=1}^\infty K_n$.
Given $\alpha\in(0,1]$ it's possible to choose $(\delta_n)$ in such a way that $H^\alpha(K)=0$ while $H^\beta(K)>0$ for all $\beta\in(0,\alpha)$.
(It follows then that $K$ has infinite $\beta$-dimensional Hausdorff measure for $0<\beta<\alpha$; note however that the Hausdorff content of any compact set is finite.)
It's enough to obtain $$2^n\delta_n^\alpha\to0$$while$$2^n\delta_n^\beta\to\infty\quad(0<\beta<\alpha).$$ So if we say $\delta_n=2^{-\gamma_n}$ we need $$\gamma_{n+1}-\gamma_n>1,$$
$$n-\alpha\gamma_n\to-\infty,$$and $$n-\beta\gamma_n\to\infty.$$ You can check that all three conditions hold if $$\gamma_n=\frac n\alpha+\sqrt n.$$
Now the fact that $2^n\delta_n^\alpha\to0$ makes it clear that $H^\alpha(K)=0$, by definition. Similarly $2^n\delta_n^\beta\to\infty$ makes it plausible that $H^\beta(K)>0$, although here there's something to be proved.
The proof is by the trivial converse of "Frostman's Lemma". There exists a probability measure $\mu$ supported on $K$ such that $$\mu(I_j^n)=2^{-n}$$for $1\le j\le 2^n$. That is, if $|I|$ denotes the length of the interval $I$, we have $$\mu(I_j^n)=|I_j^n|^{n/\gamma_n}.$$It follows that if $0<\beta<\alpha$ there exists $c$ such that for every interval $I\subset[0,1]$ we have $$\mu(I)\ge c|I|^\beta.$$Hence if $K$ is covered by a collection of intervals $I$ we have $$1=\mu(K)\le\sum_I\mu(I)\le c\sum_I|I|^\beta,$$so $H^\beta(K)>0$.

Sets with Hausdorff-Measure 0


Can enabling a RAID controller's writeback cache harm overall performance?

Question: I have an 8 drive RAID 10 setup connected to an Adaptec 5805Z, running Centos 5.5 and deadline scheduler.
A basic dd read test shows 400mb/sec, and a basic dd write test shows about the same.
When I run the two simultaneously, I see the read speed drop to ~5mb/sec while the write speed stays at more or less the same 400mb/sec. The output of iostat -x as you would expect, shows that very few read transactions are being executed while the disk is bombarded with writes.
If i turn the controller's writeback cache off, I dont see a 50:50 split but I do see a marked improvement, somewhere around 100mb/s reads and 300mb/s writes. I've also found if I lower the nr_requests setting on the drive's queue (somewhere around 8 seems optimal) I can end up with 150mb/sec reads and 150mb/sec writes; ie. a reduction in total throughput but certainly more suitable for my workload.
Is this a real phenomenon? Or is my synthetic test too simplistic?
The reason this could happen seems clear enough, when the scheduler switches from reads to writes, it can run heaps of write requests because they all just land in the controllers cache but must be carried out at some point. I would guess the actual disk writes are occurring when the scheduler starts trying to perform reads again,  resulting in very few read requests being executed.
This seems a reasonable explanation, but it also seems like a massive drawback to using writeback cache on an system with non-trivial write loads. I've been searching for discussions around this all afternoon and found nothing. What am I missing?
Comment: Would you mind putting together your data in some sort of structured table?  This is some very interesting observations you're making, I'd like to see if there's a pattern.
Answer: Well, a basic dd is probably not the best way to measure drive throughput. It's not a realistic load. However, if you do run dd, please pass the oflag=direct flag in the command line to eliminate the effect of filesystem cache. Also see: How to measure disk throughput? for suggestions on how to measure workloads.
I think your scheduler choice is having a larger effect on your results than anything else. For RAID controllers with battery or flash-backed cache (write cache), I used to run with the deadline scheduler, but now use the noop scheduler if the cache is 512MB or 1GB. You can swap the scheduler on the fly, so try the tests with the noop algorithm and the oflag=direct and see how the results look.
Have you run bonnie++ or iozone?
Comment: oflag=direct tends to give exactly the opposite results. With writeback enabled, I see a 50/50 split , which is what I want. With writeback disabled, I see write starvation
Comment: +1 for oflag=direct. I also recommend iozone.
Comment: I will try noop, though thus far I've seen the scheduler have very little effect while write-back is enabled. Will check out iozone too, but I'm not too interested in the overall performance; I'm more interested in what I'm interpreting as read starvation because of the "instant" nature of writes when write-back is enabled.
Comment: And the change in kernel elevator? How did `noop` do?
Answer: If you do plan on using iozone here are some ways to check your performance. These are better than dd as they allow the kind of test you're looking for.
iozone -s 4G -a -i 0 -i 1 -i 2

That will run tests with a 4GB dataset (-s 4G), using a variable record size and run the write-test (-i 0), the read-test (-i 1), and the random read/write test (-i 2). Selecting the file-size is critical. If you pick one that fits in RAM your results will be based more in file-cache than actual storage performance. So if you have server with 4GB of RAM, test with a file size larger then that.
However, if you have obscene amounts of RAM (I have one server with 12GB) and want your tests to finish in under many hours, you can supply the -I option, which tells iozone to set O_DIRECT and bypass the filesystem cache. You'll get your true storage sub-system performance there.
You can also do tests that check for concurrent access.
iozone -s 128M -r 4k -t 32 -i 0 -i 1 -i 2

That will run 32 concurrent 128MB threads running the same tests as the previous command but with a 4K record size (-r 4k). The working set is 4GB, but some of the files will fit in file-cache. Depending on what you're doing with this storage, this may be a more accurate test of your probable performance. As with before, the -I parameter will set O_DIRECT.
iozone -s 128M -r 4k -l 16 -u 32 -i 0 -i 1 -i 2

This does the same as the above command, but runs a series of tests starting with 16 threads and increasing to 32 threads.


Items in Compose StaggeredGrid rearranging themselves when scrolling up

Question: I have implemented a LazyVerticalStaggeredGrid which shows GIFs. The GIFs are displayed using the AsyncImage from Coil using a url from Giphy. The items asynchronously load into the grid without issue. Scrolling down works as expected, however, scrolling up makes the items rearrange themselves.
Here is my implementation of the grid:
@Composable
fun GifGrid(
    modifier: Modifier = Modifier,
    gifList: List<GiphyItem>
) {
    LazyVerticalStaggeredGrid(
        columns = StaggeredGridCells.Fixed(3),
        modifier = modifier,
        verticalItemSpacing = 12.dp,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        contentPadding = PaddingValues(vertical = 8.dp),
        content = {
            items(gifList, key = { it.id }) { item ->
                AsyncImage(
                    model = ImageRequest.Builder(LocalContext.current)
                        .data(item.images.downsized.url)
                        .decoderFactory(ImageDecoderDecoder.Factory())
                        .build(),
                    contentDescription = null,
                    modifier = Modifier
                        .clip(RoundedCornerShape(6.dp)),
                    contentScale = ContentScale.Crop
                )
            }
        }
    )
}

Here is a video of the bug
I have tried a few things to diagnose the issue:

Tried observing gifList with LaunchedEffect. There were no recompositions happening.
Tried various different sizes of GIFs. That did not have an effect.
Tried replicating the bug with images from drawables and url. Could not replicate bug.
Tried other grid views. Got the same behavior.

I also saw some implementations for fixing a bug like this in XML but I am not sure how to transfer that to Compose.
Answer: I think your issue is that you didn't give a size to the images so it only becomes available when loaded. Scrolling down this isn't an issue but scrolling up it becomes one because content below it moves...
Set a size to the items and the issue should go away
Comment: It did, specifically when I set the size through Modifier, the .size() property in AsyncImage does not seem to fix the issue.
Answer: If your API gives you width and height parameter, you can allocate the composable size first before Coil is loaded by setting a Modifier.aspectRatio(width / height).
Comment: Fixed the problem for me!


How To Determine Active Div / Panel in JqMobi/AppFramework

Question: I'm on a phonegap project.
I was doing this project with Jquery Mobile Framework. But its results and performance arre so bad at many devices (f.e. my device android 2.3.3 - jquery mobile works nice on android 4.x.x devices i think)
After that, i found this nice and fast framework.
Now, i'm trying to carry my jquery mobile project to Jqmobi.
But there are some problems when i'm trying to carry. I am stucked with the function that i need to show current/active/chosen/opened panel when i click from the navigation.
Why do i need this. Because, "i want to work the functions when the user chooses that panel" that is what i want.
Here is what i have tried in jqmobi;
HTML SIDE ;
    <!DOCTYPE html>

        <title>Live Score</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <link rel="stylesheet" type="text/css" href="css/icons.css" />
        <link rel="stylesheet" type="text/css" href="css/jq.ui.css" />
        <link rel="stylesheet" type="text/css" href="css/add.css" />

Football Live Scores

Football League Tables

Football League Fixtures

Program Settings

                home
                live
                tables
                fixtures
                settings

Javascript Side (not working)
$(document).bind('pageshow', function () {
    var id = $.ui.activeDiv[0].id;

    if (id=="contents01"){
         ctx="livescores";
        $("#contents01 [class='panel']").text(ctx);
    }
    else
    if (id=="contents02"){
         ctx="leaguetables";
        $("#contents02 [class='panel']").text(ctx);
    }
    else
    if (id=="contents03"){
         ctx="leaguefixtures";
        $("#contents03 [class='panel']").text(ctx);
    }
});

function getLiveMatches(){
    $.getJSON("MY WEB API URL", function (data){
        ctx='
';
        $.each(data, function (index, value) {
            ctx+="

" + value.MinuteOrShortStatus + "	" + value.HomeTeam.Name + "	" + (value.CurrentHomeTeamScore == null ? "-" : value.CurrentHomeTeamScore) + "

" + value.AwayTeam.Name + "	" + (value.CurrentAwayTeamScore == undefined ? "-" : value.CurrentAwayTeamScore) + "

";
        });
        ctx+='
';
        injectContext("contents01",ctx);
    });
}

function injectContext(target, context){
    $("#"+target+" [class='panel']").html(context);
}

How can i determine the active panel or page or div in Jqmobi / Appframework..
Please help about it.
Thanks.
Comment: I`m not sure howto do it with the active panel. As workaround I use
Comment: it doesnt work.thanks anyways
Comment: @kgms21-May be you can try $.ui.activeDiv.attr("id") == "contents01" or simple javascript. if(document.getElementbyId("contents01)==true)
Answer: You can run a function whenever a panel becomes active.
Add the attribute data-load="func_name" to the panel's div tag.
For Example
<!DOCTYPE html>

    ...

    ...

            ...

            ...

            ...


Azure App Service Active Directory Authentication Access Denied

Question: We have a web app that we are transitioning from a Azure classic cloud service to an App Service web app. The classic cloud service was on a vnet that contained our domain controllers (regular AD, NOT Azure AD). The App service uses VNET Integration so it is connected to our vnet, and therefore DCs,(essentially via a client vpn).
When we run the code that creates a new AD in the web app, the user is created successfully, but as soon as we try to change anything - set the password, add to a group etc, we get
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
The user we're using to create and edit the account works fine from the cloud service, so its not an AD permissions problem.
To try to simplify debugging, I wrote some Powershell that I could run in the Kudu console to see if I could trap the error:
<code>$DomainControllerIpAddress = "< domain controller IP>"
$domain   = "<domain name>"

$BaseDN=  "LDAP://$($DomainControllerIpAddress)"
$domAdmin = "domain\adminaccount"
$domPass  = "<password>"

$userdn = "CN=TestUser,OU=TestOU,OU=ParentOU,DC=domain,DC=local"

$pass = "<newuserpassword>"

$userobj = New-Object System.DirectoryServices.DirectoryEntry($basedn + "/" + $userdn), $domAdmin, $domPass

$userobj.AuthenticationType = @("Secure","Sealing") # adding this to try to force kerberos makes no difference

$userobj.Invoke("SetPassword",$pass) # this fails in the App service but works fine everywhere else
</code>
This code runs fine from my local machine connecting to the same DC as the App Service, and it runs fine from a powershell console on one the the cloud service role instances, but errors from the App service.
The fact we can create the user successfully proves ldap connectivity works, but its beyond me why setting the password gives an access denied error.
Comment: Did you ever resolve this? It's almost exactly the same problem I'm having.
Answer: I had a engineering level call with Microsoft on this subject. In a nutshell, certain kinds of calls are restricted in app services "for security reasons". The call to SetPassword is one of them.
This is not a bug but a deliberate design decision by the app service product managers.
You can run these command if you execute them from a virtual machine. That's what we ended up doing. We spun up VM in an availability set with an internal load balancer. We deployed a very small .Net Core API with security that does nothing but make the LDAP calls for us.
Not a very elegant solution but it works.


Porque e quando usar o "res.send()" em uma aplicação? NodeJS e Express

Question: Bom, sou iniciante em NodeJS e comecei a estudar para fins acadêmicos. Em outra pergunta que fiz aqui no SO-BR (Pra que serve o comando "res.send()" em Express?) eu perguntei pra que servia esse comando e que foi respondida muito bem, mas o problema agora é que eu não faço a mínima ideia do porque usar esse comando e quando usar. Poderiam me explicar e se possível exemplificar? Agradeço desde já a colaboração e paciência de todos.
Answer: O comando res.send serve para servidor enviar resposta ao cliente web.
No express ele pode ser usado para responder numa rota do servidor, como no exemplo abaixo para retornar o resultado do servidor mediante aquele pedido na URL informada usando um request GET no caminho /user:
1)No arquivo principal da sua aplicação app.js carregar o arquivo de rotas para todas as rotas a partir de /:
<code>// router
app.use('/', require('./routes'));
</code>
2)No arquivo routes/index.js indicar que para a rota /user o servidor vai responder com um texto com o conteúdo dentro do parêntesis. Envia-se também o código de resposta 201 sinalizando resposta com sucesso:
<code>const express = require('express');
const router = express.Router();

router.get('/user', (request, response) => {
    response.status(201);
    response.send("RESPOSTA TEXTO");
});
</code>
Comment: Humm... acho que entendi um pouco. Vou pesquisar mais à respeito. Obrigado por responder!


Select python - Pandas

Question: Estou desenvolvendo um programa em python onde importo dois arquivos xlsx diretamente com a biblioteca Pandas, consigo importa-los facilmente, mas necessito de criar um relatório entre esses dois arquivos.
Como posso fazer?
Comment: CSS, bom dia! Consegue disponibilizar os xlsx? Abraços!
Comment: @lmonferrari Segue os arquivos de exemplo: https://gofile.io/d/5TUFTS
Answer: Importando o pacote
import pandas as pd

Carregando os arquivos:
lojas = pd.read_excel('./lojas.xlsx')
produtos = pd.read_excel('./produtos.xlsx')

Utilizando join do pandas:
novo_df = produtos.set_index('Código da loja').join(lojas.set_index('Código da loja')).reset_index()

Reordenando as colunas:
novo_df = novo_df[['Código do produto','Nome do produto','preço','Código da loja','Nome da loja']]

Saída:
novo_df

Código do produto   Nome do produto                                  preço      Código da loja  Nome da loja
          1A        Corretivo líquido 18ml água 930761 Bic            5.70               100        Penha
          2A        Caneta esferográfica 1.0mm cristal                1.40               100        Penha
          3A        Lápis plástico preto evolution Pijama 1106666 ... 4.00               100        Penha
          2A        Caneta esferográfica 1.0mm cristal                1.38               101        Lins de Vasconcelos
          1A        Corretivo líquido 18ml água 930761 Bic            5.75               101        Lins de Vasconcelos
...

Sobre o join:

Junte colunas com outro DataFrame no índice ou em uma coluna-chave.
Junte de forma eficiente vários objetos DataFrame por índice de uma
vez, passando uma lista.

Documentação

Update
Como o requerimento da pergunta mudou vou colocar este update aqui.
Importando o pacote
import pandas as pd

Carregando os arquivos
lojas = pd.read_excel('./lojas.xlsx')
produtos = pd.read_excel('./produtos.xlsx')

Criando novo data frame e reordenando a apresentação das colunas
novo_df = produtos.set_index('Código da loja').join(lojas.set_index('Código da loja')).reset_index()
novo_df = novo_df[['Código do produto','Nome do produto','preço','Código da loja','Nome da loja']]

Criando um "filtro" para verificar os menores preços agrupados pelo nome do produto e código do produto, depois criamos um novo data frame com os valores filtrados
filtro = novo_df.groupby(['Código do produto','Nome do produto'])['preço'].min()
menor_preco_df = novo_df[novo_df['preço'].isin(filtro)].sort_values(by = ['Código da loja']).reset_index(drop = True)

Aqui criamos dois data frames guardando informações diferentes para depois criarmos um dicionário, o intuito é criar uma coluna com listas
df1 = menor_preco_df.groupby(['Código da loja','Nome da loja'])['Nome do produto'].apply(list).reset_index()
df2 = menor_preco_df.groupby(['Código da loja','Nome da loja'])['preço'].apply(list).reset_index()
df2.drop(columns = {'Código da loja','Nome da loja'}, inplace = True)
dicionario1 = pd.concat([df1,df2], axis = 1).to_dict('index')

Aqui imprime a primeira parte do problema
for chave, valor in dicionario1.items():
    print(f"{valor['Código da loja']} - {valor['Nome da loja']}")
    for v,p in zip(valor['Nome do produto'],valor['preço']):
        print(f"   Produto: {v} - R${p}")
    print('')

Saída:
100 - Penha
   Produto: Lápis plástico preto evolution Pijama 1106666 Bic BT 3 - R$4.0

101 - Lins de Vasconcelos
   Produto: Lápis plástico preto evolution Pijama 1106666 Bic BT 3 - R$4.0

102 - Curuça
   Produto: Corretivo líquido 18ml água 930761 Bic - R$5.5
   Produto: Lápis plástico preto evolution Pijama 1106666 Bic BT 3 - R$4.0

103 - Faria Lima
   Produto: Corretivo líquido 18ml água 930761 Bic - R$5.5

104 - Jardim Brasil
   Produto: Corretivo líquido 18ml água 930761 Bic - R$5.5
   Produto: Caneta esferográfica 1.0mm cristal - R$1.2

Aqui criamos o segundo dicionário agrupado por nome do produto e o preço
dicionario2 = menor_preco_df.groupby(['Nome do produto','preço'])['Nome da loja'].apply(list).reset_index().to_dict('index')

E aqui imprimimos a segunda parte do problema
for chave, valor in dicionario2.items():
    print(f"{valor['Nome do produto']}")
    print(f"  - Produto encontrado por R${valor['preço']} nas lojas",', '.join(valor['Nome da loja']),'\n')

Saída:
Caneta esferográfica 1.0mm cristal
  - Produto encontrado por R$1.2 nas lojas Jardim Brasil

Corretivo líquido 18ml água 930761 Bic
  - Produto encontrado por R$5.5 nas lojas Curuça, Faria Lima, Jardim Brasil

Lápis plástico preto evolution Pijama 1106666 Bic BT 3
  - Produto encontrado por R$4.0 nas lojas Penha, Lins de Vasconcelos, Curuça

Código completo
import pandas as pd

lojas = pd.read_excel('./lojas.xlsx')
produtos = pd.read_excel('./produtos.xlsx')

novo_df = produtos.set_index('Código da loja').join(lojas.set_index('Código da loja')).reset_index()
novo_df = novo_df[['Código do produto','Nome do produto','preço','Código da loja','Nome da loja']]

filtro = novo_df.groupby(['Código do produto','Nome do produto'])['preço'].min()
menor_preco_df = novo_df[novo_df['preço'].isin(filtro)].sort_values(by = ['Código da loja']).reset_index(drop = True)

df1 = menor_preco_df.groupby(['Código da loja','Nome da loja'])['Nome do produto'].apply(list).reset_index()
df2 = menor_preco_df.groupby(['Código da loja','Nome da loja'])['preço'].apply(list).reset_index()
df2.drop(columns = {'Código da loja','Nome da loja'}, inplace = True)

dicionario1 = pd.concat([df1,df2], axis = 1).to_dict('index')
for chave, valor in dicionario1.items():
    print(f"{valor['Código da loja']} - {valor['Nome da loja']}")
    for v,p in zip(valor['Nome do produto'],valor['preço']):
        print(f"   Produto: {v} - R${p}")
    print('')

dicionario2 = menor_preco_df.groupby(['Nome do produto','preço'])['Nome da loja'].apply(list).reset_index().to_dict('index')
for chave, valor in dicionario2.items():
    print(f"{valor['Nome do produto']}")
    print(f"  - Produto encontrado por R${valor['preço']} nas lojas",', '.join(valor['Nome da loja']),'\n')

Comment: Voce usou o Pycharm para mostrar os resultados? Usando aqui ele nao mostra todas colunas , mostra apenas algumas no console, teria que fazer alguma configuracao especifica?
Comment: Estou utilizando o jupyter notebook. No exemplo acima eu cortei as demais linhas pois ficaria muito extenso aqui na resposta. Sobre as colunas eu não sei te informar algo sobre o pycharm pois não utilizo ele.
Comment: Estava lendo sobre o pycharm e parece que existe algo no debug chamado "View as data frame". Segue o [link](https://www.jetbrains.com/help/pycharm/viewing-as-array.html)
Comment: A resposta te ajudou?
Comment: ajudou demais obrigado pela explicacao ! O link do Pycharm tambem resolveu o problema, adicionei isso no print fez que com imprimisse tudo : print(produtos.head(3000).to_string())
Comment: Que ótimo que te ajudou! Por nada meu caro! Considere em marcar como resposta aceita (não é obrigatório mas é uma boa prática do site). Isso ajuda as pessoas a visualizarem que a pergunta já foi resolvida e também estimula outras pessoas a responderem suas perguntas. [Veja como](https://i.stack.imgur.com/eyLkG.jpg) Grande abraço!
Comment: Acabei de faze-lo , se eu fosse usar o gropu by para agrupar assim como ficaria?                                                                                100 - PENHA                                                                                Caneta esferográfica 1.0mm cristal 1,40
Corretivo líquido 18ml água 930761 Bic 5,70
Lápis plástico preto evolution Pijama 1106666 Bic BT 3 4,00
Comment: Você poderia agrupar assim: `novo_df.groupby(['Código do produto','Nome do produto'])['preço'].sum().reset_index()`. Veja se é o que você imaginava. Abraço!
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/116348/discussion-between-css-and-lmonferrari).

Select python - Pandas


What is the smallest positive integer $n$ such that $(a+1)^{7^n} = (a+1)$?

Question: In $\mathbb{F} = \mathbb{F}_7[X]/(X^2+1)$ let $a$ be the class of $X$. What is the smallest positive integer $n$ such that $(a+1)^{7^n} = (a+1)$ ?
I know that the answer is $2$ but I don't see how it works. Can someone explain the logic to me? Because if I get it correctly, $a = X$ in this case and we're reducing $mod$ $X^2 +1$ so how does $ a^{49} +1$ equal to $a+1$ ?
Comment: Hint: What is $a^4$?
Comment: May be it should read $(a+1)^{7^n}=(a+1)$? That way $n=2$ comes out the right answer.
Comment: $n=2$ is incorrect.
Comment: @JyrkiLahtonen Yes, my bad. I'll edit it now.
Answer: Since this is in characteristic $7$, $(x+1)^7 = x^7 + 1$ for any $x$, and
$(a+1)^{49} = (a^7+1)^7 = a^{49} + 1$.  Since $a^2 = -1$, $a^{48} = 1$ so
$a^{49} + 1 = a + 1$.
Comment: Why is $n=7$ the smallest one?
Comment: because we are working with $\mod a^{2} +1$, so we know $a^{2}+1=0 \Leftrightarrow a^{2} = -1$
Comment: It seems you have misread the problem: the exponent is $\,\large 7n\,$ not $\,\large 7^{\Large n}\,\ $  @AbdulMalekAltawekji Which exponent is actually intended?
Comment: @Abdul Ok, now you have answers for the easy $7^{\large n}$ case *and* the more general $7n$ case.
Comment: Why is $a^2 = -1$ ?
Comment: @BillDubuque My bad, I fixed it now. I indeed meant $7^n$
Answer: [Note: this answer applies to the original more general question with exponent $7n$ vs. $7^{\large n}$]
$ \mathbb{F}_{\large 7}[x]/(x^2\!+\!1)\cong \Bbb F_{\large 7}[\,i\,]\,$ where $\,\overline{a\!+\!bi} = (a\!+\!bi)^{\large 7}\! = a\!-\!bi\,$ is the  conjugation automorphism.
If $\,w = 1\!+\!i\,$ then $\,(1\!+\!w)^{\large 7n}\! = 1\!+\!i \!\iff\! \bar w^{\large n} = w.\,$  Taking norm $\,N(x) = x\bar x\, $ of both sides yields $2^{\large n}\! = 2\,$ in $\,\Bbb F_{\large 7}\!\!\iff n\equiv 1\!\pmod{\!3},\,$ by $\,2\,$ has order $3$. $\,n = 7\,$ works: $\ \bar w^7\! = \bar {\bar w} = w,\, $ but no smaller $n$ works: $\,\bar w\neq w\,$ so $\,n\neq 1,\,$ and $\,n \neq  4\,$ else $\, \bar w^4\! = w = \bar w^7\Rightarrow\, 1 = \bar w^3 \Rightarrow\, \bar w = \bar w^4\! = w$.
Comment: Nice!${}{}{}{}{}{}{}{}$
Answer: The question can be rephrased as

What is the smallest positive integer $n$ such that $(a+1)^{7n-1} = 1$?

Let $m$ be the order of $a+1$ in the multiplicative group $\Bbb{F}^\times$, which has order $48$.
Then $m$ divides $\gcd(7n-1,48)$. Let's see the possibilities:
$$
\begin{array}{r|rrrrrrr}
n & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\
7n-1 & 6 & 13 & 20 & 27 & 34 & 41 & 48 \\
\gcd(7n-1,48) & 6 & 1 & 4 & 3 & 2 & 1 & 48
\end{array}
$$
By checking that $(a+1)^k \ne 1$ for $k=1,2,3,4,6$, we arrive at $n=7$.
Comment: Taking norms leaves $\,n = 4\,$ as the only nontrivial case to exclude - see my answer.


for loop that batch the data and throw it out in c++

Question: <code>void write_token_to_data()
    {
        typedef double* DynamicMatrix[l+m];
        // DynamicMatrix Count;
        typedef double* DynamicMatrix2[l+m];
        //DynamicMatrix2 Prob;
        for(int i=0; i<(l+m); i++)
        {
            for(int j=0; j<(l+m); j++)
            {
                if(mysqlinsert2(i,j,combine[i],combine[j]))
                {
                    cout<<"insert OK!!"<<endl;
                }
                else
                {
                    cout<<"insert failed"<<endl;
                }

            }
        }

    }//end of function
</code>

here is my question
how can i change this sub function ,that i can keep i ,j combine[i], combine[j]
until the number 100 , and throw these four value into the mysqlinsert function
and free the array in the for loop index 101 and continue record the value ,long story short,i want break this mysql insert into small part
Answer: <code> - You can contruct a string in the form
(i,j,cobine[i],combine[j]) for each iteration.
 - Inorder to insert a multiple rows in a single query.
[Normal insert query for multiple records
 INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
]
 - also rewrite mysqlinsert2(i,j,combine[i],combine[j]) into *mysqlinsert2(str)*.and execute the string.

    for(int i=0; i<(l+m); i++){
      for(int j=0; j<(l+m); j++){
        if (till count => 100) {
          // concatinate the string with prev str
          str += (i,j,combine[i],combine[j])+',';
        }
        if (count reaches hundred || count = 0) {
          // execute the string
          mysqlinsert2(str);
          // initialize str as empty string
          str = 'INSERT INTO Table ( Column1, Column2, column3, column4 ) VALUES';
          count = 0;
        }
      }
    }
</code>
Comment: my question is where to declare the count? is outside the for loop? next question , i 'd like to know where to put the count++ is suitable ?


Oracle Create trigger statement fails with internal error code ORA-00600

Question: Trying to execute a dumpfile created from Oracle. Everything gets created and altered fine until this block:
CREATE OR REPLACE TRIGGER "LABS"."CHANNEL_CHANNEL_ID_TRG" BEFORE INSERT ON channel
FOR EACH ROW
DECLARE
v_newVal NUMBER(12) := 0;
v_incval NUMBER(12) := 0;
BEGIN
IF INSERTING AND :new.CHANNEL_ID IS NULL THEN
SELECT  channel_CHANNEL_ID_SEQ.NEXTVAL INTO v_newVal FROM DUAL;
-- If this is the first time this table have been inserted into (sequence == 1)
IF v_newVal = 1 THEN
  --get the max indentity value from the table
  SELECT NVL(max(CHANNEL_ID),0) INTO v_newVal FROM channel;
  v_newVal := v_newVal + 1;
  --set the sequence to that value
  LOOP
       EXIT WHEN v_incval>=v_newVal;
       SELECT channel_CHANNEL_ID_SEQ.nextval INTO v_incval FROM dual;
  END LOOP;
END IF;
--used to emulate LAST_INSERT_ID()
--mysql_utilities.identity := v_newVal;
-- assign the value from the sequence to emulate the identity column
:new.CHANNEL_ID := v_newVal;
END IF;
END;

This fails and severs the connection, giving the following rather cryptic error:
ORA-00603: ORACLE server session terminated by fatal error
ORA-00600: internal error code, arguments: [kqlidchg1], [], [], [], [], [], [], [], [], [], [], []
ORA-00604: error occurred at recursive SQL level 1
ORA-00001: unique constraint (SYS.I_PLSCOPE_SIG_IDENTIFIER$) violated
00603. 00000 -  "ORACLE server session terminated by fatal error"
*Cause:    An ORACLE server session is in an unrecoverable state.
*Action:   Login to ORACLE again so a new server session will be create

Comment: http://www.db-eccentric.com/2011/04/ora-0600-type-of-day.html
Comment: `ORA-00600` indicates an oracle bug, in this case seemingly an interaction between import and PL/Scope. In this case your workaround (turn off PL/Scope) is fine. If you need to use PL/Scope, you can re-enable it and recompile the trigger.
Answer: Found a solution that worked.  Surround the block of code with the following ALTER statements:
ALTER SESSION SET PLSCOPE_SETTINGS = 'IDENTIFIERS:NONE';

... sql statements here ...
ALTER SESSION SET PLSCOPE_SETTINGS = 'IDENTIFIERS:ALL';

For some reason, the Oracle database dump does not include these commands, but this fixed the problem.


Should I avoid using my index finger on non-barre chords?

Question: I'm a guitar beginner who knows the basic, non-barre chords and is now learning some barre chords.
I've noticed that, usually, barre chord shapes are just like non-barre chords but shifted. For example, the B major chord is exactly the same as A major chord shifted by 2 frets (+ using the index finger for barre).
The thing is, I've learned to play the A major chord using my 1st, 2nd and 3rd fingers to push the three strings needed:

While the B major chord has a barre so I need to push the three strings using my 2nd, 3rd and 4th fingers.

Now I begin to wonder: should I try to get my fingers used to the barre chords by avoiding use of the index finger for non-barre chords, so for example doing the A major chord using my 2nd, 3rd and 4th fingers instead?

Would doing that facilitate switching from chords like A major to B major, E major to F major, C major to C# major, and so on...?
Answer: There is (and should be) no general rule. Try several fingerings for each chord, and see what works best for any specific situation / chord progression. Most advanced guitar players use several fingerings for the same chord shape, depending on the situation. It's good to have a choice.
Two more specific suggestions related to your question:

also try to play the open A chord barring your first finger on the d, g, and b-strings. Note that you can mute the high e string, no need to let it ring open because you already play the note e on the d-string.
try to play shifted versions of the open A chord (barre versions) using that same idea: first finger on the A string (no barre), and third (or fourth) finger barring the d, g, and b-strings. This makes it a lot easier to quickly shift between different chords of that shape. The 4-finger version shown in your question is almost impossible to play in higher positions (the limit obviously depends on the size of your fingers).
Comment: While one is learning to successfully mute certain strings for your suggestion, wouldn't it be more productive to learn to play full barre chords?
Comment: @Tim: By "full barre" you mean the one shown in the OP (A shape barre with 4 fingers)?
Comment: @Tim: My suggestions was actually to play 4 strings: A to b (index on A and third finger on d,g,b); in that way you play a full barre chord, which is very useful in practice. Of course it also makes sense to learn the 5-string version (with  4 fingers), but I personally think that the other one is more practical, especially in the higher positions.
Comment: Although +1 because you first emphasized that one should practice multiple different fingerings of every chord, I always object to recommendations of the "secondary barre" A-shape chord. Yes, this too has valid applications, but they are few; generally, this bar forces the hand into a bad, inflexible position and makes embellishments inconvenient. Better focus on the individual-fingers versions, and only keep the 3-string-bar version in mind as a backup. A better chord to practice that involves a bar on the same strings is the G-shape.
Comment: Yes, pressing down 5 (or in my case, usually 6) strings, instead of the suggestion to mute all but the three on 2,3 and 4.
Comment: Yes, have to say, up to about frets5/6, it's either  two/three fingers on 2,3,4, after which it's a two finger barre for me, one for 6,5,1, the other for 2,3,4. Mainly, as you say, lack of space.
Answer: It's a cunning idea, and will, to a degree, work quite well. One of the main considerations is where you came from, and where you're going next. That's actually one of the main considerations for all chord fingering.
If you were playing the Spanish sequence in Dm, then you may well start with an Am shape on 5th fret barred, go down to C, A shape barred on 3rd fret, down to Bb on 1st fret, and keep middle, ring and pinky on strings 4,3 and 2 for an open A.
However, if your open A chord was sandwiched between say E and D, then a better fingering would work. I would still play A like that after an E. Mainly because middle and ring fingers can move across a string each, and pinky goes on 2nd string, 2nd fret.
Moving on to the E shape, which I usually play with middle, ring and index. I do that for a couple of good reasons. If B7 follows, my middle stays where it is. If A follows, see previous para.
C shape also gets barred, but because of the previous and next chords' likelihood of being F or G, with open type chords (how can F be open?!) then I'd use pinky on 5, ring on 6, middle on 4, index on 2.That's not transferrable as index is already occupied, so needing to put index as the barre finger means everything has to be swapped round.
Same idea happens with an open G shape, which lends itself nicely to moving up and being barred.
EDIT: as an aside, people with larger fingers find A easier using middle, ring and pinky, as they take up less room than the first pictured version. it's also easier then to get to open E. Give it a try.
Answer: Yes, and you should also learn the same chords using your first finger.
As you say, there may be times you want to switch quickly between a barre chord and an open chord of the same shape. In those cases, it is helpful to play the open chord without using your first finger.
But there are also cases where you will want to play two chords close together where using your first finger will make it easier to change quickly. So you will want to know how to finger the same chord using your first finger.
So you should learn it both ways.
Answer: I'm trying to think of a barre chord that ISN'T "just like non-barre chords but shifted"!
"Would doing that facilitate switching from chords like A major to B major, E major to F major, C major to C# major, and so on...?"
Yes, it would.  But there are other chords that it WOULDN'T facilitate.   Choose your shapes according to context - according to what comes before and after.
Answer: For some chords, it can be very convenient to have the index finger available.
I learned to play the open G chord with the 1st, 2nd and 3rd fingers:

and the G7 chord with the same fingers:

If you want to switch from one chord to the other, you have to twist your hand fast and move 3 fingers.
But if you play the open G chord this way:

All you have to do is lift your pinky to switch from G to G7.
Here's the motion on video (not mine).
Comment: A similar situation arises with D and D7.  It can be an easy change if you use the pinky to fret the B string on the D chord, and the index finger to fret that string on the D7.
Comment: I don't use Standard tuning much, since when I was starting guitar I found it frustrating and decided to invent a tuning that would make chords more convenient, and even though I've subsequently learned Standard, I still like Flat Finger Tuning better.  On the other hand, I find it curious that materials teaching Standard Tuning so often suggest chord fingerings that don't transition at all smoothly.  Even using better fingerings, Standard tuning doesn't support many transitions that are as easy as those in Flat Finger, but that's no reason to use clumsy fingerings.
Answer: Both of your A chord forms are legitimate.  It is good that you see the pattern between barre chords and open string chords.
Some guitarists prefer to play the open string chords using the barre chord fingering with the index finger behind the nut.  But this is not a rule of any sort, just a preference.  It may interest you to know that many guitarists play the open string A chord with an index finger barre on the second fret (D, G, B, E) strings, plucking or picking only the middle four strings.  Plucking the barred high e string would create an A6 chord, and your other fingers are free to create A7, A maj7 etc.
For more advanced guitarists the choice of fingering would be driven by the context, e.g. what chords come before or after the particular chord in question.  So both methods of fingering are valid and worth practicing.


Limpar elemento select com JavaScript

Question: Possuo esse campo select:

  <select runat="server" onclick="ClearOptions(this);" name="txtpesquisa" id="txtpesquisa" class="form-control.selectize-control">
  </select>

Preciso limpar ele ao clicar, onde ele abre a pesquisa, pois está escrito pesquise aqui, ai na hora que clicasse, precisava que o campo ficasse pronto para ser digitado. Como posso fazer? Já tentei algumas formas, porém sem sucesso.
Esta é a ultima forma que tentei, mas também não deu certo:

function ClearOptions(id) {
  document.getElementById(id).options.length = -1;
}

Segue como carrego o txtpesquisa.

private void CarregaPessoa() {

  SqlCommand comando = new SqlCommand();
  comando.Connection = clsdb.AbreBanco();
  comando.CommandType = CommandType.Text;
  comando.CommandText = "select id, nome, classificacao_id from PESSOA where id != 0 order by nome asc";

  SqlDataAdapter da = new SqlDataAdapter();
  da.SelectCommand = comando;
  DataSet ds = new DataSet();
  da.Fill(ds);

  DataRow dr = ds.Tables[0].NewRow();
  dr[0] = 0;
  dr[1] = "Pesquise aqui .. ";
  ds.Tables[0].Rows.InsertAt(dr, 0);

  txtpesquisa.DataSource = ds.Tables[0];
  txtpesquisa.DataTextField = "nome";
  txtpesquisa.DataValueField = "id";
  txtpesquisa.DataBind();
}
Comment: Sua pegunta não ficou muito clara, vc quer limpar qual campo, está utilizando plugins?
Answer: Quando você utiliza o Selectize.js ele esconde seu input e cria uma série de elementos (divs e um outro input) para criar a caixa de entrada para as tags e options. Isso singifica que não é aconselhável você trabalhar diretamente com o input original, mas sim com o objeto que é retornado através do método selectize().
Para você escutar quando o objeto toma foco e limpá-lo, utilize como abaixo:
var $select = $('#txtpesquisa').selectize({
    onFocus : function(){
        $select[0].selectize.clear();
    },
});

Porém, acho que você pode utilizar de uma maneira melhor. O que você procura talvez seja um placeholder mais inteligente. Veja abaixo:
var $select = $('#txtpesquisa').selectize({
    placeholder : "Pesquise aqui"
});

Neste link você pode encontrar mais informações sobre como utilizar o Selectize.js e poderá ver o restante de suas configurações.
Comment: Consegui usando o seu código mesmo, $select[0].selectize.clear(); coloquei somente esta parte, e deu certo, obrigado.
Comment: Não funcionou, eu já tenho o pesquisa aqui, que o valor é 0 e faz a pesquisa se todos, porém preciso que na hora que o usuário clique, limpe o campo para que ele possa digitar.
Comment: Você usou a primeira opção para limpar? Ocorreu algum erro?
Comment: Não, ele não ocorre nenhum erro, vou te mostrar como que carrego o txtpesquisa, vou atualizar a pergunta.
Comment: Alguma dica @bio ?
Comment: Se o plugin está funcionando corretamente como no primeiro código que você colocou na sua pergunta, a primeira solução que te entreguei, baseada em código javascript, deveria funcionar. Você informou que não funciona, porém não ocorre nenhum erro, então o que exatamente não está funcionando?
Comment: [Veja aqui](http://abner.xyz/selectize/examples/events.html) os eventos funcionando. Inclusive o `onFocus`, que é executado assim que o elemento toma foco.
Comment: [Neste outro link](https://github.com/selectize/selectize.js/issues/319) existe uma forma alternativa de capturar o `onclick`, porém não me parece tão correto utilizar dessa forma. Enfim, se puder te ajudar...
Comment: Que bom que te ajudei e funcionou, boa sorte! :)

Limpar elemento select com JavaScript


Crash With DllImport C#

Question: Gang,
I'm using a third-party API written in (what looks like) MFC C++.  My application is a WinForms app in C#.  The API's company has a C# demo application, and I used their code verbatim.  The relevant code looks like this...
API's C++ Function:
int PASCAL CppFunction(BYTE *pbAdapterID, BYTE *pbTargetID, char *pcVendor, char *pcProduct, char *pcRelease, int iMessageBox)
{
    // The function definition is all I can see in the API's documentation
}

The DllImport Statement:
[DllImport("api.dll")]
extern public static int CppFunction(ref byte pbAdapter, ref byte pbTargetID, string pcVendor, string pcProduct, string pcRelease, int iMessageBox);

My C# Logic:
public void CallCppFunction()
{
    try
    {
        int result = 0;
        string strVendorBuffer = string.Empty;
        string strProductBuffer = string.Empty;
        string strReleaseBuffer = string.Empty;
        string strSerial = string.Empty;
        byte bAdapt = 0;
        byte bTarg = 0;

        result = CppFunction(ref bAdapt, ref bTarg, strVendorBuffer, strProductBuffer, strReleaseBuffer, 0);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

This is the code as it exists in their C# sample.  When run, it crashes with a "FatalExecutionEngineError" even in a try/catch.

I don't know PInvoke very well, but don't those variables have to be marshaled as an unmanaged type?  Any help would be appreciated.
Comment: It's a guess. It's probably due to your string handling (you don't specify how you marshal them, use `[MarshalAs]`). If the string parameters are output, you should use `StringBuilder` instead of `string` (with some preallocated storage)
Comment: I am pretty sure I know the answer but you need to tell me what `CppFunction` is supposed to do first.
Comment: Without any knowledge of what the interface is nobody can say. The C++ function prototype does not define the interface. The `ref byte` is almost certainly wrong. But what should it be? How can we possibly know with the information presented? We could guess, but do you really go through life writing code by guesswork?
Comment: You may not need to use dllImport.  You may just need to add dll as a reference and add appropriate 'using' statements at top of module.
Comment: @jdweng Really. You think this is a managed DLL?
Answer: I am taking a wild guess here, but I am pretty sure it will be the right answer
Lets take a look to the function definition:
int PASCAL CppFunction(
    BYTE *pbAdapterID,
    BYTE *pbTargetID,
    char *pcVendor,
    char *pcProduct,
    char *pcRelease,
    int iMessageBox);

And the corresponding DllImport declaration:
[DllImport("api.dll")]
extern public static int CppFunction(
    ref byte pbAdapter,
    ref byte pbTargetID,
    string pcVendor,
    string pcProduct,
    string pcRelease,
    int iMessageBox);

There are a lot of parameters there, some of them caught my attention:
    char *pcVendor,
    char *pcProduct,
    char *pcRelease,

They are not passed by reference, are they being modified by the library?
Note: That why I asked you to give details about the function.
I that's the case, you cannot marshal strings because the datatype string is immutable, you must use the StringBuilder class, just make sure the StringBuilderhas enough Capacity.
int result = 0;
StringBuilder strVendorBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strProductBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strReleaseBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strSerial = string.Empty;
byte bAdapt = 0;
byte bTarg = 0;

result = CppFunction(ref bAdapt, ref bTarg, strVendorBuffer, strProductBuffer, strReleaseBuffer, 0);

Comment: PASCAL is the same as stdcall, which is pinvoke's default calling convention
Comment: Dont guess. That's the reason asker is stuff. Too much guesswork. The ref byte args are surely wrong. Makes no sense to guess at buffer size too. That won't end well. More plausible that strings are in params. Guessing is really bad advice.
Comment: Sorry someone gave you the down vote.  Unfortunately, what I posted is what I got from the vendor, so we sort of have to guess.  However, I tried replacing the strings with StringBuilders and it worked.  Thanks!!!

Crash With DllImport C#


checkbox type in form

Question: how i can knowing if the checkbox is checked or not on the form

function darksite_config_page() {
  $form['darksite_status'] = array(
    '#title' => t('Enable pop up screen'),
    '#description' => t('When enabled, a pop up screen will be displayed on the home page.'),
    '#type' => 'checkbox',
    '#default_value' => variable_get('darksite_status', 0)
  );

  return system_settings_form($form);
}
Comment: check can be done in $form_state variable
Comment: where are you trying to check it?
Answer: Like so:
<code>if (variable_get('darksite_status', 0)) {
  // Yes.
}
else {
  // No.
}
</code>

checkbox type in form


Approximation of $\left(\frac{n - 1}{n}\right) ^ n$

Question: Is there a good approximation function for
$$\left(\frac{n - 1}{n}\right) ^ n$$
I am trying to quickly calculate the probability of an event with probability of $\frac{1}{n}$ not happening if you try $n$ times.
It's quite hard to google something you can't put a name on.
Comment: For large values of $n$ you can just take $1/e$.
Comment: @Dan Geek. this answer, probably :) is enough for the OP, but he/she may need an order 1 equivalent.
Comment: Would that work well enough for $n = 100$? As in $0.xxx$ accurate?
Comment: It doesn't work very well for $n=2$  :-)   For $n=100$, it's a lot better, but only you can decide if it's good enough.
Comment: Judging by the graph posted in an answer, for $n = 100$ the result is probably accurate to three digits, which is what I wanted.
Answer: It is $$\lim_{n\to \infty} \left(1-\frac{1}{n}\right)^n=e^{-1}$$
Answer: Note that
$$\left(\frac{n-1}n\right)^n=\left(1-\frac1n\right)^n=\frac{n-1}{1\times2n}-\frac{(n-1)(n-2)}{1\times2\times3n^2}+\frac{(n-1)(n-2)(n-3)}{1\times2\times3\times4n^3}+\dots$$
which is the binomial expansion theorem.
Comment: I am unsure that this development is useful for the question at hand.
Answer: The function
$$
f(x) = \left(\frac{x-1}x\right)^x=\left(1-\frac1x\right)^x
$$
is well-behaved, it appears, and, as others have noted, it approaches $1/e$ as $x$ gets larger. Here is a graph of $1/e - f(x)$:

So you can fit the first part of it with a polynomial, which will speed up your calculations, and you can just use $1/e$ for large values of $x$. When $x=100$, $1/e -f(x) \approx 0.00185.$
An excellent tool for fitting with polynomials is chebfun.
Answer: If you want a better approximation than $\frac1e \approx 0.36787944$ then you could try the Laurent series
$$\left(\dfrac{n-1}{n}\right)^n = \frac1e\left(1 - \frac1{2x} - \frac5{24x^2}- \frac5{48x^3} - \frac{337}{5760x^4} -O\left(\frac1{x^5}\right) \right)$$
which for small $n$ and ignoring the $O\left(\frac1{x^5}\right)$ term gives
<code>n       ((n-1)/n)^n Approx      difference
1       0           0.0474539   0.0474539
2       0.25        0.2506139   0.0006139
3       0.2962963   0.2963655   0.0000692
4       0.3164063   0.3164216   0.0000153
5       0.32768     0.3276848   0.0000048
6       0.3348980   0.3348999   0.0000019
7       0.3399167   0.3399175   0.0000009
8       0.3436089   0.3436094   0.0000004
9       0.3464394   0.3464397   0.0000002
10      0.3486784   0.3486786   0.0000001
11      0.3504939   0.3504940   0.0000001
12      0.3519956   0.3519957   0.0000001
13      0.3532585   0.3532585   0.0000000
14      0.3543353   0.3543353   0.0000000
15      0.3552644   0.3552644   0.0000000
16      0.3560741   0.3560741   0.0000000
17      0.3567862   0.3567862   0.0000000
18      0.3574172   0.3574172   0.0000000
19      0.3579803   0.3579803   0.0000000
20      0.3584859   0.3584859   0.0000000
21      0.3589424   0.3589424   0.0000000
22      0.3593565   0.3593565   0.0000000
23      0.3597340   0.3597340   0.0000000
24      0.3600794   0.3600794   0.0000000
25      0.3603967   0.3603967   0.0000000
100     0.3660323   0.3660323   0.0000000
1000    0.3676954   0.3676954   0.0000000
</code>


openvpn ios client custom url scheme

Question: My application have iOS OpenVPN Connect app dependency.
So I have to check if the app is already installed or not
if so I will just Open the app using OpenURL scheme else I will open its appstore link so that user will install it.
So my problem here is I couldn't find any open url associated with this app.
Any help is appreciated !
Answer: it exports a doctype. so you could use a UIDocumentInteractionController to check if the filetype can be opened and thus the app is installed.
uti is net.openvpn.formats.ovpn
copy a file of that type (you can make such a file on OSX) to the bundle and attempt to present an interaction controller for it using presentOpenInMenuFromRect
set yourself as delegate and if it fires willShowMenu, then you no the app is there - and you dismiss the menu.
so to get you started something like this:
NSString *file = ... //path to file with UTI in question
UIDocumentInteractionController *c = ... //init with file
c.delegate = self;
_hasAppInstalledForUTI = NO;
[c present...];

if(!_hasAppInstalledForUTI) {
    //act
}

...
- willPresentOpenInMenu {
    [c dismissAnimated:NO];
    _hasAppInstalledForUTI = YES;
}

BTW: I checked the app -- there is no url scheme.
Comment: The solution above will check whether file can be opened or not.I want to check whether openvpn is installed.As I need to open my file only using openvpn app.
Comment: that uti is only used by that app AFAIK ... openvpn config files. as there is no urrl scheme and wont be there without an updated app, this is the closest you'll get
Comment: The willPresentOpenInMenu will be called if the OpenVPN is not installed, it will open the menu with Mail and message options, please see this image http://monosnap.com/image/ja8NsXVGwhxc3QpvNQx5jBGvMgP61m
Answer: Whilst it might sound cheeky, I think one way would be to email the developers and ask them if they have a URL scheme, or if they would create support for one.  Its a win-win because their software is more likely to be installed if it can be leveraged in new ways, and you'd get the functionality you need.
Comment: Pretty much a duplicate of the second half of my answer ;)
Answer: To check if the user has the app at all, you would do the following:
NSURL *url = "appScheme://"
if ([[UIApplication sharedApplication] canOpenURL:url]) {
    [[UIApplication sharedApplication] openURL:url];
}
else {
    // can't open url
}

But not all apps have url schemes. I know mine don't.
If you are not able to find any online, then chances are there isn't one. Try to contact the developers to find out if there even is one to begin with, otherwise try finding another app that has one, and use that one instead.
Comment: thanks for your response, I have the above code ,I am searching for url scheme for open vpn app
Comment: Well, as I said, they might not have one. Try sending an email to the developers of the open vpn app and ask them.
Comment: @Daij-Djan you're not an answer. This is precisely the answer. Use `openvpn://` and read FAQ https://docs.openvpn.net/docs/openvpn-connect/openvpn-connect-ios-faq.html
Comment: Don't insult me. All ok with you? And this was still no answer in 2013. Now i don't know
Answer: You try to open an .ovpn file.
Here's an old question from myself to get you started on how to do that.
Source.
Though this is not specifically check that particular app, but it should do the job.
Comment: 100% what I wrote above just as a link ;)
Comment: I dont want to show open-in using UIDocumentInteractionController, I need to check whether openvpn is installed or not.I need custom url scheme , as I know the implementation
Answer: I think you want to open "openvpn ios" application from your application. Please check the below link for same :
http://mobile.tutsplus.com/tutorials/iphone/ios-sdk-working-with-url-schemes/
Follow the steps as it said and check whether application is opened or not.
Comment: Karthik: You can check whether application is installed or not with below code :
    NSString *ourPath = [@"appURLSheme://" stringByAppendingString:URLEncodedText];

    NSURL *ourURL = [NSURL URLWithString:ourPath];
    if ([ourApplication canOpenURL:ourURL])
        [ourApplication openURL:ourURL];
    else
        NSLog(@"There is no application installed.");
Comment: Napster,I want to check "openvpn ios" is installed or not.I know to check it using url scheme, I want to know the url scheme or any alternate way to achieve the same.
Comment: Napster,I know to check using urlscheme, I am searching for openvpn url scheme,or alternate way to achieve the same.
Comment: you can open with above code. Need to check about alternate if possible. Will update you if I got any solution for you.
Answer: Support for openvpn:// URL scheme was introduced in OpenVPN Connect 1.0.6, according to OpenVPN Connect FAQ you can use this code:
BOOL installed = [application canOpenURL:[NSURL URLWithString:@"openvpn://"]];

Following code opens iTunes to install OpenVPN Connect if it is not installed yet:
UIApplication * app = [UIApplication sharedApplication];
BOOL installed = [app canOpenURL:[NSURL URLWithString:@"openvpn://"]];
if (installed) {
    [app openURL: [NSURL URLWithString:@"openvpn://"]];
} else {
    [app openURL: [NSURL URLWithString: @"https://itunes.apple.com/app/id590379981?mt=8"]];
}

EDITED: actually this approach DOES NOT work, I have just tested myself - the matter is that published version of OpenVPN Connect in AppStore is 1.0.5, so this feature is not available in it ((

openvpn ios client custom url scheme


Markdown support in Android TextView

Question: Is there a way to enable a TextView to detect markdown tags and render the text accordingly? More specifically, my app contains a TextView in which the users can provide a description, and often they will use markdown to format their description. Unfortunately the text doesn't render, and instead we see all the tags written out in the textview.
Comment: Could you please add some of your code. This would help us detecting the problem and you will more likely get an answer
Comment: http://uncodin.github.io/bypass/, though not supported by gradle build at the moment, I'm afraid, because it's an "apklib".
Answer: There's no built-in support for Markdown in the Android SDK. You'll have to use a lib like markdown4j or CommonMark.
Answer: I understand you want to convert a String containing Markdown markup to a formatted CharSequence that you can use in a TextView. The two options I know of are :

Bypass : Use a native C library to parse the text. Unfortunately the project seems dead.
commonmark-spannable-android : Pure java, based on the very good commonmark-java
 library.

I used both and in my opinion, the second one is better : no need to deal with native architectures, smaller APK, and the performance is quite good (something like 2 times slower in my case, with is more than good enough)
Update : Found another option (it's the one I'm using now) :

Markwon : Pure java, also using commonmark-java as parser, with optional support for images and tables
Comment: Anyone these provide customisations? as in font color of all attributes etc?
Comment: Markwon allows [quite a few customization](https://github.com/noties/Markwon/blob/master/docs/SpannableTheme.md).
Comment: Hi @bwt, I trying the Markwon library in my app but I am stuck with the link handling part. I am wondering how to retrieve the link text for further formatting. Is there a place where I can get more info on using Markwon library? Any help is much appreciated.
Comment: @bwt i don't uderstand how to use markwon can you please explain it in your answer
Answer: There is no inherit support for markdown in textview, however if you only need simple markdown-lite implementation via simple "regexp" matching, this section from my "load readme from project root folder" in  https://github.com/mofosyne/instantReadmeApp would help.
Note that this does not remove the markup in the text, only styles the lines differently. This may be a good or bad thing, depending on your application.
Oh and the nice thing? It styles in native textview, so the text is still selectable like normal text.
Specifically this line: https://github.com/mofosyne/instantReadmeApp/blob/master/app/src/main/java/com/github/mofosyne/instantreadme/ReadMe.java#L137
Slightly modified below: private void updateMainDisplay(String text) to private void style_psudomarkdown_TextView(String text, TextView textview_input), so you could use the same function for different textviews
```
<code>/*
    Text Styler
    A crappy psudo markdown styler. Could do with a total revamp.
 */

/*
* Styling the textview for easier readability
* */
private void style_psudomarkdown_TextView(String text, TextView textview_input) {
    //TextView mTextView = (TextView) findViewById(R.id.readme_info);
    TextView mTextView = textview_input;

    // Let's update the main display
    // Needs to set as spannable otherwise http://stackoverflow.com/questions/16340681/fatal-exception-string-cant-be-cast-to-spannable
    mTextView.setText(text, TextView.BufferType.SPANNABLE);
    // Let's prettify it!
    changeLineinView_TITLESTYLE(mTextView, "# ", 0xfff4585d, 2f); // Primary Header
    changeLineinView(mTextView, "\n# ", 0xFFF4A158, 1.5f); // Secondary Header
    changeLineinView(mTextView, "\n## ", 0xFFF4A158, 1.2f); // Secondary Header
    changeLineinView(mTextView, "\n---", 0xFFF4A158, 1.2f); // Horizontal Rule
    changeLineinView(mTextView, "\n>",   0xFF89e24d, 0.9f); // Block Quotes
    changeLineinView(mTextView, "\n - ", 0xFFA74DE3, 1f);   // Classic Markdown List
    changeLineinView(mTextView, "\n- ", 0xFFA74DE3, 1f);   // NonStandard List

    //spanSetterInView(String startTarget, String endTarget, int typefaceStyle, String fontFamily,TextView tv, int colour, float size)
    // Limitation of spanSetterInView. Well its not a regular expression... so can't exactly have * list, and *bold* at the same time.
    spanSetterInView(mTextView, "\n```\n", "\n```\n",   Typeface.BOLD,        "monospace",  0xFF45c152,  0.8f, false); // fenced code Blocks ( endAtLineBreak=false since this is a multiline block operator)
    spanSetterInView(mTextView,   " **"  ,     "** ",   Typeface.BOLD,        "",  0xFF89e24d,  1f, true); // Bolding
    spanSetterInView(mTextView,    " *"  ,      "* ",   Typeface.ITALIC,      "",  0xFF4dd8e2,  1f, true); // Italic
    spanSetterInView(mTextView,  " ***"  ,    "*** ",   Typeface.BOLD_ITALIC, "",  0xFF4de25c,  1f, true); // Bold and Italic
    spanSetterInView(mTextView,    " `"  ,      "` ",   Typeface.BOLD,        "monospace",  0xFF45c152,  0.8f, true); // inline code
    spanSetterInView(mTextView, "\n    " ,      "\n",   Typeface.BOLD,        "monospace",  0xFF45c152,  0.7f, true); // classic indented code
}

private void changeLineinView(TextView tv, String target, int colour, float size) {
    String vString = (String) tv.getText().toString();
    int startSpan = 0, endSpan = 0;
    //Spannable spanRange = new SpannableString(vString);
    Spannable spanRange = (Spannable) tv.getText();
    while (true) {
        startSpan = vString.indexOf(target, endSpan-1);     // (!@#$%) I want to check a character behind in case it is a newline
        endSpan = vString.indexOf("\n", startSpan+1);       // But at the same time, I do not want to read the point found by startSpan. This is since startSpan may point to a initial newline.
        ForegroundColorSpan foreColour = new ForegroundColorSpan(colour);
        // Need a NEW span object every loop, else it just moves the span
        // Fix: -1 in startSpan or endSpan, indicates that the indexOf has already searched the entire string with not valid match (Lack of endspan check, occoured because of the inclusion of endTarget, which added extra complications)
        if ( (startSpan < 0) || ( endSpan < 0 ) ) break;// Need a NEW span object every loop, else it just moves the span
        // Need to make sure that start range is always smaller than end range. (Solved! Refer to few lines above with (!@#$%) )
        if (endSpan > startSpan) {
            //endSpan = startSpan + target.length();
            spanRange.setSpan(foreColour, startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // Also wannna bold the span too
            spanRange.setSpan(new RelativeSizeSpan(size), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanRange.setSpan(new StyleSpan(Typeface.BOLD), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    tv.setText(spanRange);
}

private void changeLineinView_TITLESTYLE(TextView tv, String target, int colour, float size) {
    String vString = (String) tv.getText().toString();
    int startSpan = 0, endSpan = 0;
    //Spannable spanRange = new SpannableString(vString);
    Spannable spanRange = (Spannable) tv.getText();
    /*
    * Had to do this, since there is something wrong with this overlapping the "##" detection routine
    * Plus you only really need one title.
     */
    //while (true) {
    startSpan = vString.substring(0,target.length()).indexOf(target, endSpan-1); //substring(target.length()) since we only want the first line
    endSpan = vString.indexOf("\n", startSpan+1);
    ForegroundColorSpan foreColour = new ForegroundColorSpan(colour);
    // Need a NEW span object every loop, else it just moves the span
        /*
        if (startSpan < 0)
            break;
            */
    if ( !(startSpan < 0) ) { // hacky I know, but its to cater to the case where there is no header text
        // Need to make sure that start range is always smaller than end range.
        if (endSpan > startSpan) {
            //endSpan = startSpan + target.length();
            spanRange.setSpan(foreColour, startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // Also wannna bold the span too
            spanRange.setSpan(new RelativeSizeSpan(size), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanRange.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    //}
    tv.setText(spanRange);
}

private void spanSetterInView(TextView tv, String startTarget, String endTarget, int typefaceStyle, String fontFamily, int colour, float size, boolean endAtLineBreak) {
    String vString = (String) tv.getText().toString();
    int startSpan = 0, endSpan = 0;
    //Spannable spanRange = new SpannableString(vString);
    Spannable spanRange = (Spannable) tv.getText();
    while (true) {
        startSpan = vString.indexOf(startTarget, endSpan-1);     // (!@#$%) I want to check a character behind in case it is a newline
        endSpan = vString.indexOf(endTarget, startSpan+1+startTarget.length());     // But at the same time, I do not want to read the point found by startSpan. This is since startSpan may point to a initial newline. We also need to avoid the first patten matching a token from the second pattern.
        // Since this is pretty powerful, we really want to avoid overmatching it, and limit any problems to a single line. Especially if people forget to type in the closing symbol (e.g. * in bold)
        if (endAtLineBreak){
            int endSpan_linebreak = vString.indexOf("\n", startSpan+1+startTarget.length());
            if ( endSpan_linebreak < endSpan ) { endSpan = endSpan_linebreak; }
        }
        // Fix: -1 in startSpan or endSpan, indicates that the indexOf has already searched the entire string with not valid match (Lack of endspan check, occoured because of the inclusion of endTarget, which added extra complications)
        if ( (startSpan < 0) || ( endSpan < 0 ) ) break;// Need a NEW span object every loop, else it just moves the span
        // We want to also include the end "** " characters
        endSpan += endTarget.length();
        // If all is well, we shall set the styles and etc...
        if (endSpan > startSpan) {// Need to make sure that start range is always smaller than end range. (Solved! Refer to few lines above with (!@#$%) )
            spanRange.setSpan(new ForegroundColorSpan(colour), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanRange.setSpan(new RelativeSizeSpan(size), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanRange.setSpan(new StyleSpan(typefaceStyle), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // Default to normal font family if settings is empty
            if( !fontFamily.equals("") )  spanRange.setSpan(new TypefaceSpan(fontFamily), startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    tv.setText(spanRange);
}
</code>
```
The above implementation supports only up to 2 headers (but you can easily modify the regexp to support more than 2 level headers).
It is a series of regexp based text view consisting of two functions for regexp that matches always a line changeLineinView() and changeLineinView_TITLESTYLE()
For multiline spanning spanSetterInView() function deals with it.
So extending it to fit your purpose as long as you have a regexp that doesn't clash with any other syntax would be possible.
Markdownish Syntax:
This is the supported syntax. Can't support full markdown, since this is only a lite hacky implementation. But kind handy for a no frills display that is easy to type on a mobile phone keypad.
# H1 only in first line (Due to technical hacks used)

## H2 headers as usual

## Styling
Like: *italic* **bold** ***bold_italic***

## Classic List
 - list item 1
 - list item 2

## Nonstandard List Syntax
- list item 1
- list item 2

## Block Quotes
> Quoted stuff

## codes
here is inline `literal` codes. Must have space around it.

    ```
    codeblocks
    Good for ascii art
    ```

    Or 4 space code indent like classic markdown.

Comment: could you add an `*.md` file loader with it
Answer: I followed this post since last Friday and tested many of the Markdown libraries suggested here - this question and these answers were basically the best source about the topic I could find online.
Two of them caught my attention the most, MarkdownView and Markwon, but the former was easier to deal with than the latter and so I used it to empower a Room note taking app by Markdown formatting (which was my main personal goal).
If you want to have a Markdown live preview, you could just use this sample activity provided by the library itself and, among other options, if you need to adapt your own activity to it, I suggest you add the following pieces of code to your project:
build.gradle
implementation 'us.feras.mdv:markdownview:1.1.0'

private MarkdownView markdownView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.markdownView = findViewById(R.id.markdownView);
    this.udateMarkdownView();
}

private void updateMarkdownView() {
    markdownView.loadMarkdown(note_content.getText().toString());
}

Here you find the sample I put available on GitHub in which you can see a working project apart from the samples the library itself gives us as examples.
Answer: I can recommend MarkdownView. I use it for loading markdown files from the assets folder.
In case it helps anyone, here's my implementation...
In my layout:
<us.feras.mdv.MarkdownView
    android:id="@+id/descriptionMarkdownView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    app:layout_constraintTop_toBottomOf="@id/thumbnailImageView"
    app:layout_constraintStart_toEndOf="@id/guidelineStart"
    app:layout_constraintEnd_toEndOf="@id/guidelineEnd"
    app:layout_constraintBottom_toTopOf="@id/parent"/>

In my Activity:
val cssPath = "file:///android_asset/markdown.css"
val markdownPath = "file:///android_asset/markdown/filename.md"
descriptionMarkdownView.loadMarkdownFile(markdownPath, cssPath)

Comment: Thanks to you comment, I got in touch with this library this weekend and it's pretty easty to deal with it. In my case, I used it to view notes with Markdown formatting and it worked well enough to do the task.
Answer: Take a look at the commonmark-java library.
I haven't tried that myself but I think you might be able to make it work in your case
Answer: If you want to render HTML you can use Html.fromHtml("your string"), for more resources on Strings in Android check this link

Markdown support in Android TextView


AntiForgeryToken does not work well with OAuth via WebAPI

Question: We are trying to make a MVC4 app with Oauth (Gmail) authorisation accessible via a WebAPi.
We made a WebAPI controller that returns a list of data, but we cannot put the authorise attribute to work properly.
Right now it is difficult to send the AntiForgeryToken correctly to the server and we get a session_requestverificationtoken error.
Is there a good way to parse and post the correct antiforgery token via Webai? Or is there a better way to login via OAuth via a webapi?
Answer: Why are you using an AntiForgeryToken with Web API? It's not necessary, just authenticate with your request with OAuth. They are not meant to work together.
Comment: Got it to work with an extra controller without AntiForgeryToken indeed.


What's The Limit of The Recursion $a_{n+1} = \sqrt{2+\sqrt{a_n}}$ with $a_0 = \sqrt{2}$?

Question: I'm following a study guide for an exam and the very first question is:
Show that the sequence defined by $a_{n+1} = \sqrt{2+\sqrt{a_n}}$ with $a_0 = \sqrt{2}$ is increasing, bounded and calculate it's limit as $n \to \infty$.
The first parts are easy enough, and the proof for boundedness shows that, since $a_n < 2$ for all $n$, then:
$$a_k < 2$$
$$2 + \sqrt{a_k} < 2 + \sqrt{2}$$
$$a_{k+1} = \sqrt{2+\sqrt{a_n}} < \sqrt{2+\sqrt{2}}$$
This appears to be a pretty good bound for the sequence, but the limit should also be a fixed point for the sequence. Using this and performing some polynomial division, we get:
$$ P(x) = (x^2 - 2)^2 - x = (x-1)(x^3 + x^2 - 3x - 4)$$
Performing the recursion on the computer ( and checking with Wolfram) we get a limit $L \approx 1.831177207208337$. However, $\sqrt{2+\sqrt{2}} \approx 1.8477590650225735$. How am I supposed to get a closed form solution for this thing during a timed exam? Am I missing something?
Comment: I think there is nothin' you're missing. You can write its answer as the only real root of $x^3+x^2-3x-4$.
Comment: @emilagazade That's a different recurrence relation.
Comment: ooh sorry I will delete my comment
Answer: I agree with what you have done here - if the limit is $L$, you want to solve
$$L = \sqrt{2+\sqrt{L}}$$
which gives $L \approx 1.8312$ as in your answer.
I suspect there is a mistake in the question, and it meant to say $a_{n+1} = \sqrt{2+a_n}$. Which you can work out has a limit of 2.
The first equation isn't easy to solve at all - you have $L^2 - \sqrt{L} - 2 = 0$, which is possible to solve by taking this as a quartic in $\sqrt{L}$ and applying the quartic formula, but is very unlikely what was intended on the exam! I think more likely it was a typo unfortunately.
Comment: $a_{n+1}=\sqrt{2+a_n}$ has the simpler limit $2$.
Comment: @Macavity thank you, edited my answer
Comment: $L^2-\sqrt{L}-2=(\sqrt{L}+1)(L\sqrt{L}-L+\sqrt{L}-2)$ so it's a cubic.
Comment: @GarethMa you've written it as a product of a linear polynomial and a cubic! So it is a quartic. I agree that $\sqrt{L}+1$ is never 0, so you want to solve the cubic polynomial, but it's not accurate to say  'it's a cubic'.
Comment: @FredT Close enough, I guess I meant "applying the quartic formula" is not necessary.


Especificar última linha para preenchimento de formulário - VBA

Question: Estou fazendo um formulário e quero que a pessoa cadastre somente 6x (somente 6 linhas) o conteúdo. Como limitar essa quantidade ?

Conforme exemplo acima, eu coloquei as linhas e colunas e quando vou preenchendo o formulário, novos numeros vao descendo
<code>    Private Sub CmdSalvar_Click()
Dim Linha As Integer

'Valor inicial da Variável Linha
Linha = 85

**Do Until ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 8).Value = Empty
    Linha = Linha + 1**

Loop
'SE o usuário não entrar com os dados
If TxtMes.Value = Empty Or TxtAno.Value = Empty Then
    ElseIf TxtLeitura.Value = Empty Or TxtConsumo.Value = Empty Then

        MsgBox ("Preencha todos os dados!")
Else
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 8).Value = TxtMes.Value
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 9).Value = TxtAno.Value
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 11).Value = TxtLeitura.Value
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 14).Value = TxtConsumo.Value
End If

End Sub
</code>
Acredito que seja por causa da seguinte linhas:
<code>**Do Until ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 8).Value = Empty
        Linha = Linha + 1**
</code>
Mas como alterar para parar o preenchimento na linha 90 ? (Começa na linha 85 e quero parar na 90)
Answer: Você pode adicionar uma condicional se para sair da função caso passe da linha 90.
Código
Com o seguinte código:
<code>'Verifica se a Linha é maior do que 90
If Linha > 90 Then
    MsgBox "Você não pode mais inserir cadastros. Mensagem de aviso!"
    Exit Sub
End If
</code>
Código Completo
<code>Dim Linha As Long

'Valor inicial da Variável Linha
Linha = 85

Do Until ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 8).Value = Empty
    Linha = Linha + 1
Loop
'Verifica se a Linha é maior do que 90
If Linha > 90 Then
    MsgBox "Você não pode mais inserir cadastros. Mensagem de aviso!"
    Exit Sub
End If

'SE o usuário não entrar com os dados
If TxtMes.Value = Empty Or TxtAno.Value = Empty Then
ElseIf TxtLeitura.Value = Empty Or TxtConsumo.Value = Empty Then

    MsgBox ("Preencha todos os dados!")
Else
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 8).Value = TxtMes.Value
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 9).Value = TxtAno.Value
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 11).Value = TxtLeitura.Value
    ThisWorkbook.Sheets("CADASTRO").Cells(Linha, 14).Value = TxtConsumo.Value
End If
</code>


Gratuitous CRLF in Subject: line - why is it there, and is it legal?

Question: I'm running into a problem with a NAGIOS system sending emails to a popular email-to-SMS service.  The email-to-SMS service takes emails with text in the Subject: line, and sends them on to the mobile number encoded in the To: field.  So far so good.  Sadly, sendmail (and postfix before it) seem to be inserting a gratuitous CRLF into the (necessarily long) Subject: line, and that's causing my SMS messages to be truncated at the CRLF if and only if the Subject: line contains one or more colons past the gratuitous CRLF.
I am confident that the messages are being created correctly, but just to be sure, here's me creating a completely noddy test message to myself, with a long Subject: line:
echo "foo" | mail -s "1234567 101234567 201234567 301234567 401234567 501234567 601234567 701234567 801234567 90123456789" email@example.com

Note there's no extra colon in this Subject: line; all I'm doing here is showing that an extra CRLF is inserted on the wire.  Here's the result of sudo ngrep -x port 25:

44 61 74 65 3a 20 46 72    69 2c 20 33 31 20 4d 61    Date: Fri, 31 Ma
79 20 32 30 31 33 20 31    30 3a 34 33 3a 35 35 20    y 2013 10:43:55
2b 30 31 30 30 0d 0a 54    6f 3a 20 72 65 61 70 65    +0100..To: reape
72 40 74 65 61 70 61 72    74 79 2e 6e 65 74 0d 0a    firstname.lastname@example.com..
53 75 62 6a 65 63 74 3a    20 31 32 33 34 35 36 37    Subject: 1234567
20 31 30 31 32 33 34 35    36 37 20 32 30 31 32 33     101234567 20123
34 35 36 37 20 33 30 31    32 33 34 35 36 37 20 34    4567 301234567 4
30 31 32 33 34 35 36 37    20 35 30 31 32 33 34 35    01234567 5012345
36 37 0d 0a 20 36 30 31    32 33 34 35 36 37 20 37    67.. 601234567 7
30 31 32 33 34 35 36 37    20 38 30 31 32 33 34 35    01234567 8012345
36 37 20 39 30 31 32 33    34 35 36 37 38 39 0d 0a    67 90123456789..
55 73 65 72 2d 41 67 65    6e 74 3a 20 48 65 69 72    User-Agent: Heir
6c 6f 6f 6d 20 6d 61 69    6c 78 20 31 32 2e 34 20    loom mailx 12.4
37 2f 32 39 2f 30 38 0d    0a 4d 49 4d 45 2d 56 65    7/29/08..MIME-Ve
72 73 69 6f 6e 3a 20 31    2e 30 0d 0a 43 6f 6e 74    rsion: 1.0..Cont
65 6e 74 2d 54 79 70 65    3a 20 74 65 78 74 2f 70    ent-Type: text/p
6c 61 69 6e 3b 20 63 68    61 72 73 65 74 3d 75 73    lain; charset=us

About half way down (marked in bold+italic), between the 501234567 and the 601234567 in the original Subject: header, you can see a CRLF being inserted (0x0d 0x0a, on the left-hand side hex dump, .. on the right-hand side plain text).
The receiving MTA seems happy to post-process this, and when I look at the on-disc stored mail at the receiving end, I see only a LF (0x0a) in the Subject: line, and the line is parsed correctly and in its entirety by, eg, alpine.  Nevertheless, the CRLF is there on the wire, and between me and the (excellent) email-to-SMS support people, we've established that these are the cause of the problem.
So my question is: is it lawful for an MTA to insert a gratuitous CRLF on the wire?
If it is, and I can prove it, then it's the email-to-SMS house's problem, because they are being intolerant.  If it isn't, or it is but I can't prove it, then it becomes my problem, so an answer with references would be most useful.
Edit: I can now come clean that the email-to-SMS service in question is kapow.  Once this problem was explained to them, they got it, worked with me to develop and test a fix, and have deployed the fix.  My long subject lines with colons in now get relayed correctly into SMSes.  I don't normally trumpet individual companies, especially not on SF, but I thought it worthy of note that kapow Did The Right Thing.  (Disclaimer: I have no connection with kapow except as a paying customer who's happy about the way they dealt with his problem.)
Answer: Well, if I understand RFC 822, they are legal in certain cases, I think it's an artifact from the days of small screens with 24x80 resolutions..
These sections seem to be fairly clear Subjects can be folded, and folding is a CRLF plus LWSP(linear white space) character.. it's possible they've been supeseded, Wietse (on the postfix lists) knows his RFCs inside out if you want a definitive answer.
3.1.1.  LONG HEADER FIELDS

    Each header field can be viewed as a single, logical  line  of
    ASCII  characters,  comprising  a field-name and a field-body.
    For convenience, the field-body  portion  of  this  conceptual
    entity  can be split into a multiple-line representation; this
    is called "folding".  The general rule is that wherever  there
    may  be  linear-white-space  (NOT  simply  LWSP-chars), a CRLF
    immediately followed by AT LEAST one LWSP-char may instead  be
    inserted.  Thus, the single line

        To:  "Joe & J. Harvey" <ddd @Org>, JJV @ BBN

    can be represented as:

        To:  "Joe & J. Harvey" <ddd @ Org>,
                JJV@BBN

    and

        To:  "Joe & J. Harvey"
                        <ddd@ Org>, JJV
         @BBN

    and

        To:  "Joe &
         J. Harvey" <ddd @ Org>, JJV @ BBN

         The process of moving  from  this  folded   multiple-line
    representation  of a header field to its single line represen-
    tation is called "unfolding".  Unfolding  is  accomplished  by
    regarding   CRLF   immediately  followed  by  a  LWSP-char  as
    equivalent to the LWSP-char.

    Note:  While the standard  permits  folding  wherever  linear-
           white-space is permitted, it is recommended that struc-
           tured fields, such as those containing addresses, limit
           folding  to higher-level syntactic breaks.  For address
           fields, it  is  recommended  that  such  folding  occur
           between addresses, after the separating comma.

3.1.2.  STRUCTURE OF HEADER FIELDS

    Once a field has been unfolded, it may be viewed as being com-
    posed of a field-name followed by a colon (":"), followed by a
    field-body, and  terminated  by  a  carriage-return/line-feed.
    The  field-name must be composed of printable ASCII characters
    (i.e., characters that  have  values  between  33.  and  126.,
    decimal, except colon).  The field-body may be composed of any
    ASCII characters, except CR or LF.  (While CR and/or LF may be
    present  in the actual text, they are removed by the action of
    unfolding the field.)

    Certain field-bodies of headers may be  interpreted  according
    to  an  internal  syntax  that some systems may wish to parse.
    These  fields  are  called  "structured   fields".    Examples
    include  fields containing dates and addresses.  Other fields,
    such as "Subject"  and  "Comments",  are  regarded  simply  as
    strings of text.

    Note:  Any field which has a field-body  that  is  defined  as
           other  than  simply <text> is to be treated as a struc-
           tured field.

           Field-names, unstructured field bodies  and  structured
           field bodies each are scanned by their own, independent
           "lexical" analyzers.

 3.1.3.  UNSTRUCTURED FIELD BODIES

    For some fields, such as "Subject" and "Comments",  no  struc-
    turing  is assumed, and they are treated simply as <text>s, as
    in the message body.  Rules of folding apply to these  fields,
    so  that  such  field  bodies  which occupy several lines must
    therefore have the second and successive lines indented by  at
    least one LWSP-char.

Edit by the questioner: I hope NickW will forgive me for adding a note to the effect that RFC822 has been obsoleted by RFC2822, but the new RFC says pretty much the same thing in its section 2.2.3, and explicitly confirms that such folding should be removed before any further processing is done:

Each header field is logically a single line of characters
comprising    the field name, the colon, and the field body.  For
convenience    however, and to deal with the 998/78 character
limitations per line,    the field body portion of a header field can
be split into a multiple    line representation; this is called
"folding".  The general rule is    that wherever this standard allows
for folding white space (not    simply WSP characters), a CRLF may be
inserted before any WSP.  For    example, the header field:
       Subject: This is a test

can be represented as:
       Subject: This
        is a test

Note: Though structured field bodies are defined in such a way that
folding can take place between many of the lexical tokens (and even   within some of the lexical tokens), folding SHOULD be limited to
placing the CRLF at higher-level syntactic breaks.  For instance, if  a field body is defined as comma-separated values, it is recommended  that folding occur after the comma separating the structured items in preference to other places where the field could be folded, even if   it is allowed elsewhere.
The process of moving from this folded multiple-line representation of a header field to its single line representation is called   "unfolding". Unfolding is accomplished by simply removing any CRLF   that is immediately followed by WSP.  Each header field should be   treated in its unfolded form for further syntactic and semantic   evaluation.

This is not to detract from the fact that NickW unerringly pointed me at pretty much exactly what I needed to know, only to help this answer stay relevant for anyone who might stumble across it in the future.
Comment: I'm certainly not offended :)
Answer: Sendmail server (SendMail) imposes SMTP line length limits but it is much higher (990 bytes or more for smtp mailers).
SendMail != SendEmail
As I understand Nagios uses by default SendEmail client to send emails. It seems that email client you make Nagios use imposes such "harsh" limits on length of email header/subject line.
Check and report email client configured in commands.cfg configuration file.
(notify-host-by-email and notify-service-by-email settings).
Comment: I know about the line length issue, and the `L=`/`F=L` parameters, and I agree with you that this isn't the issue.  My NAGIOS is sending just using `echo "" | mail -s "$VARIABLE$ $ANOTHERVAR$`" - but in any case, the issue is more profound than that, which is why I quoted the simple `mail`-based example above - to take NAGIOS out of the picture.


Github Deploy Key Pattern

Question: My Deployment Pattern
I have a setup as shown in the diagram above, where have a github account which owns a number of private repositories. I have a number of machines in the field that each include some subset of the repositories that I manage. Each repository, on each machine, contains a unique RSA keypair tied to a unique deploy key. I individually assign the core.sshCommand for each repo to use the unique key so I can push and pull from the repository as needed.
This works, but it's very labor intensive since every time I deploy a new machine, I have to generate a new key, add the deploy key to the GitHub, and assign it to local repo via core.sshCommand. Is there an easier way of doing this? Because it seems like a really common pattern but GitHub's security policies sort of forced me into what seems like a very inefficient pattern.
Answer: It's not going to be a satisfying solution, but I've decided that since the security policies at GitHub don't allow me to work in the way I need to, I am just going to switch to a hosted server on AWS where I can run my own Git server.

Github Deploy Key Pattern