Why the progress dialog does not show?

Question: My coding works where the data is saved in the real-time database. However, the progress dialogue does not work. How to put a coding to show if the data failed to be saved in the real-time database?
private void SaveAccountInformation() {

    loadingBar.setTitle("Registration Account");
    loadingBar.setMessage("Please wait while we are registering you in our system.");
    loadingBar.show();
    loadingBar.setCanceledOnTouchOutside(true);

    String firstname = RegisterFirstName.getText().toString();
    String lastname = RegisterLastName.getText().toString();

    if (TextUtils.isEmpty(firstname))
        Toast.makeText(RegistrationActivity.this, "Enter your first name.", Toast.LENGTH_SHORT).show();

    else if (TextUtils.isEmpty(lastname))
        Toast.makeText(RegistrationActivity.this, "Last name is required.", Toast.LENGTH_SHORT).show();

    else {
        String userid = databaseUser.push().getKey();
        User user = new User(firstname, lastname);
        databaseUser.child(userid).setValue(user);
        Toast.makeText(RegistrationActivity.this, "Registration has been successful.", Toast.LENGTH_SHORT).show();

        Intent HomeIntent = new Intent(RegistrationActivity.this, home.class);
        HomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(HomeIntent);
        finish();
    }

    loadingBar.dismiss();
}

Comment: progressDialog  only show when you done job in background, and you are working on main thread
Comment: It is showing but your code running fast, when you do any network task then it will be show
Comment: learn asynctask, thread and use according to your requirement
Comment: I cant share it here, because its too long....
Comment: Where did you initialize the `loadingBar`?
Comment: Inside this Java Class also
Comment: private ProgressDialog loadingBar;
loadingBar = new ProgressDialog(this);
Comment: You show then dismiss the dialog immediately, is that intended behavior that you want?
Comment: Is there a chance of your data is saving too quickly that you are missing the progress dialog?
Comment: Oh no, I want to remove the progress dialog if the data is successfully stored in the database or not.
Comment: Im not sure @ReazMurshed :'(
Comment: So how should I change the coding @Lokesh?
Comment: please write your db operation in thread simple
Comment: How @Lokesh? I am not clear.
Comment: @Adda put loadingBar.dismiss() inside registration complete condition before intent
Comment: Still did not show the progress dialog @VishalThakkar :'(
Comment: Can you please check my answer below?
Answer: As far as I have understood about your problem you want to track if the data is saved properly or not and show a progress dialog in the meantime. I suppose you are using Firebase database and saving the values under a specific node.
You might consider having a callback function here I suppose while saving the data in your Firebase real-time database.
I am rewriting the code. Please note that the code is not tested and modify if you get any syntax errors.
private void SaveAccountInformation() {

    ProgressDialog loadingBar = new ProgressDialog(RegistrationActivity.this);
    loadingBar.setMessage("Please wait while we are registering you in our system.");
    loadingBar.show();
    loadingBar.setCanceledOnTouchOutside(true);

    String firstname = RegisterFirstName.getText().toString();
    String lastname = RegisterLastName.getText().toString();

    if (TextUtils.isEmpty(firstname))
        Toast.makeText(RegistrationActivity.this, "Enter your first name.", Toast.LENGTH_SHORT).show();

    else if (TextUtils.isEmpty(lastname))
        Toast.makeText(RegistrationActivity.this, "Last name is required.", Toast.LENGTH_SHORT).show();

    else {

        String userid = databaseUser.push().getKey();
        User user = new User(firstname, lastname);

        databaseUser.child(userid).setValue(user)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Toast.makeText(RegistrationActivity.this, "Data saved successfully!", Toast.LENGTH_SHORT).show();
                    loadingBar.dismiss();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(RegistrationActivity.this, "Failed to save the data", Toast.LENGTH_SHORT).show();
                    loadingBar.dismiss();
                }
            });

        Intent HomeIntent = new Intent(RegistrationActivity.this, home.class);
        HomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(HomeIntent);
        finish();
    }
}

Hope that helps.
Comment: Thanks sir! I saw the progress dialog but in a few moments, it disappeared.
Answer:  private ProgressDialog  progressDialog = new ProgressDialog(Login.this);

 progressDialog.show();
 progressDialog.setMessage(getResources().getString(R.string.loading));
 progressDialog.setCancelable(false);

 progressDialog.dismiss();//close progressDialog

Comment: Which type of operations in use progress bar

Why the progress dialog does not show?


Crash when deleting a pointer

Question: I have an assignment to create a PriorityQueue structure and  I'm having trouble with this piece of code. When I compile it on my compilator everything's fine, but I tried submitting it to ideone and I get the following error:

"glibc detected *** ./prog: double free or corruption".

I was able to track the part that was giving me this error and I found out that what causes the crash is me trying to delete a pointer at the destructor of my class. The problem is that I don't know why I cant delete it. I don't know a lot about pointers but I thought that if I used new to allocate memory I had to delete it after using it and I think this is what I'm trying to do. Here is my code:
struct PriorityQueue
{
LinkedList queue; LinkNode *it,*node;
int sz;

PriorityQueue(){
    sz=0;
    queue.head=NULL;
    queue.tail=NULL;
    it = NULL;
    node=NULL;
}

~PriorityQueue(){

    if(node != NULL) //this is causing the error.
    delete [] node;

    if(it != NULL)
    delete [] it;
}

int size(){

    return sz;
}

void enqueue(int x){

    node = new LinkNode(x,NULL,NULL);

    if(sz==0){

        queue.insert_head(x);
        sz++;

    }

    else{

    if(x <= queue.head->value ){

        queue.insert_head(x);
        sz++;

    }

    else if( x>= queue.tail->value ){

        queue.insert_tail(x);
        sz++;

    }
    else{

        it = queue.head;

        for(int k=0;k<sz;k++){

                if( (x>= it->value)  && (x <= it->next->value) ){

                     node->next= it->next;
                     node->previous = it;

                     it->next->previous = node;
                     it->next = node;
                     sz++;
                     break;

                }

                    it=it->next;

        }

    }

    }

}

int dequeue_min(){

    int min = queue.remove_head();
    sz--;

    return min;
}

int dequeue_max(){

    int max= queue.remove_tail();
    sz--;

    return max;
}

};

int main()
{
PriorityQueue pq;
pq.enqueue(4);
pq.enqueue(2);
pq.enqueue(7);
pq.enqueue(-6);
pq.enqueue(0);
cout << pq.dequeue_min() << endl;   // debe imprimir -6
cout << pq.dequeue_min() << endl;   // debe imprimir 0
pq.enqueue(3);
cout << pq.dequeue_min() << endl;   // debe imprimir 2
cout << pq.dequeue_min() << endl;   // debe imprimir 3

return 0;
}

