Syncing Cubase with External Sequencer

Question: I am running Cubase Elements, trying to get Cubase to sync with external source. Or rather, get the external source to sync with Cubase.
I have set the external sequencer to use external midi.
Set up the midi settings in Cubase (see image attached)

Cubase is reading midi data ok, when I press record, it is sending out the start data so the external midi device starts ok.
The issue is that if I record a track from the midi sequencer, then record another track from the squencer, then the two tracks do not match, they are out of sync significantly.
The sync button the transport floating bar show the sync as internal but offline, even during recording it says that.
I am assuming that this may be the cause, maybe its not correcting the external source properly?
What do I need to do to get this to work.
I just thought setting the sync to internal on Cubase and external on the device would have done the job.
Thanks!
Answer: I found this link which describes midi syncing in Cubase in general. I think because you have "Internal Timecode" selected, this may be causing the synchronization to be off. If the frame rate of your external device is different from that of Cubase, then the two will be out of sync. If they're always off by the same amount, this is probably your issue. (If they're off by a different, random amount each time, it's probably a latency issue.)
Try selecting "MIDI Timecode" as your source and set Cubase as the master. Here's a link to instructions in the Cubase 4 manual on how to do this. Hopefully it will be similar enough in your version to figure it out from these.

Syncing Cubase with External Sequencer


What is the sudden sharp pitch increase in Old Country/Rockabilly

Question: You don't hear it much in country music nowadays but what is that technique or term where artists like Johnny Horton and the like make a sudden whoop or yelp at the end of a line (North to Alaska is a good example at 0:37-38).
I looked to see if it was twang, but that doesn't seem right. I even researched into the origins of most country and rockabilly-esque music, to see if it was a term originating in the African American Culture but no luck so far. Might it be yodeling?
Answer: It's definitely NOT yodeling and "twang" can describe other aspects of the rockabilly country style of singing besides the sharp pitch increase you refer to.
I am not sure if there is actually an official name for that technique.
I call it a "Hillbilly Hiccup" and I have used it myself in some of my original country songs.  In fact I first herd the term "hillbilly hiccup" from the engineer in a recording studio where I was recording one of my songs.
That's not an official term, but it is descriptive and catchy - so I will continue to use that phrase to describe the technique until someone gives me a better term.
Comment: Oh I see! Also thanks for the edit I'm on Mobile. I was discussing different songs of that genre with a friend and it bugged me that I couldn't find any sort of info for it. I really like that technique and its difficult to find any good info on it. I guess I'll use this term unless someone comes along with anything official aha . Thanks for all the info


Override imported class variables - django/python

Question: I need to override variables (or pass dynamic data) to imported class.
filters.py
import django_filters
from .models import Gate, Tram, OperationArea, Bogie
from distutils.util import strtobool
from django import forms

class GateFilter(django_filters.FilterSet):

    # Prepare dynamic lists with choices
    tram_list = [(id, number) for id, number in Tram.objects.all().values_list('id', 'number')]
    bogie_list = [(id, number) for id, number in Bogie.objects.all().values_list('id', 'number')]
    area_list = [(id, area) for id, area in OperationArea.objects.all().values_list('id', 'area')]
    # Generate fields
    tram = django_filters.MultipleChoiceFilter(choices=tram_list, label=u'Tramwaj')
    car = django_filters.MultipleChoiceFilter(choices=Gate.CAR_SYMBOLS, label=u'Człon')
    bogie = django_filters.MultipleChoiceFilter(choices=bogie_list, label=u'Wózek')
    bogie_type = django_filters.MultipleChoiceFilter(choices=Gate.BOGIE_TYPES, label=u'Typ wózka')
    area = django_filters.MultipleChoiceFilter(choices=area_list, label=u'Obszar')
    operation_no = django_filters.CharFilter(label=u'Numer operacji', widget=forms.TextInput(attrs={'size': '16px'}))
    status = django_filters.MultipleChoiceFilter(choices=Gate.GATE_STATUSES, label=u'Status')
    rating = django_filters.MultipleChoiceFilter(choices=Gate.GATE_GRADES, label=u'Ocena')

    class Meta:
        pass

views.py
from .filters import GateFilter

class GateListView(generic.ListView):

    queryset = None
    gate_type = None
    template_name = 'qapp/gate/list.html'
    context_object_name = 'gate_list'
    paginate_by = 20

    def get_queryset(self):
        # Type is stored in database as big-letter word, so 'bjc' != 'BJC'.
        if self.gate_type.upper() == 'BJW':
            ordering = ['bogie', 'bogie_type']
        else:
            ordering = ['tram', 'car']
        queryset = Gate.objects.filter(type=self.gate_type.upper()).order_by(*ordering)
        self.gate_list = GateFilter(self.request.GET, queryset=queryset)
        return self.gate_list.qs.distinct()

    def get_context_data(self, **kwargs):
        context = super(GateListView, self).get_context_data(**kwargs)
        # Return Gate.type to template.
        context['gate_type'] = self.gate_type
        # Return object (for generating form) to template.
        context['gate_list_filter'] = self.gate_list
        return context

As you can see, in the filters.py, the data for variables tram_list, bogie_list and area_list are dynamic (fetched from database).
But during importing this class to views.py, this data becomes static.
I tried to override this values:

using @classmethod decorator in class GateFilter, and calling it
before setting self.gate_list object,
in views.py using GateFilter.tram_list (and the rest) notation,

No luck.
I can't use reload() function, due to import type (from .filters import GateFilter).
Currently for update lists in filters.py I need to rerun whole app.
This is unacceptable for business logic of my app.
Answer: This is the wrong approach. Rather, you should be using the filters that are aware of querysets and that evaluate them when required: ModelChoiceFilter and ModelMultipleChoiceFilter.
class GateFilter(django_filters.FilterSet):
    team = django_filters.ModelMultipleChoiceFilter(queryset=Tram.objects.all())

Comment: I am sure it's not easy to be superhero :) Thanks @Daniel Roseman. Your solution works perfectly.
Comment: Don't forget to accept the answer if it helped you, to signal to future searchers that it solved your problem.


HTTPS/SSL not working with Cups

Question: I have a site
mysite.com
and a printer
mysite.com:631/printers/myprinter
Well, https:// www.mysite.com works perfectly and is validated, but https:// www.mysite.com:631/printers/myprinter won't. It says that the connection is not secured and I cannot install the printer.
This is what I have in conf.d in my CUPS server:
DefaultEncryption Required
ServerCertificate /etc/letsencrypt/live/mysite/cert.pem
ServerKey /etc/letsencrypt/live/mysite/privkey.pem
SSLPort 443

Any help making the printer and the site https?
Comment: if you configured cups to use port 443, why are you trying to access it via port 631?
Comment: @GeraldSchneider CUPS server is 631 by default. I tried with and without SSLPort but it doesn't work anyway. Guess you are onto something. I am a programmer not a sysadmin...
Answer: Copy your SSL (example LetsEncrypt ) to cups directory, as shown below:
cat /etc/letsencrypt/live/yourdomain.com/fullchain.pem >> /etc/cups/ssl/server.crt
cat /etc/letsencrypt/live/yourdomain.com/privkey.pem >> /etc/cups/ssl/server.key

restart cups-server:
systemctl restart cups  # on CentOS

Answer: So you also need to make sure in /etc/cups/ssl there are alone two files.
server.key and server.crt adding any extra files to this directory broke ssl for me.
But make sure they are links to your lets encrypt folder as other have said.
Answer: Gonna add some notes while I'm here.
I am using Nginx to forward a pretty domain over the CUPS IP/port.
This site here (not related to me) made it click.
Anyway in my nginx config I have a location block like this:
location /printers {
    // this is the info that came from the site mentioned
    proxy_pass http://localhost:631;
    proxy_set_header Host "127.0.0.1";
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
}

I generated my cert with Lets Encrypt, goes to same folder as mentioned by SchiWaGoA
I used symlink instead of cat as I had permission problems eg:
ln -s /lets-encrypt-path/fullchain.pem /cups-ssl-path/server.crt (same as above)

cupds.conf
I have Listen localhost:631 on
<Location />
  Order allow, deny
  Allow from @LOCAL
</Location>

At the bottom of this file I added the encryption stuff as mine didn't have it
DefaultEncryption Required
ServerCertificate /etc/cups/ssl/server.crt
ServerKey /etc/cups/ssl/server.key

And that's it, was able to add the printer on my Windows 10 client using shared hostname url with the https://example.com/printers/printer-name url scheme and then MS PS driver.
Note. I'm not 100% on the <Location /> block so check if it suits your needs.
Will add atm I'm noticing the server keeps going down, unlike my previous non https CUPS, odd.
Looks like you need to add this line to cupsd.conf
ServerAlias *
One of my problems anyway, will monitor to see if it improves.
Seems to have improved after I restarted, will report back if I discover some specific reason it was going down often. The non-https one has been up for months.
I ended up modifying the systemd file
Restart=always
RestartSec=3

Also the cert lines are supposed to go in cups-files.conf instead of cupsd.conf according to the debug logs of cups. Not a problem now but will be in the future.

HTTPS/SSL not working with Cups


system.windows.interactivity.dll

Question: I would like to know, if there is any way to know, what resources system.windows.interactivity.dll are loading?
This dll has a number of folders, containing single file: System.Windows.Interactivity.resources.dll, and I want to discover, what file is loaded during run time. How could it be done?
Answer: You can use Process Explorer utility tool to get the snapshot of assemblies and their resources loaded in memory. You can download it from here
Comment: I have tried this already. I see the System.Windows.Interactivity.dll in the list, but I didn't find any way to discover what resources.dll it is using.

system.windows.interactivity.dll


pk is passed but data not displayed

Question: I have a model that contains some judgments along with their title. Now i want to display the judgement when the related title is clicked. i have written the following code:
models.py
class Laws(models.Model):
    date= models.DateField(default=timezone.now)
    title= models.CharField(max_length=225, help_text="judgement title")
    judgements= RichTextField(blank=True, null= True)
    law_type= models.CharField(max_length=40, choices= type_of_law)
    law_category= models.CharField(max_length=60, choices= category)

views.py
class DocView(ListView):
    model= Laws
    template_name = 'doc.html'

class Doc1DetailView(DetailView):
    model= Laws
    template_name = 'doc1.html'

urls.py
urlpatterns=[
    path('doc', DocView.as_view(), name='doc' ),
    path('doc1/<int:pk>', Doc1DetailView.as_view(), name='doc1' ),
]

and the html files are
doc.html
{% for data in object_list %}

        {{data.title}}

{% endfor %}

doc1.html

{{data.judgements}}

I refered to a video in youtube and wrote this code his was working and mine not. i have chamged nothing from that code still the data doesn't show up in doc1.html. No filed is empty here.
please rectify my code and tell me what i am doing wrong here.
Answer: The Laws object is not passed as data, but as object (and also as laws), so you render this with:

{{ object.judgements }}

