A generic class which can take only certain types

Question: Suppose, I want to create a generic class that can take only int and double as types.
public class A<T> where T: int, double
{
    public T property{get;set;}
}

For instance:
A<int> i = new A<int>();
i.property = 10;

A<double> d = new A<double>();
d.property = 0.01;

but, this is not working.
How can I do that?
Is there any other way I can address my specific requirement?
Comment: You can't - how would you do anything with `property` within `A`?
Answer: There's no such constraint exists in C#. But for value type you can use struct as generic constraint. It will only allow non-nullable value types.
public class A<T> where T : struct
{
    public T property;
}

You can add a runtime type checking in constructor:
public class A<T> where T : struct
{
    public T property;
    public A()
    {
        if(typeof(T) != typeof(int) || typeof(T) != typeof(double))
        {
            throw new InvalidConstraintException("Only int or double is supported");
        }
    }
}

Comment: Using runtimechecks for generics feels wrong to me. Not downvoting, only stating my oppinion here.
Comment: can we use explicit constructors to achieve this?
Comment: You can put a check in constructor for typeof(T) but that will be runtime check not compile time.
Comment: I would put the check in a static constructor instead, `static A() { if … }`.
Answer: You could write your own Wrapper and use a basic interface for them. For example:
public class Integer : IMyNumber
{
    public int Value { get; set; }

    public Integer() { }
    public Integer( int value ) { Value = value; }

    // Custom cast from "int":
    public static implicit operator Integer( Int32 x ) { return new Integer( x ); }

    // Custom cast to "int":
    public static implicit operator Int32( Integer x ) { return x.Value; }

    public override string ToString()
    {
        return string.Format( "Integer({0})", Value );
    }
}

public interface IMyNumber
{
    // nothing needed
}

Then you can write your generic class:
public class A<T> where T : IMyNumber
{
    public T property;
}

And you can use it:
A<Integer> i = new A<Integer>();
i.property.Value = 10;

Comment: The `Integer` type could also be a `struct`. In that case I would remove the `set;` accessor from the property (you can still assign to its underlying `readonly` field in the constructor).
Answer: You can add private constructor to A<T> class and declare two corresponding classes: A_int and A_double inside it to have possibility to inherit them from A<T> - they become "friendly" to A<T>. But for classes declared outside that scope(Test class) it won't possible as well as for direct creation due to private constructor, which we have to invoke, but can't. So, practically, you will have only two usable variants of A<T> complimented with compile time notifications of not allowed usages:
public class A<T> where T : struct
{
    //constructor surely can have arguments
    private A()
    {
    }

    public T property { get; set; }
    //and other common stuff

    //each class declaration below we can treat like "where" constraint
    public class A_int : A<int> { }
    public class A_double : A<double> { }
}

//compile time error:
//'A<bool>.A()' is inaccessible due to its protected level
public class Test : A<bool>
{
}

Usage:
using static NameSpaceName.A<int>;
//you should not care about <int> - it is only needed for compiler
//and won't have any influence

var intVar = new A_int();
var doubleVar = new A_double();

//compile time error:
//'A<decimal>.A()' is inaccessible due to its protected level
var decimalVar = new A<decimal>();

Comment: If you want to make sure no-one outside class `A<>` inherits from `A<>`, just make sure all non-static constructors are private. You have not written any constructors above, so you get an automatic "default" constructor that is `protected`. To avoid that, just add `A() { }` inside the class, a private instance constructor.
Answer: You can acchive this by using a workarround with static methods and making the constructor internal.
However this only works if A<> is in a different Library. If everything is in the same library, this solution wont work.
public class Program
{
    public static void Main()
    {
        var a = A.CreateDecimal();
        a.property = 7;
    }
}

public class A<T>
{
    public T property;
    internal A()
    {
    }
}

public static class A
{
    public static A<decimal> CreateDecimal() => new A<decimal>();
    public static A<int> CreateInt() => new A<int>();
}

Answer: To my understanding of the C# generics, you have several "modes" in which you can setup your generics:

Without specifying what the generic parameter is i.e. open to every type, primitive etc.
With specifying a filter such as where T : class or where T : BaseClass or even where T : ISomeInterface in which you specify that the passed in type must, strictly be a class, a class that inherits from BaseClass or a type that implements ISomeInterface respectively.

To my knowledge there is no way of limiting to which structs or primitives you can use. Probably your best bet would be to create separate implementations using the primitive types you want to use. Alternatively you could create a constructor that checks if the passed in type matches the allowed type and if not throw an exception.
public class MyGenericClass<T>
{
    public MyGenericClass()
    {
        if(typeof(T) != typeof(int)) throw new Exception("You have passed an invalid type");
    }
}

Hope this helps.
Comment: `typeof(T) is int` is illegal. A type object of type `System.Type` can never be an `int` (inheritance `object` -> `System.ValueType` -> `int`, and the latter is sealed because it is a value type). You can ask if `typeof(T) != typeof(int)` instead.
Comment: correct, I was typing this in the browser so I lacked the corrective power of VS. I'll update the code above to reflect that
Answer: If your only goal is to prevent A from being used with anything other than an int or deouble, this will work.  The XML comment can at least tell potential developers they are limited.
///
/// T can only be an int or double or will throw an exception on construction.
///
/// <typeparam name="T">Must be int or double.</typeparam>
public class A<T>
{
    public A()
    {
        if (!(property is int || property is double))
            throw new Exception("A can only work with int and double");
    }
    public T property  { get; set; }
}


Dnsmasq Configuration for OpenVPN

Question: I'm trying to configure an OpenVZ VPS running Debian 6 to run OpenVPN. I've got OpenVPN running, and I can connect to it, but my traffic isn't passing through yet. I get an error when dnsmasq start, and I'm not sure how to resolve it. Here's the error that I get.
dnsmasq: failed to bind listening socket for 10.8.0.1: Address already in use failed!

Here's the output of netstat -ap.
user@lenwood:/usr# netstat -ap
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 *:microsoft-ds          *:*                     LISTEN      1341/smbd
tcp        0      0 localhost:submission    *:*                     LISTEN      1459/sendmail: MTA:
tcp        0      0 *:netbios-ssn           *:*                     LISTEN      1341/smbd
tcp        0      0 *:www                   *:*                     LISTEN      1401/apache2
tcp        0      0 10.8.0.1:domain         *:*                     LISTEN      1381/named
tcp        0      0 lenwood.com:domain       *:*                     LISTEN      1381/named
tcp        0      0 127.0.0.2:domain        *:*                     LISTEN      1381/named
tcp        0      0 localhost:domain        *:*                     LISTEN      1381/named
tcp        0      0 *:ssh                   *:*                     LISTEN      1476/sshd
tcp        0      0 localhost:smtp          *:*                     LISTEN      1459/sendmail: MTA:
tcp        0      0 localhost:953           *:*                     LISTEN      1381/named
tcp        0    240 lenwood.com:ssh          cpe-64-68-125-178:54763 ESTABLISHED 5316/0
tcp6       0      0 [::]:domain             [::]:*                  LISTEN      1381/named
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN      1476/sshd
tcp6       0      0 localhost:953           [::]:*                  LISTEN      1381/named
udp        0      0 10.8.0.1:domain         *:*                                 1381/named
udp        0      0 lenwood.com:domain       *:*                                 1381/named
udp        0      0 127.0.0.2:domain        *:*                                 1381/named
udp        0      0 localhost:domain        *:*                                 1381/named
udp        0      0 lenwood.com:netbios-ns   *:*                                 1337/nmbd
udp        0      0 lenwood.com:netbios-ns   *:*                                 1337/nmbd
udp        0      0 127.0.0.2:netbios-ns    *:*                                 1337/nmbd
udp        0      0 127.0.0.2:netbios-ns    *:*                                 1337/nmbd
udp        0      0 *:netbios-ns            *:*                                 1337/nmbd
udp        0      0 lenwood.com:netbios-dgm  *:*                                 1337/nmbd
udp        0      0 lenwood.com:netbios-dgm  *:*                                 1337/nmbd
udp        0      0 127.0.0.2:netbios-dgm   *:*                                 1337/nmbd
udp        0      0 127.0.0.2:netbios-dgm   *:*                                 1337/nmbd
udp        0      0 *:netbios-dgm           *:*                                 1337/nmbd
udp        0      0 *:openvpn               *:*                                 3369/openvpn
udp6       0      0 [::]:domain             [::]:*                              1381/named
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   PID/Program name    Path
unix  2      [ ACC ]     STREAM     LISTENING     1408905812 1361/saslauthd      /var/run/saslauthd/mux
unix  6      [ ]         DGRAM                    1408905918 1369/syslogd        /dev/log
unix  2      [ ACC ]     STREAM     LISTENING     1408907150 1459/sendmail: MTA: /var/run/sendmail/mta/smcontrol
unix  2      [ ]         DGRAM                    1436674630 5316/0
unix  2      [ ]         DGRAM                    1408908858 1488/xinetd
unix  2      [ ]         DGRAM                    1408907081 1459/sendmail: MTA:
unix  2      [ ]         DGRAM                    1408906063 1381/named

Can anyone point me in the right direction? Thanks in advance.
Comment: What do you mean by "traffic isn't passing through yet"? Can you ping 10.8.0.1 from a connected VPN client? If not it's probably a firewall issue. Posting the output of `iptables -nvL` would help to debug that.
Answer: tcp        0      0 10.8.0.1:domain         *:*                     LISTEN      1381/named

It looks like bind is listening on that socket, which is why dnsmasq can't start. You need to configure bind to only listen on specific IP addresses, with something like the following in named.conf:
listen-on { 184.108.40.206; };

