Angular8 app http error 405 on page refresh

Question: i am developing an using Angular8 and .NET Core 3.0 in Visual Studio. I have a page with a form which is working without any issues. However when i press F5 on that page i get the following error

Failed to load resource: the server responded with a status of 405
  (Method Not Allowed) [http://localhost:51871/notifications]

This is the submit function in the component class
  onSubmit() {

    if (this.registerForm.invalid) {
      return;
    }

    let post: NotificationsInterface = {
      email: this.registerForm.value.email,
      subject: this.registerForm.value.subject,
      text: this.registerForm.value.text,
    };

    this.http.post("Notifications", post).subscribe(result => {
      console.error("ok");

    }, error => console.error("error"));

  }

This is the notification class in C#
public class Notifications
{
    public string email { get; set; }
    public string subject { get; set; }
    public string text { get; set; }
}

This is the controller in C#
using Microsoft.AspNetCore.Mvc;
using HomeHelper.Models;

namespace HomeHelper.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class NotificationsController : Controller
    {
        [HttpPost]
        public IActionResult Post([FromBody]Notifications notification)
        {

            return Ok();

        }
   }
}

When i comment the controller part in C# the error is gone, however the data cannot be received. What is the best practice for such errors to be avoided ?
The error only occurs in the url " http://localhost:51871/notifications "
Best regards!
UPDATE: I have added the full code of the controller and the url with the specified error.
Comment: what is the url for angular app and c# app ? (generally domain point to angular app like localhost/xyz , localhost/abc , and one prefix endpoint for api like localhost/api/myApis , so we dont hit/refresh a url that contains api only angular internally point to that url , no via browser refresh and rest all other end point redirect to angular so no error should be there.
Comment: @LogicBlower Thank you for your reply ! I have updated my question with more detailed expalanation, in short the url is  " http://localhost:51871/notifications " and i have added the full controller logic. Kind regards.
Comment: your angular url is  localhost:51871/notifications  and backend Api url is too :  localhost:51871/notifications   : both are same ?
Answer: You can debug this issues by creating a get route with same end point in your controller.
when you refresh your Angular application as you have a route  localhost:51871/notifications in your controller your server resolves the route and points you to the controller but as of now there is no Get method (as browser sends a get request when you refresh) so it gives you error.
I guess either to adopt to hash location strategy or try changing the angular route  or you can do is all your backend api url should work  if there is a api in the url path
like localhost:51871/api/notifications that will help to sort api is getting called
Comment: Hello, your solution also worked. However the answer you provided is more detailed and well explained which can help other developers understand better how controllers work.
Answer: Try using hash location strategy.
RouterModule.forRoot(routes, {useHash: true})


Disabled item in menu in menu_tree_all_data

Question: I want to fetch all menu item list from specified menu list, I can fetch all of them with menu_tree_all_data, It return all item of menu and when I looked in in result I don't see enabled property
my sample code
  $menuItems=menu_tree_all_data('menu-footer-menu');
  dpm($menuItems);

(after that I put this in foreach statement and print them, but I want exclude disabled menu items)
My question is how can I find out that the menu item is disabled ?
Answer: 'hidden' key in the array returned, will tell you if the menu links is enabled or disabled. For all disabled menu links hidden will be '1'.
Answer: I am trying  to remove some menu items from the admin menu (which don't have any value in "title" field. We can have any other criteria to identify our target menus) as below (in theme_preprocess_page()).
Please note:

We are not supposed to make any changes in the already defined access configurations for those menus. We are not supposed to make any changes in the menu path.
Here, in this use case, the menus were showing in admin-menu list as those started with "admin/". Example: "admin/entity_ref_search/%".
We need to clear cache after adding this code (as changes are related with menu).

$menu_tree = menu_tree_all_data('management');
foreach ($menu_tree as $key => $menuItem) { // Runs once
  if (isset($menuItem['below']) && is_array($menuItem['below']) && !empty($menuItem['below'])) {
    foreach ($menuItem['below'] as $menu_link => $value) {
      if ($value['link']['title'] == '') {
          $value['link']['hidden'] = 1;
          menu_link_save($value['link']);
      }
    }
  }
}


Bellman Ford's algorithm with negative cycles

Question: So if I'm trying to find the shortest path using Bellman Ford's algorithm using this method to test if there is a path:
<code>public boolean hasPath(int v){
    return distTo[v] < Double.POSITIVE_INFINITY;
}
</code>
If I have a negative cycle then what happens to this algorithm? Does it still return true because I know that Dijkstra's algorithm doesn't work with negative cycles but what about Ford's?
Comment: Shouldn't you be taking the absolute then?
Answer: It will work, but the value may or may not be the shortest path. The real shortest path may be actually negative infinity, because if the negative circle reaches the destination node, there will be always a shorter path than the current shortest path.
This is actually how you use Bellman-Ford to detect negative circles. If after |V| loops, the (|V|+1)th still updates some shortest path, there is a negative circle in the graph.


Comparison of multiple regression models

Question: I have one dependent variable and many predictors, and I need to use a multiple regression model (linear).
Now, I performed a stepwise regression to determine which independent variables to include in the final model.
However, I see that when results are published, people usually show more than one model. For instance, they include just the first variable and then the first and the second, then the first, the second and the third, and so on. Showing that the adjusted coefficient of determination, $R^2$, improves.
Do I always have to do that, in order to show that each variable has a contribution (of course if coefficients are significant)?
Is there any reference to a formal procedure that better explains this?
Comment: (0) just opinion here (1) no you don't have to do this (2) I've never seen this. Usually if there a multiple models they are presented for research domain specific reasons (3) depending on your field of interest there may be standard ways of presenting models, worth fitting in with the crowed. (4) if doing backward selection (and EPV<50) you might want consider some for of boostrapping: either to validate modeling procedure or try and show stability of variable selection
Comment: @tomka: Read [this](http://stats.stackexchange.com/questions/20836/algorithms-for-automatic-model-selection/20856#20856) before using (or advocating) stepwise or similar methods. The first step should be determining whether the full model (presumably one including all available predictors in forms thought relevant to predicting the response) is over-fitting to a degree prejudicial to your model-building goals.
Comment: In econ, people commonly show many different model specificaitons as ways of showing that coefficients are or aren't robust to different controls.  Model selection is rarely the motivation for displaying tons of specifications.  Are you trying to estimate a causal parameter or predict?
Comment: EPV = events per variable BTW (by the way). "Observations per coefficient" would be a better way of putting it outside the context of logistic regression. Why couldn't you include all the independent variables?
Comment: I think the key is the type of model building strategy you choose, e.g. forward inclusion, backward exclusion, and which fit criterion or test is used. See for example: https://onlinecourses.science.psu.edu/stat501/node/91
Answer: If you've used a stepwise method (& see Algorithms for automatic model selection for the drawbacks), you can show the current model at each step (more usual for exposition of the method than because of any perceived intrinsic interest of each intermediate model, I'd have thought). Otherwise there's no point: as @charles says, it's common to compare models suggested by competing theories, or that differ in the expense of using them for prediction, or (in general) for reasons that depend on what the models say about the things they model.
It may be tempting to view the change in the coefficient of determination as you add each predictor as a measure of its importance for or contribution to the model's predictive power; but if the predictors are correlated, as they typically will be for observational data, this can be quite misleading—you get different answers by changing the order in which you add predictors. Jeromy Anglim's blog discusses the issues, & suggests better measures.


How is $3\equiv 3\bmod{5}$

Question: Just tried googling but couldn't find any example, but how $3\equiv 3\bmod{5}$
Googled it
Comment: If you count $1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,\ldots$, what is the third number that comes up?
Comment: When you divide $3$ by $5$, the remainder is $3$.
Comment: Also, $3 \equiv 3 \mod 5$, because $3-3=0 \equiv 0 \mod 5$.
Comment: If you are asking this question $\implies$ you need to look at the definition of modulo operation.  see http://en.wikipedia.org/wiki/Modulo_operation
Answer: If $a$ and $b$ are positive integers, there exist unique integers $q$, $r$ with
$$a = bq + r$$
and $0 \leq r < b$.
This theorem is called the division algorithm, and $a\ \%\ b$ is defined to be this $r$. In your case, $3 = 0\cdot5 + 3$ and $0 \leq 3 < 5$, so the answer is 3.
Answer: $a \equiv b \, (\text{mod} c)$ means $a-b$ is divisible by $c$. [Definition]
Since $3 - 3 = 0$ is divisible by $5$, we have $3 \equiv 3 \, (\text{mod} 5)$.
Answer: in general if a is less than b then a%b= a
so this implies that 3%5=3 and 6%7=6. another way of viewing this is by reading the statement a%b as "how many object remains if we SUCCESSIVELY take "b" objects from a bag with "a" objects untill we CAN'T TAKE ANYMORE!". Having that in mind 5%2 mean that we successively take 2 objects from a bag containing 5 objects. 1st we will take the 2 objects and leaving behind 3 objects, then we take another 2 object leaving behing 1 object in the bag, since we can't take 2 objects any more, SINCE there is only one remaining hence 5%2=1. applying the same analogy and solving for 3%5 we initially have 3 object in a bag and we want to successively take 5 objects. but we cant since the are insufficient objects in the bag so we can't take any objects and hence 3 objects will remain, this implies that 3%5=3.
hope this helps.
Comment: Check out the following link to help format questions/answers.
Comment: The only answer that actually made sense.  When people ask these kinds of questions, it's because of a lack of training in mathematics and the last thing they need are mathematicians trying to explain things with more math.  Thanks for breaking it down to simple terms! :)
Answer: hmmm
Actually Mod (%) returns the remainder
Given two positive numbers, a (the dividend) and b (the divisor), a modulus % is the remainder of the Euclidean division of a by b.
For instance, the expression "9 mod 8" would evaluate to 1 because 9divided by 8 leaves a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 leaves a remainder of 0.
hope this will help you
cheers
Comment: plus if your dividend if less than the divisor, then your remainder will be the dividend :)
Comment: It works for negative numbers too, unless you are using a non-standard definition on Mod?
Answer: a modulo b = r Where r is the remainder of the division a by b =>  a = b*q + r where q is the quotient of the division a/b.
For example: 9 modulo 4 = 1 and the quotient is 2
i.e 9 = (4*2) + 1
In a similar fashion:
3 modulo 5 = 3 and the quotient is 0-
=>3=(5*0)+3
Answer: by definition, the remainder of a division is the fractional part of a division.  if you have 3/5 (3 divided by 5), you have the fractional part represented as 3/5.  since a remainder is the dividend or numerator of a fraction, you just take 3 as your remainder (the divisor or denominator is not mentioned in the remainder).
therefore, 3 % 5 =  3.
just like 5 % 3 =
dividing 5 by 3, you get 1 and 2/5.  to get the remainder part, you know that 2 is the numerator so 2 is the remainder (the denominator, 5, is not mentioned in the remainder).