Note: normally a Django model is given a singular name, so Law instead of Laws.
Comment: thank you so much sir, thsi solved my probelm also i shall rectify the model name to singular

pk is passed but data not displayed


Downgrade pre installed Python version on Ubuntu 18.04

Question: Ubuntu 18.04 comes with Python3.6 and I've to downgrade it to 3.5 to support few projects.
I'm aware of the fact that, touching installations coming as part of OS will lead to the OS level issues.. Is there any safe way to achieve this ?
Answer: Managing multiple python versions could be achieved with  venv for Python 3
Where venv manages virtual environments for a specific Python version.
$ sudo apt install python3.5
python3.5 -m venv env/place/you/want/to/save/to which will create a sandbox with the desired python version

venv is available by default in Python 3.3 and later, and installs pip and setuptools into created virtual environments .

venv module provides support for creating lightweight "virtual environments" with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.

source <VENV_NAME>/bin/activate to switch into your virtual env <VENV_NAME> and used the desired python version


console shows 6 when i multiply integer (3) into string ("2") in JavaScript

Question: Hey could you please tell me why this happens when I add
var a = 3
var b = "2"
console.log(a + b ) // 32

the above output is right
But when I do subtraction then it shows
console.log(a - b ) // 1

and it is the same for multiplication (o/p:- 6) and when I divide the output is (1.5) why this is happing
when I do other arithmetic operations except for addition.
Answer: The '+' operator when operated on string does concatenation. The 'b' variable is a string literal and thats why you are getting output '32'.
Comment: I know about the this but why this happens when I do other arithmetic operations like multiplication, substraction, divide
Answer: The + operator is pecial in this sense. It will add numbers, but concatenate if it encounters a string.
However, a behavior like this makes no sense for other operators.
For example, what do you expect "foo" - 2 to do? And "foo" / 3? Divide "foo" into  3 parts? Then what about 3 / "foo"?
So, the general rule is rather that arithmetic operators always coerce their arguments to numbers, and the addition / concatenation  operator(+) is the only exception.

Actually, the comparison operators (<, <=, >, >=) can also work on strings, but those aren't arithmetic operators.


What are some methods of quantifying "interaction" among features for a model?

Question: The Gist
What are some methods of quantifying "interaction" among features for a model? I will give two short motivating examples to clarify what I mean by "interaction".
Motivating Examples

With a linear model, it is likely that a few features will
dominate some of the other features to some degree. This does not
necessarily mean that those other features are bad, although they
will probably be given a lower weight and would have performed
better in the absence of the dominating features (or if the dominating features had been given a lower weight).
With a tree ensemble model, it is likely that a more important feature will be split near the top of the tree and that some other dominated feature will get its chance to shine after that split or in some split that does contain the dominating feature.

Specifically
It would be useful to be able to represent relationships between features in some humanly interpretable way. I would especially want to see relationships between some feature F1 and some F2 in which F2 shines in the absence of F1 or contributes a lot more information towards predicting the outcome when F1 has been split (as in a decision tree).
This information might be represented as a list of triples (F2, F1, score) sorted in descending order by score, where score might represent how much more information F2 contributes towards predicting the outcome in the absence of F1 (or after F1 has been split in the case of a tree ensemble).
It's possible that the linear and tree ensemble may represent separate cases (absence of F1 vs splitting F1). It is also possible that there may be multiple useful metrics for each case. I do not necessarily want to select or remove features, but merely to see how they interact. (In my particular case, I have about 100 features.)
Answer: Good questions even though no single response can address all of your concerns. This will be, at best, a partial answer. It will also be from an applied -- not theoretical level -- it is practical advice. It sounds like you're thinking only of two-way interactions but, obviously, three-way and higher interactions are possible. In fact, one can imagine extending the interactions up to a "fully saturated" limit that would exhaust the degrees of freedom. So, let's limit the discussion to two-way interactions which are easily generalizable to higher ones.
Let's also mention that statistical theory recommends (or prescribes) that the appropriate main effects be retained in any model containing interactions with those effects. This recommendation isn't always followed or observed, but it needs to be noted -- do with it what you will. The more important thing to note is that the interpretation of the model parameters shifts from one of being conditional on the mean values of the features when there are only main effects (i.e., for models that are evaluating the mean as in OLS regression. This would change with differing functional forms such as quantile regression) to an interpretation in the presence of interactions that is conditional on the features being evaluated at zero. In applied terms, this means that, before taking the interaction, the features should be normalized to a mean of zero. Regrettably, none of the points made in this paragraph are without controversy and many statisticians can and will disagree with them. I can provide references supporting these statements if anyone is interested.
That said, the first approach to incorporating interactions can be described as a "global," "brute force" or "shotgun" approach insofar as all possible permutations of (two-way) interactions are evaluated. I say permutations and not combinations since interactions are symmetric -- it doesn't matter if the interaction is F1 with F2 or F2 with F1. Obviously, with more than a few features this approach would quickly result in an unmanageably large number of interactions. Regardless, it is possible and has been done.
A second, somewhat more reasonable approach is to use subject matter expert (SME) knowledge to make judgments as to which interactions are interesting or useful to model. This has the advantage of immediately reducing the number of interactions to a manageable size as well as minimizing time wasted on potentially fruitless exploratory analysis. On the other hand, this approach has the disadvantage that it presumes the SME knows everything there is to know about the data (in my experience this is rarely, if ever, the case), thereby precluding the possibility of serendipitously uncovering new relationships.
There is a third approach that is less reliant on SMEs and more empirically driven. This method assumes, as you have noted, that a relative handful of features are explanatorily important, i.e., they rank towards the top of relative variable importance. By focusing interactions on that subset of features, it becomes possible to derive a more manageably sized set of interactions, as long as there aren't too many important, candidate features.
So, how might one address your concern with pulling together an "ensemble" of metrics providing statistically useful information regarding the relationships between and among the features and their interactions. For me, this is entirely a function of the analyst's appetite, patience and time available for playing around with the results from an ensemble of differently specified models. A simple example of how this could work is OLS ANOVA with two features and one two-way interaction. Depending on the software, it is possible to specify that the sums of squares of the features and interaction be treated independently in entering the model -- some packages describe this as SS3 (for sums of squares type 3). One could also try SS1, SS2 or SS4 which invoke different orderings of the independent variables. By playing around with the permutations of these orderings, the "humanly interpretable" information can be deduced...that is, up to the limits of human cognition in juggling a large number of differing metrics. Ulrike Groemping has done the most work in reviewing and explaining the different statistical approaches to this kind of model evaluation of relative variable importance. She also has an R module which does a computationally intensive version of this called RELAIMPO. Check her papers out.
My personal solution is different from hers. Imagine you have summary performance statistics across a set of different model specifications returning metrics such as score, r-square, AIC, different specifications of SS types, and so on. Making sure they are all in a consistent unit of analysis would be a necessary step. Once that's done and with enough observed summary values, a PCA of these metrics becomes feasible. By scoring the input data based on the first PCA, then a summary ranking of the units under analysis is possible. I'm not sure I'm explaining this well enough but, having gotten it to work, it can be a useful tool for information reduction particularly in the case when one has a set of competing summary metrics. Pushback from other CV participants is expected here.
Answer: A linear model wont in the general case make your features sparse, unless you eg choose a loss function that encourages sparsity, such as L1/Lasso.
MSE loss on a linear model will not encourage sparsity, or one feature to dominate another, in general, for example.
In the case that you are using Lasso/L1 loss, then some of your features are likely to be driven to zero. You can then use eg the correlation matrix, $X^TX$, to look at correlations between the non-zero features and the zero features.


Regex Match Next Whole Line After Successful Match

