Cadence in Haydn's String Quartet in G, Op. 54, No 1, i, 1-13

Question: I'm studying with a book called "Analyzing Classical Form" and it says that the cadence in this piece starts it's cadence on the 2nd half of m 10 but that's a III(5) and I'm so confused.
Download the piece
If I analyzed it correctly it goes like this:
m10.5:  III(5)
m11:  IV (Csus#4 but I think it can be described as the IV)
m11.5:  II
m12:  I(64)
m12.375:  I(764)
m12.5:  V(7)
Repeated for 3 times (eights)
m12.875:  vii°(9)
m13: I
Can anyone explain to me why the cadence starts on m10.5?

Why does this Cadence start on a III? I've heard people calling it everything from Tonic to substitute Dominant so I'm confused.
Why does it go D-Pd-T-D-D-T
(Pd = pre-dominant)

If the normal structure is T-PD-D-T for a perfect authentic cadence does that mean that I could insert (in common time and 1 chord per bar) 2 Dominants with half a bar of length for the D?
PS. At this point even my confusion is confused so don't be sacred to write a long answer, it'd help me a lot. Just explaining from ground up why for God's sake this is a complete cadence (I get that eveything is in there but the order and the amount of chords is what confuses me)
Comment: The second half of measure 10 is a I⁶, not a iii. The next measure indeed contains two slightly different harmonies (IV ii⁶) that together form the PD; this is a common expansion of the predominant sometimes referred to as the IV-ii-complex.
Comment: What you describe as I(64) is really V with a suspension 6-5 and 4-3. This is a [cadential six-four](https://en.wikipedia.org/wiki/Inversion_(music)#Cadential_six-four), which is an idiomatic way to prepare a cadence (although in this example the voices get exchanged before they get resolved). This is not a tonic.
Comment: Where on the website does it say that the cadence starts on Measure 10? For that matter, where are the questions for that section? I see 4 answers in the link, but no questions.
Comment: The questions are in the book, question 4 is "Where does the cadential progression begin? Is it complete or incomplete?" My bad, I forgot to refer to them in the main question, sry
Comment: Thanks a lot, that was so helpful :). One more question: If I see this correctly it's iii-IV-ii-V-I a.k.a. T-Pd-Pd-D-T is that correct? I'm just not sure but I think that in this case the iii is counts as a tonic as it doesn't substitute for a dominant, right? Also do the two Pds count as one? That would make it a typical T-PD-D-T.
Comment: Oh wow, that explains a lot. No idea how imessed that one up. Thanks dude, people like you are why I live this forum ^^
Comment: I have combined my comments together with some examples from different periods into an answer. I hope this helps.
Answer: What you describe as I(64) is really a dominant V with a suspension 6-5 and 4-3. This is a cadential six four, which is an idiomatic way to prepare a cadence. This is not a tonic. In this example, the voices get exchanged before they get resolved.
The idea of embellishing the dominant through some sort of suspension is extremely common in the common practice period. Here are some examples (you should listen to a little bit before the linked excerpts as well to get an idea of the tonality):

Händel, Zadok the Priest, cadence at the end of the orchestral introduction. This pattern is sometimes called a double cadence (see e.g. this website), and consists of a held V in the bass with a four chord embellishment happening on top. Very typical of baroque and (early) classical.
Tchaikovsky, Overture 1812, final cadence before the coda. This only uses the 4-3 suspension.
Mahler, Symphony no. 1, final cadence in the last movement. This uses an extensive 6-5, 4-3 suspension, where the final resolution only arrives a full 16 measures (20 seconds) later. This type of extended cadential embellishment is common in the romantic period (although they'll also make you wait a bit for the dominant to arrive in the first place...).

Eventually you wear learn to recognise these quickly, both aurally and visually. The tonic-sounding chord but with a 5 in the bass is often a signifier of a cadence coming up.

The two predominants IV and ii⁶ are often combined to form a predominant expansion. This is sometimes called the IV-ii complex. In terms of voice leading, the only thing you need to do is move scale degree 1 (G in this piece) to scale degree 2 (A).
If the ii⁶ moves directly to a dominant V (without cadential six four), the A can be viewed as an anticipation of the A in the V harmony. This can help avoid parallel fifths, which is probably how the IV-ii complex originally came about.
I could probably find good examples from different periods of the IV-ii complex as well, but it's not nearly as important to know about as the cadential embellishments linked to above.
Comment: The reason I added some examples is mostly to encourage you to find examples in the pieces you love. Preferably by ear, without referring to the score.


Slow IIS performance after upgrade from 7.0 to 8.5

Question: A website was running on an IIS server 7.0 / Windows 2008. A new server was set up, running IIS 8.5 / Windows 2012, with more powerful hardware (4 CPU cores). However, performance of a new server is dramatically low.
Application is ASP classic. What I noticed is that VBScript-intensive code totally blocks other requests! For example, I have a page that loops for ~100000 records. It takes about 20 seconds to do that. During that period other requests, even for static resources, are waiting.
Unfortunately, server is being managed by someone else and I have no access to logs or performance monitors.
What could be the source of the problem?
Answer: I think this might be your problem.  I've experienced the same thing with Server 2008r2 running Classic ASP.  The problem is that the security updates to the server also install internet explorer 9 which overwrites a .dll that controls VBScript.
https://forums.iis.net/t/1177876.aspx?Classic+Application+Pool+Hang+Problem+with+Classic+ASP+


How to detect if the server is running node.js?

Question: While I have a server address just in case, how shall I know if the server running node.js?! Even more, iis or apache?
Is there any way to configure the running service on the server?
Answer: To check the node server running by logging in to the system
If you are using linux system then the easiest way is to check the process of the node service using pidof node which will give you the process of the node service if it is running.
In windows you can simply go to the Task Manager and check for node in the application list. If it is there then it is running in the machine.
To check node server from the server address
There is no default page or URL that node server provides from which you can know that node is running on that server by using the Public IP address or domain name. If you want to setup anything such then you can create a /status GET route that will be a public route and it will return you the uptime of the server. Something like this:
let example = {
  up_time: Math.floor(process.uptime())
};

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(example));

Where process.uptime() will return the time from where the server is started. Thus, you can run the URL like 192.168.10.10:3000/status (or with public IP) to check if the server is running node or not. Note that this works only when you have your own NodeJS API as you will be adding this additional /status GET route in your project.
Answer: You can do this in linux:
ps aux|grep server.js [where server.js is your filename]

You can use ps-node to configure your services and running processes
Comment: I have no access to the server. I only have the server address like ip or a http link


How to render a Views Content Pane programmatically?

Question: I have a view which displays all content of type "news" which is tagged with a specific tag, e.g. "world" (passed as parameter to the view).
The view machine name is news. It has a display of type Content Pane (machine name panel_pane_1). It also has a contextual filter set to "field_tags".
How to render this view content pane programmatically, passing tag value "world" to it?
(I've found ctools_content_render but no idea if this is the right function for this task and how to use it)
Answer: You can use
views_embed_view
e.g
print views_embed_view('news', 'panel_pane_1', 'world');

Any additional parameters will be passed as arguments, i.e contextual filter values.
Answer: You can use views_content_views_panes_content_type_render(). Here is a detailed example:
  // Important to include target content type.
  // You can also use 'views' content type but with a different render function.
  module_load_include('inc', 'views_content', 'plugins/content_types/views_panes');
  // Use your views machine name and display name here.
  $subtype = 'views_name-display_name';
  // Adjust settings to yours. You can debug ctools_content_render to see
  // all available settings in $conf. Or check
  // views_content_plugin_display_panel_pane::option_definition().
  $conf = array(
    'items_per_page' => 2,
    'offset' => 0,
    'more_link' => 1,
    'override_title' => 1,
    'override_title_heading' => 'blablalba',
    'override_title_text' => '',
    'pager_id' => 0,
    'use_pager' => 0,
  );
  // (optional) Prepare ctools context and context keys if your argument type
  // is 'context'. Check handling of other argument types in
  // views_content_views_panes_content_type_render().
  $conf['context'] = array('mycontext');
  $context = array(
    'mycontext' => ctools_context_create('node', $node),
  );
  // Render views pane.
  $pane = views_content_views_panes_content_type_render($subtype, $conf, $args, $context);

  // Get pane HTML.
  $output = render($pane->content);


how to create custom exception? and the condition is if the string length is greater than 100, just throw exception and catch?

Question: package test2;

public class StringLargeException {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
}

Comment: please follow the package naming conventions by reading https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html
Answer: Simple; put the following into some Test.java ... compile and run.
class MyException extends Exception {
   MyException(String message) { super(message); }
}

public static void main(String args[]) throws Exception {
  throw new MyException("you didnt see this one coming");
}

Answer:
make a class A that extends From Exception class
make a constructor that you can pass a message to the class
then when you want to throw the exception  just type throw new A("Message");


Proper way to record a digital piano

Question: My equipment:
Digital Piano - Yamaha p255
Audio Interface - Roland quad-capture
I bought one 1/4 inch jack from a store near my house and connected my piano to the audio interface, and when I listened to that recording, there was a lot of noise, which I think came from the cable, as it was also when I did not play a note, and also, my equipment is certainly decent.
I used it later with an electric guitar cable that I had which is also more expensive, and it was a little better but still, if I turned the input volume on the audio interface a little over the half, it would start making noise, and if I didn't, the recording would just be too quiet.
My question is, should I buy more expensive pl cables? Most expensive cables are designed by description to guitars, so I'm not sure if I would waste my money..
Would be glad for advices how to solve my problem.
PS. I know that it would be better to use 2 pl cables instead of one, but I'm not sure if that has to do with the noise problem.
Comment: What happens if you turn the output volume of the keyboard all the way up and turn the input volume of the interface down until the levels are right?
Answer: If the two cables are electrically equivalent and neither is actually faulty, I suspect you're kidding yourself that the expensive one sounded better (a common delusion in the hi-fi world :-)
Use the [L/L+R] Aux Out jack on the back of your piano into the L input of the Roland quad-capture.
There's a Hi-Z switch on the back of the Roland.  Make sure it's set to off. (That's for directly connecting an electric guitar.)
Keep the volume slider of the piano well up, or if this is annoyingly loud in the piano's speakers try bypassing the volume slider, as detailed in the Yamaha manual excerpt below. This will send a robust signal level to the Roland.  Don't be frightened of having the input level controls on the Roland low. Low for a Line input, high for a Mic input is fine.
(The manual also speaks of low-resistance plugs and cable.  This is merely confusing.  You can't buy high-resistance ones, and extra-low resistence isn't a feature of expensive cables, however much the advertising may waffle on about 'oxygen-free copper' and other snake oil.  A cable for this job needs to be adequate, but adequate is enough!)
You will get a better recording by using two cables.  But it will be better in terms of stereo effect, not signal quality.
Comment: Alright, so for a digital piano recording, just a pair of 1/4 inch cables from the local store will do the job?
Comment: Yes.  To be (almost) honest, the proverbial 'bit of damp string' could do this job.  Just make sure it's long enough!
Comment: Best answer I have got so far on stackexchange. For anyone with this specific piano, you need to choose  "2" on function 6.6, and then set function 6.7 to max value (20) or whatever suits for you.
Comment: Did it work? :-)
Comment: Yep. By the way, are you saying that there isn't a difference between cheap and more expensive PL cables? If so then why can guitar cables get so pricey?
Comment: Guitar cables carry small voltages into high impedences, so differences - particularly in capacitance - can be audible. But you don't have to pay BIG money for a certain specification. You think guitar cables can get pricy?  Look at what the audiophools fall for! http://www.russandrews.com/
Comment: I agree partly, but I think more expensive cables may have better casing against interference (but I'm not sure of that). What I do know for a fact is that some more expensive guitar cables have better protection against you standing on it and have stronger connections between the cable and the jack.
Comment: Yes.  IF there's an interference issue (notoriously so in TV studios before everything went digital) consider hi-spec cables.  But beware of cables and connectors that are vastly more sturdy than the sockets on your gear.  If it's going to get yanked, where would you LIKE it to fail?

Proper way to record a digital piano


How to automatically install civicrm extensions in drupal+civicrm installation profile?

Question: We are building a Drupal distribution / installation profile similar to CiviCRM Starter Kit. This will install Drupal 7 and CiviCRM 4.3 while installing the distribution.
We want to add some CiviCRM Extensions like "Extended Reports for CiviCRM" etc. in our distribution so that whenever user will install the distribution, these CiviCRM Extensions also gets installed by default.
We have added these CiviCRM Extensions in drupal-org.make file like below,
libraries[nz.co.fuzion.extendedreport][download][type] = get
libraries[nz.co.fuzion.extendedreport][download][url] = "https://github.com/eileenmcnaughton/nz.co.fuzion.extendedreport/archive/master.zip"
libraries[nz.co.fuzion.extendedreport][destination] = "extensions"

and these get downloaded/unzipped when we run drupal packaging script (drush make). But we are not sure how to enable them as part of the distribution installation.
We know we can add the Drupal modules in profile.info file like below,
dependencies[] = civicrm

but don't know how and where to add CiviCRM Extensions so that they get installed as part of distribution / installation profile setup.
Please suggest how can we install CiviCRM Extensions automatically as part of installation profile setup.
Comment: You might consider supporting the [CiviCRM SE Site Proposal](http://area51.stackexchange.com/proposals/77367/civicrm)
Answer: The current API call requires more than just the key. To enable modules as part of an install profile, you simply need to include this code somewhere in the process when it's possible to initialize CiviCRM...
  if (!civicrm_initialize()) {
    drupal_set_message(t('Failed to initialize CiviCRM'));
    return;
  }

  require_once 'CRM/Extension/Manager.php';

  $params = array(
    'version' => 3,
    'sequential' => 1,
    'key' => 'org.civicrm.volunteer',
  );

  $result = civicrm_api('Extension', 'install', $params);

As long as the Extensions Directory and ResourceURL are set in the civicrm.settings.php, you should be set.  I've been setting the Extensions Directory for Pantheon users, but still need to dynamically configure the ResourceURL https://drupal.org/node/1980088.
Rather than create a "Drupal distribution / installation profile similar to CiviCRM Starter Kit", PLEASE consider building on the CiviCRM Starter Kit by using it as the base distribution and contribute to maintaining it.  Take a look at this patch and how the latest version of OpenAtrium builds on Panopoly.
https://drupal.org/comment/6117722#comment-6117722
http://drupalcode.org/project/openatrium.git/blob/refs/heads/7.x-2.x:/drupal-org-core.make
We really need more developers working to push the patches that are still requires back into CiviCRM to keep this stable.  I hardly have time to figure out the changes with each CiviCRM release.  It has taken several years to get to the point we can install and run CiviCRM from the /profiles directory, package CiviCRM w/ drush make, and rebuild the required libraries.
The CiviCRM Starter Kit was always designed to remain a base install to build other use case specific distributions on, but I've really been maintaining this on my own so far and would love some help.
UPDATE:  I went ahead and created https://drupal.org/project/civicrm_extension_enabler since troubleshooting code in this queue is difficult.  That module enables the CiviVolunteer extensions and works a site running https://dashboard.getpantheon.com/products/civicrm_starterkit/spinup once CiviVolunteer is uploaded to sites/all/extensions
I've started an issue to change the specific extensions hard coded in the .install to be an array of extensions populated by the distribution https://drupal.org/node/2159317
Comment: In the params array, version isn't the version of the module... but the version of the API.  I'd enable the Devel module and use dsm($result) to see the error civicrm_api is returning.
Comment: Thanks @kreynen. I have placed the following code in module's hook_install(). I am getting last successful message, which means civicrm is getting initialized. But civicrm extensions are not being installed. Looks like Extensions Directory and ResourceURL are not being set in the civicrm.settings.php although I am using https://drupal.org/files/1980088-create-extensions-dir-4.patch patch in drupal-org.make.
Comment: function z_ext_install() {
  global $civicrm_setting;

  $d = realpath('.' . base_path()) . '/';
  $civicrm_setting['Directory Preferences']['extensionsDir'] = $d . 'sites/all/extensions/';

  if (!civicrm_initialize()) { drupal_set_message(t('Failed to initialize CiviCRM'));return;}

  $civicrm_path = drupal_get_path('module', 'civicrm') . '/';
  require_once $civicrm_path . 'CRM/Extension/Manager.php';

  $params = array('version' => 1.6, 'sequential' => 1,'key' => 'nz.co.fuzion.extendedreport');
  $result = civicrm_api('Extension', 'install', $params);
  drupal_set_message('Ok.');
}
Comment: I updated my answer with link to https://drupal.org/project/civicrm_extension_enabler.  Just added steps to test to the project page.  Let's move the discussion about making that module a flexible solution that any distribution can use to that project's issue queue since the original questions has been answered.
Answer: I haven't done this exactly (using Drupal install-profiles), but there are two key ingredients that have helped me automate setup in other contexts:

Traditionally (with Civi 3.x => 4.2 inclusive), one needed to create an extension directory and then set configuration options so that Civi would scan that directory. This is no longer necessary. Beginning in 4.3, you can put extension files anywhere in the CiviCRM source tree -- I'm partial to $civicrm_root/tools/extensions. Beginning in 4.4, you can also put extensions in $drupal_root/vendor.
To activate the extension, you can call CiviCRM's Extension API. The call needs to come after CiviCRM's core platform has been installed and bootstrapped.

Some examples of using the API
## PHP
$result = civicrm_api('Extension', 'install', array('key' => 'my.extension.name'));

## PHP
$result = civicrm_api('Extension', 'install', array(
  'keys' => array(
    'my.extension.num1',
    'my.extension.num2',
    'my.extension.num3',
  ),
));

## CLI
drush cvapi extension.install key=my.extension.name

## CLI
drush cvapi extension.install keys=my.extension.num1,my.extension.num2,my.extension.num3


Continuity of function on $C^\infty_c(K)$

Question: While learning the concept of test functions, I am stuck on the following exercise. Following the book's notation we define $C^\infty_c (\mathbb{R}^d)$ as the set of smooth, compactly supported functions mapping from $\mathbb{R^d} \to \mathbb{C}$, and $C^\infty_c(K) \subset C^\infty_c(\mathbb{R}^d)$ the subset who are supported in $K$.

Let $K$ be a compact set in $\mathbb{R}^d$. Show that a linear map $T: C^\infty_c(K) \to X$ into a normed vector space $X$ is continuous if and only if there exists $k\geq 0$ and $C > 0$ such that $\|Tf\|_{K} \leq C \| f\|_{C^k}$ for all $f\in C^\infty_c(K)$.

Prior to this exercise my textbook defines the topology on $C_c^\infty (K)$ as the topology generated by the normS $$\| f\|_{C^k}=:\sup_{x\in K}\sum_{j=1}^k |\nabla^j f(x)|,$$
with $k = 1, 2, \dots$ and $\nabla^j f(x)$ being the $d^j$-dimensional vector.
I found much trouble proving the forward direction ($\implies$). Here is what I have tried.
Let $\tau_k$ be the topology generated by the norm $\|\cdot\|_{C^k}$. Since $\| f\|_{C^{k'}}\geq \|f\|_{C^k}$ whenever $k' \geq k$, we know that $\tau_k \subset \tau_{k'}$. It follows that the topology of $C_c^\infty(K)$ is given by $\cup_{i=1}^\infty \tau_k$. We will prove the forward direction if we can show that there exists $k>0$ such that for all open set $O$ in $X$, $T^{-1}(O)\in \tau_k$. As this will then imply $\|Tf\|_{K} \leq C \| f\|_{C^k}$ due to the equivalence between boundedness and continuity of an operator.
However, I cannot convince myself that such finite $k$ exists. Specifically, what if there is a sequence of $O_k$ open in $X$ such that $O_k\in \tau_k $ but $O_k \notin \tau_{k-1}$ for every $k>1$? If this possibility is true, then it would contradict the statement of the exercise.
I would appreciate it if someone could point out any conceptual error or provide hints to solving this exercise.
Comment: Thank you so much for your elaboration!
Comment: Would this help you? [Is this estimate true for functionals on Frechet spaces?](https://math.stackexchange.com/q/3085263)
Comment: @BihuDuo I think the issue is, if $K$ is not open, we can't perhaps define a good notion of differentiability at the boundary points
Comment: @AnneBauval My textbook used $C^\infty_c (\mathbb{R}^d)$ to denote the set of smooth, compactly supported functions mapping from $\mathbb{R^d} \to \mathbb{C}$, and then use $C^\infty_c(K) \subset C^\infty_c(\mathbb{R}^d)$ to denote the subset whose support is $K$.
Comment: @AnneBauval That's right. Thanks for pointing out the unclear notation and I should say the support is contained in K (rather than the support is K).
Comment: @Akira The textbook is named "An Epsilon of Room, I: Real Analysis" by Terence tao. I am reading the edition that is published by the American Mathematical Society. This exercise is on page 215 of this textbook and is labeled as exercise 1.13.4.
Comment: I don't see how you're defining the topology at all. In the sum, we have three letters, $i,j,k$, none which appear related. Are you suggesting we take the topology generated by **all** the norms arising from **all** choices of $k$? Also, the gradient vector for a map $\Bbb R^d\to\Bbb R$ is simply $d$-dimensional, not $d^j$-dimensional (but we still don't know what $j$ is)
Comment: @FShrike Sorry! The subindex below the sum should be over "j" instead of "i". I have just fixed that. The index k range over all positive natural numbers and topology is defined to be generated by this family of norms. The gradient notation is strange to me too, but I think it can be interpreted as partial derivatives to the j-th order.
Comment: @AnneBauval Here $K$ stands for a compact subset of $\mathbb{R}^d$.
Comment: Thanks. You mean the subspace of functions whose support is contained in $K.$ Ok, so $C_c(K)$ is the space of smooth maps $\Bbb R^d\to\Bbb C$ with support contained in $K.$
Comment: Could you share the textbook you are using?
Comment: @BrunoB Thank you! I believe this is exactly what I needed.
Answer: This is my answer to my own question after reading a reference suggested in the comment.
Assume continuity of $T$ with respect to the topology of $C^\infty_c(K)$. To show that the linear operator $T$ is continuous with respect to $\tau_k$ for some finite $k$, it suffices to show that there exists a fixed $k$ such that for all $r> 0$, there exists a $\delta>0$  satisfying $\{f: \|f\|_{C^k} < \delta\} \subset T^{-1}(B_r(0))$.
Since $\{\{f: \|f\|_{C^k}< \epsilon \}  :  k \geq 0, \epsilon > 0\}\subset \tau_k$ forms a neighborhood basis of $0$,  there exists $k>0, \epsilon>0$ such that $N{\epsilon}(0) =: \{f: \|f\|_{C^k}< \epsilon\}\subset T^{-1}(B_1(0))$. Then for arbitrary $r> 0$, we get
$$
N_{r\epsilon}(0) := \{f: \|f\|_{C^k} < r\epsilon\}\subset T^{-1}(B_r(0))
$$
Hence $T$ is continuous at $0$ with respect to $\tau_k$.


Confused between multiple representations of Fourier Series' formula

Question:
I have never used the formula for Fourier Series with the representation that the instructor of the above video is using that involves $k$ and $\omega$. Instead, I use $n$ and $\pi$.
Now, suppose that I want to write the formula for complex form of the Fourier Series with the notations I am used to, it would be:
$$
f(t) = a_0 + \sum_{n=1}^\infty e^{in\pi t}(\frac{a_n-ib_n}{2}) + e^{-in\pi t}(\frac{a_n + ib_n}{2})
$$
Am I right?
Comment: Hey wait, where did the $i$ in the 2nd term's denominator go ?? :-/
Comment: Some pure mathematics students think all periodic functions have period $2\pi$...
Answer: The $n$ and $k$ are identical, just a difference in index representation.
As for the $\omega$, this is angular frequency, which is equal to $2\pi{f}$, where $f$ is the cyclic frequency.
So in summary:
$$\begin{align}
k&=n \\
\omega &= 2\pi{f}
\end{align}$$
Answer: The $w_0$ in the slides corresponds to your $\pi$. Usually, $w_0$ represents a fundamental (zeroth order) frequency, and $n w_0$ are then frequencies of its higher-order harmonics. Here, $w_0 = 2\pi f = 2 \pi/T$ so your expression is already expressed as multiples of $T/2$ which is the Nyquist minimum sampling period required for perfect signal reconstruction. Your form is more apt to digital (sampled) systems, while the form in the slides is more general and for analog systems.
The $i$ in the denominator did not go anywere; if you multiply $b_k$ by $i$ as was done, it cancels.
Comment: So basically, what I inferred was right :)


How to scope belongs to many relationship appropriately

Question: My application has the following entities:

Locations
Disciplines
Instructors

Disciplines and Instructors should be a many to many relationship, so in my Discipline model I have the following:
public function instructors() {
    return $this->belongsToMany(
        Instructor::class,
        'location_discipline_instructors',
        'discipline_id',
        'id'
    )->withPivot(['location_id']);
}

My pivot table contains the following fields:

location_id
discipline_id
instructor_id

To get a list of disciplines with their associated instructors, I do something like this:
return Discipline::whereHas('instructors', function ($query) {
    return $query->where('location_id', '=', $this->locationId);
})->with('instructors')->get();

Initially I thought this was exactly what I needed - and it is close, but not quite what I want. Here is a sample response I get back:
{
  "disciplineId": 4,
  "discipline": "Used Tire Sales",
  "updatedBy": null,
  "instructors": [
    {
      "id": 5,
      "firstname": "Jacque",
      "lastname": "Morton",
      "pivot": {
        "disciplineId": 4,
        "id": 5,
        "locationId": 27
      }
    },
    {
      "id": 1,
      "firstname": "System",
      "lastname": "Administrator",
      "pivot": {
        "disciplineId": 4,
        "id": 1,
        "locationId": 26
      }
    }
  ]
}

This is a list of all disciplines associated with locationId 26, but the instructors are not being filtered by the locationId - notice the first instructor returned has a locationId of 27 instead of 26. Have I missed something obvious in the documentation? If not, how can I filter the instructors by locationId as well?
Comment: have you tried `wherePivot()` also?
Answer: In Laravel With and WhereHas are 2 separate task performed from the eloquent builder and they are not really aware of each other since they are not sharing the same queries.
So try something like this:
return Discipline::with(['instructors' => function ($query) {
    $query->where('location_id', '=', $this->locationId);
}])
    ->whereHas('instructors', function ($query) {
        return $query->where('location_id', '=', $this->locationId);
    })
    ->get();

Comment: Thank you @Tanner - I ended up finding a solution at laracasts, but this is the correct answer


Access property of a parent object in a nested property

Question: I have this:
var SomeNamespace = {
    Model: Backbone.Model.extend(),
    View: Backbone.View.extend({
        model: new this.Model, //<-- how do I properly create a new object from parent to here?
        myMethod: function()
        {
             alert(this.model.MyName);
        }
    })

}

Where I added the comment, Model is not defined, I understand why, what I want to know is, how do I access the Model property of the parent?
Answer: 'this', in your case refers to Backbone.View.extend i believe, you need to do the following:
model: new SomeNamespace.Model

Comment: then it will say `Model` is not defined.
Comment: because the thing is not defined yet, as opposed to other languages, you can not do that in JS. You need to define it in the constructor of the class. B.t.w, by a quirk coincidence, this is the 3rd or 4th time I see this question in the last 24 hours.
Answer: var SomeNamespace = {
    Model: Backbone.Model.extend(),
    View: Backbone.View.extend({
        model: null, //<-- how do I properly create a new object from parent to here?
        myMethod: function()
        {
             alert(this.model.MyName);
        },
        init: function(){//runs when creating an instance of SomeNamespace.View
             this.model = new SomeNamespace.Model();
        }
    })

}

because the Model is not defined yet, as opposed to other languages, you can not do that in JS. You need to initialize the var to Model in the constructor of the class.
Answer: Taken from the extend documentation for Backbone.js (http://documentcloud.github.com/backbone/#Model-extend):

Brief aside on super: JavaScript does not provide a simple way to call super — the function of the same name defined higher on the prototype chain. If you override a core function like set, or save, and you want to invoke the parent object's implementation, you'll have to explicitly call it, along these lines:

var Note = Backbone.Model.extend({
  set: function(attributes, options) {
    Backbone.Model.prototype.set.call(this, attributes, options);
    ...
  }
});

Does this work?
Backbone.Model.prototype.model.MyName;


Proof by induction -inequality

Question: Prove that $ 1 + \frac{1}{2}+ \frac{1}{3} + .... + 1/n < 2\sqrt{n}$ for  $n \ge1$
Here's my attempt:
Base case:
$P(1): \frac{1}{1} \le 2\sqrt{1} = 1 \le 2$ (Base case true)
Assume $n = k$ for $k \ge1$ such that $ 1 + \frac{1}{2}+ \frac{1}{3} + .... + \frac{1}{k} < 2\sqrt{k}$
INDUCTION HYPOTHESIS: $ 1 + \frac{1}{2}+ \frac{1}{3} + .... + \frac{1}{k} < 2\sqrt{k}$
Now for P(k+1), we must show that $ 1 + \frac{1}{2}+ \frac{1}{3} + .... + \frac{1}{k+1}$ $< 2\sqrt{k+1}$

$ 1 + \frac{1}{2}+ \frac{1}{3} + .... + \frac{1}{k} +\frac{1}{k+1}$ $< 2\sqrt{k+1}$
By our induction hypothesis: $2\sqrt{k} + \frac{1}{k+1} <2\sqrt{k+1}$
Now, I add $2\sqrt{k}$ to the right side.
$2\sqrt{k} + \frac{1}{k+1} <2\sqrt{k+1} + 2\sqrt{k}$ (the inequality is still true)
Then, substract $2\sqrt{k}$ from both sides,
Hence, $\frac{1}{k+1} <2\sqrt{k+1}$
QED
Also looking forward to see other ways to complete this induction! Thanks!
Comment: This is scircular, you already assumed your conclusion in the begining.
Comment: When I read your proof again, you seem to try to go from bottom up and you only wrote down the "deriving process". However, when you try do derive from conclusion you need to pay attention to the difference between $p\implies q$ and $p\iff q$. For example in your proof even though $2\sqrt{k} + \frac{1}{k+1} <2\sqrt{k+1}\implies 2\sqrt{k} + \frac{1}{k+1} <2\sqrt{k+1} + 2\sqrt{k}$, the converse is not true.
Answer: The problem within your proof is that you assume $1 + \frac{1}{2}+ \frac{1}{3} + .... + \frac{1}{k} +\frac{1}{k+1}< 2\sqrt{k+1}$ at the beginning but this is not allowed; you are trying to prove it but you assume it at first.
Another problem is that, when you apply the induction hypothesis, you are saying $A<B,A<C$ hence $B<C$ which is logically incorrect.
To prove it you need to show $${1\over{k+1}}<2\sqrt{k+1}-2\sqrt{k}$$
which comes from
$${1\over{k+1}}={2\over{(k+1)+(k+1)}}<{2\over{\sqrt{k+1}+\sqrt{k}}}=2\sqrt{k+1}-2\sqrt{k}$$
Hence
$$1 + \frac{1}{2}+ \frac{1}{3} + .... + \frac{1}{k} +\frac{1}{k+1}<2\sqrt{k}+{1\over k+1}< 2\sqrt{k+1}$$
Comment: Well done! ... +1

Proof by induction -inequality


How to manage exported block configuration that site users can override?

Question: Using core config management, we export configuration from developer's site instances and put than under version control. Eventually, this configuration is merged and ends up in production, where we import it thru either Drush or the UI.
Trouble is, site owners have permissions to update block configuration, and this overrides our exported configuration.
What is the intended workflow in this case?
Put more generically: how to manage exported configuration that can be overriden by users (with a core CM workflow)?
Comment: I think that if your site users consider block configuration "content", then it should not be managed by configuration management.
Comment: Unfortunately there isn't (yet) a way to exclude a configuration item from being managed by configuration management.  The gray area of what is content and what is config will remain for a while.
Answer:
Trouble is, site owners have permissions to update block configuration, and this overrides our exported configuration.

I thinks it's a bad idea to give site owner to change something in site-configuration. Site owner should take care only about site's content and should have permission to change site's configuration(block's configuration it's a site configuration).
Answer: My team will be altering our deployment process to ensure any production changes are incorporated into the exported configuration before final deployment.

Setup local environment to match code on production
Export configuration from production & overwrite local configuration
Stash or commit any changes
Merge with latest development code
Deploy code to production

Ideally, if we're aware of any in-production changes we will export and merge them during development as soon as possible, rather than waiting to do one big merge before deployment.


How to render mini panel in custom template programatically?

Question: I have a minipanel and I have a custom template. How can I render minipanel in my custom template programatically?
Answer: Mini Panels are available as blocks. So you'd be rendering it in the same way you render any block programmatically in Drupal 7.
Use
<code>$block = module_invoke('panels_mini', 'block_view', 'machine_name_of_mini_panel');
print $block['content'];
</code>


Image classification where images are of different dimensions, resolutions, etc

Question: I am working on an image classification problem where I have black and white images of all different dimensions and resolutions. The images belong to 1 of 5 groups including an unknown category. These images are stored sparsely, by which I mean as a list of coordinates.
For example the first three observations for an image might look like this:
X Y
0 0
0 1
2 3
: :

where there are points at (0,0), (0,1), and (2,3). Since the images are black and white, these coordinates correspond to the pixels in the image that are black.
My goal is to classify these images into 1 of 5 groups. I have some metadata that I also plan to use, such as date the image was created, but ultimately I need to find meaningful features from the images themselves. My plan for this was to run PCA and feed the features into SVM or random forests model.
I am somewhat familiar with the classic handwriting digits example, however I am not familiar with cases where images are not of standard dimension or resolution.
One idea that I have had is to divide each image into a fixed number of cells, say a 100x100 grid. This way each image would be described by 1000 values which I could then run PCA on. My concern with this idea is that it reduces the information available for classifying the images.
The Question
Much of the work on image processing that I have seen uses examples where the images are of comparable size, resolution, etc. but how do we develop models for image classification where the images are not standardized in this way?
Comment: Are you sure that counting black pixels is a good way to solve your problem? I've never seen such approach :P
Comment: @felipeduque nope--but I don't think I said anything about counting the pixels.
Answer: I would try LBP (or any other descriptor, based on what your images (and task, i.e. classes) actually are). To deal with different sizes, you can use Bag of Words encoding.
Answer: I agree. In most of the works on image pools, images are all of the same size. So, you can consider this as one of the major challenges of your work.
Segmentation
Segmentation of images (as you had thought) is always a good practice. I would suggest the same. You can consider a grid of size g*g for all images (regardless of their size) and calculate your parameters on those cells one by one. This would give you a g*g image parameter matrix, for each image. Regarding the parameters, you could start with descriptive statistics (e.g.,mean, sd, skewness, ...) or texture-related parameters (e.g., gradient, orientation, etc.)
Sampling
But before that, perhaps you need to make a general data analysis to see what the best size is to rescale all images to. That size is not necessarily the size of the smallest image in your dataset. You can do up-sampling images (i.e., enlargement) as well as down-sampling. For instance, if only a very small fraction of your images are below d*d, then you can rescale them to d*d using any interpolation method you prefer. Or perhaps, your images are of such a nature that they won't be affected much by interpolation (e.g., they don't have much of details).
This gets more complicated if your images are not all squared. If this is the case, then you would also need to answer this question that whether or not the subjects of your images will be significantly affected if stretched horizontally or vertically.
But does this make your results will be less accurate since you are (over/under) sampling and interpolating? Yes, but your model is as good as your data. If this is the best data you could access for your work, then there is not much one can do for missing data. Here, the missing data is the images that were supposed to be all of the same size, n*n, but apparently many of them are smaller.
Other Dimensionality reduction techniques?
For PCA, you definitely need to have images of similar sizes, since you will be dealing with vector space. I know that you would also want to use SVM which deals with vectors as well, and they must be of the same size. But if PCA was the issue, you could have used other dimensionality-reduction techniques. For instance F-test (Wikipedia, F-test). Since your data is labeled, you only need to have an equal size set of features. F-test would sort your features and you can find the best ones.

A minor point that perhaps you already know; the concept of resolution is defined only in the context of visualization (on screen or print). It is all about how many pixels will represent a certain unit of the image. Hence the units of resolution, ppi (Pixel per inch) or dpi (dot per inch). So, you only need to worry about the image dimension, i.e., width and height.
Answer: Grauman and Darrel's Pyramid Match Kernel deals with how to compare histograms of images of different sizes (and thus different number of features). But since your features are simply the number of black pixels, there isn't a proper histogram to start with.
I'd normalize the pixels count by the total number of pixels in the image. That way you could compare small images against large ones.


How accurately can a good musician judge an interval to be out of tune?

Question: This is for a music/physics crossover experiment.  Almost everyone will be familiar with the Doppler Effect, even if they don't know the name. Imagine that a vehicle is blaring its a siren or otherwise making a noise with a distinct pitch.  As the vehicle approaches you and then passes you, the note will appear to drop in pitch.
The apparent note will be higher in pitch than the "true" note when the vehicle approaches, and the apparent note will be lower in pitch than the "true" note when the vehicles recedes.  (By "true" note, I mean the original frequency emitted, prior to any Doppler shift.)  There will be a glissando as the car passes.  The closer the vehicle passes you by (e.g., the closer you are standing to the side of the road as the vehicle passes), the more rapidly the glissando will occur.
It occurred to me that it should be possible to calculate the speed of the vehicle by the interval between the approaching and receding notes.  So, I have performed some calculations and here are a couple of examples: if the perceived pitch drops by a (well tempered) minor third, then the vehicle was travelling at 106.8km/h (66.4mph). To produce a perceived drop equal to a major third, the vehicle must have been travelling at 142.1km/h (88.3mph).
Personally, with my skills, even an accuracy of 10km/h would be a challenge.  Increasing the speed by only 10km/h would produce something I might recognize as "a slightly sharp minor third," but it might be difficult for me to discern precisely how sharp the interval is.

Here is my question: how close could musicians come to determining how sharp/flat an interval is, in cents?  For example, would musicians be able to detect (by ear) that an interval is 10 cents above a minor third, or will their unaided ear be limited to detecting that the interval is, e.g., 100 cents above a minor third? I can distinguish how sharp/flat an interval is to a semitone, but I expect that good musicians could do rather better.
So, does anyone know how good/precise musicians are at judging interval intonation in this fashion?

NOTES

Perfect pitch is not required, just the ability to judge the interval.
The temperature will have an effect on how much Doppler shift occurs in the perceived frequency.  The values above assume 20C / 68F.  Oddly, the air pressure does not have an effect. Humidity does in principle but it is very small.

CLARIFICATIONS

I am not expecting a musician to answer with a speed, but rather with a musical interval and, ideally, with a judgement (in cents) of how far off an interval is (e.g., "this is a minor third that is sharp by 100 cents").
I am not expecting to make radar guns obsolete.  The purpose is for fun and for education.  Forget my proposed use for the moment.
Whether the musician is a professional or a good amateur is not important.  There may be some amateurs who are better at this than some professionals.  I am also interested in how well piano tuners would be.
Comment: Interesting one, and musical too. Wonder if the police have considered this to judge speed in the past.
Comment: @Tim Yes, I have wondered that.  Might a court recognise a musician as an expert witness?
Comment: Is this your question: "how accurately (measured in km/h) can a good musician identify an interval?" Isn't "good" subjective? Setting that subjectivity issue aside, is there a need for this Doppler setup? Could you more simply ask: *'Defined intervals' include things like major third, minor third, perfect fourth, etc. When a 'good' musician listens to an interval that is slightly larger/smaller than one of these defined intervals, how far must the frequency deviation be in order for the musician to identify that he/she isn't hearing one of these 'defined intervals'?*
Comment: @jdjazz i am not expecting a musician to respond with a speed.  What i would like to know is could they say 100 cents above a minor third,  10 cents, etc.  I can tell to a semitone but I expect that good musicians could do rather better.  Is asking about the pitch accuracy of professional musicians subjective?
Comment: @badjohn, you haven't asked about the pitch accuracy of professional musicians--your title asks about the pitch accuracy of "good" musicians, and the body of your post asks how close "some" could come. (By "some" I assume you mean "good musicians.") "Professional" is probably less subjective than "good." The way this is asked, one could respond by saying, "they're not good unless they can identify 10 cents above/below." If this is the question, is there a need for the Doppler setup?
Comment: @Tim, [radar guns do use the Doppler effect](http://hyperphysics.phy-astr.gsu.edu/hbase/Sound/radar.html).
Comment: I expect it depends very much what genres of music the professional is involved with. Someone who specializes in early music and unequal temperaments will probably easily distinguish between equal-tempered and just-intonation major thirds (14 cents difference) and even between various tunings of 5ths that are only 2 cents apart. But that ability might not be so good in the Doppler shift scenario. On the other hand, a professional pianist playing mainly 19th-21st century music doesn't need those skills at all.
Comment: @jdjazz But (1) radar speed guns work at frequencies literally a million times higher than sound waves audible to humans, and (2) The *relative* frequency changes produced in Doppler radar speed measurements are of the order of 1 part in 10 million, compared with the 10 or 20 percent for "audio" Doppler effects, so the technology used to measure them accurately is very different.
Comment: @alephzero, agreed on both accounts. I still think the answer to Tim's question is yes, you're right in your suspicion, and engineers have built devices that use the Doppler shift (this is also done when measuring blood speeds). I think Tim isn't asking about whether police could catch speeders by measuring the Doppler shift in frequencies emitted *from the speeder's siren/horn*. If this is the question, then there are not only the engineering issues you elude to, but there's also the fact that most cars aren't sounding their horn when they speed.
Comment: I'm voting to close this question as off-topic because it is a poll.  Answers depend entirely on the particular person.
Comment: @MatthewRead Okay with me
Comment: Individual answers would be subjective but I had hoped that the best would be known.  E.g. "how fast can you run 100m" will depend on the particular person.  "How fast can the current world record holder run 100m" would be a more objective question.
Comment: Note that a minor third 100 cents off would be judged as a *perfectly intonated* major second or a major third. Anyway, I think this isn't really a poll, but an inquiry into the abilities of musicians (however responders wish to qualify it), hence on-topic.
Comment: @badjohn I think this is a very useful question in disguise. Rewritten to ask if there have been studies to measure the accuracy of musicians' hearing -- particularly in terms of cents -- seems to me a great fit and quite interesting/useful. The doppler stuff, IMO, is a bit of a red herring, but could be included briefly to indicate how the question arose. Should you choose to rewrite, I would near certainly vote to re-open.
Answer: I can't answer for "some" musicians, but I can answer for myself and my answer might give you some insight on why you might have a hard time getting a definite answer to this question.
Background: I am a jazz musician, a sometime professional. I do a lot of ear training. I rarely deal with non-Western tuning systems.
I've tested my threshold for identifying the (in)accuracy of intonation and it varies considerably. For perfect intervals of all kinds, I'm pretty accurate; I can generally tell within a few cents if a perfect interval is off. It gets progressively more difficult when you get into thirds and sixths, although I tend to be pretty good at identifying whether sevenths are in tune or not. Minor seconds and tritones are extremely difficult, particularly melodically, and my accuracy could be as much as ten times lower in those situations.
In many respects, that's just the tip of the iceberg. Melodic is much more difficult than harmonic. Higher pitch is correlated with greater accuracy. Accuracy is generally high when the two pitches are close to forming an inveral but generally low when the two pitches are at the midpoint of two western intervals. I might be able to tell you, for example, that "these two notes are a perfect fifth sharp about ten cents" but it is unlikely that I'd be able to tell you that a perfect fifth sharp 40 cents is anything more than somewhere vaguely between a very sharp perfect fifth and a very flat minor sixth.
I have never tried this with glissando but I would imagine that this would make things significantly more difficult.
In conclusion, I think that my ability in this regard varies so significantly (and it is my somewhat unscientific belief that this is typical among good musicians, based on my experience) that the only real answer to the question is "it depends".


Quick question on integration in Calc II (likely very easy)

Question: If I'm taking the integral of h(x) from [a, b] and the integrand is [xf(t) + g(t)]^2 dt, I can just pull out the x term as a constant (after expanding and breaking the integral up of course) since I'm integrating with respect to t, correct?
Comment: That is correct but the $x$ remains attached to $g$.
Comment: After I break up the integral there is no x on the g(t). Also, what is the rule for this so I know in the future? The fact that it was h(x) with x in the input messed me up a little.
Comment: I'd need to see more to tell you.  Your question is very vague.
Comment: I expanded out the integrand, which became x^2(f^2(t)) + 2xf(t)g(t) + g^2(t). Then I broke up the integrals and pulled x out as a constant from the first two. That's fine, right? I am asking, how do I know that I can do this? What is the rule?
Comment: That's OK, so long as $x$ does not depend on $t$.
Comment: Yeah, so we can do that as long as it's not a substitution or something where x = t^2 or something to that effect?
Comment: Yes that's right.
Answer: Yes $x$ is like a constant since you are integrating in $t$ so $\int (xf(t)+g(t))^2 dt = \int x^2f^2(t)+2xf(t)g(t)+g^2(t)dt=x^2\int f^2(t)dt+2x \int f(t)g(t)dt+\int g^2(t)dt$
Answer: $$
\int_a^b (xf(t)+g(t))^2 \, dt = \int_a^b (x^2f(t)^2+2xf(t)g(t)+g(t)^2)\,dt
$$
$$
= x^2\int_a^b f(t)^2\,dt + 2x\int_a^b f(t)g(t)\,dt + \int_a^b g(t)^2\, dt.
$$
Comment: Why does the g^2 integral say from [1, b]? Is that a typo?
Comment: Typo. ${{{{{}}}}}$


Is there a more efficient way to write max(A*x,min(y,B*x))?

Question: Suppose we know that $B > A$.  Right now,
$$\max\{A \cdot x,\min(y,B\cdot x)\}$$
requires two multiplication operations to evaluate.
Is there a way to rewrite this using max/min notation such that I only need one multiplication operation (and no other floating point operations such as division) to evaluate?
EDIT: Updated this to place an additional constraint.
Comment: For the  coding part of your question, this may not be the best site ...
Comment: Yes, I was debating whether to put this on a coding-based stackexchange/overflow site or to put this here... I was hoping the mathematicians here could work some magic with the max/min logic.
Comment: Ah!  So maybe ask that: is there some different way to mathematically define this function exploiting the min/max interplay?
Answer: You could do
$$x \cdot max(A,min(y/x,B))$$
but now of course you have a division operation. It is only 1 multiplication operator though :)
Comment: With this formulation you need to check whether $x = 0$ to avoid trying to divide by $0$.
Comment: That's a good point haha.  I should define my question a bit better...


Preciso de ajuda em um método

Question: Estou com um problema relacionado a um jogo que estou criando onde o personagem joga uma bomba na posição que ele se encontra. Na primeira execução do método bomba() a execução sai como o ordenado.
Porém, nas demais execuções do método ele só executa uma parte do método.

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] args) {
        new Game();
    }
}

class Personagem extends JLabel{

    public Personagem(int x ,int y) {
        player(x,y);
    }

    ImageIcon persoImg = new ImageIcon(getClass().getResource("personagem.gif"));
    public JLabel personagem = new JLabel(persoImg);

    public void player(int x,int y) {
        personagem.setBounds(x, y, 100, 100);
    }

}

class Game extends JFrame {

    public Game() {
        bombas.carregarbomba();
        movimento();
        componentes();
        janela();
    }

    int y = 300;
    int x = 400;
    int contador = 0;

    public  Personagem perso = new Personagem(x, y);
    public Bomba bombas = new Bomba();

    ImageIcon bombaImg = new ImageIcon(getClass().getResource("bomba.gif"));

    public JLabel bombfoto = new JLabel(bombaImg);
    public JTextField text = new JTextField(":" + contador);
    private JPanel contentPane;

    public void componentes() {
        Font font = new Font("Courier", Font.BOLD, 25);
        bombfoto.setBounds(0, 0, 50, 50);

        text.setBounds(60, 0, 50, 50);

    }

    public void janela() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(150, 100, 1000, 700);
        contentPane = new JPanel();
        contentPane.setLayout(null);
        componentes();

        add(bombas.bombaJLabel[bombas.getCont()]);
        add(perso.personagem);
        setVisible(true);

    }

    public void movimento() {
        addKeyListener(new KeyAdapter() {

            public void keyTyped(KeyEvent e) {
                char movimento = e.getKeyChar();
                if (movimento == 'w') {
                    y -= 20;
                }
                if (movimento == 's') {
                    y += 20;
                }
                if (movimento == 'd') {
                    x += 20;
                }
                if (movimento == 'a') {
                    x -= 20;
                }
                if (movimento == 'e') {
                        bombas.bomba(x, y);
                        bombas.setCont(contador);
                        contador++;
                }

                perso.personagem.setBounds(x, y, 100, 100);

            }
        });
    }

}

class Bomba extends JLabel {

    ImageIcon bombaImg = new ImageIcon(getClass().getResource("bomba.gif"));
    ImageIcon explosao = new ImageIcon(getClass().getResource("explosao.gif"));
    public int cont = 0;

    public JLabel[] bombaJLabel = new JLabel[8];
    int xbomb = 0;
    int ybomb = 0;

    public void carregarbomba() {
        for (int i = 0; i < bombaJLabel.length; i++) {

            bombaJLabel[i] = new JLabel(bombaImg);
            bombaJLabel[i].setSize(50, 50);
            bombaJLabel[i].setVisible(false);

        }
    }

    public void bomba(int x, int y){

        try {
                xbomb = x + 30;
                ybomb = y + 30;
                bombaJLabel[cont].setLocation(xbomb, ybomb);
                bombaJLabel[cont].setVisible(true);

                if (bombaJLabel[cont].isVisible()) {

                    ActionListener detonar = new ActionListener() {
                        public void actionPerformed(ActionEvent e) {

                            bombaJLabel[cont].setIcon(explosao);
                            bombaJLabel[cont].setBounds(xbomb -= 180, ybomb -= 300, 400, 400);

                            ActionListener duracaoexplocao = new ActionListener() {
                                public void actionPerformed(ActionEvent e) {

                                    bombaJLabel[cont].setVisible(false);

                                }
                            };

                            javax.swing.Timer timer = new javax.swing.Timer(1200, duracaoexplocao);
                            timer.setRepeats(false);
                            timer.start();
                        }
                    };
                    javax.swing.Timer timer2 = new javax.swing.Timer(2000, detonar);
                    timer2.setRepeats(false);
                    timer2.start();
                }
        }
        catch(ArrayIndexOutOfBoundsException ex) {}

    }

    public int getCont() {
        return cont;
    }

    public void setCont(int cont) {
        this.cont = cont;
    }
}

Comment: Cara, pense no lado de quem vai te ajudar, você acha legal forçar o cara a ter que ir num link externo pra acessar teu codigo e te ajudar? E quem não poder acessar esse link? Por isso, é importante e recomendável que você forneça um **[mcve]** e adicione-o na pergunta, clicando em **[edit]**.
Comment: @Donztt Como disse o Articuno, o ideal é que todo o código necessário para reproduzir o problema esteja na pergunta, e links sejam apenas complementos. Links podem ficar fora do ar ou mudar (e até ser bloqueado por firewall de empresas, dependendo do link e da empresa) e aí quem for tentar te ajudar não terá a informação completa. Se o código original é muito grande, tente reduzi-lo e crie um **[mcve]** <-- leia esta página, tem várias dicas de como arrumar seu código para postá-lo aqui.
Comment: @Donztt teu codigo é um **[mcve]**? Se eu colar na minha IDE, ele vai executar? Porque se nao for, nao adianta colar o codigo inteiro. Recomendo que visite o link que tanto eu quanto o hkotsubo sugeriu e tente criar um exemplo que qualquer um possa testar, sem testar fica dificil te ajudar.
Comment: Estou vendo o seu código e sei que posso ir lá no github pegar o resto porque o que foi postado aqui está incompleto. No entanto, você não descreveu qual é o seu problema. Qual é o método para o qual você precisa de ajuda? Qual é o problema que você está tendo? O que há de errado nesse código?
Comment: copiei um link para o github com o projeto completo
Comment: coloquei a parte principal do problema,espero que ajude
Comment: acredito que execute o problema quanto a isso é em relação as imagens que o programa utiliza
Comment: Então vc entende q nao é possivel outros executarem. Como vamos te ajudar se não podemos executar? Novamente, recomendo que acesse o link para aprender a transformar seu codigo num **[mcve]** para que assim seja possivel testarmos e ajudarmos.
Comment: agora é só copiar e colar que está funcionando
Comment: Estou vendo o seu código. Acho que você andou se esquecendo de algumas palavras-chave `static`.
Comment: eu não estou acostumado a criar tudo em uma classe e acabei esquecendo mesmo kk
Comment: Estou escrevendo uma resposta para a sua pergunta. Quando terminar eu posto ela.
Answer: Quando você faz isso:
public class Macaco extends Animal {
    private Banana banana = new Banana();
}

Você está dizendo que:

Todo macaco é um animal.
Cada macaco tem uma banana.

Quando você faz isso:
public class Macaco extends Animal {
    private Banana[] banana = new Banana[8];
}

Você está dizendo que:

Todo macaco é um animal.
Cada macaco pode ter 8 bananas.

Quando você faz isso:
class Bomba extends JLabel {
    public JLabel[] bombaJLabel = new JLabel[8];

    public void carregarbomba() {
        // blablabla
    }
}

Você está dizendo que:

Toda bomba é um JLabel.
Uma bomba pode ter até 8 JLabels.
Cada bomba pode carregar bombas.

Aí que as coisas estão erradas. Afirmar que cada bomba pode ter até 8 JLabels é absurdo. Ainda mais considerando que Bomba já é um JLabel. Também dizer que cada bomba pode carregar bombas também está errado.
O que você queria era carregar as bombas na classe Game. Afinal de contas um Game tem várias Bombas. Aliás, utilizar arrays para isso é uma abordagem horrível. Estamos em 2018, e não em 1995, e portanto use as listas que o Java oferece há mais de 20 anos ao invés de ficar se torturando ao tentar controlar isso usando arrays. Aliás, já que você vai ter uma lista de bombas, eis o que você faz:

Quando o usuário aperta E você instancia uma bomba (usando new) e a coloca na lista.
Quando a bomba explodir, você a remove da lista.
Crie cada bomba de forma similar a que você usa para criar personagens.
Abandone essa ideia de pré-carregar 8 bombas invisíveis no início! Isso é uma ideia muito ruim!
Esqueça aqueles malditos contadores!

Outro problema:
class Personagem extends JLabel{
    ImageIcon persoImg = new ImageIcon(getClass().getResource("personagem.gif"));
    public JLabel personagem = new JLabel(persoImg);
}

Isso está dizendo que:

Todo personagem é um JLabel.
Cada personagem tem uma imagem.
Cada personagem tem um outro personagem que é um JLabel.

Novamente, isso está bastante errado. Se o personagem já é um JLabel por meio de herança, então não tem sentido usar composição também e dizer que ele tem um personagem. Ou você usa herança ou usa composição, mas nunca deve usar os dois simultaneamente. Vejo que no seu código, você parece utilizar o JLabel da composição, então elimine o da herança.
Vejo que isso é um trabalho de TCC. Então:

Uma forma muito fácil de tomar porrada do pessoal da banca na hora da sua defesa é colocando o modificador public nos seus atributos. Qualquer livro decente sobre Java avisa logo nos primeiros capítulos que isso é uma péssima ideia e explica o porquê.
Esquecer de colocar o private e deixar a visibilidade de pacote também não é uma boa ideia.
Siga rigorosamente as regras de nomenclatura e indentação do Java porque você não vai querer nenhum membro da banca enchendo o saco por causa disso.
Também sugiro usar os recursos que as versões mais recentes da linguagem (especialmente a partir da 8) usam quando for pertinente, em especial os lambdas.

Outra coisa importante é nunca manipular componentes Swing fora da Event-Dispatch Thread. Veja nessa minha outra resposta o porquê.
Herança não é algo considerado muito legal. Falo disso aqui e também aqui (junto com muitas outras coisas). Isso significa que fazer Game usar um JFrame ao invés de herdar de JFrame é uma boa ideia. Retirar todos os extends JLabel também é uma boa ideia.
Também recomendo essa outra resposta minha.
Observe que você está chamando o método componentes() dentro do construtor de Game e dentro de janela(). Isso significa que está chamando duas vezes. Isso não faz sentido. Aliás, recomendo colocar tudo isso direto no construtor de Game pois nesse caso você não está ganhando nada ao dividi-lo em métodos.
As URLs das imagens devem ser carregadas em variáveis estáticas.
Isso daqui:
perso.personagem.setBounds(x, y, 100, 100);

Está violando o encapsulamento de Personagem. No entanto, você já tem o método player (que recomendo renomear para posicionar) para fazer isso, então basta usar esse método.
Nesse lugar:
public JTextField text = new JTextField(":" + contador);

O valor de contador vai ser zero quando isso for executado. No entanto, você nunca adiciona esse componente à janela, então isso acaba não servindo para nada.
Essas linhas estão sobrando de bobeira, pois isso já está dentro da classe Bomba, não precisa ficar em Main:
ImageIcon bombaImg = new ImageIcon(getClass().getResource("bomba.gif"));
public JLabel bombfoto = new JLabel(bombaImg);

Outras coisas que estavam de bobeira:
private JPanel contentPane;
Font font = new Font("Courier", Font.BOLD, 25);

Os campos x e y que representam a posição do personagem deveriam estar dentro da classe Personagem. Ao invés de alterá-los dentro da classe Game, o certo é que a classe Personagem ofereça métodos para manipular a sua posição (subir(), descer(), esquerda() e direita(), por exemplo). Aliás, essa posição nem precisa ser armazenada na classe Personagem pois pode ser obtida do JLabel por meio do método getLocation().
O tamanho da explosão é 350x350 e não 400x400. Mas você pode usar os métodos getIconWidth() e getIconHeight() e calcular as posições a partir do tamanho da imagem. A vantagem disso é que se você mudar o tamanho da imagem, não tem que sair arrumando um monte de números.
Outros detalhes importantes:

Sem ter um setLayout(null); coisas muito estranhas acontecem.
Sem ter um repaint() fica sujeira na tela quando componentes são removidos.

O código resultante ficou assim:
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class Main {
    public static void main(String[] args) {
        EventQueue.invokeLater(Game::new);
    }
}

class Personagem {

    private static final URL GIF = Personagem.class.getResource("/personagem.gif");

    private final Game jogo;
    private final JLabel label;

    public Personagem(int x, int y, Game jogo) {
        this.jogo = jogo;
        ImageIcon img = new ImageIcon(GIF);
        this.label = new JLabel(img);
        jogo.add(label);
        label.setBounds(x, y, img.getIconWidth(), img.getIconHeight());
    }

    public void subir() {
        posicionar(0, -20);
    }

    public void descer() {
        posicionar(0, 20);
    }

    public void direita() {
        posicionar(20, 0);
    }

    public void esquerda() {
        posicionar(-20, 0);
    }

    private void posicionar(int dx, int dy) {
        Point p = label.getLocation();
        int x = (int) p.getX();
        int y = (int) p.getY();
        label.setLocation(x + dx, y + dy);
    }

    public Bomba colocarBomba() {
        Point p = label.getLocation();
        int x = (int) p.getX();
        int y = (int) p.getY();
        return new Bomba(x, y, jogo);
    }
}

class Game {

    private final JFrame janela;
    private final List<Bomba> bombas;
    private final Personagem bomberman;

    public Game() {
        this.bombas = new ArrayList<>();
        this.janela = new JFrame();
        this.bomberman = new Personagem(300, 400, this);
        janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        janela.setBounds(150, 100, 1000, 700);
        janela.setLayout(null);
        janela.setVisible(true);
        janela.addKeyListener(new KeyAdapter() {

            @Override
            public void keyTyped(KeyEvent e) {
                char movimento = e.getKeyChar();
                if (movimento == 'w') bomberman.subir();
                if (movimento == 's') bomberman.descer();
                if (movimento == 'd') bomberman.direita();
                if (movimento == 'a') bomberman.esquerda();
                if (movimento == 'e') bombas.add(bomberman.colocarBomba());
            }
        });
    }

    public void removerBomba(Bomba b) {
        bombas.remove(b);
    }

    public void add(JLabel c) {
        janela.add(c);
    }

    public void remove(JLabel c) {
        janela.remove(c);
        janela.repaint();
    }
}

class Bomba {

    private static final URL GIF_BOMBA = Bomba.class.getResource("/bomba.gif");
    private static final URL GIF_EXPLOSAO = Bomba.class.getResource("/explosao.gif");

    private final Game jogo;
    private final JLabel label;

    public Bomba(int x, int y, Game jogo) {
        ImageIcon img = new ImageIcon(GIF_BOMBA);
        label = new JLabel(img);
        this.jogo = jogo;
        jogo.add(label);
        label.setBounds(x, y, img.getIconWidth(), img.getIconHeight());

        Timer timer = new Timer(2000, evt -> detonar());
        timer.setRepeats(false);
        timer.start();
    }

    private void detonar() {
        ImageIcon img = new ImageIcon(GIF_EXPLOSAO);
        int w1 = label.getWidth();    // Largura da bomba.
        int h1 = label.getHeight();   // Altura da bomba.
        int w2 = img.getIconWidth();  // Largura da explosão.
        int h2 = img.getIconHeight(); // Altura da explosão.
        Point p = label.getLocation();
        int x = (int) p.getX();
        int y = (int) p.getY();
        label.setIcon(img);
        label.setBounds(x + w1 / 2 - w2 / 2, y + h1 - h2, w2, h2);

        Timer timer = new Timer(1200, evt -> remover());
        timer.setRepeats(false);
        timer.start();
    }

    private void remover() {
        jogo.removerBomba(this);
        jogo.remove(label);
    }
}

Ainda há mais umas mudanças que deveriam ser feitas, em especial porque o modelo MVC não está sendo respeitado. Mas isso já deve servir para fazer o que você quer e já deve resolver o seu problema.
Comment: Obrigado pela ajuda!
Comment: @Donztt Se essa resposta resolveu o seu problema e não restou nenhuma dúvida, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique a vontade para comentar.
Comment: Ta certo! Obrigado pela atenção

Preciso de ajuda em um método


Iterating through a large array filling it with identically sized, but different, smaller arrays

Question: I have a large array full of zeros simply defined by:
BigArray = np.zeros((100,1000,1000),np.float16)

I then have a 3D volume that I randomly rotate outside of python and each time it is rotated I want to import the file into python and add it to the next bit of the array. I currently have the following code that will do it:
n = 0

while n < 99:
    Zaxisangle = randint(0,360)
    Yaxisangle = randint(0,360)
    Xaxisangle = randint(0,360)

    os.system('rotatevol -angles {},{},{} -input {} -output {}'.format(Zaxisangle, Yaxisangle, Xaxisangle,
                                                                   MRCfilewithextension, MRCforoutput))
    particledata = mrcopen(MRCforoutput)

    if n < 10:
        ArtTomo[:, 0:100, (100*(n+1))-100:100*(n+1)] = particledata
        n = n+1
    else:
        n = n+1

For the purpose of this example we can simplify it down to the following:
BigArray = np.zeros((100,1000,1000),np.float16)
particledata = np.random.rand(100,100,100)
n = 0
while n < 99:
    if n < 10:
        ArtTomo[:, 0:100, (100*(n+1))-100:100*(n+1)] = particledata
        n = n+1
    elif: 10 < n < 20
        ArtTomo[:, 100:200, (100*(n+1))-100:100*(n+1)] = particledata
        n = n+1
    else:
        n = n+1

I would then write lots of elif statements for each 'row'. Because I am iterating through the array with different files I can't simply fill it with a 'in range(0,1000,100)' statement annoyingly.
whilst I can write out all the elif statements I feel as if there must be a more efficient way to write this code I am just not good enough to see it. Could anyone else write this in a nicer way or am I just going to have to write 10 elif statments (i just don't feel like it is neat code!).
Answer: If I understand correctly, I think what you are writing could just be expressed like:
BigArray = np.zeros((100,1000,1000),np.float16)
particledata = np.random.rand(100,100,100)
n = 0
while n < 99:
    start = 100 * (n // 10)
    ArtTomo[:, start:start+100, (100*(n+1))-100:100*(n+1)] = particledata
    n = n+1

Comment: Unfortunately this does not work. Error putting a 100,100,100 array into 100,0,0 array although I cannot understand why erroring doing this at n = 5 with your code.
Comment: If a dimension of the target is `0` it means the slice stop is the same as the start, or smaller.  Sounds like this is just a bookkeeping error, making sure that the slice numbers are correct at all iterations.


how to show alert confirmaton on click of delete button

Question: Please look at the following example,
stackblitz
Please look at the example in stackblitz, I can drag and upload images there. Once i will drag and upload the image, delete button will appear. How can I write click function for that delete button in angular 2 and how to get the droped file url?
If i click that delete button it should ask the confirmation, "Are you sure you want to delete?"
I can't able to find way how to write onclick function for that delete button? Can anyone please help me?
Comment: I can't see any code you have written on it for upload. check if you posted a correct saved one. One suggestion is to use `@HostListener()` decorator to add events.
Comment: Its correct code only. Delete function will happen. Please check once. Delete code is there somewhere inside dependencies. I didn't write any code, its plugin.
Answer: Use the deleteFile EventEmiter
Html:
<input-file (deletedFile)="confirmDelete()" inputId="input-file" placeholder="Drop files below!"></input-file>

JS:-
confirmDelete() {
    var result = confirm("Want to delete?");
if (result) {
    alert('Deleted');
} else {
  alert('Not deleted');
}
  }

Link: https://stackblitz.com/edit/ngx-input-file-rr2lvr?file=src/app/app.component.html
Comment: Thank you so much.
Comment: So, when you cancel it what happens? @sathishkumar
Comment: How to get the uploaded file name or image url after drop the image in a field
Answer: You can use sweetalerts for that here is the link : https://www.npmjs.com/package/sweetalert2
wait i will implement & share you the stackblitz link in a while
Comment: please help me. I want to write on click function. If i got the click function , i will resolve 3 more defects.
Answer: You must read the documentation. The component supported deletedFile to trigger when you delete the figures.
html
<input-file inputId="input-file" placeholder="Drop files below!" (deletedFile)="deleteG()"></input-file>

appcomponent.ts
export class AppComponent {

  deleteG(){
    console.log('here you detect the delete when you click delete icon');
  }
}


Como criar um regex para apagar letras e número depois da 3ª casa decimal

Question: Preciso de uma expressão regular com as seguintes regras:

Apagar tudo que é letra
Apagar tudo que é número depois da 3ª casa decimal

Por exemplo, se eu digitar 34,444 qualquer próximo número será apagado. Se eu digitar a também será apagado.
 $scope.validateLimits = function(){
    $scope.numLimiteInferior = $scope.numLimiteInferior.replace(/\d|,/g,'');
 }

Answer: A regex que você usou (/\d|,/) significa "um dígito ou uma vírgula", o que significa que você está substituindo os números e as vírgulas por '' (ou seja, está removendo todos os números e vírgulas da string).

Sugiro fazer por partes: primeiro remova as letras e depois remova as casas decimais:

let x = '3b4,4444444a';
x = x.replace(/[a-zA-Z]/g, '').replace(/(,\d{3})\d+/, '$1');
console.log(x); // 34,444

Para letras eu usei [a-zA-Z] (qualquer letra de a a z, maiúscula ou minúscula).
Para as casas decimais eu usei parênteses para formar um grupo de captura, e dentro deles coloquei ,\d{3} (vírgula seguida 3 números). Como esta parte está dentro de parênteses, caso exista uma vírgula seguida de 3 números, eles farão parte do grupo de captura. E como é o primeiro par de parênteses, então será o primeiro grupo.
Depois tem \d+ (um ou mais dígitos), e em vez de substituir pela string vazia, eu uso a referência $1, que significa "tudo que corresponde ao primeiro grupo de captura". No nosso caso, é a vírgula seguida de 3 dígitos. Sendo assim, eu mantenho a vírgula e os 3 dígitos seguintes, e elimino todos os números da quarta casa decimal em diante.
Repare também que para remover as letras eu uso a flag g, pois assim todas as letras são removidas. Já na segunda regex eu não uso o g, pois estou assumindo que só haverá uma vírgula seguida de números.
Além disso, a regex /[a-zA-Z]/g não considera letras acentuadas. Se quiser, pode mudá-la para /[a-záàâãéèêíïóôõöúçñ]/ig (com a opção i para aceitar tantos maiúsculas quanto minúsculas, assim ela fica mais curta). Se quiser, nesta pergunta tem outras opções de regex para letras acentuadas.


How to process HttpResponse in AsyncTask android

Question: My activity executes http request using AsynTask.
How to process HttpResponse in case if web-server does not answer?
Currently when my web-server is down, AsynTask just stopped at "HttpResponse response = client.execute(httppost);" and then do nothing. I need to process this response and do something, but code belowe "execute" is not executed.
Here is ny background task:
<code>    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        String result = null;
        try {
            // Add your data
            List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
            postData.add(new BasicNameValuePair("session_id", session_id));
            postData.add(new BasicNameValuePair("i_key", params[0]));

            HttpPost httppost = new HttpPost( "http://my.webserver.com/getInfo.php");
            httppost.setEntity(new UrlEncodedFormEntity(postData));

            HttpResponse response = client.execute(httppost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(responseEntity.getContent(),
                                "UTF-8"));
                result = reader.readLine().toString();
            } else {
              Toast.makeText(this, "DDDDDDD",Toast.LENGTH_LONG).show();
            }

        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        return result;
    }
</code>
How I can handle response if web-server is down and not reply ?
Comment: Did you get timeout exception after 1 minute?
Comment: Put a timeout, after that you will get a timeout exception, if you web-server is not down/don't reply. Give it a try, http://stackoverflow.com/questions/16098810/access-network-availability-state-android/16099100#16099100
Comment: You should'nt use AsyncTask to perform network request since when the orientation of your device changes the activity is destroyed but also the AsyncTask which is tied to the lifecycle of this activity. To avoid that you should use Service pattern instead.
Answer: You need to set a timeout for your client's connection. For instance:
<code>protected String doInBackground(String... params) {
    HttpParams httpParameters = new BasicHttpParams();
    // set the connection timeout and socket timeout parameters (milliseconds)
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 5000);

    HttpClient client = new DefaultHttpClient(httpParameters);
    . . . // the rest of your code
}
</code>


Taking my own preset digital mixer to a live act - does it work or not?

Question: I'm thinking of ways to ensure my band sounds great at every gig. I found a digital mixer called Behringer XR18, which is capable of setting up, saving, and restoring stage presets at a click of a button. My assumption is that if we hired a proper sound engineer to set us up once and save it as a preset (or a number of presets in case we need more), we would be able to go to gigs and sound great, giving the sound guys a stereo out only, and ask them to handle the drums.
I know that different stages require different sound. As far as I know, stage sound engineers traditionally handle this mostly with the channel eq controls of their mixers as well as lowering the volume on the bass if the room is bass-heavy, or making the vocals / sologuitar louder if the room diminishes highs. This is a very simplistic generalisation of course, and I may be wrong in these assumptions. I would be happy to learn where I'm mistaken.
I would think that if I gave them a stereo out, EQing that stereo signal would achieve a similar EQ envelope that sounds good in that room without messing up the balance between the instruments / vocals.
This would also fasten the setup process, as this particular hardware has 6 buses, so we would be able to pre-mix our monitors as well. In this scenario, we would take our own guitar amps, and they would go directly to the sound card without a mic set up.
Do you think this is a reasonable assumption, or are there nuances that I haven't taken into account?
Answer: It's going to get you close, but will still need tweaking for each gig - it might be better to get it right at some of the regular gigs you do, and save those. The sound guys will be able to give a general nudge eq-wise, to the sound you have from the mixer, so you'll generally be in the right ball park, more with balance between mics, instruments,etc. Although that will need tweaking during the gig. Sound checks are o.k., but usually done in an empty room, the acoustics of which will change, sometimes drastically, once it fills with audience.
On the occasions I've had to use the in-house p.a. and operator, quite a few have not been happy ones, as the sound guy seemed to have his own agenda. When I worked as sound guy, my preference for sound was always second to that of the performers. Some were happy to let me get on, others very exacting - and rightly so!
So, it's not as simple as setting it all up somewhere and thinking the job's done for ever, and handing the sound guys two leads! You'll still need to get that radio mic, or remote plug for guitar, and wander round the venue, and show the sound guys that you know exactly what you want. Also, don't forget that speaker configuration, amp placing, monitor siting, will all have a sometimes drastic effect on the sound - both on stage and auditorium, necessitating fiddling with your mixer...
Answer: This assumes that your band will sound the same every time, and throughout the entire performance.
In practice, on every gig I start out with a slightly different setup, and I keep having to adjust the mix throughout a performance. These are subtle changes, but sometimes 2 dB is the difference between having a guitar nicely embedded in the mix or not audible at all.
You'd have to be very careful with instrument presets (synth sounds vary massively in volume, guitar effects too, for instance), but you may be able to arrive at a set of presets you can use without changing the mix.
Voices would be the most difficult to accommodate, as they're the most prone to variation.
The sound engineer will also want to finetune the EQ for each channel to rule out feedback (which depends on the room characteristics, microphones and loudspeakers used, etc.
As an engineer, I wouldn't be a happy camper if a band pitched up at my venue and gave me a stereo mix from their XR18.


Find a function for my P&P RPG's skill calculation

Question: I'm (software engineer;) writing a computer program for a pen and paper RPG; We use a simple iterative procedure to get the actual skill level. I have been trying to create a continuous function which will come close to the same values. I will try and explain the procedure as well as I can:

skill level (lvl)
statistic (stat)
experience points (xp)

when you begin your lvl will equal your stat, while your xp > 0
while lvl < stat * 2
1 xp => lvl + 3
xp => xp - 1
while lvl < stat * 3
1 xp => lvl + 2
xp => xp - 1
while lvl < stat * 4
1 xp => lvl + 1
xp => xp - 1
etc, etc
quick list:
1xp = +3 lvl
1xp = +2 lvl
1xp = +1 lvl
1xp = +2/3 lvl
1xp = +1/2 lvl
As an example:
stat 60, 20 xp => lvl 120
stat 30, 20 xp => lvl 80
stat 60, 60 xp => lvl 190
stat 73, 20 xp => lvl 133
Could someone help me find a function which will calculate the right skill level given some xp and a statistic?
EDIT: Here is a link to a little JSFiddle which will calculate the correct level given a statistic and some xp. As you can see it's done with an itteration; I hope this fiddle helps.
fiddle
Thank you in advance!
Comment: Also, please add more words to explain what is going on.  There are "=" and "=>" symbols all over the place, and they seem to mean different things in different places.  Also, what is $x$?
Comment: @vadim123 I use the = to test for equality and => to 'assign to' or 'then'. I will edit the rest of my answer because you are correct. I misstyped and x should be xp, thank you. I will also try and get a better graph.
Comment: Hi! Since you're a software engineer, please use the proper markup to format your questions. This way indeed it's really easier to understand at best!
Comment: HI, thank you for the reaction. @MattAllegro, could you tell me more about which parts are improperly formatted? I might have used a code format but my psuedo-code is more descriptive then actual code. If you give me a bit more to work with I'll reformat the question.
Answer: Looking at your posted code, here is some pseudocode that does what you want without a loop.
$stat_a=ceil(stat/3)$
$stat_b=stat_a+ceil(stat/2)$
$stat_c=stat_b+ceil(stat)$
$stat_d=stat_c+ceil(stat*3/2)$
$value=stat+max(0,(1/2)*(xp-stat_d))+$
$+max(0,(2/3)*(min(xp,stat_d)-stat_c))+$
$+max(0,(1)*(min(xp,stat_c)-stat_b))+$
$+max(0,(2)*(min(xp,stat_b)-stat_a))+$
$+max(0,(3)*(min(xp,stat_a))$
Your question as posted doesn't make sense, and doesn't match your pseudocode (even after your revision of x to xp).  In the future, I suggest you proofread your questions more carefully.
Comment: I apologize if the question didn't make sense. I will try and formulate them better in the future.


What is the lower and upper bound on $R^2$ with no intercept?

Question: With an intercept in linear regression, I know that $R^2$ is bounded by [0,1]. Without an intercept, I know that $R^2$ can be negative. What is the lower bound for this case? And is the upper bound still 1 for this case?
Comment: The $R^2$ doesn't have any meaning when there is no intercept so it can be anything but the number itself is meaningless. There's a good paper on this. If I can find it, I'll link to it.
Comment: @ShawnHemelstrand will check it out. interesting that you just commented. it's a 3+ year old post with no recent noise, and I literally referred back to this yesterday and now I see your notification
Comment: Zhanxiong just posted an answer yesterday, which is why I saw and commented about the link. So its not quite so random after all.
Comment: I found it. http://web.ist.utl.pt/~ist11038/compute/errtheory/,regression/regrthroughorigin.pdf
Comment: You might also enjoy this paper on no-intercept regression: https://www.tandfonline.com/doi/full/10.1080/00224065.1977.11980770
Comment: @ShawnHemelstrand oh I see. I actually didn't see the new answer until you mentioned it. weird, I still don't see it in my notifications
Answer: There is no lower bound.
Consider an intercept-free regression on two points, $(0,a)$ and $(1,a+2)$. By forcing the regression line to go through the origin, you can make the fit as bad as you want by making $a$ very large.
I think the upper bound remains $1$, but I confess that I'm not sure, though I find it hard to believe otherwise.
EDIT
The upper bound is $1$. Consider a regression through $(0,0)$, $(1,1)$, and $(2,2)$.
Comment: Ah so the lower bound is negative infinity basically?
Comment: It's fairly awkward phrasing to me to call $-\infty$ the lower bound (more interestingly, the greatest lower bound), but I think you get the idea.
Comment: What happens if the two points were both on the y axis? Like say $(0, a), (0,-a)$. It seems you cannot even get a fit for these 2 points?
Comment: Throw that in the $(X^TX)^{-1}X^Ty$ matrix and see what happens! I've never considered myself his particular problem. Something is going to go wrong, but I don't know what.
Comment: yeah the system is singular
Answer: +1 to Dave's answer about the lower bound.
And yes, the upper bound is still $1$. In
$$ R^2 = 1-\frac{SS_\text{res}}{SS_\text{tot}}, $$
the numerator and the denominator of the fraction are both sums of squares, so they are nonnegative, so the entire fraction must be nonnegative. So the entire expression is maximized (with a value of $1$) if the fraction is zero.
And this will happen in a regression without an intercept if and only if all data points lie on a line that goes through the origin. So this upper bound will be achieved in a specific case.
Comment: Ooo right. that should've been obvious to me..
Answer: In order to determine the lower/upper bound of the $R^2$ for a linear model $y = X\beta + \varepsilon$ without an intercept (i.e., $X$ does not contain the column $e$ of all ones), it is helpful to first review why $R^2 \in [0, 1]$ when $X$ contains $e$.
In matrix form, regardless $X$ contains $e$ or not, $R^2$ can be written as (the first equality is by  definition, the second equality is by algebra)
\begin{align*}
R^2 = 1 - \frac{y^\top(I - H)y}{y^\top(I - n^{-1}ee^\top)y} =
\frac{y^\top(H - n^{-1}ee^\top)y}{y^\top(I - n^{-1}ee^\top)y}, \tag{$\star$}\label{0}
\end{align*}
where $H = X(X^\top X)^{-1}X^\top$ is hat matrix.
When $e$ is a column of $X$, one can easily verify that $He = e$ (geometrically, this is very obvious: when you project a vector onto a space that contains this vector, you get the vector itself), whence the matrix $H - n^{-1}ee^\top$ is idempotent:
\begin{align*}
(H - n^{-1}ee^\top)^2 = H^2 - n^{-1}Hee^\top - n^{-1}ee^\top H + n^{-1}ee^\top = H - n^{-1}ee^\top.
\end{align*}
Together with that $H - n^{-1}ee^\top$ is symmetric, it follows that $$y^\top(H - n^{-1}ee^\top)y = \|(H - n^{-1}ee^\top)y\|^2 \geq 0. \tag{1}\label{1} $$
This shows that $R^2 \geq 0$. On the other hand, since
\begin{align*}
y^\top(I - n^{-1}ee^\top)y - y^\top(H - n^{-1}ee^\top)y = y^\top(I - H)y
= \|(I - H)y\|^2 \geq 0
\end{align*}
and $y^\top(I - n^{-1}ee^\top)y > 0$ always hold (unless $y$ is a multiple of $e$, for which case $y$ has no variability and we usually rule this case out), we see that $R^2 \leq 1$. Note that since $I - H$ is idempotent and symmetric regardless $X$ contains $e$ or not, this part of the proof also applies to the intercept-free case. That is, $1$ continues to be the upper bound of intercept-free $R^2$.
Now when $e$ is not a column of $X$, the key property $He = e$ in general no longer holds. Consequently, $\eqref{1}$ becomes invalid (i.e., $y^\top(H - n^{-1}ee^\top)y$ can be negative). However, as argued above, $y^\top(I - n^{-1}ee^\top)y$ is always positive.  As a result, the right hand side of $\eqref{0}$ may become negative.
One step back, then does it have a fixed lower bound (possibly negative)?  The answer is no.  For example, consider the case $n = 2, p = 1$, $X = \begin{bmatrix}0 \\ 1 \end{bmatrix}$, $y = \begin{bmatrix} y_1 \\ y_2 \end{bmatrix}$. Direct evaluation of $\eqref{0}$ yields
\begin{align*}
R^2 = \frac{-(y_1 + y_2)^2 + 2y_2^2}{(y_1 - y_2)^2}.
\end{align*}
Setting $y_2 = M$, $y_1 = M + 1$ in the above expression gives
\begin{align*}
R^2 = -2M^2 - 4M - 1
\end{align*}
which tends to $-\infty$ as $M \to \infty$. This shows that intercept-free $R^2$ cannot be bounded from below.


How to check if all dom-elements in an object containing a value

Question: I saved all dom-elements in an object. I want that my Script is able to check every time when there is some input if all input fields are empty anymore. If yes, the button should still be disabled, otherwise the forward button is enabled and the user can click to the next page.
Ways like like using querySelectorAll input field etc. are working but I want that this is working with using the object.
The "areTruthy" variable is directly true if one input field is not empty anymore but it should only be true if all input fields are true. Where is my code wrong?
window.onload = () => {
  forward = document.getElementById("forward");
  input = {
    caseNumber: {
      month: document.getElementById("month"),
      year: document.getElementById("year"),
    },
    clientsInformation: {
      gender: document.getElementById("gender"),
      inpName: document.getElementById("inpName"),
    },
    adress: {
      street: document.getElementById("street"),
      houseNumber: document.getElementById("house-number"),
      postCode: document.getElementById("postCode"),
      city: document.getElementById("city"),
      receiver: document.getElementById("receiver"),
    },
  };

  addEventListener("input", () => {
    for (parts in input) {
      const areTruthy = Object.values(input[parts]).every((value) => value != "");
      if (areTruthy) {
        forward.style.backgroundColor = "rgb(77,55,120)";
        forward.style.color = "white";
        forward.disabled = false;
        forward.style.transition = "1s ease";
        forward.addEventListener("click", () => {
          window.open("case.html");
        });
      } else {
        forward.style.backgroundColor = "rgb(191,191,191)";
        forward.style.color = "black";
        forward.disabled = true;
      }
    }
  });
};

Fill in all fields

  <input id = "month" placeholder="Zahlenfolge">
  <input id = "year" placeholder = "Jahr">

  Name
  <select id = "gender">
    <option>Herr</option>
    <option>Frau</option>
  </select>
  <input id = "inpName" placeholder = "Name">

  Adresse

  <input placeholder = "Straße" id = "street" >
  <input placeholder = "Hausnummer" id = "house-number">
  <input placeholder = "Postleitzahl" id = "postCode" >

  <input placeholder = "Stadt" id = "city" >
  <input placeholder = "Adressant" id = "receiver" >

 <  Zurück

  Weiter  >

.navbar {
    display: flex;
    list-style: none;
    background-color: rgb(77, 55, 120);
    margin: 0;
    position: fixed;
    width: 100%;
    gap: 4rem;
    height: 50px;
    text-align: center;
    line-height: 45px;
    left: 0;
    top: 0;
  }

  .nav-text {
    text-decoration: none;
    color: white;
    width: auto;
    cursor: pointer;
    font-size: 18px;
    padding-bottom: 5px;
  }

  #wrapper {
    margin-top: 10rem;
    margin-left: 5rem;
    display: sticky;
  }

  #caseNumber {
    display: block;
  }

  input::placeholder {
    font-size: 1rem;
    text-align: center;
    line-height: 19rem;
  }

  .button-bar {
    position: fixed;
    bottom: 0;
    width: 100%;
    display: flex;
    margin: 0;
    left: 0;
  }

  .nav-inner {
    cursor: pointer;
    width: 50%;
    text-align: center;
    line-height: 83px;
  }

  #backward {
    background-color: rgb(101, 93, 93);
    color: white;
  }

  #forward {
    background-color: rgb(191, 191, 191);
  }

  h3 {
    left: 20vh;
    position: absolute;
    font-size: 24px;
    margin-top: 0.5rem;

  }

  #caseNumber {
    position: absolute;
    left: 20vh;
    margin-top: 6.5rem;
    text-align: left;
  }

  #name {
    position: absolute;
    left: 20vh;
    margin-top: 12.5rem;
  }

  label {
    display: inline-block;
    text-align: left;
    width: 140px;
    font-size: 20px;
  }

  input,
  select {
    width: 30vh;
    height: 5vh;
    font-size: 19px;
    border-radius: 5px;
    border-style: solid;
    border: 1px solid;
  }

  #adress {
    position: absolute;
    left: 20vh;
    margin-top: 18.5rem;
    max-width: 40rem;
    display: block;

  }

  #adressWrapper1 {

    display: flex;
    gap:5vh;
    flex-direction: column;
    left: 18vh;
    position: absolute;
    top:0rem
  }

  #adressWrapper2 {
    display: flex;
    gap:5vh;
    flex-direction: column;
    position: absolute;
    left: 50vh;
   top:0rem
  }

Answer: You are not checking input values. Also you are only checking every on child per parent object key, not on all children together so you need to lift if outside for
addEventListener("input", () => {
    let allFilled = true;
    for (parts in input) {
      const anyEmpty = Object.values(input[parts]).some(el => el.value == "");
      if (anyEmpty) {
        allFilled = false;
        break;
      }
    }
    if (allFilled) {
      forward.style.backgroundColor = "rgb(77,55,120)";
      forward.style.color = "white";
      forward.disabled = false;
      forward.style.transition = "1s ease";
      forward.addEventListener("click", () => {
        window.open("case.html");
      });
    } else {
      forward.style.backgroundColor = "rgb(191,191,191)";
      forward.style.color = "black";
      forward.disabled = true;
    }
  });
};

If you want to see what is exactly happening you can use this to log
  const anyEmpty = Object.values(input[parts]).some((el) => {
    console.log(el, el.value, el.value == "");
    return el.value == "";
  });