How is $3\equiv 3\bmod{5}$


Did I solve the problem $\lim_{n\to\infty}\sum_{k=0}^{n}\frac{1}{{n\choose k}} \to 2$ correctly?

Question: I'm in a calculus class I need to prove that
$$\lim_{n\to\infty}\sum_{k=0}^{n}\frac{1}{{n\choose k}} \to 2$$
Is my below solution valid?

We are given the problem
$$\lim_{n\to\infty}\sum_{k=0}^{n}\frac{1}{{n\choose k}}$$
Looking at this, we can see that the sum is always at least $2$, for:
$$\frac{1}{{n \choose 0}} + \frac{1}{{n \choose n}} = 1+1$$
$$= 2$$
looking at the above, we see that each term must be $\le 1$ for ${n \choose k}$ must always be less than or equal to one. Therefore:
$$\sum_{k=0}^{n}\frac{1}{{n\choose k}} \le n \cdot 1 = n$$
From the above, we can conclude that the graph of the function looks like an upside-down normal distribution curve, this is because it starts at 1, decreases, and then increases back to 1. From this, we can see that the function is symmetrical, and thus all the numbers in the middle(not including the edge cases) must be less than:
$$\frac{1}{{n \choose 1}} = \frac{1}{{n \choose n-1}} = \frac{1}{n}$$
Therefore, since
$$\lim_{n\to\infty}\frac{1}{n} \to 0$$
Our final answer is $$1+0+0+....+0+0+1 = 2$$
And therefore,
$$\lim_{n\to\infty}\sum_{k=0}^{n}\frac{1}{{n\choose k}} \to 2$$
Comment: If this reasoning was correct, all Riemann integrals would be zero. The individualterms go to zero, but the number of terms goes to infinity, so it is possible for the sequence to converge to a non-zero value.
Answer: "[W]e can conclude that the graph of the function looks like an upside-down normal distribution curve, this is because it starts at 1, decreases, and then increases back to 1" is not properly justified (though it is a true statement that we can bound $\frac{1}{\binom{n}{k}}$ by $\frac{1}{\binom{n}{1}}$ for $1 \leq k \leq n-1$).
It's true that the limit of a sum is the sum of the limits, but if a sum contains a variable number of elements, this no longer holds. Note that by your reasoning, the sum of $\frac{1}{n}$ with itself $n$ times would limit to $0$, when for any $n$, it equals $1$. (This mistake feels similar in flavor to me as this argument Where is the flaw in this "proof" that 1=2? (Derivative of repeated addition)) To prove this you need a stronger bound on $\frac{1}{\binom{n}{k}}$.
Comment: Thanks! Fixed it.
Answer: As has been pointed out, the sum has a variable number of elements, so your original proof doesn't go through.
But ${n \choose 0} = {n \choose n} = 1$ and ${n \choose 1} = {n \choose n-1} = n$.   So the sum is
$$2 + {2 \over n} + \sum_{k=2}^{n-2} {1 \over {n \choose k}}$$
Can you find a stronger bound on the terms of that sum?
Answer: Just for your curiosity.
In year $1981$,  Rocket proved the nice identity
$$S_n=\sum_{k=0}^{n}\frac{1}{{n\choose k}}=
\frac{n+1}{2^{n+1}}\sum_{k=1}^{n+1}\frac{2^k}{k}$$ Using special functions
$$\sum_{k=1}^{n+1}\frac{2^k}{k}=-2^{n+2} \Phi (2,1,n+2)-i \pi$$ where $\Phi(.)$ is the Lerch transcendent function.
Comment: Nice reference. (+1)


How to use installed SSL certificate to secure iOS app?

Question: I am trying to secure a iOS app by checking the installed SSL certificate exists or not. First I created a self-signed certificate with OpenSSL, and then install it to my iPhone. Right now I need to programmatically check this certificate is installed or not. If it exists, the app can run without limit, if not, use won't be able to use the app. So how to programmatically check this device is installed or not in my app code?
Why do we need to install SSL certificate on our iOS devices?
Comment: You want to handshake SSL with the server or need to check valid certificate on local?
Comment: @CodeChanger I need to check valid certificate on local iOS device.
Answer:
Users can install digital identities (certificates plus their
  associated private keys) onto their iOS devices by downloading them
  from within Safari, by opening them as email attachments, and by
  installing them with configuration profiles. Or, identities can be
  pushed from a Mobile Device Management (MDM) server. However,
  identities installed in any of these ways are added to the Apple
  keychain access group.

Refer below links for more info.
https://forums.developer.apple.com/thread/52345
https://developer.apple.com/library/archive/qa/qa1745/_index.html
Comment: @iAnurag agreed, this approach is more popular.
Comment: We can also add certificate in Our bundle and pin it...so that every time we can initiate SSL handshake...


Extending an existing LVM partition with fdisk

Question: I am looking for some help on expanding my LVM partitions. I have two disks I want to expand (10GB to 50GB and 40GB to 150GB).
I added the extra space in VMWare and the expanded disk is being picked up.
root@server:/home/admin# lvs
  LV                     VG                   Attr   LSize
  chat_history           chat_history_vg      -wi-ao  50.00g
  file_store             file_store_vg        -wi-ao 150.00g

They are on sdb and sdc. This is all new to me but from what I can see there is still more to do to make them accessible based on the Alloc PE/Size value shown below.
root@server:/home/admin# vgdisplay
  --- Volume group ---
  VG Name               file_store_vg
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  55
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                1
  Open LV               1
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               150.00 GiB
  PE Size               4.00 MiB
  Total PE              38399
  Alloc PE / Size       38399 / 150.00 GiB
  Free  PE / Size       0 / 0
  VG UUID               H4tar2-QUt0-xCd1-iC2T-kQb3-TBZR-aVGk9O

  --- Volume group ---
  VG Name               chat_history_vg
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  55
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                1
  Open LV               1
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               50.00 GiB
  PE Size               4.00 MiB
  Total PE              12799
  Alloc PE / Size       12799 / 50.00 GiB
  Free  PE / Size       0 / 0
  VG UUID               CHnhT1-UBNw-wFQe-AA1D-4z8N-Cx3M-EX6zvo

I have been reading up numerous sites on using fdisk. My first question relates is when I run fdisk on one of these partitions I get this warning about the lack of a partition table. Is this benign?
root@server:/home/admin# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel with disk identifier 0x2b40ee91.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.

Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)

Command (m for help): m
Command action

From what I understand, even though I have existing data on the disk I wish to expand I should still choose to 'n' to create a new partition?
One last question the RedHat site starts with the step to unmount the disk before working on it. Other sites don't mention this. Am I ok leaving /dev/sdb mounted during the expansion?
Thanks,
Michael
Answer: From what you describe, the "disk" is really a virtual disk inside a virtual machine and you increased the disk size by resizing the volume in VMWare?
If that's the case and the disk inside the virtual machine doesn't have a partition table (which is fine), than you have to use pvresize directly to increase the PV and don't use fdisk at all.
pvresize /dev/sdb

After that, you can extend the size of the logical volumes with lvresize.
As usual: Working with LVM, fdisk & co is really dangerous, especially if you don't fully understand how they relate to each other. Always make sure you have a current backup before doing that kind of operations.
Comment: From what I can gather vgdisplay shows that the extra disk is picked up already (I restarted the VM).  VG Size: 150.00 GiB and Alloc PE/Size:       38399 / 150.00 GiB. I am wondering if I now need to look at running lvresize and then resize2fs?


How do I add a Windows 2003 Domain Controller to a Windows 2000 Forest?

Question: I currently have a Windows 2000 Active Directory and Domain.  I want to move to 2008 but I believe I have to go to 2003 first.

I thought the best way to start was to add the 2003 server as a domain controller in the existing forest.
Run adprep forestprep to bring the domain to 2003 functionality

I've seen several article, including on here.  Apparently, if I just want to add a 2003 server as a domain controller I run dcpromo.  But then I'm still at 2000 AD level.
Since the goal is to move to 2003, then 2008, should I just run adprep and forestprep on the win2k domain controller and then use dcpromo on 2003?  Or should I just run dcpromo on the 2003 server and then use adprep and forestprep on the windows 2000 server?
What's the best way to do this?  Thanks.
update:  do you think this would work with going from 2000 to 2008?
Replace 2000 domain controller
Answer: Before you can add a Windows 2003 or 2008 domain controller (DC) to a Windows 2000 Active Directory you need to run the adprep /forestprep on the forest and adprep /domainprep on the domain in the forest where you'll be adding the new DC. A review of Microsoft's documentation of the process is probably in order before you start.
You do not need to install any Windows 2003 DCs prior to installing a Windows 2008 DC. You need only prepare the AD with adprep. Once you've done that you can begin to promote W2K8 DCs.
Comment: @johnny: You owe it to yourself to read the Microsoft documentation. It describes the process and the pre-migration concerns. Since this is an operation that you can't back off once you've completed it you need to be sure that you're all ready before you begin. You don't need to use a Windows 2003-based DC to upgrade your domain to Windows 2008.
Comment: but after I do that do I run dcpromo on the 2003 server?  That's where I'm confused.  Don't I have to have a 2003 DC before I do this?  I read on here SF, that you can just have a 2003 DC without the adprep.
Comment: you can go straight from windows 2000 to 2008?  OH I see the title in the article.  Thanks.


Rotation matrices and prior invariance for arbitrary dimensions