Question: I have lots of lines:
<code>"extra": {
"address": "112 Hart blah blah DC 20510",
"contact_form": "https://www.blah.html",
"office": "112 Hart Building"
</code>
Basically, sometimes there is not a "contact_form" line after the "address" line and sometimes there is, but there is always an "address" line.
So, after matching the address line: ("address":\s{1}.*\r?)
I want to match the next whole line, whatever it is.  After that I'll figure out if the line is the contact_form line or not.
Thanks!
Comment: If it's Json [use a parser](http://stackoverflow.com/questions/21676708/simple-working-example-of-json-net-in-vb-net) and make your life easier.
Comment: It is Json, and I plan on implementing that some time, but for now I just want to use Regex.
Comment: Please provide example inputs and expected outputs.
Answer: If you're intent on using regex, you could use positive lookbehind to match the line that comes after the address line, something like this:
<code>(?m)(?<=("address":.*)\r?\n)^.*$
</code>
Comment: Great answer, just what I was looking for.  Thanks!


How do I run 2 environments of SkyDns/Skydock simultaneously?

Question: Ref: https://github.com/crosbymichael/skydock
https://github.com/crosbymichael/skydns
First I fired up those two instances.
docker run -d -p 8080:8080 -p 172.17.42.1:53:53/udp --name skydns crosbymichael/skydns -nameserver 188.8.131.52:53 -domain docker

docker run -d -v /var/run/docker.sock:/docker.sock --name skydock crosbymichael/skydock -ttl 30 -environment dev -s   /docker.sock -domain docker -name skydns

And this setup is working as expected.
Now I want to spawn another production environment. This time I only fired another skydock container with the env production as follows.
docker run -d -v /var/run/docker.sock:/docker.sock --name skydock-prod crosbymichael/skydock -ttl 30 -environment prod -s /docker.sock -domain docker -name skydns

Querying the api doesn't show the production skydoc.
curl $(docker-ip):8080/skydns/services/

And now I am wondering on how to setup the production version of skydock.
Do I have to run in separate docker-host?
If I fire up in the same docker host, in which DNS url entry will the new containers be available?
Do I have to pass some flags/variables when I fire new containers to be available in the production env?
Answer: I don't about the way to make 2 or more skydock instances listen to the same docker.sock (within single host machine). I think conceptually it is not right. Docker containers know nothing about your logical enviroments (production, staging, ...)
I got a multihost setup with skydns and skydock. I run skydns on a separate host. Each of two other servers run single instance of skydock, which registers all docker containers ips in centralised SkyDNS, so that all containers are visible by dns name across different physical hosts.
All of that is working on top of Flannel network overlay https://github.com/coreos/flannel (which requires etcd)
Comment: This makes sense. @viktortnk Have you any notes/posts of those commands to setup skydns in separate host and such as you've described anywhere? It would be more helpful.
Comment: How are you binding docker to dns and flannel?
Comment: /usr/bin/docker -d --bip=${FLANNEL_SUBNET} --mtu=${FLANNEL_MTU}. I'd recommend looking at this repo for config files examples https://github.com/kelseyhightower/kubernetes-fleet-tutorial
Comment: For the SkyDNS https://www.youtube.com/watch?v=Nw42q1ofrV0. docker run -d --name skydns -p 53:53/udp -p 8080:8080/tcp crosbymichael/skydns:latest -nameserver="22.214.171.124:53" -domain="cluster.whisk.com"  Then on each node with skydock:  docker run -d -v /var/run/docker.sock:/docker.sock --name skydock crosbymichael/skydock -ttl 30 -environment dev -s /docker.sock -domain cluster.whisk.com -skydns="http://SKYDNS_IP_ADDRESS:8080"


Use "view" inside a loop / clone a view

Question: I'm trying to use a view inside a loop but it's not working,
I'm using "views_get_view($name)" but "clone_view()" / "copy()" is not working, I can't create another reference.
I have a view with a contextual filter and by settings different arguments on each loop with "set_arguments" the result should be different. I get the result for the first loop but all the others are empty.
I'm trying to use something like this:
for($i=2; $i<=4; $i++){

    $view = views_get_view('view_name');
    $view->set_display($i);
    $view->set_arguments(array($i));
    $view->execute();

    dpm($view->result);
}

and the result is:
... (Array, 4 elements)

... (Array, 0 elements)

... (Array, 0 elements)

The first result is working great (4 elements inside the array) but the others are empty.
I know the above code is not correct as this is not the way to handle objects but at least you will know what I want, a different result for each set of arguments, arguments which are connected to a contextual filter inside view.
Can someone help me with a method to use the view inside a loop ?
I only managed to generate the result once no mather what.
Thanks.
Answer: The $view->set_display($i); will not work unless you have an integer as the display name of your view (which is something I'm not sure if possible or if you need it).
try changing the $i in $view->set_display($i); to the display name of your view:
for($i=2; $i<=4; $i++){

    $view = views_get_view('view_name');
    $view->set_display('display_name'); //Example: page, page_1, block_1, custom_display_name ..etc
    $view->set_arguments(array($i));
    $view->execute();

    dpm($view->result);
}

Comment: Tried that allready, same result. The function will work also without set_display so that step is not important.
Comment: Have you tried:

`$view = views_get_view('view_name', TRUE);`
Comment: Yes, same result. I've also tried "unset($view)" at the end of each iteration but with no luck. It seems I can't use a view multiple times on a page and I can't understand why.
Answer: The problem was/is "$view->execute", it seems that I can run this method only once no matter what I do, so I had to approach the issue different.
I've found another solution:
for($i=7; $i<=10; $i++){

        $view = views_get_view('edc_menu', TRUE);
        $view->set_arguments(array(2, $i));
        $view->use_pager();
        $view->set_items_per_page(0);
        $view->build();

        $q = edcmenu_qc($view->build_info['query'], TRUE);
        $q = db_query($q);

        foreach($q AS $key => $item){
            // Generate array with results.
        }
    }

I extracted the view query from each iteration then I used db_query() to run it.
edcmenu_qc() is a method based on "devel" method dpq() to convert the object query into a string so I can pass it further to db_query()
function edcmenu_qc($query, $return = FALSE) {

    if (method_exists($query, 'preExecute')) {
        $query->preExecute();
    }
    $sql = (string) $query;
    $quoted = array();
    $connection = Database::getConnection();
    foreach ((array) $query->arguments() as $key => $val) {
        $quoted[$key] = $connection->quote($val);
    }
    $sql = strtr($sql, $quoted);
    if ($return) {
        return $sql;
    }

    return ($return ? NULL : $query);
}

Problem solved and eveyrthing is working perfect.

Use "view" inside a loop / clone a view


How to set the app language in android within a service? (FirebaseMessagingService)

Question: I am building an app, in which you can change the language of the app, independent of your phone/tablet language. It is working well inside activities, but it is not working inside a notification service. I want to be able to show the notification to the user in the language, he or she, specified in the app.
Here is the code I use for setting the language in my MainActivity
<code>@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(LanguageHelper.onAttach(newBase, "sr_ME"));
}
</code>
And here is the code from the LanguageHelper.onAttach method. This code is from this tutorial: https://www.youtube.com/watch?v=ugMTnF1R3Io
<code>public static Context onAttach(Context context, String defaultLanguage) {
    String lang = getPersistedData(context, defaultLanguage);
    return setLocale(context, lang);
}

public static Context setLocale(Context context, String lang) {
    persist(context, lang);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResources(context, lang);
    }

    return updateResourcesLegacy(context, lang);
}

@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String lang) {
    Locale locale = new Locale(lang);
    Locale.setDefault(locale);

    Configuration config = context.getResources().getConfiguration();
    config.setLocale(locale);
    config.setLayoutDirection(locale);

    return context.createConfigurationContext(config);
}

@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String lang) {
    Locale locale = new Locale(lang);
    Locale.setDefault(locale);

    Resources resources = context.getResources();

    Configuration config = resources.getConfiguration();
    config.locale = locale;
    if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.setLayoutDirection(locale);
    }

    resources.updateConfiguration(config, resources.getDisplayMetrics());
    return context;
}

private static void persist(Context context, String lang) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.shared_prefs_logging), MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    editor.putString(context.getResources().getString(R.string.user_default_language), lang);
    editor.commit();
}
</code>
It seems that attachBaseContext is doing nothing inside my service class which extends FirebaseMessagingService, becuase I always get the notification in the language of my device.
I will really appreciate your help.
Best regards!
Comment: Notification will show by system Launcher and the launcher use system language. so you can't show notification in any language except system language
Comment: Thank you for your answer. Could there be any workaround for this? I tried creating a string array like this:

    ``
    `Imate novu poruku`
    `You have a new message`
    ``

And then, when in onCreate of my service, I read what is the language user chose, save it in a variable. I create an array of strings ["sr_ME", "en"], and then find out which index to use, and than use the same index when selecting a string from string-array
Comment: Yes. I think this is only workaround. You should detect current system language and handle resources in that language by yourself. but it has a problem and that is you can't change direction of notification in RTL languages by default, and you should create your own notification layout.
Answer: Firebase service and other services useds ApplicationContext, you should update configuration in applicationContext in onCreate() and in onConfigurationChanged()
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/29818143)


Deleting a subset from a topological manifold

Question: Consider an $n$-topological manifold $M$. We remove a subset $A$ from $M$. Are there cases where $M-A$ is no longer a topological manifold.  In case we suppose that $M-A$ is still a manifold, what should be the dimension of $M-A$, is it exactly $n$ or some other integer $\leq n$ ? thank you !!
Comment: It can be anything $\le n$. You can remove a subset of the sphere to get a circle or single point.
Comment: Take $\mathbb{R}^2$ and take out $A:=\left\{\left(\frac{1}{n},0\right): n\in\mathbb{Z}_{>0}\right\}$: $\mathbb{R}^2\setminus A$ is no more a manifold, in fact the origin has no neighborhood homeomorphic to $\mathbb{R}^2$ (It is neither a CW complex anymore).
Comment: Take out from $S^2$ the equator minus a point: a neighborhood of "the point" is not homeomorphic to $\mathbb{R}^2$.
Comment: @AymanHourieh seeing the example of the circle in the sphere, I wonder if we delete a **connected** subset $A$ would we always get a manifold with same dimension as $M$  ?
Answer: Here's the complete answer to part of your question: If $M$ is a topological manifold of dimension $n$ and $A\subseteq M$, then $M\smallsetminus A$ is a topological manifold of dimension $n$ (in the subspace topology) if and only if $A$ is closed in $M$.
One direction is easy to prove: If $A$ is closed, then $U=M\smallsetminus A$ is an open subset of $M$, and an open subset of an $n$-manifold is easily shown to be an $n$-manifold.
Conversely, suppose $M\smallsetminus A$ is an $n$-manifold in the subspace topology. We'll show that $U = M\smallsetminus A$ is open in $M$. Given $p\in U$, there exist a neighborhood $V$ of $p$ in $U$ and a homeomorphism $\phi\colon V\to \widehat V$ to some open subset $\widehat V\subseteq\mathbb R^n$.  If $\iota\colon U\hookrightarrow M$ is the inclusion map, then $\iota\circ\phi^{-1}$ is an injective continuous map from $\widehat V$ into $M$, and it follows from invariance of domain that $\iota(\widehat V) = V$ is open in $M$.  Thus each point of $U$ has an open neighborhood in $M$, so $U$ is open.
The question of when $M\smallsetminus A$ is a manifold of some dimension less than $n$ is much more complicated, and I doubt that there's any simple necessary and sufficient condition.


If $X \subset Y \subset Z$ are Metric Spaces with the same metric, is $\overline{X}$ the same be it taken in relation to $Y$ or $Z$?

Question: If $X \subset Y \subset Z$ are Metric Spaces, if $d_Z(\cdot,\cdot):Z \times Z \rightarrow \mathbb{K}$ is the metric of $Z$, $d_Y(\cdot,\cdot):=d_Z(\cdot,\cdot)\restriction_{Y\times Y}$ is the metric of $Y$ and $d_X(\cdot,\cdot):=d_Z(\cdot,\cdot)\restriction_{X\times X}$ the metric of $X$ are the following sets the same ?
$$\overline{X}_Y := \{y\in Y\, | \,\,d_Y(y,X) =0 \} \,;\ \ \ \ \ \ \ \ d_Y(y,X) := \inf_{y' \in Y}d_Y(y,y')$$
$$\overline{X}_Z := \{z\in Z\, | \,\,d_Z(z,X) =0 \} \,;\ \ \ \ \ \ \ \ d_Z(z,X) := \inf_{z' \in Z}d_Y(z,z')$$
That is $\overline{X}_Y = \overline{X}_Z\,?$ If so can this be generalised for when $X,Y$ and $Z$ are topological spaces and the closure of $X$ being defined by the topological closure ?( i belive it to be something like the intersection of all closed sets in relation to $K= Y$ or $Z$ that contain $X$).
Comment: $\overline{X}_Y = Y\cap \overline{X}_Z$
Comment: What if $Y=X$ and $X$ is not closed in $Z$?  (e.g. $X = Y = (0,1)$, $Z = \mathbb{R}$)
Comment: @DanielSchepler I belive that in the case $X = Y ,  \overline{X}_Y = X $, therefore perhaps i should put proper inclusion, but $X$ doesn't need to be closed in Z, that is the hole point.
Comment: The two are the same if $Y$ is a closed subset of $Z$.
Answer: Here's the point-set way to get to the right conclusion.  If you want to do it in metrics, everything is still true.  First prove the following:
Lemma:  Let $A$ be a subset of a space $Z$ and give $A$ the corresponding subspace topology. Prove that a set $C$ is closed in the subspace topology on $A$ if and only if $C = A \cap K$ for some set $K$ closed in $Z$.
With that it's not hard to prove the following, which is the answer to your question:
Proposition:  Suppose we have a chain $X \subseteq Y \subseteq Z$ where $Z$ is a topological space.  Write $\overline{X}_Z$ for the closure of $X$ in the space $Z$ and $\overline{X}_Y$ for the closure of $X$ in the subspace topology on $Y$ inherited from $Z$.  Then $\overline{X}_Y = Y \cap \overline{X}_Z$.
From this, you get that $\overline{X}_Y = \overline{X}_Z$ if $Y$ is a closed set in $Z$.
Answer: I belive i have come to the conclusion that if i take $Y=X\ \cup \{y\}$ such that $y\not\in X$ and $d_Y(y,X) = 0$ then $\overline{X}_Y = Y$  and if $Z=Y \ \cup \{z\}$ such that $z\not\in Y$ and $d_Z(z,X)=0$ then $\overline{X}_Z = Z$. So it is false.


