Need a solution to enter more then 100 PDF (or other) documents to one node

Question: My client wants to be able to enter over 100 PDF and other documents to be downloaded from a single node. There will be several nodes like this each with their own linked files. Most of these are going to be less then 50, but there is a use case for over 100.
Right now they are using a field collection, as the nodes need to be restricted to area, have English and French description fields, and be able to be deactive.
The display of the nodes is ok, its the editing of the node. They are currently using field collections to gather the meta and file information. Then you hit a button to add another item and AJAX fires. It saves the node revision data for the file uploads and creates the next entry entity.  Once you get over 70 or so, IE pushes the returned JSON info out as a file for download.
This has to work in IE, as there are other systems the client uses that will only work in IE, and this can not be changed.
I have considered the media browser, but there are limits to that the client does not want.
Answer: Without having all of the context here, my initial recommendation would be to consider integrating with a Digital Asset Manager (DAM), where your client can manage their documents much more efficiently, and select/attach which documents are part of individual nodes/entities.
In addition, most DAM solutions will serve your assets for you, so you are able to preserve disk space on the web application machine, while ensuring images are available and served up quickly via the DAM's CDN.
Comment: Also one issue with using just file fields (which it sounds like above) is that the node owns the files, instead of the node referencing media items which own the files.


How can I improve the performance of my Julia program for excellent numbers?

Question: I've been playing with some Perl programs to calculate excellent numbers. Although the runtimes for my solutions were acceptable, I thought a different language, especially one designed for numeric stuff, might be faster. A friend suggested Julia, but the performance I'm seeing is so bad I must be doing something wrong. I've looked through the Performance Tips and don't see what I should improve:
digits = int( ARGS[1] )

const k = div( digits, 2 )

for a = ( 10 ^ (k - 1) ) : ( 10 ^ (k) - 1 )
    front = a * (10 ^ k + a)

    root = floor( front ^ 0.5 )

    for b = ( root - 1 ): ( root + 1 )
        back = b * (b - 1);
        if back > front
            break
        end
        if log(10,b) > k
            continue
        end
        if front == back
            @printf "%d%d\n" a b
        end
    end
 end

I have an equivalent C program that's an order of magnitude faster instead of the factor of 2 noted on the Julia page (although most of the Stackoverflow questions about Julia's speed seem to point out flawed benchmarks from that page):
And the non-optimized pure Perl I wrote takes half as long:
use v5.20;

my $digits = $ARGV[0] // 2;
die "Number of digits must be even and non-zero! You said [$digits]\n"
    unless( $digits > 0 and $digits % 2 == 0 and int($digits) eq $digits );

my $k  = ( $digits / 2 );

foreach my $n ( 10**($k-1) .. 10**($k) - 1 ) {
    my $front = $n*(10**$k + $n);
    my $root = int( sqrt( $front ) );

    foreach my $try ( $root - 2 .. $root + 2 ) {
        my $back = $try * ($try - 1);
        last if length($try) > $k;
        last if $back > $front;
        # say "\tn: $n back: $back try: $try front: $front";
        if( $back == $front ) {
            say "$n$try";
            last;
            }
        }
    }

I'm using the pre-compiled Julia for Mac OS X since I couldn't get the source to compile (but I didn't try beyond it blowing up the first time). I figure that's part of it.
Also, I see about a 0.7 second start up time for any Julia program (see Slow Julia Startup Time), which means the equivalent compiled C program can run about 200 times before Julia finishes once. As the runtime increases (bigger values of digits) and the startup time means less, my Julia program is still really slow.
I haven't gotten to the part for very large numbers (20+ digit excellent numbers) which I didn't realize Julia doesn't handle those any better than most other languages.

Here's my C code, which is a little different from when I started this. My rusty, inelegant C skills are essentially the same thing as my Perl.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] ) {
    long
        k, digits,
        start, end,
        a, b,
        front, back,
        root
        ;

    digits = atoi( argv[1] );

    k = digits / 2;

    start = (long) pow(10, k - 1);
    end   = (long) pow(10, k);

    for( a = start; a < end; a++ ) {
        front = (long) a * ( pow(10,k) + a );
        root  = (long) floor( sqrt( front ) );

        for( b = root - 1; b <= root + 1; b++ ) {
            back = (long) b * ( b - 1 );
            if( back > front )  { break; }
            if( log10(b) > k ) { continue; }
            if( front == back ) {
                printf( "%ld%ld\n", a, b );
                }
            }
        }

    return 0;
    }

