How can I generate similar sets of fields in views quickly from within the views ui?

Question: I have several views that I have made of the users on my site.  Each view has different contextual filters, pages, and fields.  However, certain "groups" of fields are the same.
In particular, I have a series of four checkboxes on the user profile that I use the views module's rewriting ability to display, and this "group" of four fields is the same among all views.
Is there a way to somehow save this as a reusable unit within the views UI so I don't have to input it manually all the time?
Answer: The easiest thing to do it to add all of the common fields to the Master display, and then a few displays to the view that get customized for the individual uses using overrides.
Comment: I was hoping there would be some concept like "field sets" which I didn't know about, but I suppose no luck...


Skip TestNg test in runtime

Question: I don't have a lot of experiences with TestNG, so do you know hot to skip or ignore some tests in Java Runtime. My idea is to write @Before-annotiation test and if it fails the incoming test will be ignored.
I tried to use JUnit with assume method, but I don't prefer it because if "before-test" fails the incoming test is highlighted as passed and it's not a reliable solution because it has ambiguous meaning.
So if you have any experiences with TestNG, please help I would be grateful.
Answer: You can skip test by throwing SkipException
<code>throw new SkipException("Skip this");
</code>
Answer: You need group of tests. Annotation @Test with next params
dependOnGroup
or
dependsOnMethods
e.g.
<code>@Test
public void verifyConfig() {
//verify some test config parameters
}

@Test(dependsOnMethods={"verifyConfig"})
public void dotest(){
//Actual test
}
</code>

Skip TestNg test in runtime


How to place $k$ objects in $P$ boxes, such that many objects can be placed in one box

Question: Given $P$ boxes, how many ways are there to place $k$ indistinguishable objects, $k\leq P,$ whereby you can place from $0$ up to $k$ objects in each container. The result should be $C^{k+P-1}_{k},$ which I can eventually prove by induction.
What I don't understand is the way this result is established. Can somebody provide an explanation to derive the result?
Many thanks.
Answer: Let $x_i$ be the number of objects in box $i$ with $i=1,\dots ,P$. Then we have to count the number of non negative integer solutions, i.e. $x_i\geq 0$, of
$$x_1+x_2+\dots+x_{P-1}+x_P=k.$$
Which is the same (see Stars and Bars Thm 2) to place $P-1$ bars $|$ which divides a sequence of $k+P-1$ stars $\underbrace{\star\star\dots \star\star}_{k+P-1}$ into $P$ blocks:
$$ \binom{k+P-1}{P-1}=\binom{k+P-1}{k}.$$
A similar reasoning works when we have to count the number of positive integer solutions, i.e. $x_i\geq 1$, (see Stars and Bars Thm 1) which is given by
$$\binom{k-1}{P-1}.$$
P.S. I recommend also the Numberphile's video Stars and Bars (and bagels).
Answer: This is the supermarket principle:
Consider $k+P-1$ objects lining in a line. Choose $k$ of them as 'dividers'. Then there is a bijection between the objects and dividers with the number of objects in each box.


show that if $\frac{2(m^2+n^2+n)+1}{m(2n+1)}=k$, k is the multiple of 3

Question: $$\frac{2(m^2+n^2+n)+1}{(2n+1)m}=k$$
where k, m, and n are all integer.
show that $3|k$
Comment: Have you tried using cases, such as when $m=0, 1, 2 \pmod 3$?
Comment: First examples are $(m,n)=(-1,-1)$ and $(m,n)=(1,0)$.
Answer: Write it as
$$
2(m^2+n^2+n)+1=k(m(2n+1))
$$
Compute both sides mod $3$, that is, for $m,n=0,1,2$.
It turns out that there are two cases:

The LHS is not zero and the RHS is zero. This cannot happen.
The LHS is zero and the RHS is not zero. This implies that $k \equiv 0 \bmod 3$.

$$
\begin{array}{cccc}
m & n & 2(m^2+n^2+n)+1 & m(2n+1) \\
0 & 0 & 1 & 0 \\
0 & 1 & 2 & 0 \\
0 & 2 & 1 & 0 \\
1 & 0 & 0 & 1 \\
1 & 1 & 1 & 0 \\
1 & 2 & 0 & 2 \\
2 & 0 & 0 & 2 \\
2 & 1 & 1 & 0 \\
2 & 2 & 0 & 1 \\
\end{array}
$$


Ajax loader when facet is selected

Question: When we add a facet block to the page, a filter is selected and the page starts to load the results. However there is no loading icon or indicator the change is being applied.
When we check the page, there is no JS error and nothing visible.
How do we get the loading icon or throbber to show when a facet is selected?
Comment: Sorry I don't have time to test & write a proper answer, but you may be able to use hook_form_alter() to add the throbber to the form element filter such as `$form['my_form']['facet_filter_1']['#ajax'] = ['event' => 'keyup', 'progress' => [ 'type' => 'throbber', 'message' => NULL ]];` - for more info checkout https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x && https://www.drupal.org/docs/8/api/javascript-api/ajax-forms
Answer: You can try the following.
Add in your JS file:
$(document).ajaxStart(function(){
  $('#ajax_loading').show();
});

$(document).ajaxStop(function() {
  $('#ajax_loading').hide();
});

Add the HTML in your page:

Add in your CSS file:
#ajax_loading {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 9999;
}

Ajax loader when facet is selected


iOS: Push notification not showing dictionary info in iOS 10

Question: I am working on push notification in XCode 8 Beta, iOS 10 Version. I have got push notification received on device. When I clicked on notification, it fired delegate of UNUserNotificationCenterDelegate, app is opened, but it didn't show any response in userinfo. Do I need to change parameter for sending push in iOS 10 on server side. Below is my code.
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [application registerUserNotificationSettings:settings];

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"request authorization succeeded!");
        }
    }];

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {

    NSLog(@"Notification is triggered");
    completionHandler(UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {

    NSLog(@"Tapped in notification");
    NSLog(@"%@",response.notification);
    NSString *actionIdentifier = response.actionIdentifier;

    if ([actionIdentifier isEqualToString:@"com.apple.UNNotificationDefaultActionIdentifier"] ||
        [actionIdentifier isEqualToString:@"com.apple.UNNotificationDismissActionIdentifier"]) {
        return;
    }
}

In iOS 9,
aps =     {
    alert = "Multi extra param push.";
    badge = 0;
    sound = default;
};
t = I;
url = "http://www.google.com";

and in iOS 10
alert = "Multi extra param push.";
badge = 0;
sound = default;

Comment: why are you using beta iOS version ?
Comment: try this  NSLog(@"%@",[response.notification.request.content.userInfo objectForKey:@"aps"]);
Comment: In iOS 9     aps =     {
        alert = "Multi extra param push.";
        badge = 0;
        sound = default;
    };
    t = I;
    url = "http://www.google.com";
In iOS 10     alert = "Multi extra param push.";
    badge = 0;
    sound = default;
Comment: I am not getting url and t value in iOS 10, is there any way to retrieve or do I need to change any thing.
Comment: I got the solution how to do, thanks for all the help
Answer: - (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog(@"%@", notification.request.content.userInfo);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)())completionHandler {
    NSLog(@"%@", response.notification.request.content.userInfo);
}


i want static variables in c++ and other languages.getting error " `total_no_of_customers': undefined method `+' for nil:NilClass'"

Question: this is my code in which i want to use static ruby variable. which shows total no of objects created a an time
<code>!/usr/bin/ruby

class Customer
    @total_customers = 0
    def initialize(id, name, addr)
        @cust_id = id
        @cust_name = name
        @cust_addr = addr
    end

    def display_details()
        puts "Customer id #@cust_id"
        puts "Customer name #@cust_name"
        puts "Customer address #@cust_addr"
    end

    def total_no_of_customers()
        @total_customers += 1
        puts "Total number of customers: #@to**strong text**tal_customers"
    end
end

# Create Objects
cust1 = Customer.new("1", "Ali", "Johar Town, Lahore")
cust2 = Customer.new("2", "Umer", "Farid Town, Sahiwal")

#Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()
</code>
Comment: There is no question in your question.
Answer: <code>!/usr/bin/ruby

class Customer
      @@total_customers = 0
      def initialize(id, name, addr)
          @cust_id = id
          @cust_name = name
          @cust_addr = addr
          @@total_customers +=1;
      end

      def display_details()
          puts "Customer id #{@cust_id}"
          puts "Customer name #{@cust_name}"
          puts "Customer address #{@cust_addr}"
      end

      def total_no_of_customers()
          puts "Total number of customers: #{@@total_customers}"
      end
    end
</code>
You need a class variable which is defined by using @@ and the name of the variable.
Every time a new object of type customer is being instantiated this variable will increase by one therefore you should increase this counter on the initialize method.
The @@ creates a class variable which will be shared with all instances of Customer.


QR code generation programmatically

Question: In my application I need to generated a QR code and I have to scan it to get the result which is contained in the QR code. I have implemented the QR code scanning using ZBAR SDK but I cannot generate a QR code. I have tried to use ZXING but it is not working. Please suggest any SDK or or any link which I can go through to implement it. I have tried this link
https://github.com/zxing/zxing
Answer: Use CIFilter to generate QR code.
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

[filter setDefaults];

NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKey:@"inputMessage"];

CIImage *outputImage = [filter outputImage];

See: https://github.com/shu223/iOS7-Sampler/blob/master/iOS7Sampler/SampleViewControllers/QRCodeViewController.m
Comment: Thank you.I have implemented it successfully.Can I customise the QR code image according to my own will?
Comment: You can use `[UIImage drawInRect:]` to draw a customized QR code image. See https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKitFunctionReference/

QR code generation programmatically


How to debug a stored procedure without using any tools or breakpoints