Why is 0 factorial is equal to 1 ??

Question: Why is 0! Equal to 1? Can anyone can help to understand ? Please explain with discription
Comment: If you Google it, you will find thousands of results
Answer: Let's start from $5! = 5*4*3*2*1$
Now if we go down one number to $4!$ essentially we divide $5!$ by $5.$
Following that logic going down to $3!$ we divide $4!$ by 4 keep doing this till $1!$. So to get $0!$ all we do is divide $1!$ by $1$

Why is 0 factorial is equal to 1 ??


Not able to run terraform from jenkins

Question: I am trying to run a terraform command from jenkins pipeline but I am getting an error stating that, "terraform command not found". I have installed terraform plugins as well as terraform in the system where jenkins is also installed. Please help.
Comment: Welcome to Stack Overflow _ This website is more about correcting code that has already been written and which may have issues that you're seeking help with _ You might be better consulting "terraform plugin" documentation for the information that you're seeking _ Please take a moment to visit the Help Center and specifically the section on 'Asking' for more details on writing questions >>> stackoverflow.com/help/asking
Answer: I haven't used Jenkins' Terraform plugin yet but have you considered to run inside a docker container which has preinstalled terraform?

Not able to run terraform from jenkins


MemoryStream vs Stream

Question: Qual seria a principal diferença entre os dois?
Há vantagens no ganho de performance?
Para utilização web, qual o mais indicado?
Estou utilizando para "ler" um array Byte[]:
private void bytetoStrem(byte[] pdf)
{
    Stream pdfStream = new MemoryStream(pdf);

    pdfViewer1.LoadDocument(pdfStream);
}

Comment: Como o método principal (que chama esse `bytetoStrem`) carrega esse array de bytes do PDF? É uma API que retorna para ele? Ou você lê de uma pasta no próprio servidor?
Answer:
Qual seria a principal diferença entre os dois?

O Stream é uma classe abstrata base para todos os streams (definição mais completa)  que podem existir, assim você pode codificar algoritmos que precisem de stream sem saber de onde eles vêm e vão.
Já MemoryStream é uma classe concreta, obviamente derivada de Stream como pode ser observado no código da pergunta, e trabalha com fluxos de dados na memória bruta.

Há vantagens no ganho de performance?

Em ralação a que? Entre um deles? Como um é abstrato sequer pode ser comparado. Se for com outros precisa ver a implementação de cada um, depende do hardware onde ele trabalha.

Para utilização web, qual o mais indicado?

Entre os dois sempre será a classe concreta já que a abstrata faz nada. Se quiser comparar com outras coisas não faz sentido analisar o uso para web, desenvolvimento para web é algo genérico demais para definir algo.
Entre os streams existentes no .NET não vejo outro que poderia ser usado para web especificamente, mas no geral sim. É possível usar algum outro de terceiros ou desenvolver o seu próprio. A documentação linkada acima tem todas as classes do .NET que herdam de Stream.
Seu caso
Se o que está fazendo funciona e atende todos os requisitos que deseja em todas situações, ou seja, se é o certo, ok. Me parece que este caso está ok, está carregando um PDF com API específica e jogando isso na memória conforme essa API permite. Eu vou chutar que não é necessário ser um stream no caso, mas não sei se a API do visualizador de PDF tem outra forma de acessar. Se a intenção é enviar diretamente para outro local então pode ser que outro seja mais adequando, mas pela pergunta não temos como saber.
O problema em geral ocorre porque as pessoas não leem a documentação, não entendem pontos colaterais e não testam todas situações que pode ocorrer, em geral a pessoa testa para funcionar, quando o certo é testar para não funcionar e descobrir onde pode dar problema e evitá-lo.
Coloquei no GitHub para referência futura.
Answer: Stream nada mais é do que a classe base e abstrata (ou seja, não pode ser instanciada) para todos os demais tipos de Stream disponíveis.
MemoryStream é uma das implementações de Stream, que provê uma forma de você armazenar um Buffer (dados em bytes crus) em memória.
Na página de documentação você encontrará diversas implementações nativas do próprio framework .NET, tais como:

System.IO.Compression.GZipStream: Encapsula um outro Stream, (des)compactando as informações deste;
System.IO.FileStream: Provê manipulação (leitura, gravação, navegação) em um buffer apontando para um arquivo do sistema de arquivos;
System.Net.Sockets.NetworkStream: Provê manipulação de buffer da rede;
Answer: Como já dito anteriormente, o STREAM é uma classe abstrata. MEMORYSTREAM é uma classe derivada dessa classe, como também o FILESTREAM.
Eu costumo usar MEMORYSTREAM quando estou trabalhando com arquivos pequenos e não vejo problemas em mantê-los integralmente em memoria (MEMORYSTREAM). Ex. uma foto, ou algo assim.
Já quando se vai trabalhar com arquivos grandes, imagine um vídeo de 200MB por exemplo, é bem mais aconselhável que se use um FILESTREAM, que ele vai lendo e transmitindo o arquivo aos poucos, sem carrega-lo totalmente para a memória.
Espero ter ajudado a esclarecer a sua dúvida.

MemoryStream vs Stream


Inference from conditional observations

Question: Let $(x_1, \ldots, x_n)$ be an i.i.d. random sampling from a conditional normal distribution ${\cal N}(\mu,\sigma^2)$ distribution given some event $A$ possibly parameter-dependent: for instance when we sample ${\cal N}(\mu,\sigma^2)$ but we only retain $x_i$ when $x_i \in [\mu-3\sigma, \mu+3\sigma]$. Are there some known methods to perform statistcal inference on the parameters?
Comment: Do you know what the conditioning event is *a priori* (up to the values of the parameters)?
Comment: Yes, as if you set $\mu$ and $\sigma$ in a computer and you simulate but you reject values outside $A=[\mu-3\sigma, \mu+3\sigma]$.
Answer: If you throw out observations outside 3 sigma from the mean the distribution you end up with is a truncated normal.  You just divide the normal density by the norming constant that makes the integral over the restricted region equal 1.  Then you can write down the likelihood function for your data and compute the maximum likelihood estimate.  I am addressing you specific example and not the generalconditional distribution question.
Comment: Yes, of course maximum likelihood ia available, but what about a confidence interval about $\mu$ ?
Comment: If the maximum likelihood estimator is well behaved then you could use its asymptotic normal distribution to construct approximate confidence intervals.  I think bootstrap confidence intervals would work in this case also.
Comment: Asymptotic normal distribution is not "standard" when the support is parameter-dependent, is it ?
Comment: @stephane I think you are right.  The endpoints for the distribution are functions of mu and sigma in your case so this is not a regular case for the mle.  I don't know what would happen with bootstrap confidence intervals in this case. It seems that there is information about mu in the center of the distrbution and in the extremes.  What about just using the sample mean to estimate mu.  This would ignore some information in the data but couldn't we construct approximate confidence limits based on the CLT?  Maybe we could show that bootstrap confidence intervals for the sample mean would work.
Comment: @stephaneLaurent Did you want to estimate sigma as well?
Comment: @StéphaneLaurent This problem strikes me as being interesting in many ways. What is the best estimate for the mean and standard deviation and how do you construct best confidence intervals. Are the mles good estimates? Do bootstrap confidence intervals work in this case? I see that [X$_($$_n$$_)$ - X$_b$]/3 is a consistent estimate for sigma where X$_b$ denotes the sample mean. Also [X$_b$-X$_($$_1$$_)$]/3 is consistent for sigma and the average of the two is unbiased based on symmetry considerations.
Comment: In addition to X$_b$ being an unbiased estimator for mu, I think [X$_($$_n$$_)$+X$_($$_1$$_)$]/2 is also unbiased for mu. Combining some of these estimates by averaging them might give better ones. I don't know if this problem has been studied much. Is there any literature on it? I think the answers to the bootstrap question on confidence intervals might be new.

Inference from conditional observations


What does increase the margins when the form appears?

Question: If you click the second orange button at this page white form will appear and something will increase the margins for the div.container. How to find out what or who is it doing?
Comment: Please provide the necessary code. It's easier then trying to debug the whole page.
Comment: No idea what margins you are talking about here. The script for this modal disables the main scrollbar of the page, so that naturally makes the content "jump" a bit sideways.
Comment: Please read [Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackoverflow.com/questions/125997/something-on-my-web-site-doesnt-work-can-i-just-paste-a-link-to-it). Questions that depend on external resources to be understood become useless when the external resource goes away or is fixed. Create a [MCVE] and put it in **the question itself** instead.
Answer: body is set to overflow:hidden  =  scrollbar dissapears so the content moves :)
Comment: Thank you. And what the best sites doing with this shift to neutralize it?
Comment: to neutralize this shift I added such js-code: jQuery("body").css("padding-right","17px"); jQuery("nav > .container").css("padding-left","6px");


Code First Entity Framework disallows access to table

Question: I am trying to use code first to generate a database for an asp.net mvc application. the OrderItem class does get generated as OrderItems table in the database but I end up without having any access to it. what can I do to allow the following for example: db.OrderItems.Find(id);
the model is as follows:
namespace CustomerOrders.Models{

public class Customer
{

    public virtual int  CustomerID { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Company { get; set; }
    public virtual string Email { get; set; }
    public virtual string EmailCheck { get; set; }
}

public class Order
{
    public virtual int OrderID { get; set; }
    public virtual int CustomerID { get; set; }
    public virtual DateTime OrderDate { get; set; }
    public virtual double OrderTotal { get; set; }
    public virtual double Tax { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual List<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public virtual int OrderItemID { get; set; }
    public virtual int OrderID { get; set; }
    public virtual int ProductID { get; set; }
    public virtual double PricePerItem { get; set; }
    public virtual double Quantity { get; set; }
    public virtual Product Product { get; set; }
    public Order Order { get; set; }
}

public class Product
{
    public virtual int ProductID { get; set; }
    public virtual string Title { get; set; }
    public virtual string Description { get; set; }
    public virtual double Price { get; set; }
}
}

Comment: What's the issue?  Is there data in the database?  Does db.OrderItems.Find(id); just throw an exception?
Comment: Maybe show the code how you create your dbcontext and the code how you try to use it?
Comment: The OrderItems table is inaccessible and it doesn't show up in the intellisense, all the other tables can be accessed as properties through code.
Comment: Have you added it correctly to the DbContext?
Comment: As I've already said, give us the actual code.. It's useless to guess the cause like this.
Answer: You probably haven't got the declaration in your dbContext so Open up the dbContext and add  this:
public DbSet<OrderItem> OrderItems { get; set; }
you should end up with this:
public class CustomerOrdersDB : DbContext
{
    public DbSet<Order> Orders { get; set; }

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Product> Products { get; set; }

