Composition - How to connect musical periods

Question: How do you exactly keep a continuum between musical periods? And somewhat related, how exactly do you tell a story with it?
I am trying to compose something for piano, and while I'm able to connect various phrases that make sense and have a clear ending, I can't seem to be able to connect more periods that make sense together. They seem unrelated, just something in the same key merged together.
I'll edit later in a sample of what I'm doing or a screenshot of the piece, maybe - if it's not too much - you can pinpoint what I'm doing wrong, or what I could do better.
EDIT: Here is the piece in question.
Also a screenshot of it:

https://i.stack.imgur.com/I1uxI.jpg
https://i.stack.imgur.com/Dn6nl.jpg

EDIT2: Thanks for the work behind the answer, Patrx2. I am actually trying to compose for the piano not knowing how to play the instrument itself, hopefully it won't be too much hard!
While composing, I more often than not, consider a chord block and melody block as sort of separated entities. I find it more easy to think this way, but I guess this is one of the things that separates full-fledged composers from beginners.
One of the things you're saying is, should I give more thought to the individual voices separatedly?
I know that in harmony there are some rules - conventions maybe is better - about how voices should move, or how should I set certain chords before using them. Are those conventions a part of what makes a melody have sense or have not?
EDIT3: I don't have anything to ask anymore, you've really been of help, thanks a lot again! It's actually been in my mind for quite some time, I believe it's time I really get myself a keyboard, for the better.
Comment: Want to clarify for other readers that the OP is using the term *periods* to refer to cogent musical thoughts with antecedents and consequents, **not** aesthetic shifts in musical zeitgeist over centuries of time.
Comment: My pleasure, @Dodicin.
Comment: You should have a story to tell before you begin writing sentences, but you seem to be going in the opposite direction: You have a bunch of disconnected sentences that you like, and now you are trying to synthesize a story from them. Good writers (or composers) don't approach things that way. They have a grand concept in mind before they began filling in the details of the final work.
Answer: Tentative answer, and I may edit it as I see your edit, is that you are using periods where they shouldn't be used. Periods are, by their very nature, a rounded musical paragraph, with a dominant in the middle and a tonic at the end: they're great if you're looking to confirm a tonality; less so if you're looking to elaborate a tonality. So, periods are good to set up a tonality, and good to round one off. Use them when you have a rounded-off theme. If you use them all the time, though, you run the risk of having your music come to a dead stop all the time with all those perfect cadences, and it sounds to me like you may be finding that out firsthand.
Ending phrases with other cadences is definitely possible. Overlapping phrases is also possible (ending one voice's phrase while another voice is already starting its phrase), and frequently desirable. Remember that your accompaniment consists of voices that can develop a certain independence at times. (Haydn, Mozart and Beethoven were all good at evolving accompaniments into primary or secondary voices and back again.)

Edit: Oh my! How did you get stuck way up there?
Here's some thing to look at. I won't claim it's great (not my usual idiom), but it isn't falling apart quite so much, so it gives us something to discuss.

This is going to be more difficult to play, to be sure. (The bass notes, which really add to the difficulty, are there to give the passage an incentive to come back down out of the clouds.)
The first four bars are pretty much as you wrote them. The changes really start in the 5th bar, and they kind of accelerate from there. In the left hand, I thickened up the beginning of the bar so that it follows the previous phrase better and added some melody notes to push into the rising passage. The biggest change, however, is, rather than leaving the previous phrase's final high A in the right hand high and dry, I created a simple counter-melody.
By the time we get to m.8, I'm leading your original harmony into a LH figure that extends into m.9, while maintaining the simple counter-melody in the RH. This gives the phrase overlapping I was talking about. The real end of the phrase in the left hand is the 2nd beat of m.9. The counter-melody does add some suspensions to tie the phrase together. I added a few non-harmonic upbeats in the RH for the same reason.
By the time we get to m.13, however, the changes start becoming substantial. The melody through to m.17 is based on yours, but filled out with non-harmonic tones and reharmonised. Even in a period, you are under no obligation to start a phrase with the tonic. You'll notice that the highest voice is overlapping the start of the phrase.
The first point of instability shows up in m.15, in the form of a C7 harmony, which "resolves" into a G7 in the next bar (cancelling the B♭ in the process). The second comes with the fermata on the first beat of m.17 (I forgot to add fermate to the other voices): I pick up the melody from the middle of m.15 a whole tone lower (with some small changes) - its a modified sequence. This creates a rhythmic instability that pretty much demanded the extra beat in m.19. Notice that the C7 returns (and is again canceled in the following bar). By the time I'm done, I end up on the G M6 chord. From there, I can start something different.
The main things to take away from all this:

The last chord of a phrase is often the start of the next phrase.
Voicing, voicing, voicing. Your chords have voices that can often exert their own demands. A voice's phrase may not necessarily start or finish in sync with the rest of the voices.
Voicing, voicing, voicing (redux). There are times when the voices of your chords want to act like voices. Don't hesitate to introduce non-harmonic notes if they a) make melodic sense, and b) lead logically into or away from chord tones.
You are thinking in single bar patterns. Don't. Let your voices (including the accompaniment) go where they want, because music does have some resemblance to rhetoric and, sometimes, to discussion. If you spin out the voices, and they don't quite fit together, pound on 'em until they do. If that means crossing bar lines or adding extra measures, so be it.
Do not worry so much about periods. I used only one here (the first two phrases), despite basing most of this on your work. Use them, as I said earlier, when establishing your tonality, or when reaffirming it at the end. In all cases, though, make sure that your phrase ends imply a continuation, and try to introduce instability when the time comes to start moving away from the key.

2nd edit: Yeah, in some ways those conventions are part of what of what makes a melody  make sense. In other ways, they come about because the strong intervals in melodies tend to be whole- and half-tone steps (as opposed to the more open intervals that are stronger harmonically) - it's a bit of a "chicken or the egg?" question. It's like, on the one hand, you can see a melody as a voice in the harmony that has been brought to the fore, and on the other, you can see block chords as superimposed voices that are working in lockstep.
There has always been some tension between how Western harmonic theory deals with the vertical, and how it deals with the horizontal. The need for conjunct motion in the voices  making up the harmony leads to notes being sounded that don't fit the conceptual framework of the underlying chords, and hence these notes get called "non-harmonic", e.g., passing tones, suspensions, anticipations, appoggiaturas, etc.
Are these notes really non-harmonic?
Not in the least. At some point in your composing life, you'll run across a situation where you use non-harmonic tones according to the "rules", and find you've blown the tonality of the passage right out of the water. In other situations, a conventional use of non-harmonic notes over a common chord leads to a new standalone chord. The dominant seventh chord got its start that way: it originated as the suspension of a seventh over the dominant triad that resolved by a downward step to the third of the tonic chord. After a while, the preparation of the dissonance became unnecessary, and eventually, even its stepwise resolution did as well.
The tl;dr is that, yeah, there are times when it's very fruitful to look at your chords as voices working together. If you do so, you can have your melody extending a phrase when the accompaniment is ending one, or vice versa. Looking at the entire texture as voices working at times somewhat independently can allow you to spin a very long line in your music; it can allow you promote voices out of the background to act as responses to, or "sing duets" with, the melody, and then retire them into the background again; it can allow you to use the accompaniment to bridge motivically between different ideas in the melody.
That's not to say that using chords as splashes of harmonic colour is necessarily a bad thing. There are certainly times when chords used that way are great for amplifying the implications of a really dominant (in the sense of being in the forefront) melody - a lot of jazz "comping" works that way.
That's also not to say that you aren't already doing some of this instinctually: the chords in your first phrase have a fairly strong melodic thrust to them.
A word of advice: get yourself a cheap keyboard just so you can feel how the hands have to move in response to what you have written. I'm not primarily a keyboard player myself, but I write a lot for keyboards (although I have never written at the keyboard, not even back before computer notation programmes existed). I know how the instruments work, and I have some pretty good heuristics to keep the piece real while I'm writing it, but I like to bench-test my pieces for practicality after I've finished writing. I figure that, if I can work my way through a passage slowly, a reasonably skilled keyboard player can do the same at tempo.
Comment: +1 for the work, analysis, and suggestions. While it is not entirely comprehensive in answering the OP's questions, it should provide much material for the OP to think about and apply to their music.
Comment: Thank you. It wasn't meant to be _totally_ comprehensive, though. For one, it isn't really my idiom, so, although I can feel my way around this kind of writing, I don't have all the nomenclature for it, so I'd have to go into very low-level aspects of voice leading to really explain. For another, I'm not sure that a comprehensive answer is the best _starting point_ for this kind of question: an example of "comment c'est fait" allows the questioner to see if it comes close to his needs. My own experience has been that follow-up questions tend to be very, very specific as a result.


CS CART call a controller at add on front end with microformat ajax

Question: I am very new to cs cart. I have read their documentation about calling Ajax with form micrformats. I am able to create a Ajax request. But I would like to call a controller inside my add-on controllers/frondend/ directory names as mycheckout.php. I am using the a hidden file dispatch with the valu mycheckout.mymode. Can any one help me. I actually want to perform some action in my controller. But their documentation did not help me. Thanks in advance.
Answer: You can do something like this (use extra "cm-ajax-force" or "cm-ajax-full-render" classes if needed):

<form class="cm-ajax" name="your_name" action="{""|fn_url}" method="post">
    <input type="hidden" name="result_ids" value="div_id_to_be_updated" />
    {include file="buttons/go.tpl" but_name="mycheckout.mymode" alt=__("Ajax button")}
</form>

Or you can use any button you want (even <input type="submit" name="mychechkout.mymode" value="Ajax!">)
Answer: Note that the Ajax request can be also done via simple link:
Ajax!


Mostrar valores com angular

Question: Tenho o seguinte codigo:
$http.get('/estados').success(function(retorno) {
    $scope.ufs = retorno.ufs;
    console.log(retorno);
});

e o resultado do console.log(retorno) é:

Agora estou tentando mostrar os valores deste retorno em um <select> do HTML:

    public
    <select name="uf" required="true">
        <option ng-repeat="(key, value) in ufs">[{value.sigla}]</option>
    </select>

Porém não está mostrando valor nenhum, mas ao inspecionar o elemento vejo o código abaixo:

Ele está atribuindo os valores aos <option> do <select> porém na página para o cliente selecionar não aparece nada.
Alguém já passo por isso?
OBS: Estou usado {[ porque troquei nas configs.
app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('[{').endSymbol('}]');
});

Comment: Eu particularmente uso o ng-options no select: https://docs.angularjs.org/api/ng/directive/ngOptions
Comment: Quando você da faz isso: `console.log(retorno.ufs)` qual o resultado?
Comment: Tenta colocar o ng-repeat no select
Comment: @Techies o resultado de `console.log(retorno.ufs) é igual, so muda que na primeira linha fica `[Object, Object....]`
Comment: Tentou colocar o ng-repeat no select? @MeuChapeu
Comment: não funciona no select
Comment: @Techies acredito que o problema não esteja relacionado com o angular visto que as options foram geradas corretamente.
Comment: @Oeslei sim, eu estava imaginando o mesmo, só queria ter 100% de certeza rs
Answer: ufs é um array, não um objeto com chaves e valores.
Ao invés de utilizar
<option ng-repeat="(key, value) in ufs">[{value.sigla}]</option>

Tente
<option ng-repeat="value in ufs">{{value.sigla}}</option>

Answer: O problema é que você está usando [] no binding do value. Você está fazendo dessa forma:
[{value.sigla}]

O correto seria utilizar {{value.sigla}}
Exemplo: http://jsfiddle.net/81t6cbjw/25/
Comment: Eu mudei as configs de `{{` para `{[`
Comment: Não entendi @MeuChapeu
Comment: Desconfio que seja algo do frameworks `css` o materialize, pq desabilitando funciona...
Comment: No meu código tenho: `app.config(function($interpolateProvider) {
 $interpolateProvider.startSymbol('[{').endSymbol('}]');
});` o que me permite usar `{[` ao invés de `{{`.
Comment: Ah sim, agora entendi.
Comment: Tenta dar uma modificada na ordem das declarações das bibliotecas
Answer: Cara já tentei utilizar isso ai
$http.get('/estados').success(function(retorno) {
    $scope.ufs = retorno.ufs;
    console.log(retorno);
});

Da uma olhada no ngResource, um exemplo que fiz no meu service.
 var services = angular.module('ProcessoService', ['ngResource']);

    services.factory('ProcessosFactory', function($resource,apiUrl){
      var resource = $resource('http://restTest/retornos');

      var factory = {
          listar: function () {
              var lista = resource.query({}, function(data){
                 lista = data;
              });
              return lista;
          }

      }

  return factory;

no controller só chama:
$scope.lista = ProcessosFactory.listar();

no html:

            {{ processo.id }}

vê se ajuda no seu caso.

Mostrar valores com angular


NotifyDataSetChanged not working in FragmentStateAdapter with Viewpager2

Question: I am making a file selection page with viewpager2 with FragmentStateAdapter. In one of the pages I show all mounted storage devices on which I would like to tap to view the contents but I want the contents to be on another fragment.
I want to replace fragment with another one in the last page of viewpager. but with the following code, the page just refreshes and new Fragment is not created as createFragment does not get called.
My PagerAdapter
public static class PagerAdapter extends FragmentStateAdapter {

        private Fragment mFragmentAtPos0;
        private final FragmentManager mFragmentManager;
        private final FirstPageListener listener = new FirstPageListener();
        public final class FirstPageListener implements
                FirstPageFragmentListener {
            public void onSwitchToNextFragment() {
                mFragmentManager.beginTransaction().remove(mFragmentAtPos0)
                        .commit();
                if (mFragmentAtPos0 instanceof FilesandFolder_Others_MainPage){
                    mFragmentAtPos0 = new FileExplorer(listener);
                }else{ // Instance of NextFragment
                    mFragmentAtPos0 = new FilesandFolder_Others_MainPage(listener);
                }
                notifyDataSetChanged();
            }
            public void onSwitchToNextFragment(Bundle bundle) {
//                mFragmentManager.beginTransaction().remove(mFragmentAtPos0)
//                        .commit();
                if (mFragmentAtPos0 instanceof FilesandFolder_Others_MainPage){
                    mFragmentAtPos0 = new FileExplorer(listener);
                    mFragmentAtPos0.setArguments(bundle);
                }else{ // Instance of NextFragment
                    mFragmentAtPos0 = new FilesandFolder_Others_MainPage(listener);
                    mFragmentAtPos0.setArguments(bundle);
                }
                notifyDataSetChanged();
//                notifyItemChanged(getItemPosition(mFragmentAtPos0));
            }
        }

//        @Override
//        public void onBindViewHolder(@NonNull FragmentViewHolder holder, int position, @NonNull List<Object> payloads) {
//            super.onBindViewHolder(holder, position, payloads);
//            if (position == getItemPosition(mFragmentAtPos0)) {
//
//                Fragment f = mFragmentManager.findFragmentByTag("f" + holder.getItemId());
//                if (f != null) {
//                    mFragmentManager.beginTransaction().replace(holder.getItemId(), )
//                }
//            }
//        }

        private int getItemPosition(Fragment mFragmentAtPos0) {
            for (int i = 0; i < getItemCount(); i++){

                if (createFragment(i).equals(mFragmentAtPos0)){
                    return i;
                }
            }
            return -1;
        }

        public PagerAdapter(FragmentActivity fm) {
            super(fm);
            mFragmentManager = fm.getSupportFragmentManager();
            mFragmentAtPos0 = new FilesandFolder_Others_MainPage(listener);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            switch (position){
                case 0:
                    return new AppSelectionFragment();
                case 1:
                    return new Photos();
                case 2:
                    return new VideoGalleryFragment();
                case 3:
                    return new Gallery();
                default:
                    return mFragmentAtPos0;
            }
        }

        @Override
        public int getItemCount() {
            return 5;
        }
    }

Here is the constructor of Fragment from which I would like to replace to another Fragment:
    private static FileSelection.PagerAdapter.FirstPageListener pageFragmentListener;

    public FilesandFolder_Others_MainPage() {
    }
    public FilesandFolder_Others_MainPage(FileSelection.PagerAdapter.FirstPageListener firstPageFragmentListener) {
        pageFragmentListener = firstPageFragmentListener;
    }

And on tap of a view,
the following code is supposed to be called:-
Bundle bundle = new Bundle();
bundle.putString("PATH", volumes.get(position).path);
pageFragmentListener.onSwitchToNextFragment(bundle);

I have searched all over stackoverflow, and never saw a proper answer with viewpager 2 and FragmentStateAdapter as everyone seems to be using Viewpager
I tried to implement this:- FragmentStateAdapter for ViewPager2 notifyItemChanged not working as expected
but couldn't understand how to edit my code. Pls help
Thanks in advance
Comment: I'm trying to do the same. Did you solve the problem?
Answer: Had same problem, and that's what i found:
FragmentStateAdapter has method onBindViewHolder(holder, position, payloads), which you can override (unlike onBindViewHolder(holder, position) which is final). This method calls when you call notify methods, and for notifyItemChanged(), notifyItemRangeChanged() methods you can access the fragment, and manually update it.
Here is code to access the fragment:
public void onBindViewHolder(@NonNull FragmentViewHolder holder, int position, @NonNull List<Object> payloads) {

    String tag = "f" + holder.getItemId();

    Fragment fragment = fragmentManager.findFragmentByTag(tag);

    if (fragment != null) {
        //manual update fragment
    } else {
        // fragment might be null, if it`s call of notifyDatasetChanged()
        // which is updates whole list, not specific fragment
        super.onBindViewHolder(holder, position, payloads);
    }
}

FragmentStateAdapter is tagged his fragments by "f" + holder.getItemId(), that's why it works.
Also you can use DiffUtil, and this is better way. Here is good example of solving this problem, and some links in the end for better understanding of ViewPager2.
Comment: It's nice to know this `onBindViewHolder(...)` method exists and can be overridden like this to update the Fragments in a `ViewPager2`. Anyone using this approach has to take into account that it's relying on an implementation detail of `FragmentStateAdapter`, i.e. the fact that Fragments are being added to the `FragmentManager` with the tag `"f" + holder.getItemId()`. You should cover your application with some UI tests so that you detect at development time if this implementation detail is ever changed in future versions of the `FragmentStateAdapter` class.
Comment: Yes, that's not safe. Maybe if compare fragments tags manually instead of using `fragmentManager.findFragmentByTag("f" + holder.getItemId())` will made is safe.
Comment: In my case I have a FragmentActivity instead, do you know how I could still make this work?
Answer: you can override this two method
    override fun getItemId(position: Int): Long {
        // generate new id
        return getItem(position).hashCode().toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        // false if item is changed
        return dataList.find { it.hashCode().toLong() == itemId } != null
    }

Comment: This cause `java.lang.IllegalStateException: Design assumption violated.` when screen is recreated.
Answer: I faced the same issue today and thought I would share my solution here. Instead of intercepting onBindViewHolder(), my solution simply replaces the old fragment:
OldFragment.instance.containerId?.let {
    replace(it, NewFragment.instance)
}

To be more concrete:
My App has a ViewPager2 with two fragments. Let's call them MainFragment and DetailFragment. On a button click in the MainFragment, I wanted to replace it with a SecondMainFragment. And the same behaviour vice versa: Button click in SecondMainFragment would replace itself with the MainFragment.
class CustomFragmentStateAdapter(
    private val fragmentActivity: FragmentActivity
) : FragmentStateAdapter(fragmentActivity) {

    var displaySecondMainFragment: Boolean = false
        set(value) {
            if (field != value) {
                switchFragments(replaceWithSecondMainFragment = value)
            }
            field = value
        }

    private fun switchFragments(replaceWithSecondMainFragment: Boolean) {
        fragmentActivity.supportFragmentManager.commit {
            if (replaceWithSecondMainFragment) {
                MainFragment.instance.containerId?.let {
                    replace(it, SecondMainFragment.instance)
                }
            } else {
                SecondMainFragment.instance.containerId?.let {
                    replace(it, MainFragment.instance)
                }
            }
        }
    }

    // Standard adapter overrides
    override fun getItemCount(): Int = 2

    override fun createFragment(position: Int): Fragment = when (position) {
        0 -> if (displaySecondMainFragment) SecondMainFragment.instance else MainFragment.instance
        else -> DetailFragment.instance
    }
}

With this extension property to get the id of the container the fragment is in:
inline val Fragment.containerId: Int?
    get() = (view?.parent as? ViewGroup?)?.id

In the end I would only need to do something like that:
button.setOnClickListener {
    customFragmentStateAdapter.displaySecondMainFragment = true // Or false for the other way
}


Multiple rows of data into a single row sql

Question: I have the following query:
SELECT EMPLID, APDATE, STARTTIME, ENDTIME
from MYTIME

Sample of the results:
1234,4/1/2017,8:00,12:00
1234,4/1/2017,13:00,21:00
1234,4/2/2017,23:00,07:00
1234,4/2/2017,08:00,11:00
4444,4/1/2017,08:00,15:00
4444,4/2/2017,14:00,18:00
4444,4/2/2017,19:00,21:00

I need help constructing a query that returns a single row based on the emplid and apdate matching.  If the emplid and apdate match then return all start times and endtimes on a single row.   Below is what I'm looking for using the sample results from above:
1234,4/1/2017,8:00,12:00,13:00,21:00
1234,4/2/2017,13:00,21:00,23:00,0700
4444,4/1/2017,08:00,15:00,NULL,NULL
4444,4/2/2017,14:00,18:00,19:00,21:00

Comment: Which dbms are you using? (The solution will probably be product specific.)
Comment: Can there be more than 2 that match?
Comment: Based on your input and expected output, is this a homework question on joins? What have you tried so far?
Comment: sql server 2012.  Only up to 2 matches
Comment: Can two rows have same date etc, and also same start/end time?
Comment: look up PIVOT queries
Comment: thanks randy.  I'm checking that out now.  @jarlh Times would never be the same for the same emplid, but dates would be the same.  Multiple emplids may have same dates and times.
Answer: Do a GROUP BY. Use MIN() to pick first time. If MAX() > MIN(), also select last time (else null).
SELECT EMPLID, APDATE, MIN(STARTTIME), MIN(ENDTIME),
       case when MAX(STARTTIME) > MIN(STARTTIME) then MAX(STARTTIME) end,
       case when MAX(ENDTIME) > MIN(ENDTIME) then MAX(ENDTIME) end
from MYTIME
GROUP BY EMPLID, APDATE


If $p_1$ and $p_2$ are primes, prove that there exists an integer such that $p_1+k$ is a prime but $p_2+k$ is not.

Question:
Let $P_{1}$ and $P_{2}$ be primes. Prove that there exists a $k\in \Bbb Z^+$ such that $P_{1} + k$ is a prime but $P_{2} + k$ is not.

It seems like the proof should be trivial, but for some reason, I am not able to construct it.
Any help would be appreciated.
Comment: @TheMathsGeek $p_1 + p_2$ is probably even, so not a prime.
Comment: Hmm, this certainly follows from Direchlet (which gives infinitely many such $k$). But I am missing an elementary argument.
Comment: Assuming that $p_1$ and $p_2$ are different primes, can you not just choose $k = p_2$? Then $p_2 + p_2 = 2p_2$ is certainly not prime, but $p_1 + p_2$ has *no* prime factors, therefore prime?

I may be missing something though! (Turns out I'm missing most of my brain cells today! This is obviously wrong)
Comment: @Tobias Kildetoft Ha, of course it's likely even - it's been a long day already, maybe I'll wait to answer after I've had a coffee next time!
Comment: @TheMathsGeek I was typing the same idea when I saw your comment. Only then did I realize it was not correct.
Comment: Sorry i deleted the comment that Tobias is replying to above. Yeah, it seems like p1+p2 might not be a prime.
Comment: Silly question: Am I missing something, or would it suffice to find one triplet $(P_1,P_2,k)$ that satisfies the conditions to prove that "there exists a $k$..."? (In which case one could pick $P_1=5$, $P_2=7$, and $k=2$.)
Comment: Not to be a stick in the mud, but the inconsistency of notation between the question title and the question body is bothering me. I'm not sure it rises to the level that makes it worth editing.
Answer: Note that the numbers $P_1+nP_2, n\in \mathbb N$ are in arithmetic progression and this contains (by Dirichlet) infinitely many primes. So choose $n\ge 1$ which makes this a prime. $P_2+nP_2$ is clearly not prime.
Comment: This does use a fact about primes which is not so easy to prove. Maybe there is an easier way, but it is not obvious apart from the case $P_1=2$ when $k$ has to be odd and $P_2+k$ is even - this could be seen as using the odd numbers as the arithmetic progression, and there is a relatively easy proof that there are infinitely many odd primes.
Comment: yeah, I had never heard of Dirichlet progression. This came up in a proof regarding formal languages, so am assuming the author of the textbook expected me to prove the claim some other way. Anyways, thanks!
Answer: Here is a more elementary approach than just quoting Dirichlet.
Suppose $P_2\gt P_1$ and $P_2-P_1=d$. If $P_3=P_1+k$ we want $P_3+d=P_2+k$ not to be a prime.
So given $d$ we need to find a prime $P_3$ with $P_3+d$ not a prime.
Now we know that there are arbitrarily large gaps between primes e.g. $n!+2, \dots n!+n$ gives a gap of size at least $n-1$. (all these are composite by construction, so the prime before and the prime after will have a big gap)
We can choose $n\gt d+1$ here, so there will be a $P_3$ distance greater than $d$ from the next prime, and we can choose $k$ to pick this out.
Comment: NIce!  I knew there had to be a more elementary proof: thank you!
Comment: Don't you lose some generality by assuming P2 > P1? You can't just switch them, because the problem statement asks specifically for P1+k to be prime and P2+k not to be, rather than asking for one of them to be prime and the other not.
Comment: @amalloy Not really, I just want $d$ to be positive. If they are the other way around I can define $d$ equivalently.
Answer: Assume wlog $p_1 < p_2$ and $p_1+k$ is prime iff $p_2+k$ is prime. Set $z:=p_2-p_1$. By induction, $p_1+nz$ is prime for all $n$. This is impossible since the primes have density zero.
Comment: As noted in a comment to my answer, it's enough to see it's not prime for $n=p_1$.
Answer: EDIT: Same proof but significantly cleaned up.
Suppose this is not true, and let $p_2 > p_1$.  Then for $k=p_2-p_1$, we have $p_1 + k$ is prime, so $p_2 + k$ is prime.  We also have $p_1 + (k+p_2-p_1)$ is prime then, so $p_1 + 2\cdot(p_2-p_1)$ is prime.  Continuing in this way we get that $p_1 + n\cdot(p_2-p_1)$ is prime for all $n$, which is not possible.
Comment: To make the last point clearer, plug in $n=p_1$.
Comment: I don't get it ... say $p_1=7$ and $p_2=13$. Then $k=p_2+p_1=20$, so $p_1+k=27$ .. is not prime ...
Comment: I don't follow. Showing that this works for some $k$ doesn't seem to imply that there's **no** $k$ for which this works.
Comment: @Bram28 Thanks, I typoed.  Should have been $p_2 - p_1$.
Comment: @LivingRobot Working by contradiction.  If there is no $k$ such that $p_1 + k$ is prime but $p_2 + k$ is not, then $p_1 + k$ prime implies $p_2 + k$ is prime.
Answer: Hint: We must assume $P_1 \ne P_2$ for this to be true. Now, what would the world look like if this were false?
Well, take $d = |P_1 - P_2|$. If this were false, then either for all $x$ $x \ge P_1$ being prime implies $x + d$ is also prime, or for all $x$ $x \ge P_2$ being NOT prime implies $x + d$ is also NOT prime. In either case, deduce the following absurd fact:

The function $f: \mathbb{N} \to \mathbb{N}$, defined by $f(n) = 1$ if $n$ is prime and $f(n) = 0$ otherwise, is eventually periodic with period $d$.

From here there are probably multiple ways to derive a contradiction. One idea: there are infinitely many primes, so there must be some $N$ such that $N, N + d$, $N + 2d$, $N + 3d$, etc. are all prime. Now pick $k$ so that $N + kd$ just certainly cannot be prime.
Comment: Yeah, I was following this same train of thought myself, but didn't quite know how to get that contradiction in the first case ... could you please elaborate on that, please?
Comment: @Bram28 I edited to clarify the main point of the argument. The last sentence of the new version of my answer may answer your question. Let me know if it doesn't.
Comment: Hmm, still struggling to see it ... I *feel* it has to be true, but maybe this proof does require a big gun after all ...
Comment: @Bram28 No big gun! Just take $k = N$. Or are you asking about he earlier part of the proof?


Find the total number of matchings in a complete graph with even number of vertices

Question: I am trying to solve questions from a Walk through combinatorics.., I came across this proof which I was unable prove:
Determine the number of perfect matchings for a complete graph with 2n vertices.
I don't know how to approach this, I have tried counting..
The answer is:  $$ \frac{(2n)!}{n!2^n}. $$
Please help me with this, thanks :)
Comment: Maybe this will help you: http://math.stackexchange.com/questions/1352477/show-frac2nn-cdot-2n-is-an-integer-for-n-greater-than-or-equal-to/1352492#1352492.  Think of a graph on $2n$ vertices as a collection of $2n$ people, and an edge is a group of two people.
Comment: @Batominovski Thanks for the proof, its very nice:), but could you think of a more straight forward proof ? i.e is there an easier/shorter way to do this
Comment: $(2n-1)(2n-3)(2n-5)\cdots(5)(3)(1)$
Answer: There is an old principle in combinatorics.  To count the number of sheep in your field, count the number of legs and then divide by four, the number of legs per sheep.
Look at the expression $$\frac{(2n)!}{2^n n!}.$$
Here $(2n)!$ is the number of permutations of your set of $2n$ things.  Given such a permutation, can you think of a simple way of getting a matching?  Once you have this, you can show that each matching shows up in the same number of permutations, which ought to be $2^n n!$ from the above formula.
Answer: I wasn't able to figure out the answer without looking at the expression provided in the post. The expression itself is quite telling though. As already mentioned in another answer, we just have to see how $2^n*n!$ arrangements out of all the $(2n)!$ ones, correspond to the same matching.
Let's look at one of the $(2n)!$ arrangements shown below and see how it corresponds to a matching in a complete graph-
A matching in a graph
Every arrangement of $2n$ vertices can be divided into two halves of $n$ vertices each and numbered as shown in the figure above. We can define a matching $M$ as set of pairs of vertices $(l_i, r_i)$ for $1<=i<=n$. We can change this arrangement in following two ways so that it will still correspond to the same matching-

Permute any of the two sets of vertices and arrange the other set in lock-step to ensure that $l_i$ is always matched with $r_i$. This can be done in $n!$ ways.
Interchange $l_i$ and $r_i$ for any number of pairs. Every pair has $2$ configurations - $(l_i, r_i)$ and $(r_i, l_i)$. You can choose any configuration independently for each pair. Hence this can be done in $2^n$ ways.

Both the above adjustments can be done independently and hence there are $2^n*n!$ ways to arrange a set of vertices and still keep the same matching. Hence total number of unique matchings is $(2n)!/(2^n*n!)$.
Comment: I recommend writing $2n!$ as $(2n)!$ to distinguish it from $2(n!)$. Nice first answer!
Comment: Thankyou for your feedback Misha! :) I have made the required edits.
Answer: Let $f(n)=\frac{(2n)!}{n!2^n}$. The idea is to proceed by induction on $n$, the base case being trivial. So suppose that $f(n-1)$ is the number of perfect matchings on a complete graph with $2(n-1)$ vertices.
Consider a complete graph on $2n$ vertices and fix a vertex $v$. Any matching $M$ of this $K_{2n}$ contains an edge $e$ incident to $v$, say $e=(v,w)$. Now $M\setminus \{e\}$ is a matching of $K_{2n}\setminus\{v,w\}\simeq K_{2n-2}$. Since there are $2n-1$ choices for $e$, it follows that the number of complete matchings of $K_{2n}$ is $(2n-1)f(n-1)$. I'll leave it to you to verify that $(2n-1)f(n-1)=f(n)$.


Does holomorphic map preserve orientation for any dimension?

Question: Let $f:M\to N$ be a holomorphic map between two oreintable complex manifolds. Given a volume form $dx_1\wedge dy_1\wedge...dx_n\wedge dy_n=(\frac{i}{2})^ndz_1\wedge d\overline{z_1}...dz_n\wedge d\overline{z_n}$ on $Y$, then $f^*(dx_1\wedge dy_1\wedge...dx_n\wedge dy_n)=f^*(\frac{i}{2})^ndz_1\wedge d\overline{z_1}...dz_n\wedge d\overline{z_n}=(\frac{i}{2})^ndf_1\wedge d\overline{f_1}...df_n\wedge d\overline{f_n}$.
Note $df_i\wedge d\overline{f_i}=(\sum_j\frac{\partial f_i}{\partial w_j}dw_j)\wedge (\sum_j\frac{\overline{f_i}}{\overline{w_j}}d\overline{w_j})$.
It's easy to see when $n=1$, we have $f^*dx\wedge dy=f^*\frac{i}{2}dz\wedge d\bar{z}=\frac{i}{2}|f'(w)|^2dw\wedge d\bar{w}=|f'(w)|^2dx'\wedge dy'$, which is a volume form on $X$. But I can see it's true for $n>1$. So I wonder if  a holomorphic map preserves orientation for any dimension?
Comment: Of course, it only makes sense to ask this if $M$ and $N$ have the same dimension, and at a point where $df$ is nonsingular.
Answer: This is really just a linear algebra question: restricting our attention to the tangent space at a single point, the question is whether an invertible complex-linear map $\mathbb{C}^n\to\mathbb{C}^n$ (the derivative of $f$ at our point) always has positive determinant when considered as a map $\mathbb{R}^{2n}\to\mathbb{R}^{2n}$.  The answer is yes.  Here is one way to prove it.  Since the determinant is a continuous function, it suffices to show that $GL_n(\mathbb{C})$ is connected, since the identity obviously has positive determinant.  There are many ways to show $GL_n(\mathbb{C})$ is connected; for instance, by Jordan normal form it suffices to show the set of invertible upper triangular matrices is connected and that is easy since it is just a product of copies of $\mathbb{C}\setminus\{0\}$ (for the diagonal entries) and $\mathbb{C}$ (for the entries above the diagonal).
(Note that applying this result to the transition functions of the complex charts on a complex manifold, this shows that every complex manifold is orientable and has a canonical orientation (the one given by its complex charts, identifying $\mathbb{C}^n$ with $\mathbb{R}^{2n}$ in a fixed way).  This then says that any holomorphic immersion between complex manifolds of the same dimension is orientation-preserving if you give both of them the canonical orientation.  Of course, if you do not require any compatibility between the orientation and the complex structure then you cannot conclude a holomorphic map is orientation-preserving, since you could just reverse the orientation on the domain or codomain.)


$ P\left(E_e\right)=\sum _{\eta =1}^{\mathbb{H}} P\left(H_{\eta }\right) P\left(E_e|H_{\eta }\right) $ How to prove?

Question: Is it that true?
If yes, how to prove this?
$$
P\left(E_e\right)=\sum _{\eta =1}^{\mathbb{H}} P\left(H_{\eta
   }\right) P\left(E_e|H_{\eta }\right),
$$
where $E_e$ is an generic evidence, $H_\eta$ it's the $\eta$-esim hyphotesis and $\mathbb{H}$ is the cardinality of the hypothesis ($H$) set.
Comment: I don't quite follow the jargon, but the formula looks like the [law of total probability](http://en.wikipedia.org/wiki/Law_of_total_probability).
Comment: Just be aware that the law of total probability $P(A) = \sum_i P(A\mid B_i)P(B_i)$ assumes $A \subset \cup_i B_i \subset \Omega$ where $\Omega$ is the entire sample space.  More simply, people just assume $\cup_i B_i = \Omega$ for simplicity.
Comment: Looks like very simple yet...but didnt find a way until now. Thx about the link. I will take a look.
Comment: @SrivatsanNarayanan, if one fo you answer this question, I will embrace it. Someone else too. I just don't want post my own answer.
Comment: @DilipSarwate if one fo you answer this question, I will embrace it. Someone else too. I just don't want post my own answer.
Comment: @GarouDan There's nothing wrong whatsoever with answering your own question! In fact, the site explicitly permits and encourages this. In any case, I already posted an answer this time. :-)
Answer: The formula you quote seems to be just the law of total probability. Assume that the set of events $\{ H_\eta \}_{1 \leq \eta \leq \mathbb H}$ forms a partition of the sample space $\Omega$; i.e., the $H_\eta$'s are pairwise disjoint, and $\bigcup \limits_{\eta = 1}^{\mathbb H} H_\eta = \Omega$.
Now for any event $E_e$, the set of events $\{ E_e \cap H_\eta \}$ forms a partition of $E_e$. Therefore, by additivity, we have
$$
P(E_e) = \sum_{\eta = 1}^{\mathbb H} P(E_e \cap H_\eta). \tag{1}
$$
Now, by the definition of conditional probability, we have $P(E_e \cap H_\eta) = P(H_\eta) \cdot P(E_e \mid H_\eta)$. Plugging this in $(1)$ we get the claim.*
The following sentence taken from the wikipedia article explains what this theorem means intuitively (notation changed to match ours):

The summation can be interpreted as a weighted average, and consequently the marginal probability, $P(E_e)$, is sometimes called "average probability"; "overall probability" is sometimes used in less formal writings.

*The formula is true even for $\{ H_\eta \}_{\eta \geq 1}$ forms a countably infinite partition of $\Omega$. The proof has to be modified only slightly for this.
Comment: Thx. A good answer!


By taking answers modulo $m$, show that $Z_m$ has no divisors of zero iff $m$ is prime

Question: For a positive integer $m$, let
$Z_m$ = {$0,1,...,m-1$}
$+: Z_m * Z_m \rightarrow Z_m$
Mult: $Z_m * Z_m \rightarrow Z_m$
by taking answers modulo $m$ (e.g. $Z_6$ = {$0,1,2,3,4,5$} and $(3)(5)$ = $15$ modulo $6 = 3$) Show that $Z_m$ has no divisors of zero $\Longleftrightarrow$ $m$ is a prime.

I'm guess I'm getting confused about the zero divisor part. I'm unsure how to approach this problem.
Comment: What are *answers* modulo $m$?
Answer: First suppose that $m$ is prime.  Then
$$\eqalign{\def\Z{{\Bbb Z}}
  ab=0\ \hbox{in}\ \Z_m\quad
  &\Rightarrow\quad m\mid ab\ \hbox{in}\ \Z\cr
  &\Rightarrow\quad m\mid a\ \hbox{or}\ m\mid b\ \hbox{in}\ \Z\cr
  &\Rightarrow\quad a=0\ \hbox{or}\ b=0\ \hbox{in}\ \Z_m\ .\cr}$$
So $\Z_m$ has no zero divisors.
Conversely, suppose $m$ is composite.  Then $m=ab$ for some $a,b$ with $1\le a,b\le m-1$; so in $\Z_m$ we have $ab=0$ but neither $a=0$ nor $b=0$.  Thus $\Z_m$ contains zero divisors.
Comment: What does m | ab in Z mean?
Comment: "$m\mid ab$" means that $m$ is a factor of $ab$; "in $\Z$" means that we are thinking of $a$ and $b$ as ordinary integers, not as elements of $\Z_m$.


Como recuperar tudo depois do "?" em RewriteRule?

Question: Eu tenho a seguinte regra que foi criada por um outro programador e que está em funcionamento em alguns processos:
RewriteRule ^chk-error/(.*) chk_err.php?error=$1 [L]

Ela recupera tudo que vem depois de chk-error/ e coloca dentro de error para ser tratado dentro do arquivo chk_err.php. Funciona normalmente.
Porém vou precisar usar a mesma página chk_err.php e a URL que ira acessar esse path virá com um ponto de interrogação. Assim:
https://www.example.com/chk-error/?errcat=5&errcd=514&id=12&in=gt5

Eu gostaria de adaptar para que ela possa recuperar tudo que vem depois da interrogação "?". Sem quebrar o processo anterior.
Como seria a nova RewriteRule com o "?" sendo opcional?
Em resumo eu queria reescrever a RewriteRule que esta funcionando para recuperar essa URL:
https://www.example.com/chk-error/errcat=5&errcd=514&id=12&in=gt5

Para poder recuperar esse outro padrão de URL:
https://www.example.com/chk-error/?errcat=5&errcd=514&id=12&in=gt5

Note que a diferença entre eles é somente o ponto de interrogação "?" depois de chk-error/ .
Comment: Não entendi a pergunta. `$_GET` não atende?
Comment: Oi Felipe eu melhorei a pergunta. Quando eu uso GET a variavel error vem vazia. O que está parecendo que a regex não esta pegando tudo depois de `chk-error/?`.  Mas se eu retiro a interrogação tudo funciona.
Answer: Essa é a única regra que a URL passa? Se eu entendi direito, basta você negar o simbolo ? na regra e tudo deve funcionar como você quer.
RewriteRule ^chk-error/(^?.*) chk_err.php?error=$1 [L]
Answer: É necessário utilizar a flag [QSA] (Query String Append) para passar os parâmetros da url.
Fonte


How can I (or should I) test that observation A tends to be greater than observation B for each subject?

Question: I measured 2 sediment parameters in multiple lakes.  The organic matter content at the sediment/water interface surfOM and the mean organic matter content of the whole core meanOM.
surfOM <- c(34.4600, 42.1700, 48.6700, 18.4711, 19.5300, 18.4238, 20.5601, 28.2800, 19.1739)
meanOM <- c(31.23571, 37.57117, 43.47832, 18.47110, 17.18266, 17.42377, 19.96015, 25.09943, 19.37392)

The two measures are correlated > cor(surfOM, meanOM) [1] 0.9967266 and surfOM is generally greater than meanOM:
 > surfOM - meanOM
[1]  3.22429  4.59883  5.19168  0.00000  2.34734  1.00003  0.59995  3.18057
[9] -0.20002

When reporting the results I say:

"The surface percent organic matter and the mean percent organic matter of the same core were highly correlated with slightly greater surface percent organic matter in most lakes."

I did not initially feel like the difference needed a statistical test because it just is what it is but both reviewers asked for a test showing that surfOM tends to be greater than meanOM in a lake.
My initial thought was to calculate the confidence interval of surfOM - meanOM and show that it does not contain 0 but I am not sure if this is the most appropriate approach.
Questions:

Does the difference between the two variables need a statistical test?
What is an appropriate way of testing this difference?

(Note: this is just a subset of the data.  The complete dataset has 23 lakes)
Comment: (+1) It's a good question.  Concerning how to report results: first, it needs a comma before "with" to be understood correctly.  Second, it is better to be quantitative instead of using the qualitative "slightly," although "highly correlated" is ok.  You might instead write, "The surface % o.m. is highly correlated with the mean % o.m. in each core and exceeds it on average by 3.2%" (or whatever the mean difference is).
Comment: @whuber Thanks for your feedback on the results, that is useful.
Answer: You can do a paired t-test.
In R, t.test(surfOM,meanOM,paired=TRUE)
That will give you a p-value and a confidence interval for the mean of the differences. These only really makes sense if the lakes are a sample of a larger population of lakes, not if you have data on all the lakes in your population (e.g. all the lakes in some geographical area, or all the lakes of a certain type of interest).
Comment: +1 One *never* has complete information about sediment characteristics: these data are measurements of very small portions of the total sediments in each lake.  Therefore these data make perfect sense when either (a) inference is about this set of lakes and/or (b) inference is about all lakes and these form a representative sample.
Answer: When I hear the statement "A tends to be greater than B" it sounds like A is greater than B a bunch of the time, say, more than 50% of the time.  This can happen when $\mu_{A}$ is greater than $\mu_{B}$, but it can also happen that $\mu_{A}$ is greater than $\mu_{B}$... yet $P(A > B) < 0.50$.
(For a concrete example of what I'm getting at, let B be identically 1/2, and let A put probability $1 - p$ on zero with its remaining probability $p$ on some integer $n \geq 1$.  We can make $P(A > B)$ as small as we like by letting $p \to 0$, yet we can make $\mu_{A}$ as big as we like by letting $n \to \infty$.)
On top of all this, it looks like your "B" is itself a "mean", which complicates the language.
So, my first thought is to try to figure out whether you'd be more interested in $\mu_{A} > \mu_{B}$ or if you'd rather be more interested in $P(A > B) > 0.50$.  If you're interested in the means then the t-test should be just fine.
If you're more interested in $P(X > Y)$, you might consider the Sign Test.  It's a nonparametric test, it's light on assumptions, and you don't need to be so concerned about outliers. If you could additionally say that the distribution of the differences of organic matter was symmetric, you could do one better and go for the Wilcoxon Signed Rank test.
Anyway, suppose you can say nothing more about the distributions, and suppose they are appropriate for the Sign Test.  The data given above had 8 out of 9 pairs with A greater than B. For these data, in R, you would do
binom.test(8, 9, alt = "greater")

The output would give a p-value and a 95% one-sided Clopper-Pearson confidence interval (which generally is conservative).
Comment: Also: bear in mind that nowhere is it chiseled in stone that we must throw away every slope estimate which doesn't have a p-value vanishingly small (it's typed on paper in lots of places, though).  You may judge it worthwhile to keep the slopes -- at least temporarily -- to investigate a different question which may be important.  On the face of it, I'd rather preserve the information in the slope estimates than throw the ties completely away.  Bottom line: we are searching for the *truth*, and the path leading there isn't always paved in steel with road signs pointing everywhere.
Comment: Ha! double-checking the data it looks like entry 4 is a tie!  That's one of the wrinkles of the Sign Test.  There are several ways to address that, and here's a paper that talks about some of them: http://www.jstor.org/pss/2683818.  But given the context, is that truly a tie...?
Comment: Kerns - thanks for your answer.  I am most interested in $P(A > B)>0.50$ so I will look into the Sign Test.  It is a true tie.  `surfOM` is the y-intercept of a linear model of %OM by depth (i.e., the %OM at depth = 0) in a few cases the slope of the model was not different from 0 so I used the `meanOM` as `surfOM`.
Comment: I see.  Well, the quick and dirty approach is to throw away the ties.  This has advantages and disadvantages (see the paper).  And, it might not be appropriate for your study;  you'd have to decide (and defend) in the context of the bigger picture of your research question.  For the given data, the conclusion doesn't change whether you keep them or not (but the interval estimates do, of course).


Mass Modification of Questions (bumping)

Question: What should we do if someone modifies a bunch of their questions in order to bump them onto the first page again?
Comment: I think about half those bumps were on answers. Still it is a good idea to have a policy on this.
Comment: Why is this always a bad thing, (and so would require some kind of pre-decided treatment)?
Comment: @AlecosPapadopoulos I think one problem which arises is that newer questions (which have yet to be answered) end up buried and may not get answered because of it.
Answer: if the edits are not at all constructive, flag one of the posts for moderator attention, and describe what's going on.
If they are constructive, then you could post a polite comment asking them to slow down so that they don't swamp the front page.
Comment: A good process, However,  my understanding is that the SE system doesn't actually allow private messages to users.
Comment: @BKay I'm not sure which of my two sentences you're referring to, so if (1) a flag for moderator attention does include a private message to the moderators; if (2) the polite comment I propose would be public, not private
Answer: I don't know if I am the implicit target of this question (and I really don't take it personally if I am), but I clearly have, from time to time, edited a bunch of my old questions/answers, which made them bump onto the first page again.
The reason I sometimes edit my old questions/answers is I am not a great writer.  I usually leave typos and grammatical errors in my posts (sometimes embarrassing ones).
Every now and then, when I have time, I like to go over old posts of mine to correct as many typos as I can.
I believe there is a value-added for the site to me improving the wording, grammar and spelling of these old posts. But I've noticed that it bumps the posts back onto the first page, and I agree that this is disruptive of the site's question flow as it makes new questions disappear quicker from the first page.
Any suggestions on how to get the best of both worlds (i.e. the ability to improve past posts without swamping the first page) would be much welcome. I'd be happy to follow them.
One suggestion : is there a way to ask SE to only bump edited posts to the first page after substantial edits, say only when more than x-characters were changed?
(I have no problem either with refraining from these edits if the community deems them too disruptive and there is no way to prevent first page bumping.)


Página não encontrada Erro 404, [Route("Categorias/list/{page=1}")] no Asp.Net MVC

Question: Olá, estou com um problema referente a configuração do Route no Asp.Net MVC. O problema e que eu criei uma página de teste onde nesta página estou tentando configurar os recursos de rota. Montei uma pagina com pesquisa com um método para cria um url com o parâmetro da pesquisa.
Ex:

http://localhost:59180/catetorias/list/1

O número "1" é o parâmetro que esta sendo passado, e da PadedList que crie. E pesquisa funciona perfeitamente e ela consegue altera a url no Chrome, mais quando eu copie a url e colo no Microsoft Edge aparece um página de erro 404, página não encontrada.
Controller: CategoriasController.cs
using PartionView.DAO;
using PartionView.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace PartionView.Controllers
{

    public class CategoriasController : Controller
    {
        #region Carregamentos de páginas

        public ActionResult Index()
        {
            listCat();
            listUsers();
            return View();
        }

        /*
            O Endereço ficará:
            Get - categorias/list/{page}
        */
        [Route("Catetorias/list/{page=1}")]//Para acessar a função
        public ActionResult pagteste(int page = 1, int pageSize = 4)
        {
            listCatPg("", page, pageSize);
            return View();
        }

        [Route("Categorias/list/{pesquisa=}/{page=1}/{pageSize=4}")]
        public ActionResult pagteste(string pesquisa = "", int page = 1, int pageSize = 4)
        {
            listCatPg(pesquisa, page, pageSize);
            return View();
        }
        #endregion

        //===================================================================================

        #region Metodos Usados
        ///
        /// Método usado para lista todas as categórias.
        ///
        /// <param name="Pesquisa">Recebe a categoria para pesquisa.</param>
        /// <returns>Retorna lista na ViewBag de categorias.</returns>
        public ActionResult listCat(string Pesquisa = "")
        {
            var dao = new CategoriaDao();

            var list = dao.listaCategoria(Pesquisa);

            if (Request.IsAjaxRequest())
            {
                return PartialView("_PvCategorias", list);

            }

            ViewBag.cat = list;

            return View();
        }

        ///
        /// Método usado para lista todas as categórias.
        ///
        /// <param name="Pesquisa">Recebe a categoria para pesquisa.</param>
        /// <returns>Retorna lista na ViewBag de categorias.</returns>
        [HttpGet]
        public ActionResult listCatPg(string pesquisa = "", int page = 1, int pageSize = 4)
        {
            var dao = new CategoriaDao();

            var list = dao.listaCategoria(pesquisa);

            PagedList<Categoria> pl = new PagedList<Categoria>(list, page, pageSize);

            PesquisaFiltro pf = new PesquisaFiltro
            {
                categorias = pl,
                pesquisa = pesquisa,
                page = page,
                pageSize = pageSize
            };

            ViewBag.pf = pf;

            if (Request.IsAjaxRequest())
            {
                return PartialView("_PvPagteste", pf);
            }

            ViewBag.cat = pf;

            return View(pf);
        }

        ///
        /// Método usado para lista todas as usuários.
        ///
        /// <param name="Pesquisa">Recebe a usuário para pesquisa.</param>
        /// <returns>Retorna lista na ViewBag de usuários.</returns>
        public ActionResult listUsers(string PesquisaUsers = "")
        {
            var dao = new CategoriaDao();

            var list = dao.listaUsuarios(PesquisaUsers);

            if (Request.IsAjaxRequest())
            {
                return PartialView("_PvUsuarios", list);
            }

            ViewBag.us = list;

            return View();
        }
        #endregion

    }
}

No RoutConfig.cs e a padrão, só adicionei MapMvcAttributeRoutes().
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //Para mapear os atributos das rotas direto no controller.
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Coisas que eu percebi fazendo testes:

Se você roda a página index, e colo a url "http://localhost:59180/catetorias/list/1" já passando o parâmetro 1, 2 ou 3 ele não funciona.
Não funciona também se você copia a url acima e cola em outro navegador.

Se alguém souber seria de uma boa ajuda.
Answer: Já descobri, foi só um erro de digitação:
[Route("Catetorias/list/{page=1}")]


Why isn't it counted as a hit in baseball?

Question: It happened at the bottom of the 5th inning between Baltimore and Seattle on June 30, 2016. With the bases fully loaded, a batter hit the ball to the right field and the third base runner scored a run, but the second base runner started late because he thought the ball could be caught by the right fielder and got forced out on the third base. The batter was not the one who was forced out.
What I don't understand is why it is not counted as a hit? I have been looking for a relevant rule, but I couldn't find it. Can you explain why it isn't a hit?
Answer: This is covered by Rule 9.05(b)(1):

The official scorer shall not credit a base hit when a runner is forced out by a batted ball.

Also note that this

third base runner scored a run

is incorrect. The runner may have reached home base before the out was made, but no run is scored. Quoting from Rule 5.08:

A run is not scored if the runner advances to home base during a play in which the third out is made [...] by any runner being forced out.
Comment: The last paragraph doesn't apply to the actual play in question.  There was only one out at the start of the play.  The runner forced at third was only the second out.  The third out was not made on the play and the run did score.
Comment: In light of an edit, the reference to "scored a run" won't make much sense, but I believe an appropriate change in your answer will clarify why crossing home plate won't be counted as such.
Comment: @Nij Hi, thanks for your edit. The problem of editing a question is there is a possibility of making an answer posted earlier partly (or fully) invalid. I didn't clearly mention the fact that "the third base runner crossed a home plate" and I think that's why Philip answered this way.
Comment: @Rathony I've edited the question to differentiate based on the answer itself. The runner crossing home can be assumed to have happe
Comment: @Nij I don't think you should edit a question based on an answer. I will roll your edit back.
Comment: @Rathony unless the scorer actually awarded a run, it's not true to say the runner crossing hone did so. But that he did cross home, is known, and it's a minor change to explain why (in this situation) doing so would not score.
Comment: @Nij The hit helped Seattle score a run. That's what happened.
Comment: I'd make the edit with that correction to it, if you prefer?
Answer: OK. This actually happens a lot more than people think. The most likely case is with a runner on first. The ball is hit so hard into the outfield the fielder gets to it in a matter of seconds. This makes it very difficult to make it to 2nd in time.
In the case of the game you are talking about its like a sacrifice ground ball. Say the batter hit a ground ball to third or short and the fielder went to 3rd and got the force out but the run still scored. This would be considered a fielder's choice with the batter receiving a RBI.
Even though the ball was hit to the outfield they still went to third and it would be scored a fielder's choice with an RBI.
Answer: Note that you have good answers - and this isn't an answer per se but too long for a comment.
However this rule is just stupid.
It is antiquated and has carried over because of MLB - at all lower levels I am sure they would change this and some leagues have rules overruling this (see later).  MLB hasn't changed it because:

MLB doesn't like to make changes that effected past stats.  Which is just dumb because this literally hardly ever happens at the MLB level.
Since it doesn't happen at the MLB level, no one gives a crap about it.  The first time someone won or lost a batting title based on a baserunning error ESPN would do a documentary and MLB would happily change the rule.

I did scorekeeping for a few high school teams my sons played on.  I told the coaches from the get go that I counted hits as hits, rules be damned.  Doing otherwise doesn't let the stats reflect what is going on, on the field.  Just like when giving out errors in baseball or assists in basketball it is about obeying the spirit of the rules.
Examples:

Men on first and second.  Batter lines a one hopper to the left and the shortstop dives and catches the ball. Notices that runner from first is already at second.  Runner that was on second was caught daydreaming and thought there was no one on first so decided not to try to advance.  He would have been safe by a mile but is out on force.  Why in the world would the batter have a "FC" on his score card.  My score card shows "1B" for batter and baserunning error and out for the kid forced out at third.
Man on first.  Batter hits a hard line drive to left.  Runner was moving from the start.  Leftfielder was playing in and picks up the ball clean off one hop and fires to second base for the out.  That is a "FC".  The batter caused the out.  Highly unlucky but that is his out.
Man on first.  Batter hits a bloop well over third baseman's head.  Runner decides to tag when he should have been in the middle of first and second.  Leftfielder doesn't get to it but fires to second and beats runner by a step.  Again this is a hit "1B" and a baserunning error.
Now if someone is superbly slow... We had one player like that.  He literally took 7-8 seconds on a good day to get to second with a lead off (and he wasn't fat so it fascinating).  I charged him with 4 baserunning errors that year.  It simply isn't measuring the hitter when he keeps getting forced out at second from the outfield.  I kid you not one play the ball was batted between center and left and dumb "Chad" (yes he wasn't bright either) takes like 4 steps towards second then shifted his momentum back to first.  The centerfielder had to backtrack big time so the ball didn't pass him.  The batter probably had a 95%+ chance at a double and surely would have went for two.  Chad got nailed.

In my opinion if you did this right you would set the right attribute to the right stat.  For instance a batter who hits a one hopper to the right fielder and trips on his way to first, that is really a 1B and baserunning error.  The at bat resulted in a "hit".  The baserunning resulted in an out.  So in conclusion the rule is absurd.  If scorekeepers get to give a third basemen an error after he lays out for a ball but then bobbles it, well they can handle these obvious baserunning issues a few times a year.  How you score things is up to your league and if your league doesn't have rules it is up to you.


Subversion - Set default commit hook?

Question: Is there anyway to set a custom commit hook to be a "default" hook when repositories are created?
Answer: Outside of the nine standard hooks installed into a new repository by the 'svnadmin create /path/to/repo' command (start-commit, pre/post-commit, pre/post-revprop-change, pre/post-lock, and pre/post-unlock), I know of no way to have additional hooks automatically included as a "default" hook for all newly created repositories.
I suppose you could build a wrapper shell script for creating new repositories that calls the svnadmin create command with a variable set for the repository path followed by a copying of the custom commit hook into the path/to/repo/hooks folder and use that for all new repositories.
Lastly, because you mention that this custom hook in particular is a commit hook, I should repeat the warning given by Version Control with Subversion when discussing hook scripts (emphasis mine):

While hook scripts can do almost
  anything, there is one dimension in
  which hook script authors should show
  restraint: do not modify a commit
  transaction using hook scripts.
  While it might be tempting to use hook
  scripts to automatically correct
  errors, shortcomings, or policy
  violations present in the files being
  committed, doing so can cause
  problems. Subversion keeps client-side
  caches of certain bits of repository
  data, and if you change a commit
  transaction in this way, those caches
  become indetectably stale. This
  inconsistency can lead to surprising
  and unexpected behavior. Instead of
  modifying the transaction, you should
  simply validate the transaction in the
  pre-commit hook and reject the commit
  if it does not meet the desired
  requirements. As a bonus, your users
  will learn the value of careful,
  compliance-minded work habits

Subversion - Set default commit hook?


Two MIDI files generated by Lilypond output the same audio

Question: When generating the MIDI files for the two Lilypond files below, and then
generating the WAV audio files with Timidity (timidity --output-24bit -A120 f.midi -Ow -o f.wav), I can hear no differences
between the two outputs, even if the two scores were in different keys.
Is it a MIDI problem (but MIDI does support key signature) or a synthesis one? Cause the generated scores (PDF files) look different.
File 1:
\score {
  \new Staff <<
    \new Voice {
      \set midiInstrument = #"acoustic grand"
      \voiceOne
      \key c \minor
      \time 4/4

      c'' d'' e'' f'' g'' a'' b'' c'''
    }
  >>
  \layout { }
  \midi {
    \context {
      \Staff
      \remove "Staff_performer"
    }
    \context {
      \Voice
      \consists "Staff_performer"
    }
    \tempo 2 = 72
  }
}

File 2:
\score {
  \new Staff <<
    \new Voice {
      \set midiInstrument = #"acoustic grand"
      \voiceOne
      \key g \major
      \time 4/4

      c'' d'' e'' f'' g'' a'' b'' c'''
    }
  >>
  \layout { }
  \midi {
    \context {
      \Staff
      \remove "Staff_performer"
    }
    \context {
      \Voice
      \consists "Staff_performer"
    }
    \tempo 2 = 72
  }
}

Comment: It does as a meta message (the two bytes 0xFF 0x59 indicate "key signature"). But it is either not written by Lilypond, or not read by Timidity.
Comment: No, MIDI does **not** support key signatures, nor can it distinguish between c-sharp and d-flat.
Answer: Their documentation at http://www.lilypond.org/doc/v2.18/Documentation/learning/accidentals-and-key-signatures (in the section Warning: key signatures and pitches) states

key signature only affects the printed accidentals, not the note's
  pitch!

It seems that Lilypond equates a note name with a particular pitch - you have to add the relevant suffix ('es' or 'is') to lower or raise the pitch, regardless of key signature.
So the two files above would be expected to generate midi files with the same midi note numbers.
Answer: Those are the same notes.  LilyPond names its notes "absolutely"; changing the key does not change the meaning of the note names.
In the printed version, you'll see that f'' now gets a natural sign in order to keep it at the same pitch.
However, if you play the Midi on an arranger with a key display or load it into a sequencer with note display, the display will change to indicate G major (more exactly, a key signature of one sharp as Midi does not distinguish G major from E minor in its key messages).
Comment: @nightcod3r I think that's what I'd expect. In G major, the F# is in the key signature, so there's no need for an accidental if you are actually playing F# (`fis`). On the other hand, F natural (`f`) is not the F normally found in G major, so it would have the natural sign accidental.
Comment: Problem is that when the 'is' is added (`fis''`), then the note in the score does not show the sign anymore. Looks like there's no way to conciliate the printed and midi representations, you can either have it well written, or well played, but not both.
Comment: @nightcod3r in which key does `fis` not show the sign?
Comment: G major.  There's a natural sign for `f''` and there's no sign for `fis''`.


Launch Summernote Popover on Other Events

Question: Using Summernote in airMode, the popover toolbar launches on a mouseUp event.
Is there a way to make it launch on other events (specifically, mouseEnter)?
Answer: This is obviously a hack, and risks being broken on new releases, but it does the job. Put this code in the Summernote onInit event:
<code>     callbacks: {
         onInit: function () {
             let summernote = $(this).data("summernote");      // Get the summernote data object

              $(summernote.layoutInfo.editable).mouseenter(function (ev) {
                  summernote.modules.airPopover.$popover.css({
                      display: 'block',                        // Set the css to display the popover
                      left: ev.clientX - 20,                   // Offsets to position popover relative to pointer
                      top: ev.clientY + 10
                   });
               });

               $(summernote.layoutInfo.editable).mouseleave(function () {
                   setTimeout(function () {
                       // Delay so that moving over popover doesn't immediately close it
                       summernote.modules.airPopover.hide(); },1000);
                    });
                }
            }
       }
</code>
Does the job, but I'd prefer something actually supported by the library.


Multivariate Maximization

Question: For fixed $g$, I want to find maximum $b$ with $$-2b(3t^2(s+1)+6t(s+1)+3s+2)-2g(6ts+3t+6s+2)-3ts^2+6ts+3t-3s^2+3s+1>0$$ for some nonnegative reals $t,s$. Here $g, b$ are also $\geq 0$. Can it be possible to get a function $f$ such that we get the upper bound on $b$ as $f(g)$ i.e, $b<f(g)$? If one can find $t,s$ for which $b$ is maximum, one will get $f(g)$.
Comment: There might be some typo in the expression you want to be positive. You could check it.
Answer: For every nonnegative $g$, $s$ and $t$, let $$
u(g,s,t)=\frac{-2g(6ts+3t+6s+2)-3ts^2+6ts+3t-3s^2+3s+1}{2(3t^2(s+1)+6t(s+1)+3s+2)}.
$$
and
$$
\varphi(g)=\inf\{u(g,s,t);s\ge0,t\ge0\}.
$$
Then $f(g)=\varphi(g)$ fits your requirement and no number greater than $\varphi(g)$ can.
The problem is that for every $g$, $u(g,s,1)\to-\infty$ when $s\to+\infty$ hence $\varphi(g)=-\infty$ and no finite $b$ is such that $b<u(g,s,t)$ for every nonnegative $s$ and $t$.

Multivariate Maximization


Prove if $\Box \Box p \to \Box p$ is valid on Frame $F=\langle W,R \rangle$ then $R$ is dense

Question: Prove if $\Box \Box p \to \Box p$ is valid on Frame $F=\langle W,R \rangle$ then $R$ is dense.
Where dense means $\forall  w,v \in W: wRv \implies \exists u \in W : wRu\ \&\ uRv$.
I know we are supposed to come up with a valuation such that when $wRv$ and $M,w \models \Box \Box p \to \Box p$ we must have the denese-ness property but I'm not sure where to even begin since $\Box\Box p$ requires length 2 path.
Comment: Did you notice that the definition of "dense" also requires a length $2$ path, $wRu\ \&\ uRv$?
Answer: We have to be careful about what things we're quantifying over at what time when dealing with modal logic. Sequitur answered a question of mine eight months ago that gives  the standard names for the different parts of a modal model.
I interpret $\square\square p \to \square p$ holds on the frame to mean:

For all models $M$ with frame $\langle W, R \rangle$ and all worlds $w$, it holds for all propositions $p$ that $M, w \models \square \square p \to \square p$

In particular, a frame $\langle W, R \rangle$ does not include a valuation, which means we get to pick our valuations in very obnoxious ways to rule out features of the accessibility relation that we don't like.
First, let's note that $\square \square p \to \square p$ enforces the same conditions as $\lozenge p \to \lozenge\lozenge p$.
Proof:

$\square\square p \to \square p \;\;\;\;$ is our hypothesis.
$\square\square \lnot \lnot p \to \square \lnot \lnot p \;\;\;\;$ holds by double negation introduction.
$\lnot \lozenge \lozenge \lnot p \to \lnot \lozenge \lnot p \;\;\;\;$ holds since $\square$ and $\lozenge$ are dual.
$\lozenge \lnot p \to \lozenge \lozenge \lnot p \;\;\;\;$ holds by contrapositive elimination.

And note that $\lozenge p \to \lozenge \lozenge p$ enforces the same frame condition since $p$ is universally quantified, so we can add or remove $\lnot$ as long as we do it uniformly.
With that out of the way, let's pick two not necessarily distinct worlds, $u$ and $v$, such that $uRv$.
World $u$ is our starting point.
Pick a variable, let's say $a$ and declare $a$ to be true at world $v$ and false everywhere else.
$M, u \models \lozenge a$ is true, since we can get from $u$ to $v$, the only world where $a$ holds.
Therefore, $M, u \models \lozenge \lozenge a$ must also be true, i.e. there must exist an intermediate world $w$ such that $uRw$ and $wRv$. This is the only way to satisfy $\lozenge \lozenge a$, since $a$ is false everywhere except at world $v$.
Therefore $R$ is dense.
Comment: I think i understand everything except how  $\Diamond \neg p \to \Diamond\Diamond \neg p$ implies $\Diamond p \to \Diamond\Diamond p$
Comment: @CHTM $\lozenge p \to \lozenge \lozenge p$ is not a logical consequence. What I'm saying is $p$ ranges over all propositions and $\lnot$ is an involution on propositions, so uniformly replacing $p$ with $\lnot p$ yields an equivalent frame condition.


What is the reason Men play 5 sets & Women play 3 sets in a Grand Slam in Tennis?

Question: In the ATP & WTA events, both Men & Women tennis players play best of 3 sets. But when it comes to Grand Slams, the Men play 5 sets.
At the risk of sounding a misogynist, I always believe the reason to be strength & endurance. After all, a 5 set EPIC match lasts 5 hours while a 3 set EPIC last 3 hours.
Is that the only reason. Or am I a naive misogynist?
Also was that the case since the history of Grand Slams or did Men play 3 sets before?
Comment: Yes.. Usually men has more stamina than women..
Comment: Men and women should play equal number of sets as they get equal prize-money.
Comment: I believe that women should play best of 5 from at least the round of 16 on for several reasons.
1. They are professional athletes and should be able to go 5 sets.
2. The game is very psychological and it would give a good player time to regroup if she got off to a slow or bad start, and play her best tennis...especially if she is overwhelmed by all the media and the nerves that causes and it would give her time to work it out.
3. As a spectator I would like to see a great match continue!
4. My wife works as hard as her male peers and gets paid less ... Why the reverse in tennis?. Although one
Comment: Quora: [Tennis: Why do women play best of 3 sets, while men play best of 5 sets?](http://www.quora.com/Tennis/Why-do-women-play-best-of-3-sets-while-men-play-best-of-5-sets?share=1)
Comment: @SalmanZaidi That is pretty false. In pretty much all endurance sports women compete at the same distances as men.
Answer: In addition to diggers3's answer, I would add:

Grand Slam (major) events are not ATP or WTA events - they are ITF
events and are not subject to the ATP's or WTA's rules. All non-major tournaments for both men and women are now best of 3 sets matches.
Generally in tennis, when more is on the line (think $$) then best of 5 sets are played instead of best of 3. It is a more comprehensive test and ensures that one player (or doubles team) can outperform the other and not that one player was just "hot" or "cold" for a set or two.
Other men's tournaments used to play best of 5 sets also - Masters
Series tournaments and the season-end Masters Cup (now World Tour
Finals) used to play the best of 5 sets format also but changed to
best of 3 in recent years.
Tennis, as sports go, tends to be very entrenched in tradition and
doing something like changing men's grand slam matches from best of 5
sets to best of 3 would take a lot of convincing of those in
authority to make that change. In recent years, many tennis
journalists and media figures have suggested that the grand slam
events have the men play best of 3 sets up until the second week (or
QuarterFinals) - then switch to best of 5 beyond that.
As far as having the women play best of 5 sets like the men - I do
not think that would be a good idea and would only contribute further
to player injury and fatigue. I think you would end up seeing more
retirements and walkover results than you do now. If anything, I
think the men should switch to best of 3 before women change to best
of 5.
Answer: Men have played 5 set matches and women 3.  However from 1984-1998 women did play 5 set matches to conclude the year.
Men and women just recently have been paid the same for their matches in tournaments.  This has led to men including Andy Murray to suggest women play the same length of match as the men if they are getting paid equally.
As far as strength and endurance are concerned, I believe it is pretty relative.  Women compete in strength and endurance competitions just like men.  The overall time, weight, scores, etc. may be lower for women, but it is relative.  Women would wear down in long, tough matches just as men do.
By the way, Martina Navratilova thinks that men should play 3 instead of 5.
Comment: Seems like your first link is linking to something not relevant to what you are saying.
Comment: @user0810 just referencing that women have played 5 set matches in the past.
Comment: Your first link seems to be linking to the story that [Soldier Adopts Hero Dog Shot 4 Times Point Blank Saving His Life](http://www.barstoolsports.com/barstoolu/super-page/soldier-adopts-hero-dog-shot-4-times-point-blank-saving-his-life/).
Comment: Even though it's relative (in the sense that both women would degrade similarly), it may not be completely irrelevant that men may have more stamina.  Just like a reliever with a 99mph fastball would suffer when pitching as a starter in many cases, the play might suffer in a longer match, because 'tired' matches would be more random, have a lot more errors, and overall just be less interesting.  You might be more likely for the more technically skilled player to lose - or to win.  There are many reasons to consider different lengths of matches.


Apache 2.2 + Varnish not listening to 8080 port

Question: I'm running apache 2.2 with multiple VirtualHosts and varnish cache on Centos 6.6. The problem is I can't get this to work.
httpd.conf:
Listen 8080
NameVirtualHost *:8080
<VirtualHost *:8080>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /home/example/public_html

Varnish is set to run on 80 port and DAEMON_OPTS="-a :80
default.vcl:
backend default {
.host = "127.0.0.1";
.port = "8080";}

Content of /etc/hosts
127.0.0.1 localhost
2a01:xxx:190:xxx8::2
5.0.100.000

Whenever I try to reach my virtualhost I see /var/www/html content.
What should I do?
Comment: Where ate you trying to access the system from itself or another system ?
Comment: From another system.
Comment: I have noticed error message varnishd[10982]: Child start failed: could not open sockets. If I start varnish first its ok, but when I try to start httpd Address already in use: make_sock: could not bind to address xxxxxxxx:80
Answer: Edit: I re-read the question.
Grep your httpd.conf for Listen and Include directives. If you don't find any extra Listen directives in the httpd.conf, repeat the process on any files or directories referenced by Include directives.
Something is telling Apache to continue listening on port 80, you just need to find which file/line is doing it.
Original:
your apache config for a Listen directive - it's probably trying to listen on port 80 still.
On Debian and probably Ubuntu systems this would be in /etc/apache2/ports.conf
Change the Listen 80 to Listen 8080
Answer: Problem solved! Seems there was more Listen params in ssl.conf, commented out all except Listen 443, everything seems to be working fine now.


Filter a view by a value being absent from a multiple value field

Question: Given a field "field-participants" on a node type "discussion" that references an unlimited number of users:
How can I produce a view that shows all discussions that do NOT have the current user listed in their field_participants?
The problem comes from the fact that views creates a separate row of results for each reference in field_participants in any given discussion.
I can use 'Distinct' or Aggregation to get rid of duplicate rows, but while this would work to include results (showing discussions that listed the current user as a participant) it doesn't work to exclude results.
This is because a contextual filter on the current user with "excludes" checked only excludes the one of these rows that matches the current user. It doesn't exclude all the rows from that discussion. Therefore I get false positives: the view shows all discussions that have someone other than the current user listed as a participant.
Right now I'm thinking that I either need to figure out some arcane HAVING clause and add it to the query programmatically, or try to use the pre-alpha Flag module (setting a per-user flag and filtering by that instead of field_participants).
Answer: You could use hook_views_query_alter() to modify SQL query.
/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $nids = Drupal::entityQuery('node')
      ->condition('type', 'discussion')
      ->condition('field_participants', $uid)
      ->execute();
    $query->addWhere(0, 'nid', $nids, 'NOT IN');
  }
}

In the example above we are getting ID's of excluded nodes using entity field query and then them to NOT IN condtion.
The resulting SQL query will be as follows:
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
WHERE (nid NOT IN ('1', '2', '3')) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

Alternative way would be using JOIN with extra conditions:
/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $definition = [
      'table' => 'node__field_participants',
      'field' => 'entity_id',
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'extra' => [
        0 => [
          'field' => 'field_participants_target_id',
          'value' => $uid,
        ],
      ],
    ];
    $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
    $query->addRelationship('participants', $join, 'node');
    $query->addWhere(0, 'field_participants_target_id', NULL, 'IS NULL');
  }
}

The generated SQL query:
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_participants} participants ON node_field_data.nid = participants.entity_id AND participants.field_participants_target_id = '1'
WHERE (field_participants_target_id IS NULL) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

The view itself becomes quite simple. No need of contextual argument and aggregation.
Comment: I could end up with a few top users who have participated in up to a few thousand discussions. What would the performance of this approach be like for these users?
Comment: That case needs performance benchmarking. I've added another approach to the answer.


Em R, criar uma função para mudar alguns levels de uma variavel

Question: Quero criar uma função que facilite minha vida na hora de tratar algumas variáveis
Quero uma função que receba como entrada uma base de dados, uma coluna ou variável u dessa base de dados, um vetor c especificando os levels a serem trocados e o novo nome que vai substituir tais levels.
Na verdade, tentei fazer isto diretamente com a função relevel, ma não achei muito fácil de usar.
Eu criei uma função que me retorna um vector tipo factor... mas na verdade, eu quero que a função transforme a matrix data de maneira que a variavel u já fique modificada... pois depois de usar a minha função e dou um levels(data$u) aparecem os levels antigos
  juntar<- function(data, u, c , novolevel)
 {

 ### Trasformamos nossa variável em tipo character
 data[,which(colnames(data)== u )]<- as.character(data[,which(colnames(data)== u )])

 levels<- c

 ### determinamos as coordenadas levels
 coordenadas_levels<- data[,which(colnames(data)== u )] %in% levels
 coordenadas_levels<- which(coordenadas_levels == TRUE)

 ### Fazemos a mudança
 data[,which(colnames(data)== u )][coordenadas_levels]<- novolevel

 ### Convertemos em factor
 data[,which(colnames(data)== u )]<- as.factor(data[,which(colnames(data)== u )])

 }

Obrigado
Answer: Fiz a seguinte função:
juntar <- function(dat, variavel, levls, novosLevls){
  # pega o nome da variável
  variavel <- deparse(substitute(variavel))
  # cria data frame auxiliar para dar merge
  aux <- data.frame(x = levls, .Novo = novosLevls)
  names(aux)[1] <- variavel

  # merge desse novo data frame
  dat <- merge(x = dat, y = aux, by = variavel, all.x = T)
  # substitui a variavel species pela nova
  dat[[variavel]] <- ifelse(is.na(dat$.Novo), as.character(dat[[variavel]]), as.character(dat$.Novo))
  # exclui a variavel nova
  exc <- names(dat) == ".Novo"
  dat <- dat[!exc]
  # retorna o data frame
  return(dat)
}

Acho que está funcionando. Testei com o data.set iris assim:
juntar(iris, Species, c("setosa", "virginica"), "novo") %>% head

  Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1    novo          4.9         3.1          1.5         0.1
2    novo          5.0         3.4          1.5         0.2
3    novo          4.4         2.9          1.4         0.2
4    novo          5.1         3.5          1.4         0.2
5    novo          4.9         3.0          1.4         0.2
6    novo          4.7         3.2          1.3         0.2

O último argumento novosLvls pode ser tanto um vetor do mesmo tamanho que o levls quanto um único valor.


Regex - remove four special characters between [image=][/image] BB tag

Question: In a script I have a BB-image code that can have one of these two formats:
[image=http://i459.photobucket.com/albums/xxx/enkidu-wd/test/38602_450pom.jpg][/image] (without Alt text)

[image=https://m.photobucket.com/enkidu-wd/test/38602_450pomnik.jpg]alt text[/image] (with Alt text)

My goal is to always remove these four characters: $ & ' " - but ONLY IF these characters are added as the alt text (ie. between the [image=...]ALT TEXT[/image]). If these characters appear anywhere outside of the [image][/image] tags in the $text message, they should be ignored (not removed).
I tried to use preg_replace as below, but it doesn't work.. Note that $text is a message that may or may not include this [image][/image] tag.
$start = '\[image=';
$end  = '\[\/image\]';
$text = preg_replace(
    '#('.$start.')(.*)('.$end.')#i',
    '$1'.str_replace(array('$','&','\'','"'),'').(*).'$3',
    $text
);

Comment: what is the reason behind removing the characters? i would think a better practice would be to sanitize them as you might otherwise corrupt the users original intent.
Comment: The reason is 'security', ie. when user enters one of these characters, BB-code image doesn't work.. not sure why but it's a 3rd party script.. they say it's for security..
Comment: ah, well. if that's their excuse `¯\_(ツ)_/¯`
Comment: @Tom please try my library Shortcode for parsing shortcodes https://github.com/thunderer/Shortcode .
Answer: You can try something like this:
$pattern = '~(?:\G(?!\A)|[image\b[^]]*])[^[$&\'"]*\K[$&\'"]~i';

if other BBCODE tags can be included between image tags, you can change it like this:
$pattern = '~(?:\G(?!\A)|[image\b[^]]*])[^[$&\'"]*(?:\[(?!/image\b)[^][]*][^[$&\'"]*)*\K[$&\'"]~i';

use:
$result = preg_replace($pattern, '', $yourstring);

details:
~ # pattern delimiter
(?:
    \G(?!\A) # contiguous to the previous match, not at the start of the string
  | # OR
    [image\b[^]]*] # an opening image tag
)
[^[$&\'"]* #"# all that isn't an opening square bracket or one the chars
\K # remove all that has been matched before from the match result
[$&\'"]
~i

Explanation:
Since [^[$&\'"]* forbids an opening square bracket, once the closing [/image] is reached, the contiguity is broken and the \G anchor fails. The only way to continue is to find an other opening [image...] tag.
Comment: @Tom: take the first pattern and change `[^[$&\'"]*\K[$&\'"]` to `[^][$&\'"]*\K(?:[]$&\'"]|\[(?!/image\b))` (inside a character class in pcre, if you don't want to escape the closing square bracket `]`, put it at the beginning of the class or after the negation `^`)
Comment: @Tom: you forget to escape literal opening brackets: `$pattern = '~(?:\G(?!\A)|\[image\b[^]]*])[^][$&\'"]*\K(?:[]$&\'"]|\[(?!/image\b))~i';`
Comment: Sorry - what if I also wanted to remove: [] from the alt text, what should I add? I tried: $pattern = '~(?:\G(?!\A)|[image\b[^]]*])[^[[]$&\'"]*\K[$&\'"]~i'; but it doesn't work?
Comment: OK so it should be:?

$pattern = '~(?:\G(?!\A)|[image\b[^]]*])[^][$&\'"]*\K(?:[]$&\'"]|\[(?!/image\b))~i';
Comment: Perhaps, but I can't really see since you don't use formatting (put grave accents around code)
Comment: `$pattern = '~(?:\G(?!\A)|[image\b[^]]*])[^][$&\'"]*\K(?:[]$&\'"]|[(?!/image\b))~i';` - this one :)?
Comment: The issue - when I used it like below, it shows warning: "PHP Warning:  preg_replace(): Compilation failed: unrecognized character after (? or (?- at offset"

`$text = preg_replace('~(?:\G(?!\A)|\[image\b[^]]*])[^][$&\'"]*\K(?:[]$&\'"]|\[(?????!??/image\b))~i','',$text);`
Comment: Hm, the likely issue was when copy-pasting this code, extra spaces/question marks are added for some reason, when manually entering it seems to work well : )


Generate ISO from installed system

Question: As part of my infrastructure I have many Virtual Machines running different Linux distros, under Proxmox using OpenVz.
My problem is that I need to export into a personalized installable ISOs some of the VMs I have, (installable snapshots of the current state of the VMs), some of them are running Ubuntu, some of them CentOS, so my question is:

Is there a way I can do this aware of the OS the VM is running?
Exporting VMs to ISOs the way I just explained is the way to go or
is there any other approach?

I'm open to any advice from those how has experience with this subject even if I have to setup different Virt. Technology to host the VMs.
Comment: Have you tried rsync instead of iso?
Comment: I would like if possible to take the generated ISO, mount it on anther PC and install the snapshot of the VM generated, the same it does the Proxmox people with their ISO, when you install Proxmox it comes pre-configured system, how will I be able to do this with rsync?
Comment: I don't know how ISOs are deployed. If it simply unpacked then rsync is enough (you can convert output to iso). If it is writtend directly to disk then better would be dd.
Answer: Depending on what you want to do, you might have different choice : did you think about clonezilla ? Simple tool to clone any machine (virtual or physical).
Also if you just need to install several VM with the same configuration, VM templating is the right choice : https://pve.proxmox.com/wiki/VM_Templates_and_Clones
Answer: Any bootable distributon with a dd image of your base system.

Generate ISO from installed system


Confluent jar not recognized by Eclipse

Question: I have the below dependency configuration in my pom.xml. I am able to download both the JARs, but Eclipse is not recognizing kafka-json-schema-serializer. I have tried to clean, delete, re-import, and update the project, but to no avail.
How can I solve this problem?
pom.xml configuration:
<dependency>
    <groupId>io.confluent</groupId>
    <artifactId>kafka-json-serializer</artifactId>
    <version>6.0.0</version>
</dependency>

<dependency>
    <groupId>io.confluent</groupId>
    <artifactId>kafka-json-schema-serializer</artifactId>
    <version>6.0.0</version>
</dependency>

I am also receiving the following error when running mvn install:

[WARNING] The POM for
io.confluent:kafka-schema-registry-client:jar:6.0.0 is invalid,
transitive dependencies (if any) will not be available, enable debug
logging for more details
Comment: Are you sure 6.0.0 is available yet?
Comment: @OneCricketeer I could see 6.0.0 in my company nexus repository. but I tried with 5.5.2 but still got the same issue
Comment: The message seems to be referring to `kafka-schema-registry-client`, which is not listed in your XML here
Comment: Ok I will try to include that and test
Comment: @OneCricketeerI solved the problem..issue was because some dependecy was being downloaded from everit.so i gave the url for everit in pom
Answer: You need to add the confluent repository under repositories section in your pom.xml in order to allow maven recognize the confluent dependencies. Here is the snippet:
<repositories>
  <repository>
    <id>confluent</id>
    <url>https://packages.confluent.io/maven/</url>
  </repository>
</repositories>

Comment: i have already added that..taht why jar fetting downloaded
Comment: i am able to download jar only for kafka-json-serializer but no jar is getting downloaded for kafka-json-schema-serializer
Comment: Did you try to run `mvn clean install`? Also if you can check `.m2` folder and remove any repository named as kafka-json-schema-serializer and run the `mvn clean install`
Comment: I have done the both the steps as described by you but to noavail. In between the repository url is pointing to my organisation nexus url.
Comment: Do I need to delete the .m2 folder and then run man clean install?
Comment: The error shows  `kafka-schema-registry-client` jar is invalid. Can you try deleting that and run `mvn clean install`?
Comment: Yes I will try and let you know.I have logged out of work for now
Comment: solved the problem..issue was because some dependecy was being downloaded from everit.so i gave the url for everit in pom
Comment: @NishuTayal it worked for me, but can you please explain, why we need to add the confluent repository explicitly while other dependencies from different vendors get downloaded without their repo addition in po.xml?

Confluent jar not recognized by Eclipse


Convertendo mp3 para ogg em php no joomla

Question: Estou tentando converter um arquivo mp3 para ogg usando o ffmpeg.exe o problema é que o Joomla não me deixa executar um arquivo externo, mesmo no mesmo diretório.
<?php exec('C:\\path\\to\\ffmpeg.exe -y -i file.mp3 -acodec libvorbis file.ogg'); ?>

Esse código não retorna nenhum erro, ele só não executa.
Existe alguma outra forma para executar o ffmpeg.exe dentro do Joomla?
Ou existe uma forma de converter direto via php que o Joomla aceite?
Answer: Consegui executar e converter o arquivo, porém somente no mesmo diretório onde o ffmpeg.exe está, depois tive que move-lo.
Antes de fazer a chamada exec ativei o safe_mode e adicionei o diretório onde estou trabalhando e funcionou.
ini_set('safe_mode',true);
ini_set('safe_mode_exec_dir','C:\\path\\to\\');
exec('C:\\path\\to\\ffmpeg.exe -y -i file.mp3 -acodec libvorbis file.ogg');

Não sei se essa é a melhor forma, porém assim funcionou. Movi o arquivo utilizando o JFile::move().
Answer: O safe_mode esta em desuso no PHP5.3 e foi removido no PHP5.4
O caminho mais correto é utilizar a função exec com $output e passar os argumentos com escapeshellcmd (no caso do Windows), se for linux/like-unix use o comando escapeshellarg
Exemplo:
<?php
$comando = 'C:\\path\\to\\ffmpeg.exe';
$argumentos = escapeshellcmd('-y -i file.mp3 -acodec libvorbis file.ogg');

exec($comando . ' ' . $argumentos, $output);

echo '
';
print_r($output);
echo '
';