Thanks.
Comment: Using the wrong form of `delete` is UB.
Answer: it and node point to objects, not arrays.
You cannot use the array form of delete[] on them.
Answer: Using delete[] will try to remove a pointer whose object is an array of some sort. There is another type of delete, that allows for the deletion of pointers to single objects. (Hint: it's pretty intuitive)
Answer: You are deleting it and node using delete []. They are not arrays. You can only use delete [] syntax on arrays or arrays of your objects. Remember the rule of thumb to use the similar delete and new commands for the same data types. If you have allocated memory by new, delete by delete. If you have allocated memory by new [], delete it  by deete [].
Answer: It seems that it and node not only point to objects rather than arrays, as Slaks pointed out, it seems they also potentially point to the same thing. As a side note, you don't need to check for null before calling delete[] p or delete p: If the pointer p is null, this expression will have no effect.
It is unrelated to your question but please also note that your priority queue as O(n) (with n being the size) complexity. Typically, when implementing a priority queue you want to get O(log(n)) complexity. The easiest strategy to implement such a priority queue is a d-heap which, conveniently, lives in an array and is actually easier to maintain than your linked list (I think, at least).

Crash when deleting a pointer


How do I get Bootstrap modals to work with AngularJS?

Question: I would like to get my Bootstrap modals to work with AngularJS. One modal is

My Modal

MODAL BODY

                <button class="btn btn-primary">Save</button>

It adds a song to a playlist the user already has or creates a new playlist. I want to use it with a set of songs, but only have it work with 1 song at a time (for now).

The Angular controller is
'use strict';

angular.module('PortalApp')
  .controller('SongsCtrl', function ($scope, MediaService, $location, AudioPlayerAPI, FavoriteService) {

$scope.toggleFaves = function (song) {

  FavoriteService.toggle(song).success(function (response) {
    if (response.successFlag) {
      song.favorite = !song.favorite;
    }
  });
}

$scope.fetched = false;

});

How do I make this work?
P.S. I don't want jQuery, just the jQuery Lite plugin Angular has.
Comment: See my answer here: http://stackoverflow.com/questions/18875095/how-can-i-populate-modal-data-with-angular-js
Answer: You should look at the AngularUI Bootstrap modals (http://angular-ui.github.io/bootstrap/#/modal). Passing data in and out is very easy and it all works the Angular-way.
Answer: Here's a reusable Angular directive that will hide and show a Bootstrap modal.
app.directive("modalShow", function () {
    return {
        restrict: "A",
        scope: {
            modalVisible: "="
        },
        link: function (scope, element, attrs) {

            //Hide or show the modal
            scope.showModal = function (visible) {
                if (visible)
                {
                    element.modal("show");
                }
                else
                {
                    element.modal("hide");
                }
            }

            //Check to see if the modal-visible attribute exists
            if (!attrs.modalVisible)
            {

                //The attribute isn't defined, show the modal by default
                scope.showModal(true);

            }
            else
            {

                //Watch for changes to the modal-visible attribute
                scope.$watch("modalVisible", function (newValue, oldValue) {
                    scope.showModal(newValue);
                });

                //Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
                element.bind("hide.bs.modal", function () {
                    scope.modalVisible = false;
                    if (!scope.$$phase && !scope.$root.$$phase)
                        scope.$apply();
                });

            }

        }
    };

});

Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition

 ...bootstrap modal...

Usage Example #2 - this uses an Angular expression in the modal-visible attribute

 ...bootstrap modal...

Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)

I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal
Hope this helps.


Dirichlet processes for supervised learning?

Question: It seems when I glance around here at the fashionable learning algorithms, things like neural networks, boosted trees, support vector machines, random forests, and friends are promoted for supervised learning problems. Dirichlet processes and their ilk seem to be mentioned mostly in unsupervised learning problems, such as document or image clustering. I do see them get used for regression problems, or as general purpose priors when one wants to do Bayesian statistics in a nonparametric or semiparametric way (e.g. as a flexible prior on the distribution of random effects in certain models) but my limited experience suggests that this doesn't come as much from the machine learning crowd as it does from more traditional statisticians. I've done a small amount of googling on this and I've found a few definitive uses in machine learning of DPs for supervised learning, but it seems like whenever I need to look up something about (say) hierarchical DPs, whatever paper I find the answer in is using it for unsupervised learning.
So, are Dirichlet processes and their cousins most effective as priors for flexible clustering models? Are they not competitive with boosting, SVMs, and neural networks for supervised learning problems? Are they useful only in certain situations for these problems? Or is my general impression incorrect?
Comment: What sort of regression do mean? in the base distribution of the DP? or in the mixing parameter?  I would think you'd have a hard time fitting such a model.
Comment: Or do you mean some sort of generic "regression" where you fit a multivariate DP to the marginal and joint distributions.
Comment: @probabilityislogic fit distribution drawn from DP to joint and then go get the conditionals is the sort of thing I had in mind, with variations on that theme. Modeling the weights in the stick breaking construction is similar.
Answer: This question isn't getting too much attention, so I'm going to answer to update on what I've found and (hopefully) stimulate discussion. I've ran into an article I'm looking forward to reading that uses DPMs to do classification (Shahbaba and Neal, 2007) which they tested on protein fold data. Essentially it appears that they used did something similar to what I suggested in the comments above. It compared favorable against both neural networks and support vector machines. This comes as a bit of a relief to me since I've dumped a lot of time into these models with an eye towards supervised machine learning problems so it appears I (perhaps) haven't been wasting my time.
Answer: Take a look at the DPpackage of R. Dirichlet process can be used at least as a prior for a random effect, and to construct a nonparametric error distribution for regression.


Adobe Air - Database vs XML for large static data

Question: I'm developing an application using Flas Builder / Flex for Adobe Air.  This application will be processing a large set of static text (100 - 200 MB) using a variable set of processing instructions.  The target platforms will be iOS, Android and Desktop.
The data set can be either one large XML file or broken into a bunch of XML files about 3MB each.  This will be decided at design time.
From your experience would it be better to store the text in an Adode Air database or a set of XML files for best performance (including speed and battery life)?
What other considerations should I take into account?
Answer: I quote one of my favourite bookmarks:
There are several different methods for persisting data in AIR applications:

Flat files
Local shared objects
EncryptedLocalStore
Object serialization
SQL database

Each of these methods has its own set of advantages and disadvantages (an explanation of which is beyond the scope of this article). One of the advantages of using a SQL database is that it helps to keep your application's memory footprint down, rather than loading a lot of data into memory from flat files. For example, if you store your application's data in a database, you can select only what you need, when you need it, then easily remove the data from memory when you're finished with it.
Source: http://www.adobe.com/devnet/air/articles/10_tips_building_on_air.html
I don't understand one thing: is EVERY file 100-200 Mb in size? Or this is the total size of ALL your files?
Comment: The data set can be either one large XML file (100-200 MB) or broken into a bunch of XML files about 3MB each. I can do both ways.
Comment: I would not load a 200 Mb XML file (you can try with 3 Mb, but remember to free memory with disposeXML). Anyway, I would go SQLite.


Is it possible to change the layout of the registration form using display suite?

Question: My registration form contains the following fields
-Name
-City
-Mobile
-Email
-Password
-Confirm Password
-Terms and Conditions (using legal module)
Is there some way to change the layout? I want it to appear something like this
<code>************** ***************
*   TERMS    * *   Name      *
*     &      * *   City      *
*   COND.    * *   Mobile    *
* ************ *   Email     *
*   Submit   * *   Password  *
************** ***************
</code>
Comment: By using user-register.tpl you can have this.
Comment: is it possible to do this using display-suite
Comment: It's not possible with Display suite. You may go with custom `.tpl` file.
Answer: Sorry, I don't think it is possible with display suite on its own but you may find this link helpful Changing the layout of user profile edit page. Display suite appears to only get you some of the way there.
Comment: Its not showing all the fields. Just the name, city and mobile
Comment: You may find this post useful http://drupal.stackexchange.com/questions/90163/changing-the-layout-of-user-profile-edit-page.


How to take z scores of averages

Question: I have a bunch of neuropsychological test scores for patients and controls which I have then grouped into cognitive domains and averaged the scores across each individual test to get domain averages for each participant. I want to use z scores of single patient vs control group to look for significance in each domain. My problem is the z score uses standard deviation and I don'd know how to calculate this for the domains in the control group. Do I sum all the standard deviations of the individual tests or do I calculate from the domain averages (so it would be the deviation of the mean of the means)?
Comment: One generally uses t-tests for this.
Comment: Thanks Carl, but we are using the Z-scores to standardise the unequally weighted tasks
Comment: One can use z-statistics when the standard deviations are known, when they are estimated from the population, one corrects for the error by using t-statistics. BTW, only in medicine would anyone say "Z-scores". The "z" is not usually capitalized, and it is not a score.
Comment: So essentially I am trying to compare one participant to twelve controls. I understand now why t-statistics are better but it doesn't wipe out the fact that I have tasks with unequal weightings. For example in the 'executive' domain I have one task that has a total possible score of 60 and one test with a total of 6. If I averaged across those the one out of 6 would have very little bearing on the overall mean even if they are significantly impaired. Do you have any suggestions as to which tests I can use?
Comment: So far, I know that your data is not paired. That rules out the more powerful tests. It is unclear from your description what should be used. 1) Is the data normally distributed? 2) How many patients are in the test group? If I take you at your word that there is only one test subject, then one-sample Wilcoxon might be useful. Wilcoxon is the non-parametric version of a t-test. A t-test would be parametric but requires normal conditions. I would not use one-sample t-testing without reasonable evidence of normality.
Comment: Thank you Carl, that's really helpful. The data is unfortunately not normal. There are 13 patients in the test group and 12 controls but we wanted to look at it as a case series and so treating each patient as a single case. I shall look at the Wilcoxon.
Answer: You are asking for the One-Sample Wilcoxon Signed Rank Test. However, I think you need to do a two-sample test to compare difference of location, e.g., Mann-Whitney, as well as a Conover test which is a non-parametric test for difference of variance. I like the Wikipedia entry on that last one (I wrote it, so I am partial, even though it is sloppy.)

How to take z scores of averages


Classical Hardy inequality from the modern form of the Hardy inequality.

Question: This is well known Hardy operator $$(Hf)(x)=\frac{1}{x}\int_{0}^{x}f(t)dt. (1)$$
We have the classical Hardy inequality
$$\int_0^{\infty}\left(\frac{1}{x}\int_0^x f(t)dt\right)^pdx\leq \left( \frac{p}{p-1}\right)^p\int_0^{\infty}f^p(x)dx, (2)$$ which tells us about the boundedness of the Hardy operator in $L^p(0,\infty)$ (conditions on $p$ and $f$ are not impotant for this question).
During the last decades this inequality was extended to the form $$\left( \int_0^{\infty}\left( \int_0^x f(t)dt\right)^pu(x)dx\right)^{\frac{1}{p}}\leq C \left( \int_0^{\infty}f^p(x)v(x)dx\right)^{\frac{1}{p}}, (3)$$ which holds when $A<\infty,$ where $$A=\sup_{t>0}\left(\underbrace{ \int_t^{\infty}u(s)ds}_{T}\right)^{1/p}\left(\int_0^tv^{1-p^{'}}(s)ds\right)^{1/p^{'}}.$$
The inequlity (3) (if I understand correct) tells us about the boundedness of the operator $\int_0^xf(t)dt$ from $L^p_u(0,\infty)$ to $L^p_v(0,\infty)$
QUESTION 1: Does the condition on A mean that the operator $\int_0^xf(t)dt$ does not bounded in $L^p(0,\infty)$? (because of the term $T$).
QUESTION 2: How we get the classical Hardy inequality from the modern one? We show that the operator $\int_0^xf(t)dt$ is bounded from $L^p_{\frac{1}{x^p}}(0,\infty)$ to $L^p(0,\infty)$. In other words $$\left( \int_0^{\infty}\left( \int_0^x f(t)dt\right)^p\frac{1}{x^p}dx\right)^{\frac{1}{p}}\leq C \left( \int_0^{\infty}f^p(x)dx\right)^{\frac{1}{p}}.$$
And then say that it is equavalent to the boundedness of Hardy operator $$(Hf)(x)=\frac{1}{x}\int_{0}^{x}f(t)dt$$ in $L^p(0,\infty)$. Are my thoughts correct?
Answer: Answer to Question 1: The operator $\int_0^x f(t)\,dt$ is not bounded on $L^p(0,\infty)$ for $p>1$, but your reason is not correct. In this case, $u=v=1$ and thus $A=\infty$. However, what you invoked here is that "$A<\infty$ implies boundedness", which doesn't mean that "$A=\infty$ implies unboundedness"! So, you can't conclude anything if $A=\infty$. To show that $Tf(x)=\int_0^x f(t)\,dt$ is not bounded on $L^p(0,\infty)$ for $p>1$, we consider the function $f(t)=\frac1t \chi_{(1,\infty)}(t)$, then $f\in L^p(0,\infty)$ for $p>1$, but $Tf(x)=\log x\cdot\chi_{(1,\infty)}(x)\notin L^p(0,\infty)$. So, $T$ is not bounded on $L^p(0\infty)$.
Answer to Question 2: Your thoughts are correct. We only need to take $u(x)=x^{-p}$ and $v=1$, in which case we have
$$\left(\int_t^{\infty}u(s)ds\right)^{1/p}\left(\int_0^tv^{1-p^{'}}(s)ds\right)^{1/p^{'}}\stackrel{\text{if }p>1}=C\left(t^{-p+1}\right)^{1/p}t^{1/p^{'}}=C t^{-1+\frac1p+\frac1{p'}}=C,\qquad t>0,$$
thus $A<\infty$. Note that here we need $p>1$ ("conditions on $p$ are not impotant for this question", no, $p>1$ is needed). Now it follows from the modern Hardy inequality that
$$\left( \int_0^{\infty}\left( \int_0^x f(t)dt\right)^p\frac{1}{x^p}dx\right)^{\frac{1}{p}}\leq C \left( \int_0^{\infty}f^p(x)dx\right)^{\frac{1}{p}}.$$
This is the classcial Hardy inequality, expect that we cannot determine the best constant $\frac{p}{p-1}$. We cannot deduce this constant from the modern one.


require help in routing in asp.net core 3.0

Question: In my regular MVC project i handle routing like below and there are similar routings for other pages as well.
public static void RegisterRoutes(RouteCollection routes) {
    routes.MapRoute(
        name: "",
        url: "login",
        defaults: new { controller = "Access", action = "SignIn", id = UrlParameter.Optional }
    );
}

but am not able to do it in asp.net core 3.0.
When i tried to use the similar approach in asp.net core 3.0, the page is redirecting. but the styles and scripts are not getting loaded.
Answer: Make sure you added the following settings at the Configure Method of Startup.cs
app.UseRouting();

app.UseEndpoints(endpoints =>
{
    services.AddControllersWithViews();
    services.AddRazorPages();
});

Also, set your route inside of UseEndpoints method as follows:

app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute("default", "{controller=Access}/{action=SignIn}/{id?}");
    });