Question: I have a question about a rotation matrix, which can be represented in 2 dimensions as:
$$R_{2}(\theta)=\begin{bmatrix}  \cos\theta & \sin\theta \\ -\sin\theta & \cos\theta \end{bmatrix}$$
For some arbitrary angle $\theta$.  This can be extended to an arbitrary number of dimensions by adding an identity matrix:
$$R_{n}(\theta)=\begin{bmatrix} R_{2}(\theta) & 0 \\ 0 & I_{n-2}\end{bmatrix}$$
I have found some "invariance" properties of a n-dimensional prior distribution when rotated in 2 arbitrary dimensions.  My question is: can any rotation in arbitrary dimensions be represented by a sequence of 2-D rotations?  It doesn't matter if the sequence is unique or not for my purposes.
Or perhaps a better question is: if a prior distribution is invariant when rotated about 2 arbitrary dimensions, is it invariant when rotated about an arbitrary number of dimensions?
Comment: I think you'd be better asking this on math.SE, as the question clearly applies equally to anything that can be represented in $n$-dimensional space, not just a probability distribution.
Comment: @onestop - I am thinking the same thing.  I'll leave this question here anyway, just in case somebody in stats world knows the answer.  One thing I have found with stats (particularly Bayesian stats) is that you tend to come across just about every branch of maths (pardon the pun).  So maybe some stats person may know it.
Comment: I guess if you can "rearrange" the indexes (apply permutations) in you space the answer is yes otherwise it is no.
Comment: @robin- that is what I implicitly meant by rotating about "arbitrary" dimensions, in that it doesn't matter which "dimension" you call 1 and 2.
Answer: The answer, I believe, to your first question is "yes". This can be accomplished with Givens rotations, which allow for the annihilation of arbitrary elements of a matrix via a $2\times 2$ rotation matrix. The implication is that if you start with a rotation matrix, then you can reduce it to a diagonal matrix via Givens rotations. But, since orthogonality of a matrix is preserved by multiplication with another orthogonal matrix, this means that the diagonal matrix must be orthogonal, and hence, must contain only 1's and -1's. Additional rotations then reduce this matrix to the identity. The affirmative answer to your first question follows immediately.
Thus the space of $n\times n$ orthogonal matrices is spanned by Givens rotations with respect to matrix multiplication.
If this doesn't give you enough detail, let me know and I'll fill it in.
Comment: @probabilityislogic, Givens rotations are very popular in numerical linear algebra due to their simplicity and good numerical-stability characteristics. Some QR decomposition methods use them and I think any good SVD implementation will use them as well.
Comment: thanks for your answer, especially the terminology - I've never heard of "givens" rotation before.
Comment: Thanks for this, you have saved me a lot of useless algebra!  Because I can go "rotation 2-D" new prior invariant... "rotate 2-D" new new prior invariant ..... etc.
Comment: (+1) @Cardinal One small thing: the resulting diagonal matrix does not need to be the identity.  It can have an even number of -1's.  But those can be converted to +1's by means of suitable rotations (of 180 degrees).  It's also worth nothing the implicit assumption that the only rotations one can use are with respect to a fixed basis.  If not, then *any* rotation can always be written in the form $R_n(\theta)$ (that is, as a single such matrix) by choosing an appropriate basis adapted to that rotation.
Comment: @whuber, Good catch! Thank you, and I've updated it accordingly.
Answer: Yes, arbitrary rotations in an $n$ dimensional space can be written as the compositions of Givens rotations. The other question (and I think what you're aiming at) is

Or perhaps a better question is: if a
  prior distribution is invariant when
  rotated about 2 arbitrary dimensions,
  is it invariant when rotated about an
  arbitrary number of dimensions?

The answer is yes, and moreover look no further! since this class of distribution has been completely characterized: it's a subset of the elliptical distributions, when $\Sigma=I$. Elliptical distributions are all and only the rotationally invariant distirbutions, after an affine transformation of its variables. The standard normal multivariate distribution is its best-known example.


Finding the value of x within a given differential equation

Question: I know that $\frac{dy}{dx}=\cos^2(\frac{\pi y}{4})$.
I also know that $y=1$ when $x=0$. Which I believe can be written as the point $(0, 1)$ or $y(0) = 1$.
I am meant to find what $x$ equals when $y = 3$.
I figure I should integrate both sides to find $y$, and this leads me to $\int\frac{dy}{dx}=\int\cos^2(\frac{\pi y}{4}) = \frac{y}2 + \frac{\sin(\frac{\pi y}2)}\pi$.
I then substitute the given value $3$ for $y$ and get $\frac{3}2 + \frac{\sin(\frac{3\pi}{2})}\pi$.
Which simplifies to $\frac{3}2+\frac{-1}{\pi}$
My possible choices given for this particular problem are: $(\frac{1}8, -\frac{\pi}8, 1, -\frac{8}{\pi}, \frac{8}{\pi})$.
I don't believe this satisfies any of those given $x$ values for $y = 3$.
What is/are my mistake(s) in finding $x$; how could I fix them to solve for $x$?
Answer: Hint
The equation is separable. So rewite is as $$\frac{dx}{dy}=\frac{1}{\cos(\pi y/4)^2}$$ to get  $$x=\frac{4 \tan \left(\frac{\pi  y}{4}\right)}{\pi }+C$$
I am sure that you can take from here.
Comment: I've found $x=-4\pi+C$. I'm trying to determine the value of the constant, but I find it to equal 1, which doesn't make much sense to me, considering $-\frac{4}{\pi}+1$ is not one of my given answers either.
Comment: If you use the equation as I wrote it, the condition $y(0)=1$ gives you $0=\frac {4}{\pi}+C$. Then, ...
Comment: Right, so, $C = \frac{-4}\pi$, meaning the solution for $x$ is $\frac{-8}{\pi}$, ja?
Comment: You got it for this range of values ! Cheers.
Comment: I hope you understand how wrong was your integration process. This is most important point. The remaining is simple ! Cheers again.


Populating large matrix with values

Question: I have a 100K by 12 by 100K matrix that I need to populate with computation results.  I tried creating it using numpy.empty but got a memory error.
So I turned to dask instead.  I'm able to create the dask array.  I'm running a function that creates a vector as I traverse through the 0th and 1st dimension in a for loop.  I then populate this vector into the i,jth position of the matrix.  If I just populate the dask array as is, just the assignment step takes 50 milliseconds, which is way too long when extrapolated for all atomic cells in the matrix.
It seems it should be possible to speed up the assignment with dask's delayed function, but can't figure it out.
Here's how this would look without delay:
import dask.array as da
import dask.delayed as delayed
from dask import compute
import numpy as np

test_arr = da.empty(shape=(10000, 12, 10000), dtype='float32')
for i in range(test_arr.shape[0]):
    for j in range(test_arr.shape[1]):
        vals = np.random.normal(size=test_arr.shape[2])
        test_arr[i,j,:] = vals

And here is my attempt at using delay:
def populate_array(i, j, vec):
    test_arr[i, j, :] = vec
    return test_arr

for i in range(test_arr.shape[0]):
    for j in range(test_arr.shape[1]):
        vals = np.random.normal(size=test_arr.shape[2])
        delayed(populate_array)(i, j, vals)

compute(test_arr)

The latter doesn't error but just seems to return an array with all zeroes.
I know that I can also speed this up by getting rid of the for loop and vectorizing but assume that is currently not feasible.
I'm not tied to dask per se but it seems like a practical approach with a familiar syntax if coming from pandas / numpy.
Update:
Accepted answer works but the task stream has a lot of blank spaces.  I bring this up because my actual use case with a complex create_array_chunk formula just hangs.  Cannot see the dashboard or what's going on.
Comment: Have you done the math?  I'm not sure you're being realistic.  A 100k x 100k x 12 array of floats will be 500GB.  That's clearly outrageous.  Even your reduced 10k x 10k x 12 array will be 5GB.  Creating 1.2 billion random values is never going to be quick.
Comment: So the question is: why do you want to create such a huge matrix? Storing data in RAM is not possible here and storing it on disk will be very slow (at least few minutes). Practical experience shows that such huge matrix are rarely actually *needed*.
Comment: They're not random values, I was just using that for the purpose of this question.  Each atomic cell contains a probability density of measurements from a particular device at a particular point in time (so first 2 dimensions are time and device, 3rd dimension is probability density value of a pdf).
Comment: Then I'm not sure what you're expecting, nor what you plan to do with this enormous matrix.  Your original requirement is not achievable, and filling an array with data values is not generally something that can be sped up.  Are they coming from disk?  Do you really need all 12 devices in memory at once?
Comment: Ideally would like for this to compute within 45 minutes.  I'm content with someone showing whether assignment to a matrix can be sped up using dask on a much smaller dataframe.  If such functionality doesn't exist, that's also an answer.
Answer: This is how I'd do it. You don't fill an existing Dask Array, you build it chunk by chunk:
import dask.array as da
import dask.delayed as delayed
import numpy as np

shape = (10000, 12, 10000)

def create_array_chunk(i, j, k):
    # should use i and j information probably here
    return np.random.normal(size=k)

i_arrays = []
for i in range(shape[0]):
    j_arrays = []
    for j in range(shape[1]):
        darray = da.from_delayed(delayed(create_array_chunk)(i, j, shape[2]), dtype=np.float64, shape=(shape[2],))
        j_arrays.append(darray)
    j_stack=da.stack(j_arrays, axis=0)
    i_arrays.append(j_stack)
j_stack = da.stack(i_arrays, axis=0)

j_stack is a Dask Array structure of shape (10000, 12, 10000), has can be seen below:

It's a lazy structure, nothing has been computed yet. Be careful, if you call compute on it it will convert it to a Numpy array and take a lot of memory. You might want to stream it to disk using to_zarr or equivalent.
Comment: Although this works when the create_array_chunk is a dummy function like above, when I run it on my actual dataset with a much more complex set of operations in create_array_chunk it just hangs.  The dashboard is blank too and doesn't reload properly.  I noticed the task graph for the dummy code had a lot of blanks, so lots of time spent with handoff, maybe that's the issue.  I'll include a screenshot of the task screen in my original question.
Comment: The reason the task stream plot has a lot of blank is because chunks are much too small in this example, and the time taken to create them is shorter than the actual overrhead of working with Dask. More code should be moved to the delayed function.

Populating large matrix with values


Turn off perl-debug-m ansi escape sequences on Windows 7

Question: On Windows 7 cmd.exe, the perl6-debug-m script outputs ansi escape sequences to set the colors, I suppose.  How do I suppress these codes or at least make them functional?  I'm just getting started with Perl 6 after working with Perl 4 and Perl 5 for over 20 years.  I need this to work on Windows because of a program I'm trying to port from Perl 5.
<code>C:\rakudo\bin\lib>perl6 -v
This is Rakudo Star version 2018.04.1 built on MoarVM version 2018.04.1
implementing Perl 6.c.

C:\rakudo\bin\lib>perl6-debug-m
←[35m>>> LOADING ←[0m<REPL 1>
←[34m+ <REPL 1> (1 - 1)←[0m
←[34m| ←[0m←[1;33mREPL←[0m
←[34m> ←[0mquit
←[34m- ←[0mRun END blocks (y/N)?

C:\rakudo\bin\lib>perl6 -V |grep -v "moar:"
distro::auth=unknown
distro::desc=2018-05-20T09:17:12.587605-04:00
distro::is-win=True
distro::name=mswin32
distro::path-sep=;
distro::release=unknown
distro::signature=
distro::version=6.3
kernel::arch=unknown
kernel::archname=unknown-win32
kernel::auth=unknown
kernel::bits=64
kernel::desc=
kernel::hardware=unknown
kernel::name=win32
kernel::release=unknown
kernel::signature=
kernel::version=unknown
perl6::build-date=2018-05-07T10:08:20Z
perl6::codename=
perl6::implementation=Rakudo Star
perl6::language_version=6.c
perl6::libdir=C:\rakudo\share
perl6::prefix=C:\rakudo
perl6::release-number=
perl6::source-digest=688d0872d150048d083b7a499e9fc7a9e8b6ab5b
perl6::version=2018.04.1
repo::chain=inst#C:\Users\danhale\.perl6 inst#C:\rakudo\share\perl6\site inst#C:\rakudo\share\perl6\vendor inst#C:\rakudo\share\perl6 ap# nqp# perl5#
</code>
Comment: Can you use [powershell](https://learn.microsoft.com/en-us/powershell/scripting/setup/installing-windows-powershell?view=powershell-6#finding-powershell-in-windows-10-81-80-and-7)? It seems to work well with ANSI, and [allow some configuration options](https://superuser.com/questions/1264444/using-ansi-escape-codes-in-powershell-prompt-to-add-color-looses-meaning-after)
Comment: Thank you for the suggestion, but it didn't work for me.  Under powershell the perl6-debug-m.bat script still outputs the escape sequences, not color changes.

`C:\Users\danhale>powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\Users\danhale> perl6-debug-m
←[35m>>> LOADING ←[0m
←[34m+  (1 - 1)←[0m
←[34m| ←[0m←[1;33mREPL←[0m
←[34m> ←[0m'
Comment: you might need to install a program such as this one... https://github.com/adoxa/ansicon/
Answer: There's currently no way to disable them (I just checked the debugger interface's source to verify that). I've previously used ANSICON on Windows in order to work with applications that produce ANSI color codes, including the Perl 6 debugger, and recall that it rendered them fine.
Comment: Thank you.  That worked.  I found I needed to run ansicon whenever a new command window is opened.  I wrote a wrapper script p6db.cmd to do this every time, just in case.

@ ANSICON.EXE c:\rakudo\bin\perl6-debug-m.bat "%*"
Comment: Now that I've RTFM for ansicon :), I realize I can make it permanently apply to current and future invocations of cmd.exe by invoking it once with the -i flag.  So there's no need for my p6db wrapper script.


Clicar num sinalzinho de + e aparecer mais inputs

Question: Haveria alguma forma de um usuário ao clicar em uma pequena imagem com um sinal de +, adicionar mais inputs aos formulário. No caso eu tenho os seguintes inputs:

Identificação do Responsável da Empresa 1: <input type="text" name="socio1">

Número de Identificação Civil do Responsável da Empresa 1: <input type="text" name="socio1">

Nif do Responsável da Empresa 1: <input type="text" name="socio1">

Identificação do Responsável da Empresa 2: <input type="text" name="socio1">

Assim colocaria uma imagem com um sinal de + e ao clicar nessa imagem apareciam mais 3 inputs mas com os names diferentes.
Como poderia fazer isso?
Comment: Estou marcando como duplicata porque a resposta lá na outra pergunta explica bem como fazer isso. Se tiver alguma dúvida, pode ser o caso de editar e reabrir está pergunta, ou fazer uma nova mais específica.
Answer: HTML
<button id="add">
+
</button>

JavaScript
var add = document.getElementById('add');

add.addEventListener('click', function(e) {
  var newInput = document.createElement('input');
  var newListItem = document.createElement('li');
  newListItem.appendChild(newInput);
  var list = document.getElementById('list');
  list.appendChild(newListItem);
});

Live: https://jsfiddle.net/tx0xf059/
Answer:

<input name="a" type="text" value="input 1"/>
<input name="b" type="text" value="input 2"/>
<input name="c" type="text" value="input 3"/>

 +

Comment: Parece que você entendeu errado a pergunta.


htaccess: redirect old asp url strings

Question: I have a client we built a new site for and are trying to redirect his old urls to point to the new site. The problem is they are long strings and my current solution is not working correctly. This is what I currently have:
Redirect 301 /frameset.asp?page=services.htm http://domain.com/

this results in the user being sent to:
http://domain.com/.asp?page=services.htm

Last but not least is there a wildcard solution?
FROM THE ACCEPTED ANSWER: (Just so this is documented for the next guy, yhis is what i ended up using.
RewriteEngine on
RewriteCond %{THE_REQUEST} /frameset\.asp\?page=* [NC]
RewriteRule ^ http://domain.com/? [L,R]

Answer: You can not redirect query strings using a Redirect directiv, you have to use mod-rewrite
Try :
 RewriteEngine on

 RewriteCond %{THE_REQUEST} /frameset\.asp\?page=services\.html [NC]
RewriteRule ^ http://domain.com/? [L,R]

htaccess: redirect old asp url strings


Como ter vários endereços em uma classe de pessoa?

Question: Caso uma pessoa possua mais de um endereço. O código abaixo está correto?
public class Pessoa implements Serializable {
    private static final long serialVersionUID = 1L;

    private int codigo;
    private String descricao;
    private String dataNascimento;
    private String cpfcnpj;
    private PessoaEndereco pessoaEndereco;

Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Não, desta forma você só conseguirá ter um endereço. Tem várias formas de permitir mais de um endereço, uma delas, talvez a mais simples, é esta:
public class Pessoa implements Serializable {
    private static final long serialVersionUID = 1L;

    private int codigo;
    private String descricao;
    private String dataNascimento;
    private String cpfcnpj;
    private ArrayList<PessoaEndereco> Enderecos;

Coloquei no GitHub para referência futura.
Obviamente você deve ter métodos de acesso aos diversos endereços de forma fácil. A única mudança foi criar uma lista de endereços onde só cabia um.


Possible to create an overflow table which will contain MySQL table data

Question: I have a web page which displays a table listing 50 products with product information (ID, price, stock and colour) from a mysql table.
As I am designing this webpage for a specific resolution and system I would like to display the information in two tables side by side, rather than using one table with a overflow scrollbar.
Currently I have done this by using two tables posited next to each other and then inserting half of the products into each table with the use of 'between' function to select each half by the product ID:
Table 1:
<code>"SELECT * FROM products WHERE ID between '01' AND '25'"
</code>
and Table 2:
<code>"SELECT * FROM products WHERE ID between '26' AND '50'"
</code>
This works and does what I initially wanted but as I would also like to add 'sort by' buttons this option won't work. For example if I wanted to sort the tables by colour the two tables will only sort their specified half of the data.
Does anyone know if it's possible to create a separate overflow table that will just continue to list the information in order in both tables as if it was just one table?
Allowing me to use:
<code>"SELECT * FROM products"
</code>
with the relevant 'sort' options.
Thanks.
Answer: I'd like to point you to a post I made about splitting an array into multiple columns of data similar to how array_chunk() works but "vertically", this means you can apply your sorting to a single SQL query and then split your array output afterwards and loop through your "tables of data"
https://stackoverflow.com/a/8735136/61795
<code>function array_chunk_vertical($array,$cols = 3, $pad = array(null))
{
  if (is_array($array) == true and empty($array) != true)
  {
    // total items in the array
    $count = count($array);
    // count the number of vertical rows
    $rows = ceil($count/$cols);
    // group the array into colums
    $array = array_chunk($array,$rows);
    // if the array is less that the number of cols required
    // pad it to ensure length remains constant
    if (count($array) < $cols)
    {
      $array = array_pad($array,$cols,$pad);
    }
    // pad the array with a null character as required
    foreach($array as $key => $value)
    {
      $array[$key] = array_pad($value,$rows,null);
    }
    // now inverse the rows with the cols
    foreach($array as $key => $value)
    {
      foreach($value as $sub_key => $sub_value)
      {
        $output[$sub_key][$key] = $sub_value;
      }
    }
    // spit it out
    return $output;
  }
  else
  {
    // oops
    return $array;
  }
}
</code>


Como fazer um botão "voltar ao topo" em uma página?

Question: Como eu posso fazer um botão voltar ao topo em uma página html?
Jquery, javascript, o que seria melhor?
Answer: Usando Jquery
//scroll normal
$('html,body').scrollTop(0);

//scroll suave
$('html, body').animate({scrollTop:0}, 'slow'); //slow, medium, fast

Usando Javascript
var scrollTop = function() {
    window.scrollTo(0, 0);
};

Comment: E como eu coloco efeito? Para suavizar a ida para o topo.
Comment: Editei a resposta.
Answer: A melhor forma vai depender das suas necessidades.
Além da forma apresentada pelo Mauro, pode utilizar somente html apontado o href do link para o trecho da página que fique no topo:

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

  bla bla
 bla bla
 bla bla

Voltar ao topo
Comment: +1 Solução limpa e objetiva, e funciona mesmo com JS desligado. Não faz parte da pergunta, mas se ele quiser scroll animado, tem scripts pra isso sem perder a compatibilidade. Eis um sem jQuery: https://github.com/cferdinandi/smooth-scroll/blob/master/src/js/smooth-scroll.js e um com https://css-tricks.com/snippets/jquery/smooth-scrolling/#comment-197181


RewriteCond not working on force https for HTTP_HOST

Question: I am trying to write a condition that will force https on the live host name(domain.com), but not if it's on our local testing host name (domain.local).
Here is what I have:
#force https
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !domain\.local [NC]
RewriteRule ^(.*?)$ https://www.domain.com/$1 [L,R=301]

This condition rewrites to https but also redirects domain.local to domain.com
I've also tried this condition in place of the middle condition which doesn't do anything on .local or .com:
RewriteCond %{HTTP_HOST} ^domain\.com [NC]

Here is the complete contents of my htaccess file
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

#force ssl
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L,NE]

#rewrite payments subdomain
RewriteCond %{HTTP_HOST} ^payments\.domain\.local$ [NC]
RewriteRule ^(.*)$ https://otherdomain.com/dmi_domain.htm [NC,R=301,L]
RewriteCond %{HTTP_HOST} ^payments\.domain\.com$ [NC]
RewriteRule ^(.*)$ https://otherdomain.com/loanadmin/dmi_domain.htm [NC,R=301,L]

#agents folder to subdomain
RewriteCond %{HTTP_HOST} ^agents\.domain\.local$ [NC]
RewriteRule ^agents/(.*)$ /agents/$1 [L,P]
RewriteCond %{HTTP_HOST} ^agents\.domain\.com$ [NC]
RewriteRule ^agents/(.*)$ /agents/$1 [L,P]

#force www for .com
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^payments\. [NC]
RewriteCond %{HTTP_HOST} !^agents\. [NC]
RewriteCond %{HTTP_HOST} !^domain\.local
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*?)$ https://www.%{HTTP_HOST}/$1 [L,R=301]

#force www for .local
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^payments\. [NC]
RewriteCond %{HTTP_HOST} !^agents\. [NC]
RewriteCond %{HTTP_HOST} !^domain\.com
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*?)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

#force trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_URI} !^/rate-panel/xml/
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*)$ $1/ [L,R=301]

#get rid of index.php in url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*)$ /index.php/$1 [L]

thanks
Answer: You may use
RewriteCond %{ENV:HTTPS} off
some time https flag not working . Don't know why. But I have found a solution to use ENV:HTTPS . This stop redirect loop for me.
Comment: It's not for all time work. anyway, did you found your proper solution?
Comment: In my case I needed to use RewriteCond %{ENV:HTTPS} !=on ('off' did not work in my particular environment).
Comment: I'm not sure, but probably. Sorry if I haven't posted anything about it, I was focused. Thank you anyway for your attention.
Comment: Do you have still problem?
Comment: No, not anymore. Thanks mate.
Answer: You need to move your bottom http->https rule to the top of your .htaccess just below RewriteBase / line. Also use this slightly modified rule:
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !local [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L,NE]

Comment: In my case I needed to use RewriteCond %{ENV:HTTPS} !=on. So the environmental variable mentioned below and specifically '!=on' instead of 'off'.
Comment: @giovannipds `%{HTTPS}` is standard Apache variable. You may be behind proxy or firewall. Check server documentation from your hosting providers.
Comment: Yes, but I've figured out right now that the problem is with my hosting server (I've compared the same codes on two different servers). Anyway, I'm still looking for an alternative. Best regards.
Comment: Thanks, but still doesn't work. Nothing happens on either .com or .local.
Comment: Can you update your question with out latest .htaccess? Is this some kind of PHP/CMS framework?
Comment: Htaccess updated. The site is on the codeigniter php framework. thanks!
Comment: ok rule looks fine. Is it possible that CI is forcing it back to `http://`? Can you run your request in Firebug and see what redirections you get in Net tab.
Comment: I meant to add that if i remove the condition the redirect works fine, but it redirects both .local and .com to https.I don't see any redirects in the Net tab, but I don't know exactly where to find the redirects.
Comment: Your suggetion to move the https rule to the top saved my day! Many thanks! Can you please help me to understand why this rule must be the first?
Comment: Didn't solve to me, looks the problem it's with %{HTTPS} variable. Alternatives?
Answer: As many state, sometimes only RewriteCond %{ENV:HTTPS} !=on works


PCI-E Connection between two servers?

Question: I'd like to achieve PCI-E Gen3 X16 duplex speed for my server file transfers. I thought about this and asked myself why not.
I saw cable connecting PCI-E slot and a PCI-E riser card. So I believe there is already a cable exists to connect PCI-E slot to another PCI-E slot. Now I guess I need some kind of connection protocol to work with PCI-E.
Anyone has knowledge about this?
Comment: @jspirto did you go with myrinet?  If not look at the mellanox infiniband stuff its a lot cheaper!
Comment: Which host's PCI-E controller do you propose owning the interface itself?  PCI-E isn't a multihomed connection technology.
Comment: Exactly how is your storage array going to support file transfers at those speeds?
Comment: Currently I can get 2gb/sec rate from my raid0 array.
Answer: A PCI-e bus is not the same thing as a PCI-e device.
There would have to be custom circuitry on both sides, most likely a PCI-e card that supports high-bandwidth interconnects.
The interconnect protocol most likely to be of use to you is Infiniband (IB), which can run at 4-lane speeds up to 40gbits/sec.
This is not cheap by any means, but for a point-to-point solution, you can't beat it.
Comment: Mellanox (and probably others) make 56Gb IB cards now. They support hardware RDMA, probably the fastest way to transfer data from one server to the other (some NFS implementations already support it, don't think any CIFS do though).
Comment: There is also Myrinet.
Comment: I guess Myrinet is the way to go. 10gbps is very cheap. 40gbps is very expensive right now. Thanks for your answer.
Answer: That bus is not designed for machine to machine communications directly.  You would need to use some sort of networking device to connect between the machines.
While there are PCI Express 16 network cards out there (gigabit and above), any of these solutions will incur overhead penalties, and you will not get the full speed of the bus.
Comment: For the record, I'll go with Myrinet. Although I've found this product: http://www.magma.com/pcie_linkx8g2.asp

You may need to check it out.

PCI-E Connection between two servers?


Como calcular colunas igual a do Skeleton

Question: A .col-md-1 é calculado assim: 100/12 = 8.3333...3 no Skeleton foi calculado de outra maneira que retornou o seguinte resultado:
.one.column,
.one.columns {
  width: 4.66666666667%;
}

Qual lógica o desenvolvedor usou? Qual cálculo?
Answer: Realmente, é um enigma meio complexo de se resolver. Depois de alguns testes e algumas pesquisas, não foi possível obter o resultado de 4.66..67%, porém cheguei em 4,25%.
De acordo com esse problema no github, parece que a base de colunas do skeleton antigamente era 16, ao invés do convencional 12 (usado por muitos atualmente - Bootstrap).
Outro ponto que analisei, foi o método que muitos estavam calculando a grid do skeleton quando convertido para SASS ou LESS, ao invés de diminuir o valor de margem para cada lateral (esquerda e direita), foi removido apenas 1 dos lados.
Veja a fórmula usada nesse exemplo de conversão para LESS/SASS:
.one.columns {
    width: @column-width*1-(@column-margin/2)*1%;
}

//Essa área é a interessante para a análise: (@column-margin/2)

Considerando que o próprio github não é atualizado a 2 anos e que o próprio desenvolvedor falou estar ausente nas atualizações, usando alguns valores do CSS original do Skeleton e algumas fórmulas usadas em LESS e SASS cheguei a esse cálculo:

@larguraTotal = 100;
  @colunas = 16;
  @margem = 4%;
  Fórmula: @larguraTotal / @colunas - (@margem / 2);

  100/16 - (4%/2) = 4,25%

Link para skeleton SASS, aqui.
Link para skeleton LESS, aqui.

Lembrando que a fórmula atual usada em LESS e SASS já difere do cálculo que eu elaborei, pois hoje o sistema é baseado em uma grid de 12 colunas, portanto a conta não vai bater. Usei a lógica de cálculo com 16 colunas (com base na grid usada antigamente) para tentar responder o por que de ser obtido o valor de 4,66..67% encontrado no arquivo CSS original do Skeleton.
Comment: @GuilhermeSpinXO Como já faz muito tempo que isso foi criado e não é atualizado, talvez foi usado algum guia de "boas práticas" que já não se aplica mais hoje. Por exemplo, o grid do primeiro arquivo publicado (2011) usava `px` ao invés de `%`, talvez tenha sido algum cálculo para fazer essa conversão. Mas sugiro que abandone a tentativa de chegar nesse resultado, já que temos muitos outros frameworks excelentes e atualizados. O que vale a pena é o resultado final =D
Comment: Oloco... Eu nunca iria conseguir chegar a 4,25%, obrigado pela sua resposta, vou marca-la como resolvido, já que não se pode obter `4,66...67%`, mas cara será que não é outra lógica ? vou pesquisar mais a fundo, mas acho que não vou obter o resultado diferente, o seu é o mais próximo.


CakePHP - Conditional behaviour not working in find()

Question: I have SubjectGroup, which hasMany Subject.
class SubjectGroup extends AppModel {

    public $hasMany = array(
        'Subject' => array('order' => 'Subject.name')
    );

}

class Subject extends AppModel {

    public $belongsTo = array('SubjectGroup');

}

I want to get all SubjectGroups, and recursively retrieve their Subjects, but only the Subjects that have a status of 2.
$this->SubjectGroup->find('all', array(
    'contain' => 'Subject.status != 2',
    'order' => 'SubjectGroup.name'
));

There are no errors, but it just returns all Subjects, even the ones with status = 2.
Answer: I think you need to set the condition for the Subjects more explicitly.
$this->SubjectGroup->find(
    'all',
    array(
        'contain' => array(
            'Subject' => array(
                'conditions' => array('NOT' => array('Subject.status' => 2)),
            ),
        ),
        'order' => 'SubjectGroup.name'
    )
);

Comment: Didn't work still.  Same thing where it just retrieves all subjects.
Answer: Well, I finally discovered two problems.  I was trying to add an $actsAs definition to the controller, to bring in the behaviour. I completely forgot it's not the model.  You have to bring in the behaviour in the controller action.
class SubjectGroupsController extends AppController {

    public function index()  {

        $this->SubjectGroup->Behaviors->attach('Containable');

        $subjectGroups = $this->SubjectGroup->find('all', array(
            'contain' => 'Subject.status != 2',
            'order' => 'SubjectGroup.name'
        ));
    }

}

But anyway, the condition only seems to work if I use the very basic syntax of:
'contain' => 'Subject.status != 2'
Anything more complex doesn't seem to work for me:
// DOES NOT WORK
'contain' => array(
    'Subject' => array(
        'conditions' => array('NOT' => array('Subject.status' => 2)),
    ),
)

Comment: How come you're not using $actsAs to give the model the containable behaviour in the subject_group.php and subject.php model files, or better still in app_model.php?


Como criar uma lista para salvar inúmeros plots gerados pela minha função no R?

Question: Boa noite caros amigos!
Criei um script que gera várias pirâmides etárias simultaneamente. No caso, a grande vantagem é gerar centenas, ou até milhares de pirâmides em poucos minutos. Estou precisando de ajuda para indexar os Plots gerados (pirâmides) para conseguir acessá-las depois. O ideal seria indexar pelo Nome da localidade.
Enfim, vou compartilhar meu script que faz 646 pirâmides para todas as cidades do Estado de SP.
Bom, se vocês rodarem esse código com o banco de dados que utilizei verão que ele funciona e gera todas pirâmides, porém, como disse no inicio preciso de alguma dica para conseguir indexar esse tanto de Plot gerado.... Obrigado.
library(plotrix)
library(GetoptLong)
library(tidyverse)

#Importando base de dados com valores absolutos estimados para 2020
#produzidos pela Funda??o SEADE

p_etarias_raw <-
  read.csv2(
    "C:\\Users\\User\\Desktop\\projetos\\piramides_etarias\\p_etarias_estado_sp.csv",
    encoding = "windows-1250",
    sep = ";",
    dec = ",",
    header = TRUE)

view(p_etarias_raw)

p_etarias <- p_etarias_raw[,2:647]

dataset_length <- length(names(p_etarias))

for (a in 2:dataset_length) {
  p_etarias[2,a] <- (p_etarias[2,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[3,a] <- (p_etarias[3,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[4,a] <- (p_etarias[4,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[5,a] <- (p_etarias[5,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[6,a] <- (p_etarias[6,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[7,a] <- (p_etarias[7,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[8,a] <- (p_etarias[8,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[9,a] <- (p_etarias[9,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[10,a] <- (p_etarias[10,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[11,a] <- (p_etarias[11,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[12,a] <- (p_etarias[12,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[13,a] <- (p_etarias[13,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[14,a] <- (p_etarias[14,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[15,a] <- (p_etarias[15,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[16,a] <- (p_etarias[17,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[17,a] <- (p_etarias[17,a]/sum(p_etarias[1,a]) * 100)
  p_etarias[19,a] <- (p_etarias[19,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[20,a] <- (p_etarias[20,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[21,a] <- (p_etarias[21,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[22,a] <- (p_etarias[22,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[23,a] <- (p_etarias[23,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[24,a] <- (p_etarias[24,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[25,a] <- (p_etarias[25,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[26,a] <- (p_etarias[26,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[27,a] <- (p_etarias[27,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[28,a] <- (p_etarias[28,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[29,a] <- (p_etarias[29,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[30,a] <- (p_etarias[30,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[31,a] <- (p_etarias[31,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[32,a] <- (p_etarias[32,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[33,a] <- (p_etarias[33,a]/sum(p_etarias[18,a]) * 100)
  p_etarias[34,a] <- (p_etarias[34,a]/sum(p_etarias[18,a]) * 100)
}

agelabels <- c(
  "0-4",
  "5-9",
  "10-14",
  "15-19",
  "20-24",
  "25-29",
  "30-34",
  "35-39",
  "40-44",
  "45-49",
  "50-54",
  "55-59",
  "60-64",
  "65-69",
  "70-74",
  "75+"
)

#Definindo as cores das barras
mcol <- color.id('#5882FA')
fcol <- color.id('#FE2E2E')

for (i in 2:dataset_length) {

  xy.pop <- c(p_etarias[2:17, i])
  xx.pop <- c(p_etarias[19:34, i])

  municipality_name = names(p_etarias[i])

  piramide1 <- par(
    mar = pyramid.plot(
      xy.pop,
      xx.pop,
      labels = agelabels,
      main = qq("Pirâmide Etária @{municipality_name}"),
      lxcol = mcol,
      rxcol = fcol,
      gap = 1.3,
      show.values = FALSE,
      top.labels = c("Masc", "Idade", "Fem"),
      ndig = 3,
    )
  )

}```

Comment: Lucca, boa noite! Consegue disponibilizar o arquivo: p_etarias_estado_sp.csv? Abraço
Answer: Vou usar um exemplo genérico, para a resposta ser útil para o maior número possível de usuários. No caso, gerar uma lista com os box plots de cada coluna de um data.frame.
# Dados de exemplo
dados <- as.data.frame(matrix(rnorm(100), 10, 10))
names(dados) <- LETTERS[1:10]

Para armazenar gráficos em objetos, existe a função recordPlot. Ela funciona para gráficos gerados via graphics e grid (então não serve, por exemplo, para gráficos gerados por ggplot2).
Crie uma lista vazia para receber os gráficos e use um loop para atualizar:
plot.list <- vector("list", ncol(dados))
names(plot.list) <- names(dados)
# Poderia usar simplesmente `plot.list <- NULL', mas é uma boa prática já criar o objeto com o tamanho final.

for (id in names(dados)) {
  plot.new()
  boxplot(dados[[id]], main = paste("Boxplot da coluna", id))
  plot.list[id] <- list(recordPlot())
}

Ou, para evitar o uso de loop (uma boa prática em R), coloque o código que gera o gráfico em uma função e use lapply:
plot.bp <- function(j) {
  plot.new()
  boxplot(dados[[j]], main = paste("Boxplot da coluna", names(dados)[j]))
  recordPlot()
}

plot.list <- lapply(seq(ncol(dados)), plot.bp)
names(plot.list) <- names(dados)

Para exibir, por exemplo, o plot da variável B:
plot.list["B"]
# ou
plot.list$B


Chain-calling parent initialisers in python

Question: Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class initialiser in an initialiser? If this still sounds too vague, here's some code.
class A(object):
    def __init__(self):
        print "Initialiser A was called"

class B(A):
    def __init__(self):
        super(B,self).__init__()
        print "Initialiser B was called"

class C(B):
    def __init__(self):
        super(C,self).__init__()
        print "Initialiser C was called"

c = C()

This is how I do it now. But it still seems a bit too non-generic - you still must pass a correct type by hand.
Now, I've tried using self.__class__ as a first argument to super(), but, obviously it doesn't work - if you put it in the initialiser for C - fair enough, B's initialiser gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's initialiser again (this ends in an infinite recursion).
There is no need to think about diamond inheritance for now, I am just interested in solving this specific problem.
Comment: I am not ready to answer this question if full. But anyway, what if the class gets renamed? What if I want to write a decorator function to automate this kind of chaining? Now I see, that this is not possible, but at the time of asking the question I did not know that.
Comment: "But it still seems a bit too non-generic - you still must pass a correct type by hand."??  You're passing the class name to super().  You never need to know the superclass or anything else.  How is this non-generic?  What problem does it create?  Can you give an example where this breaks?
Comment: @shylent, if I understand your question, what your describing is possible.  You can use super() to make parent references fully generic if you understand the mro.  Google "python super is super", watch the video.
Comment: @shylent actually, reading your question again I believe the infinite recursion you're experiencing is not what you think it is.  I believe the mro order is making you call a constructor you're not intending to.  I just dealt with this same thing myself not long ago.  No matter what you pass to the first argument of super, super will call the first constructor in the mro, not the type you passed in.  For instance if you call super(self.__class__, self) in the constructor of C, you will still call B's constructor because it is the first parent in the mro.
Answer: Python 3 includes an improved super() which allows use like this:
super().__init__(args)

Comment: if I have more than one parent class how will super identify the which parent class to invoke ?
Comment: @kracekumar It will be determined by the class' Method Resolution Order (MRO), which you can find out by calling `MyClassName.mro()`. I may be incorrect, but I believe that the first specified parent is the one whose `__init__` will be called.
Comment: @user815423426 Because it makes the up-calls more generic, no longer repeating the class name, which was the subject of the original question.
Comment: @ironfroggy, would you mind elaborating on How does this improved super help with the question? I just found this old thread and I am having the same exact questions. Also Have things improved for Python 2.x since this question was first asked?
Comment: @kracekumar, super(X,obj) actually returns a special "super" object that, when you do an attribute access on it, will return the attribute that would have been returned had class X had no attributes at all. for example, super(X,obj).__init__ will return the __init__ method of your obj as if __init__ in class X not been there. Now, if class X has two parents, and X.__init__ doesnt exist, the default behavior is to call __init__ of only _one_ of the parents, not both. This is effectively what super is doing... giving you one of the parents.
Answer: The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".
Comment: Python IS a strongly typed language, but it is dynamically typed. There is a difference between weak and dynamic typing.
Comment: @Leopd: `super()` only works with new-style classes, i.e. you must inherit from `object`.
Comment: In Python 2.6 I get `TypeError: super() argument 1 must be type, not classobj` using this method.  Am I missing something?
Comment: I've had a really hard time deciding which answer to accept, but I will accept this one, simply because it is relevant to the version of python I am using.
Comment: @TheScienceBoy the definitions are clear though. Python is strong-dynamic. Something like Java is strong-static. PHP is weak-dynamic. Static typing guarantees (within some limits at least) that input parameters are the correct type. Strong typing means that the compiler/runtime will not attempt to coerce the *value* of one type to another.. like changing "1" to a 1 so you can do math on it. Please see here: https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language
Comment: @Philluminati: See http://www.python.org/dev/peps/pep-0020/
Comment: How on earth can you possibly say Python's philosophy is "explicit is better than implicit". It's not a strongly typed language.
Comment: In Python 2.7 you get: **TypeError: must be type, not classobj**
Comment: @JoshSmeaton: I would definitely not categorise Python as being strongly typed. The definition varies, I guess, but to me a strongly typed language is one where all variables and parameters must have a type. This is just not the case in Python. I can call methods on a variable without having any idea what object it is or what type it is. As long as that type has that method with the correct input parameters, it is called.

I'm not starting a discussion about the definition of strongly typed. I just want an opposing opinion to appear in this list to show that you're not necessarily right. :)
Comment: This answer really doesn't make sense for being explicit, and you may find that passing the class to the super(cls, instance) call does not do what you want.  It actually implicitly - calls the parent class based on [method resolution order](https://docs.python.org/3/library/stdtypes.html?highlight=mro#class.mro). You can google more about it from here.  To explicitly call a class constructor as you suggest you should go with @Jay Parikh 's answer.  Using super() is all about implicit reference so as to decouple the class from its parent.
Answer: You can simply write :
class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"


Prove this following integral inequality

Question: Prove that $$\int_{1}^{\infty}\frac{(\sqrt{u+b})du}{u^2 + b} > \frac{\pi}{2}, b > 0$$
I know it is necessary to show the work done, but i already tried by parts and by substitution, and it does not help in nothing. My guess is that it will involves trigonometric functions, but i don't know how to get rid of the b in the integrals. Any tip?
Comment: In general, when you're trying to show $\int_a^b f(x) \; \mathrm{d}x > \text{[something}]$, you should try to get a bound on $f$. For example, here if you could prove that $\sqrt{u + b}/(u^2 + b) \geq e^{-u}$, we would conclude $$\int_1^\infty \frac{\sqrt{u + b}}{u^2 + b} \; \mathrm{d}u \geq \int_1^\infty e^{-u} \; \mathrm{d}x = 1/e.$$
This isn't exactly what you want, but it's an example of the kind of argument you could try to use
Answer: Here's a partial answer / an idea for an approach.

For $b \geq 0$, let
$$\ell(b) = \int_1^\infty \frac{\sqrt{u+b}}{u^2+b} \; \mathrm{d}u$$
We see that
$$\ell'(b) = \int_1^\infty \frac{\partial}{\partial b} \frac{\sqrt{u+b}}{u^2+b} \; \mathrm{d}u = \int_1^\infty \frac{u^2 - 2u - b}{2\sqrt{b+u}(b+u^2)^2} \; \mathrm{d}u \geq \int_1^\infty \frac{u^2 -2u - b}{2(b+u^2)^{5/2}}\; \mathrm{d}u,$$
and we can actually do this last integral! It turns out to be
$$\int \frac{u^2 - 2u - b}{2(b+u^2)^{5/2}} \; \mathrm{d}u = \frac{b (2-3 u)-u^3}{6 b \left(b+u^2\right)^{3/2}} + c,$$
so
$$\ell'(b) \geq \int_1^\infty \frac{u^2 - 2u - b}{2(b+u^2)^{5/2}} \; \mathrm{d}u = \frac{\frac{1}{\sqrt{b+1}}-1}{6 b}.$$
Now, for any $b > 0$, we have
$$\ell(b) = \ell(0) + \int_0^b \ell'(t) \; \mathrm{d}t \geq \ell(0) + \int_0^b \frac{\frac{1}{\sqrt{t+1}}-1}{6 t} \; \mathrm{d}t = 2 + \frac{1}{3} \log \left(\frac{2}{1 + \sqrt{1 + b}}\right).$$
For $b \leq 38$ this is enough to show $\ell(b) > \pi/2$. With a better bound on $\ell'$ we might be able to improve this.


How to create a window in Unity from a script and attach it to an existing tab?

Question: i'm trying to make a custom editor script for Unity, but i'm stuck in what I thought would be an easy step.
When using UnityEditor.GetWindow(), the window doesn't open in the main tab but as a separate Window. The scene view is not attached to the main Unity window.
I've tried a few workarounds but none seem to work:

First I tried to use the desiredDockNextTo parameter from the API, but I keep getting an error i'm not able to fix.
  Type inspWndType = typeof(Editor).Assembly.GetType("UnityEditor.SceneView");

 EditorWindow[] allWindows = Resources.FindObjectsOfTypeAll<EditorWindow>();
 Type[] insWindTypeList = new Type[allWindows.Length];
 for(int i = 0; i < allWindows.Length; i++)
 {
     insWindTypeList[i] = allWindows[i].GetType();
 }
 var window = EditorWindow.GetWindow<typeof(inspWndType)>(insWindTypeList);

I keep getting an error in <typeof(inspWndType)> saying that it's a variable instead of a type (I also tried with inspWndType.gettype or casting it, nothing worked).

Also tried using Jayatubi's Docker and it didn't work either.

TLDR: I want to be able to create a window using EditorWindow.GetWindow() and dock it from a script.
Thank you to anyone that could help me with this.
Answer: First of all typeof expects a compile time constant type not a dynamic variable.
So if something it should be e.g.
var inspWndType = typeof(UnityEditor.SceneView);

However, the second issue: You can't have this as generic type parameter.
What you want to do is assuming your editorwindow looks like e.g.
public class YOURWINDOW : EditorWindow
{
    ...
}

then it should rather be
var inspWndType = typeof(UnityEditor.SceneView);
var window = EditorWindow.GetWindow<YOURWINDOW>(inspWndType);

There is no reflection needed here as you don't want o deal with any runtime types and UnityEditor.SceneView is public anyway.

Example:
using System;
using UnityEditor;

public class ExampleWindow : EditorWindow
{
    [MenuItem("Examples/ExampleWindow")]
    private static void Init()
    {
        var inspWndType = typeof(SceneView);
        var window = GetWindow<ExampleWindow>(inspWndType);
    }

    private void OnGUI()
    {
        EditorGUILayout.LabelField("Tadaaaa!", EditorStyles.boldLabel);
    }
}

Now if you actually want to have it docked no matter what tab is opened you could use reflection to find just each and every inheritor of EditorWindow and do
using Linq;

...

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(type =>type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(EditorWindow))).ToArray();
// This kind of equals doing something like
//var typesList = new List<Type>();
//var assemblies = AppDomain.CurrentDomain.GetAssemblies();
//foreach(var assembly in assemblies)
//{
//    var allTypes = assembly.GetTypes();
//    foreach(var type in allTypes)
//    {
//        if(type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(EditorWindow)))
//        {
//            typesList.Add(type);
//        }
//    }
//}
//var types = typesList.ToArray();

var window = GetWindow<YOURWINDOW>(types);

Note though that due to order the ConsoleWindow is kinda the first entry almost so if there is a console tab opened it would always first attach to that one ^^
You can still add your preferred ones though like e.g.
var types = new List<Type>()
{
    // first add your preferences
    typeof(SceneView),
    typeof(Editor).Assembly.GetType("UnityEditor.GameView"),
    typeof(Editor).Assembly.GetType("UnityEditor.SceneHierarchyWindow"),
    typeof(Editor).Assembly.GetType("UnityEditor.ConsoleWindow"),
    typeof(Editor).Assembly.GetType("UnityEditor.ProjectBrowser"),
    typeof(Editor).Assembly.GetType("UnityEditor.InspectorWindow")
};

// and then add all others as fallback (who cares about duplicates at this point ? ;) )
types.AddRange(AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(type =>type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(EditorWindow))));
var window = GetWindow<YOURWINDOW>(types.ToArray());

since it literally goes through this array from start to end and uses the first matching opened window type.
Comment: @SalvioCalvilloMatas `Debug.Log(string.Join('\n', AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(type =>type.IsClass && !type.IsAbstract&& type.IsSubclassOf(typeof(EditorWindow))).Select(t => t.FullName)));` will give you a complete list of anything inheriting from `EditorWindow` in the console ;)
Comment: @SalvioCalvilloMatas your specific ones you will need to get via reflection as shown e.g. `typeof(Editor).Assembly.GetType("UnityEditor.InspectorWindow")`, `typeof(Editor).Assembly.GetType("UnityEditor.ConsoleWindow")`, `typeof(Editor).Assembly.GetType("UnityEditor.ProjectBrowser")` etc because they are not public
Comment: @SalviCalvillo there is no need to use `GetWindow` for the internal windows as you do not want to open one of these windows you rather want to open **your** window next to one of them. **IF** you really wanted to actively open one of the other windows you will need to use the non-generic overload `ar window = EditorWindow.GetWindow(test);` but you will not be able to attach those ... though i sounds like in such case you rather want to use a custom window Layout ;)
Comment: You helped me a lot, but is there any way to get other types of unity windows?
I want to use some other basic window types and i can't find any public reference for them. More specifically I'd need SceneHierarchyWindow, GameView, ConsoleWindow, InspectorWindow and ProjectBrowser. I don't know if there's a way to access them easily, but trying UnityEditor. didn't work for me. Thanks a lot!
Comment: It's not possible to use GetWindow with non-public windows? With the typeof there's the same problem as before, that it passes as a variable.
`Type test = typeof(Editor).Assembly.GetType("UnityEditor.InspectorWindow");
var window = EditorWindow.GetWindow (types.ToArray());`
Comment: It would've been great if it was possible to attach two windows easily from script i believe, i'll take a look at custom window layouts. You have helped me a lot, thank you!


Como especiar a sequência de activities a serem iniciadas?

Question: Olá.
Estou com uma dúvida. Tenho um APP no qual 8 Activities, entre elas possui uma Splash Screen Activity que apresenta a minha logo e depois entra no meu APP.
A Splash Screen está definida como padrão, mas preciso definir uma outra Activity como sendo sencudária para ser iniciada após a tela que possui a logo, pois está iniciando outra Activity que não é a tela inicial do App.
Como poderia realizar esse procedimento?
Segue o meu AndroidManifes.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" />
        <activity android:name=".Main"/>
        <activity android:name=".ContraDenuncia" />
        <activity android:name=".FavorDenuncia" />
        <activity android:name=".Investigados" />
        <activity android:name=".Objetivo" />
        <activity android:name=".SplashScreenActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>/>
        </activity>

    </application>

</manifest>

Preciso que a Activity Main seja executada após a SplashScreenActivity.
Muito Obrigado.
Answer: Você terá que fazer a sua outra activity ser startada após a execução da sua splash. Mas antes disso, coloque a <activity android:name=".SplashScreenActivity"> como primeira no manifest. Após isso vá no código da sua splash, e após terminar de executar a splash, coloque isso
    Intent it = new Intent(this, MainActivity.class);
    startActivity(it);

Na definição do intenent, você está especificando digamos, "de onde para onde" e o método startActivity() é para começar a atividade definida no Intent
Comment: Muito Obrigado!
Funcionou belezinha.
Comment: Boa, precisar tamos ae =)


Remember Me Page - Unexpected End of File error

Question: I have a page that remembers the users name.  But it tells me that there is an unexpected end of file.  I looked for missing brackets, found one, added it, but now it tells me theres an unexpected bracket (by the session end).
Any help???
<!DOCTYPE html>

<title>Remember UserName</title>
<?PHP
    session_start();
    if (isset($_POST['Submit1'])) {
        $username = $_POST['username'];

        if ($username == $_POST['username']) {
            print "Welcome back, ". " $username ";
            print "Would you like to log out?";
            echo '<form action="Logout" method="post">
            <Input Type = "Submit" Name = "Logout" Value = "Logout">
            </FORM>';

        }
        else {
            print ("You're not logged in to this site");
        }
    }

    if (isset($_POST['Logout'])) {
        $Logout = $_POST['Logout'];

        if ($Logout == $_POST['Logout'])
            print "You are now logged out";
            session_destroy()
    }
?>

<Form name ="form1" Method ="POST" Action ="index.php">
<Input Type = "text" Value ="username" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</FORM>

Comment: This is why you indent your code! 1. you're setting `$Logout` and then testing it against the value you just assigned...why? 2. I'm guessing you want braces around that logout code? These things become quite apparent when you properly format / indent your code. Did I mention you should *indent your code* ?
Comment: why are you assigning the value of `$_POST['Logout']` and then immediately checking if its what you just assigned...? You're also missing braces around that logout code - you can only use that shorthand syntax when your conditional block is one line.
Comment: try to normally format your code and look closely to indentation. you'll see your mistakes.
Comment: @sevenseacat Looks like we're on the same page tonight!
Answer: This line:
session_destroy()
                 ^-- right there

is missing a closing semi-colon
session_destroy();

Which is the cause for the Unexpected End of File error error message.

Notes:
Using your present code, you may very well get the following error message: (which I tested)

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at...

It's best to use the following method, placing session_start(); above any output:
Sidenote: I am uncertain why you're using session_start(); in your code, since there are no session variables in your posted code. If you're not going to be using something to the effect of $username=$_SESSION['username']; then you can safely remove it.
<?php
session_start();
?>

<!DOCTYPE html>

<title>Remember UserName</title>
<?php
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];

if ($username == $_POST['username']) {
print "Welcome back, ". " $username ";
print "Would you like to log out?";
echo '<form action="Logout" method="post">
<Input Type = "Submit" Name = "Logout" Value = "Logout">
</FORM>';

}
else {
print ("You're not logged in to this site");
}
}

if (isset($_POST['Logout'])) {
$Logout = $_POST['Logout'];

if ($Logout == $_POST['Logout'])
        print "You are now logged out";
        session_destroy();
}
?>

<Form name ="form1" Method ="POST" Action ="index.php">
<Input Type = "text" Value ="username" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</FORM>

Additional notes:
I also noticed a few discrepencies in your logout button.
This echo '<form action="Logout" method="post">
should be replaced with echo '<form action="" method="post">
(unless you're using an actual file, yet this seems to be most unlikely)
Plus, you can narrow this down:
if (isset($_POST['Logout'])) {
    $Logout = $_POST['Logout'];

    if ($Logout == $_POST['Logout'])
        print "You are now logged out";
        session_destroy();
}

to:
if (isset($_POST['Logout'])) {
        print "You are now logged out";
        session_destroy();
}

Complete rewrite:
<?php
session_start();
?>

<!DOCTYPE html>

<title>Remember UserName</title>

<?php
if (isset($_POST['Submit1'])) {
    $username = $_POST['username'];

if ($username == $_POST['username']) {
    print "Welcome back, ". " $username ";
    print "Would you like to log out?";
    echo '<form action="" method="post">
        <Input Type = "Submit" Name = "Logout" Value = "Logout">
</form>';

}
else {
    print ("You're not logged in to this site");
    }
}

if (isset($_POST['Logout'])) {
    print "You are now logged out";
    session_destroy();
  }
?>

<form name ="form1" Method ="POST" Action ="">
<Input Type = "text" Value ="username" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</form>

Comment: Plus, I double checked the OP's bracing matches, and it's fine (they're screwy, but there are none missing). Usually a missing closing or extra brace is the cause, as would a missing semi-colon.
Comment: Thanks a lot!  I did some copy pastes from online sites and added some of my own coding.   Can you explain tell me the difference if I use $username = $_POST['username'] and $username=$_SESSION['username'];?  Is it only a session when I use the $_SESSION?  Would this still work without the session start and session destroy?  And if so, how?  I thought only cookies and sessions would allow a name remember.
Comment: You're welcome. If you plan on using sessions, then you first need to assign a variable to the session name. I have found success in using a chained method, to the effect of `$username = $_POST['username'] =  $_SESSION['username'];` works. @TheOneNOnlyQ which starts by assigning a variable `$username` then passing it on to `$_POST['username']` and in turn over to `$_SESSION['username']`
Answer: While not the explicit cause of your EOF error,
if (isset($_POST['Logout'])) {
    $Logout = $_POST['Logout'];          // Okay you assigned it...

    if ($Logout == $_POST['Logout'])     // ... and now you're seeing if they're equal?
    {                                    // You want braces here...
        print "You are now logged out";
        session_destroy();     // As Fred -ii- mentioned you're missing this ;
    }                                    // ...and here
}

Comment: I agree on the bracing method. The OP's bracing is indeed off. I will +1 this.


Solaris disk I/O spike... which monitoring tools do I need?

Question: My Solaris 10 websever / database server disk io keeps spiking at intermittent times.
Using iostat -xtc 5 the reads / sec will jump from 3.0 to 1450.0 and %busy will jump to 98%
The apache access log doesn't indicate anything out of the ordinary. In other words, requests aren't any higher than usual.
top doesn't generate anything useful. The cpu usage is fine with mysql using about 20% and nothing else to speak of really.
What monitoring tool should I be using to see what process is using excessive disk I/O? or if there are any other suggestions I'm all ears.
Thanks
Answer: You need to use dtrace. Try the dtrace toolkit, it comes with lots of scripts and howto files.
Here's a nice presentation, and a few one-liners you may find useful.
Files Opened by process
$ dtrace -qn 'syscall::open*:entry{ printf("%s %s\n",execname,copyinstr(arg0)); }'

Read Bytes by process
$ dtrace -n 'sysinfo:::readch{ @[execname] = sum(arg0);}'

Write Bytes by process
$ dtrace -n 'sysinfo:::writech{ @[execname] = sum(arg0);}'


Get dates of a day of week in a date range

Question: I need a function in PostgreSQL that accepts a date range and returns the dates inside the date range that are Mondays. Anybody have an idea how this could be done?
Answer: create function f(dr daterange)
returns setof date as $$
    select d::date
    from generate_series(
        lower(dr), upper(dr), interval '1 day'
    ) s (d)
    where
        extract(dow from d) = 1 and
        d::date <@ dr;
    ;
$$ language sql;

select f(daterange('2014-01-01', '2014-01-20'));
     f
------------
 2014-01-06
 2014-01-13

Comment: Nice and simple. A minor gripe: When working with a `daterange` inclusive / exclusive borders should be observed.
Answer: The most efficient way should be to find the first Monday and generate a series in steps of 7 days:
CREATE OR REPLACE FUNCTION f_mondays(dr daterange)
  RETURNS TABLE (day date) AS
$func$
SELECT generate_series(a + (8 - EXTRACT(ISODOW FROM a)::int) % 7
                     , z
                     , interval '7 days')::date
FROM  (
   SELECT CASE WHEN lower_inc(dr) THEN lower(dr) ELSE lower(dr) + 1 END AS a
        , CASE WHEN upper_inc(dr) THEN upper(dr) ELSE upper(dr) - 1 END AS z
   ) sub
$func$ LANGUAGE sql;

The subquery extracts start (a) and end (z) of the range, adjusted for inclusive and exclusive bounds with range functions.
The expression (8 - EXTRACT(ISODOW FROM a)::int) % 7 returns the number of days until the next monday. 0 if it's Monday already. The manual about EXTRACT().
generate_series() can iterate any given interval - 7 days in this case. The result is a timestamp, so we cast to date.
Only generates Mondays in the range, no WHERE clause needed.

Call:
SELECT day FROM f_mondays('[2014-04-14,2014-05-02)'::daterange);

Returns:
day
----------
2014-04-14
2014-04-21
2014-04-28

SQL Fiddle.


ios haptic feedback globally for all UIButtons

Question: how can I apply haptic feedback throughout my app for every touchupinside event of every UIButton without writing code for each individual button? I have tried making a UIButton category and overriding <code>- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event</code> but this messes up some of my UIButton actions, (i may have implemented it badly)
does anyone have any suggestions?
Answer: Overriding in categories such kind of methods that mentioned @ChoungTran isn't such good idea. If you want to customize the default methods in a Category, it'd be better to do that in a swizzled method.
But, I'll prefer to make a custom class derived from UIButton, and implement that logic there and use that button everywhere where I need haptic.

From Apple documentation:

Although the Objective-C language currently allows you to use a
  category to override methods the class inherits, or even methods
  declared in the class interface, you are strongly discouraged from
  doing so. A category is not a substitute for a subclass. There are
  several significant shortcomings to using a category to override
  methods:
When a category overrides an inherited method, the method in the
  category can, as usual, invoke the inherited implementation via a
  message to super. However, if a category overrides a method that
  exists in the category's class, there is no way to invoke the original
  implementation.
A category cannot reliably override methods declared in another
  category of the same class.
This issue is of particular significance because many of the Cocoa
  classes are implemented using categories. A framework-defined method
  you try to override may itself have been implemented in a category,
  and so which implementation takes precedence is not defined.
The very presence of some category methods may cause behavior changes
  across all frameworks. For example, if you override the
  windowWillClose: delegate method in a category on NSObject, all window
  delegates in your program then respond using the category method; the
  behavior of all your instances of NSWindow may change. Categories you
  add on a framework class may cause mysterious changes in behavior and
  lead to crashes.
Comment: Besides, In your app you can have a case, where you don't want haptic (for example some system alerts which use UIButton subclasses, etc..)
Answer: Try to use category with class UIButton. In UIButton-Extention register event forControlEvents:UIControlEventTouchUpInside
<code>#import "UIButton+Extention.h"

@implementation UIButton (Extention)

- (instancetype)init
{
    self = [super init];

    if (self)
    {
        [self addTarget:self action:@selector(customTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];

    [self addTarget:self action:@selector(customTouchUpInside:)
                                 forControlEvents:UIControlEventTouchUpInside];
}
- (void)customTouchUpInside:(UIButton *)sender
{
    //TODO:
    NSLog(@"Do something here...");
}
@end
</code>
Updated: Register event when UIButton created programmatically
Comment: Note that -awakeFromNib would be called only for buttons, loaded from nibs, but not for ones created programmatically.
Comment: @BorysVerebskyi yes, nibs or storyboard. If you want to create programmatically, try this

 - (instancetype)init
 {
     self = [super init];

     if (self)
     {
         [self addTarget:self action:@selector(customTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
     }
     return self;
 }
Comment: It's possible to create a category that will handle all buttons. I think that instead of overriding -awakeFromNib one should override -viewWillMoveToSuperview. But I'm too lazy to check this now.


How do I change the color of the :active link in my nav on page reload?

Question: I'm surprised I'm having so much difficulty finding the answer to this question considering this is such a common thing. I'm working on a tumblr site and I need to change the color of the active link when the user clicks different links in the nav. I've seen tons of answers like this...
$(function() {
    var $sidebar = '#sidebar';

    $sidebar.on('click', '.item a', function(e) {

        console.log('hit desktop');
        $('ul.nav li a').removeClass('active');
        $(this).addClass('active');
 });

//css
.active { color: black;}

So this function gets called and added to the DOM momentarily but is removed as soon as the page is refreshed to the new link. But assuming your not using sometype of accordion when you click a nav link the user is redirected to that page. So even though the function gets called as soon as the page refreshes to the new one the function is essentially erased. Can I use a cookie or an if statement to compare the href? Can this be done client side?
Answer: simply use CSS:
a{
    color:blue;
}
a:hover{
    color:green;
}
a:active{
    color:orange;
}
a:visited{
    color:red;
}

:active is when the user is holding the click on the link or the functions related to the link is being called or working.
:visited is when the user has clicked on it and it is done
Comment: Note that it's a colon `:` before `active`, not a period `.` as in the question. Period is for classes.
Comment: It shows up in inspector but has no effect on the menu. I have no idea why.
Comment: see, this works perfectly, there might be something else wrong with your code: http://jsfiddle.net/CMMt7/
Comment: But the link clicked on will open a new page so the active state will only be seen for a fraction of a second. active works if the link stays on the page (a page anchor for example).
Answer: I'm not entirely sure what you meant but if you'd like to change the active state on the current navigation button and remove the state from all others through jquery then you could do it like this.
$('#sidebar li a').click(function() {
    $(this).closest("li").addClass('active').siblings().removeClass('active');
    return(false);
});

and the HTML would be

First Item

Second Item

Third Item

This would essentially add the class active to the current list item and remove it from all other siblings.
Comment: What you wrote is a variation of the code I wrote. The problem is when you click the link in the nav it gets added but then the pages href changes to the new page and then is removed again.
Comment: Although the css elements of this code would work, return false would prevent the client navigating to the page they selected.
Comment: There is a hacky way to do it, but it has to be hard coded manually. Is it possible to see a link to the tumblr just to make sure of a couple of things?