Question: Folks could someone please share the ways to debug a Stored Proc ? It was an interview question where the interviewer was asking the way to debug a SP without using tools. Finally he said like, in Oracle, there is something in a package which gives a way to debug. I didn't understood neither he completely explained :(
Answer: well, if you are on SSMS, the easiest way would be to use the print function. Each line you want to see if ti was "reached", just add a print 'line X' and check your messages tab.
If you are not on SSMS, you can create a global temp table (create table ##debug_table....) and add insert statments in your proc folowing the same logic as the prints.
All of these "solutions" are considering that you have permisison to update the proc, of course. If yo udont I really dont see how it could be done.
Comment: It might be worth noting that using `print` won't make it appear in the messages window immediately (you might want it to if you're going round a long running loop or something like that?). If you required such a thing it could be achieved with `RAISERROR`, along with the `WITH NOWAIT` clause ([MSDN ref](http://msdn.microsoft.com/en-us/library/ms178592.aspx)) If you are going to go down this route, make sure you don't set the severity too high!
Comment: Thank you Diego and Bridge. Bridge, I am sure you are saying something high end. I am newbie and my apologies, I don't really understand much the jargons you use :( Anyway I will try to understand better...


R Why plot.xts creates extra graph after calling lines?

Question: Consider two following plots, first uses generic plot function and the second one uses plot.xts:
Generic plot
par(mfrow = c(2,1))
plot(1:5, type="l", main = "generic plot")
lines(5:1)

as expected, lines function adds to existing graph so it results in single graph

I've set mfrow = c(2,1) to show you that, there is only one graph.
Now using xts data:
par(mfrow = c(2,1))
plot(xts(x = 1:5, order.by = 1:5+as.Date("2017-01-01")), type="l", main = "plot.xts")
lines(xts(x = 5:1, order.by = 1:5+as.Date("2017-01-01")), main = "plot.xts")

Unexpectedly it results in two graphs. Why?
My particular case is a bit more complex, but I've found this snippets of code the easiest way to reproduce my issue. Basically I want to keep adding xts data on one plot. I was able to accomplish that using generic plot and lines function.
Platform information:
R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.2
quantmod_0.4-12
xts_0.10-1
Answer: The xts plotting functions don't really work like base plotting functions despite they fact the calls look the same.
The plot.xts function returns an object. By default, if you don't assign the object anywhere, R will "print" the object which results in a plot being drawn. The lines.xts function changes the most recent plot object and adds a new series. Since the plot is not saved, that new object is printed as well. This new object remembers the first series as well as the newly added series.
The best thing to do would be to save these object and only print them when you are done adding layers. For example
par(mfrow = c(2,1))
pp <- plot(xts(x = 1:5, order.by = 1:5+as.Date("2017-01-01")), type="l", main = "plot.xts")
pp <- lines(xts(x = 5:1, order.by = 1:5+as.Date("2017-01-01")), main = "plot.xts")
pp #plot will be drawn here


How do I change where psycopg2 looks for a pid file?

Question: I am trying to configure a PostgreSQL database. Postgres is installed and running, but the PID file that it creates by default is different from what psycopg2 wants (which is /var/run/postgresql/.s.PGSQL.5432).
When I change /etc/postgresql/8.4/main/postgresql.conf to reflect this file, it fails silently and doesn't create the file. I tried a different file name that did not begin with a dot and it worked.
Is there a way to force Postgres to create this file, or to change the path that psycopg2 looks at to connect?
Thanks.
Comment: What you are describing the is not a PID file, but a Unix domain socket file.  Also, if something fails, show the error message.  If you change a configuration file, say what you changed.
Answer: You can set unix_socket_directory in your postgresql.conf to force your server to put the socket in /var/run/postgresql. I'm not positive where psycopg2 picks up the default path from, I wouldn't be surprised if it were compiled in based on the default.
Comment: That's fine, but it doesn't solve my problem. Postgres is responding to most changes to PID file parameters, it just won't create a file that begins with a dot, which is what psycopg2 looks for.

I suppose I supplied an inappropriate title. It should have been "How can I change the PID file that psycopg2 looks for?" but I believe that is moot because it has to be done by postgres.


How to extract data from implicit function with a parameter in MAPLE

Question: I plotted number of functions $y=y(x)$ with different parameter $a$ for given value of $\tau$ (see the code below) via MAPLE
restart;
R0:=gamma+2*ln(2)+Re(Psi(1/2+(1+I)*tanh((1+I)*x)/((tau+0.25e-1*a)*y)))+ln(y);
tau := 9.975;
with(plots);
implicitplot({seq(R0, a = 1 .. 50)}, x = 0 .. 5, y = 0 .. 1, numpoints = 1000);

My question is how I can extract the values of $y$ from these plots in the form of matrix $50\times1000$ ($a\times x$) in data file?
Thanks in a advance.
Answer: You can use getdata to extract points data from a plot (see documentation https://www.maplesoft.com/support/help/Maple/view.aspx?path=plottools/getdata):
> with(plottools):
> p:=implicitplot({seq(R0, a = 1 .. 50)}, x = 0 .. 5, y = 0 .. 1, numpoints = 1000);
> data:=getdata(p);

By inspecting the structure, you see it gives usually list of curves, their ranges and corresponding points stored in a matrix. For example:
> data[1];
  ["curve", [0. .. 1.21568604536228397, .250000000000000000 .. 1.],
  Matrix(6, 2, [[1.21568604536228, .250000000000000],
  [1.18320567278278, .263358865443444],
  [1.02207824594441, .500000000000000],
  [.813115565428804, .587376886914239],
  [.606754726975888, .750000000000000],
  [0., 1.]])]

You can then iterate through these and do what you want with them (e.g. store them to a file).


Get custom attributes from material ui text field inside onChangeHandler

Question: Hi I am using react and material ui.
The markup for textfield is something like this
<TextField
    floatingLabelText="Email"
    onChange={this.props.onChange}
    ref="email"
    customAttr="customValue"
    errorText = {this.props.errors.email}
/>

My onChange handler is below
function onChange(e) {
   var customVal = e.target.getAttribute("customAttr");
   alert(customVal);  //undefined
}

I want to get the value of the my custom attribute when using material ui.
Please help!!
Answer: you can try something like this.
in TextField:
    onChange={() => { this.props.onChange("customValue") }}

or without es6
    onChange={function () { this.props.onChange("customValue") }}

and update onChange func:
    function onChange (customVal) {
       alert(customVal)
    }


generalized matrix inequality for complex Hermitian matrices

Question: Assume having a symmetric real matrix $A$ and a skew-symmetric matrix $\Delta = [0 1; -1, 0 ]$, such that the following generalized matrix inequality holds in the PSD sense:
$$\pm \frac{i}{2} \Delta\preceq A.$$
Given the fact that for $ \frac{i}{2} \Delta$ the eigenvalues are $\lambda_{1,2} = \pm 1/2$ and for $ -\frac{i}{2} \Delta$ the eigenvalues are $\lambda_{1,2} = \mp 1/2$, does this inequality imply:
$$\frac{1}{2}I \preceq A?$$
If yes (or no), then can you explain what is the difference between them? Thanks.
Comment: Ah ok. Well I posted an answer. The really interesting thing is that if you assume that A is real symmetric, it will never commute with $\Delta$ unless A is a multiple of the identity. This sort of suggest that something bad might happen when trying to transfer the positive definiteness since A and $\Delta$ will not be simultaneously diagonalizable.
Comment: @AnCar let me ask this way. When comparing matrices with PSD inequality, does the two matrix have to have the same diagonalization so that you can compare their eigenvalues directly? right? otherwise if they don't commute you have to add them and find the eigenvalue of the summed matrix as a whole and see if the eigenvalues are positive...
Comment: exactly. if they commute, you can simply do arithmetic directly on the eigenvalues. if they do not commute, you can't in general do this. the solution to your problem is a nice and simple example of when doing eigenvalue arithmetic directly goes wrong due to non-commutativity. You can also think of this geometrically. if two matrices stretch vectors in different directions (by stretch i mean the action on the eigenvectors), you can't simply add or subtract their contributions since they occur on non-parallel vectors.
Comment: What exactly do you mean by symmetric Hermitian? Do you mean that if A= [a,b; c,d] then b=c and are real?
Comment: @AnCar Sorry, A is actually real and symmetric in my problem. I will fix that now.
Comment: To be a bit more precise with what I meant above. If A and $\Delta$ did commute, you would have that $(A+i/2\Delta)(A-i/2\Delta)=A^2-1/4 I$. So $A^2-1/4 I$ would be psd, meaning that the eigenvalues squared of A are bigger than 1/4.
Comment: @AnCar Thanks a lot. I understood the answer you provided. But I am not sure what was wrong with the argument that I made with the PSD inequalities that resulted in $1/2 I \leq A$?
I understand that you say A and \Delta don't commute. But how did that violate any of the steps of the argument?
Comment: Did my next answer clarify?
Answer: Consider the following family of matrices $A_t:=\begin{pmatrix} 1 & t \\ t & 1 \end{pmatrix}$ for $t\in\mathbb{R}$. Obviously this is Hermitian (even symmetric Hermitian if that is what you really meant).
It is clear that the characteristic poly is $P_t(\lambda)=\begin{vmatrix} 1-\lambda & t \\ t & 1-\lambda\end{vmatrix} = (1-\lambda)^2-t^2=\big((1-t)-\lambda\big)\big((1+t)-\lambda\big)$, so the eigenvalues are $\lambda=1\pm t$.
Now consider the characteristic polys for $A_t\pm\tfrac{i}{2}\Delta$, which we denote by $Q_t$.
We get $Q_t(\lambda)=\begin{vmatrix}1-\lambda & t\pm\tfrac{i}{2} \\ t\mp\tfrac{i}{2} & 1-\lambda\end{vmatrix}=(1-\lambda)^2-(t-\tfrac{i}{2})(t+\tfrac{i}{2})=\lambda^2-2\lambda+\tfrac{3}{4}-t^2$. The discriminant for this is $\delta=1+4t^2$, so the eigenvalues will be $1\pm \sqrt{t^2+\tfrac{1}{4}}$.
We want $A_t\pm\tfrac{i}{2}\Delta$ to be psd, so we need that $t^2\leq\tfrac{3}{4}$, i.e., that $t\in[-\tfrac{\sqrt{3}}{2},\tfrac{\sqrt{3}}{2}]$. Note however that if we pick $t\in(\tfrac{1}{2},\tfrac{\sqrt{3}}{2}]$, then $A_t$ will have an eigenvalue smaller than $\tfrac{1}{2}$, meaning that $A-\tfrac{1}{2}I$ is not psd.


Autosave Not Working

Question: I wanted to provide a feature to autosave the data while adding the article so that user can restore the content in the event he goes to some other page.
For that I am using Autosave module. I have installed it and set it for my content type. But it is not showing any kind of message that form has been saved.
Also I have checked that it is not running in "Stealth Mode", so it must give message that it has been saved.
Is there anything I am missing. I am using drupal 7 and latest version of autosave ie 7.x-2.1
Also it would be better if someone could suggest some other module that helps to accomplish this.
-- Thanks
Comment: Have you checked the issue queue for the module and reported this there first? This site isn't for module bug reports
Answer: Autosave module works fine with a multilingual Drupal site.
So I'm assuming that you are working on a single language Drupal site.
In order to make Autosave module work on single language Drupal site, you need to apply this patch file
Edit:
The patch file should be for Autosave 7.x-2.x-dev
Check the actual issue
Comment: It is not working. It is giving some error of service unavailable.
Comment: Sorry I forget to mention that the patch is for autosave-7.x-2.x-dev - try to apply it and see if you'll get the same errors
Answer: Save Form State can be a good alternative. This module provides a way to autosave data entered in any Drupal form without actually submitting the form, which helps if the user is writing an article or a comment and the browser crashed or the power went down, or even if the window was closed accidently.

Autosave Not Working


Single click function in a Drupal behaviour?

Question: The following in a Drupal behaviour is working fine:
<code>  $('.trigger', context).click(function(e){
    e.preventDefault();
    $('.target').toggleClass('open');
  });
</code>
However I know that I should be using the once function. Is the following correct? It does work but so did the code above so im not sure how to check if its been done with best practices.
<code>  $('.trigger', context).once('toggle-name', function(){
    $(this).click(function(e) {
      e.preventDefault();
      $('.target').toggleClass('open');
    });
  });
</code>
Answer: If you don't use .once() then your code will still work but - depending on whatever else happens on the page - your click() function may be attached multiple times to the same element, which is less efficient and may cause undesired effects if, as in this case, you are using a toggle function in your callback.
Because you are limiting the scope of your selector by context, multiple attachment is less likely, but you should definitely use once() if you want your code to be robust.
Comment: I understand the general concept. Is my second block of code correct?
Comment: Looks OK to me, yes.


Need to get the messages passes through the sonic queue per minute

Question: I need to get the numver of messages passes through the sonic queue per minute via a java code. I need this so i can create an alert when this messages per minute is higher than normal count. Can some on please assist me with this. Thanks
Answer: this information should be available via JMX (enqueued/dequeued count).
try to connect to the broker with VisualVM to find the ObjectName and Attributes.
to access sonicmq by JMX :
<code>Hashtable env = new Hashtable( );
env.put("ConnectionURLs", "tcp://localhost:2506");
env.put("DefaultUser", "Administrator");
env.put("DefaultPassword", "Administrator");
JMSConnectorAddress address = new JMSConnectorAddress(env);
JMSConnectorClient connector = new JMSConnectorClient( );
connector.connect(address);
ObjectName brokerName = new ObjectName("Domain1.Container1:ID=Broker1");
MBeanInfo mi = connector.getMBeanInfo(brokerName );
... usual JMX attributes access
</code>


Recover from a Lost Drupal Administration Menu

Question: When I log into the Admin on my site, the drupal controls are all missing.  Our former Web Developers refered me to an article online that told me I need to enable the toolbars by:
What you need to do is access the main "Modules" page. The best way to get there is by typing in the URL of the modules page.
Try adding one of these to your main domain name:
•/admin/modules/
•?q=admin/modules
Neither of these worked. With /admin/modules/ I get "Page Not Found".
With ?q=admin/modules I get "Access Denied"
How can I get the drupal controls back so I can make edits?
Answer: Open below URL and change settings
admin/people/permissions
Or else you can edit here roles & permissions
admin/people/permissions/roles
Comment: Didn't work.  I got "Access Denied"
Comment: If you use Devel Module than load user and edit access

$a = user_load(1);
dpm($a);
Answer: If you use "Devel" Module than load user and edit access
<code>$a = user_load(1);
dpm($a);
</code>


Setting up folder sharing in Windows Server

Question: I am currently setting up a Windows Server 2008 R2 with Active Directory and are currently facing an issue with setting up file/folder sharing between users/groups:
My organization is divided into sections, each section has a section manager and section users. I want to achieve that each section user has a shared folder that can be accessed only by him and the the section manager. The section manager can access all shared folders of his section users, but not the shared folders of any other section. Furthermore its important that section users cannot access any other shared folders (e.g. the shared folders of other section users).
Well, how do I setup such a structure? I basically need a conception for needed groups, users, rights and where to store the actual folders in the file system.
Looking forward to your answers!
Answer: Your description/requirements seems fairly "flat" in which it should not require anything too elaborate. You may consider an approach in which:

Each section has its own group with the manager in its membership
Each section can also have its own main folder with subfolders for each member
Each user is assigned/associated to their own subfolder and "everyone" removed
The manager group is assigned/associated to each of its section subfolders

The arrangement should accomplish what you described as well as facilitating efficiencies of changing managers across any of the sections. The group-section-manager will just need updating, each subfolder assignments will then reflect the access change by having the group already associated/assigned to it.


Embed content from one part of my website to another page (responsive)

Question: I am trying to take the div #content of server list from here (same domain): http://bans.endlessgamers.com/index.php?p=servers
And embed it on a new page (same domain): http://www.endlessgamers.com/server-list/
The issue: I have managed to embed it fine with , but the server list is responsive and expands/collapses when clicked. When I expand, I have to scroll in the  window to see the content. Is there a way to force my page to expand and collapse with the information in the  div?
Note: To replicate my issue click on hostname of server to expand or collapse it.

Answer: You can try set iframe height dynamic:
//Initially set iframe height on load
$($("#elCmsPageWrap iframe")[0]).css("height",+$("#elCmsPageWrap iframe")[0].offsetParent.clientHeight);

//Set iframe height again when collapse/expand in table
$(".listtable tbody tr td").click(function(){
    $($("#elCmsPageWrap iframe")[0]).css("height",+$("#elCmsPageWrap iframe")[0].offsetParent.clientHeight);
});

Comment: I tried adding that into the html, it only expanded my iframe slightly. When i expand the table, the div remains fixed. Am i doing something wrong?
Answer: Why don't you copy the code of the original #content div into a new file? Let's say: server-list.php
Then, you include this file on both pages:
<?php include 'server-list.php'; ?>

The include function basically pastes the code into the file.
iFrames are mostly used to embed external pages.
Comment: Yeah the file structure for sourcebans is a little odd to me. It calls to several files for server details, page template, etc. (im a novice coder). Not sure how I would go about doing that. If you or anyone can help me achieve it, that would be great. Thanks for your response.


Understanding Scope of Quantifiers

Question: I have a set of questions below that I'm trying to logically work my way through. I have ideas about each but I'm not sure if I'm correct. Any advice would be most welcome! Thanks so much!
1) I know that the converse is not true because there exists a Y not all Y. I don't know how to write out the converse though.
2) I believe they differ in meaning because the ∀x [P(x)]∨ ∀x [Q(x)] could have two different possible values for x. I'm not sure of a good example of that though.
3) would be similar to #2 where the first half could have two different values for X. Also not sure of an example.
4) I'm not sure at all about this one. I believe they are equivalent because the domain is not changing.