Comment: BIND was listening on all addresses before, so it's more restrictive. Unless you don't want BIND to be externally accessible (i.e. you're only using it internally) you need it to listen on the external IP.
Comment: This solved it. Thank you! I set the listen-on option to listen to the external IP address, now everything works. Is it any kind of security risk for BIND to be listening to an external IP address?
Answer: What's the network scheme and configs?
If traffic won't route via tunnel, you surely won't get DNS answers (or whatever traffic you need).

Dnsmasq Configuration for OpenVPN


Lilypond acciaccatura slur position

Question: Lilypond issue: I'm trying to get the slurs in acciaccatura to look like this (generated in Musescore):

Notice that the slur is beneath the grace note. However, Lilypond insists on putting the slur above:

In voice one for the bar in question I have:
\acciaccatura   d8(  -4   <c a>4)  -2 -1 <g b>4 e4 \rest |

and in the second voice I have:
e2  e'4

I've tried (and failed) to find something like this in the manual and the snippets.Is it possible to move the slur?
Comment: Does \slurDown work? http://lilypond.org/doc/v2.18/Documentation/notation/direction-and-placement#the-direction-property
Comment: Why is the slur in the top picture going **between** the notes in the quarter-note chord next to it instead of just **below** the quarter-note chord?
Comment: Musescore puts the end of the slur *between* the notes of the chord, do you want to replicate that as well?
Comment: @Greg: this kind of works, the slur does go down, but the slur goes to the bottom of the chord rather than the top note (sorry for not making this need clear).
Comment: @Dekkadeci: this is a guitar notation thing. It indicates that a D should be played initially and the pull off goes to the C.
Answer: To me, the easiest change is to include \once \override Slur #'direction = #DOWN immediately preceding the \acciaccatura. This produces:

\version "2.19.82"

line = \relative c'' {
  \key g \major
  \time 3/4
  <<
    {
      \once \override Slur #'direction = #DOWN
      \acciaccatura d8-4 <c a>4-2-1 <g b>4 r4 |
    }
    \\
    {
      e,2 e'4 |
    }
  >>
}

\score {
  \new Staff \line
  \layout { }
}

Or, if the slur moving to C is a necessity, you can skip all of this and just input \slashedGrace d8-4_( <c) a>4-2-1:

line = \relative c'' {
  \key g \major
  \time 3/4
  <<
    {
      \slashedGrace d8-4_( <c) a>4-2-1 <g b>4 r4 |
    }
    \\
    {
      e,2 e'4 |
    }
  >>
}

\score {
  \new Staff \line
  \layout { }
}

Comment: Thanks, that final version does the trick. It does mess with my polyphony though – in the full version I have the two voices defined separately and then build the staff. To use this approach I have to have the two parts within the << \\ >> structure and use a silent rest in the second voice for the bars where the acciaccatura occurs.
Answer: Put _ before the ( which represents the slur.
\version "2.18.2"

{
\time 3/4
\key g \major
\acciaccatura d''8_( <c'' a'>4) <g'b'> r4
}

If Lilypond does the opposite, and curves the slur down when you want it up, put a ^ before the (.
Comment: This gives a slur down, but also leaves the acciaccatura slur in place at the top of the construct.
Answer: Thanks to everyone for the suggestions. They have helped me narrow down the issues.
I have now found a way to get the look I want:
\override Flag.stroke-style = #"grace"   d8_(-4   <c) a>4  -2 -1
   <g b>4 e4 \rest

Which generates:

Its slightly more complicated than I'd have liked, but there you go. Of course, if anyone can spot an easier solution I'd love to hear about it.
Comment: But that hasn't solved your problem: Your d'' is not an acciaccatura, but a full quaver/eighth. It's made the following stem-up chords a quaver too late. If there had been a third crotchet/quarter in that upper line, it would have straddled the bar line and the subsequent layout would have gone haywire.
Comment: True, but it is the least wrong to read (to my eyes). After far more reading of the documentation than I should have to do, I'm beginning to think that the issue is related to the way Lilypond deals with polyphony and I may have to add a temporary second voice to hold the a in the chord.
Comment: This isn't right at all, look at the position of the bass note

Lilypond acciaccatura slur position


MySQL and large pages/hugetlb performance gain in numbers?

Question: MySQL has large page/hugetlb support for InnoDB. And there's plenty of posts (example) on the topic.
But does anyone have examples of what performance changes they saw ?
I have seen other database systems gain performance from using hugetlb. Eg. a proprietary nosql distributed mmapped key-value store. The store would slow down as the mmapped file grew beyond to .5GB. It didn't degrade particularly more even at after 2 or 3GB.
The observation was along the lines of ; if we stored active user sessions, and at eg. 100 users we had 32MB of data, the read speed would be X records/sec. At 3000 users, we'd be around 1GB, and the read speed degraded to X/2. Read speed covered both hash lookup and copying data. All access was machine local, so it was memory to memory copy.
Now if the users logged out, the store's data file would remain the same, even though the key/val space would shrink back to 32MB, hashtables were rebucketed etc. But the read speed stayed at X/2, and did not climb.
It turned out to be TLB cache misses, and using hugetlb/large pages meant that the speed would stay around X even as users crept towards 10000 and the file grew larger and larger.
That's great and all. And instinct now tells me that MySQL should have the same characteristics and that enabling hugetlb/large pages But without some examples, it's a hard sale to try out.
So, has anyone tried using hugetlb/large pages for performance gain, and what was your experience (good/bad/neutral) ? I'd love to hear both what the DB sizes were and roughly what performance change, if any, you saw.
Numbers welcomed!
Comment: Here is me challenging you to run this: http://www.cyberciti.biz/tips/linux-hugetlbfs-and-mysql-performance.html on a copy of your production data on a test box and then post your performance results *:)
Answer: Not a MySQL example, but I have seen this exact behavior in Oracle:
http://www.pythian.com/blog/performance-tuning-hugepages-in-linux/
As the post points out, look at <code>/proc/meminfo</code> at the size of PageTables. If you're seeing huge waste of RAM for page tables, you might spend significant CPU time managing them.
MySQL also has some notes on how to implement it and why you would:
http://dev.mysql.com/doc/refman/5.6/en/large-page-support.html

Applications that perform a lot of memory accesses may obtain performance improvements by using large pages due to reduced Translation Lookaside Buffer (TLB) misses.


Regular expression for valid decimal or hexadecimal with prefix

Question: I use the following RegEx to validate hex/decimal numbers:
(0x)?[0-9A-Fa-f][0-9A-Fa-f]*

This correctly matches:
1234   (decimal)
0x12CD (hex)
0x12cd (hex lowercase)

However, it also allows
12CD   (hex without the 0x prefix)

Is there a way with RegEx to require the 0x prefix before allowing the hex [A-Fa-f] characters please?
Comment: Use the regex for a hex first: `0x[0-9A-Fa-f]+`, and then use another regex to match decimals.
Answer: Can you do:
\b(0x[0-9a-fA-F]+|[0-9]+)\b

This will match either hexadecimal or decimal numbers, which seems to be what you're after. It asserts that if the number is a hexadecimal value, it must be prefixed with 0x.
NOTE: the word boundaries, \b, are also important here.
Here's a link to a working example.
Comment: Thank you. That works perfectly and solves the problem in a single RegEx.


Map.emplace with multiples arguments C++ 17

Question: Using C++ 17: Having
using working_t = bool;
std::map<std::thread, working_t> _pool;

I'm trying to add a new thread to this map but I dont find the decent syntax..
class ThreadPool {
   std::map<std::thread, working_t> _pool;

   void init() {
      _pool.emplace(&ThreadPool::thread_init, this, false);
   }
   void thread_init();
};

This should add a thread to the map with false as value, but it cant compile.. Is this possible?
Comment: You are getting a particular compiler error?  Probably about copying a `std::thread`?
Comment: I'm using emplace for avoid copies. Emplace should create the types with the given arguments
Comment: Do you need the equals sign between `init()` and `{` ?
Comment: miss type, fixed
Comment: What's your use case for looking up a thread in a map? You can never have another instance of that thread.
Answer: You need:
_pool.emplace(
    std::piecewise_construct,
    std::forward_as_tuple(&ThreadPool::thread_init, this),
    std::forward_as_tuple(false)
);

... to distinguish the arguments lists for the key and the value. You will then, however, run into the issue that std::thread has no operator <, but that's for another question :)
Comment: @MrSmith it's needed more or less at all times, since `std::map` is an ordered container. I expect issues with the constness of the key as well (is a `const std::thread` usable at all?), so maybe a map is not the right container here.
Comment: @MrSmith its not particular about emplacing, but maps are sorted containers, hence the keys need to have a `<`
Comment: @MrSmith `std::thread` doesn't have `std::hash` nor `operator ==`, so no `std::unordered_map` either (unless, of course, you implement your own comparator & hasher). I don't think the two-vectors solution would have any measurable performance impact.
Comment: why is the < operator needed while emplacing?
Comment: @MrSmith because keys in `std::map` are sorted
Comment: I see.. I wanted to store the thread state, so I will create a map with the thread id and its state..
Comment: @MrSmith may I suggest two `std::vector`s, one for active threads and one for inactive ones?
Comment: @QUentin idk.. it may cost at runtime
Comment: @MrSmith If you just want to just store the thread state, having a map of thread id to state does indeed sound like a good idea. The question still remains though how you will store your threads in your thread pool.


assign multiple values to a matrix in c#

Question: is there a way to have a matrix that stores an int and a boolean at the same time?
Imagine having a matrix: matrix[x, y]
Now, is it somehow possible to do something like this?
matrix[2, 1] = 5, true
matrix[1, 5] = 2, false
The matrix simply stores an int and a boolean value at the same time.
Answer: C# 7.0 introduced a simple syntax for tuples to store multiple values in one matrix element:
var matrix = new (int, bool)[10, 10];

matrix[2, 1] = (5, true);
matrix[1, 5] = (2, false);

The example creates a 2D array of 10 times 10 tuples.
Here, (int, bool) defines tuples which consist of an int and a bool value.
It would be simpler to use two matrices in parallel, one for the integers and one for the bool values.
Comment: wow, thank you so much, that's exactly what I needed!


Como migrar para a nova versão do Realm

Question: Olá, tenho um app simples do meu site de notícias, o encontrei no GitHub há algum tempo e editei.
Porem ele deixou de funcionar em alguns dispositivos (Android 5.1 pra cima) quando foi a correção descobri que com as ultimas atualizações do Android Studio não é mais possível usar a versão do realm que eu usava

classpath 'io.realm:realm-gradle-plugin:1.2.0'

pois o android-apt ficou obsoleto e nesta versão (1.2.0) o mesmo é usado.
Tentei atualizar para a versão 4.3.3 do Realm porem o construtor utilizado na primeira vez mudou.
@Override
public void onCreate() {
    super.onCreate();
   mInstance = this;
    // init realm database
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
            .name("wordpress.realm")
            .schemaVersion(0)
            .deleteRealmIfMigrationNeeded()
            .build();
    Realm.setDefaultConfiguration(realmConfiguration);

Então preciso de ajuda para adequar o código acima nas novas formas
*Sou um aventureiro no mundo de desenvolvimento Android, não tenho formação na área toda ajuda é bem-vinda
Answer: Se você estiver se referindo a como atualizar o gradle do Android Studio você pode encontrar as informações aqui:
https://realm.io/docs/java/latest/#installation
Se você está se referindo a fazer uma migration, você precisa buscar a respeito de realm migration. Essa migration é relacionado a trocar a versão do seu banco de dados, isso ocorre mudando o schemaVersion(0) por exemplo para .schemaVersion(1) dai sua migração é necessária.
Você usou  .deleteRealmIfMigrationNeeded()
Se você muda a versao do banco com essa linha você apaga as informações da versão anterior(definida pelo schemaVersion). Então seu banco de dados fica zerado e caso você precise alguma informação prévia o app irá da crash.
O link abaixo explica como fazer um migration.
https://medium.com/@budioktaviyans/android-realm-migration-schema-4fcef6c61e82

Como migrar para a nova versão do Realm


Rotate icon around center

Question: I want to rotate this Font Awesome icon around its centre but the code i have now doesn't do that. I think it's anchor is at the top right. How do I change it to the centre?
I also want the icon to move to move to the centre of the screen when on click as its rotating.

(function ($) {
    $(document).ready(function(){

        $('.icon').on('click', function(){
            $(this).toggleClass('icon--active');
        });

        var animation = 'rubberBand';

        $('.icon').on('click', function(){
            $(this).addClass('animated ' + animation).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
            $(this).removeClass('animated ' + animation);
            });
        });

    });

}(jQuery));
button:focus {
    outline: none;
}

.icon {
    background-color: rgba(0, 0, 0, 0);
    cursor: pointer;
    position: relative;
    border: none;
    top: 50px;
    left: 1950px;
}

.fa-plus {
    color: white;
}

.icon i {
  display: block;
  position: absolute;
  -webkit-transition: -webkit-transform 0.3s;
  -webkit-transition: all 300ms ease-in-out;
  transition: all 300ms ease-in-out;
}

.icon--active{
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  position: absolute;
}
<button class="icon">

</button>
Answer: Try adding this to your CSS
 .icon i:after {
      transform-origin: center
 }

Comment: Its still the same
Answer: I just messed around you code, pls check below.
and since you're using FontAwesome icon. you dont need to really mind with rotating the icon, you can add a class fa-spin to the icon itself. You can play with making the icon to left when clicked. you can also make an if statement to remove the fa-spin class if its already in the left.
edit: for smooth transition. i dont know but it seems not working here in the snippet, maybe it'll work in the browser. pls let me know.

(function ($) {
    $(document).ready(function(){

        $('.icon').on('click', function(){
            $(this).toggleClass('icon_active fa-spin');
        });

    });

}(jQuery));
button:focus {
    outline: none;
}

.icon {
    background-color: rgba(0, 0, 0, 0);
    cursor: pointer;
    position: relative;
    border: none;
    top: 50px;
    left: 150px;
}

.fa-plus {
    //color: white;
  border:1px solid;
}

.icon i {
  display: block;
  position: absolute;
  -webkit-transition: -webkit-transform 0.3s;
  -webkit-transition: all  ease-in-out 0.3s;
  transition: all ease-in-out 1s;
}

.icon_active{
  left:0;
}

<button class="icon">
  icon
</button>

Rotate icon around center


How to create a fieldset in a node form, that expands with ajax

Question: I have a (view of a ) tasks list on a page, and also a form block where users can add a new tasks.
I want to increase page load time by hiding some fields in the tasks form block, which can expand using ajax by clicking on "task details" link (the fieldset label)
Is this is possible without programming?
Comment: I don't think this is possible without programming.
Answer: You might need to add this module.  https://www.drupal.org/project/field_group
Add those fields on the form to a field group, and set the group to start out "Collapsed".


Barra de progresso na barra de tarefas do windows c#

Question: Estou desenvolvendo um aplicativo que vai enviar email para vários clientes.
Gostaria de exibir o progresso do envio mesmo com o form minimizado.
Gostaria de fazer da mesma forma que o Windows 7 copia arquivos, em que, mesmo a janela da cópia estando minimizada, aparece na barra de tarefas do Windows a barrinha verde com o progresso.

Fiz algumas pesquisar e pelo que vi, teria que utilizar o métodoWindows7Taskbar.SetProgressValue, porém, nos testes que fiz, não atualizou o progresso!
Answer: Considerando a imagem que você postou, creio que você esteja usando o Windows 7, uma solução para seu problema seria utilizar o componente Windows 7 Progress Bar, que pode ser baixado aqui, ele é distribuído com licença BSD.
Após realizar o download adicione o componente a Toolbox, você pode fazer isso clicando com o botão direito em uma aba de sua preferência (Common Controls por exemplo) e selecionando a opção Choose Items..., na janela que abrir, na aba .NET Framework Components, clique no botão Browse... e selecione o arquivo Windows7ProgressBar.dll que está no Windows7ProgressBar\Control\bin\Release (esse diretório é referente as pastas que estão dentro do arquivo compactado) e depois clique em Ok, feito isso você terá o componente Windows7ProgressBar disponível para uso, ai basta clicar e arrastar para seu Form.
As propriedades e eventos do componente são os mesmos da ProgressBar com algumas coisas a mais, como por exemplo as propriedades: ShowInTaskbar e State.
A propriedade ShowInTaskbar indica se o progresso deve ser exibido na barra de tarefas, e a propriedade State, qual o estado do progresso (essa propriedade faz a alteração na cor do progresso para verde, vermelho ou amarelo)
Dentro do arquivo compactado, existe um exemplo utilizando C#, não vou colocá-lo aqui porque pela sua duvida o problema está relacionado com a exibição do progresso na barra de tarefas e não na utilização da ProgressBar.

Observação: considerei que você está utilizando o Visual Studio.


What is the percentage increase to any value when initial value is 0?

Question: This is a very simple maths problem, which doesn't seems simple to me when I just put some extra thoughts on it. So need to borrow some extra brains for this.
Question:
If cost of coffee in my office was Dollar 0 till yesterday and today it is Dollar 2.5 then what is the percentage increase in the cost of coffee?
Initially it seemed like 2.5% increase, simply
by distributing number from 0 to 100, but this is not the case.
Some suggested it is infinitely more than the previous value, because we are calculating percentage by dividing by zero. But what about this if the cost of coffee was $0.25? Isn't still infinitely more! Something is wrong here.
PS:
Yes, coffee were free in our office but not anymore, and we are still recovering from this shocker.
Comment: "Isn't still infinitely more!": no.
Comment: Bring your own coffee machine and sell coffee for $1.50. This will teach office management!
Comment: you can say that, in the old days, it costed $100 %$ less !
Answer: The relative increase from $a$ to $b$, which is given wrt $a$, is computed in percent as
$$100\,\frac{b-a}a.$$
Hence,

$0$ to $2.5\to100\,\dfrac{2.5-0}{0}=\infty\%$,
$0.25$ to $2.5\to100\,\dfrac{2.5-0.25}{0.25}=900\%$.
Answer: Let's say the initial cost of coffee in your office was $\$0$ per cup. Now a cup of coffee costs $\$2.5$. We could use the following formula to try to come up with the answer for the increase in the price of coffee in terms of percents:
$$
\text{cost_now}=\text{initial_cost}+\frac{\text{initial_cost}}{100}\cdot\text{percentage_change}.
$$
$$$2.5=$0+\frac{$0}{100}\cdot p\implies 0\cdot p=2.5.$$
There is no real number such that when you multiply it by zero, it gives you a nonzero quantity. I guess, one possible interpretation of this result would be that with the initial cost of $\$0$, the concept of increase/decrease in percentage does not really apply. In other words, when you're talking about the increase/decrease in the cost of something percentage-wise, you necessarily need an initial cost that's greater than zero as the basis for your calculations. If there is no initial cost, there can be no calculations.
Answer: Short answer: percent change is undefined when the starting quantity is $0$. Calling it a $2.5\%$ increase makes no more sense than calling it a $\frac{\pi^2}{\sqrt{17}}\%$ increase (why would you distribute anything on a $(0,100)$ interval?)
If you want a bit of an intuition, imagine it raised from $\$1$ to $\$1.10$. Take the starting prize, increase it by $5\%$. You are still below the current prize. Go back and increse again, this time by $6\%$ instead. You are still below. When you get to $10\%$, you stop being below the current prize.
Now start at $0$. Increase $0$ by 10%. You are below the current prize. Now try $20\%$, $50\%$, $1,000,000\%$. You still haven't reached the current prize, and you never will. Therefore if makes sense to talk about an "infinitely big percentage increase"
Comment: price, not prize
Answer: $$\text{margin}=1-({1\over {1+\text{markup}}}) $$ Or equivalently,$$\text{markup}= ({1\over {1-\text{margin}}})-1$$ where markup and margin are written in decimal form (0.25=25% etc.). If we have 100% margin (1 in decimal), then we hit a division by 0 error.  It's undefined if the margin comes from simply setting a price after having it at 0.


Javascript form validation. How to use external .js validation script

Question: I'm having trouble with Javascript form validation. I don't know how to use the external .js script with validation rules and insert them into a html file and get them working.
I have linked the script in the head section like this:
This is what's in the .js validation script
<code>  function IsValid4DigitZip( str )
    if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
        return false;

    var isValid = true;

    str += "";

   if (IsBlank(str) || (str.length != 4) || !IsInt(str, false))
        isValid = false;

   return isValid;
}
</code>
I tried inserting it into the  section as follows
<code>    function IsValid4DigitZip(document.orderbooks.Postcode) {

    if (document.orderbooks.Postcode.value+"" == "undefined" || document.orderbooks.Postcode.value+"" == "null" || document.orderbooks.Postcode.value+"" == "")
        alert("Invalid Postcode !")
        return false;

    var isValid = true;

    document.orderbooks.Postcode += "";

   if (IsBlank(document.orderbooks.Postcode) || (document.orderbooks.Postcodestr.length != 4) || !IsInt(document.orderbooks.Postcode, false))
        alert("Invalid Postcode!")
        isValid = false;

   return isValid;
}
</code>
orderbooks is my form name in my html and Postcode is the name attribute I want to validate using javascript..
What am I doing wrong?
Comment: You do not modify the existing function - you need to pass your data into it and capture the return to further process it. [Here is some basic reading to do](https://www.w3schools.com/js/js_function_parameters.asp). You also mention your HTML but it doesn't seem to be added to the question which makes it only more difficult to answer.
Comment: I don't get it :( Sorry I am new to this. Can you show me and example?  How do I pass the data and capture it?
Answer: Since you already have the zip code validation function, you just have to call it for form data.
<code>if ( IsValid4DigitZip(document.orderbooks.Postcode.value) ) {
  // Zip code is valid
} else {
  // Zip code is invalid
}
</code>
Comment: But wait! There is more! `orderbooks is my form name in my html and Postcode is the name attribute` is the part that made me realize how much broader this "question" is and how answering it is impossible without explaining a large chunk of JS and HTML.
Comment: I just uploaded my html can you take a look and get back to me?
Comment: Don't see any html


TS/JS break iterative function with for loop inside

Question: I'm having an issue to break an iterative loop and return false if a condition was met.
What I'm trying to do actually is to check if a reactive form is empty :
<code> public isEmpty(form: AbstractControl): boolean {
    if (form instanceof FormGroup) {
      for (const key of Object.keys(form.controls)) {
        if (key !== 'modalite') {
          const control = form.get(key);
          if (control instanceof FormGroup) {
            this.isEmpty2(control);
          } else {
            if (control.value && control.value !== '') {
              return false;
            }
          }
        }
      }
    } else {
      if (form.value && form.value !== '') {
        return false;
      }
    }

    return true;
  }
</code>
The problem is that my return false is breaking the for loop but keeps iterating after, so I'm always returning true. What I want to do is that if one formcontrol is not empty I want to return false and break the for loop and the iterative funtion. Thank you.
Comment: I don't see how your `return false` could fail to break out of the entire function.  Is the problem perhaps that `this.isEmpty2(control);` should be replaced with `if (!this.isEmpty2(control)) return false;` ?  Have you tried stepping through the code with a debugger or adding `console.log` statements to trace what is happening?
Answer: I think, it would be better to use required validator instead of iterating over your controls.
<code>const control = new FormControl('', Validators.required);
console.log(control.value);      // ''
console.log(control.status);     // 'INVALID'
</code>
See: https://angular.io/api/forms/FormControl
Comment: I'm checking if my form and subforms values are empty not if they are valid. Not all of my controls are required.
Comment: you can add **required** just on controls whose need it.
What's your goal by checking if they are empty or not ?
Comment: I have a button that user click, and if he has some inputs in the form, he gets a modal saying that he is gonna lose everything he typed in the form. But I don't want that modal to show if user didn't type anything in the form.


hook_mail_alter() doesn't remove the Return-Path, Sender, and Reply-To headers

Question: I want to remove the Return-Path, Sender, and Reply-To headers from the sent emails. I am trying to achieve this using the following code, but the headers aren't removed from the email.
function mymodule_mail_alter(&$message) {
  unset($message['headers']['Return-Path']);
  unset($message['headers']['Sender']);
  unset($message['headers']['Reply-To']);
}

We are using default PHP mailer of Drupal 8 and the SMTP module . We are trying to fire the Test Mail via the SMTP module after entering credentials. But it seems we are not able to modify the headers from hook_mail_alter().
What am I doing wrong?
Comment: So much left unsaid ... such as what @Mail plugin(s) you're using.
Comment: We are using default PHP mailer of Drupal 8 and the SMTP module . We are trying to fire the Test Mail via the SMTP module after entering credentials. But it seems we are not able to modify the headers from hook_mail_alter
Answer: Removing the values from $message['headers'] isn't sufficient, as the plugin  used to send emails could also use $message['Return-Path'], $message['Sender'], or $message['Reply-To'] value to build the email headers. The class that is used as default plugin to send emails, PhpMail uses the following code, but other plugins could use different code.
$site_mail = $this->configFactory->get('system.site')->get('mail');
$additional_headers = isset($message['Return-Path']) && ($site_mail === $message['Return-Path'] || static::_isShellSafe($message['Return-Path'])) ? '-f' . $message['Return-Path'] : '';
$mail_result = @mail($message['to'], $mail_subject, $mail_body, $mail_headers, $additional_headers);

Since the email plugin is used to send the email after the hook_mail_alter() implementations are invoked, and since the email plugin can add one of those headers to its discretion, there isn't any warranty the email is sent without those headers. Assuming the email plugin adds only those headers when $message or $message['headers'] contains a value for them, the following code should work.
function mymodule_mail_alter(&$message) {
  unset($message['Return-Path']);
  unset($message['Sender']);
  unset($message['Reply-To']);
  unset($message['headers']['Return-Path']);
  unset($message['headers']['Sender']);
  unset($message['headers']['Reply-To']);
}

Comment: I'd like to add that the RFC says headers are case insensitive, so for example "unset($message['headers']['Return-Path']);" is insufficient - the header key could be "return-Path", so your unset wouldn't do anything. Likewise, the @Mail plugin could be assuming a certain casing, so even if the plugin tried to respect your choice the case you use could trip it up. Bottom line is what apademo said above: "Since the email plugin is used to send the email after the hook_mail_alter() implementations are invoked ... there isn't any warranty the email is sent without those headers."
Answer: The SMTP module always sets certain headers which cannot be unset. See the following lines from  Drupal\smtp\Plugin\Mail\SMTPMailSystem:
$headers['Sender'] = $from;
$headers['Return-Path'] = $from;
$headers['Reply-To'] = $from;

This is to make it compatible with Drupal core which does the same from what I can tell.
For more control, you can use the module PHPMailer SMTP instead which explicitly unsets the Return-Path header to comply with RFC 5321.
It also makes no assumptions about which extra headers should be present (beyond the required ones) and only sets them if they are added elsewhere.
The following would work if the case of the headers match:
function mymodule_mail_alter(&$message) {
  unset($message['headers']['Sender']);
  unset($message['headers']['Reply-To']);
}

Alternatively, the following would unset headers regardless of case:
function mymodule_mail_alter(&$message) {
  $message['headers'] = array_change_key_case($message['headers']);
  unset($message['headers']['sender']);
  unset($message['headers']['reply-to']);
}

Disclaimer: I am the author of PHPMailer SMTP.
Answer: Use function hook_mail($key, &$message, $params) instead. Also, you would need additional $key I believe to distinguish for which functionality is the mail being sent.
Then this hook would be triggered when sending the mail manually:
$send = true;
$mailManager = \Drupal::service('plugin.manager.mail');
$result = $mailManager->mail($module, $key, $to, $langcode, $params, null, $send);

I would suggest using Swiftmailer, it omits all of the manual work.
Comment: I take the OP wants to remove those headers from every email. `hook_mail()` would not help with that.
Comment: Even if the OP wanted to remove the Return-Path, Sender, and Reply-To headers from the email sent by a module the OP wrote, or by a specific module, this answer doesn't say how to achieve that.


Joining a table on itself for different criteria

Question: So I have a table, at it's base is the following structure:

WorkOrder
SubOrder
Status
StatusDate
Type
Category

(There are other things, but we're ignoring them for the sake of the question)
I'm filtering for a certain subset of type/category, and I know how to do that.  But what I need to come out is the following
WorkOrder | SubOrder | Type - Category | Min(StatusDate) where Status = Open | Min(StatusDate) where Status = Complete | Calculated Date Difference between the two

I can get one at a time and that's no issue.  Ror the time being, I've just been monkeying with it in Excel.  I need to however get this into a SQL statement for a report I need to start generating.  There may or may not be a StatusDate with the status Complete (if the SubOrder has not been marked complete elsewhere), and the dataset needs to reflect that as well.  There could be multiple times that each SubOrder was opened and completed, so we just need the first (hence the Min())
Any ideas on how I should approach this task? (And no, changing the data structure is not allowed, OTS software, and we're not paying to change it)
Answer: I'm not sure that I understand why you would need to join the table to itself.  It sounds like you just want
SELECT WorkOrder,
       SubOrder,
       Type,
       Category,
       min( case when Status = 'Open'
                 then StatusDate
                 else null
             end) min_open_status_date,
       min( case when Status = 'Complete'
                 then StatusDate
                 else null
             end) min_complete_status_date,
       min( case when Status = 'Complete'
                 then StatusDate
                 else null
              end) -
         min( case when Status = 'Open'
                   then StatusDate
                   else null
                end)
  FROM table_name
 WHERE <<whatever conditions>>
 GROUP BY WorkOrder,
          SubOrder,
          Type,
          Category

If that is not what you are looking for, it would be very helpful to edit your question post the DDL to create the table, the DML to populate some rows, and tell us exactly what output you want for that sample data.  Or create a fiddle on sqlfiddle.com.  Otherwise, we have to guess at what you want.  For example, you say that you want to calculate the difference between two dates but one of the two dates may not exist-- do you want to use some baseline date for the calculation if there is no closed date?  This query will return NULL for the calculated difference which may or may not be what you want.
Comment: This actually has it all that I need, and is doing it perfectly.  Only issue I'm still having is that no matter how I write a WHERE based on my need to limit the StatusDates for open statuses, it won't work.  Ideas?
Comment: @danielw-msu - I'm afraid I don't understand what you're asking.  This is probably where you'd need to edit your question to include DDL and DML that would let us replicate the problem on our systems (or create a fiddle on sqlfiddle.com).  Show us with sample data where the query I posted isn't doing what you want.
Comment: I got it taken care of, I was making a stupid mistake.  Thanks for all of your help.


Script PHP para contar registros separados por virgulas

Question: No bando de dados eu tenho uma coluna que recebe strings nesse formato: ["87","12","67"]
O que eu preciso é contar cada valor separado por virgula e atribuir a alguma variável, lembrando que existem mais linhas. Nesse caso eu teria uma variável com o valor 3.
Meu código não evoluiu muito, mas creio que esse seja o caminho:
$conexao = mysqli_connect('localhost','root','');

$banco = mysqli_select_db($conexao,'bd');

mysqli_set_charset($conexao,'utf8');

$res = mysqli_query($conexao,"SELECT  replace(replace(coluna,'[',''),']','') FROM tabela");

$var = array($res);

echo count($var);

Conto com a ajuda da comunidade.
Answer: O formato ["87","12","67"] é um formato de JSON válido, então você pode usar o json_decode.
$conexao = mysqli_connect('localhost','root','');
$banco = mysqli_select_db($conexao,'bd');
mysqli_set_charset($conexao,'utf8');

$res = mysqli_query($conexao,"SELECT coluna FROM tabela");

while($r = mysqli_fetch_assoc($res)) {
      echo "Quantidade: ". count(json_decode($r['coluna'], true));
}

Comment: +1, bem simples e direto


Iterate through folders and extract shapefiles to a geodatabase in python

Question: Hi I am using sample data. In a folder called Shapefile, I have 3 folders; each one has 3 shapefiles named Hazard1.shp, Hazard2.shp, Hazard3.shp (there are about 3000 records in each). I am trying to iterate through each of these folders and extract Hazard1.shp from each folder and merge it into a feature class in a geodatabase called totals. This code is meant for hundreds of folders but I am using a sampling of 3. I run my code, with no errors but when I check totals there are only 3000 records - from the merge there should be 12,000. What am I doing wrong?
import os, arcpy.da

print os.getcwd()

for dirname, dirnames, filenames in os.walk('.'):
    for subdirname in dirnames:
        current_dir =  os.path.join(dirname, subdirname)
        arcpy.env.workspace = current_dir
        fcList = arcpy.ListFeatureClasses("Hazard1.shp")
        destination = r"F:\Extraction\GeoDatabase\Total.gdb\totals"
        for fc in fcList:
            print fc
            arcpy.Merge_management(fc,destination)
        break

Answer: You are overwriting your 'totals' feature class each time you iterate a folder. You should either:

create an empty list outside the loop and append fc to it each time you iterate, then merge all items in this list.
Or, more simply, use Append instead of Merge (if 'totals' already exists).
Answer: add:
Merge = r"F:\Extraction\GeoDatabase\Total.gdb\totals_Merge"

Then your for loop should be:
    for fc in fcList:
        print fc
        arcpy.Merge_management([fc,destination],Merge)
        arcpy.Delete_management(destination)
        arcpy.Rename_management(Merge, destination)


asp.net listbox on selectindexchanged doesn't fire an event

Question: <asp:ListBox ID="list1" runat="server" Height="200" Style=" margin: 0"   OnSelectedIndexChanged="list1_SelectedIndexChanged">
            <asp:ListItem Selected="True" Value="1">1</asp:ListItem>
            <asp:ListItem Value="2">2</asp:ListItem>
            <asp:ListItem Value="3">3</asp:ListItem>
            <asp:ListItem Value="4">4</asp:ListItem>
        </asp:ListBox>

i have listbox in the updatePanel
but when i select something it doesn't fire an event what am doing wrong?
Answer: You need to Set AutoPostBack Property to True.  then only Postback happens and your selected index event will fire.
<asp:ListBox AutoPostBack="true" ID="yourLIst" runat="server" Height="200" Style=" margin: 0"   OnSelectedIndexChanged="yourLIst_SelectedIndexChanged">

Answer: You have to set AutoPostBack to true (default is false):
<asp:ListBox AutoPostBack="true" ID="list1" runat="server" Height="200" Style=" margin: 0"   OnSelectedIndexChanged="list1_SelectedIndexChanged">
   ....

Also note that you have to databind the ListBox only on the initial load not on every postback, so use the IsPostBack property to check it:
protected void Page_Load(Object sender, EventArgs e)
{
    if(!IsPostBack)
        DataBindListBox();
}


JNI stdout is not print to the console

Question: I use JNI because I need some c libraries.
My problem is that not all is printed to the stdout.
I know I can do
puts("test");
fflush(stdout);

by myself. But my problem is that the c library has a debug function which prints to the stdout and therefore is not visible in the console. How can I solve this?
Answer: You cannot write to stdout because JNI runs the native code from within the Java code, and is not attached to the stdout.
You  can use the following function to write directly to the console device.
void console_printf(const char *fmt,...)
{
    int fd = open("/dev/console", O_WRONLY);
    char buffer[1000];
    if (fd < 0)
        return;

    va_list ap;
    va_start(ap, fmt);
    vsprintf(buffer, fmt, ap);
    va_end(ap);

    write(fd, buffer, strlen(buffer));
    close(fd);
}

JNI stdout is not print to the console


Error on installing module

Question: I've got Drupal 7.20 on my server (skyislands.pl). I wanted to install (from my local computer) Wysiwyg module (http://drupal.org/project/wysiwyg), but I see this error. My server is running on EHCP. How can I solve this problem ?
Thanks for any help,
Answer: It is a permissions problem. You will be able to install the module by downloading it and putting it into your sites/all/modules folder
Comment: extracted, so the path to the module info file is sites/all/modules/wysiwyg/wysiwyg.info
Comment: Should I change permissions of sites/all/modules ?
Comment: I am not sure, I don't use the automatic module download thing that is in Drupal 7. I always just download modules and copy them across, or use drush.
Comment: Ok, Should I send extracted archive or don't extracted ?

Error on installing module


Does it make sense to use variance to describe non normal distributions?

Question: I would like to know if it makes any sense to use the variance or standard deviation to describe non gaussian distributions
Comment: Yes - for example you can then use Chebyshev's inequality
Comment: The variance does not "describe" the Normal distribution but is one of its parameter. In that sense, the variance better describes distributions with a single parameter like the Bernoulli or the Exponential or the $\chi^2$ distributions.
Answer: Yes, the variance can still be a useful descriptor for non-Gaussian distributions, but it will also depend on your goal. For example, a Gaussian distribution is uniquely characterized by its mean and variance (i.e. if we know the mean and variance, then we know everything about the distribution), and this is true for some others, but certainly not all distributions.
Answer: You can compute many statistics for many distributions. They have a used.
Some of the most common ones include:

Quantiles
moments (including mean and variance)
Extreme values

If I rearrange this list it is still useful:

measures of central tendency.
measures of tendency of variation or spread
Measures of other geometric tendencies.
Ordered measures vs moments

You can see how under the heading of the measures of Tendency of variation, also called measures of tendency of spread, the variance could be quite useful. In fact, being a moment, it is not necessarily derived or contingent on a distribution being normally distributed.


Extensibilidade V10 erro evento DepoisDeAbrirEmpresa ao abrir CustomForm

Question: Com a ultima atualização do PRIMAVERA este código Demo que estava a funcionar anteriormente, no evento abrir empresa, deixou de funcionar.
using (var result = BSO.Extensibility.CreateCustomFormInstance(typeof(FDU_GuiaEntrada)))
{
    if (result.IsSuccess())
    {
        (result.Result as FDU_GuiaEntrada).Show();
    }
}

Erro:

Object reference not set to an instance of an object.

Existe outra forma de mostrar um CustomForm ?
Comment: A ideia é chamar o formulário sem ser via código?
Comment: Olá Rui, não vai funcionar essa tentativa de abrir um form nesse evento, a shell do erp ainda não foi totalmente carregada para suportar o form. Qual a finalidade de abrir um form nesse evento?
Comment: Existem, pelo menos, duas formas de abrir um customform: (1) Usando esse mesmo código a ser executado pela chamada de uma função de utilizador do tipo "Macro Extensibilidade"; (2) Criando uma função de utilizador do tipo "Formulário do Utilizador". Ambas as funções podem depois ser colocadas num menu do utilizador.
Comment: Existe a necessidade de abrir um form de utilizador ao abrir empresa
Answer: Boa tarde
Pelo que consegui apurar trata-se de é um erro da ultima publicação do ERP PRIMAVERA e deve ser disponibilizada correcção.


UNIX Crop multiple files from dynamic position

Question: I have a directory containing a huge amount of html files
I know that in order to find the starting point i have to use the following command
grep -n -m1 "/header" filename.html| cut -d':' -f1

and to find the end point of my crop i have to use this one
grep -n -m1 "footer" 39646_20160820.html | cut -d':' -f1

My question is: how can i crop all files in a directory using these two criteria for each file to have the start and the end of the crop of each file?
Answer: To remove all lines between /header and footer for all files in the current directory:
sed -i.bak '\|/header|,\|footer|d' *

The expression \|/header|,\|footer| defines a range of lines that start with a line that contains /header and ends with a line that contains footer.  The command d tells sed to delete all lines in such a range.
* is a glob which refers to all files in the current directory.  If you don't want to operate on all files, change this glob.
Example
Consider this test file:
$ cat File
1
/header
2
footer
3

To remove all lines starting with a line that contains /header and ending with a line containing footer and display the result to stdout:
$ sed '\|/header|,\|footer|d' File
1
3

To update all files in the current directory in-place:
$ sed -i.bak '\|/header|,\|footer|d' *

To verify that this worked:
$ cat File
1
3

Backup files
The above command creates backup files with the extension .bak.  If you are confident that the command does the right thing and you do not want backup files, then use:
sed -i '\|/header|,\|footer|d' *  # GNU/Linux

Or:
sed -i '' '\|/header|,\|footer|d' *  # OSX/BSD

Keeping the range instead of deleting it
To keep the range, deleting all else:
sed -n '\|/header|,\|footer|p' *

For example, on our sample file:
$ sed -n '\|/header|,\|footer|p' File
/header
2
footer

To save the changes to the file in-place:
sed -ni '\|/header|,\|footer|p' *  # GNU/Linux

Or:
sed -ni '' '\|/header|,\|footer|p' *  # OSX/BSD

Comment: The scope is the opposite, i need to keep what's inside the two tags, and remove all the rest
Answer: This solution generates a list of the filenames with the header and footer line numbers - the generated list is used to construct a sed command run inside a loop to crop the files - the cropped file is created in a new directory called destdir - I assume the header and footer markers cannot be nested
files=$*
mkdir destdir
#grep header and footer line numbers with filename
grep -Hn -m2 -e'/header' -e'footer' $files|
# join pairs of consecutive lines to get header and footer line numbers on one line
sed -n 'N; s/\n/:/;p'|
# remove header and footer pattern matches and duplicate filename
cut -d: -f1,2,5|
# construct sed command to crop file
while IFS=: read file beg end; do
  echo $file
# remove what's between header and footer
#  sed "$beg,${end}d" $file >destdir/$file
# keep what's between header and footer
sed -n "$beg,${end}p;${end}q" $file >destdir/$file
done

Comment: It freezes before the cut -d: -f1,2,5|
I tried removing some files, but even with 4 files, it still freezes in that part...
Comment: How do you know it freezes before cut? What's the commandline you used to run the script? To debug build the pipeline one command at a time and check output, i.e. first the grep then add the sed then add the cut etc
Comment: I edited the code to show both sed commands for cropping inside or outside the block - use one or the other as you need


Drush equivalent setup on Windows?

Question: One of my clients insists on using WAMP for hosting Drupal 7. I've always been using Ubuntu for development, but now I have to work with WAMP. I do much Drush administration with sql-dump and modifying Drupal from the command line. I tried Drush on windows, but it is PITA to use.
What are some ways to use Drush as close as possible to the Linux versions? For some reasons, some Drush commands don't properly work on Windows. I usually use drush sql-dump > backup.sql, but in Windows there is no equivalent to that.
Comment: I am using xampp (which I don't think that does make any huge difference in relation to wamp) on windows 7 and `drush sql-dump > backup.sql` works very well (Drush version 5.8). Actually I don't think that drush is lacking to anything when is used on windows. You don't even need Cygwin to install it and make it run. I'll post a detailed answer later if I have the time.
Comment: That doesn't work. I get the following error: C:\sites\tmsample>drush sql-dump > adsf.sql
mysqldump: Couldn't execute 'SET OPTION SQL_QUOTE_SHOW_CREATE=1': You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_QUOTE_SHOW_CREATE=1' at line 1 (1064)
Database dump failed                                                                                [error]
Comment: Check this [post](http://dba.stackexchange.com/questions/42321/issue-on-mysqldump-in-mysql5-6), seems to be the case. Your MySQL version does not support the `SET OPTION SQL_QUOTE_SHOW_CREATE=1;`,  read [this](http://bugs.mysql.com/bug.php?id=66765) for more details.
Answer: There are four possibilities:

Using Git Bash for Drush. Off the top of my head, this won't work for SQL commands, though
If you're using Windows 10, you may want to install the anniversary edition update. It gives a Linux bash shell. It also has its limits (no kernel modules), but those limits shouldn't impede Drush use
CYGWIN. It may take some fiddling, but may do the trick too
Try and persuade your client to use Vagrant, then run Ubuntu in there
Comment: 5. You can also install it via composer (for windows) and than set it into global enviroment.
6. Installing Acquia Dev Desktop also contains a working drush and a maybe working composer.

Drush equivalent setup on Windows?


How do you refer to an xml node that has two namespace definitions?

Question: I have an xml message from a 3rd party that has a node:
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:npfitlc="NPFIT:HL7:Localisation"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
classCode="DOCCLIN" moodCode="EVN">

I created a Namespace object to use to identify npfitlc items under this node:
ns.AddNamespace("npfitlc", "NPFIT:HL7:Localisation");

But when I try to choose the ClinicalDocument node it can't find it:
XmlNode myNode = soapEnvelop.SelectSingleNode
        ("//soap:Envelope/soap:Body/itk:DistributionEnvelope/itk:payloads/itk:
        payload/ClinicalDocument", ns);

As you can see in my doc there are multiple nodes to get to Clinical Document. And when I reference down to itk:payload it locates it fine:
XmlNode myNode = soapEnvelop.SelectSingleNode
       ("//soap:Envelope/soap:Body/itk:DistributionEnvelope/itk:
       payloads/itk:payload", ns);

I took out xmlns="urn:hl7-org:v3" from the ClinicalDocument tag and then I could find it find with my SelectSingleNode call, but the system I sent the message to fails validation because that is missing.
I am not sure how to handle it where there is a "root" namespace defined in that node.
Answer: ClinicalDocument has no prefix and it has an xmlns="urn:hl7-org:v3" namespace declaration, which means that its namespace is urn:hl7-org:v3. The rest of the namespace declarations there are completely irrelevant for the purpose of selecting this particular element.
So what you need to do is...
Add that namespace to your namespace manager (using any nonempty prefix):
ns.AddNamespace("hl", "urn:hl7-org:v3");

Use that prefix in your XPath:
XmlNode myNode =
    soapEnvelop.SelectSingleNode("//soap:Envelope/soap:Body" +
                                  "/itk:DistributionEnvelope/itk:payloads" +
                                  "/itk:payload/hl:ClinicalDocument", ns);

and that should do it.
Comment: Thanks. I was wanting to add it in the namespace but new it had to have a key value. I never thought I could just make a prefix up,


How to get python script file path that has been compiled in binary .exe?

Question: I have python script myscript.py that I compiled with pyinstaller with the following command: pyinstaller -F myscript.py . Now I get a file called myscript.exe  . In my script, there are line that I wrote to get the path of this file using the following code:
this_file = os.path.realpath(__file__)
src = this_file
filenameOnly, file_extension = os.path.splitext(src)
exeFile = filenameOnly+'.exe'
print ('exe file to check', exeFile)
if os.path.exists(exeFile):
    src = exeFile
print ('Binary file', src)

But this works well only if the .exe file is having the same name as the initial .py file. If I rename the binary file, my script will not detect that change
Answer: I would suggest using sys.argv to access command line parameters. The first value in sys.argv is the name of the program. e.g:
...
filenameOnly = sys.argv[0]
exeFile = filenameOnly + '.exe'
...

Here are some related stackoverflow links for further reading on this subject.
sys.argv[1] meaning in script
How to input arguments after compiling python program with PyInstaller
Answer: I solved the problem with src = sys.executable


Show that $\sum\limits_{p = 0}^k\sum\limits_{r = 0}^{k-p} a_{k-p-r}b_rc_p = \sum\limits_{r = 0}^ka_{k-r}\sum\limits_{s = 0}^rb_{r-s}c_s$

Question:
How does one prove that
  $$\sum\limits_{p = 0}^k\sum\limits_{r = 0}^{k-p} a_{(k-p)-r}b_rc_p = \sum\limits_{r = 0}^ka_{k-r}\sum\limits_{s = 0}^rb_{r-s}c_s$$ is true for any $k$?

This is the same as saying that $$\sum\limits_{p+q = k}\sum\limits_{r+s = p}a_rb_sc_q = \sum\limits_{r+w = k}\sum\limits_{s+q = w}a_rb_sc_q$$ but I want to give a formal proof, rather than an intuitive argument, perhaps one by induction.
Comment: I think $c_q$ in LHS should be $c_p$.
Comment: Both sums are simply $$\sum_{r,s,t\geqslant0}a_rb_sc_t\,[r+s+t=k]$$
Answer: For any $0 \leq m \leq k$, consider the coefficients of $a_m$. For LHS the coefficient is the sum of $b_{p-m}c_{k-p}$s (since $r+s=q=k-p$), which is $\sum_{m\leq p \leq k}b_{p-m}c_{k-p}=\sum_{x+y=k-m}b_xc_y$. For RHS the coefficient is the sum of $b_sc_q$s with $s+q=k-m$ (since $w=k-m$), which is $\sum_{s+q=k-m}b_sc_q=\sum_{x+y=k-m}b_xc_y$. Thus they are same. In other words, you can write both sums as following: $\sum_{0\leq m \leq k} \sum_{x+y=k-m} a_mb_xc_y$.
Answer:
We start with the left-hand side and obtain
  \begin{align*}
\color{blue}{\sum_{p=0}^k\sum_{r=0}^{k-p}a_{k-p-r}b_rc_p}&=\sum_{s=0}^k\sum_{r=0}^{k-s}a_{k-r-s}b_rc_s\tag{1}\\
&=\sum_{s=0}^k\sum_{r=s}^ka_{k-r}b_{r-s}c_s\tag{2}\\
&=\sum_{0\leq s\leq r\leq k}a_{k-r}b_{r-s}c_s\tag{3}\\
&\color{blue}{=\sum_{r=0}^k\sum_{s=0}^ra_{k-r}b_{r-s}c_s}\tag{4}
\end{align*}
  and the claim follows.
Comment:

In (1) we rename $p$ with $s$.
In (2) we shift the index of the inner sum and start with $r=s$.
In (3) we write the index range somewhat more conveniently as preparation for the next step.
In (4) we exchange the order of the summation.


How to grant permission to specifc role to perform CRUD operations on a particular content type only?

Question: I've set up different roles and in my site and I want a specifc role to grant permission to perform CRUD(create, Read, Update, Delete) operations on a particular content type only. But I can't find any such option in drupal admin.
Any suggestions?
Comment: Create, update and delete can be controlled via admin > people > permissions for that content type. View permissions requires a node access module (e.g content access)  or custom node access code to control.
Answer: Use Rule module. And create action assign role.
How to use.
Answer: A module specifically designed for this and very easy to use is the Content Access Module. When you use this, you will see that there are new per-content type permissions in the permissions configuration page.


What is the best way to overfit a model with accuracy?

Question: I need to overfit a model to specific data.(These data have been created from simulation of complex multidimensional models.)
The final goal is to extract coefficients (betas) to retrieve with accuracy the results of the database, without any complication, any assumptions, any need for extrapolation, just math.
I thought about a regression that try to maximize the adjusted R-squared, as it represents "the proportion of the variance for a dependent variable that's explained by a regression model".
But it may exist some other method, maybe machine learning method, that are more relevant and easy to apply ?
An important point is that the method have to be easily replicable on a non professionnal software like Excel , that why regressions (that contains coefficients) interest me.
Thank you a lot !
Comment: You can add polynomial terms until you hit every point.
Comment: Is there a textbook that covers the topic of on-purpose overfitting? This approach sounds like adversarial learning
Answer: My thought is that knowing the generating distribution implies one may be able to use something like factor analysis to derive the sets of variables/factors that account for nearly all of the variability, where such factors are related to the parameters of the generating distribution model which also encompasses a randomness component.
Use this set of factors to derive the regression model.
Put differently, fit as close as possible to the extent of the underlying noise model.
An interpolation model would be a correct approach if there is no (or very little) randomness and a poor choice in the presence of significant random noise.


Is it ok to stop my serve when I've already started my racquet forward?

Question: In a match last night, I was serving, threw the ball in the air, and started swinging my racquet. Just before I hit the ball, I stopped my racquet and caught it because I didn't like the toss. Did I go too far? Should I have lost the point? Or is it ok to still stop my serve at that point?
I recorded the match. This is how close I got to hitting the ball before backing off.
Answer: Should i have lost the point? No. Or its okay to skill stop my serve at that point? Yes.
The rule is cleary on this one (Portuguese language, page 10 - paragraph 19)
Question: After throwing the ball into the air to perform the service, the server decides not to hit it and
instead take it. Is this a fault?
Answer: No. A player who throws the ball in the air and then decides not to hit it is allowed catch it with your hand or racket or drop it on the floor.
Answer: It looks like this case is not considered a service fault.
From https://www.tennisgems.com/ball-toss/:

the rules of tennis state that you are able to catch and redo your
  ball toss during the tennis serve. If your racquet has not made
  contact with the ball, you are allowed to try again.

From here: https://www.usta.com/content/dam/usta/sections/pacific-northwest/pdfs/play/leaguenew/ITFRuleswheader.pdf

A player, who tosses the ball and then decides not to hit it, is
  allowed to catch the ball with the hand or the racket, or to let the
  ball bounce.


Is $\sum_{p}\frac{1}{p^{2}}$ irrational?

Question: Is $\sum_\limits{p}^{\infty}\frac{1}{p^{2}}$ irrational where p is prime? How to prove it?
Comment: @Aniket It's an infinite sum.
Comment: @Casteels You are right.. but I wanted to hear that from the OP..:-)
Comment: @Masacroso Fractions can easily have infinite decimals, e.g. $1/7=0.142857\, 142857\ldots$, the difference is that irrational numbers have infinite decimals that never repeat/don't have a period. A number is irrational if and only if its decimal representation is infinite without a period.
Comment: Why do you think this is irrational? It is the sum of rational fractions only.
Comment: I dont know the theory about that but if the sum is some irrational number it means that it have infinite decimals.
Comment: True @user236182, I forget completely :p
Answer: The function $P(s)=\sum_p \frac{1}{p^s}$ is called the prime zeta function. Unfortunately the value $P(2)$ does not have a known value like $\zeta(2)=\frac{\pi^2}{6}$. Similarly for $P(3), P(4)$ etc. For a related discussion see this MO-question. I think it is not known whether or not $P(2)$ is irrational.
Comment: This answer may help in finding the solution but it doesn't really answer the question. Not having a "known value" does not mean that rationality is unknown.
Comment: @Solomonoff'sSecret: if there is a solution to this question - I think it is unknown.
Comment: Okay, then that is the real answer.
Comment: Yes, that's what I meant. Even for $\zeta(n)$, rationality questions are very hard. And $\zeta(n)$ is much "nicer" here than $P(n)$.


Return data from PHP to JavaScript using AJAX - data type error?

Question: I am using AJAX to return a query to my JavaScript function, but I am having an issue returning the json_encode. I might have an error in the data type somewhere, but thought to check here for some advice.
This is my AJAX request:
$.ajax({
            url: 'testajax.php',
            method: 'POST',
            data: {value},
            dataType:'json',
            success: function(data){
                console.log(data);}
});

This is my PHP script:
<?php
require 'login.php';
$connection = new mysqli($host, $user, $pword, $database, 3306);
$insertquery = $connection->prepare("SELECT tracking_type, tracking_change_date, vessel_fcm_new, vessel_hull_id_new, vessel_name_new, vessel_length_new, vessel_manufacturer_new, vessel_manufacturer_id_new, vessel_year_new, vessel_value_new, owner_id_new, loss_payee_id_new, policy_id_new, policy_start_date_new, policy_end_date_new FROM tracking WHERE tracking_type = ?");
$insertquery->bind_param("i", $trackingtype);
//$trackingtype = $_POST['value'];
$trackingtype = 1;
$insertquery->execute();
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
while ($insertquery->fetch()){
    $data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
    echo json_encode($data);
}

If I only have 1 row matching this query, then it works fine. But as soon as I add another row that matches the select query, it does not return properly to the JavaScript function, but does display fine in the browser (if you visit testajax.php).
This is currently how the data is being returned. Maybe I have an error in the data type being usesd:
["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null]["Insert","2018-05-27","fFH465","FDDEE453","GIIGE","22","Shippers","2432465we",2014,205222,"Smith Jones","Capital One",null,null,null]

Answer: This bit might have given you a clue If I only have 1 row matching this query, then it works fine
So save your rows in an array and then send the whole array like this
while ($insertquery->fetch()){
    $data[] = array($tracking_type, $tracking_change_date, $vessel_fcm_new,
                $vessel_hull_id_new, $vessel_name_new, $vessel_length_new,
                $vessel_manufacturer_new, $vessel_manufacturer_id_new,
                $vessel_year_new, $vessel_value_new, $owner_id_new,
                $loss_payee_id_new, $policy_id_new, $policy_start_date_new,
                $policy_end_date_new);
}
echo json_encode($data);

EDIT:
A simple test of this code would be
$data[] = array('Insert','2018-05-26', 1);
$data[] = array('Insert','2018-05-26', 2);

echo json_encode($data);

This will generate
[
 ["Insert","2018-05-26",1],
 ["Insert","2018-05-26",2]
]

and not the sample output you suggest.
Comment: this is something I tried before, so the return data looks like this now: [["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null]][["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null],["Insert","2018-05-27","fFH465","FDDEE453","GIIGE","22","Shippers","2432465we",2014,205222,"Smith Jones","Capital One",null,null,null]] However, console.log(data[0]); or data[1] does not work
Comment: I dont see how this code would genarate that JSON String
Comment: Then you are not doing exactly what I suggested. See my edit
Comment: i'm beating myself up now....I forgot to move the encode outside of the loop ;) --- I think that was my issue the whole time lol.. Thanks for the suggestion!
Comment: No sweat, we have all been there
Answer: What you should be doing is return an array of objects. Not multiple objects.
$to_return = [];
while ($insertquery->fetch()){
    $data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
    $to_return[] = $data;
}

echo json_encode($to_return);

Comment: ___don't forget to parse it to JSON___ Not necessary when using `dataType:'json',`
Comment: this is something I tried before, so the return data looks like this now:

[["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null]][["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null],["Insert","2018-05-27","fFH465","FDDEE453","GIIGE","22","Shippers","2432465we",2014,205222,"Smith Jones","Capital One",null,null,null]]

However, console.log(data[0]); or data[1] does not work
Comment: @dataviews Updated my answer
Answer: The problem is that you're printing an array of columns for each pass through the loop and therefore the JSON is not be correctly encoded as an array of arrays; you can modify your code as follows:
$results = array();
while ($insertquery->fetch()) {
  $newResult = array($tracking_type, $tracking_change_date, ...);
  array_push($results, $newResult);
}
$encoded = json_encode($results);
echo $encoded;

Will print something like this:
[
    ["Insert","2018-05-26","JBL5693", ...],
    ["Insert","2018-05-27","JBL5694", ...],
    ...
]

Note that it's better to design a client<>server interface to use an array of objects, something like:
[
    {"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
    {"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
    ...
]

This approach has the advantage that the client client does not need to know the order of the columns, rather it can directly access the properties it cares about.
Answer: Make sure to keep
echo json_encode($data);

outside of the while loop.


Is there a CAGED system for pentatonic scales when playing guitar?

Question: I studied the Caged system for scales on guitar and find it useful when I'm doing scales over chords, but when I'm doing Pentatonic scales, I only learned Major and Minor with roots on 5th and 6th strings. I'm interested in learning more but I've never heard about CAGED For Pentatonics.
Comment: Yeah you just leave out two notes.
Comment: To me, the CAGED system pretty much 'just works' for all types of scales - what difficulty are you having applying it to pentatonics?
Comment: I suppose my difficulty has to do with my own uncertainty of if I do the analysis and figure out the fingering patterns, will I be able to pull it off, since in my little circle, no one has even mentioned it being done, let alone explained what I might need to understand. You've enlightened me and inspired me to move ahead with the idea.
Comment: I don't understand, but I don't play guitar so I'm just looking for someone to explain. To me, CAGED _is_ pentatonic, namely (CDEGA) C major pentatonic or (ACDEG) A minor pentatonic. On a guitar you can move the shape up and down the neck, but it's still pentatonic. What have a misunderstood?
Answer: (Expansion of comment)
The point of CAGED is to not see the C-A-G-E-D chord shapes as separate, but as one big interlocking chord shape that covers 12 frets - and then repeats again. This allows you to not get stuck in one little 'box' when playing chord tones up and down the neck. The idea is the same whichever chord type you're playing - Here's an illustration from rockprodigy.com of how it relates to the major and minor chords, for example...

Once you are comfortable playing chord tones, it shouldn't take too much mental gymnastics to work out where each note in a whole scale is, based on where the chord tones are. As with the major and minor examples above, the CAGED 'concept' remains the same - you just have to teach yourself to 'spot' all the intervals in a scale - e.g. C major pentatonic:


Adding Firebase Script Tags In The HTML File

Question: I am trying to create a front end website to talk to a Firestore Database and have been following the official documentation for the new version 9 modules but I have given up with this route as I just keep getting errors so I have started looking at another tutorial which I have got working but I have a question regarding the html head script tags.
In the html  I have the following.

>

My question is:
Am I ok to use version 5.03 or is it likely this will get removed from the gstatic.com in due course now they are moving over to version 9 modules.
Answer: firebaser here
Firebase doesn't remove SDKs from its CDNs. You can still find our 0.9 and event 0.0 SDK versions there, and in fact (I happened to recently check some usage statistic) they are still being used (luckily very sparingly ).
That said, I recommend upgrading to a more recent version to ensure you get the latest improvements and fixes. I get that the new modular syntax in v9 may be a big step, so a first step towards that could be to use the compat versions, which are drop-in compatible with v8 (and often earlier versions).
Comment: thank you for the clarification on this.


How do you orderby nested items from the same table in Linq?

Question: I have a single table with all my MenuItems in
public class MenuItem
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Url  { get; set; }
    public string Attributes { get; set; }
    public List<MenuItem> SubItems { get; set; }
    public int OrderId { get; set; }
    public int Seperator { get; set; }
}

I'm then getting my nested hierarchy like this (I've removed the failed ordering)
var result = _context.MenuItems.Where(mi => mi.ID == ID)
            .Include(si => si.SubItems)
            .ThenInclude(ssi => ssi.SubItems)
            .ThenInclude(sss => sss.SubItems).FirstOrDefault();

Here's the database. Where the OrderId is 0 I don't care about that order, but for anything else, I want the items in that order.

So I would expect [File][Test][Edit][Properties][View][Help]
What I'm getting is [File][Edit][View][Help][Test][Properties]
You specify the top-level menu item that you want (in this case 23). and the object that comes back is duly populated with all those menu-items and sub-menu-items.
I'm using react and bootstrap to then display the menu, which it does. So that all works fine, but the items are returned in database (ID) order and I can't seem to get the OrderId column to have any effect.
Any ideas?
Comment: What LINQ are you using? LINQ to SQL / EF 6.x / EF Core 2.0 / 2.1 / 3.x?
Answer: Have you tried to order your result by ascending OrderId?
int requestedMenuItemId = 23;
var result = _context.MenuItems

    // keep only those menu items with ID equal to requestedMenuItemId
    .Where(menuItem => menuItem.ID == requestedMenuItemId)

    // order the remaining menu items by ascending OrderId
    .OrderBy(menuItem => menuItem.OrderId)

    // finally select only the properties that you plan to use
    .Select(menuItem => new
    {
        // Select only the menu items that you actually plan to use
        ID = menuItem.Id,
        Name = menuItem.Name,
        ...

        SubItems = menuItem.SubItems.Select(subItem => new
        {
            ID = subItem.Id,
            Name = subItem.Name,
            ...

            SubItems = subItem.SubItems.Select(ssubItem => new
            {
                ID = ssubItem.Id,
                ...
            })
            .ToList(),
        })
        .ToList(),
    });

By the way, I would expect that every menuItem has some foreign key to the parent menu item. Did you forget it?
Comment: Nope, I didn't forget it, if you look at my database image it the column called MenuItemId. I'm using EF and code-first so let that manage the database creation for me. I like your solution and typically that's what I'd normally do. I was hoping to have minimal code and have the database rather than code to do all the heavy lifting.
Answer: Use SelectMany to flatten results
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Context _context = new Context();
            var results = _context.MenuItems.SelectMany(x => x.SubItems.Select(y => new
            {
                parentId = x.ID,
                parentName = x.Name,
                child = y
            })).ToList();

        }
    }
    public class Context
    {
        public List<MenuItem> MenuItems { get; set; }
    }
    public class MenuItem
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public string Attributes { get; set; }
        public List<MenuItem> SubItems { get; set; }
        public int OrderId { get; set; }
        public int Seperator { get; set; }
    }
}

Comment: I don't see any ordering in your query. I can't see how this will solve my problem. Could you explain a bit more please
Comment: I just did code to get both parent and child.  You can add code to sort and filter.  the code adds two additional columns to your results (parent id and name).


How can I automatically apply a shipping service and skip shipping selection during checkout?

Question: In certain circumstances, you may want to automatically add a particular shipping rate to an order. For instance, you might want to:

use a particular service for estimation purposes
force a particular shipping service based on business logic (e.g. it might be free or fixed cost)
have the customer skip the shipping pane in checkout
Answer: You can use Rules for this. You can modify the rule export below and either import it directly into Drupal or include it in MYMODULE.rules_defaults.inc:
/**
 * Implements hook_default_rules_configuration().
 */
function MYMODULE_default_rules_configuration() {
  $configs = array();

  $configs['rules_auto_add_shipping_service'] = rules_import('{ "rules_auto_add_shipping_service" : {
      "LABEL" : "Auto-add shipping service",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "TAGS" : [ "Commerce Shipping" ],
      "REQUIRES" : [ "rules", "commerce_order", "commerce_shipping", "entity" ],
      "ON" : { "commerce_order_update" : [] },
      "IF" : [
        { "data_is" : { "data" : [ "commerce-order:type" ], "value" : "commerce_order" } }
      ],
      "DO" : [
        { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
        { "commerce_shipping_method_collect_rates" : {
            "shipping_method_name" : "flat_rate",
            "commerce_order" : [ "commerce_order" ]
          }
        },
        { "commerce_shipping_rate_apply" : {
            "commerce_order" : [ "commerce_order" ],
            "shipping_service_name" : "standard_shipping"
          }
        }
      ]
    }
  }');

  return $configs;
}

In the example above, the rule fires when an order is updated. When an update occurs it:

Removes all shipping line items from the order. (commerce_shipping_delete_shipping_line_items)
Collects rates for the specified shipping method. You can edit the shipping_method_name from flat_rate to any service you are using (it doesn't have to be Flat Rate).
Applies a particular rate. This rate must be collected during the previous step.

Now, your order will always have a shipping rate applied to it.
To skip checkout, you can disable the shipping pane using the UI or use something like the snippet below to handle it in code:
/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // No need for shipping since it's auto-selected.
  $checkout_panes['commerce_shipping']['enabled'] = FALSE;
}


How to start views at %nid position (from path)?

Question: I have a portfolio showing somes nodes (views3 + views slideshow using cycle). Everything works fine, I've a default path /portfolio to access to it.
However, I'm trying to set a path for each slide. I would like to use /portfolio/%nid and using %nid in views to default the first viewed slide to this node id.
Anyone know how it is possible ? I've tried with UI but I don't think it is enough.
Answer: In jQuery Cycle there is an option called startingSlide. By default this is set to 0, like this: startingSlide: 0
If I remember correctly there is a tab/textarea for advanced settings where you can add options to jQuery Cycle from within the Views UI. I think you can add "startingSlide: 5" for example there.
You will need to find out which is the starting slide (convert the %nid to which row in the view it is) and add it as a HTML element. When that is in place we can fetch it with jQuery and add it as a jQuery Cycle option. I'm not sure which is the best way but I think you could do something like:
    function MYMODULE_views_pre_render(&$view) {
      if($view->name == "MYVIEW") {
        $view->attachment_after = $startingslide;
      }
    }

You will have to add more code to find out $startingslide there of course. Look inside $view->result and find out which of the rows that is the argument, that will be your $startingslide. Use dpm() on the view to search through the object.
Hope this will help you. Let me know what you ended up doing :)
Answer: You could add an exposed filter to your view, configure it to show nids greater than the provided value, and mimic it's URL accordingly.
for example /portfolio?nid_is_greater_than=3
You could then hide your filter with css.
Comment: I'd use an argument (contextual filter) rather than an exposed filter - unless there are already arguments in use and this extra one would mess with the handling of those.
Comment: I know of no way to _compare_ a field value to a contextual filter value.
Comment: Good point. Must have been half-asleep when I posted the previous comment, sorry.
Answer: Since your problem is about appearance, not about structure I suggest to not solve it on the server and not in the URL path but on the client with a URL fragement: /portfolio#slide-[nid].
I've not read the javascript code of views slideshow + cycle, but I guess it's quite easy to adopt it's behavior to read the URL fragment on initialization of the slideshow. Or maybe there is already such a logic implemented which you could use...
Answer: How about using 'Rewrite Output Results' option in Fields section of Views?

In Views, go to Configure (Image) Field > Rewrite Results
Check the 'Output this field as a link' checkbox
Enter the Link Path (nid/) and other details
Click on Apply
Save View

Hope this helps.
Answer: Views passes off the display to node_view() in that case, and doesn't get involved with the markup for the row.
The easiest way to do what you want is to implement hook_preprocess_node(), look for a View in the current context, and if the node is being rendered as part of that display, you can make some alterations.
TAKE A LOOK AT THIS:
function MYMODULE_preprocess_node(&$vars) {
  if (!empty($vars['view']) && $vars['view']->view_name == 'foo') {
    $nid = $vars['node']->nid;
    $vars['extra_link'] = l('Some text', "node/$nid");
  }
}

In your node.tpl.php file you'll have access to $extra_link.


Maximum/Minimum Modulus Principle Problem

Question: Let $f(z)$ be an entire function such that $|f(z)| \geq \sqrt{|z|}$ for all $|z|\leq 1$. I want to show that $|f(0)|\geq 1$.
Now, assume f has no zeros. Then, the minimum of $f$ on $\mathbb{D}$ is attained on the boundary when $|z| = 1$. However, this means that any minimum $z_0$ we have that $|z_0| = 1$ and so $|f(z_0)| \geq \sqrt{|z_0|} = 1$. In particular, since $0$ is not on the boundary, then we have that $|f(0)|\geq 1$.
Now, if f does have a zero on $\mathbb{D}$, say $z_0$, then $f(z_0) = 0$, so that $|f(z_0)| = 0$. Hence, $z_0 = 0$ by our given inequality. However, I'm not sure how to derive a contradiction from here to show that $|f(0)| \geq 1$. How do I proceed forward?
Answer: If $f$ has a zero in $\mathbb D$ then it must be in $0$, every other point would violate the inequality. If this is the case, then $f(z) = zg(z)$ for an entire function $g$.
It follows $|g(z)| \geq \frac{1}{\sqrt{|z|}}$ for $|z|\leq 1$ which is impossible.


Correctly interpreting keyboard mallet percussion hand notation

Question: I'm completely new to keyboard mallet percussion and, for now, working without a teacher.  I'm going through basic exercises such as those in G. H. Green's Instruction Course for Xylophone.  I'm not certain how to interpret hand notation on the very first exercises on pp. 6 & 7; e.g., is Exercise #9 to be played with the right hand only?  Similarly with this selection where the notation switches from alternate to just notating one hand:

I suppose this should be head-slappingly obvious but as a beginner I don't want to head down the wrong path by practicing incorrectly since most sticking direction strongly emphasizes alternating hands.
Answer: It works just like as any 2 hand/stick based percussion: whenever hand notation is not specified, it's assumed that you have to alternate hands, eventually starting from the last specified hand, if any.
Being this a beginner's book, there are sections in which the hands have to be explicitly written in order to introduce the student to the exercise, but a few notes after that they are gradually removed, and only reintroduced when there are changes that require clarifications.
This is clear in the image you posted: it begins with alternate (single) strokes in the first two quarters of the first bar, then it just writes the first hand out of four notes, but since the same note structure is kept you can assume that you just have to keep alternating your hands.
The full hand marking only returns at the end of the second bar, where the double right is introduced, which is required due to the change of structure that comes after that; the same happens at the very end when the exercise has to be repeated again.


Joint convergence in distribution

Question: I've one question concerning convergence in distribution of random variables: Let $X_n \rightarrow X$ and $Y_n \rightarrow Y$ for $n \to \infty$ where $\rightarrow$ denotes convergence in distribution. Furthermore assume $X_n$ and $Y_n$ to be independent for all $n$ and also $X$ and $Y$ are independent. Does $(X_n,Y_n) \rightarrow (X,Y)$ hold (meaning that the joint distribution also converges)?
Many thanks in advance!
Answer: Yes, because if we look at the joint characteristic function:
$$Ee^{i(uX_n + vY_n)} = Ee^{iuX_n}Ee^{ivY_n} \to Ee^{iuX}Ee^{ivY} = Ee^{i(uX + vY)}$$
Comment: OK, this is convincing. Thanks a lot!
Comment: @pierreparis1 you are welcome!

Joint convergence in distribution


The commerce_product.field_produit_labels field needs to be updated

Question: almost every time I delete a field in my product types I get this message popping up in my dashboard :

ENTITY/FIELD DEFINITIONS Mismatched entity and/or field definitions
The following changes were detected in the entity type and field
definitions. Product The commerce_product.field_produit_labels field
needs to be updated.

It has not been possible to update entities with "Drush" for some time.
Why do I have these problems regularly ? This is only with the Commerce module.
How can I correct this? Without breaking my site.
ubuntu@ov-b2b650 ~/www-example-com $ drush entup

In UpdateDBCommands.php line 110:

  Drupal removed its automatic entity-updates API in 8.7. See https://www.drupal.org/node/3034742.

entity:updates [--cache-clear [CACHE-CLEAR]] [--no-cache-clear] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--druplicon] [--xh-link XH-LINK] [--notify] [--] <command>

Answer: You can quick-fix it by adding module devel_entity_updates https://www.drupal.org/project/devel_entity_updates and run the command drush entup.
Don't forget to export configurations after that.
Also, you can fix it by manually creating an update hook - follow https://www.drupal.org/node/3034742#comment-13097250
Comment: Ok thank you, why do you have to export ?
Comment: just to be safe if something changed and that configuration is same as in database
Answer: You need to enable or install the devel entity updates first before running drush entup command.
Install Devel Entity Updates Module with composer (Source: https://www.drupal.org/project/devel_entity_updates)
composer require 'drupal/devel_entity_updates:^3.0'
(or composer require drupal/devel_entity_updatesto automatically get the latest version)
Enable Devel Entity Updates Module
drush en devel_entity_updates
Hope this will work for you.