Evaluate this network with three firewalled zones

Question: I want to set up a basic lab for a one-time project.
This is what I was thinking:
<code>computer ->Router -> firewall e0 -> switch 1 -> DMZ (just a web server for now)
                     firewall e1 -> switch 2 -> inner network (office comps)
</code>
Now this is NOT going to be connected to the Internet in any way, it is going to be all within the same LAN. I usually go with 192.168.1.0 and 220.127.116.11... but that's probably not that important.
My questions:
First of all, will this setup even work? it doesn't need to be great. All I want to do is to do some scans on target machines, and set a couple new rules on the firewall. I'm worried about the comp to router connection, I just need it to connect to the network and I don't have another switch. I suppose I could always disconnect things and move them around to show another scenario.
Secondly, what special configurations( RIP, trunking, etc...) might I need to do for this setup?
I do have another router if needed but only one crossover cable, I do have a serial cord for the routers if I need that.
Answer: The set up is valid, however with a set up this size I would recommend just sticking with static routes on routers and firewalls. If you plan to do some scans pay attention to natting on that firewall. Chances are you will not want to nat at all.
As for RIP, it's not needed but if you want to learn a routing protocol use OSPF or EGRP.
You could play with trunking or should I say VLANS if you just want to learn but a network of this size will not benefit greatly from the layer 2 optimization that VLAN's can provide. Not to mention it seems you only have one or no devices connected on your switches in these diagrams.
Most modern day devices do not require a crossover nowadays but if you run across some older devices such as these it is quite possible you may need to create the cross over cables.
Answer: If all the workstations/test machines are in the same subnet its gonna work just fine. I suggest you turn on the DHCP server just to make it more easy for you test machine to get an IP and a default Gateway.
If not, you need to configure a static route or a routing protocol.
Depending on how old are your equipement, crossover cables are no longer required, modern switch and routers are quite clever enough to detect the equipement connected to them.
Answer: You need at least 3 ports on your router, because you have 3 subnets.
(ignoring the firewalls for a minute) You don't need any kind of dynamic routing because you only have 3 subnets directly connected to your router.  You only need to share routes when you have multiple routers.  Your machines on each subnet should use the IP address of the router for the interface on their subnet for the default gateway (upstream gateway).
If you transparently firewall (firewall don't have IP addresses) you only have 3 subnets.  If you don't want to have a bridging firewall you need to have additional subnets and then you need to inform your router than "subnet dmz" is reachable out interface X and vice-versa.
Once you start segmenting at layer 3 (IPs and subnets), you possibly make DHCP much more complicated because it relies on broadcasting within a subnet.


How does finite integral implies convergence almost everywhere in this proof in Stein-Shakarchi's Functional Analysis?

Question: I am trying to understand a step in the following proof of completeness of $L^p$ in Stein-Shakarchi's Functional Analysis. (See the proof on page 5 of the link or at the end of this post.)
In the proof, it is said that:

... applying the monotone convergence theorem implies that $\int g^p<\infty$, and therefore, the series defining $g$ and hence the series defining $f$ converges almost everywhere, and $f\in L^p$.

I do not understand why.
Question 1: How does one get from the above argument that the almost everywhere convergence?
Question 2: How does one get that $f\in L^p$?
Comment: There's a theorem that convergence in $Lp$ implies a convergence almost everywhere of a sub-sequence. I suppose you can get rid of the sub-sequence somehow, though I'm not sure how.
Answer: Since $g \geq 0$ and $\int g^p<\infty$, $g^p$ (and thus $g$) is finite almost everywhere. Thus the series defining $g$ converges almost everywhere.
Since $|S_K(f)(x)| \leq S_K(g)(x)$ for all $x$, the series defining $f(x)$ converges for almost every $x$.
Finally, $|f| \leq |g|=g$, so $\int|f|^p \leq \int g^p < \infty$, so $f \in L^p$.
Comment: Well what happens to $\int g^p$ if $g \geq 0$ and $g^p$ is infinite on a set of positive measure?
Comment: This is nothing to do with $L_p$, just the definition of integration. If $g=\infty$ on a set $A$ of positive measure, what is $\int_A g^p $? Then, since $g \geq 0$, we have $ \int g^p  \geq \int_A g^p $...
Comment: It's not necessarily true that $|g|<\infty$ everywhere, only *almost* everywhere. This is a result of the fact that $\int g^p<\infty$. Moreover, your claim that $|g|<\infty$ implies $\int |g|^p<\infty$ is false.
Comment: This set of measure zero could be $\emptyset$, but it could be nonempty. I can't possibly say what this set is when the functions $f_n$ are completely arbitrary, but the point is such a set could exist.
Comment: The "almost everywhere" doesn't change anything. That's just shortcut for "on a set whose complement has measure zero." If this series is finite at a point $x$, it converges at a point $x$ because this is the definition of convergence. Thus if it is finite almost everywhere (i.e., at every $x$ in a set whose complement has measure zero), then it converges almost everywhere (i.e., at every $x$ in a set whose complement has measure zero).
Comment: What is the result that guarantee the first line?
Comment: I don't know. I don't know much about $L_p$ results.
Comment: I think your first paragraph is not necessary since we have that $S_K(g)$ converges. Hence $g=\vert g\vert$ converges which can be seen as $|g|<\infty$ thus $|g|^p<\infty$, thus $\int|g|^p<\infty$.
Comment: almost everywhere, then there must be a set of measure zero such that $\vert g\vert$ is not finite, where is this set?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/93566/discussion-between-galleta-and-kccu).
Comment: I think a proof for this is needed, finite almost everywhere then converges almost everywhere. Could you provide please?
Comment: If a series has a finite sum then it converges. That is what it means to converge, that is the definition.
Comment: yes:) but notice I wrote _almost everywhere_ .Anyway nevermind I am reading of it. (I should have delete my previous comment hehe..)


Dropping unused levels in facets with ggplot2

Question: Is it possible to drop levels that are not used in ggplot2s facets? This is my code:
tab = as.data.frame(cbind(groups = mtcars$cyl, names = row.names(mtcars), val = mtcars$mpg, N = mtcars$disp))
tab$N = as.numeric(tab$N)

ggplot(tab, aes(names,val)) +
geom_point() + coord_flip() +
theme_bw() +
facet_grid(groups ~ ., drop=TRUE)#, scales="free", as.table=F, space="free")

I tried the drop=T switch but it doesnt help. What am I doing wrong?
Comment: For pure programming (not stats) questions like this, please migrate to StackOverflow
Answer: Your example data just doesn't have any unused levels to drop. Check the behavior in this example:
dat <- data.frame(x = runif(12),
                  y = runif(12),
                  grp1 = factor(rep(letters[1:4],times = 3)),
                  grp2 = factor(rep(LETTERS[1:2],times = 6)))

levels(dat$grp2) <- LETTERS[1:3]

ggplot(dat,aes(x = x,y = y)) +
    facet_grid(grp1~grp2,drop = FALSE) +
    geom_point()

ggplot(dat,aes(x = x,y = y)) +
    facet_grid(grp1~grp2,drop = TRUE) +
    geom_point()

It may be that you're looking to change which factors are plotting on the vertical axis in each facet, in which case you want to set the scales argument and use facet_wrap:
ggplot(tab, aes(names,val)) +
    geom_point() + coord_flip() +
    theme_bw() +
    facet_wrap(~groups,nrow = 3,scales = "free_x")

Comment: For future readers, `drop` drops any factor levels that weren't used in *any* facet of the plot, while `scales` drops any factor level that wasn't used in a particular facet of the plot.  This took me a while to understand from this post, so I thought I'd clarify here to save someone else the trouble.
Comment: Oh i see now what it does. My intention was to plot only those levels in every facet, that are actually grouped by the facet. Like, using my tab example,`dotchart(as.numeric(tab$val), labels=tab$names, groups=tab$groups)`. Is it possible?
Comment: @mrrrau Yes, see my edit.
Comment: @JakeFisher Thanks for pointing this out!  Quite helpful!


Give an example of a series such that $\sum a_n$ is convergent but $\sum a_{3n}$ is divergent

Question: Give an example of a series such that $\sum a_n$ is convergent but $\sum a_{3n}$  is divergent.
I am trying to construct an example such that $\sum a_n$ is convergent but $\lim a_{3n}$ is not zero. But I could not find such example. Give me some hints.
Comment: Hint:  start with the alternating harmonic sequence, so $a_{3n}=\frac {(-1)^n}n$.  That diverges.  Now add terms to make the full sequence converge (conditionally).
Comment: By "convergent" do you mean absolutely convergent, or what?
Comment: @Rwitam Jama, your point it would not be useful, since the series converges $a_n$ tends to zero, so is every subsequence.
Comment: @lulu  If $a_{3n} = (-1)^n/n$ then $\sum a_{3n}$ converges.
Comment: @zhw  Right, of course.  So make $a_{3n}=\frac 1n$, even simpler.
Answer: $$1/2 + 1/2 -2/2 +1/3 +1/3 -2/3 + 1/4 + 1/4- 2/4 + 1/5 + 1/5 -2/5 + \cdots $$


How to display module ouptput in a page with content