(6) Explain why [∀y∀x P(x, y)] → [∀x∃y P(x, y)]. Use a counterexample to demonstrate that the converse is not always true.
(4) How do ∀x [P(x)∨Q(x)] and ∀x [P(x)]∨ ∀x [Q(x)] differ in their meaning? Use examples to illustrate.
(4) How do [∀x P(x)] → [∀x Q(x)] and ∀x [P(x) → Q(x)] differ in their meaning? Use examples to illustrate.
(4) Are ∀x [P(x) → ∃y [Q(x, y)]] and ∀x∃y [P(x) → Q(x, y)] logically equivalent? Explain why or why not.
Answer: In finding examples, it is often useful to restrict $P$ and $Q$ to some set. For example: $P(x) \equiv (x \in \Bbb N \implies 2\mid x)$.

You are just looking for some statement $P(x, y)$ which for any $x$ has a value $y$ which makes it true, but which is not true for every $y$. For example, $x = y$.
$\forall x [P(x) \vee Q(x)]$ means for each value of $x$, either one or the other of $P$ or $Q$ is true. $\forall x [P(x)] \vee \forall x [Q(x)]$ means that either $P$ is true for every $x$, or $Q$ is true for every x. Look for an example where $P$ and $Q$ complement each other: one is true in the places where the other is false.
is indeed similar to 2. The first form is true any time that $P$ is false for even one $x$, regardless of $Q$. The second form requirs $Q$ to be true for each $x$ where $P$ is false.
The change between $\forall x [P(x) \implies \exists y [Q(x,y)]]$ and $\forall x \exists y [P(x) \implies Q(x,y)]$ is the scope of the $\exists y$, which in the first only includes "$Q(x,y)$", but in the second also includes "$P(y) \implies$". Now ask yourself, what effect does knowing a particular value of $y$ have on the meaning of "$P(x)\implies$"?

Understanding Scope of Quantifiers


Upgrading from 5.3 to current

Question: Is there a reasonable upgrade path from drupal 5.3 to the current version or should I just rebuild the site from scratch? It's a pretty small site, but it does have a few custom content types, and use tac_lite for role-based security.
These are the modules I have installed:
<code>tac_lite
filebrowser
private_upload
role_weights
site_user_list
user_import
cck
views
imagefield
imagecache
token
pathauto
path_access
marksmarty
devel
admin_menu
</code>
Answer: Nope, there is none. No matter if by "current" you mean 7.x or 8.x, skipping 6 is too much gap, and even upgrades from 6 to 7 are known not to be painless and safe.
You may try to rebuild site's structure from scratch, and then use Drupal-to-Drupal data migration module to import your data:

migrate_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed. As of 7.x-2.1-beta1, it requires Migrate 7.x-2.6-beta1 or later.
Comment: @sprugman sorry to disappoint.
Answer: If you want to upgrade drupal 5.x to drupal 7.x then you have to updgrade it in two steps.

Upgrade drupal 5.x to drupal 6.x.
and then upgrade drupal 6.x to drupal 7.x.

I have done up-gradation of a drupal website from 5.x to 7.x alongwith thousands of nodes migrated successfully to new one.
Drupal upgrade steps are listed in this link https://www.drupal.org/node/570162. I have followed these steps to make migrate successful. Currently site is running without any error.
Remember, there are some things which are included in core when you upgrade from drupal 5 to 6. Key point is you follow these 20 steps to make it functional.

Upgrading from 5.3 to current


Precise vertical alignment of text inside div

Question: Is it possible to position single-line text element inside div so, that its baseline coincides with bottom border of div precisely. Just like in svg rect. I can do it manually, but it would be fine to have universal method for any font-size. Some shift measured in 'em' units maybe?
Now i do something like this to align text in two div's ('name' and 'start'), font-sizes are different and horizontal alignments are different, i want them to align vertically precisely not by manual tuning of bottom margin:
.project-div .footer {
  position: absolute;
  bottom: 0px;

  height: 28px;
  width: 100%;

  display: inline-block;
  line-height: 28px;
}

.project-div .footer .name {
  position: absolute;
  left: -1px;
  bottom: -20%;

  line-height: 28px;
  font-size: 28px;
  height: 28px;
}

.project-div .footer .start {
  position: absolute;
  right: -3px;
  bottom: -10%;

  line-height: 18px;
  font-size: 18px;
  height: 18px;

  font-family: "Arial Black";
  color: #ccc;
}