Comment: `I didn't see any speed-up by wrapping the code in a function` -that is odd. Moving from global to local scope provided a big speed-up for me. You would need to provide more detail on exactly how you are running your code to go further here (perhaps you are already in local scope)... `I guess the answer is that Julia is slow` -that is a very broad conclusion to draw from one very specific example on a language that is in beta. I'm sure you didn't mean it that way, but it comes across as inflammatory.
Comment: You should include your actual benchmark timings, and some description of how you obtained them.
Comment: Also, wrapping your code in a function as suggested by @VincentZoonekynd gives a four factor speed-up on my machine. Not quite the performance you're after, but getting there.
Comment: Huh... What do you know? Slow run-time of the log function in Julia is [issue #8869](https://github.com/JuliaLang/julia/issues/8869) on github. So I guess what you might be seeing here is simply some of the wrinkles that will hopefully be ironed out by v1.0.
Comment: The standard library is pre-compiled in v0.3, but nothing else, hence the 0.7 second start up time. It looks like we're going to get compilation of packages in v0.4 - apparently it is already possible if you want to play around a bit (see [here](https://groups.google.com/forum/#!topic/julia-dev/qdnggTuIp9s)). So in other words, slowly but surely the obstacles to reducing start-up time are being knocked over one-by-one.
Comment: Also also, out of curiosity, I had a quick look at the functional form using ProfileView. A disproportionate (to me) quantity of run-time on my machine is spent on `log(10, b)`. If `b` is always positive, there may be a macro for skipping the domain check in the `log` function, although I wouldn't have thought this would make a huge difference. Not an answer, but this might point you in the right direction for further reducing run-time
Comment: @ColinTBowers I guess the answer is that Julia is slow. I didn't see any speed-up by wrapping the code in a function.
Answer: I've benchmarked your code (brian.jl) against the following code, which attempts to make minimal changes to your code and follows Julian style:
function excellent(digits)
    k = div(digits, 2)
    l = 10 ^ (k - 1)
    u = (10 ^ k) - 1

    for a in l:u
        front = a * (10 ^ k + a)
        root = isqrt(front)
        for b = (root - 1):(root + 1)
            back = b * (b - 1)
            back > front && break
            log10(b) > k && continue
            front == back && println(a,b)
        end
    end
end
excellent(int(ARGS[1]))

Separating out u and l was a personal preference for readability. As a baseline, the Julia startup time on my machine is:
$ time julia -e ''
real    0m0.248s
user    0m0.306s
sys 0m0.091s

So if the computation you are running per execution of Julia from a cold start is on the order of 0.3 seconds, then Julia might not be a great choice for you at this stage. I passed in 16 to the scripts, and got:
$ time julia brian.jl 16
1045751633986928
1140820035650625
3333333466666668

real    0m15.973s
user    0m15.691s
sys     0m0.586s

and
$ time julia iain.jl 16
1045751633986928
1140820035650625
3333333466666668

real    0m9.691s
user    0m9.839s
sys     0m0.155s

A limitation of this code as written is that if digits>=20 we will exceed the storage of a Int64. Julia, for performance reasons, doesn't auto-promote integer types to arbitrary precision integers. We can use our knowledge of the problem to address this by changing the last line to:
digits = int(ARGS[1])
excellent(digits >= 20 ? BigInt(digits) : digits)

We get the BigInt version of excellent for free, which is nice. Ignoring that for now, on profiling my version I found that ~74% of the time is spent calculating log10, following by ~19% on isqrt. I did this profiling by replacing the last line with
excellent(4)  # Warm up to avoid effects of JIT
@profile excellent(int(ARGS[1]))
Profile.print()

Now if we wanted to dabble in minor algorithmic changes, given what we know now from the profiler, we can replace the log10 line (which is just checking the number of digits in effect) with ndigits(b) > k && continue, which gives us
$ time julia iain.jl 16
1045751633986928
1140820035650625
3333333466666668

real    0m3.634s
user    0m3.785s
sys     0m0.153s

This changes the balance to about ~56% from the isqrt and ~28% from ndigits. Digging further into that 56%, about half is spent executing this line which seems like a pretty sensible algorithm, so any improvement would probably change the spirit of the comparison as it'd really be a different approach altogether. Investigating the machine code with @code_native tends to suggest there is nothing else too strange going on, although I didn't dig deep into this.
If I allow myself to engage in some more minor algorithmic improvements, I can start from root+1 and only doing the ndigits check once, i.e.
for a in l:u
    front = a * (10^k + a)
    root = isqrt(front)
    b = root + 1
    ndigits(b) > k && continue
    front == b*(b-1) && println(a,b)
    b = root
    front == b*(b-1) && println(a,b)
    b = root - 1
    front == b*(b-1) && println(a,b)
end

which gets me down to
real    0m2.901s
user    0m3.050s
sys     0m0.154s

(I'm not convinced the second two equality checks are needed, but I'm trying to minimize differences!). Finally I thought I'd eke out some extra speed by precomputing 10^k, i.e. k10 = 10^k, which seems to be computed freshly each iteration. With that, I get to
real    0m2.518s
user    0m2.670s
sys     0m0.153s

Which is a fairly nice 20x improvement over the original code.
Comment: We can have the extra precision and wait days to see an answer, but that's not unique to Julia. :)
Comment: I used the in-built profiler - I'll update the answer.
Answer: I was curious about how Perl was getting such good performance from this code, so I felt I ought to do a comparison. Since there are some seemingly needless differences in both control flow and operations between the Perl and Julia versions of the code in the question, I ported each version to the other language and compared all four. I also wrote a fifth Julia version using more idiomatic numerical functions but with the same control flow structure as the question's Perl version.
The first variant is essentially the Perl code from the question, but wrapped up in a function:
sub perl1 {
    my $k = $_[0];
    foreach my $n (10**($k-1) .. 10**($k)-1) {
        my $front = $n * (10**$k + $n);
        my $root = int(sqrt($front));

        foreach my $t ($root-2 .. $root+2) {
            my $back = $t * ($t - 1);
            last if length($t) > $k;
            last if $back > $front;
            if ($back == $front) {
                print STDERR "$n$t\n";
                last;
            }
        }
    }
}

Next, I translated this to Julia, keeping the same control flow and using the same operations – it takes the integer floor of the square root of front in the outer loop and takes the length of the "stringification" of t in the inner loop:
function julia1(k)
    for n = 10^(k-1):10^k-1
        front = n*(10^k + n)
        root = floor(Int,sqrt(front))

        for t = root-2:root+2
            back = t * (t - 1)
            length(string(t)) > k && break
            back > front && break
            if back == front
                println(STDERR,n,t)
                break
            end
        end
    end
end

Here's the question's Julia code with some minor formatting tweaks, wrapped up in a function:
function julia2(k)
    for a = 10^(k-1):10^k-1
        front = a * (10^k + a)
        root = floor(front^0.5)

        for b = root-1:root+1
            back = b * (b - 1);
            back > front && break
            log(10,b) > k && continue
            if front == back
                @printf STDERR "%d%d\n" a b
                # missing break?
            end
        end
    end
end

I translated this back to Perl, keeping the same control flow structure and using the same operations as the Perl code – taking floor of root raised to the 0.5 power in the outer loop, and taking the logarithm base 10 in the inner loop:
sub perl2 {
    my $k = $_[0];
    foreach my $a (10**($k-1) .. 10**($k)-1) {
        my $front = $a * (10**$k + $a);
        my $root = int($front**0.5);

        foreach my $b ($root-1 .. $root+1) {
            my $back = $b * ($b - 1);
            last if $back > $front;
            next if log($b)/log(10) > $k;
            if ($front == $back) {
                print STDERR "$a$b\n"
            }
        }
    }
}

Finally, I wrote a Julia version that has the same control flow structure as the question's Perl version but uses more idiomatic numerical operations – the isqrt and ndigits functions:
function julia3(k)
    for n = 10^(k-1):10^k-1
        front = n*(10^k + n)
        root = isqrt(front)

        for t = root-2:root+2
            back = t * (t - 1)
            ndigits(t) > k && break
            back > front && break
            if back == front
                println(STDERR,n,t)
                break
            end
        end
    end
end

As far as I know (I used to do a lot of Perl programming, but it's been a while), there aren't Perl versions of either of these operations, so there's no corresponding perl3 variant.
I ran all five variations with Perl 5.18.2 and Julia 0.3.9, respectively, ten times each for 2, 4, 6, 8, 10, 12 and 14 digits. Here are the timing results:

The x axis is the number of digits requested. The y axis is median time in seconds required to compute each function. The y axis is plotted on a log scale (there's some rendering bug in the Cairo backend of Gadfly, so the superscripts don't appear very raised). We can see that except for the very smallest number of digits (2), all three Julia variants are faster than both Perl variants – and julia3 is substantially faster than everything else. How much faster? Here's a comparison of the other four variants relative to julia3 (not log scale):

The x axis is the number of digits requested again, while the y axis is how many times slower each variant was than julia3. As you can see here, I was unable to reproduce the Perl performance claimed in the question – the Perl code was not 2x faster than Julia – it was 7 to 40 times slower than julia3 and at least 2x slower than the slowest Julia variant for any non-trivial number of digits. I didn't test with Perl 5.20 – perhaps someone could follow up by running these benchmarks with a newer Perl and see if that explains the different results? Code to run the benchmarks can be found here: excellent.pl, excellent.jl. I ran the them like this:
cat /dev/null >excellent.csv
for d in 2 4 6 8 10 12 14; do
    perl excellent.pl $d >>excellent.csv
    julia excellent.jl $d >>excellent.csv
done

I analyzed the resulting excellent.csv file using this Julia script.
Finally, as has been mentioned in the comments, using BigInt or Int128 is an option for exploring larger excellent numbers in Julia. However, this requires a little care for writing the algorithm generically. Here's a fourth variation that works generically:
function julia4(k)
    ten = oftype(k,10)
    for n = ten^(k-1):ten^k-1
        front = n*(ten^k + n)
        root = isqrt(front)

        for t = root-2:root+2
            back = t * (t - 1)
            ndigits(t) > k && break
            back > front && break
            if back == front
                println(STDERR,n,t)
                break
            end
        end
    end
end

This is the same as julia3 but works for generic integer types by converting 10 to the type of its argument. Since the algorithm scales exponentially, however, it still takes a very long time to compute for any number of digits much larger than 14:
julia> @time julia4(int128(10)) # digits = 20
21733880705143685100
22847252005297850625
23037747345324014028
23921499005444619376
24981063345587629068
26396551105776186476
31698125906461101900
33333333346666666668
34683468346834683468
35020266906876369525
36160444847016852753
36412684107047802476
46399675808241903600
46401324208242096401
48179452108449381525
elapsed time: 2260.27479767 seconds (5144 bytes allocated)

It works, but 37 minutes is kind of a long time to wait. Using a faster programming language only gets you a constant factor speedup – 40x in this case – but that only buys a couple of extra digits. To really explore larger excellent numbers, you'll need to look into better algorithms.
Comment: @briandfoy – you wrote "the non-optimized pure Perl I wrote takes half as long". What was the comparison to if not the Julia version?
Comment: This is a great comparison.  Nicely done. That said, I believe all of @briandfoy's performance issues stemmed from timing the Julia code externally as a standalone script, which includes startup and compilation time.  Julia is in this strange middle-ground; you wouldn't include compilation time in a C benchmark, but since we don't support caching or outputting compiled binaries yet it's not entirely unreasonable to include it for Julia.
Comment: Yeah, the Perl and Julia versions in the question are pretty different. That's why I ported them both ways and did the multiway comparison.
Comment: The comparison to C would also be interesting. I would expect that calling the same functions in Julia as called in C would produce the same performance. The `julia3` variant, which is 40x faster than Perl is in the right ballpark. If you post the C code as well, we could add that to these benchmarks.
Comment: Well, to be fair I think the performance of log() has a lot to do with it, and I was using some functions that had to do implicit conversions. I posted my C code, which is a straight port from my Perl.
Comment: I just realized the inner loop varies between `root-1:root+1` and `root-2:root+2` between versions in the OP and here - I guess it didn't matter for me because I wasn't trying to compare against the Perl version.
Comment: I didn't make any claims about Perl being faster. I said my C was much faster than the Julia webpage would have me believe.
Answer: I get a big speedup when I use ifloor (which isn't listed in Mathematical Operations and Elementary Functions) instead of floor. Getting rid of either floor in favor of isqrt shows the same speedup. I don't see where that is documented either.
Now I see performance that I would expect, although on my Mac, it looks like Julia couldn't start k = 10. BigInt can help that but then the performance is rotten. Part of the reason I looked at Julia was my hope that it could easily handle bigger numbers, so I'll have to keep looking at that.
The rest of the expected speed might be hidden in the implementation of the logarithm algorithms, as Colin noted in the comments.
I had fun checking out this language, and maybe I'll try again when it's mature.
Comment: [`ifloor`](http://julia.readthedocs.org/en/release-0.3/stdlib/math/#Base.ifloor) is in the 0.3 docs (current release), but has been deprecated in the development version (which are the docs you're seeing) in favour of `floor(Int,x)`
Comment: Final thought: You could likely get further optimisations from the [julia-users](https://groups.google.com/forum/#!forum/julia-users) group. The core devs regularly monitor the threads, and questions about performance are taken very seriously...
Comment: [Here is the 0.3 manual](http://julia.readthedocs.org/en/release-0.3/manual/mathematical-operations/)
Answer: You can try to to put your code in a function.
function excellent(k)
  for a = ( 10 ^ (k - 1) ) : ( 10 ^ (k) - 1 )
    front = a * (10 ^ k + a)
    root = ifloor( sqrt(front) ) # floor() returns a double

    for b = ( root - 1 ): ( root + 1 )
      back = b * (b - 1);
      if back > front
        break
      end
      if log(10,b) > k
        continue
      end
      if front == back
        @printf "%d%d\n" a b
      end
   end
  end
end

@time excellent(7)
## 33333346666668
## 48484848484848
## elapsed time: 1.451842881 seconds (14680 bytes allocated)

For arbitrary-precision numbers, you can use BigInt (e.g., ten = BigInt("10"), but the performance drops...
Comment: @briandfoy `isqrt` might help with that step
Comment: I removed the command-line argument part of your program because I could see no obvious improvement to make to it.
The argument of the function is `k`, which is half the number of digits:
7 corresponds to 14 digits, for which your Perl program took 15 seconds on my machine.
The `DomainError` is caused by integer overflow: `front` becomes negative, and the square root fails.
For `k>9`, you could use longer integers: `Int128` is only 3 times slower and will allow twice as many digits.
Comment: I tried putting the code in a function. There was no difference in time. 1.45 seconds is very, very slow.
Comment: This code doesn't work for me with k > 8. I get a DomainError.
Comment: This also doesn't take the number of digits from the command line, which is a very useful part of the program.
Comment: The `ifloor` is much faster.


Função de retorno do próximo caractere ASCII em C

Question:
Faça uma função: strShift() que recebe uma cadeia de caracteres com
  letras do alfabeto e retorna uma nova cadeia com as letras
  substituídas por seus sucessores na tabela ASCII. Por exemplo, "Ana"
  retorna "Bob" e "zaZA" retorna "{b[B".
A função deve retornar NULL se não houver memória disponível.

Eu fiz:
char* strShift(char *s) {
    int i;
    int tam = strlen(s);
    char* nova = (char*)malloc((tam + 1) * sizeof(char));
    if (nova == NULL)
        return NULL;
    for (i = 0; i < tam; i++) {
        nova = *(s + i + 1) ;
    }
    nova = '\0';
    return nova;
}

Não consigo entender mais o que fazer, onde estou errando?
A saída me dá um monte de pontos de exclamação.
Answer: Tem vários problema no código. Eu não gosto da ideia de alocar memória só para isso, poderia alterar direto no objeto já existente. Mas se o exercício dede isso vamos fazer. Lembrando que se fosse mais que um exercício sem um free() vazaria memória.
Tirei as partes irrelevantes do código (provavelmente está aprendendo com material antigo.
O acesso ao conteúdo está confuso e mais complicado do que deveria ser, é só acessar como se fosse um array, assim evita problemas, acabou misturando endereço com o conteúdo e fez tudo uma coisa só, separando os conceitos de forma mais clara fica mais fácil acertar. Faça o simples primeiro, use a sintaxe fácil.
Em alguns pontos deveria acessar o elementos da string e não colocou índice algum para isso então automaticamente o índice é o 0, e aí quando colocou o terminador no lugar errado já melou o texto.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *strShift(char *s) {
    int tam = strlen(s);
    char *nova = malloc(tam + 1);
    if (nova == NULL) return NULL;
    for (int i = 0; i < tam; i++) nova[i] = s[i] + 1;
    nova[tam] = '\0';
    return nova;
}

int main(void) {
    printf("%s", strShift("anaz"));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Amigo, perdão. Eu esqueci de mencionar algumas outras características que o exercício pedia. Como por exemplo o uso de aritmética de ponteiros, falha minha. Entretanto, já consegui aqui resolver com o que vc respondeu. Muito obrigado e grande abraço!


How do I use gpg --pinentry-mode loopback in a bash script?

Question: When decrypting a file, if I use any method other than --pinentry-mode loopback I get the following error.
gpg: public key decryption failed: Permission denied
gpg: decryption failed: No secret key

I would like to decrypt the pgp file using a bash script but pinentry-mode requires user input. Is there a way to use --pinentry-mode loopback in a bash script without requiring manual user input?
Comment: I voted to move this question to superuser.com. Because this question has nothing to do with software development.
Comment: @Cyrus Genuine question. Is writing bash scripts not considered development?
Answer: Yes, but the solution posted below is not secure since the passphrase will be in plaintext. You can use --pinentry-mode loopback in a bash script by combining it with --passphrase-fd 0 which tells gpg to expect the passphrase from STDIN.
echo "yourpassphrase" | gpg --passphrase-fd 0 --pinentry-mode loopback --output somefile.txt --decrypt somefile.txt.gpg

To make this more secure you would need to acquire your passphrase by a more secure means like retrieving it from a secret management system (HashiCorp Vault or similar).
Comment: The rub is `echo "yourpassphrase"` means it will be part of the shell environment and potentially able to be compromised on a multi-user system. (not to mention likely permanently part of the `history` file). Though not the crux of the question, a necessary consideration.


Wanted to get notified when somebody deletes my filter

Question: I have WFP driver where I am filtering network events, added filer using FwpmFilterAdd, but someone/an application may delete my filter using FwpmFilterDeleteByKey0. I want to get notification on my filter deletion.
Can it be done?
I can see there is API for user mode tracking FwpmFilterSubscribeChanges0 but did not find for kernel mode
Answer: After too much msdn research, I found FWPS_CALLOUT0_ member NotifyFN helps us to get filter add/delete notifications.


I want to create a dropdown filter for my post categories on Index page using an enum in ASP.NET MVC

Question: I am creating a recipe blog website. While creating post, I have option to categorize them into Veg and NonVeg posts using an Enum dropdown. The posts are displayed as cards on index page. I want to create a dropdown filter on index page to display only the selected category.
Enum:
public enum PostCategory
{
    [Display(Name = "Veg")]
    Veg = 0,

    [Display(Name = "NonVeg")]
    NonVeg = 1
}

Model:
public class Post
{
    // Post
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string? Link { get; set; }
    public string? Ingredient { get; set; }
    public string Recipe { get; set; }
    public string Image { get; set; }

    // Category
    public PostCategory PostCategory { get; set; }
}

Controller:
// Index
[HttpGet]
public async Task<IActionResult> Index()
{
    IEnumerable<Post> posts = await _postInterface.GetAll();
    return View(posts);
}

// Search Bar
[HttpPost]
public async Task<IActionResult> Index(string searchString, PostCategory postCategory)
{
    var posts = from p in _context.Posts select p;

    if (!string.IsNullOrEmpty(searchString))
    {
        posts = posts.Where(t => t.Title!.Contains(searchString));
    }

    return View(await posts.ToListAsync());
}

// Category Filter goes here.

View:

        <form class="d-flex mb-2" role="search" asp-controller="Post" asp-action="Index">
            <input class="form-control me-2" type="search" placeholder="Search Posts" aria-label="Search" name="SearchString" required oninvalid="this.setCustomValidity(' ')" />
            <button class="btn btn-outline-success me-2" type="submit">Search</button>
            Reset
        </form>

        <form  asp-controller="Post" asp-action="Index" id="category">
            <select class="form-control" asp-items="@Html.GetEnumSelectList<PostCategory>()" id="post-filter">
                <option value="">All</option>
            </select>
            <button class="btn btn-outline-success me-2" type="submit">Search</button>
            Reset
        </form>

            @foreach (var item in Model)
            {

                        @* Card Details *@

 @item.Title

                                @item.PostCategory

                        @* Admin privlages *@

                            Edit
                            Delete

            }

I have tried using adding additional [HttpPost] action in Index for it to only crash route with searchbar action. Combining it with searchbar action helps, as there is no Route crash, but even then, the code is only half complete, not giving the expected results, only showing veg category.
Here is what I have tried:
// Enum Category
[HttpPost]
public IActionResult Index(PostCategory postCategory)
{
    var posts = _context.Posts.Where(c => c.PostCategory == postCategory).ToList();
    return View(posts);
}

Thank you!
Answer:
the code is only half complete, not giving the expected results, only
showing veg category

You failed model-binding and PostCategory enum has the default value 0(Veg)
Add the name property to your dropdownlist for model-binding,
<select class="form-control" asp-items="@Html.GetEnumSelectList<PostCategory>()" name="postCategory" id="post-filter">
    <option value="">All</option>
</select>

also,modify your controller,add the codes for when you select all :
[HttpPost]
public IActionResult Index(PostCategory? postCategory)
{
    List<Post> posts;
    if(postCategory!=null)
    {
         posts = _context.Post.Where(c => c.PostCategory == postCategory).ToList();

    }
    else
    {
        //wheather you don't select or select all,postCategory would be null
        //you could replace the logic here yourself
        posts = _context.Post.ToList();

    }
    return View(posts);
}

Result:
Answer: This is the final code I have got that works.

// Filter
[HttpPost]
public async Task<IActionResult> Index(string searchString, PostCategory? postCategory)
{
    var post = from p in _context.Posts select p;

    // Searchbar
    if (!string.IsNullOrEmpty(searchString))
    {
        post = post.Where(t => t.Title!.Contains(searchString));
    }

    // Category Dropdown
    if (postCategory != null)
    {
        post = _context.Posts.Where(c => c.PostCategory == postCategory);
    }

    return View(await post.ToListAsync());
}


Invoking Drupal core tests from within a custom module .test script

Question: I am writing a simpletest test script, where I would like to enable my module, and then invoke a Drupal core test to ensure that my module is producing core-compliant results (in particular, I render a pager alternative to core's, and would make sure that, at its minimal setup, is equal to core's one).
Is there a way to do that?
Thanks for help
mondrake
Answer: So... I found a solution that's working, at least for my case.
It has to do with the fact that test cases are actually PHP classes that can be extended. So I tried to leverage inheritance, with a caveat...
I want to run a test on the pager, Drupal 7, after I have enabled a module that replaces the core pager.
The core pager test class is defined as
class PagerFunctionalWebTestCase extends DrupalWebTestCase {

now, my problem was that the core test would not be caring about my module to be loaded before running the tests.
I created my module test class as an extension of the core one, like
class MyPagerTest extends PagerFunctionalWebTestCase {

This is OK, but the point is that if I call parent::setUp() at this stage, the core setup will be run and I will still miss my module from loading before the actual test.
So the caveat is that instead of calling parent::setUp, I will call directly the 'ancestor' DrupalWebtestCase::setUp function, with my setup, and skip the call to parent.
Like this:
...

public function setUp() {
  // Enable required modules.
  $modules = array(
    'dblog',
    'mypager',
  );
  DrupalWebTestCase::setUp($modules);

  // Insert 300 log messages.
  for ($i = 0; $i < 300; $i++) {
    watchdog('pager_test', $this->randomString(), NULL, WATCHDOG_DEBUG);
  }

  $this->admin_user = $this->drupalCreateUser(array(
    'access site reports',
  ));
  $this->drupalLogin($this->admin_user);

}

....

That's all - class inheritance will do the magic and bring the rest of the test functions in.
Anybody sees other options?


Get Inserted id in register.php in WHMCS

Question: I want to add custom registeration field in tblclient. In whmcs here all code works dynamically and logic related files are encrypted so after registration I want to get last inserted id in  hook so that I can update the field with my custom record. Can anyone know the how it can be done.
Sorry all codes are encrypted by default by whmcs so I cant paste it.
For my efforts I know I have to create a hook in hooks folder.
Any help will be appreciated.
Comment: add some codes ..then only somebody can helps you
Comment: @DreamHunter I cant as all logic related codes are encoded. :( I only know that we can use hook, once client registers it.
Answer: You would need to use the ClientAreaRegister hook, it provides you with the ID of the newly created client.  https://developers.whmcs.com/hooks-reference/client-area-interface/#clientarearegister
If you need info on how to actually use that you'll have to look through the WHMCS docs on hooks https://developers.whmcs.com/hooks/


Binary WebSockets in Flash

Question: Is it possible to send binary (blob) data down a WebSocket equivalent in Flash?
I've heard that you can hijack an XMLSocket for text-based messaging. Is it possible to do this for binary types?
Any resources much appreciated! Thanks.
Comment: Yes, have a look at the [Socket](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html) class.
Answer: As pointed out by Sunil in his comment, instead of using an XMLSocket you can use a Socket:
From http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html:

The Socket class enables code to establish Transport Control Protocol
  (TCP) socket connections for sending and receiving binary data.
The Socket class is useful for working with servers that use binary
  protocols.
To use the methods of the Socket class, first use the constructor,
  new Socket, to create a Socket object.

It looks like someone has taken advantage of this to create a complete WebSocket equivalent in AS3: https://github.com/Worlize/AS3WebSocket (which supports both text and binary data, I believe).

Binary WebSockets in Flash


How does this proof show that this conjugate group is a subgroup of $\pi_1(X, x_1)$?

Question: I'm self learning Rotman's Algebraic Topology and I've come across the proof in the below picture.
I don't understand how the proof shows that $S=p_*\pi_1(\tilde X, \tilde x_1)$.  The proof initially starts with conjugate groups and then uses the commutative diagram to show the equality.  But I don't understand what the link is here between the graphs being conjugate and the commutativity of the diagram.
It seems like it skips a step relating the two.  It constructs a path in $\tilde X$ from $\tilde x_0$ to $\tilde x_1$ and then immediately starts the line $S = \dots$
What is the link between the constructed path, the conjugate groups, and the commutative diagram?  (The figure at the bottom of the image is the diagram used in the proof)
Comment: Well, I think that $\sigma(x)=[\lambda^{-1}]x[\lambda]$ is the canonical isomorphism and since $S=[\lambda^{-1}]H[\lambda]$ then $S=\sigma(H)$. That's where the first equality "$S=\ldots$" comes from. The second one comes from the commutative diagram (it would be easier if we knew what Theorem 10.10 says) since $\sigma p_{*}=p_{*}\Sigma$.
Answer: I feel this a good example where one uses the algebraic model of a covering map in terms of a covering morphism $q: H \to G$ of groupoids.
Certainly if $p: \widetilde{X} \to X$ is a covering map of spaces then the induced morphism $\pi_1(p)$ of fundamental groupoids is a covering morphism. The definition of covering morphism $q: H \to G$ is that if $y \in Ob(H)$ and $g: p(y) \to x $ in $G$ then there is a unique $h: y \to z$ in $H$ such that
$q(h) = g$.
The full details are in Chapter 10 of Topology and Groupoids, (T&G, downloadable),  as they were in previous differently titled editions (1968, 1988). Peter May's "Concise ..." book also has some information on covering morphisms of groupoids. The simplification of notation,  replacing $\pi_1(X,x)$ by the object group $G(x)$, should also make it easier to write down the necessary arguments.
The relation of covering morphisms to actions of groupoids on sets is given in this stackexchange answer, and also in T&G. The notion of covering morphism of groupoids is also a special case of the useful notion of fibration of groupoids.


Estou com o seguinte erro no meu código "Illegal modifier for the local class Ponto; only abstract or final is permitted code: 16777522"

Question: Não manjo muito de Java e tenho um trabalho da facul para entregar, e só preciso alinhar este código.
public class Main {

public static void main(String[] args) {

    public class Ponto {
        private double x, y;

        public Ponto() {
            x = 0;
            y = 0;
        }

        public Ponto(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public void mover(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public double getX() {
            return x;
        }

        public double getY() {
            return y;
        }

        public double distancia() {
            double distancia;
            distancia = (double) Math.sqrt(x * x + y * y);
            return distancia;
        }

        public String toString() {
            return "Ponto (" + x + "," + y + ")";
        }
    }
}

}
Comment: Talvez manter a classe `Ponto` restrita ao escopo da função `main` não seja o que pretendia fazer, pode o ser mais interessante mover a declaração da classe `Ponto` para fora da declaração da classe `Main`, veja https://ideone.com/LrwAi4
Comment: Você declarou a classe `Ponto` dentro da função `main()` então o modificador de acesso `public` nesse caso é redundante pois fazendo assim a classe existe apenas dentro do escopo da função `main()`. Para fazer o código funcionar apenas remova o modificador de acesso, veja https://ideone.com/lLxdbm
Answer: Testando aqui não encontrei nenhum erro de sintaxe no seu código, porém acredito ser incomum criar uma classe dentro da Main.
O que fiz para o código funcionar foi apenas criar uma classe Ponto.java e utilizá-la na Main.java trazendo o valor de x apenas para testar.
Segue os códigos presentes em cada arquivo para consulta:
Ponto.java
public class Ponto {
  private double x, y;

  public Ponto() {
      x = 0;
      y = 0;
  }

  public Ponto(double x, double y) {
      this.x = x;
      this.y = y;
  }

  public void mover(double x, double y) {
      this.x = x;
      this.y = y;
  }

  public double getX() {
      return x;
  }

  public double getY() {
      return y;
  }

  public double distancia() {
      double distancia;
      distancia = (double) Math.sqrt(x * x + y * y);
      return distancia;
  }

  public String toString() {
      return "Ponto (" + x + "," + y + ")";
    }
}

Main.java
public class Main {

  public static void main(String[] args) {
    Ponto ponto = new Ponto();
    System.out.println(ponto.getX());
  }
}


How to resolve this Kaldi ASR MFCC feature Extraction

Question: I am facing some issue related to Kaldi Feature extraction. I am new to Kaldi, please help me out.
OS: Ubuntu 18.04
I am currently trying to extract MFCC features and get VAD from the speech,when I am running the file  mfcc.sh
 #!/bin/bash
#cd ./allWavFiles/
kaldi_path=~/kaldi
featbin_path=$kaldi_path/src/featbin
ivectorbin_path=$kaldi_path/src/ivectorbin
folder=~/Downloads/

find ./ -iname "*.wav" > files
sed -e 's/.wav//g;s/Audio//g;s/\///g;s/\.//g' files > unique
paste unique files | sed 's/\t/ /g' > wav.scp
mkdir mfcc;
mkdir vad;
count=`ls Audio | wc -l`

for i in `seq 1 $count`;
do
cat wav.scp | head -n $i | tail -1 > wav_1.scp
    name=`cat wav_1.scp | cut -d " "  -f1`
    name=$name'.txt';
#Computing mfccs and copying to archive
$featbin_path/compute-mfcc-feats --frame-length=20 scp,p:wav_1.scp ark:- | $featbin_path/copy-feats --compress=true ark:- ark,scp:test.ark,feats.scp
$featbin_path/add-deltas ark:test.ark ark,scp:test_delta.ark,feats_delta.scp
$ivectorbin_path/compute-vad scp:feats_delta.scp ark,t:vad/$name
$featbin_path/compute-cmvn-stats scp:feats_delta.scp ark,scp:cmvn.ark,cmvn.scp
$featbin_path/apply-cmvn scp:cmvn.scp scp:feats_delta.scp ark,t:mfcc/$name
sed -i '1d' mfcc/$name
sed -i "s/\]//g" mfcc/$name
sed -i 's/.*\[\([^]]*\)\].*/\1/g' vad/$name
done

rm -r files unique wav.scp wav_1.scp feats.scp test.ark test_delta.ark feats_delta.scp cmvn.scp cmvn.ark

#Readable archive
#$path/copy-feats ark:test.ark ark,t:mytext.arkco

and I am getting this error
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/compute-mfcc-feats: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/copy-feats: No such file or directory
./mfcc.sh: line 22: /home/navaneeth/kaldi/src/featbin/add-deltas: No such file or directory
./mfcc.sh: line 23: /home/navaneeth/kaldi/src/ivectorbin/compute-vad: No such file or directory
./mfcc.sh: line 24: /home/navaneeth/kaldi/src/featbin/compute-cmvn-stats: No such file or directory
./mfcc.sh: line 25: /home/navaneeth/kaldi/src/featbin/apply-cmvn: No such file or directory
sed: can't read mfcc/5.txt: No such file or directory
sed: can't read mfcc/5.txt: No such file or directory
sed: can't read vad/5.txt: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/compute-mfcc-feats: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/copy-feats: No such file or  directory
./mfcc.sh: line 22: /home/navaneeth/kaldi/src/featbin/add-deltas: No such file or directory
./mfcc.sh: line 23: /home/navaneeth/kaldi/src/ivectorbin/compute-vad: No such file or directory
./mfcc.sh: line 24: /home/navaneeth/kaldi/src/featbin/compute-cmvn-stats: No such file or directory
./mfcc.sh: line 25: /home/navaneeth/kaldi/src/featbin/apply-cmvn: No such file or directory
sed: can't read mfcc/4.txt: No such file or directory
sed: can't read mfcc/4.txt: No such file or directory
sed: can't read vad/4.txt: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/copy-feats: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/compute-mfcc-feats: No such file or directory
./mfcc.sh: line 22: /home/navaneeth/kaldi/src/featbin/add-deltas: No such file or directory
./mfcc.sh: line 23: /home/navaneeth/kaldi/src/ivectorbin/compute-vad: No such file or directory
./mfcc.sh: line 24: /home/navaneeth/kaldi/src/featbin/compute-cmvn-stats: No such file or directory
./mfcc.sh: line 25: /home/navaneeth/kaldi/src/featbin/apply-cmvn: No such file or directory
sed: can't read mfcc/2.txt: No such file or directory
sed: can't read mfcc/2.txt: No such file or directory
sed: can't read vad/2.txt: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/compute-mfcc-feats: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/copy-feats: No such file or directory
./mfcc.sh: line 22: /home/navaneeth/kaldi/src/featbin/add-deltas: No such file or directory
./mfcc.sh: line 23: /home/navaneeth/kaldi/src/ivectorbin/compute-vad: No such file or directory
./mfcc.sh: line 24: /home/navaneeth/kaldi/src/featbin/compute-cmvn-stats: No such file or directory
./mfcc.sh: line 25: /home/navaneeth/kaldi/src/featbin/apply-cmvn: No such file or directory
sed: can't read mfcc/1.txt: No such file or directory
sed: can't read mfcc/1.txt: No such file or directory
sed: can't read vad/1.txt: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/compute-mfcc-feats: No such file or directory
./mfcc.sh: line 21: /home/navaneeth/kaldi/src/featbin/copy-feats: No such file or directory
./mfcc.sh: line 22: /home/navaneeth/kaldi/src/featbin/add-deltas: No such file or directory
./mfcc.sh: line 23: /home/navaneeth/kaldi/src/ivectorbin/compute-vad: No such file or directory
./mfcc.sh: line 24: /home/navaneeth/kaldi/src/featbin/compute-cmvn-stats: No such file or directory
./mfcc.sh: line 25: /home/navaneeth/kaldi/src/featbin/apply-cmvn: No such file or directory
sed: can't read mfcc/3.txt: No such file or directory
sed: can't read mfcc/3.txt: No such file or directory
sed: can't read vad/3.txt: No such file or directory
rm: cannot remove 'feats.scp': No such file or directory
rm: cannot remove 'test.ark': No such file or directory
rm: cannot remove 'test_delta.ark': No such file or directory
rm: cannot remove 'feats_delta.scp': No such file or directory
rm: cannot remove 'cmvn.scp': No such file or directory
rm: cannot remove 'cmvn.ark': No such file or directory

Even I have provided the kaldi path correctly, it is showing me this error
I will provide more details if required. Please help me out to resolve this.
Thanks
Answer: It seems you have not installed Kaldi. Kaldi binaries need to be compiled to make them executable. You can do the installation following the instructions in the INSTALL file in the root of the repo.
Once you have installed it, you need to add it to your PATH variable. This can be done following any of the path.sh scripts in any example recipe. Once you have added it to your PATH, you can try to run compute-mfcc-feats from your command line and it should print a usage message.
Comment: Thanks a lot, I have installed properly and can run the files. Previously Intel MKL was not installed I read those warnings and downloaded Intel MKL manually and performed the instruction .


android reset timer multiple times

Question: My first question!
I am trying to make an app where you have a random amount of time generated (between 1 second and 5 minutes) and it starts to count down from it. By pushing a button on the screen the timer resets to a new random time between the parameters and so on over and over again.
My problem is that it is using the method .cancel() that is in the countDownTimer class which only stops it. So when I generate a new random time and use the .start() method it starts the countdown and the old one to which I don't want.
package com.example.kasutaja.refugecamp;

import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

Button Start;
TextView textViewTime;
TextView textViewScore;
public boolean run=true;
public long milliss;
public long aeg;
public long score;
public int a;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Start=(Button)findViewById(R.id.Start );
    textViewTime=(TextView)findViewById(R.id.textViewTime);
    textViewScore=(TextView)findViewById(R.id.textViewScore);
    textViewTime.setText("00:00:00");
    aeg=Randoom();
    final CounterClass timer= new CounterClass(aeg,1000);
    Start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (run) {

                System.out.println(aeg + " aeg");
                aeg = aeg - milliss;
                System.out.println(aeg + " aeg2");
                score = score + aeg;
                System.out.println(milliss + " milliss");
                System.out.println(score + " score");
                String hmse = String.format("%02d:%02d:%02d",  TimeUnit.MILLISECONDS.toHours(score),
                        TimeUnit.MILLISECONDS.toMinutes(score) -  TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(score)),
                        TimeUnit.MILLISECONDS.toSeconds(score) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(score)));

                textViewScore.setText(hmse);
                timer.cancel();
                aeg = Randoom();
                final CounterClass timer = new CounterClass(aeg, 1000);
                timer.start();

            }

        }

    });

    timer.start();

}

public long Randoom() {
    Random rand = new Random();
    long aeg = rand.nextInt(300000 - 5000) + 5000;
    return aeg;
}
public class CounterClass extends CountDownTimer{

    public CounterClass(long millisInFuture,long countDownInterval){
        super(millisInFuture,countDownInterval);
    }
    @Override
    public void onTick(long millisUntilFinished){

        long millis =millisUntilFinished;

        String hms=String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis)- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis)-TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

        textViewTime.setText(hms);
        milliss=millis;
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Answer: Found a solution.
Just have to reinitialize the
final CounterClass timer = new CounterClass(aeg, 1000);

in the onClick method
as
this.timer = new CounterClass(aeg, 1000);

android reset timer multiple times


UIViewAutoresizingNone: Resize after rotation

Question: i have a simple structure for IPAD with an AppDelegate that include a view from a viewController :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ClockVC *clockVC = [[ClockVC alloc]init];
    clockVC.view.frame = CGRectMake(100, 100, clockVC.view.bounds.size.width, clockVC.view.bounds.size.height);

    [self.window addSubview:clockVC.view];
    [self.window makeKeyAndVisible];

    return YES;
}

clockVC has a viewDidLoad defined by this code :
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.autoresizingMask = UIViewAutoresizingNone;
    self.view.autoresizesSubviews = UIViewAutoresizingNone;
}

Bounds of clockVC are defined by IB and override in application:didFinishLaunching...
Width and Height are respectively 200 and 150.
ClockVC implements method for one-step auto-rotation :
/
/ Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
     [UIView animateWithDuration:0.5
                     animations:^{self.view.alpha = 0;}
     ];
}

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
    [UIView animateWithDuration:1
                     animations:^{self.view.alpha = 1;}
     ];
}

At the first load the page is correctly viewed and clockVC view is in position.
When i rotate clockVC view (whose autoResizeMask is set to UIViewAutoresizingNon)resize to take the entire screen.
Why ?? i'd like to mantain initial size.
Here screenshots of my problem.
Before rotation:

After Rotation:
Comment: i just added `clockVC.view.autoresizingMask = UIViewAutoresizingNone;` to  application:didifinishlaunching into app delegate... but nothing change.
Answer: Don't use the root view for this, add a subview to the view controller's view instead. UIViewControllers are typically designed to fill the entire space of their container (the window in this case).
For example, if you would add a UIViewController to a UINavigationController, the navigation controller takes over the responsibility to size the view controller's view according to the navigation controller's layout (whether the navigation bar is visible etc.). I'm not sure how exactly UIWindow behaves (I think this is not very clearly documented), but in a lot of places in the SDK, a view controller's parent is responsible for the positioning and size of its children (UIPopoverController, UITabBarController et.al.).
Comment: Would't it just be easier to create 2 nib files one for each position?
Comment: Thank you omz, i can't find something about that on Documentation but  i read only this :
`In an iOS application, the window object does much of the work associated with changing the current orientation. However, it works in conjunction with the application's view controllers to determine whether an orientation change should occur at all, and if so, what additional methods should be called to respond to the change. Specifically, it works with the view controller whose root view was most recently added to, or presented in, the window`.


Restriction of a diffeomophism is still a diffeomorphism?

Question: Suppose I have an open box $U = I_1 \times ... \times I_n \subseteq \mathbb{R}^n$ (so each $I_j$ is a non-empty open interval) and $F$ defines a diffeomorphims on $U$. What I was wondering was, if take $x_1 \in I_1$, is $F(x_1, \cdot)$ still a diffeomorphim on $I_2 \times...I_n$? Thank you!
Answer: If $F$ is a diffeomorphism from $I_1\times I_2\times\cdots\times I_n$ onto some subset $A$ of $\mathbb R^n$, then your map is a diffeomorphism from $I_2\times\cdots\times I_n$ onto $F\bigl(\{x_1\}\times I_2\times\cdots\times I_n\bigr)$, since, if $G=F^{-1}$, both $F|_{\{x_1\}\times I_2\times\cdots\times I_n}$ and $G|_{F(\{x_1\}\times I_2\times\cdots\times I_n)}$ re differentiable and each one is the inverse of the other one.
Comment: Yes, it would. ${}$
Comment: Would it be the same if I wanted $C^r$-diffeomorphism as well?


List the elements of the smallest set of pairs which needs to be added to R to form an equivalence relation, R∗

Question:
Suppose R = {(1, 1),(1, 4),(1, 5),(2, 2),(2, 7),(3, 3),(3, 6)} is a
relation on the set A = {1, 2, 3, 4, 5, 6, 7}

Q: List the elements of the smallest set of pairs which needs to be added to
R to form an equivalence relation, R∗
Attempt:
No clue how to answer this. What does equivalence mean? Would the smallest set be (1,1)? Would equivalence be (4,1), (5,1) (2,2) (7,2), (3,3), (6,3) etc etc? Not sure.
Comment: Read the definition of [equivalence relation](https://en.wikipedia.org/wiki/Equivalence_relation) if you don't know it.
Answer: An equivalence relation has to be reflexive wich means $(a,a) \in R$, for all $a \in R$, therefore you have to add $(4,4),(5,5),(6,6)$ to $R$.
It also has to be symmmetric wich means: for all $a,b \in R$, $(a,b) \in R \  \iff (b,a) \in R$. Therefore you have to add $(4,1),(5,1),(7,2),(6,3)$.
The last condition for $R$ to be a an equivalence relationship is that $R$ needs to be transitive, wich means for all $a,b,c \in R$, $(a,b)\in R$ and $(b,c) \in R$ then $(a,c) \in R$ therefore you don't need to add any elements to $R$ because $R$ is already transitive.


Stateful IPv6 configuration when router is absent on link

Question: RFC 2462 specifies:

5.5.2. Absence of Router Advertisements
If a link has no routers, a host MUST attempt to use stateful  autoconfiguration to
obtain addresses and other configuration    information. An
implementation MAY provide a way to disable the    invocation of
stateful autoconfiguration in this case, but the    default SHOULD be
enabled.  From the perspective of    autoconfiguration, a link has no
routers if no Router Advertisements    are received after having sent
a small number of Router Solicitations    as described in [DISCOVERY].

If I understand correctly is that if a host fails to receive a router advertisment upon solicitation or within specified time limit, it should use DHCPv6 for address configuration.
Since DHCPv6 cannot carry the information about default gateways (https://datatracker.ietf.org/doc/html/draft-droms-dhc-dhcpv6-default-router-00 is deprecated), what is the point of address configuration (the address cannot even be used for link-local traffic since DHCPv6 lacks prefix information)?
Answer: The Neighbor Discover Protocols, of which Router Advertisements are a part, is currently the only way to auto-configure the router options for a client. It's being debated whether this is an actual shortcoming of the DHCPv6 protocol, or if NDP-RA is sufficient. There's more than a few people who contend DHCPv6 is wholly unnecessary and should be deprecated too (I wont wade into that discussion here, but it's "hot").
Also, the DHCPv6 Router Option draft you linked is the original draft, they're currently on draft 4.
The essential argument is that if your router(s) are not broadcasting NDP-RA then they must not be working correctly, and you wouldn't want a client trying to contact them anyway. This allows you to configure a backup router more easily as the clients would automatically find it.
The Windows (6.0+), BSD, and Linux clients I have tested will all accept NDP-RA announcements and seek DHPCv6 information as one would expect. Currently you can auto-configure these clients for DNS with the mDNS/Bonjour protocol (an unacceptable solution for most enterprises). NTP has manycast and broadcast capabilities. WINS has NetBIOS. Only a few commonly used configuration options can't be replaced yet (notably PXE and the centralized management aspects of DHCP).
Neither DHCPv6 nor NDP address the security issues of computers receiving automatic configuration information over an essentially untrusted network. This is especially true of completely unprovisioned computers that have no certificates or information to base security on.


Crossvalidating for number of hidden layer nodes or not?

Question: I have come across a paper where the number of nodes in a one hidden layer neural network is being "empirically" derived as some function of the number of input and the number of output nodes. Since the number of nodes of the hidden layer is a hyperparameter of the model, I would assume that it would have to be crossvalidated for - or is the "empirical" approach also valid?
Thanks
Comment: It would really help if citation information, or the paper itself were available.
Comment: There can not be a rule  that works for every problem, just because of the inmense variety of problems and features that you can be in front of. There are rules like 2/3 of the inputs or things like that for simple nets but its precisely choosing parameters one of the difficulties of neural nets and other models with that kind of parameters.Cross validation or a similar method is better in my opinion.
Comment: Not *systematically.* the model could still be over- or under- fit, though.
Comment: @D.Castro "Best" is a huge overstatement. Grid search is stupidly simple to parallelize and it's exhaustive... but gtobal optimization with surrogate models or particle swarms can often find high-quality solutions with fewer function calls.
Comment: @user777 here is the paper: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC4301668/ the formula I am talking about is in the supplementary material, page 6
Comment: @D.Castro why would CV be better? I am not thinking only about the particular case of Neural Networks, but if I test my classifier correctly, is it not as well ok to start with some hyperparameters chosen a priori?
Comment: @Pegah but what if some other hyper parameter choices are better? If you're comfortable restricting yourself to some set of hyper parameter choices, that's fine. But otherwise....
Comment: @user777 yes I agree, I am just trying to understand. Particularly I was curious if an a priori choice somehow could lead systematically to overfitting, of if it is theoretically at least ok
Comment: @Pegah if you've tested some parameter for a problem then it's normal continuing with it, but only for that problem. With another problem you start again with othe features,measures, sizes etc.As there is no valid and magic formula the bestapproach is to test some grid of parameters.
Answer: Some people have "rules" about the relationship between the number of input and output nodes, but I'm not aware of any such rule which has a strong theoretical foundation.
The standard practice for this type of problem is to try lots of different configurations and measure performance on out-of-sample data.


Tem a possiblidade de fazer um toggle button com dois button?

Question: Tenho um sisteminha, para mudar o layout da página para um layout de visão noturna, porém para isso acontecer eu tive que usar dois botões, e eu acho que fica melhor usar um toggle button  para mudar o tema. Se vcs puderem ajudar eu agradeço.

function applyTheme (theme) {
    "use strict"
 document.getElementById("mypage").className = theme;
 localStorage.setItem ("theme", theme);
}

function applyDayTheme () {
    "use strict"

 applyTheme("day");

}

function applyNightTheme() {
        "use strict"
 applyTheme("night");

}

function addButtonLestenrs () {
        "use strict"

document.getElementById("b1").addEventListener("click", applyDayTheme);
document.getElementById("b2").addEventListener("click", applyNightTheme);

}

function initiate(){
        "use strict"

 if(typeof(localStorage)===undefined)
  alert("the application can not be executed properly in this browser");
 else{
  if(localStorage.getItem("theme")===null)
   applyDayTheme();
  else
   applyTheme(localStorage.getItem("theme"));

 }
 addButtonLestenrs();
}

initiate();
<!DOCTYPE html>

 <meta charset="utf-8">
 <link rel="stylesheet" href="Estilos.css">

Choose a theme

 <button id="b1">Theme day</button>
 <button id="b2">Theme night</button>

 This is an example of use of HTML5 storage API

    in

.day{
color:black;
background-color:rebeccapurple;

}
.night{
color:white;
background-color:black;
}
Answer: Coloca uma classe para os dois buttons , tipo toggle-btn

function applyTheme (theme) {
   document.getElementById("mypage").className = theme;
   //localStorage.setItem ("theme", theme);
}

function toggleThemes(){

    var day = document.getElementById('b1');
    var night = document.getElementById('b2');

    if(day.className=="toggle-btn enabled"){
         night.className = "toggle-btn enabled";
         day.className =  "toggle-btn"
         applyTheme("night");
    } else {
         day.className = "toggle-btn enabled";
         night.className =  "toggle-btn"
         applyTheme("day");
    }

}
    .toggle-btn.enabled{
        border: 1px inset #DDD;
        background: blue;
        color: white;
    }
    .toggle-btn{
        border: none;
        padding: 5px 10px;
    }
    #mypage{
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0px;
        top: 0px;
     }
     #mypage.night{
         background: black;
     }

<button id="b1" class='toggle-btn enabled' onclick='toggleThemes()'>Theme day</button>
<button id="b2" class='toggle-btn' onclick='toggleThemes()'>Theme night</button>

Answer: Uma opção com JavaScript puro, sem precisar de jQuery, fazendo apenas um botão para alternar entre Dia e Noite.
Veja o exemplo:

function myFunction() {
    var element = document.getElementById("mypage");
    element.classList.toggle("night");
}
body {
    color:black;
    background-color:rebeccapurple;
}
.night{
    color:white;
    background-color:black;
}
body.night button {
    background:blue;
}

Choose a theme

    <button id="b1" onclick="myFunction()">Dia/Noite</button>

 This is an example of use of HTML5 storage API

    in

Sei que não é exatamente o que vc pediu, mas se quiser uma opção usando jQuery vc pode usar o método .toggleClass("") para colocar e retirar a classe night do body apenas com um botão do tipo "on/off"
Veja o exemplo:

$("#b1").click(function(){
    $("#mypage").toggleClass("night");
});
body {
    color:black;
    background-color:rebeccapurple;
}
.night{
    color:white !important;
    background-color:black !important;
}

Choose a theme

    <button id="b1">Dia/Noite</button>

 This is an example of use of HTML5 storage API

    in


How to detect differences between two repeated measures for not-normally distributed variables, adjusting for a continuous covariate?

Question: I'll explain briefly the experimental set-up.

One gruop of subject measured in two conditions:

A: with treatment (Instrumented gait analysis with foot orthosis)
B: without treatment (Barefoot instrumented gait analysis)
Before testing, subjects used the treatment (foot orthosis) for different periods, this may have an impact on the results. I need to verify if there are differences between the two conditions using the treatment duration as a covariate.
Comment: Do you just mean something like ANCOVA but extending the Wilcoxon test instead of the t-test (same as the ANOVA F-test with two groups)?
Comment: Questions solely about how software works are
[off-topic](https://stats.stackexchange.com/help/on-topic) here, but
you may have a real statistical question buried here.
You may want to edit your question to clarify the underlying
statistical issue. You may find that when you understand
the statistical concepts involved, the software-specific elements are
self-evident or at least easy to get from the documentation. --- so you might want to edit to title so this do not looks like a software only question!
Comment: I am with @kjetilbhalvorsen that there is a statistical question hiding in here, and, if the answer to my question in the previous comment is in the affirmative, then there is a good statistical answer to be posted that culminates with, "Implement this with `rms::orm`." [See here.](https://stats.stackexchange.com/questions/525112/what-are-rmsorm-wilcox-test-and-kruskal-test-in-r-doing-differently)
Comment: Thanks both for your advices, I am sorry for the form of my question but the first time I post something on this website. I edited the question as you suggested, hope it is fine now. Thank you again
Comment: How would you do it if you had normal distributions? // What is not normally distributed? There is no assumption in linear regression that the pooled/marginal $y$ variable is normal. That assumption is about the error term (estimated by the residuals).
Comment: If i had normal distribution I would run a repeated measure ANCOVA.
My dependent variables are not normally distributed.
Comment: Dependent variables, as in plural? What do you mean by that? // It might be worth doing something Wilcoxon-like, even if there is a normal error term. In that case, the link I gave states which regression method extends the Wilcoxon Mann-Whitney U test the way that linear regression extends the t-test (it's proportional odds ordinal logistic regression, and the implementation, I think, is to take the exact same formula you'd use in `lm` and put it inside `rms::orm`.)
Comment: Do you just want to adjust for duration as a confounder? Or do you want a conditional effect using duration as a covariate? If the former, look up average treatment effect estimation (R package tmle) for estimating the effect difference between a binary treatment adjusting for arbitrary confounders nonparametrically.
Comment: @Lars I need to verify if there are differences between the conditions and if a significant interaction between the conditoin and the duration exists
Answer: You could use the a robust ANCOVA for two dependent groups and one covariate called Dancova from the WRS package in R. Uses by default 20% trimmed means. Assumptions for classic ANCOVA are not required.
# load the latest WRS package
> source("https://dornsife.usc.edu/assets/sites/239/docs/Rallfun-v38.txt")

> Dancova(x1, y1, x2 = x1, y2, tr = 0.2, plotit = TRUE)

x1 are covariate values for your first group, x2 for the second (should be the same as x1)
y1 are dependent variable values for your first group, y2 for the second
Comment: How to intrepret output from Dancova function?
Rows have no names
Comment: Forgot to explain the output. So the function determines 5 points (values) of your covariate and then for each value performs a dependent yuen's t-test on 20% trimmed means (i.e. whether the DV for the two groups differs significantly). Due to multiple tests the function controls for keeping the type 1 error rate so you can conclude that you have a significant difference on each point only if `p.value` <  `p.crit`. By the way you can set trimming to 0 (`tr = 0`) if your DV is not skewed and you do not have outliers -- increases power of your test.
Comment: Thank you again, one last question. Do you have any suggestion on how to report the results?
Comment: Yes, a robust ANCOVA for two dependent groups has been deployed with the function `Dancova` the WRS package [(Wilcox, 2017)](https://www.sciencedirect.com/book/9780128047330/introduction-to-robust-estimation-and-hypothesis-testing) in R. This function does not make parametric assumptions about the form of the regression line and uses a running interval smoother instead. The analysis revealed that for the treatment duration "x" the (20% trimmed) mean of DV was significantly higher in group 1 than in group 2 (p = .024). For the treatment duration "y" ...
Comment: You can also report the test statistic which is $T_y$ for trimmed means or $t$ respectively $W$ for no trimming (uses Welch's t-test instead). In case you don't need the confidence intervals or the test statistic you can also use the function `DancovaV2` which uses bootstrap samples and is more powerful. Also if you don't like the chosen points (values) of the covariate you can determine their values and number manually for both functions. Like this: `pts = c(4, 7, 10)`.


How can I make an idempotent projection to an Hermitian operator in a Hilbert space?

Question: I have tried to solve the following question:
Consider the Hilbert space $\mathbb R^3$. Find the projection to the 2-dimensional subspace
$$\text{span}\{|0\rangle+|1\rangle,|0\rangle+|2\rangle\}$$.
I found the following idempotent operator which projects any vectors to that subspace:
$$
\begin{bmatrix}
0 & 1 & 1\\
0 & 1 & 0\\
0 & 0 & 1
\end{bmatrix}.
$$
However, it is not Hermitian. How can I make it Hermitian? or should I find another solution which is both Hermitian and idempotent, can anyone guide me please?
On the other hand, if I change the Hilbert space in question to $\mathbb C^3$, is the solution differ?
Comment: are the vectors $|0\rangle,|1\rangle$ and $|2\rangle$ linearly independent, orthonormal, or what? could you tell more about them ?
Comment: The answer is now below
Answer: Let $\{|v_j\rangle\}_{j=1}^m \subset \mathbb R^3$, where $0 \le m \le 3$ and $n = 3$. Let the subspace spanned by $\{|v_j\rangle\}_{j=1}^m$ be denoted
$$
V \equiv \text{span}\{|v_j\rangle\}_{j=1}^m
$$
First one has to find an orthonormal basis in $V$, for the tensor ket-bra notation to work. Denote this ONB in $V$ by  $\{|u_j\rangle\}_{j=1}^{m'}$, where $m' \le m$.
The projector operator (in the tensor bra-ket notation or the like) that projects the space onto $V$ is
$$
P:= \sum_{j=1}^{m'} |u_j\rangle\langle u_j|
$$
and is clearly hermitian.
For the case at hand if the given kets $| 0\rangle,| 1\rangle,| 2\rangle$ are the standard basis in $\mathbb R^3$, then we orthonormalise the vectors $\{|v_j\rangle\}_{j=1}^m$ (by the Gram-Schmidt process) to get the $\{|u_j\rangle\}_{j=1}^{m'}$, which are in terms of {$| 0\rangle,| 1\rangle,| 2\rangle$}. So it remains to substitute these $\{|u_j\rangle\}_{j=1}^{m'}$ in the operator and then expand the ket-bras to get the matrix elements wrt {$| 0\rangle,| 1\rangle,| 2\rangle$}.
the answer is
$$
\begin{pmatrix}
\frac{2}{3} &  \frac{1}{3} &  \frac{1}{3} \\
\frac{1}{3} &  \frac{2}{3} & -\frac{1}{3} \\
\frac{1}{3} & -\frac{1}{3} &  \frac{2}{3} \\
\end{pmatrix}
$$
which is an idempotent (checked by Mathematica) and hermitian (symmetric in $\mathbb R^{3\times3}$). If I have to add the details of the solution, tell me in the comment below.
Answer: Suppose you have a subset $V$ of a Hilbert space $H$, which is spanned by $m$ orthogonal elements $v_1,\ldots,v_m$. Then, the unique hermitian projection (also called orthogonal projection) $P_V$ onto $V$ can be written as
$$ P_Vx = \sum_{k=1}^m \frac{1}{\|v_k\|^2}\langle v_k,x\rangle v_k \qquad\mbox{for}\ x\in H. $$
It can be easily verified, that this yields $P_V$ to be self-adjoint (hermitian) and idempotent.
In Dirac notation, this takes the slightly easier form
$$ P_V = \sum_{k=1}^m \frac{1}{\|v_k\|^2}|v_k\rangle\langle v_k|.$$
If $H=\mathbb R^n$, then $\langle v_k|=v_k^T$ is the transposed vector of $v_k$. If $H=\mathbb C^n$, then $\langle v_k|=v_k^\dagger$ is the transposed and complex conjugated vector of $v_k$.
In your example, $V$ is spanned by the vectors $u_1 = \begin{pmatrix}1\\1\\0\end{pmatrix}$ and $u_2 = \begin{pmatrix}1\\0\\1\end{pmatrix}$. (I assume you have $\{|0\rangle,|1\rangle,|2\rangle\}$ as the standard basis in $\mathbb R^3$.) As $\langle u_1,u_2\rangle = 1$, we first need to orthogonalize the two vectors. Therefore, we set $v_1=u_1$ and
$$v_2 = u_2-\frac{\langle u_2,v_1\rangle}{\|v_1\|^2}v_1 = \begin{pmatrix}1\\0\\1\end{pmatrix} - \frac12 \begin{pmatrix}1\\1\\0\end{pmatrix} = \begin{pmatrix}\frac 12\\-\frac 12\\1\end{pmatrix}.$$
Now, $V=\operatorname{span}\{v_1,v_2\}$ and $\langle v_1,v_2\rangle = 0$.
Then we obtain
\begin{align}
P_V &= \frac 12 \begin{pmatrix}1\\1\\0\end{pmatrix}\begin{pmatrix}1&1&0\end{pmatrix} + \frac{2}{3} \begin{pmatrix}\frac 12\\-\frac 12\\1\end{pmatrix}\begin{pmatrix}\frac 12&-\frac 12&1\end{pmatrix} \\&= \frac 12\begin{pmatrix}1&1&0\\1&1&0\\0&0&0\end{pmatrix}+\frac23\begin{pmatrix}\frac 14&-\frac 14&\frac 12\\-\frac 14&\frac 14&-\frac12\\\frac 12&-\frac 12&1\end{pmatrix} \\&= \begin{pmatrix}\frac 23&\frac 13&\frac 13\\\frac 13&\frac 23&-\frac13\\\frac 13&-\frac13&\frac 23\end{pmatrix}. \end{align}
Comment: @AmHsnSharafi You're welcome. That is completely up to the basis you use. The standard basis is the same as in $\mathbb R^3$, so the result doesn't change in the complex setting.
Comment: I am sorry for the wrong answer at first. The spanning vectors need to be orthogonalized, afterwards you can apply the expansion technique. I have added some details. The answer by @Physor is also correct and detailed now.
Comment: @Benjamin, many thanks for your response. What are {|0⟩,|1⟩,|2⟩} in $C^3$ please?
Comment: But it doesn't satisfy the condition $P^2=P$ of the projections. So how do you explain that?
Comment: @Physor So do you have an idea how can we find a projection onto this subspace?
Comment: I've found this, to be able to use Dirac notation for tensor "ket-bra", **the basis of the space in the tensor expansion must be orthonormal**, it is difficult to explain why in this comment. Secondly, the vectors $v_k$ are *not* orthogonal
Comment: @Physor yes, It's clear that ket of 0, 1, and 2 are the standard basis and $v_k$ are not orthonormal, so the question is that in this situation how can we find the projection operator onto this subspace?
Comment: I'm working on it, first, use Gram-Schmidt to orthonormalise the $v_k$, then put these in the tensor expansion, second since the $v_k$ and therefore their normalized versions will be in terms of the standard basis, expand the tensor in the tensor basis (ket-bra of the standard) you get the matrix elements
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/113447/discussion-between-mehrd97d-and-physor).


Filter module won't let me add nested values to my configuration

Question: I'm working on the D8 port of my xbbcode module; my latest sources are here.
The module is supposed to let administrators enable individual BBCode tags either in the global default settings or in an individual text format that overrides those defaults.
The settings structure for both is basically (in YAML):
tags:
  abbr:
    module: xbbcode
    enabled: 0
  b:
    module: xbbcode_basic
    enabled: 1
  [...]

The default configuration (set in the annotation comment of my filter plugin class) is
/**
 * Provides a filter that converts BBCode to HTML.
 *
 * @Filter(
 *   id = "xbbcode",
 *   title = @Translation("Convert BBCode into HTML."),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 *   settings = {
 *     "autoclose" = FALSE,
 *     "override" = FALSE,
 *     "tags" = {}
 *   }
 * )
 */

However, when I try to create a new text format, I get the following error:
InvalidArgumentException: The configuration property filters.xbbcode.settings.tags.abbr
doesn't exist.
in Drupal\Core\Config\Schema\ArrayElement->get()
(line 97 of core/lib/Drupal/Core/Config/Schema/ArrayElement.php).

Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings.tags.abbr', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings.tags', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters', Array)
Drupal\Core\Config\Config->save()
Drupal\Core\Config\Entity\ConfigEntityStorage->doSave('bb2', Object)
Drupal\Core\Entity\EntityStorageBase->save(Object)
Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object)
Drupal\Core\Entity\Entity->save()
Drupal\filter\FilterFormatFormBase->submitForm(Array, Object)
Drupal\filter\FilterFormatAddForm->submitForm(Array, Object)
call_user_func_array(Array, Array)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object)
Drupal\Core\Form\FormBuilder->processForm('filter_format_add_form', Array, Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\Core\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

Some examination of the StorableConfigBase class reveal that it seems to insist on merging my configuration values with the existing ones, down to the bottom level, and when it doesn't find the "abbr" key it shuts down. This seems pretty silly, because obviously an array can gain or lose entries when you save it.
The weird thing is that the global defaults have absolutely no problem when I change them with $this->config('xbbcode.settings')->set('tags', [...])->save() in my own ConfigFormBase settings form.
Edit: filter.format.* has a config schema, while my module doesn't. I'm not sure how to tell this schema "this array may have a number of keys, each of which has the form {enabled: ..., module: ... }
Answer: I figured out how to declare the filter settings schema by comparing with modules/filter/config/schema/filter.schema.yml and using the Schema docs.
Apparently my schema file simply needs to declare
filter_settings.xbbcode:
  type: filter
  label: 'XBBCode filter'
  mapping:
    [...]

Comment: I have no idea how you managed to not have a config schema in the first place, that seems like a problem, but yes, you should implement a config schema that describes your structure.
Comment: It seems that missing schemas on your own settings are simply ignored, and even filter.module somehow gleans an implicit schema from the annotation comment? The keys that were described there didn't run into any problems. :)
Comment: Yes, correct, the default schema is defined as a list of strings. That's extremely weird, everywhere else we force plugins to define their schema. I've opened https://www.drupal.org/node/2472927.


Como gerar links para paginação com limites?

Question: Eu tenho uma paginação cujo os resultados geram grande quantidade de links-números.
Cenário:

tenho 10.000 (dez mil) registros sendo paginados.
A paginação deverá ser de 30 em 30;
Porém, os links não podem exibir 333 links, mas apenas 15. E esses links, vão dinamicamente sendo exibidos de acordo com a página atual.

Exemplo:
1 .. 15

16 .. 30

30 .. 40

317 ... 333

Porém desejo fazer isso, deixando a página atual "no meio" desses links.
Exemplo:
 Página 35 exibe de 28 à 43

Se eu clicar em 320.
317 ... 333

Como poderia fazer isso em PHP?
Observação: Já consegui fazer isso no Laravel 4, mas acho que a pergunta vai ajudar algumas pessoas que têm essa dificuldade (e que não usam um framework).
Exemplo de paginação com pontos nos links no Laravel 4:
@for ($i = $initial = max(1, $paginator->getCurrentPage() - 15), $l = min($initial + 20, $paginator->getLastPage()); $i <= $l; $i++)

    @if($paginator->getCurrentPage() == $i)
        {{ $i }}
    @else
        getUrl($i) }}">{{ $i }}
    @endif

@endfor

Comment: http://stackoverflow.com/questions/11272108/logic-behind-pagination-like-google
Comment: Recompenso ou não recompenso? Eis a questão!
Comment: Não precisa... eu apenas informei um link de uma resposta ja dada aqui mmesmo
Comment: @JeffersonSilva aqui mesmo? stack overflow != stack overflow em portugues
Answer: Eu acabei decidindo publicar minha própria resposta.
Eu criei uma função para poder gerar um range de números de acordo com o limite passado.
A lógica é a seguinte: Se tenho 55 paginas e quero limitar a 10. Será exibido 5 itens antes e 5 depois da página atual. Caso a página atual seja o valor inicial que é 1, os 5 que deveriam ser exibidos antes de 1 são acrescentados ao final. Se o valor limite for 55, então exibimos 10 antes de 55 (ou seja 45).
A ideia é que os resultados fiquei assim:
[1] 2 3 4 5 6 7 8 9 10
1 [2] 3 4 5 6 7 8 9 10
1 2 [3] 4 5 6 7 8 9 10
1 2 3 [4] 5 6 7 8 9 10
1 2 3 4 [5] 6 7 8 9 10
1 2 3 4 5 [6] 7 8 9 10
2 3 4 5 6 [7] 8 9 10 11
3 4 5 6 7 [8] 9 10 11 12

44 45 46 47 48 [49] 50 51 52 53 54
45 46 47 48 49 [50] 51 52 53 54 55
45 46 47 48 49 50 [51] 52 53 54 55
45 46 47 48 49 50 51 [52] 53 54 55

45 46 47 48 49 50 51 52 53 54 [55]

Para isso criei a seguinte função:
/**
 * @param int $current Página atual
 * @param int $total Total da Paginação
 * @param int $limit Limite de links exibidos
 * @param int $start_at Valor inicial. Geralmente o Padrão é 1
 * @return \Generator
 */
function range_limit($current, $total, $limit = 10, $start_at = 1)
{
    $middle = ceil($limit / 2);

    $current = max($start_at, min($total, $current));

    $start = $current - $middle;

    $end = $middle + $current;

    if ($start <= $start_at) {
        $start = $start_at;
        $end = $limit;

    } elseif ($end >= $total) {
        $end = $total;
        $start = $total - $limit;
    }

    for ($i = $start; $i <= $end; $i++) yield $i;
}

Para usar, basta fazer assim:
  range_limit($pagina_atual, $ultima_pagina, $limite_de_links);

Veja funcionando no Ideone.
Em um caso mais próximo do real, poderia ficar assim:
 $pagina_atual = $_GET['pagina'] ?? 1;

 $limite_da_paginacao = 15;

 // Se for 1, é 0
 // Se for 2, é 15
 // Se for 3, é 30
 // Se for 4, é 45
 $offset = ($pagina_atual * $limite_da_paginacao) - $limite_da_paginacao;

 $resultado = query("SELECT COUNT(*) as total FROM usuarios")->primeiro();

 $ultima_pagina = ceil($resultado->total / $limite_da_paginacao);

 $limite_de_links = 10;

 $dados = query("SELECT * FROM usuarios LIMIT ? OFFSET ?", $limite, $offset)->todos();

Para gerar os links, bastaria fazer:
  <?php foreach(range_limit($pagina_atual, $ultima_pagina, $limite_de_links) as $pagina): ?>
      <a href="index.php?pagina=<?=$pagina?>"><?= $pagina ?>
  <?php endforeach ?>

Answer: Como na pergunta está citado que a resposta deve prover uma solução para usuários iniciantes, então tentei fazer o exemplo mais simples possível, com o cálculo mais simples que consegui pensar.
Passo a passo
A paginação é o processo de separar muitos resultados de alguma busca, logo é obrigatório termos um objeto para ser manipulado nessa paginação. No exemplo esse objeto é um array simples de string onde cada string representa uma página (seja ela um artigo, ou lista de produtos, etc).
Outra coisa que devemos levar em consideração é em resguardar a página atual em que o usuário está, a demonstração usa o GET do PHP para armazenar e informar o valor da página atual para o usuário.
A última coisa é pensar no objetivo, que é além de exibir o conteúdo da página selecionada, mostra o link para X páginas anteriores e X páginas posteriores da página atual. Logo definimos algumas variáveis, como:

display - que armazena o valor definido como quantidade máxima de
links de páginas.
middle - que é apenas a variável anterior    dividida por 2 para
informar quantas páginas antes e depois da página    atual iremos
buscar.

Após tomar conhecimento dos requisitos para fazer tal paginação, partimos para o código:
pager.php:
<?php
// array que simula o objeto a ser paginado, que normalmente é resultado de uma busca na persistência
$pages = array
(
    'page01', 'page02', 'page03', 'page04', 'page05',
    'page06', 'page07', 'page08', 'page09', 'page10',
    'page11', 'page12', 'page13', 'page14', 'page15',
    'page16', 'page17', 'page18', 'page19', 'page20',
    'page21', 'page22', 'page23', 'page24', 'page25',
    'page26', 'page27', 'page28', 'page29', 'page30',
);

// Resgata número página atual da URL, o padrão é 1
$current = isset($_GET['page']) ? $_GET['page'] : 1;

// Informa número de links para navegação de páginas a ser mostrado
// de preferência ser ímpar, para que possa haver um meio exato para página atual
$display = 7;

// se a página existir
if(array_key_exists($current - 1, $pages)):
    // exibe conteúdo da mesma
    echo "
Current page: {$pages[$current - 1]}
";

    // define o meio dos links, defino um contador com o mesmo valor
    // ele auxiliara na hora de mandar x links para direito e x para esquerda
    $middle = $cont = (int)($display/2);

    // Percorre de 0 até o limite de links
    for($pg = 0; $pg < $display; $pg ++):
        // Se não é o meio da quantidade de links
        if($pg != $middle)
        {
            // Se for uma página anterior
            if($pg < $middle)
            {
                // Página será igual a atual menos o contador
                $page = $current - $cont;
                // Decrementa contador, para que a proxima pagina seja +1
                $cont --;
            }
            // Se for uma página posterior
            else if($pg > $middle)
            {
                // Define numero da página, como atual + contador + 1 (que indica que já passou a página atual também)
                $page = $current + $cont + 1;
                // Incrementa contador, para que a proxima pagina seja +1
                $cont ++;
            }
            // Exibe o link apenas se a página tiver no intervalo de resultados
            if($page > 0 and $page <= count($pages))
                echo "{$page} | ";
        }
        // Se for a página atual (estará no meio)
        else
        {
            // Exibe o link em negrito
            echo "{$current} | ";
        }
    endfor;
// Se a página não existir
else:
    echo "
Page not exists!
";
endif;

?>

Comment: Cara sou iniciante em php, eu não entendi a parte do GET['page'], inicial, onde diz que o padrão é 1, mas a nomeação dos valores do array está como "01"... Pode me dar uma breve esclarecida ?
Comment: @MagicHat Na linha eu olho, se existe parâmetro get, se sim eu armazeno o valor do get em current, se nao eu armazeno o numero um, supondo que a primeira página é a 1. No array são apenas exemplos de conteúdo, voce pode edita-lo normalmente, o que importa no caso é a chave do array que no caso vai de 0 até 29, onde zero humanizando, significa a página 1, e assim por diante até a página 30. O conteúdo do elemento do array seria o texto da página, nada mais. Espero ter esclarecido nesse texto breve.


SQL before insert trigger

Question: I am trying to create a trigger but I'm running into trouble on a certain aspect. What I want the trigger to do is check the stock levels of a product being inserted, if the stock levels = 0 then the trigger will prevent the insert, if the level is between two values it will allow the insert but display a warning and lastly if the level is above a value it will insert no questions asked.
My problem is extracting the information from the insert in order to obtain the correct value for the trigger variable @stock_level.
Below I have a sample insert statement that will be retrieved from a GUI and below is the trigger I plan on using. I have entered in the required information into the trigger by hand but is it possible to extract this information without hard coding in the values?
Insert Statement
  --sample insert
  insert into sales_table values (1,2,3,4, '12/31/2015', '12:30:21');

Trigger
  create or replace trigger inv_check
  before insert on SALES_TABLE
  --declaring variable that contains the stock number of the product being inserted
  --4 is the product code and 1 is the outlet_number taken from the above
  DECLARE @stock_level = (select quantity from inventory_table where product_code = 4 and outlet_number = 1);
  BEGIN

  IF @stock_level = 0 then
    DBMS_OUTPUT.PUT_LINE("Sorry, out of stock");
    ROLLBACK;
  ELSIF @stock_level > 0 and @stcok_level < 15 then
    DBMS_OUTPUT.PUT_LINE("Running low order more");
    --continue with insert
  ELSE
    DBMS_OUTPUT.PUT_LINE("Inserting row...");
  END;

Answer: You don't need to declare the variable at all. In this case, the value you tried to assign to the variable is stored in :new.stock_level, such is the case with triggers. Here is a fix for the code you posted
CREATE OR REPLACE TRIGGER inv_check
BEFORE INSERT ON sales_table
BEGIN
    IF :new.stock_level == 0 THEN
        DBMS_OUTPUT.PUT_LINE("Sorry, out of stock");
        ROLLBACK;
    ELSE IF :new.stock_level > 0 AND :new.stock_level < 15 THEN
        DBMS_OUTPUT.PUT_LINE("Running low order more");
        --continue with insert
    ELSE
        DBMS_OUTPUT.PUT_LINE("Inserting row...");
    END IF;
END;

Answer: What value you need to extract?
To get values inserted in sales_table use

:new.fieldname

SQL before insert trigger


Not automatically built by drone.io

Question: Set trigger/ref in drone.yaml.
This is the expected behavior of the build at develop/master push and when creating merge requests, but it is not happening!
<code>--drone.yaml--
kind: pipeline
type: docker
name: default

trigger:
  ref:
  - refs/heads/master
  - refs/heads/**
  - refs/pull/*/head

steps:
- name: test
  image: golang
  commands:
  - cd src/chat
  - go get github.com/stretchr/gomniauth
  - go get github.com/stretchr/gomniauth/providers/facebook
  - go get github.com/stretchr/gomniauth/providers/github
  - go get github.com/stretchr/gomniauth/providers/google
  - go test
  - go build main.go auth.go client.go room.go
</code>
Manual Build
github webhook
How can I build automatically in response to push and pull requests?
Answer: All the details can be found in this documentation https://docs.drone.io/pipeline/triggers/
You can use something like this to achieve your requirement
<code>trigger:
  branch:
    include:
    - develop
    - master
  event:
    include:
    - push
    - pull_request
</code>

Not automatically built by drone.io


An example of a beginner-level Algorithm, intermediate level Algorithm and a complex/expert level Algorithm?

Question: I'd like to get a sense for the range of complexity that Algorithms fall into.  I think it would be interesting and helpful for those, like me, trying to better understand how algorithms are formulated and how to deconstruct them.
Can you offer a basic algorithm with explanation, an intermediate algorithm with explanation, and maybe an expert level one (with or without) an explanation?
Comment: I believe this question is unanswerable.
Comment: Meh, it's a perfectly reasonable question for a beginner to ask.
Comment: @Alexander: it's undecidable.
Comment: @Legatou So what would be a perfectly reasonable question for an intermediate/advanced user to ask? ;)
Comment: Everything is relative, other than the fact that this question is subjective and argumentative. ;-)
Answer: Allow me to refer you to this website for happy brainmunching. http://projecteuler.net/index.php?section=problems
Beginner Algorithm: Find the first element of a sequence that matches a criterion. This is a simple O(n) traversal of, say, a list or array, search for the first truth case it sees and returns the result or index position.
Beginner-Intermediate Algorithm: Define an in-place Heap Sort that requires O(1) memory. This requires playing with memory and enough abstract thinking to break you out of the diapers of computational science.
Intermediate Algorithm: Find the 1,000,000th prime number within 5 seconds of computation time. This is a simple math problem that most programmers should be able to solve in a day, if they consider themselves at all acquainted with computation science.
Intermediate-Advanced Algorithm: Define a genetic algorithm. Not much to say here, just Wikipedia it.
Advanced Algorithm: Define a quantum annealing sort function that finishes in O(n) time. You can earn your Ph.D with this one. I mention something like this that is damn near impossible with a Turing-complete digital computation system because it's in places like this that computation science is treading new ground. Anyone that's advanced in computer science and algorithmic study is concerned with strange ground like this.
Comment: Kind of a leap from "Beginner" to "Beginner-Intermediate" there!  My guess is that around 30% of working programmers have *heard of* a heap data structure.  (Also genetic algorithms aren't hard -- that would be a better choice for "Intermediate".)
Comment: 30% of working programmers maybe, but 100% of CS grads should have heard of it. The original question isn't really clear as to whether it's asking for algorithm examples from a CS perspective or a working programmer perspective.
Comment: Yeah, you guys come up with great criticism. I did my best to give him an idea of computation science algorithms. I'd edit and expand if the question weren't closed.
Answer: From what I remember of my algorithms college course, we first started with various sorts, like merge sort and quick sort, then we learned Dijkstra's algorithm


Why Is It Useful to Put Things in Vector Spaces?

Question: Many different things in math/physics that don't seem to be related to linear algebra can be classified as elements in a vector space, such as polynomials of degree $n$ for example. This can be done as long as all the elements follow all of the vector space axioms.
Another example from physics would be waves $y(x,t)$ that satisfy the linear wave equation $$\frac{\partial^2y(x,t)}{\partial x^2}=\frac{1}{v^2}\frac{\partial^2y(x,t)}{\partial t^2}$$
Which (since $v=\frac{\omega}{k}$) has solutions in the form of $$A\cos(kx\pm\omega t+\phi)$$
Since any addition between the solutions is algebraic, the commutativity associativity laws hold and there exists an identity which can be added to any solution so as not to change it ($0$), and an additive inverse to every solution such that the sum of the element and its additive inverse is equal to 0.
The distributivity laws also hold for all real numbers, as well as the associativity law of multiplication. Any solution multiplied by 1 is also itself, satisfying the unitary law. The vector space is also closed under addition and scalar multiplication, since the addition of 2 waves yields another wave.
My question is: Is there any use for classifying waves (or any other sets of things in math/physics that at first glance may not be related to linear algebra) as elements of a vector space?
Comment: If you know that some collection of objects has the structure of a vector space, then every theorem we've ever proved about vector spaces immediately applies to that specific collection of objects.
Comment: Good observation, in fact they are, and the cos\sin are the orthogonal base vectors. This is indeed extremely useful and is called linear operator theory. More keywords: Fourier transform, Hilbert space
Comment: And there are thousands of theorems about vector spaces.
Answer: It gives you access to the big toolbox of linear algebra.
Most of the results from linear algebra are solely based on the vector-space axioms.
You have a lot of theorems beginning with: "If $V$ is a vector space".
Thus, once you can show that your structure obeys the vector-space axioms, you can apply these results without further ado.
(Of course, there are some results from linear algebra that have further constraints such as your vector space being finite-dimensional, but it's not that these are secret.)
Of course, you can also prove all the stuff you need from scratch and without ever referring to vector spaces, but that's rather tedious.
It allows you to use an existing language / thought structure
Once you work sufficiently long with vector spaces, you develop an intuition for such things as dimensions, bases, orthogonality, etc.
Showing that a structure is a vector space allows you to apply that intuition to that structure and quickly think about things.
Relatedly, you can communicate about that structure with others much more easily.
For instance, just consider the examples in the first sentence of this section.
(If you wonder why language and thought structures are related: Having a vocabulary for something is crucial to effective thinking about it.)

This is the general way mathematics operates:
You recognise similarities in structures, create an abstract framework that comprises these similarities, and benefit from synergy effects.
For a blatant example, consider numbers:
At some point, people realised that when you tie some strings together, their lengths behave in the same way that the time required for two subsequent activities behaves.
Numbers allow you to think and speak about these things in a coherent way and you do not have to reinvent the wheel again every time you find something new to quantify.