Question: I would like to display my module otuput in one page. The only solution I found till now is to use iframes. Is there some better solution?
I created a module to display a map with branches, branches are stored in DB. But before and after this map there should be some content, like text or pictures.
I hope there is a posibility. Maybe with blocks?
Comment: did you try to use hook_menu and make a new page that display your map (if you want to make it custom) and if you can make a block using a view you can put it at any new page
Comment: I allready use hoock_menu and it's on a page with own link. But my concern is to have a possibility to put it on some page with content, where admin without html or php konweledge can change text throw edit button.
Comment: maybe there a way to enable php in content? so I can symple write  in the content?
Comment: That's it, I simply printed the output of my module with php, thanks!
Answer: If the code for output your result is not so big than you can put the code in block and show that block on any page you want.
Comment: Hi, Sumit, thank you for the answer. I have to display this map only on one single page, and there are queries to the remote DB, so I would like this block to be called only on this single page. Maybe there are some possibilities like print the output of the module in the middle of content? Or print the output somthere in template?
Comment: You can print the block as
`$block = module_invoke('block', 'block', 'view', 'block_id');

$output .= $block['subject'];

$output .= $block['content'];

print $output;`


Integral sinus in C#

Question: I want to implement perfomance-sensitive integral calculations in C#. I was told that function int Sin(int angle) that returns a value between -256 and 255 is useful in this situation, since I don't need it to be exact. Is there a good implementation of such a function that I can use, or some algorithm that I can implement?
Comment: It's just a lookup table. Just create the table using the built-in sin function at startup, and write your function to lookup into that table.  Here is a question which is basically the same, your function would just take an int rather than a double: http://stackoverflow.com/questions/2088194/fast-sin-cos-using-a-pre-computed-translation-array - this answer also uses unsafe code to get a bit of extra speed, but you can just use a normal array if you don't want unsafe code.
Comment: I think that this comment is actually a perfect answer to my question. Thanks!
Comment: @JamesGaunt post this as an answer...
Answer: It's just a lookup table. Just create the table using the built-in sin function at startup, and write your function to lookup into that table. Here is a question which is basically the same, your function would just take an int rather than a double:
Fast Sin/Cos using a pre computed translation array
This answer also uses unsafe code to get a bit of extra speed, but you can just use a normal array if you don't want unsafe code

Integral sinus in C#


Why do we need a pullback for the definition or classification of subobjects?

Question:
Regarding the subobject classifier construction, why do we need the pullback?
Monos from $U$ to $X$ are called subobjects, but I see that there might be injections which just have elements of the X (viewed as a set like in set theory) permuted. This is therefore somewhat weak.
However, as far as I can see, $\text{Hom}(X,\Omega)$ are the characteristic functions (set theory terminology) and these are in bijective correspondence with what we understand as subsets. Why then do we need $U$, $j$, etc. to do set theory? The only purpose for the $U\rightarrow 1\rightarrow\Omega$ route I can come up with is to define $\chi_j$ in terms of function composition and therefore associating $\chi_j$'s with objects like $U$. Is it ment that the subobject classifier enables us to classify certain unique $U$'s and we can then associate objects (like $U$) as subobjects of objects (like X)? But why would that be necessary? Why not just consider $\text{Hom}(X,\Omega)$ as subobjects (vs, plural) of $X$? And in case we just don't want them as morphisms: I've seen hom-sets taken to a new category via a functor, why doesn't this suffice?
Secondly, it's always explicitly stated that we need a terminal object to do all of the above. But don't we also need "true" and "!" as well, must this also always be explicitly required, or are we sure some of them are implying by there being a terminal object?
Lastly, it is said that topos theory aviods the stacking of element-inclusion, i.e. $\in$ get replaced by axioms of function composition. But if Set contains any universe you would want to talk about, then surely these nested sets are to be find there too, and this just means that there are super long chaings involving subobject classifiert. Does this really reduce notational ballast, compared to any set theory with multiple types?
Comment: We already have a pre-existing notion of subobject, and not every category has such a wonderful object as a subobject classifier. (It is the most distinctive feature of a topos.)
Comment: @Nick: You might be trying to be too abstract. We know subsets and characteristic functions are both very useful in set theory. The notion of subset translates quite nicely to category theory in the form of subobjects (represented by monomorphisms). But since characteristic functions are also useful, we want to translate that notion as well. The commutative diagram is pretty much a *direct* translation of the usual set-theoretic definition of characteristic function.
Comment: @Nick: The commutative diagram is the equation that says $\chi_j$ is the characteristic function of the subobject (represented by) $j$. In the set-like internal language, it says  that it is the subobject $$\{ x \in X \mid \chi_j(x) \} $$
Comment: "Why not consider $\hom(X,\Omega)$ as a subobject of $X$?" Are you mixing up of $\hom(X,\Omega)$ with what in $\mathbf{Set}$ are its elements? The elements of $\hom(X,\Omega)$, i.e. the subobjects, are picked out exactly by the diagram you show.
Comment: @KevinCarlson: I'm not sure if I read your question correctly, but what I mean is that every element of the set $hom(X,\Omega)$, which if $\Omega=\{0,1\}$ are characteristic functions, corresponds to a specification of a subset of $X$. Hence, the arrows from $X$ to $\Omega$ should be defined as (isomorphic to) the subsets. Seem to be unique too. But if this would suffice, the we'd not do all this pullback business - I wonder where the problem is. (cont.)
Comment: @KevinCarlson: (cont.) It seems the information of subsets of $X$ are easier to define than with this definition over $j$, I don't understand what this is for. I expect the answer to be something in the sense of "If we consider a fixed category ( = fixed class = fixed objects), then this enables us to say which objects are subobjects of other object in this class". Okay, but still, why not e.g. consider just the characteristic functions and construct a categroy where the subobjects are indexed by nomenclature.
Comment: @ZhenLin: What do you want to say with the first comment? And well, if I consider $hom(X,\Omega)$ to be the subobject then I too need the subobject classifier. But it doesn't explain to me why we need the commutative diagram.
Comment: @Hurkyl: This is essentially *"The only purpose for the $U\rightarrow 1\rightarrow\Omega$ route I can come up with is to define $\chi_j$ in terms of function composition and therefore associating $\chi_j$'s with objects like $U$."* right? This just says which $U$'s or monos $j$'s are really the same subobject.
Comment: @Nick: Tentatively yes. Your statement feels analogous to saying "the only purpose of the group axiom $x x^{-1} = 1$ is to define ${}^{-1}$ in terms of group multiplication, associating inverses with group elements" in that it is a correct statement, but it *feels* like you're missing something significant.
Comment: Perhaps more capable men than myself can answer this, but shouldn't [tag:topoi] be actually [tag:topos-theory] which already exists?
Comment: @AsafKaragila: Yes probably. I asked a category theory question before and someone introduced that tag and added it to my question - that's why I used it again. Regarding the question, I start to feel that the definition is just so one can make this and that construction, but I don't see the necessity yet. Maybe the definition is just to "equalize" (classify as equal subobjects) monos from $U$ with with same codomain (because these would have the same characteristic function)?
Comment: @Asaf I fixed the tags.
Answer: We do not need pullbacks to define subobject classifier. All we need is the notion of a logic over a category, or equally, the notion of subobjects. This may be abstractly characterized as giving a logical fibration over the category. The subobject classifier is then a universal object that allows us to recover all subobjects via substitutions.
Pullbacks are needed to define the logic of subobjects. With every category $\mathbb{C}$ with pullbacks one may associate the canonical logic fibration --- $\mathit{sub} \colon \mathit{Sub} \rightarrow \mathbb{C}$. It is showable that if $\mathit{sub}$ has the universal object $X \rightarrow \Omega$ in the above sense, than $X$ is necessary a terminal object in $\mathbb{C}$.
One may consider other logics over $\mathbb{C}$, and reach other notions of subobjects. For example, the crucial role in the quasitopos is played by a regular subobject classifier --- it is just the universal object induced by the logic of regular subobjects.
One may even consider non-logical fibrations over $\mathbb{C}$, and see how such universal classifiers look like. For example, the external family fibration $\mathit{fam}(\mathbb{C}) \colon \mathit{fam}(\mathbb{C}) \rightarrow \mathbf{Set}$ has a universal classifier precisely when $\mathbb{C}$ is small; it is given by $\mathbb{C}_0$ --- the set of all objects of $\mathbb{C}$.
You have also said:

Monos from U to X are called subobjects, but I see that there might be injections which just have elements of the X (viewed as a set like in set theory) permuted.

That is why we do not define subobjects as monos, but as abstraction classes of equivalent monos.


Understanding a proof that a compact multiplication operator is zero

Question: This answer gives a proof of the fact that if $g\in L^\infty(0,1)$ and the multiplication operator $T_g:L^2(0,1)\rightarrow L^2(0,1)$ is compact, then $g=0$ almost everywhere:

We show that if $g$ is not the equivalence class of the null function, then $M_g$ is not compact. Let $c>0$ such that $\lambda(\{x,|g(x)|>c\})>0$ (such a $c$ exists by assumption). Let $S:=\{x,|g(x)|>c\}$, $H_1:=L^2[0,1]$, $H_2:=\{f\in H_1, f=f\chi_S\}$. Then $T\colon H_2\to H_2$ given by $T(f)=T_g(f)$ is onto. Indeed, if $h\in H_2$, then $T(h\cdot \chi_S \cdot g^{—1})=h\cdot\chi_S=h$.
As $H_2$ is a closed subspace of $H_1$, it's a Banach space. This gives, by the open mapping theorem that $T$ is open. It's also compact, so $T(B(0,1))$ is open and has compact closure. By Riesz theorem, $H_2$ is finite dimensional.
But for each $N$, we can find $N+1$ disjoint subsets of $S$ which have positive measure, and their characteristic functions will be linearly independent, which gives a contradiction.

I'm interested in the part in bold.  My question is, why does the fact that $T(B_1)$ is open and its closure is compact imply that $H_2$ is finite-dimensional?  The answer cites Riesz's theorem, but that theorem just says that a Banach space whose closed unit ball is compact must finite dimensional.  Why does the fact that the closure of the image of the open unit ball under $T$ is compact imply that the closure of the open unit ball is compact?
Or is there a mistake in this proof?
Answer: $T(B(0,1))$ contains some open ball $B(0,r)$ around $0$ in $H_2$ (because it is open and contains $0$). So the closure of $B(0,r)$ is contained in the closure of $T(B(0,1))$ which is compact since $T$ is a compact operator. If a closed ball around $0$ in $H_2$ is compact then $H_2$ is finite dimensional.


What is the relation between the eigenspace of a matrix and its column space?