Comment: where is your try
Answer: I would say, assign the property position: relative to your parent, and then assign the properties position: absolute and bottom: 0 to your child if you want to completely have it at the bottom of the parent div.
Next time elaborate on your questions a bit more by the way.
Comment: so i`ll get aligned bottomlines of two div's, but I want to align baselines, they are at different heights for different font-sizes
Comment: Would you mind posting a screenshot of what you currently have?
Comment: http://blogs.adobe.com/webplatform/2014/08/13/one-weird-trick-to-baseline-align-text/ Try taking a look at this article
Comment: screenshot: https://yadi.sk/d/t07OUukDy9DJK 'timeline' and '2012' are manually aligned but not precisely. thanks for link i'll try it later


Background thread with pthreads

Question: i'm using pthreads to create a background thread to load and do some tasks in background, but it lags the application a little bit as it's work is intense sometimes.
Is there any way i can set a lower priority or a different scheduling (or combination of both)  so the main thread has more CPU time to run?
Answer: Use pthread_attr_setschedparam
http://linux.die.net/man/3/pthread_attr_setschedparam
Use SCHED_IDLE scheduling policy to lower the priority of thread
Hope below SO links may help.
How to increase thread priority in pthreads?
Equivalent of SetThreadPriority on Linux (pthreads)
Unable to set Pthread Priority
Comment: Have you included sched.h ?
Comment: yes, but SCHED_IDLE is not defined, only SCHED_OTHER, SCHED_FIFO and SCHED_RR
Answer: This does not verbatim answer your question, but
in the Concurrency Programming Guide
Apple recommends to move away from threads and use "Dispatch Queues" or
 "Operation Queues" for asynchronous operations on OS X and iOS, for example
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    // ... background task
});

and DISPATCH_QUEUE_PRIORITY_LOW is documented as

Items dispatched to the queue run at low priority; the queue is
  scheduled for execution after all default priority and high priority
  queues have been scheduled.
Comment: @XavierAriasBotargues: Dispatch queues and blocks are available to C, C++ and Objective-C, compare http://developer.apple.com/library/mac/#featuredarticles/BlocksGCD/_index.html.

Background thread with pthreads


If we identify $V$ and $U$ with their canonical images in $V^{**}$ and $U^{**}$ prove that the restriction of $T^{**}$ to $V$ coincides with $T$.

Question: Let $T : V \rightarrow U$ be a bounded map between two normed spaces.  Let $T^* : U^* \rightarrow V^*$ be defined by $T^*(f) = f\circ T$ for all $f\in U^*$ (the adjoint map).
My Question:
If we identify $V$ and $U$ with their canonical images in $V^{**}$ and $U^{**}$ prove that the restriction of $T^{**}$ to $V$ coincides with $T$.
I think I want to try and use the canonical mappings $V \rightarrow V^{**}$ and $U \rightarrow U^{**}$ but I am not entirely sure what the canonical images would be. The restriction would be $T^{**}\cap V$ and I am not sure where that comes into play...
I would really appreciate some help on this proof. hank you.
Answer: I will instead write $v^{**}\in V^{**}$ and $u^{**}\in U^{**}$ as the images of $v\in V$ and $u\in U$, respectively, under the duality maps $V\to V^{**}$ and $U\to U^{**}$.  We note that
$$T^{**}v^{**}(\varphi)=v^{**}\circ T^*(\varphi) =v^{**}(\varphi \circ T)=\varphi\circ T(v)=\varphi(Tv)=(Tv)^{**}(\varphi)$$
for all $v\in V$ and $\varphi \in U^*$.  Therefore, $T^{**}v^{**}=(Tv)^{**}$ for every $v\in V$, and the conclusion follows.
Comment: Thank you very much. I really appreciate the help on this one.


Disable drop up on Rails form - bootstrap

Question: I'm trying to prevent Bootstrap's automatic drop up from occurring on smaller screen sizes.
The S.O. question here says to add to add the attribute data-dropup-auto and set it to false, however upon doing so it doesn't work. Inspecting the select drop down from the Chrome developer console also reveals the attribute to be present and correctly set to false.
Here is the code for my select in the form.
<%= f.select(:countries_id_eq, Country.order(:name).collect{|c| [c.name,c.id]}, {:prompt => "Exam Cycle"}, { :class => 'form-control input-lg', "data-dropup-auto" => "false" }) %>

In the developer console, the select renders like this
<select class="form-control input-lg" id="q_universities_id_eq" name="q[universities_id_eq]" data-dropup-auto="false"><option value="">Subjects</option>...</select>

Any help would be much appreciated.
Comment: Did you mean to link another SO question? Also, go to the rendered HTML page and paste here what the `select` looks like.
Comment: @nicholas79171 I've added in both now.
Answer: As noted in the comment to this answer, you need to remove the quotes around the attribute value since it's boolean.
<%= f.select(:countries_id_eq, Country.order(:name).collect{|c| [c.name,c.id]}, {:prompt => "Exam Cycle"}, { :class => 'form-control input-lg', "data-dropup-auto" => false }) %>

Comment: Thanks for the answer Nicholas - I saw that comment as well and tried it but unfortunately it resulted in the same behaviour with the drop-downs becoming drop-ups on smaller screen sizes.
Comment: Have you tried editing the default value in the `bootstrap-select.js` file? For me it's on line 298. Setting that to false should do it.
Comment: I have, still the same behaviour unfortunately.
Comment: Have you tried adjusting the setting using JavaScript like in the answer I linked to?
Comment: I have - This however adds the bootstrap class of `select-picker` to my select element which alters the appearance of the element. It does however fix the issue.
Comment: That's the problem. `select-picker.js` looks for `select` items that are tagged with the class `select-picker`. Otherwise, it doesn't know which `select` tags you want to edit. Add `select-picker` to your `select` and it will solve your issue. You'll have to use more CSS or JS to fix the style changes.
Comment: Thanks Nicolas - I was thinking that myself but I thought there may have been a more elegant way to tackle this issue. I'll go with that though. If you post an answer I'll give you the green tick :)


Rails routing / assets with proxied location

Question:
OK so - I have a rails app, let's call it "railsapp", on a domain on a Dreamhost VPS (on which I have other domains, some 'static' and one that serves a perl/CGI script).
For obvious reasons, Passenger cannot be run on port 80, and is currently serving this app on port 8001. I have a proxy (configured in Apache) set up to route requests for http://DOMAIN/books to DOMAIN:8001/ (which, incidentally, works as DOMAIN/railsapp).
The issues:
1) No assets are served - the request for the stylesheets 404s, despite the fact that the stylesheets do in fact exist in [railsapp]/public/assets. I have tried every possible combination of precompiling, not precompiling, etc., and nothing seems to work.
2) Links aren't working exactly right. Accessed explicitly through port 8001, links work correctly, e.g., DOMAIN:8001/about shows the 'about' page and DOMAIN:8001/[railsapp]/[:id] brings me to the appropriate item.  Similarly, accessed explicitly (i.e., by manually typing the address in the address bar), DOMAIN/books/[railsapp]/[:id] and DOMAIN/books/about work perfectly fine. But the links at DOMAIN/books (to the items identified by id) all point to DOMAIN/[railsapp]/[:id], which gives me a 404; the link to 'about', similarly pointing to DOMAIN/about, also does not work.
Now! If I were to throw caution to the wind and switch my VPS to use nginx instead of Apache, guess what? The pathing mostly works! Items identified by id are linked as DOMAIN/books/[railsapp]/[:id] and "about" is linked as DOMAIN/books/about, and this is great. The only issue in the rails app is that links back to root are inexplicably(?) rendered as links to 127.0.0.1:8001. This is annoying, but seems like it would be trivial to fix.  The one problem with this is—you may remember this from the beginning of this post—the VPS also hosts a site that uses perl/CGI, and this is broken as hell given that nginx isn't really meant to deal with perl/CGI. As such, I'm sticking with Apache so that the CGI remains unbroken.
I have done the search for this issue, many times, in many different ways. I have probably seen whichever stackoverflow question or blog post you are thinking about linking me to. If you have any idea how to fix the pathing and assets issues, given the above information, let me know.
Comment: This doesn't really look like a `perl` question. I'm also not sure it's actually on topic either, given it's not really about coding.
Comment: It's not about perl - that tag was accidental, and I have removed it. Thanks.
Comment: What is the reason against specifying the port explicitly? Because DOMAIN/anything would be expected to access port 80. Or, where possible, to use relative links?
Comment: Re: port - that's entirely an aesthetic decision on my part. If the answer to my question is "There is literally no way to make this app visible without the port in the URL, given the constraints of the server it's running on", then, well, OK, but I have a hard time believing that. There must be something I'm missing.

Re: relative links - the links are being generated by rails - I *could* change them, but the fact that they work under nginx makes me think it could be easily solved.
Answer: Try in application.rb inside "class Application < Rails::Application":
config.action_controller.default_url_options = {host: 'DOMAIN/books', port: 80}
config.action_controller.asset_host = 'DOMAIN/books'
config.serve_static_files = true # for rails4; for rails3 use .serve_static_assets = true

After that, restart your application.
Make sure that application uses *_url-helpers everywhere rather than *_path-helpers (i. e. root_url instead of root_path)
Comment: OK, wow, thank you! This gets me 90% of the way there. I'm still having problems with the links produced - links to root_url appropriately go to `DOMAIN/books`, but links to "about" and individual items with ids still go to `DOMAIN/about` and `DOMAIN/[railsapp]/[id]` rather than `DOMAIN/books/about` and `DOMAIN/books/[railsapp]/[id]`, respectively. Sincerely grateful that you got me this far.
Comment: **Update:** between your answer and some sleuthing on my own, I was able to suss out where I was going wrong with my links. Cheers.


Moving to an outsourced Exchange provider - turning Exchange off and updating user accounts

Question: we used to have Exchange on the SBS 2003 server inside our AD environment. Earlier this year we moved to outside Exchange provider but for the time being our local Exchange was still up&running and forwarding email to the new email accounts.
Now the time has come to turn it off and I'm not quite sure what that means for SBS environment and how to proceed.
Specifically, there is a local e-mail account associated with every user in the domain. Can I simply change the e-mail address of every user to their outside address, or should I first delete the Exchange account for every user + their Mailbox, and only then update the e-mail address?
What do you suggest? How do I proceed? TNX!
Answer: Your best bet is to delete all of the user mailboxes on the SBS server (after you've backed up or exported the email from them) and then remove Exchange from the SBS component in Add Remove Programs.
Comment: It's largely a manual process. You can use Exmerge to export the contents all of the mailboxes to pst files from the server if the mailboxes are under 2GB in size. In ADUC you can select all of the user accounts, right click, select Exchange tasks, and select Delete mailbox. You'll need to reconfigure every Outlook profile to connect to the external email provider. W2K3 and AD don't care where the mailbox is.
Comment: True enough about using another email server. That may be the best option. I've used hMailServer on Windows with good success. http://www.hmailserver.com/.
Comment: Is there an automated way to do that or do I have to manually do it (backup&delete mailboxes) for every user separately? And what about e-mail info in the user profile? How does Win2003 domain and AD play with an outside email references in user profile?
Comment: Thank you. I've already reconfigured Outlook profiles, so this should work. If I understand correctly, after I delete mailboxes the only thing left is to enter new email address into user profiles in AD and I'm done? The Exchange General and Exchange Advanced tabs will be gone?
Comment: You won't need to enter any email addresses in AD for the users. There's no link between an AD user and an email address if Exchange isn't installed. You can add the email address if you like, but it has no bearing on the operation of AD. Also, don't confuse the email address with the UPN. A UPN is required and is normally set to the email@example.com format, where domain.local is your AD DNS suffix. Once the mailboxes are deleted there won't be any Exchange related tabs on the user account properties.
Comment: Yes, clear - no need to enter the email address. It is optional. :) Thank you again.
Comment: Glad to help... Don't forget to accept my answer, if in fact you do accept it as your solution. :)
Comment: I wouldn't forget :) I was just being courteous to others in case someone else had something to add. But I think it's safe to assume yor answer is the best despite being the only one. :)
Comment: ADDENDUM: Does the situation change if the new email is at different domain (previously firstname.lastname@example.com, now email@example.com)? Also - I previously wanted to turn the local Exchange off, but in fact several local services would still need an email server (backup, helpdesk, AV control center...). Does running a local server changes anything? Should I then simply delete local email accounts for users and their corresponding mailboxes, leaving only email accounts for specific service users?
Comment: You could do that, yes. You just need to make sure that you don't have internal and external email addresses that "match". Also, why not set up mailboxes with the new email provider for backup, helpdesk, etc?
Comment: Well, I'm not sure that Backup (Symantec Backup Exec) or similar services can send e-mail thru outside server...? I see no options to set up authentication to email server in Backup Exec, only server name, port, and *send as* email field. I believe server has to be open relay (locally) for this to work? And I think some other services we use have a similar limitation - no authentication possible.
Comment: What version of BackupExec are you running? Versions 12.5 and 2010 support SMTP authentication. I don't remember if earlier versions support it.
Comment: Unfortunately it's version 10.1. I see no SMTP authentication. In any case I would need Exchange connection over HTTPS for this to work, as we will be still using Exchange server - it's just located at an offsite location. Do you think leaving local Exchange server in open relay for local clients would in any way interfere with accounts? As you put it previously: if I make sure that email addresses don't match...? Also, maybe turning Exchange off and setting up other email server on Linux would work as well...
Comment: Glad to help...


Unbounded Lebesgue integrable and continuous function

Question: Problem
Show that there exists a function $f$ integrable on $[0,\infty)$, continuous and such that there is a sequence $(x_n)_{n \in \mathbb N}$ for which $$\lim_{n \to \infty}x_n=\infty \space \space \text{and} \space \lim_{n \to \infty} f(x_n)=\infty$$
I thought of picking the ordinary divergent sequence $x_n=n$ so as to construct a continuous lebesgue integrable function $f$ for which $f(x_n)=n$. I don't know if this is possible but my idea was to make the function take the value $0$ except on a very small neighborhood around each natural number $n$, I've attached a horrible drawing of the function.
I'm awfully sorry about my drawing skills, I hope the idea of the function I have in mind is clear. I would like to know if there is a way of making the slopes tend to infinity so that the integral is finite. If this is not possible, I would appreciate suggestions to construct a function that satisfies the conditions of the problem. Thanks in advance.
Answer: Here's an example with an explicit formula: $f(x) = x[\cos^2(x)]^{x^5}.$
Sketch of proof: Easy part: $f(n\pi) = n\pi \to \infty.$ Harder part: From Laplace's method
$$\int_0^\pi [\cos^2x]^p\ dx \le Cp^{-1/2}$$ as $p\to \infty.$ Hence
$$\int_{n\pi}^{(n+1)\pi} x[\cos^2x]^{x^5}\ dx \le (n+1)\pi\cdot C[(n\pi)^{5}]^{-1/2} \le C'/n^{3/2}$$
as $n\to \infty.$ Because $\sum 1/n^{3/2}
< \infty,$ we see
$$\int_0^\infty x[\cos^2x]^{x^5}\ dx <\infty.$$
Comment: This is very good example, but you'd better give a detailed proof on how it converges.
Comment: I added to my original answer.
Answer: Hint.
Your idea is good.
The integral of $f$ is the sum of the areas of the triangles. Find the slope in order to have the area of triangle $n$ equal to $\frac{1}{n^2}$. As $\sum \frac{1}{n^2}$ converges you're done.
For more details, you can hve a look here.


What is the benefit of Panels Everywhere

Question: Several websites advocate the benefits of Panels Everywhere (I have put them at the end of this question).
However, I have tried the module out out and cannot see the benefits.
A regular Panel page gives you the option to Disable Blocks. It also lets you display things like Menu Links, Footers and User Log-ins.
So I'm not sure what Panels Everywhere brings.
I could never see the benefits of Panels, but Drupal Answers enlightened me and now I wouldn't dream of making a Druapl site without it, so I'm hoping it can shed some light on the benefits of Panels Everywhere).

Sites Advocating Panels Everywhere

AWebFactory
Druapl Answers Thread
Lullabot
Answer: My experience with PE (panels everywhere) was great.
I been working for 1 year with PE on a big project and i can say:

The first advantage of PE is the entire layout control. while panels only affect the "content" region, PE get full control of all page including header and footer (which is no possible only with panels).
Second big advantage its the possibility to select variants as layouts letting you decide wich layout (variant) to show on every page taking that decision with the access arguments like a normal panel.

as you can see there are similarities with Omega theme, and in the fact both modules resolves the same issue.
Comment: +1 I've been working on a project using **Omega theme** to set the general layout using panels-like regions, **ctools Page Manager** to control the layout in each page's content area, and numerous **Mini Panels** placed as blocks for almost all the non-content layout... It works, but it feels increasingly like a clunky MacGuyvered impersonation of the features Panels Everywhere provide. That said, for sites with simple layouts, Panels Everywhere is probably overkill.
Answer: Besides the layout creation and management tools, there is another advantage to Panels: performance. Although not that apparent on smaller sites, it can have a major impact on larger installations. If a site is created using the standard Drupal block system, all blocks must load, and then not displayed (if set as so), instead of only pulling appropriate content for the given visitor.
Answer: One of the main advantages of Panels Everywhere is that it lets you override pages that regular Panels does not allow (such as node/add, user, etc).


OLS with clustered standard errors vs. multilevel modeling when the main interest is at the individual level

Question:
Possible Duplicate:
Under what conditions should one use multilevel/hierarchical analysis?

I have been reading various papers dealing with multilevel analysis, and to be honest, I am still confused re: choosing simple OLS regression or multilevel (random or mixed) models when data is clustered, but the main focus of the research is at individual-level (while group-level effects are treated as a nuisance)? What would be the most "proper" way to proceed in this case?
Comment: This question is very broad. can you be more specific?
Comment: The trouble with OLS is that it assumes the errors are independent, and, if data are clustered, that assumption is violated.
Answer: You have two major options:

multilevel analysis that you must have  been reading about;
OLS with clustered standard errors (Peter Flom made a comment that OLS assumes that the errors are independent, but that assumption is easy to circumvent with the right choice of the covariance matrix estimator)

Multilevel analysis surely is fancy and hot. That's also the reason it is misused a lot, because everybody seems to want to do something multilevel, no matter whether their data are suitable for it or not. My reaction to about 2/3 of the questions with this tag on this site is that the goals of the study (except for being published in a highly ranked journal, which is often THE goal of many studies) are better addressed by other methods. In multilevel analysis, you have to make strong assumptions: (i) that your random effects are normal (or, if you have random slopes as long as random intercepts, that the joint distribution is multivariate normal), (ii) that your model contains all relevant variables, so that you are safe assuming that errors and regressors are uncorrelated at all levels, (iii) you have enough observations at each level to really utilize the asymptotic theory results concerning the likelihood ratio test statistics and inverse of the information matrix as the estimator of the variances of the parameter estimates. These assumptions are swept under the carpet, most of the time, and rarely if ever checked. The methods that deal with them do exist, but they would require a Ph.D. in statistics to read them. There are also alternative Bayesian solutions which too require a solid stat sequence in Bayesian computing before you even dare to open these papers.
OLS with clustered errors makes fewer assumptions: something like (ii) above, i.e., to be able to convince yourself that the regressors and errors are uncorrelated, and something like (iii), that you have enough clusters so that the variance-covariance estimate is obtained as a sum over sufficiently many independent terms. Note that you don't need to have asymptotics in terms of the number of observations per cluster, unlike multilevel models. An unpleasant side effect concerning OLS with clustered standard errors is that you may run out of degrees of freedom if you have a model with 40 variables and only 30 clusters. (Well if you have 30 clusters, you're screwed anyway.)
An interesting feature of multilevel models is that they can address interactions between levels (e.g., how does the education and experience of a teacher affect the student gains?) It is messier, but possible, to address in OLS as well by explicitly constructing the interactions and using them as explanatory variables in your regression.
With enough data, you can run both analyses and construct a Hausman specification test on the difference between the efficient estimator (multilevel model) and a less efficient and more robust estimator (OLS with clustered standard errors) for the parameters that both models estimate. Most of the time, I would trust the OLS with clustered standard errors more than I would multilevel analysis, frankly.
Comment: A little niggle: I don't think you need a phd in statistics to deal with random effects correlated with regressors by adding averages of individual level covariates as predictors for group level intercepts. This fixes assumption ii) across levels, and if you don't like it within level then you ought to think twice about regression models altogether.


Single-node SLURM server: restrict interactive CPU usage

Question: I have SLURM setup on a single node, which is also a 'login node'. I would like to restrict interactive CPU usage, e.g. outside the scheduling system.
I found the following article which suggests to use cgroups for this: https://rolk.github.io/2015/04/20/slurm-cluster
I thought this was perfect and set it up in the following way:
/etc/cgconfig.conf:
group root {
        cpu {}
}

group interactive {
        cpu {
                cpu.cfs_period_us=100000;
                cpu.cfs_quota_us=400000;
        }
}

group batch {
        cpu {}
}

/etc/cgrules.conf:
root             cpu    root
slurm            cpu    batch
*                cpu    interactive

I use cgrulesengd to apply these rules.
The problem is that tasks properly queued using SLURM also run under the respective user's own user (and not slurm), so they get put in the interactive cgroup. Of course, this is not what I want. I assume the article I followed expected that the tasks would get run under the slurm user.
Is there a way to put all tasks run by SLURM in the right cgroup?
Answer: I have been beating my head against exactly this problem for a while now and I finally came across this solution on stackexchange: https://unix.stackexchange.com/questions/526994/limit-resources-cpu-mem-only-in-ssh-session. My answer below is adapted from that. First, create your limited "interactive" cgroup in /etc/cgconfig.conf:
group interactive {
   perm {
      admin {
         uid=root;
         gid=root;
      }
      task {
         uid=root;
         gid=shelluser;
         fperm=775;
      }
   }
   cpu {
      cpu.cfs_period_us = "1000000";
      cpu.cfs_quota_us = "500000";
   }
   memory {
      memory.limit_in_bytes = "8G";
      memory.memsw.limit_in_bytes = "8G";
   }
}

We've added the perm{} subsection, which will enable user accounts to place themselves into this cgroup using cgclassify (I think, but do not know for sure, that they won't have permission to then remove themselves from that group, however that may be a loophole in this process. For my purposes, it's a potential loophole I'm willing to accept given my user base). The task{} section dictates who is allowed to assign tasks to the cgroup. In this case, we set the tasks file to group-writable and owned by the 'shelluser' group. You'll need your users to be members of this group or none of this will work.
Now, create the script /etc/profile.d/ssh.sh. In this script we'll assign ssh sessions to the 'interactive' cgroup, thus preventing users from hogging system resources directly. However, sometimes you do need to run some things interactively, so I've allowed interactive sessions spawned by slurm to run unrestricted. Again, the way I've done this is almost certainly exploitable by a clever user, but it's a risk I'm willing to accept given our users:
# check if user is in an SSH session and *hasn't* been spawned by slurm
if [[ -n $SSH_CONNECTION ]] && [[ -z $SLURM_JOBID ]]; then
  # get the shell pid
  SESSIONPID=$$
  # attach the shell to the relevant cgroup
  cgclassify -g memory,cpu:interactive $SESSIONPID
  # now everything spawned by this shell should be in this cgroup
fi

Users logging in via SSH will be placed in the 'interactive' cgroup on login (provided they're members of the 'shelluser' unix group). In that case they'll be limited to 8G and 1/2 of one CPU. If they need to be able run stuff directly without limits, they can spawn a bash instance under slurm with
$ srun -p <partition> -c <cpus> --mem=<mem> -t <time> --pty /bin/bash

And it should run  unrestricted.


WordPress plugin Elementor not working with custom theme

Question: When trying to edit with Elementor on my website I get, "The preview could not be loaded" "We're sorry, but something went wrong. Click on 'Learn more' and follow each of the steps to quickly solve it."
I have tried looking at the steps it provided but that didn't help.
Any assistance would be greatly appreciated.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: Make sure that your theme uses the function the_content()


GPO will only work after an Admin logs in with same policy being applied to the admin account

Question: I have created a GPO that will put a shortcut on our receptionists desktops that is linked to a file share that is full of Internet shortcuts for Insurance verification. This has worked for almost 90% of my users. I have that remaining 10% that just don't want to behave. I can run gpresult /r and see that the result of the GPO should be displaying but it isn't. The only thing that I've found will "jump start" the GPO is if I log into the problem machine and I have the policy applied to the OU my user account is a member of. If I log into the machine without the policy being applied to my account the domain users experience will not change. So something must be happening to the system when I log in as a domain admin and have the policy applied to my account that then allows all other domain user accounts to accept the policy when they log in after me. I haven't found a lot out there googling this topic. The GPO is a user Policy. Any ideas?
Comment: Does the GPO place the shortcut in the Public / All User's folder ? If so can be a local security problem. How you push the shortcut too ? Thougth to create a GPP's GPO and create it directly with the %desktop% location ? No need for a central's file and it's place on the user's own desktop directly.
Comment: That was it. I was trying to send it to the "All Users Desktop" location. After changing it to just "Desktop" it began working for all users. I'm interested to know why that is the case. I can admit I don't understand systems deeply enough to know what security settings are being affected by each setting. Thank you for you suggestion and help!
Comment: It's because that folder is restricted to admin only, so if a infected user log into the computer, it cant go write there. For security purpose the user is directly restricted to it's c:\users\folder only :)
Comment: oh, will write the tip as an answer too :)
Answer: If the GPO place the shortcut in the Public / All User's folder, then it's a local security problem.
The way you push the shortcut can be made other some other way. Like with a GPP's GPO and create it directly with the %desktop% location. No need for a central's file and it's place it on the user's own desktop directly.
A restricted user by default can only write in it own's profile.
The description from Microsoft;

What is a standard user account?
A standard user account lets a person use most of the capabilities of
  the computer, but permission from an administrator is required if you
  want to make changes that affect other users or the security of the
  computer.
When you use a standard account, you can use most programs that are
  installed on the computer, but you can't install or uninstall software
  and hardware, delete files that are required for the computer to work,
  or change settings on the computer that affect other users. If you're
  using a standard account, some programs might require you to provide
  an administrator password before you can perform certain tasks.


Metric Space Axioms

Question: I've been reading about metric spaces recently and had a question about the definition. Everywhere I've seen, we take a metric space to be a set $E$ equipped with a metric, a binary map $d:E\times E\mapsto \mathbb{R}$, where $\forall x, y, z\in\mathbb{R}$,  $d$ satisfies:

$d(x, y) \geq 0$
$d(x, y) = 0 \iff x = y$
$d(x, y) = d(y, x)$
$d(x, z) \leq d(x, y) + d(y, z)$

It isn't difficult to see that axioms $2$, $3$, and $4$ imply $1$, so $1$ doesn't add anything to the definition and is superfluous. Why then do we keep 1 as an axiom in the definition of a metric instead of it being a corollary to the definition?
Comment: Perspicuousness.
Comment: or better yet, just define $d$ to be a function $d\colon E\times E \to \mathbb{R}_{\geq 0}$.
Comment: btw, you probably mean $\forall x,y,z\in E$.
Comment: Convention, history...
Answer: In fact, it is enough to require only that
$$d(x,y)=0 \textrm{ if and only if } x=y$$
and
$$d(y,z)\leq d(x,y) +d(x,z)$$
All other properties of the metric follow from these, including
nonnegativity.
Comment: How does (3) follow from these?
Comment: Nevermind, I see the slight of hand now. ;)
Answer: There is obviously no need ;
But since "Metric Space" deals with  distance function and the distance between any two objects is always non-negative so the axiom is added to mark its significance.

Metric Space Axioms


What makes an interval "perfect"? Is this scale-dependent?

Question: Ok, so I am very curious about why the major scale 4th and 5th are deemed "perfect" while other intervals are "major."  This may just be an arbitrary thing based on sounds we find pleasing, but I've been at least trying to find something more rigorous.  I did notice one thing.
If you take the C major scale, C D E F G A B C, we know there are 12 semitones from C to C.  The 4th, F, is five semitones from C, and the 5th, G is at 7 semitones from C.  5 + 7 = 12.  In other words, if you choose either one of those notes and find its distance from C in semitones, then it turns out the remaining number of semitones to reach 12 is the position of a note that is IN THE SCALE AS WELL.
If you check D, the 2nd, it's at 2 semitones, and you'd need 10 to get to 12, but the scale doesn't have a note 10 semitones above C.  Similarly for E, the 3rd; it's 4 semitones from C, and there is nothing in key at 8.  F and G, the 4th and 5th, are unique by this criterion.
Ok, so far so good.  I then said to myself, "Ok, the major scale is the Ionian mode.  What about the other modes?"  So I proceeded to walk through all seven of them, and the answer varies from mode to mode.  Specifically, you get this:
Ionian: 4th+5th
Dorian: EVERY SINGLE NOTE
Phrygian: 4th+5th
Lydian: 4th only (it's 6 semitones above the root, so it's its own partner)
Mixolydian: 4th+5th and 2nd+7th
Aeolian: 4th+5th and 2nd+7th
Locrian: 5th only (same story - it's 6 semitones above the root)
So this is all very interesting.  But really I'm just a mathematically-inclined engineer with a strong curiosity about music theory.  I'm primarily self-taught using the internet.  So my question is simple:
Does what I laid out above actually mean anything?  Or is it just a curious coincidence?  I don't really believe in coincidences - usually when something this intriguing shows up there's a reason for it.
As a possible motivator for insights, the Aeolian mode is the natural minor scale, and in addition to 4th+5th that one has 2nd+7th.  So is there any existing knowledge out there about the 2nd and 7th intervals taking on any new prominence in the natural minor scale?
One more interesting thing.  If you use the circle of fifths to "order" the modes, you get this order:
Lydian: 4th only
Ionian: 4th+5th
Mixolydian: 4th+5th, 2nd+7th
<code>                                 MAJOR ABOVE
</code>

<code>                                 MINOR BELOW
</code>
Dorian: Every note
Aeolian: 4th+5th, 2nd+7th
Phrygian: 4th+5th
Locrian: 5th only
There's structure and pattern there...
Answer: To your first question, an interval is named perfect when inverting it results in another perfect interval. This is a source of confusion and mystery for no small number of musicians, but it's actually fairly straightforward.
In all cases, the logic is commutative.
When you invert a perfect interval, it becomes perfect.
When you invert a major interval, it becomes minor.
When you invert an augmented interval, it becomes diminished.
It breaks down like this:
Augmented - Major - Minor - Diminished
Augmented - Perfect - Diminished
Fourths, fifths, unison, and octaves are all perfect intervals.
What your analysis of the existence (or non-existence) of a note at 12 semitones minus the number of semitones from the root away is basically doing is getting to this point in a very... erm, roundabout way.
The second is a very important note in the minor scale and the seventh is a very important note in every septatonic scale, but on this subject one could write a book.
Comment: Do you see what I meant about it seeming arbitrary?  C-G is a 5th.  G-C is a 4th.  So the definition seems to be saying that the 5th is perfect because the 4th is perfect, and the 4th is perfect because the 5th is perfect.  It's circular.  If I just decided to call the 3rd C-E and the 6th E-C perfect, then the same conditions would be satisfied.  I'm trying to find something inarguably unique about perfect intervals.
Comment: My concern with that definition is that it seems arbitrary - you've picked both of the perfect intervals, and they're inversions of each other.
Comment: Ooops - didn't realize it was going to submit on enter.  Continuing, if the inversion also has to be in the scale, that's getting a bit more demanding.
Comment: Interval names have nothing at all to do with scales, really. It is nevertheless true that if both notes of an interval are in a key, then the inversion of that interval is in that key. I'm not sure how that's relevant, however.

There are, by the way, far more than two perfect intervals. There's an infinite number, and it is still true that a twelfth -- a perfect interval -- inverts into a perfect interval and is therefore so named.
Comment: You can't call C-E perfect because when you invert it the corresponding interval isn't also perfect. There is E-C# to consider.
Comment: Well, that seems to bring me to what I talked about in the original post.  I see that C-E is 4 half steps, and E-C is eight half steps.  And eight half steps from the root isn't an interval that's in my scale.   When you say "there is E-C# to consider," what exactly do you mean?  I'm sorry - I'm not trying to argue but just to understand.  I appreciate the time you're taking to answer.
Comment: As I said in my answer, this is a very common blind spot in theory knowledge for a lot of people, so I absolutely don't blame you. There is E-C# to consider because this is is also a sixth; the argument you set forth in your previous comment is that the naming is arbitrary because you can call any two set of intervals perfect, but you can't: If you call C-E a perfect third and E-C a perfect sixth, what do you call E-C#? An augmented sixth? Is C#-E now a diminished sixth? What of C#-Eb and its inversion? This comment is getting long so I'm going to break it up.
Comment: The way that you're trying to analyze interval names is very divorced from the actual process of naming intervals. As I said previously, interval names have nothing at all to do with scales and I'm not totally sure why you're trying to analyze it from that perspective. If I understand what you're doing correctly, the correlation between an interval being named perfect and satisfying the criteria you've set up is simply because the major scale, like most commonly-used septatonic scales, puts the non-octave perfect intervals right in the middle.
Comment: @Fugu you are just arguing about names, not things. Nothing in *music* would change if C-E was called and "Ermyntrude third", and C#-E a "Zebedee third", and C-G a "Dougal fifth." (Google "Magic Roundabout characters" if you don't get the references.) The only justification for a particular name is that everyone knows what it means!
Comment: ... there is no more logic behind the use of "perfect" and "imperfect" than the names used for rhythms in mensural notation (before 1600) when rhythmic divisions into three parts were called "perfect" (by analogy with God and the Holy Trinity) and divisions into two were called "imperfect". When religious dogmatism is sufficient reason for something, you don't need logic!
Comment: Sure, it doesn't matter whether they're called perfect or kdfjhdfkgd, but that's not the point: The point is that perfect is distinct from major and you can't conflate the two without losing the meaning of one or both terms.
Comment: So, maybe this will help me, Fugu.  Do you always call the 4th and 5th in a scale perfect, or is that term reserved for intervals of 5 and 7 semitones, respectively?
Comment: Because those are the ones that correspond to the ratios 4/3 and 3/2 in terms of frequency.
Comment: The fourth and the fifth of a scale are not always perfect intervals. As I said before, there is no connection between interval terminology and scales. Take a look at C major pentatonic: C D E G A. The fourth degree of this scale is a perfect fifth, but the fifth degree is a major sixth. Here's another scale, the rather obsucre B super locrian diminished: B C D E F G Ab. Here the fourth is perfect but the fifth is diminished. It's no accident that the major scale (and most commonly used septatonic scales) have perfect fourths and fifths from the root in them, but it's not why they're named.
Comment: Ok.  Then the perfect intervals are those where the upper tone is 4/3 or 3/2 of the lower one, or some octave derivative of those.
Comment: Or 1/1 or 2/1 (to get unison and octave).
Comment: Like leftaroundabout said.
Comment: Sure, but that's a happy accident and not why they're called what they are. That has to do with inversions.
Comment: Alright, I had some time to think about this, and this is the best way I can explain this: Let's say we're no longer going to drive a distinction between major/minor and perfect. So now we have a major octave instead of a perfect octave. What happens when we invert the major octave? Because major intervals, when inverted, become minor, we now have to call this a minor octave, even though it's the same two notes. We now have two names for the same interval, which is impossible: Fundamentally, each set of two notes can be described by only one interval name.
Answer: An interval is perfect when it can be derived unambiguously as a Pythagorean ratio, i.e. when the frequency ratio is f1⁄f0 = 2 k · 3 j for some k, j ∈ ℤ. That includes beyond doubt

Octave: f1⁄f0 = 2, which is a span of 1200 ct
Fifth: f1⁄f0 = 3⁄2, or 702 ct
Fourth: f1⁄f0 = 4⁄3, or 498 ct

...and compounds thereof. Now you may say, but why isn't every interval perfect then – can't you just traverse the circle of fifths..? – that's why I wrote unambiguously. You can indeed stack those perfect fifths, but that's not compatible with post-1600 Western harmony, which also makes use of frequency ratios including the number 5.
For all of the intervals from Western standard theory save the ones above, there are thus at least two intonation ratios available, and it's not possible to say universally which one is right: it depends on the context (and to some degree, the performer) which one is chosen.

Major third: either 5⁄4 (386ct) or 81⁄64 (408 ct)
Minor third: either 6⁄5 (316ct) or 32⁄27 (294 ct)
Major second: either 9⁄8 (204ct) or 10⁄9 (182 ct)

and so on.
Comment: I'm not convinced there is any historical justification for this logic. It doesn't fit with two inconvenient facts: (1) the catholic church decreed than 4ths and 5ths were "perfect" and 3rds and 6ths were "imperfect," and (2) the same church, at the same time, decreed that the size of a major third should be 81/64 and nothing else - tuning systems using the 5/4 ratio were forbidden. Of course they had a 1,000 year track record of making dogmatic pronouncements *before* they made those two, so nobody much argued (except the peasants who carried on using 5/4, but they didn't count for anything!)
Comment: Well, I think your answer is certainly  mainstream, but it does bring us back to a human judgement call - we're giving preference to the tones that arise from the smallest integers in the calculations.  A line was drawn.  And that's fine - it may be that the ultimate answer is "because those sound special to us, and we decided."  I still think the pattern I observed is pretty interesting, though.  :-)
Comment: Note that many modern players use 12-TET, so each semitone is actually just 1/12 of an octave higher. Unless you're a stringed, fretless instrumentalist or a vocalist, your instrument (mostly) determines your tuning for you. (Yes, I know how wind instruments can bend their pitch and those which are tuned to a key exist.)
Comment: @CAD97 apart from the fact that you could easily turn that statement around ("unless you're a keyboard-, fretted-string or valved/keyed wind instrumentalist...") it's doesn't refute my point. In 12-edo, the impure intervals are _literally_ imperfect in the sense of always being significantly out of tune.


Como verificar corretamente o status de um Checkbox em js?

Question: Preciso de uma funcionalidade em que os Checkbox estejam aninhados entre si.
Dessa forma, o elemento pai selecionaria todos os filhos e assim por diante.
Minha lógica foi a seguinte:

Como vou receber esses dados externamente, eu consigo manipular os ids e as class desse checkbox
  Assim, se eu criar uma classe pai que tem em todos os atributos que receberão essa funcionalidade e concatenar uma class específica aos filhos, eu tenho uma relação entre os dois.

Exemplo: o elemento cujo a class  é pai e o id é idPai, teria uma relaçao a todos os checkbox cujo a class seja filhoidPai
Essa é a estrutura do HTML que eu utilizei:

Checkbox

            <input class="form-check-input pai" type="checkbox" id="idPai">

                Checkbox exemplo

                    <input class="form-check-input filhoidPai"  type="checkbox" id="idOption1">

                        Checkbox exemplo

                    <input class="form-check-input filhoidPai" type="checkbox" id="idOption2">

                        Checkbox exemplo

Nesse código vemos que o idPai tem a class pai, portanto ele controla o estado de todos que tem o seu nome (nesse casso, todos os filhoidPai).
Dessa forma, para esse problema o script abaixo atende a minha situação:
$(".pai").on("change", function (e) {
    var select = ".filho" + $(this).attr("id")

    var isChecked = $(this).prop('checked');

    $(select).each(function (e) {
        $(this).prop("checked", isChecked);
    })
});

Porém (é ai que vem a dúvida), quando eu tento adicionar mais um nível nessa hierarquia (ou seja, um pai que também é filho), as coisas ficam um pouco diferentes...

Checkbox

            <input class="form-check-input pai" type="checkbox" id="idPai">

                Checkbox exemplo

                    <input class="form-check-input filhoidPai"  type="checkbox" id="idOption1">

                        Checkbox exemplo

                    <input class="form-check-input filhoidPai pai" type="checkbox" id="idOption2">

                        Checkbox exemplo

                            <input class="form-check-input filhoidOption2" type="checkbox" id="idOption2SubOption">

                                Checkbox exemplo

Ao meu ver, a função change alteraria o status de todos os checkbox na hierarquia, coisa que não acontece.

Quando o idPai é acionado, automaticamente todos os filhoidPai são acionados também (inclusive o que é filho e pai). Da mesma forma que quando o idOption2 é acionado, todos os filhoidOption2 também são. O problema é que quando idPai for selecionado, eu queria que eles acionasse tanto os filhos quanto os filhos dos filhos, tornando-a, uma função recursiva.
Alguma ideia de como fazer isso?
Answer: Há algumas formas:

Adicionar a classe idPai nos netos. Ex: class="form-check-input filhoidOption2 idPai"; ou
Usar uma classe com o nome que possua todos os níveis.

Ex: class="pai", class="filho-1", class="filho-2", class="filho-1-1" (neto)

Percorrer todos os input:checkbox com a função .find

Optei fazer um exemplo usando este método. Para isso, usei a função .parents() para retornar ao elemento pai .form-check e, logo após, utilizei o método next para ele pegar o elemento ul irmão.
Como a estrutura é sempre (div.form-check > input:check) + ul, vai funcionar corretamente. Com isso, podemos usar o método .find() para buscar os input:checkbox daquele pai específico.
Exemplo:

$(".pai").on("change", function(e) {
  var filhos = $(this)
    .parents('.form-check') /** Seleciona o elemento pai `.form-check` */
    .next('ul') /** Busca o elemento `ul` irmão do pai */
    .find('input:checkbox') /** Seleciona todos os `input` do tipo `checkbox` */

  var isChecked = $(this).prop('checked');

  $(filhos).each(function(e) {
    $(this).prop("checked", isChecked);
  })
});

Checkbox

      <input class="form-check-input pai" type="checkbox" id="idPai">

                Checkbox exemplo (Pai)

          <input class="form-check-input filhoidPai" type="checkbox" id="idOption1">

                        Checkbox exemplo (Filho)

          <input class="form-check-input filhoidPai pai" type="checkbox" id="idOption2">

                        Checkbox exemplo (Pai e Filho)

              <input class="form-check-input filhoidOption2" type="checkbox" id="idOption2SubOption">

                                Checkbox exemplo (Neto e Filho)

Comment: @WalterFelipe Funciona com diversos níveis de hierarquia, desde que tenham a mesma estrutura (expliquei-a no 3º parágrafo). Também é possível marcar o pai ao marcar o filho e vice-versa, mas isso foge da pergunta principal. Recomendo que crie outra com as novas dúvidas. Caso contrário a moderação do site poderá reverter sua pergunta para a original.
Comment: Esse procedimento funciona se eu criar uma nova hieraquia de checkbox? (ou seja, o próximo pai interfirirá nos filhos do outro pai?)
Comment: E eu sei que isso não é mais pertinente a minha pergunta, mas tem como desmarcar o pai ao ter todos os filhos desmarcados? E se sim, há alguma forma de ao marcar um filho, ele encontre o pai e o marque também?


Which steel strings are more suitable for fingerpicking on acoustic guitar?

Question: I want to ask acoustic guitar experts, what strings can be suitable for fingerstyle playing on steel string acoustic if I play with my fingers - no nails or fingerpicks. Currently I'm using GHS infinity bronze, but they are very hard and give me a pain in the fingers.
What type of steel strings are more close to nylon feel, which are softer?
Comment: Growing finger nails may also take some pressure of your fingertips.
Answer: Steel strings are under higher tension than nylon, so, whether they are round-wound, flat-wound or taped, they will still require greater pressure to fret and pick.
You can go to a lighter gauge, which will reduce the pressure needed, but your sound will become brighter, and the bass response of the guitar will be reduced; you're moving less metal, which means the vibrations transmitted to the guitar top via the bridge and nut will be less. It also could cause fret buzz because the lighter strings won't pull on the neck as hard. If you have an adjustable truss rod you might need to reduce its tension a bit.
An option I used to use on a 12-string was to go with silk and steel strings. They're lower tension and kind of a hybrid between nylon and steel. Again, you might need to have your guitar neck adjusted with them. And, again, they will affect the sound of the guitar.
I'd recommend going to talk to a good guitar technician and let him look at your guitar. It might be that your current string gauge is unnecessarily high and you could drop to a bit lighter string, change to a different type, such as using a bronze-string, and keep a pleasing tone while reducing some pressure on your pickin' fingers.
Finally, your fingers will adjust and eventually you won't notice. You might want to pick a bit lighter and look into miking your guitar or using a pickup when you need to be heard by an audience. There's a happy balance between getting lots of volume and retaining skin on your fingertips, and electronics can play a good part.
Comment: I remember reading somewhere that Tommy Emmanuel used 13! :O
Answer: There are no steel strings "close" to nylon. You cannot use nylon on an acoustic guitar designed for steel strings(you can but eventually you'll be sorry).
Acoustic steel strings are heavy and as a result more stiff. There are special techniques when creating strings to make them more flexible such as using a hex core or double wrapping(this is more for bass guitar strings).
Your fingers are going to hurt until you build callouses on them. The same thing applies to electric guitars.  Our fingers weren't designed to be scraping and pulling against small still wire.
Either change styles and get a classical style guitar, use fake fingernails, or get used some callouses. You can change the string size a little but you'll still have that problem until you get callouses.
How long have you been playing? If it's a short time then just keep playing. If it's a long time and no callouses then either you do not have callouses or something odd is happening(such as picking way to hard but even then callouses should take care of it).
I have had tingling/pain in my fingers before but it usually happens when I do not play for a while then come back and play a lot. It goes away after a while but I usually slow down playing when it "hurts" to give my fingers a rest. Eventually they toughen up and it's all ok.
Answer: Martin makes steel strings expressly for fingerpicking called the FX series (flexible core)  The FX640 light is 80/20 bronze, and the FX740 light is phosphor bronze which will last a bit longer
Answer: I play fingerstyle on steel strings, have for many years.  I keep my nails about the same as would a classical guitarist; just long enough to break across the string as the stroke is made.  It's a combination of nail and flesh that classical players find produces the best tone, and I find it works very well for steel string as well.
No nail at all results in a rather dull tone that might improve as you develop a little callous...
Long nails, long enough so that no flesh contacts the string, are very fragile and likely to split or crack or chip...   Some folks have sturdier nails than others, of course.
Answer: I have been using the Martin FX 740 Light, phosphorous bronze for close to a year, fingerpicking on an Epiphone (Expedition) and it has, and continues to be an absolute pleasure. I play daily, and last thing at night.
Cheers
Mandy Rice
email@example.com
Answer: I play on martin acoustic extra light (the purple package). I play fingerstyle a lot. I advise you to actually try out different gauges / brands and materials. I find phosphore bronze less interesting soundwise. I feel the sound is flat. I always go for 80/20, extra light. It is true that it buzzes a little on the frets but I like it that way.
If you play fingerstyle you want flexible strings.
I have tryed heaps of strings. Everyone is different so yep, hope this is helpfull


Flutter websocket + spring. WebSocketChannelException: [object Event]

Question: For the second day I can not make my flutter mobile application receive messages via websocket.
As I understand it, I use StompClien to work with Websocket message broker
There is only one error from the logs: WebSocketChannelException: [object Event]
I could not find information anywhere on the Internet either on this error or on how to work with web sockets on flutter.
I would be extremely grateful for any help!
Config from spring:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/ws");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        registry.addEndpoint("/our-websocket").withSockJS();
    }
}

flutter app
StreamController<List<String>> streamController = StreamController();
String ws_url = "ws://localhost:8080/our-websocket/websocket";
String destination = "/topic/messages";
String message_destination = "/ws/message";
var _listMessage = <String>[];

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: MyApp(),
  ));
}

void onConnect(StompFrame frame) {
  stompClient.subscribe(
    destination: destination,
    callback: (frame) {
      Map<String, dynamic> result = json.decode(frame.body!);
      //receive Message from topic
      _listMessage.add(result['content']);

      //Observe list message
      streamController.sink.add(_listMessage);
    },
  );
}

final stompClient = StompClient(
  config: StompConfig(
    url: ws_url,
    onConnect: onConnect,
    onWebSocketError: (dynamic error) => print(error.toString()),
  ),
);

...(application rendering)

The spring web socket works if you use a web application as a frontend. js does exactly what I want it to do.
Answer: at the method inside registerStompEndpoints, use
registry.addEndpoint("/our-websocket").setAllowedOrigins("*");

and also in the flutter ws_url variable, write "ws://localhost:8080/our-websocket"


Como pegar lista de todas as actions de todas as controllers, inclusive de Plugins?

Question: Estou tentando pegar todos os methods/actions de todas as controllers de minha aplicação CakePHP.
Acontece que não consigo trazer os métodos de todas as controllers e não entendo o motivo.
Tentei importar App::import e com App::uses, mas o get_class_methods() não retorna os methods/actions de todas.
Segue o que eu criei:
//Pega a lista de controllers da aplicação e adiciona num array;
$controllersApp = App::objects('controller');
//Varre o array de controllers da aplicação e adiciona cada item num array global
foreach($controllersApp as $c)
    {
        $temp_listControllers[] = $c;
    }
//Pega a lista de plugins
$plugins = App::objects('plugin');

//Varre o array de plugins
foreach($plugins as $plugin)
    {
        //Cria string para pegar lista de Controllers de cada Plugin: Plugin.controller
        $p = $plugin.'.controller';

        //Pega lista de controllers do Plugin corrente em $plugin
        $lista = App::objects($p);
        //Varre o array de controllers do Plugin corrente e adiciona cada item no array global
        foreach($lista as $l)
            {
                $temp_listControllers[] = $l;
            }
    }

foreach($temp_listControllers as $c)
    {
        //$r = str_replace("Controller", "", $c);
        $listControllers[] = $c;
    }

foreach($listControllers as $controller)
    {

        $actions = get_class_methods($controller);
        echo "

".$controller."
";
        pr($actions);
    }

Estou fazendo algo errado? Existe alguma outra forma de fazer isso?
Answer: Tente utilizar Configure::listObjects();
Eis aqui um exemplo.
Comment: não tenho como testar esse método no momento, mas espero conseguir ajudar.
Comment: Então, estou usando uma versão 2.3.1 do CakePHP. Acontece que verifiquei na documentação do CakePHP e não encontrei em nenhuma versão o método getInstance da Class Configure. Dá o seguinte erro quando executo: Error: Call to undefined method Configure::getInstance()


Is it possible to place a fielder other than standard fielding positions?

Question: Is it permitted to place the fielders other than the standard fielding positions terms in international cricket match?
To be more specific,
can a fielder be placed in

between the mid-on and long-on
straight back to keeper on the circle
straight back to the bowler on the circle
any other place which is not yet been given a place term(like fine leg, point..)

Refer the red circles in the below image
Answer: Yes, such placements are generally allowed. Neither the MCC's Laws of Cricket nor any of the ICC's Playing Conditions rule any such placements out.

There are a number of named basic fielding positions, some of which are employed very commonly and others that are used less often. However, fielding positions are not fixed, and fielders can be placed in positions that differ from the basic positions. Most of the positions are named roughly according to a system of polar coordinates - one word (leg, cover, mid-wicket) specifies the angle from the batsman, and is optionally preceded by an adjective describing the distance from the batsman (silly, short, deep or long). Words such as "backward", "forward", or "square" can further indicate the angle.

Wikipedia

But keep in mind the fielding restrictions:

Fielders may be placed anywhere on the field, subject to the following rules. At the time the ball is bowled:

No fielder may be standing on or with any part of his body over the pitch (the central strip of the playing area between the wickets). If his body casts a shadow over the pitch the shadow must not move until after the batsman has played (or had the opportunity to play) at the ball.
There may be no more than two fielders, other than the wicket-keeper, standing in the quadrant of the field behind square leg. See Bodyline for details on one reason this rule exists.
In some one-day matches:

During designated overs of an innings (see Powerplay (cricket)), there may be no more than two fielders standing outside an oval line marked on the field, being semicircles centred on the middle stump of each wicket of radius 30 yards, joined by straight lines parallel to the pitch. This is known as the fielding circle. In addition, during these overs there must be two fielders (other than the wicket-keeper) in designated "close catching" positions.
For the remainder of the innings there may be no more than four fielders standing outside the fielding circle.

The restriction for one-day cricket is designed to prevent the fielding team from setting extremely defensive fields and concentrating solely on preventing the batting team from scoring runs.

Wikipedia
Comment: I've cut this off at the pass and removed the incorrect statement in the wiki page about players behind the keeper. Answer updated accordingly. If someone wants to add it back into the wiki page they should provide a citation.
Comment: @Bogdanovist Good idea. Unfortunately, looks like your Wikipedia edit was reverted, possibly by someone imagining it to be vandalism.
Answer: 1) This position is called deep mid on and is a perfectly legitimate position usually used when the batsmen is chipping over mid on but not trying to carry all the way for six.
2) Another perfectly legitimate position, this is called short stop (as opposed to the man on the fence, long stop), and is often seen in village cricket when a low quality wicket keeper is standing up to the spinner.
3) This is actually an illegal position as it is obstructing the batsmens sight line behind the bowlers arm, and he is perfectly at liberty to ask the opposition captain to move him to one side. The straight man on the fence you have drawn is similarly in an illegal position.
4) Where you have drawn the circle would probably be described as 'cow corner but twenty yards in', and used when a guy is slogging but not strong enough to clear the field.
Basically fielders can be placed anywhere except on the wicket, straight behind the bowlers arm, and no more than 2 behind square on leg. Ive seen a field of 3 slips, gully, third man, midwicket, forward cow corner, cow corner and backward cow corner set to a batsmen - the batsmen first drilled the ball over the three cow fielders for six, second ball swing and miss, third ball hit it straight to one of the cow fielders. If the batsmen had limited strokes the fielding captain is perfectly at liberty to put all his fielders where he knows the batsmen will hit it.
Comment: Your last paragraph is not quite true.  A fielder's shadow must not be cast on the wicket.