    public DbSet<OrderItem> OrderItems { get; set; }
}


Data sync between on Prem MySQL and Azure Data Store

Question: We have a legacy system which talks to on-premise MySQL database. We are building a new system and its hosted in Azure. The database it uses to store the data is in Azure Storage. Since the legacy application will be functional for some time, we would like to sync the data from MySQL to Azure Table Storage. Is there any tool that can help in the synchronization of the data from MySQL to Azure Table Storage?
Answer: You could use Data-in Replication feature for synchronization of data between MYSQL and Azure database.
Please refer this document for more information.
Hope it helps.


Expression of cosine and sine of $\frac{\phi}{3}$

Question: For $n\in \mathbb{N}$ it holds that $\left (\cos \phi +i\sin \phi \right )^n=\cos \left (n\phi \right ) +i\sin \left (n\phi \right )$.
How can we derive from that an expression of cosine and sine of $\frac{\phi}{3}$ ?
Or do we use the identity $e^{i\phi }=\cos \phi +i\sin \phi $ ?
Then we would have $e^{i\frac{\phi}{3} }=\cos\frac{\phi}{3} +i\sin \frac{\phi}{3}$ and $e^{i\frac{-\phi}{3} }=\cos\frac{-\phi}{3} +i\sin \frac{-\phi}{3}$.
It holds that $\cos (-x)=\cos (x)$ and $\sin (-x)=-\sin (x)$.
Therefore we get $e^{i\frac{-\phi}{3} }=\cos\frac{\phi}{3} -i\sin \frac{\phi}{3}$.
So it follows that $e^{i\frac{\phi}{3} }+ e^{i\frac{-\phi}{3} }=2\cos\frac{\phi}{3}\Rightarrow \cos\frac{\phi}{3}=\frac{e^{i\frac{\phi}{3} }+ e^{i\frac{-\phi}{3} }}{2}$.
Respectively we have that $e^{i\frac{\phi}{3} }- e^{i\frac{-\phi}{3} }=2i\sin\frac{\phi}{3}\Rightarrow \sin\frac{\phi}{3}=\frac{e^{i\frac{\phi}{3} }- e^{i\frac{-\phi}{3} }}{2i}$.
Is that correct?
Comment: Not quite: in the expression for $\sin \phi/3$ it should be $2i$ in the denominator.
Comment: Yes, everything is correct.
Comment: No, you cannot here.
Comment: I edited it. Is now everything correct? @TobyMak
Comment: So we cannot use the property $\left (\cos \phi +i\sin \phi \right )^n=\cos \left (n\phi \right ) +i\sin \left (n\phi \right )$, do we? @TobyMak
Comment: Ok! Thank you!! :-) @TobyMak
Answer: Any $z$ satisfies$$\exp\pm iz=\cos z\pm i\sin z\implies\cos z=\frac{\exp iz+\exp-iz}{2},\,\sin z=\frac{\exp iz-\exp-iz}{2i},$$including $z=\phi,\,z=\frac{\phi}{3}$. It's worth nothing the values of $\cos\phi,\,\sin\phi$ don't determine those of $\cos\frac{\phi}{3},\,\sin\frac{\phi}{3}$: equivalently, $\exp i\phi$ doesn't determine $\exp\frac{i\phi}{3}$. For example, $\exp i\phi=1$ is consistent with $\exp\frac{i\phi}{3}$ being any of the three cube roots of unity.
Comment: Thank you!! :-)


Is packet forwarding possible on Android?

Question: Our requirement is to develop an Android App &/or service that does the following. Listen to http (port 80) requests/packets sent from the device (by any app). forward them to a different server and not to the host that they are meant to go to.
Can someones please indicate whether this is possible and if yes, then how?
Comment: Hi I am also facing some problem, any help will be greatly appreciated.
Answer: As android is a Linux system you might want to check redirection by using its iptables. However I assume that you might need root rights to do so.
Answer: It's possible on android versions 4.0 or greater with VPNService. Have a look at the ToyVpn example provided by google. It's not nice for the user as they get a popup and a constant icon on the notification bar, but it's possible.
If you only want port 80 you will have to decode the ip and tcp headers in your app.


Como fechar uma JDialog após terminar de executar uma Thread?

Question: Tenho uma janela de configuração que abre na primeira execução do aplicativo que estou desenvolvendo. Após digitar os diretórios que o aplicativo irá rodar o usuário clica em salvar, alguns testes são executados e por fim roda uma Thread.
Eu gostaria de fazer com que após terminar a execução dessa Thread a janela de configuração fechasse sozinha, porém tentei executar dispose() e setVisible() e ela desaparece antes de executar a Thread.
// Evento para salvar os diretórios
btnSalvar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        // Testa o campo com o diretório a ser indexado
        // Se está vazio
        if ((txtDirIndexado.getText().length() == 0 || Character
                .toString(txtDirIndexado.getText().charAt(0)).equals(
                        " "))) {
            JOptionPane
                    .showMessageDialog(panel,
                            "O campo com o diretório a ser indexado não pode estar em branco.");
        } else if ((txtDirIndice.getText().length() == 0 || Character
                .toString(txtDirIndexado.getText().charAt(0)).equals(
                        " "))) {
            JOptionPane
                    .showMessageDialog(panel,
                            "O campo com o diretório que guardará o índice não pode estar em branco.");

        } else {
            try {
                ArquivoDeConfiguracao.defineFonte(txtDirIndexado.getText());
                ArquivoDeConfiguracao.defineIndice(txtDirIndice.getText());
                ArquivoDeConfiguracao.definePrimeiraExecucao(1);
                // Janela de aguardo
                final JDialog janelaProgresso = new IndexAndo();

                // Cria um novo processo e mostra a janela
                new Thread(new Runnable() {
                    public void run() {
                        Indexador ind = new Indexador();
                        ind.iniciaIndexacao();

                        // Ao terminar fecha
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                janelaProgresso.setVisible(false);
                            }
                        });
                    }
                }).start();
                // Salva a data
                dispose();
                ArquivoDeConfiguracao.defineIndiceUltAtualizacao();
            } catch (IOException e) {
                // Gera erro
                e.printStackTrace();
            }
        }
    }

});

O código na integra pode ser acessado no git.
Edição:
// Evento para salvar os direstórios
btnSalvar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        // Testa o campo com o diretório a ser indexado
        // Se está vazio
        if ((txtDirIndexado.getText().length() == 0 || Character
                .toString(txtDirIndexado.getText().charAt(0)).equals(
                        " "))) {
            JOptionPane
                    .showMessageDialog(panel,
                            "O campo com o diretório a ser indexado não pode estar em branco.");
            // Se está vazio
        } else if ((txtDirIndice.getText().length() == 0 || Character
                .toString(txtDirIndexado.getText().charAt(0)).equals(
                        " "))) {
            JOptionPane
                    .showMessageDialog(panel,
                            "O campo com o diretório que guardará o índice não pode estar em branco.");
            // Se o diretório existe
        } else {
            try {
                ArquivoDeConfiguracao.defineFonte(txtDirIndexado.getText());
                ArquivoDeConfiguracao.defineIndice(txtDirIndice.getText());
                ArquivoDeConfiguracao.definePrimeiraExecucao(1);

                final JDialog janelaProgresso = new IndexAndo();

                new Thread(new Runnable() {
                    public void run() {
                        ProcessoIndexacao base = new ProcessoIndexacao();
                        base.start();
                        synchronized (base){
                            try {
                                base.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                janelaProgresso.setVisible(false);
                            }
                        });
                    }
                }).start();
                janelaProgresso.setVisible(true);
                // Salva a data
                ArquivoDeConfiguracao.defineIndiceUltAtualizacao();
            } catch (IOException e) {
                // Gera erro
                e.printStackTrace();
            }
        }
        dispose();
    }

public class ProcessoIndexacao extends Thread{
    public void run(){
        synchronized (this){
            Indexador ind = new Indexador();
            ind.iniciaIndexacao();
            notify();
        }
    }
}