Question: I was wondering if there is any relation between the space span by all eigenvector of a matrix $A$ and its column space.
Also, is there any condition on $A$ that ensures that these two spaces are the same?
Comment: In general, no relation. If $A=\pmatrix{1&1\cr0&1\cr}$ then the column space is bigger. If $A=\pmatrix{0&0\cr0&0\cr}$ then the eigenvectors span the bigger space.
Comment: @GerryMyerson, for what it's worth I vote for making that an answer.
Answer: To add a bit to Gerry's answer...
If you look at a matrix as a linear operator, $T(v)=Av$ then the column space is just the range of that linear operator. Eigenvectors for non-zero eigenvalues will be members of the range (if $Av=\lambda v$, then $A(\lambda^{-1}v) = v$).
So the span of the eigenvectors with non-zero eigenvalues, is contained in the column space.
(...and the span of the eignevectors with eigenvalue zero is the null space.)
Answer: [Comment elevated to answer]
In general, there is no relation between the two spaces.
For example, if $$A=\pmatrix{1&1\cr0&1}$$ then the column space is all of ${\bf R}^2$ while the eigenvectors span a 1-dimensional subspace.
If $$A=\pmatrix{0&0\cr0&0\cr}$$ then the eigenvectors span all of ${\bf R}^2$ while the column space is just the zero vector.
If $A$ is invertible and diagonalizable, then the two spaces will both be all of ${\bf R}^n$. I expect there are other examples of equality.
EDIT: Here's another example of equality: $$A=\pmatrix{2&-4\cr1&-2\cr}$$ The vector $(2,1)$ generates the column space, and also generates all the eigenvectors.
Answer:
is there any condition on A so that these two spaces are the same

Yes.  Over a field $F$ of scalars, the condition is that

all eigenvalues of $A$ belong to $F$ (all irreducible factors of the characteristic polynomial are linear)
Every element of the $0$-eigenspace, is in the image of $A$ (there is a direct sum decomposition of the generalized $0$-eigenspace into $2 \times 2$ examples like the one in Gerry Myerson's answer)
every generalized eigenvector with nonzero eigenvalue is an eigenvector (if $\lambda \neq 0$ is a root of multiplicity $m$ in the characteristic polynomial, the $\lambda$ eigenspace of $A$ has dimension $m$)
Comment: What about conditions for the space spanned by all eigenvectors of a matrix $A$ associated to nonzero eigenvalues to be the same as the column space of $A$? I've just bumped into this answer after posting this question math.stackexchange.com/questions/776896/…
Comment: I did not see an answer immediately, and it will be some time before I can think about it, but I might have another look in a week or two (feel free to remind me with another message if you don't hear anything by then).
Comment: many thanks any help would be greatly appreciated
Answer: Let me point out the situation for the special case where A is symmetric positive definite:

If a matrix A $\in \mathbb{R}^{n \times n}$ is symmetric positive definite, then it diagonalizable, as the Schur transform gives a diagonal matrix.
Thus, the algebraic multiplicity equals the geometric multiplicity for every eigenvalue.
As the eigenvectors of Hermitian matrices are orthogonal to each other, we know that the dimension of the span of the eigenvectors is equal to the sum of the geometric multiplicities over the different eigenvalues which is $n$.

Thus, the eigenvectors span $\mathbb{R}^n$ in this special case.
Comment: Positive definite not necessary. Every symmetric matrix is diagonalizable, so its eigenvectors span ${\bf R}^n$.


Radio button in rails

Question: I am new to rails (and non ASP.NET web development). For creating a user signup page with a radio button, I'm doing the following. However the user.roles is not updated. What could be the problem?
(I edited the user model created by sorcery gem to add a new string field roles.)
view/users/new.html.erb
<%= form_for @user do |f| %>
     ..

        <%= radio_button_tag(:assistanttype, "TA") %>
        <%= label_tag("TA") %>
        <%= radio_button_tag(:assistanttype, "RA") %>
        <%= label_tag("RA") %>

Answer: Try changing the code to:
<%= form_for @user do |f| %>
 ..

    <% %w{TA RA}.each do |value|-%>
    <% f.radio_button :assistanttype, value %> <% value %>

    <% end -%>

%w{} is used to put string inside and automatically change it to an array.
Example:
%w{A B C} = [A, B, C]
Comment: im sorry the <%end %> was part of an if, i forgot to add here.
Comment: syntax error, unexpected tCONSTANT, expecting keyword_do or '{' or '('
Comment: It should be %w{} not  w%{}. Sorry my bad.

Radio button in rails


Dúvida sobre o método reduce em JavaScript

Question: Peguei esse pequeno código de um material da internet para imprimir quantas vezes um numero se repete no array, porém não consegui entender direito o que foi feito, principalmente com esse if e com o acumulado[atual].
Quem puder me explicar melhor esse trecho de código agradeço e positivo a resposta.
const numeros = [7, 61, 36, 2, 17, 61, 114, 20, 2, 17, 7, 61]
const quantasVezesRepetiu = (acumulado, atual) => {
  if(!acumulado[atual]){
    acumulado[atual] = 0
  }
  acumulado[atual] += 1
  return acumulado
}
const vezes = numeros.reduce(quantasVezesRepetiu, {})
console.log(vezes)

Comment: O codico está errado, a variável `numero` não foi definida.
Comment: Na verdade o código está certo, @MariaEduarda...
Comment: @MariaEduarda ja editei, tinha feito a publicação sem o array
Answer: Devemos entender, primeiramente, que o Array.prototype.reduce trabalha sobre um array. No caso, o array que será reduzido é o próprio array sob o qual chamamos o método reduce. Além do array (que é o "argumento" this), reduce requer uma função redutora e aceita um valor inicial.
No exemplo que tratamso nesta resposta, chamamos reduce assim:

const result = [1, 2, 3, 1, 2, 1].reduce(countReducer, {});

Então:

O array a ser reduzido será [1, 2, 3, 1, 2, 1] ("argumento" this).
A função redutora é countReducer (primeiro argumento do método).
O valor inicial é {} (segundo argumento do método).

Com isso, para cada elemento do array [1, 2, 3, 1, 2, 1], a função redutora que passarmos será chamada. O truque para "entender" é saber que o valor que a função redutora retornar será utilizado como o parâmetro accumulator para a iteração seguinte. Por isso é importante definir um acumulador inicial na maioria dos casos.

Leia a documentação, que tem um exemplo explicando passo a passo.

É importante observar que se você não definir acumulador inicial, o primeiro elemento do array será utilizado como tal. No entanto, nessa situação, de acordo com a lógica do que queremos fazer, isso não é desejável.

Indo, agora, ao código completo, temos:

function countReducer(accumulator, current) {
  // Caso o item da iteração atual ainda não tenha sido contabilizado.
  if (!accumulator[current]) {
    // Inicializamos o contador para o item da iteração atual como 0:
    accumulator[current] = 0;
  }

  // Incrementamos o contador para o item da iteração atual:
  accumulator[current] += 1;

  // Retornamos o acumulador para as próximas iterações:
  return accumulator;
}

const result = [1, 2, 3, 1, 2, 1].reduce(countReducer, {});
console.log(result);

1  | function countReducer(accumulator, current) {
2  |   // Caso o item da iteração atual ainda não tenha sido contabilizado.
3  |   if (!accumulator[current]) {
4  |     // Inicializamos o contador para o item da iteração atual como 0:
5  |     accumulator[current] = 0;
6  |   }
7  |
8  |   // Incrementamos o contador para o item da iteração atual:
9  |   accumulator[current] += 1;
10 |
11 |   // Retornamos o acumulador para as próximas iterações:
12 |   return accumulator;
13 | }
14 |
////                                                        ↓↓
15 | const result = [1, 2, 3, 1, 2, 1].reduce(countReducer, {});
16 | console.log(result);

Vamos entender o que queremos que aconteça para depois entender o código acima, linha a linha.
Supondo que temos um array como [1, 2, 3, 1, 2, 1], queremos retornar um objeto com a quantidade de cada elemento do array, assim:
{
  1: 3,
  2: 2,
  3: 1
}

E como o reduce nos ajudará a chegar nisso?
Partindo da primeira linha a ser executada (15), onde invocamos o método reduce, note que passamos, como valor inicial, um objeto literal "vazio" ({}). Esse é o nosso objeto accumulator, só que ele ainda se encontra "vazio"!
A partir disso, o reduce chamará a função countReducer para cada elemento do array. De modo que o parâmetro accumulator será dado pelo que a função countReducer retornar na iteração anterior (exceto na primeira iteração, na qual accumulator é o objeto vazio que definimos no segundo argumento do método).
Partindo da primeira iteração (na qual {} ainda está vazio), precisamos ir adicionando os elementos com as respectivas contagens. Para isso, utilizamos a notação accumulator[current]. Essa é a notação de colchetes para acesso em objetos no JavaScript.
No caso específico da primeira iteração, por exemplo, o accumulator ainda estará vazio. Nesse caso, como current corresponde ao primeiro elemento do array, o que estamos fazendo é, isto:
accumulator[current]

É o mesmo que:
accumulator[1]

Isso significa que estamos tentando acessar a propriedade 1 no objeto accumulator. No caso da primeira iteração, essa propriedade ainda não estará definida, portanto, a expressão accumulator[current] (na primeira iteração) retornará undefined.
Nesse caso, como o contador ainda não foi definido, precisamos criar um jeito de definir o contador como 0 para que possamos iniciar a contagem para o elemento em questão. É isso que o if (linhas 3~6) está fazendo. Ele verifica se o contador referente ao elemento (current) atual ainda não foi definido e, se realmente não tiver sido definido, seta o contador do elemento atual para 0.
Desse modo, na linha 9 podemos incrementar a contagem referente ao elemento atual. Novamente temos a expressão accumulator[current], que, basicamente, significa:

Acesse, no acumulador, a propriedade cuja chave é (dinamicamente) current e incremente 1, indicando que percorremos esse item uma vez.

Essa mesma lógica é processada para cada elemento do array.
Comment: Luiz, muito obrigado pela resposta, esclareceu algumas coisas, mas essa expressão 'accumulator[current]' ainda está confusa para mim, ainda não consegui entender qual valor essa expressão está pegando, e essa na verdade era minha principal duvida.
Comment: @danielhcr22, tentei editar a parte final da resposta para explicar um pouco melhor. Agora deu para entender? :-)
Comment: Luiz, agradeço a sua resposta, mas vou levar um tempo ainda para assimilar isso, lendo sua resposta e mais alguns outros materiais percebi que ainda me resta algumas duvidas sobre objetos, vou rever esse assunto melhor e retornar aqui para ler sua resposta, assim ficará bem mais fluido o entendimento, obrigado!


Simple getJson causing me major headaches

Question: I'm trying to grab some data from facebook, and since it is a pretty huge amount of requests I've created a php file that will output to a nice .html file once a day. the data comes back from facebook as json so I'm doing my best to maintain that, but I'm having trouble getting any values back after retrieving the valid JSON.
simplified code looks like this:
    var graphURL = "http://www.explorevictoria.dreamhosters.com/csv/graphdata.html";

    jQuery.getJSON(graphURL, function(data){
       $.each(data.item, function(){
           alert(this.id);
        })

    });

I keep getting a mix of undefined, null, or broken javascript. So I turn to you oh stack overflow gurus. Is there a fundamental flaw in my procedure?
Comment: interestingly, as an interim measure I fetched the data through yahoo pipes and rendered it as a json feed and now it works, so perhaps it is what getJSON thinks it getting(html vs json header)?
Answer: Short answer, your json is invalid. http://www.explorevictoria.dreamhosters.com/csv/graphdata.html just scroll down and you'll see text which is clearly just some loose html.
"item":

<TITLE>400 Bad Request</TITLE>

Method Not Implemented

Invalid method in request

, "item":
<TITLE>400 Bad Request</TITLE>

Method Not Implemented

Invalid method in request

Comment: I noticed that while I was working on it yesterday and got rid of that problem. What you are saying is, my method is sound, I just need to use valid json and it should work?


setting the cookie header with the value of anouther header in an nginx reverse proxy

Question: We are working with a piece of hardware(chromecast) that seems to be stripping out cookies, but will happily pass along a custom header (which we signal is acceptable from the back end) one workaround we came up to stuff the cookie data into said custom header and put it back into the cookie header on the proxy.  This allows most clients (which respect normal CORS signaling) and the backend to remain unchanged.  In my Nginx config I currently have a map defined like:
map cookie $cookie {
    default   $http_cookie;
    ""        $http_my_token;
}

which I'm later using as follows:
server {
  listen 443 ssl;
  #...
  location /myurl {
      proxy_pass http://nodeserver;
      proxy_set_header X-Forwarded-For $remote_addr;
      #...
      proxy_set_header Cookie $cookie;
 }
}

I expect this code to replace the Cookie header with the value supplied in the "My-Token" header, but what I see instead is that the value of both headers is passed through unchanged.
Answer: Your map specifies that the value you want to check is the literal string cookie. This is not what you said you want, and it's pretty useless to try to check a literal string since it can only be itself.
The first parameter to map is the value you want to test. Instead of the string cookie you should pass what you actually want to check. It seems you are looking for whether the user agent is sending a cookie. If that's the case, you should use $http_cookie.
map $http_cookie $cookie {


Importing excel xlsx data using XLconnect and readWorksheet causes incorrect format

Question: I have a Excel file with the extension xlsx where Sheet1 and Sheet contains the following: 18:20, 10:10 (column A, row 1:2). When I try to import them into R I do not get expected results.
library(XLConnect)

setwd("...")
my_book <- loadWorkbook("test.xlsx")

xlsx_import <- lapply(getSheets(my_book), readWorksheet, object = my_book)
xlsx_import

# Returns some kind of date format

xlsx_import <- lapply(getSheets(my_book), readWorksheet, object = my_book, colTypes = "character")
xlsx_import

# Same as above

Is it possible to fix  this in R somehow? As I have quite a lot of sheets to go through.
Comment: I would guess the problem is that Excel is thinking that these cells are times, so it will export them in date/time format. If they are held in Excel as dates, then your best option might be to import them into R as you are doing, and then try to extract the data, rather than doing it via `readWorksheet` options.
Comment: After you import the data, try something like this `df$problem.column <- format(df$problem.column, format = "%H:%M")`
Comment: did not work...
Answer: Try This.

wb=loadWorkbook("Test.xlsx", create = TRUE)

setStyleAction(wb, XLC$"STYLE_ACTION.DATATYPE")
cs = createCellStyle(wb, name = "myDateStyle")
setDataFormat(cs, format = "dd-mm-yyyy")
setCellStyleForType(wb, style = cs, type = XLC$"DATA_TYPE.DATETIME")

s<-readWorksheet(wb,sheet = "Sheet1")

***Operations which you wanna do***

writeWorksheet(wb, wq, sheet = "Sheet1")
setForceFormulaRecalculation(wb,"*",TRUE)
saveWorkbook(wb)

Comment: Some additional information about this code only answer would probably be beneficial.


How can I build a single file .ts to my src? by setting up the tsconfig.js (command yarn build)

Question:   {
    "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "declaration": true,
    "rootDirs": [
      "./components",
      "./pages",
      "./public",
      "./styles",
      "./utils",
      "./types",
      "./services"
    ],
    "outDir": "./src",
    },
    "include": [
     "next-env.d.ts",
     "**/*.ts",
     "**/*.tsx"
    ],
    "exclude": [
     "node_modules",
     "lib"
    ],
    "types": [
     "cypress",
     "@percy/cypress"
    ]
    },

I want to make this project a library that will embed the intercom button on any website. My senior suggested I build a single .ts file that includes all of my code in the src folder through yarn build, but I am still unable to do so. This project is written using NextJS and Typescript. Any suggestion? The following is the sample directory of the project.
project
| components
  | component 1
    | some .ts & .tsx files // including styles.ts file and index.ts
  | component 2
    | same structure as comp 1
  | index.ts // for exporting
| pages
  | API
    | some .ts files
  | _app.tsx & other .tsx files
| public
  | font
  | some icons & image folder
| service
  | folder
    | config.ts
| styles
  | theme.ts, styles.ts, .css
| types
  | some .d.ts & .ts & folder
| utils
  | some .ts & folder that contained functions used in this project.
| src

Answer: You might follow T3's documentation about their folder structure. Basically, the src folder contains all other folders such as pages, styles, utils , ...
.
├─ public
│  └─ favicon.ico
├─ prisma
│  └─ schema.prisma
├─ src
│  ├─ env.mjs
│  ├─ pages
│  │  ├─ _app.tsx
│  │  ├─ api
│  │  │  ├─ auth
│  │  │  │  └─ [...nextauth].ts
│  │  │  └─ trpc
│  │  │     └─ [trpc].ts
│  │  └─ index.tsx
│  ├─ server
│  │  ├─ auth.ts
│  │  ├─ db.ts
│  │  └─ api
│  │     ├─ routers
│  │     │  └─ example.ts
│  │     ├─ trpc.ts
│  │     └─ root.ts
│  ├─ styles
│  │  └─ globals.css
│  └─ utils
│     └─ api.ts
├─ .env
├─ .env.example
├─ .eslintrc.cjs
├─ .gitignore
├─ next-env.d.ts
├─ next.config.mjs
├─ package.json
├─ postcss.config.cjs
├─ prettier.config.cjs
├─ README.md
├─ tailwind.config.ts
└─ tsconfig.json

More information here: https://create.t3.gg/en/folder-structure
Upvote would be highly appreciated if you found this helpful! Thanks!!


How do I create a new variable from the result of a for loop with an if else statement in it in python?

Question: I have these temperatures:
temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

This works as a statement, but I can't get this in to a variable:
for i in temperatures:
if i < -2:
    print('Cold')
elif i >= -2 and i <= 2:
    print('Slippery')
elif i >2 and i < 15:
    print('Comfortable')
else:
    print('Warm')

I know that the following code works to get a variable from a loop:
x = [i for i in range(21)]
print (x)

So I tried this, but it doesn't work:
temp_class = [i for i in temperatures:
if i < -2:
    print('Cold')
elif i >= -2 and i <= 2:
    print('Slippery')
elif i >2 and i < 15:
    print('Comfortable')
else:
    print('Warm')]

But get this error:
File "", line 1
    temp_class = [i for i in temperatures:
                                         ^
    SyntaxError: invalid syntax
What would be the correct code to:
1. Get a variable from my statement
2. Get both the temperatures and classes in a table similar to a tibble or data.frame in R.
Thanks
Comment: There is something strange with your code, if you enter `-2`, as temperature, it will print `'Warm'` :)
Comment: Thanks @WillemVanOnsem, I have changed that now.
Comment: Actually, there is still something strange with it I think. I will work on that. But do you have any tips on creating the variables?
Comment: Your `for` loop only prints text, so what do you want to assign to `temp_class`?
Comment: you can use https://docs.python.org/2/library/functions.html#map
Comment: Yes @UnholySheep, I would like to assign the result of the loop to temp_class.
Answer: If you goal is to get these strings into temp_class just append them instead of print
temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

temp_class = []

for i in temperatures:
    if i < -2:
        temp_class.append('Cold')
    elif i >= -2 and i <= 2:
        temp_class.append('Slippery')
    elif i >2 and i < 15:
        temp_class.append('Comfortable')
    else:
        temp_class.append('Warm')

print(temp_class)
# ['Cold', 'Slippery', 'Slippery', 'Cold', 'Comfortable', 'Slippery', 'Cold']

Answer: You can create a function and use it in your list comprehension:
temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

def feeling(temp):
    if temp < -2:
        return 'Cold'
    elif -2 < temp <= 2:
        return 'Slippery'
    elif 2 < temp < 15:
        return 'Comfortable'
    else:
        return 'Warm'

[feeling(temp) for temp in temperatures]
# ['Cold', 'Slippery', 'Slippery', 'Cold', 'Comfortable', 'Slippery', 'Cold']

Answer: Using map()
temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

def get_temp_class(i):
    if i < -2:
        return 'Cold'
    elif i >= -2 and i <= 2:
        return 'Slippery'
    elif i >2 and i < 15:
        return 'Comfortable'
    else:
        return 'Warm'

temp_class = map(get_temp_class, temperatures)


Nested class vs implements ActionListener

Question: Are there any benefits or drawbacks to creating a nested class that implements ActionListener:
public class Foo{
    Foo(){
        something.addActionListener(new ButtonListener());
    }
    //...
    private class ButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            //...
        }
    }
}

versus implementing ActionListener in the main class itself:
public class Foo implements ActionListener{
    Foo(){
        something.addActionListener(this);
    }
    //...
    public void actionPerformed(ActionEvent e){
        //...
    }
}