Comment: Seria importante você seguir esse conselho: [Como criar um exemplo Mínimo, Completo e Verificável](http://meta.pt.stackoverflow.com/q/1186/3117). Assim mais pessoas se interessariam em lhe ajudar, pois nem todo mundo vai querer acessar o GitHUB para entender sua dúvida.
Answer: Não vi seu código inteiro, mas se entendi bem seu problema você quer que uma Thread espere outra terminar para ser executada.
Basicamente o que você precisa é entender os conceitos de wait() e notify().
Aqui tem um exemplo que eu implementei enquanto estudava para a prova de certificação Java:
public class WaitNotify {
    public static void main(String[] args) {
        //aqui você inicia uma nova Thread e manda ela rodar
        ThreadB b = new ThreadB();
        b.start();
        //Thread atual deve ter o "lock" da thread b,isso é necessário para chamar o wait()
        synchronized(b) {
            System.out.print("Waiting for b to complete...");
            try {
                //aqui você diz que a Thread atual deve esperar a Thread b terminar
                b.wait();
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Total is: " + b.total);
        }
    }
}

class ThreadB extends Thread {
    int total;
    //aqui sua Thread começa a rodar
    @Override
    public void run() {
        synchronized(this) {
            for(int i=0; i<16; i++) {
                total += i;
                try {
                    //um temporizador para sua Thread não acabar na velocidade da luz!
                    Thread.sleep(300);
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
                //faz uma frescura
                if(i%2 == 0) {
                    System.out.print(".");
                }
            }
            System.out.println();
            //Thread avisa que terminou sua execução para quem possui o lock de b
            notify();
        }
    }
}

Lembre-se que quando você roda uma classe que possui um método main() você está rodando uma thread que se chama main, assim como no exemplo acima, a thread main é uma thread como outra qualquer, então apenas a faça esperar uma outra thread até que ela chame o notify().
Comment: Não consegui implementar 100%, quando rodo a Thread ela "trava" e nunca termina.
Comment: @Strokes você rodou o meu código ou implementou as threads no seu? Se for no seu poderia nos mostrar como ele ficou?
Comment: Implementei a sugestão adaptando com a minha necessidade. Postei na pergunta o novo código
Comment: @Strokes olhando me parece tudo certo.. vou ver melhor na hora do almoço, guentae
Comment: @Strokes fiz alguns testes aqui para tentar dar pau no código, e não consegui, daí me surgiram algumas dúvidas: o que você quer dizer com trava? Seu código entra em um loop infinito? Sua tela aparece e não responde? Teria como vc usar o debug para saber exatamente onde está o erro?
Comment: Então, pelo que eu percebi ele para ali no wait(). Ele abre a minha janelaProgresso mas não termina de desenhar, e fica nisso, consigo redimensionar ela e tudo mais. Mas o código não continua.
Comment: @Strokes você tem duas Thread, a primeira normalmente parará no wait mesmo, até que a outra chame o notify. Você chegou a ver se a segunda chega a executar o run? Se sim, onde ela trava? Outra coisa, vi que entre o `setVisible` true e false da janela tem apenas um método, será que ele não executa rápido demais não, ou então demorado demais e você acha que travou? Ultimo ponto de observação, será que você precisa mesmo de outra thread? Não tem como você chamar a janela dentro do seu primeiro código? Ou então pelo menos puxar o código de abrir e fechar a janela para a primeira thread.
Comment: Ele vai até o janelaProgresso.setVisible(true); e simplesmente para. Nada mais acontece!
Essa minha Thread tem relação com outra pergunta que fiz [aqui no SO](http://pt.stackoverflow.com/questions/10114/jdialog-nao-modal-nao-desenha-os-componentes-no-java). Pois tenho a seguinte lógica: abre-se a janela de configuração, preenche e verifica o conteúdo, abre uma janela de "processando", executa o processo e fecha as duas janelas.
Comment: @Strokes no exemplo dele a instanciação da janela está fora da criação da nova thread, teria como voce modificar isso?
Comment: Pelo que eu entendi o Java tá esperando a minha janelaProgresso ser fechada para continuar o código!
Comment: Consegui resolver o problema, estou postando abaixo da pergunta.
Answer: Galera, consegui resolver meu problema com o comando abaixo:
myJDialog.getOwner().dispose();

Segundo a documentação, esse método existe desde a versão 1.2 do java.
Comment: Esse comando vai fechar não só a dialog, mas a janela da qual ela foi chamada. Olhando a resposta aceita, não creio que isso resolveria o problema da pergunta.


Is there a test for independence in a Bernoulli process?

Question: I have a process with binary output. Is there a standard way to test if it is a Bernoulli process? The problem translates to checking if every trial is independent of the previous trials.
I have observed some processes where a result "sticks" for a number of trials.
Comment: Not sure autocorrelation applies as well as a runs test would, since the data are binary.
Comment: If you think stickiness is a potential problem, you can test for autocorrelation.
Answer: I think you can devise a big number of tests, and the good choice depends on the alternate hypothesis you have in mind... I just have a few remarks. I place this post under community wiki as I feel it can be improved a lot.

The first think I would think to: divide your sample in n subsamples of size k; if the experiments are independents, in sample number $i$ the number $X_i$ of successes is a $\mathcal Bin(k,p)$, so you have $n$ independent values $X_1, \dots, X_n$ of a binomial variable. This can be tested by a $\chi^2$ test. (The choice of $n,k$ will depend on the total sample size...)
Considering your remark about the process sticking for a number of trials, it seems that you think of positive correlation between successive experiments. I think the above test can be powerful in this case. However you can consider the length of runs in your sequence of trials: denoting $L_1$ (resp. $L_0$) the length of a 1 run (resp. of a 0 run), you have
$$\mathbb P(L_1 = k) = p^{k-1} (1-p),$$
$$\mathbb P(L_0 = k) =(1-p)^{k-1} p.$$ These are geometric distributions, beware: in some softwares like R, $k$ is shifted by $1$. You can again test for goodness of fit of the observed values.
I don't know how the preceding suggestion performs as compared to Wald–Wolfowitz runs test.
Special attention has been given to the case where $p={1\over 2}$, as this is the case of a sequence of random bits generated by a Random Number Generator. A number of tests has been devised by George Marsaglia, under the name Diehard test battery. You can surely generalize (most of) these tests to the case $p \ne {1\over 2}$. (But is it worth it?)
Comment: The runs test looks promising.  I wonder how it compares in power to the alternatives suggested in this thread?
Comment: @whuber Yes, if my days were 96 hours long I would be right on it :) If you can read italian the article on the WW test is a bit more detailed. Before assessing the power, defining good alternative models is not so easy... the worst case is that of most modern RNG, fully deterministic periodic sequences for which these tests will have no power at all.
Answer: Let the sequence of values be realizations of random variables $X_i$, $1\le i\le n$, each identically distributed as a Bernoulli($p$) variable (with $p$ unknown).  When they are independent, the sequence is a Markov chain with transition probabilities
$$\Pr(x \to 0) = 1-p, \quad \Pr(x \to 1) = p$$
for $x = 0,1$.  The sequence yields $n-1$ (presumably) independent transitions $X_i \to X_{i+1}$, $1\le i\le n-1$, which can be summarized as a $2 \times 2$ matrix of their counts.  Independence of the sequence implies independence of this table.  So, test the table for independence and reject the hypothesis of an independent sequence if the test is significant.
For example, here is a sequence of 24 binary outcomes:
1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 1 1 0 0 0

The 23 transitions in this sequence are 1->1, 1->1 , ..., 1->0, 0->0, 0->0.  Their table of counts is
To:      0  1
From  0: 3  2
      1: 3 15

Its chi-squared statistic is 1.8947.  The p-value (using the chi-squared approximation, which is not very good due to the small cell counts in the table) is 0.1687: no evidence of dependence.  Indeed, these 24 values were generated randomly and independently with a 2/3 chance of the outcome 1 and a 1/3 chance of a 0 (i.e., $p=2/3$).
If the hypothesis of independence is not rejected, you can continue to test for higher-order dependence or seasonal dependence (by checking transitions from season to season, rather than between consecutive values).
Here is sample R code to compute the chi-squared test p-values for any desired order (1, 2, ...) and to simulate the null distribution (which can be used for a more accurate permutation test of the independence hypotheses if you wish).
set.seed(17)
x<-rbinom(256,1,2/3)             # Sample data generated with the null distribution.
cc <- function(x,k) {            # Chi-squared test of kth order independence in x.
    n <- length(x)-k-1
    m <- sapply(1:k, function(j) x[j:(n+j)])
    y <- m %*% (2^(0:(k-1)))     # Classifies length-k subsequences of x
    chisq.test(y, x[(k+1):length(x)])$p.value
}
sapply(1:2, function(k) cc(x,k)) # P-values for chi-squared tests of orders 1, 2.
order <- 1                       # Use 2 for second order, etc.
hist(replicate(999, cc(sample(x),order))) # Simulated null distribution of the p-value.

Comment: @whuber Your test makes sense. The reason I asked my question is because the $\chi^2$ statistic 1.8947 that you calculated with `R` doesn't match the $\chi^2$ statistic I calculated by hand using the formula on the page you cite: $\frac{(3-5*6/23)^2}{5*6/23}+\frac{(2-5*17/23)^2}{5*17/23}+\frac{(3-18*6/23)^2}{18*6/23}+\frac{(15-18*17/23)^2}{18*17/23}=3.8101$.  What am I doing wrong?  (I don't use `R`, though I'm quite familiar with MATLAB.)
Comment: @M.B.M. Good question. Your calculation is right--but `R` uses a continuity correction by default to create more accurate results with small amounts of data: "one half is subtracted from all $|O-E|$ differences; however, the correction will not be bigger than the differences themselves." In a $2\times 2$ table like this, all the $|O-E|$ differences are equal--in this case, they are $|3-5\times 6/23|\approx 1.6957\ge 1/2$. Thus the statistic is reduced by a factor of $(1 - 1/(2|3-5\times 6/23|))^2\approx 0.4972$, thereby turning $3.81$ into $3.81\times 0.4972\approx 1.8947$.
Comment: (+1) Nice. Very efficient way to compute the table of transitions.
Comment: Thanks, @Elvis.  I appreciate any constructive comments about the `R` code.
Comment: @whuber I am confused by this test.  Could you elaborate how your calculate the chi-square test statistic from the table of counts in your example?
Comment: @M.B.M This is the standard [Pearson $\chi^2$ test](http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test). It is illustrated in the `R` code in this answer. The test of that particular table can be executed in `R` as `chisq.test(matrix(c(3,2,3,15),2))`, for instance.
Comment: @whuber Aha!  So `R` applies [Yate's correction for continuity](http://en.wikipedia.org/wiki/Yates%27s_correction_for_continuity) because there are small values in your table (like 2 and 3). If the table contained large values, then continuity correction is not necessary.  Is that correct?
Comment: @M.B.M. Yes, that's right (although I believe `R` would, by default, apply the continuity correction even to large values).
Comment: @whuber Thanks! I think I won't apply the continuity correction since the values in my tables are large (on the order of hundreds).
Comment: This test seems to only account for lag 1 correlation, it might fail for lag k correlation. For example, consider the sequence replicating 1001:   1001100110011001....
Comment: @Statisfun Thank you for that observation.  But did you read my remarks about "higher-order dependence"?  I suspect you might be describing the second argument to the `cc` function.


Can i plug an 12v DC to a 9v Pedal?

Question: pretty much as the title goes..
is it okay to plug an 12v DC power supply(Voodoo Lab) to 9v pedal(ADA GCS-5)?

Power Supply >> Voodoo Lab ISO-5's Manual for reference
Pedal >> ADA GCS-5's Manual for reference
more info regarding the Pedal and Power Supply

my Power Supply got 6 power output

3x[all available] 9v 100mA
9v[used by a Pedal which couldn't run below 150mA]/12v[available] 400mA
18v[Used] 100mA)

ADA GCS-5's manual did say that "The GCS-5
is an all-analog circuit that runs on a standard 9-volt AC adapter (ADA Part Number 240013G5) or a pedal board power supply rated at 200mA or more.". Which is quite ambiguous whether if its okay to put an unregulated 12v DC on it.
Comment: I don't know any of this equipment but I would not suggest using a supply with too high a voltage, especially not an unregulated one.
Answer: 15% above seems to be recognised as safe, but here it's twice that. I've done it in desperate circumstances (borrowed psu in middle of gig), and got away with it. Maybe I was just lucky - as was my gear! An unregulated psu can almost double the stated voltage with no load, and it would be an unwise move to connect, unless you're in dire straits (or Mark Knofler, who can probably afford to replace gear better than us mere mortals)...
Another important issue is the polarity. With d.c. it's of paramount importance that the pedal gets fed pos. and neg. the right way round. There's often a 50/50, and guessing may mean the pedal doesn't work anyway, and possibly will suffer damage, although most d.c. pedals have a blocking diode.

Can i plug an 12v DC to a 9v Pedal?


$X,Y$ are r.v.s. $f_{X,Y(x,y)}=ce^{-0.5(3x^2+2xy+2y^2)}$ , $c>0$ is a constant. Find $f_{X|X+Y}(x|1)$

Question: $X,Y$ are r.v.s.
$f_{X,Y(x,y)}=ce^{-0.5(3x^2+2xy+2y^2)}$ , $c>0$ is a constant.
Find $f_{X|X+Y}(x|1)$
I want to find $f_{X+Y=1}({x,y})$ , then find $f_X(x)=\int_{-\infty}^{\infty}f_{X,Y(x,y)}dy$
and get $f_{X|X+Y}(x|1)=\frac{f_X}{f_{X+Y=1}}$
SO,
$f_{X+Y=1}(x,y)=\int_{-\infty}^\infty \int_{-\infty}^{1-x}ce^{-0.5(3x^2+2xy+2y^2)}dydx=c\int_{-\infty}^\infty \frac{e^{-0.5(3x^2+2x(1-x)+2(1-x)^2)}}{x-2(1-x)}=c\int_{-\infty}^\infty \frac{e^{-2.5x^2+3x-2}}{3x-2}$
I don't know how to solve it.
Help please
Thanks !
Answer: If $U = X, V = X + Y$, first find $f_{UV}(u, v)$ using Jacobian Transformation.
Here, $|J| = 1$
So, $ \displaystyle f_{UV} (u, v) = |J| ~f_{XY}(u, v-u) = c \cdot e^{-(3u^2 + 2v^2 - 2 uv)/2}$
$ \displaystyle f_V(v) = \int_{-\infty}^{\infty} f_{UV}(u, v) ~ du = c \cdot \sqrt{\frac{2\pi}{3}} \cdot e^{-5v^2/6}$
Now, $~ \displaystyle f_{U \mid V} (u, 1) = \frac{f_{UV} (u, 1)}{f_{V}(1)}$


O que são Mutexes e quando é aconselhável usar este recurso?

Question: Li a respeito de Mutexes e a classe Mutex. Porém, não consigo compreender de forma clara o que de fato é Mutex e o que esta classe faz.
Sendo que eu gostaria de saber se posso usar este recurso para impedir que minha aplicação desktop seja executada mais de uma vez (várias instancias do mesmo processo no caso do usuário abrir o programa repetida vezes).
Uma implementação que fiz foi a seguinte:
private bool ProcessoExecutando()
{
    var localizacao = Assembly.GetExecutingAssembly().Location;
    FileSystemInfo systemInfo = new FileInfo(localizacao);
    Mutex mutex = new Mutex(true, "Global\\" + systemInfo.Name, out bool novoProcessoCriado);
    if (novoProcessoCriado)
    {
        mutex.ReleaseMutex();
    }
    return !novoProcessoCriado;
}

Este método é chamado no método Main() e serve em tese para verificar se já existe uma instancia do processo da aplicação executando. E me parece um pouco gambiarra =/
Veja:
static void Main()
{
    if (ProcessoExecutando())
    {
        return;
    }

    //Inicia aplicação
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new AppMain());
}

No entanto, o significado da classe Mutex esta confuso em minha mente e a minha falta de conhecimento nisto pode fazer com que eu use este recurso de forma equivocada.
Sendo assim, eu gostaria de ter as dúvidas abaixo esclarecidas.
Dúvidas

O que são Mutexes?
Quando é aconselhável usar a classe Mutex?
O caso ilustrado acima do usado da classe Mutex é o ideal para
impedir que a aplicação seja executada mais de uma vez?
Answer:
O que são Mutexes?

O mecanismo de MUTual EXclusion é usado em ambientes concorrentes e é uma forma de impedir que um recurso seja acessado por mais de uma linha de processamento ao mesmo tempo. Ele é usado principalmente para evitar a condição de corrida, para manter uma operação atômica.
Ele é uma forma de travamento de um recurso, em geral na memória. Existem outros mecanismos parecidos como o semáforo, por exemplo, onde já dei uma resposta e falei superficialmente sobre o Mutex. O artigo da Wikipedia mostra alguns.
Enquanto um recurso qualquer não pode ser acessado concorrentemente ele não precisa de um mecanismo desse tipo, e muitas vezes é preferível ter alguma forma assim que é muito mais simples, até mesmo se precisar duplicar o recurso. Criar um Mutex não é barato, e todo recurso que só pode ser acessado com uma consulta ao Mutex tem um acesso muito mais caro que o normal, em alguns casos esse controle é mais caro que o acesso em si. Mas nem todos os casos podem ter o acesso concorrente eliminado, há objetos que precisam de um estado global consistente.
Há casos que um objeto pode ter um Mutex interno, em outros pode ser usado de forma individualizada. O uso interno pode dar mais garantia que nenhum acesso será violado, porém obriga o objeto ter o custo desse controle em todos os acessos, até mesmo quando não há concorrência.
O Mutex, de forma geral, é um objeto que indica se o objeto está sendo acessado por algum código naquele momento ou não. Então você sempre precisa consultá-lo para saber se pode fazer algo no objeto. Se a consulta não for feita e tentar acessar o objeto sem cuidado poderá causar problemas. Você só poderá acessar o objeto de forma livre se o Mutex for liberado e isto só deve ocorrer quando quem o criou o fizer.
Só uma linha de processamento pode ser dono de um Mutex para um recurso.
Entenda o Mutex como um porteiro que diz quem pode entrar ou não em um lugar e ele só deixa entrar se o local está vago. Sabe ambientes onde todo mundo quer falar e só um pode. Alguém controla o microfone de quem pode falar naquela hora. Esse é o Mutex. Esse caso específico só quem pode dizer que outra pessoa pode usar o microfone é quem está usando. Só ele pode desligar o uso e permitir que outra pessoa comece usar. A outra pessoa pode ficar tentando, mas não tem acesso a ele enquanto o outro está usando.
No C# é possível ver o código da classe que implementa o Mutex. Ou pode ver como é no .NET Core, bem diferente e precisa seguir as abstrações já que cada sistema operacional é diferente.

Quando é aconselhável usar a classe Mutex?

Em essência o que já foi dito. Há exemplos nos links para respostas já postadas aqui no SOpt que mostram isto.

O caso ilustrado acima do usado da classe Mutex é o ideal para impedir que a aplicação seja executada mais de uma vez?

Não me parece ser necessário um Mutex, é possível você saber que a aplicação está em execução de outras formas, e o custo disto geralmente já é bem alto, não preciso de um mecanismo de baixo custo que é o caso do Mutex.
Normalmente um Mutex deve durar muito pouco tempo sob pena de causar deadlocks.
Coloquei no GitHub para referência futura.


Kohana 3.3 : required field

Question: I'm using Kohana 3.3.
I use ORM for validation form, by determining some rules.
I would like to make a radio button required. I have three options, and no one can be checked in advance.
I've searched on web, no doc.
Someone has an idea ?
Thanks
Answer: Just use not_empty rule:
<code>public function rules()
{
        return array(
            'your_field_name' => array(
                array('not_empty'),
            ),
        );
}
</code>
Comment: I was looking for keyword 'required', or 'checked', but no results. Thank you.

Kohana 3.3 : required field


How to prevent closing CTools modal window with ESC during AJAX?

Question: How can I prevent closing CTools modal window with ESC key during AJAX request?
Answer: Try this one
<code>/**
 * Override Ctools modal content function to prevent closing the modal with
 * the escape key.
 */
Drupal.CTools = Drupal.CTools || {};
Drupal.CTools.Modal = Drupal.CTools.Modal || {};
var modalContent = Drupal.CTools.Modal.modalContent;
Drupal.CTools.Modal.modalContent = function(content, css, animation, speed, modalClass) {
  modalContent(content, css, animation, speed, modalClass);
  $(document).unbind('keydown', modalEventEscapeCloseHandler);
}
</code>
Comment: This method prevents pressing ESC always. I need to prevent pressing ESC only during AJAX request was sent.


Paginação no codeigniter 3

Question: Galera fiz a paginação no codeigniter e ela funciona com excessão de um detalhe o link da página dois fica url/1, da página três fica url/2 e da primeira só a url. O que faço pra deixa a página dois com url/2? Segue o código:
<code>$config = array();
    $config["base_url"] = base_url() . "usuarios";
    $config["total_rows"] = $this->usuario->totalRegistros();
    $config["per_page"] = $this->config->item('registros_por_pagina');
    $config["uri_segment"] = 2;
    $this->pagination->initialize($config);

    $pagina = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;

    $data['usuarios'] = $this->usuario->listarUsuarios($config["per_page"], $pagina);
    $data["paginacao"] = $this->pagination->create_links();
</code>
Obrigado
Answer: <code>$config ['use_page_numbers'] = TRUE;
</code>
Põe isto no seu código.

Paginação no codeigniter 3


Deserialise Dynamic JSON string with Hierarchical data using JSON.NET

Question: Ive a JSON like this
{
  "id": 1,
  "name": "user1",
  "hasChildren": true,
  "parentID": 0,
  "children": [
    {
      "id": 2,
      "name": "user2",
      "paretnID": 1,
      "hasChildren": true,
      "children": [
    {
      "id": 3,
      "name": "user3",
      "parentID": 2,
      "hasChildren": false,
      "children": [

      ]
    },
    {
      "id": 4,
      "name": "user4",
      "parentID": 2,
      "hasChildren": false,
      "children": [

      ]
    }
      ]
    },
    {
      "id": 5,
      "name": "user5",
      "paretnID": 1,
      "hasChildren": true,
      "children": [
    {
      "id": 6,
      "name": "user6",
      "parentID": 5,
      "hasChildren": false,
      "children": [

      ]
    },
    {
      "id": 7,
      "name": "user7",
      "parentID": 5,
      "hasChildren": false,
      "children": [

      ]
    }
      ]
    },
    {
      "id": 8,
      "name": "user8",
      "paretnID": 1,
      "hasChildren": true,
      "children": [
    {
      "id": 9,
      "name": "user9",
      "parentID": 8,
      "hasChildren": false,
      "children": [

      ]
    },
    {
      "id": 10,
      "name": "user10",
      "parentID": 8,
      "hasChildren": true,
      "children": [
        {
          "id": 11,
          "name": "user11",
          "parentID": 10,
          "hasChildren": false,
          "children": [

          ]
        },
        {
          "id": 12,
          "name": "user12",
          "parentID": 10,
          "hasChildren": false,
          "children": [

          ]
        }
      ]
    }
      ]
    }
  ]
}

Here as you can see its maintaining a hierarchy in each level in the children node. What my scenario is to convert this dynamic JSON as datatable rows
For deserilising this is how I tried
dynamic myJSON=jObject.parse(JSONstring);

but when I try myJSON.id its triggering an error like id not exists
What my plant is if children array has some elements, call another function to get its members and add to the datatable. But how can I get these fields from the dyanmic json string.
Comment: Correct typos `JObject.Parse`. Then it works for me.
Answer: You can use like this
 public class Child2
 {
  public int id { get; set; }
  public string name { get; set; }
  public int parentID { get; set; }
  public bool hasChildren { get; set; }
  public List<object> children { get; set; }
 }

public class Child
 {
  public int id { get; set; }
  public string name { get; set; }
  public int paretnID { get; set; }
  public bool hasChildren { get; set; }
  public List<Child2> children { get; set; }
}

public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public bool hasChildren { get; set; }
public int parentID { get; set; }
public List<Child> children { get; set; }
}

then Deserialize
  var data=JsonConvert.DeserializeObject<RootObject>(JSONstring);

then you can access data.id
You need to add reference Newtonsoft.json


Unstacking in Pandas

Question: Struggling with an unstacking problem.  I have a table in the following format:
Word    Number  MetaData    Label   Value
One     1       Hello       A       5a
One     1       Hello       B       2b
One     1       Hello       C       8c
Two     2       World       A       2a
Two     2       World       B       5b
Two     2       World       C       1c

I want to unstack it to this, preserving all of my other columns.  In all cases, Word, Number, and MetaData will always be the same for each set of A, B, and C:
Word    Number  MetaData    A   B   C
One     1       Hello       5a  2b  8c
Two     2       World       2a  5b  1c

Comment: You want pivoting, not unstacking.
Comment: I edited my question to be more clear.  Pivot seems to imply that I am summarizing the value field which.  The closest example of what I am doing is a jmp unstack function while keeping all of my columns.  I will resubmit the question with my edits.
Answer: You want pivot_table here:
df.pivot_table(
    index=['Word', 'Number', 'MetaData'],
    columns='Label',
    values='Value'
).reset_index()

Label Word  Number MetaData  A  B  C
0      One       1    Hello  5  2  8
1      Two       2    World  2  5  1

Unstacking in Pandas


Como utilizar a API do Youtube?

Question: Tenho uma pagina com um video que abre num modal, preciso que ele fique pausado quando o modal estiver ocultado.
Testei exemplos que encontrei em outros sites mas não funcionou.
Preciso adicionar algum arquivo extra para utilizar o control da API?
Comment: Como você está incorporando o vídeo ?
Answer: Não sei como você está fechando o seu modal, mas se vc está utilizando .hide() do jQuery, você pode fazer o seguinte:
function pause_video(){
    $('#youtube_iframe_id')[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}

function hideCallBack() {
    pause_video()
}

Com as duas funções adicionadas no seu código, seu vídeo será pausado quando você fechar o modal usando:
$('#modal_id').hide(hideCallBack);

Como utilizar a API do Youtube?


error in Sign with Google+ in rails

Question: I am trying to implement sign in with google or any other social network in rails. I am already followed the Codeplace tutorial with http://r12---sn-cvh7kn7y.googlevideo.com/videoplayback?sparams=dur,ei,expire,id,i
I faced the following problem
 Error: invalid_request

Missing required parameter: client_id

Learn more

 Request Details
  access_type=offline
 scope=email profile
response_type=code
redirect_uri=http://localhost:9292/auth/google_oauth2/callback
state=2f6a1b1d2e0a2fb1c75647a6d145efa907c3ee9038a8bb54
client_id=

My related code are -
omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2,ENV['238730796202-.com'],ENV['TyqJqfiOJLoLgqRRGgTIynxt']
 provider :facebook, ENV['1585034338471672'],ENV['3211b382a1636bdc747d37921aab2a90']
 end

sessioncontroller.rb
 class SessionsController < ApplicationController

def create
    auth = request.env["omniauth.auth"]
    puts auth
    session[:omniauth] = auth.except('extra')
    user = User.sign_in_from_omniouth(auth)
    session[:user_id] = user_id
    redirect_to root_url, notice:"Sign In"
end
def destroy
    session[:user_id] = nil
    session[:omniauth] = nil
    redirect_to root_url, notice:"Sign OUT"
end
end

user.rb
   class User < ActiveRecord::Base
    def self.sign_in_from_omniouth(auth)
    find_by(provider: auth['provider'], uid: auth['uid'])||
    create_user_from_omniauth(auth)
end

   def self.create_user_from_omniauth(auth)
      create(
    provider:auth['provider'],
    uid:auth['uid'],
    name:auth['info']['name']

    )
end
end
end

can any one help me?
Answer: As per error encountered, client_id is missing.
Try the basic steps given in the documentation wherein to obtain OAuth 2.0 credentials from the Google API Console by doing this:

Visit the Google API Console to obtain OAuth 2.0 credentials such as a client ID and client secret that are known to both Google and your application.

Please also try enabling the "Contacts API" and "Google+ API" via the Google API console. As noted in this GitHub post, if these are not enabled, you will receive OAuth2::Error(Error: "Invalid credentials") stating that access is not configured when you attempt to authenticate.
Please try going through the given GitHub post, OmniAuth Google OAuth2 Strategy for important details.

error in Sign with Google+ in rails


How to reference parent DataContext in user control [C++/winrt]

Question: Edit: Solved via blank user control, not custom control (See below solution)
I'm basically trying to modularize complex XAML stuff away from MainPage into a user control, hence I need to figure out how to inject the local DataContext within MainPage.Xaml into my user control.
Following the MSDN Doc's tutorial for custom user controls, I have a custom control in my MainPage.xaml file, called NutriDetailsControl.
// MainPage.xaml

...<ListBox x:Name="ItemList" ItemsSource="{x:Bind Basket}" RelativePanel.Below="AddDelCol"
      <ItemsControl.ItemTemplate>
         <DataTemplate x:DataType="local:BasketItem">
            <StackPanel GotFocus="ItemGotFocus" Orientation="Horizontal">
               <Button Content="Delete" Click="DeleteItemClickHandler"/>
               <TextBlock VerticalAlignment="Center" Text="{x:Bind Name, Mode=OneWay}"/>
HERE------->   <local:NutriDetailsControl Background="Red" MyItem="Hello, World!" MyBasketItem="x:Bind ???"/>
            ...
         ...
      ...
   ...
...</ListBox>

MyItem is a string, and I am able to access it within the custom user control, but I can't access MyBasketItem, which is a DependencyProperty of type BasketItem (ViewModel variable within the local DataContext). In Generic.Xaml, I've tried to access BasketItem's data via binding locally, and through the DependencyProperty I passed in (MyBasketItem),

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:NutritionBasket">

                                    </Flyout.FlyoutPresenterStyle>
                                    <StackPanel>
    LOOK HERE ---------------->          <TextBlock Text="{x:Bind Name}"/>
     AND HERE ---------------->          <TextBlock Text="{TemplateBinding MyBasketItem.Name}"/>
                                    </StackPanel>
                                </Flyout>
                            </Button.Flyout>
                        </Button>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

For the first line, I am trying to access BasketItem->Name() via the local DataContext. I am getting an error "This Xaml file must have a code-behind to use {x:Bind}".
For the second line, when I am passing in BasketItem as a DependencyProperty within NutriDetailsControl.h, I am getting "MyBasketItem is not supported in a Windows Universal project"
I know that for Name(), I can simply pass it in as a DependencyProperty; my GOAL is to reference another variable, BasketItemNutri() which is a sub-ViewModel variable of BasketItem. So I need to figure out a way to either pass in BasketItem, or BasketItemNutri, from the MainPage into custom user control.
Any help would be appreciated. What should I do?
Answer: Solved
I wasn't able to get the Nico's solution to work for me, since I still needed to somehow bind within NutriDetailsControl.xaml to MyBasketItem, and no permutation I tried seemed to work.
After reading the Data Binding in Depth, I thought maybe I should forget about this whole custom control thing situation, and just go with a blank user control, called NutriControl.
I created a DependencyProperty in NutriControl.idl (blank user control) by adding
static Windows.UI.Xaml.DependencyProperty MyBasketItemProperty{ get; };
        BasketItem MyBasketItem;

(Note that MyBasketItemProperty and MyBasketItem; must be the same). A DependencyProperty of a user control, "exposed" through the NutriControl.idl file, is basically like a box that you can put data into from other Xaml files (like MainPage.xaml). The data can be text, class objects (including your viewmodels), etc.
// Mainpage.Xaml
<local:NutriControl MyBasketItem="{x:Bind}"/>

"x:Bind" binds to the local DataContext (DataType??), which was a BasketItem here, so I didn't need to specify anything else.
// NutriControl.h
...other stuff...
struct NutriControl : NutriControlT<NutriControl>
    {
        NutriControl();

        NutritionBasket::BasketItem MyBasketItem()
        {
            return winrt::unbox_value<NutritionBasket::MyBasketItem>(GetValue(m_myBasketItemProperty));
        }

        void MyBasketItem(NutritionBasket::MyBasketItem const& value)
        {
            SetValue(m_myBasketItemProperty, winrt::box_value(value));
        }

        static Windows::UI::Xaml::DependencyProperty MyBasketItemProperty() { return m_myBasketItemProperty; }

        static void OnMyBasketItemChanged(Windows::UI::Xaml::DependencyObject const&, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const&);

    private:
        static Windows::UI::Xaml::DependencyProperty m_myBasketItemProperty;
    };
}
...other stuff...

// NutriControl.c
    NutriControl::NutriControl() {
        InitializeComponent();
    }

    Windows::UI::Xaml::DependencyProperty NutriControl::m_myBasketItemProperty =
        Windows::UI::Xaml::DependencyProperty::Register(
            L"MyBasketItem",
            winrt::xaml_typename<NutritionBasket::BasketItem>(),
            winrt::xaml_typename<NutritionBasket::NutriControl>(),
            Windows::UI::Xaml::PropertyMetadata{ winrt::box_value(L"default label"), Windows::UI::Xaml::PropertyChangedCallback{ &NutriControl::OnMyBasketItemChanged } }
    );

    void NutriControl::OnMyBasketItemChanged(Windows::UI::Xaml::DependencyObject const& d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const& /* e */)
    {
       // still unimplemented
    }

// NutriControl.Xaml
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button HorizontalAlignment="Right" VerticalAlignment="Center" Content=">">
            <Button.Flyout>
                <Flyout>
                    <Flyout.FlyoutPresenterStyle>

                    </Flyout.FlyoutPresenterStyle>
                    <StackPanel>
 see here-------->      <TextBlock Text="{x:Bind MyBasketItem.Nutrition.Amount, Mode=OneWay}"></TextBlock>
 and here-------->      <ListBox ItemsSource="{x:Bind MyBasketItem.Nutrition.Elems}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate x:DataType="local:BasketItemNutriElem">
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock VerticalAlignment="Center" Text="{x:Bind Nutrient, Mode=OneWay}"/>
                                        <TextBlock VerticalAlignment="Center" Text="{x:Bind Amount, Mode=OneWay}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ListBox>
                    </StackPanel>
                </Flyout>
            </Button.Flyout>
        </Button>
    </StackPanel>

This worked. MyBasketItem (-> Nutrition) and (->Elems->BasketItemNutriElem) are both sub-viewmodels of type BasketItem, so I've successfully passed local instances of viewmodels from MainPage.Xaml to a user control.
Answer:
So I need to figure out a way to either pass in BasketItem, or BasketItemNutri, from the MainPage into custom user control.

You has placed NutriDetailsControl in the  DataTemplate, so you can't use x:Bind to bind property in the code behind directly. For this scenario, the better way is that use bind element name then find it's DataContext
MyBasketItem="{Binding ElementName=ItemList,Path=DataContext.MyBasketItem}"

Please note, you need specific current page as page's DataContext.
public MainPage()
{

    this.InitializeComponent();
    DataContext = this;
}

For more detail please refer this case reply .