I've seen both examples quite often, and just want to know if there's a 'best practice.'
Comment: See also [Advantages to Nested Classes](http://stackoverflow.com/questions/5085157).
Answer: @Ankur, you can still use anonymous inner classes as your listeners and have a separate free-standing control class and thus have code that's quite maintainable, a technique I like to use a bit.  For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AnonymousInnerEg {
   private static void createAndShowUI() {
      GuiPanel guiPanel = new GuiPanel();
      GuiControl guiControl = new GuiControl();
      guiPanel.setGuiControl(guiControl);

      JFrame frame = new JFrame("AnonymousInnerEg");
      frame.getContentPane().add(guiPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class GuiPanel extends JPanel {
   private GuiControl control;

   public GuiPanel() {
      JButton startButton = new JButton("Start");
      startButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (control != null) {
               control.startButtonActionPerformed(e);
            }
         }
      });
      JButton endButton = new JButton("End");
      endButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (control != null) {
               control.endButtonActionPerformed(e);
            }
         }
      });

      add(startButton);
      add(endButton);
   }

   public void setGuiControl(GuiControl control) {
      this.control = control;
   }

}

class GuiControl {
   public void startButtonActionPerformed(ActionEvent ae) {
      System.out.println("start button pushed");
   }

   public void endButtonActionPerformed(ActionEvent ae) {
      System.out.println("end button pushed");
   }
}

Answer: I think first approach is better, as your class will have a separate code for handling action. And usually also composition is better than inheritance so a class should extend a class or implement a interface only if it truly is-a super type.
Also for maintainability, let us say Foo class has a new requirement to listen for another different type of events and then perform action, in that case also first class can be easily modified.
If I am not worried about maintainability I would rather go for a anonymous class.
Comment: please see reply as an answer
Answer: If the class Foo has no other responsibility than encapsulating this button, then the first solution is sort of ok.
However, as soon as Foo gets more "somethings" that it has to listen to then it gets messy. I prefer the second solution since it is more explicit and has a better scalability.
An even better solution may be to create an anomymous inner class.
public class Foo{
    Foo(){
        something.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                //...
            }
        });
    }
}

Answer: Usually you want to use a nested or even anonymous class rather than exposing ActionListener to the API of the enclosing class. (public class Foo implements ActionListener -> Javadoc will state that Foo is an ActionListener, though this is usually just an implementation detail -> bad)


Proper Use of Quantifier _ \forall($\forall$) \for each \for every

Question: In our natural language \forall\forevery\foreach are pretty much well discernable for me. However, in mathematical description I always confusing whether we actually needs all these 3 of them.
Question is,
$1$. Do mathematician need above three all?
$1-1$. If so, what kind of difference do they hold for which functional use?
Comment: You may want to look up something called 'universal instantiation'
Comment: The only real problem is with "for any", which depending on the context can be read as "for every", "for some", or *both*. (I advocate avoiding it as much as possible.)
Comment: I prefer both of two answers below.
Comment: @MathematicsStudent1122 https://en.wikipedia.org/wiki/Universal_instantiation
Answer: These statements are equivalent, and any confusion is arising as more of an English issue, then a logic issue. $\forall$ is the universal quantifier. It is stated, in English, generally as "for all," but this is just an English phrase for the universal quantifier. The phrases "for each" and "for every" are less common, but still valid ways of prononcing $\forall$ that sometimes are motivated by context.
Consider: $\forall_i \in \mathbb{R}$ in English, it would by odd to pronounce the universal quantifier as "for each" or "for every." "For each /every Real number" implies a sort of discrete aspect that is not a part of the Real numbers. Saying "for all", captures the continuous nature of the set in English more readily.
Consider: $\forall_x \in A = \text{{x|x $\in \mathbb{N} \land x \lt 10$}}$ in this case all of the English pronunciations of the universal quantifier make sense, this is a finite discrete set, so "each element," "every element," and "all elements" convey the correct idea in English.
Again though, this is interjecting confusion from the world of English that ideally does not exist because of the clarity of symbols like $\forall$. How you pronounce this symbol is ultimately meaningless, the symbol notes that some propositional function is satisfied by every member of a domain of discourse.
Comment: I thought they were equivalent and there is really no difference. Finally it has been confirmed. Thanks @Scott.
Answer: The short answer: the phrases "for each", "for every" and "for all" all mean exactly the same thing.


How do i approach finding the number of equivalence classes of a relation?

Question: (Question too long to post as title) The question is, Let S = {1,2,3,4,5,6,7,8,9} and let T = {2,4,6,8}. Let R be the relation on P(S) defined by for all X, Y ∈ P (S), (X, Y ) ∈ R if and only if |X − T| = |Y − T| and i have to find the number of equivalence classes. I had to initially prove it was an equivalence relation which i dont think i had trouble with but i'm struggling to understand how to approach solving this? I looked up what an equivalence class is again and it makes sense when it was such a simple example like for instance when a set of the relation was given to me and all i had to do was check for each x in the original set which other x did it have a relation with and then find the distinct relations. However, i am struggling to understand how to apply it here to such a larger scale and more complex problem.
In this case two elements or subsets of S in P(S) are related if the elements in X and not T give a cardinality equal to the elements in Y and not T? is this the correct understanding? Then to find the number of equivalence classes i have to do what? I dont really get how to start the process any help is appreciated thank you!
Could someone perhaps explain what an equivalence class would mean in this case?
Answer: Hint:  for any subset $X, |X-T|$ is the number of odd elements of $X$.  How many choices are there among the subsets of $S$ for the number of odd elements?
Comment: True there are $5$ odd numbers, but there are $6$ choices because you could have none.
Comment: That is right because of the definition in terms of the size of the set.  You segregate all the elements of $P(S)$ by the number of odd elements, which gives us six piles.  Once you see that, the proof that it is an equivalence relation and each pile is an equivalence class is easy.
Comment: $\{1,2,3,4\}$ has two odd elements, so it is in the class of subsets with two odd elements.  Any other subset with exactly two odd elements is related to it.  You choose any two odd numbers and any combination of even numbers to make one.  There are ${5 \choose 2}=10$ choices for the pair of odd numbers and $2^4$ choices for the even numbers, so $160$ subsets in the class of two odd numbers.
Comment: Okay so there are 5 different choices since there are 5 odd numbers
Comment: Wait thats it? I am so confused that makes sense but could you explain how that is an equivalence class? Oh wait is each equivalence class would be like an equivalence class with only 1 odd number another with only 2 etc until 5 and then like you said a class with none. In this case the types of odd numbers is not important like the amount of odd numbers is? Why
Comment: Okay i guess that makes sense but if i was asked like for an equivelance class of the empty set or for instance the equivalence class of {1,2,3,4} how would i be able to find the number of elements in that class? If we just established that there are 6 different equivalence sets each with a different number of odd numbers then where does the empty set fall or {1,2,3,4} fall, like 1,2,3,4 has 2 odd numbers does that mean it falls in the equivalence class with 2 odd numbers? If it does i have to take into account the actual numbers now?
Comment: Or like for {1,2,3,4} am i finding how many subsets of S,Y have a cardinality of 2? But that would mean y would be anything with atleast 2 things not in common with T so i guess i'm confused by how we defined the 6 equivalence classes but now we are asked a specific equivalence class and how does that connect to the other 6 we defined
Comment: Wait what? {1,2,3,4} falls under one of the 6 predefined equivalence classes [2] where it needs to have 2 odd numbers right? I dont understand what Y is either, X and Y are related if the cardinality of X and not T is equal to cardinality of Y and not T. Am i not trying to find the number of subsets, Y that make fall under equivelance class [2]?
Comment: Yeah thats what i got for that one thanks a lot, i understand it and you've helped a lot, i'm just worried i'm not sure if i understand equivalence classes very well as a general concept. In this specific example where they are defined by cardinality i got it now. So as a general idea, equivalence classes is just dividing the possible elements of a relation based on a shared thing like in this case # odd numbers and then we can find elements in a specific equivalence class by relating back to which one of the major equivalence class it falls into and then we count, right?
Comment: Yes.  Because equivalence relations are transitive, any chain of related elements are all related to each other.  It means they separate the set into disjoint subsets.  In problems like this you need to find the unifying idea behind those subsets.


Traveling or moving neck bow

Question: This is very strange. I have a Godin Icon which I love. This month I have noticed a neck bow that I can't straighten itch the truss rod. The problem is that this bow seems to move up and down the neck. It starts out between the tenth and twelvth frets and moves between the 7th and 10nth fret, eventually going to between the 5th and seventh fret. If I watch carefully, I can actually see it move. It's almost as though the neck is having spasms. I have tied loosening the rod leaving it for a day and then tightening it the opposite way for a day. I'm trying to release the seemingly stored tension in the neck to no avail. I changed the strings to see what effect that might have but the problem continues. It has been unusually cold and dry this Winter and I'm thinking this could the cause. I have the guitar next to a humidifier to try and rehydrate it.
Has anyone experienced this phenomena with a guitar?
Comment: Contact the Godin company customer service department and ask about authorized repair work and whether or not it is covered by their warranty.
Comment: Hi there! I don't think we can give a more proper answer than "visit a guitar repairer". Note that StackExchange is not a forum, so you shouldn't expect people hitting you with random ideas of what could be the issues and how to try to get around them.
Comment: You can only release tension by loosening the rod; tightening it back is adding all the tension back.  There's no magic tension originating from the ether that can be released like letting pressurized air out of a can :P.
Comment: The tightening and loosening of the truss rod could account for the movement in the location of the bow.  The neck does not always fully react immediately to a truss rod adjustment.  During re-hydration you might want to loosen the truss rod for a few days by turning it counter clockwise.  Remember, the truss rod is designed to counteract the tension of the strings.  So you have strings pulling one way and truss rod pulling the other way.  I would loosen everything during re-hydration.
Comment: I confirmed my suspicion that your guitar might have a double action truss rod via the Godin Website, thus you can't exactly "loosen" the truss rod.  For more on this see my detailed answer below.
Answer: What you are describing is rather unusual with a neck bow moving up and down the neck.  Keep in mind that the truss rod and strings both put tension on the neck - theoretically in opposite directions.  But see below because your Godin may have a truss rod that can defy the opposing tension theory and possibly account for this unusual behavior.
From what you have shared - two things come to my mind.  It is likely that your guitar has been subjected to an environment with low relative humidity (common during winter heating season) which often will cause a bow in the neck due to drying of the wood.
The other thing to be aware of is that according to the Godin website, all Godin guitar necks are equipped with a DOUBLE Action truss rod.  Most guitars have a single action truss rod which counteracts the string tension to lessen the bow (or relief) that is caused by the string tension.  Loosening a one way truss rod will relax the neck and allow it to bow under string tension but will not cause it to bow in the absence of tension.
A two way adjustable truss rod (or double action) like the ones found on Godin guitars and a few others actually will bow the neck if turned one way and bow the neck in the opposite direction if turned the other way.  So you might say you can "tighten it" in BOTH directions.  One direction causing a bow, the other direction causing a back bow - with or without string tension.
This could account for your observation of a bow showing up in different places after turning the truss rod in alternate directions.  It is also important to understand that the guitar's reaction to a truss rod adjustment may be gradual and the neck may continue to respond for a period of time after the adjustment is made.
Here is a picture of how the Godin double action truss rod works from the Godin webstite Double Action Truss Rod - Godin guitars
Before doing anything else - if your guitar is under warranty, you may be able to take it to an authorized Godin repair tech and have them repair it under warranty.  My Taylor guitars have a lifetime warranty to the original owner.   Or even if it isn't under warranty please make a phone call to Godin to see if they will offer support over the phone.
If you are unable to get any support from Godin - you can take your guitar to a local recommended guitar repair technician or luthier whom you can trust - or you can follow my recommendations below.
You are probably doing the right thing by re-hydrating your guitar.  Shoot for about 55-60% relative humidity during the re-hydrating (re-humidification) process and once stabilized, try to maintain around 50% if you can.
While re-hydrating your guitar, I would loosen the strings and then adjust your truss rod until the neck is straight with no string tension.  Use the chart in the link to determine which way to turn the truss rod to achieve this.  Remember, don't turn too much in either direction because the double action truss rod will actually exert tension on the neck in both directions.
During the re-hydrating process you will probably notice some movement in the neck as the wood absorbs moisture.  After a few days of re-hydration your guitar should stabilize and the neck should stop moving.  Once you are sure your guitar is fully re-hydrated - add tension back to the strings and adjust the truss rod to provide the desired amount of relief and hopefully you will be back in business.
To those who might fear that relieving string tension will hurt your neck - that is a myth and totally without merit.  I have four friends who are luthiers (build and repair guitars).  They often have guitars in their shop where the strings are off the necks for a week or more.  How else would you do a re-fret? If you are skeptical about this - call or visit any luthier.
Good luck!

Traveling or moving neck bow


How to check in rails uploaded file type?

Question: How can i see what type of file is comming?
For example, csv or xls...
Give code please...
I get file so:
aut_name = uploaded_io.original_filename
      File.open(Rails.root.join('public', 'uploads_prices', uploaded_io.original_filename), 'wb') do |file|
        file.write(uploaded_io.read)
      end
      as_load(aut_name)

Maybe by MIMO, but how?
Answer: uploaded_io.content_type contains the MIME type of file.
So:
uploaded_io.content_type == "text/csv"
Comment: and how to check it? like: if uploaded_io.content_type == "csv"? or what
Comment: is this correct for xls? .content_type == "application/vnd.ms-excel"
Answer: Unfortunately, it (content_type method) is not going to work if a user changes file extension. I've tested that in rails console and the changing the file extension also changes "content_type" output.
Found this SO question quite helpful:
Determine file type in Ruby


Hibernate 4 + org.hibernate.MappingException: Unknown entity

Question: I am using Spring MVC 3 and Hibernate 4
Below is code to perform DAO operations
@Repository("headCategoryDao")
@Transactional
public class HeadCategoryDaoImpl extends CustomHibernateDaoSupport<HeadCategory, Integer> implements HeadCategoryDao {

    @Override
    public void delete(HeadCategory headCategory)  throws InstanceNotFoundException {
        getHibernateTemplate().delete(headCategory);
    }

    @Override
    public HeadCategory findHeadCategoryByName(String headCategoryName) throws InstanceNotFoundException {
        List list = getHibernateTemplate().createCriteria("from HeadCategory where headCategoryName="+headCategoryName).list();
        if(list.isEmpty()) {
            throw new InstanceNotFoundException("HeadCategory not found for provided headCategoryName");
        }
        return (HeadCategory) list.get(0);
    }

    @Override
    public List<HeadCategory> getHeadCategoriesByMainType(WealthConstants.ACCOUNT_TYPE mainCategoryType)  {
        List list = getHibernateTemplate().createCriteria("from HeadCategory where mainCategoryType="+ mainCategoryType).list();
        return list;
    }
}

findHeadCategoryByName method is called throws below exception, what can be issue ?
nested exception is org.hibernate.MappingException: Unknown entity: from HeadCategory where headCategoryName=Cash In Hand] with root cause
org.hibernate.MappingException: Unknown entity: from HeadCategory where headCategoryName=Cash In Hand
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1131)
    at org.hibernate.internal.SessionImpl.getOuterJoinLoadable(SessionImpl.java:1737)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1642)
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
    at com.wms.dao.impl.common.HeadCategoryDaoImpl.findHeadCategoryByName(HeadCategoryDaoImpl.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy35.findHeadCategoryByName(Unknown Source)
    at com.wms.service.impl.common.HeadCategoryServiceImpl.findHeadCategoryByName(HeadCategoryServiceImpl.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy36.findHeadCategoryByName(Unknown Source)
    at com.wms.web.helper.ScriptHelper.headsScript(ScriptHelper.java:282)
    at com.wms.web.helper.ScriptHelper.initialDataScriptExecution(ScriptHelper.java:130)
    at com.wms.web.controller.StaticController.buildDataUsingScript(StaticController.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)

Answer: Look at the query:
from HeadCategory where headCategoryName=Cash In Hand

That's not a valid query at all. What is Cash? What is Hand? A correct query would be
from HeadCategory where headCategoryName='Cash In Hand'

Learn to pass parameters correctly and safely to queries:
session.createQuery("from HeadCategory where headCategoryName = :name")
       .setString("name", headCategoryName)
       .list();


use Firestore model value as toggle to present fullscreen view in SwiftUI

Question: I have two screens in a SwiftUI app.
Screen A is displayed after the app launch and contains a button which will update the value for currentWorkoutID on the user model and save that modification to a Firestore database.
Screen B is shown from screen A when currentWorkoutID is not nil on the user model.
The problem that I'm seeing is that when I press the button in screen A, screen B immediately shows up (no animation), then is dismissed with animation and then is shown again with no animation.
I'm unsure what the issue is or how to solve it.

struct TrainingProgramDetails: View{
    @EnvironmentObject var workoutCompletionStore: WorkoutCompletionDataStore
    var presentWorkoutScreenBinding: Binding<Bool> {
        Binding(get: {
            return userDataStore.user.profileData.currentWorkoutID != nil
        },
                set: { value in
            //nothing to do here
        })
    }

    var body: some View {

        let nextWorkoutID = userDataStore.user.profileData.currentWorkoutID

        GeometryReader { screenGeometryProxy in
            let imageHeight = screenGeometryProxy.size.height / 3
            WorkoutsList(workouts: program.workoutsData) {
                ...
            }
            .fullScreenCover(isPresented: presentWorkoutScreenBinding,
                             onDismiss: {
                             }, content: {
                                 WorkoutScreenAdaptor(workoutID: nextWorkoutID!,
                                                      onShowFeedback: showFeedback)
                             })
        }
        .edgesIgnoringSafeArea(.top)
}

struct User: Codable {
    var profileData: ProfileData = .init()
    ...
}

struct ProfileData: Codable {
    var currentWorkoutID:String?
    ...
}

Answer: Turns out the problem was on a container to this screen that would cause this screen to be taken out of view and then reloaded.


Is this slide/shift slide?

Question: I found this in a riff, but I don't know the meaning of (sl). I suspect it means slide, however, the slide symbol is / or \.

g--(sl)----(sl)----7----

Could someone clarify this, please? And why there are two?
The complete riff. The song is Walk Of Life.

e-------8---------------
b--8-10---10-8-6--------
g--(sl)----(sl)----7----
d-----------------------
a-----------------------
e-----------------------
Comment: Can you also provide the song?
Comment: @shev Sure, _Walk Of Life_.
Answer: It means slide. There are many variations in how tab is written. Some people will use sl, and some use /. Bends are sometimes notated with an arrow and a number (usually 1/2 or 1) to indicates how may tones to bend up, sometimes it will be like --7-b-(9)- meaning bend the note at the 7th fret until it matches the pitch of the note at the 9th fret. If in doubt use your ears to tell you if it sounds correct.
As to why there are 2, it could mean pick the string again during the slide. Again, try to use your ears to judge. Many tabs are not totally accurate and you should err on the side of what your ears tell you sounds right.

Is this slide/shift slide?


VBA Traverse through each non-empty element of 2-d array

Question: I would like to perform some action on each element of a 2D array where the second dimension of the array varies on each of the first dimensional elements. I would like the loop to skip empty elements.
A 1D array would make it run through the loop without wasting any time on empty elements of the array, but I would like to use a 2D array to make it easier to associate data into a certain group and make the code easier to modify later by somebody else if needed. The 1D array runs much faster than the 2D array.
Application.EnableCancelKey = xlDisabled

On Error Resume Next

For i = 0 To UBound(somearray,1)
    For j = 0 To UBound(somearray,2)
        perform some action on somearray(i,j)
    Next j
Next i

It should be noted that I do get a subscript 9 out of range error without the On Error Resume Next. I assume this is because it is attempting to perform an action on something that doesn't exist. It works as intended but is just slower.
I apologize if the question is trivial. I wasn't able to find an answer to this and I know nothing about VBA.
Comment: How do you define `somearray`? Think we need a bit more code. Nothing obviously wrong with the code you've posted.
Comment: If your array indeed has [different number of elements in the second dimension](https://stackoverflow.com/q/9435608/11683), you cannot access it as `somearray(i,j)`, but rather as `somearray(i)(j)`. If your array is a normal array where some of the last elements in each row are `Empty`, then use `IsEmpty()` to not "loop over them".
Comment: What are the lower bounds of the array? Also, `On Error Resume Next` when used like that is just awful. Errors should be fixed or at least handled, not suppressed.
Comment: Can you elaborate on both part of *where the second dimension of the array varies on each of the first dimensional elements. I would like the loop to skip empty elements.*?  I don't want to be wrong in assuming where the empty elements are (,1 or ,2)
Comment: I managed to figure it out and the comments were helpful. For some reason IsEmpty() didn't work for me but = "" did.
Answer: Remove On Error Resume Next, and don't hard-code the lower bounds:
Dim currentRow As Long
For currentRow = LBound(somearray, 1) To UBound(somearray, 1)
    Dim currentColumn As Long
    For currentColumn = LBound(somearray, 2) To UBound(somearray, 2)
        DoSomething somearray(currentRow, currentColumn)
    Next
Next

If you got your 2D array from a Range, it's a 1-based Variant array, so subscript 0 is out of range.