Get the route name of the current page

Question: The route name of the current page is available in page.html.twig?
The page is generated by the default feedback form.
Answer: To get the current route name, use:
$route_name = \Drupal::routeMatch()->getRouteName();

You can add the current page's route name as a variable in your theme's ".theme" file.  Add a _preprocess_page function like this, and clear the drupal cache.
/**
 * Implements hook_preprocess_page().
 *
 */
function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::routeMatch()->getRouteName();
}

Then you can access in page.html.twig like this:
{{ route_name }}

Note: \Drupal::routeMatch()->getRouteName() will sometimes return null.
If you are inside a class, to do things properly, you'll want to inject the route match service in the constructor and then call it this way:
$this->currentRouteMatch->getRouteName()

The constructor (and variable) will be like this:
  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $currentRouteMatch;

  /**
   * Constructs a new ThemeTestSubscriber.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $current_route_match
   */
  public function __construct(RouteMatchInterface $current_route_match) {
    $this->currentRouteMatch = $current_route_match;
  }

If it's a service class, you'd then pass it into the service in the yaml file in your custom module:
services:
  mymodule.service:
    class: Drupal\mymodule\MyCustomService
    arguments: ['@current_route_match']

Comment: There is a CLI (line mode command) somewhere that shows all drupal routes... can't seem to remember what it was... I'll update (unless someone else knows)
Comment: @sea26.2 It use to be `drupal router:debug`  :grin: but is now `drupal debug:router`
Answer: Another way to handle this is by using the Devel Module if you are developing locally.

Download and enable Devel
Log in as an administrator
Navigate to /admin/config/development/devel/toolbar
check "Current route info"
click Save configuration
Navigate to the url you are wanting the route information for
Click Devel in your toolbar above the admin menu
Click Current route info

If you are in a theme or situation where you can't find the admin toolbar or can't find the "Current route info" menu link, modify the url /devel/routes/item?path=/user/1 where /user/1 is the path that you are looking for path information for. It appears that this method will not work for pages that change routes based on get parameters... for example, ?_format=json or other custom routing like that.
Answer: Not for in a template, but to inspect the route: drush core:route:
drush core:route --path=/node/123/latest
drush core:route --path=/user/1

Ref: drush commands docs: core:route
Example:
$ drush core:route --path=/node/123/latest
name: entity.node.latest_version
path: '/node/{node}/latest'
defaults:
  _entity_view: node.full
  _title_callback: '\Drupal\Core\Entity\Controller\EntityController::title'
requirements:
  _entity_access: node.view
  _content_moderation_latest_version: 'TRUE'
  node: \d+
options:
  _content_moderation_entity_type: node
  parameters:
    node:
      type: 'entity:node'
      load_latest_revision: true
      converter: paramconverter.entity
  _access_checks:
    - access_check.entity
    - access_check.latest_revision

Get the route name of the current page


Debugging MySQL performance issues

Question: I work on a WordPress site that gets roughly 100K page views per day. We use Varnish for a caching layer.  Recently, we've been running into a problem where, seemingly at random, MySQL performance slows to a halt and brings down our application.  Here's a graph from New Relic for an outage that occurred yesterday:

This has happened twice in the past week.  The site will run fine for a week without anybody touching the production servers, and then this happens out of nowhere.  Usual response time is around 500ms, and here it is peaking at 60K ms(!).  The problem is fixed by stopping apache, letting the database cool down, and then starting apache back up.
It's not that more queries are being run, or that a particular slow query is running and causing this problem.  If I take any of the 'slow queries' that are being reported by New Relic and run them any other time, they are blazing fast.  Here's a graph for MySQL throughput for the same time frame:

I've checked the stats for WordPress hooks and plugins, and everything seems to be normal.
My question is, where should I start looking? Which MySQL settings could be causing this? Is it even likely a MySQL problem, or is it more likely to be an application problem?
Comment: Brute-force bots visit Wordpress sites regularly and hammer your login script for 20 minutes at a time.  It might be worth checking to see if that's happening to you.
Answer: Do you have everything in one machine? Are you sure your server(s) are not swapping?
During the problem can you check with top and friends if your workload is CPU / Memory / IO bound?
Do you collect this data? If not start installing systat (sar and friends) so you can check what happened system wide after the problem happens.
Then enable the slow logging on both PHP and MySQL:
1) https://stackoverflow.com/questions/8560579/how-to-monitor-slow-php-processes
2) https://stackoverflow.com/questions/11606972/how-can-i-enable-slow-query-log-on-my-server
Having this data you can pinpoint the eventual problem or have a better understanding of what is happening and target better your monitoring or adapt your setup ecc.
Answer: Before getting into something application specific, I would start with the basics. It doesn't take long or much effort.
Start with some of the basic/generic server diagnostics stuff. top/iostat/atop/htop/iotop/free/df/vmstat, etc... during this time. Report back with what you find. My personal preference is atop for many things (it also runs in the background and records a log kind of like sysstat). Look at memory, swap, disk IO, load, etc... everything.
Then look at logs like the kernel log (or dmesg output) and syslog messages.
Then look at mysql and your web services when all else fails to reveal anything.
Answer: In addition to the other tools mentioned, I'd suggest using 'mytop' to see what mysql is doing when it slows down.  It is very top-like and shows stats like queries/sec as well as actively running queries.

Debugging MySQL performance issues


External HDD as backup

Question: (This question might define a new level of noob on serverfault!)

Is it okay to use an external 2TB HDD on a server to backup data (~250GB and growing)?
Backup frequency is intended to be daily (say midnight). Should the external HDD be allowed to remain connected to the (dedicated) CentOS server (rented, I'll have remote access) at all times?
Is it not a normal practice to ask server hosting company to connect and disconnect an external HDD when required by client (me, once a day)?

Note - Buying another server for storing backups or sending all data daily to another computer seem to be costly solutions to me (sending data will require me to use up my monthly bandwidth quota for creating backups which I don't want!)
Thanks!
Answer: I have used this method for backing up servers for several years and have not had too many problems with it.  My method is to use two external drives and alternate between them in case one fails.  I leave them connected at all times.  The only issue I've had is that occasionally one drive will fail after years of use, but this is to be expected.  Once a drive fills up, I format it and start over.  This usually leaves me with two months' worth of backups at a time, which is sufficient for our needs.
A hosting company will often charge for regular hands-on work.  It may or may not be normal practice; it isn't for us.  Personally I don't find it necessary to connect and disconnect the drives.
Answer: Is it okay to use an external 2TB HDD on a server to backup data (~250GB and growing)? - Yes.
Backup frequency is intended to be daily (say midnight). Should the external HDD be allowed to remain connected to the (dedicated) CentOS server (rented, I'll have remote access) at all times? - Yes.
Is it not a normal practice to ask server hosting company to connect and disconnect an external HDD when required by client (me, once a day)? - It's perfectly acceptable to ask them to do that for you. If you make that request on a daily basis though they may want to charge you a fee for doing it. An occasional request is usually withing the bounds of their "goodwill", but asking them to do this every day goes beyond that.

External HDD as backup


Using jquery to slide in content horizontally

Question: I have a few links on a page which refers to some content divs on the same page. I'm trying to create a very simple horizontal sliding effect to sliding effect to show the content. For example, initially only box1 content should be visible, and when clicked on link2, the box2 content shold slide in.
Link 1
Link 2
Link 3

..

..

..

Please have a look at the jsfiddle here: http://jsfiddle.net/G9eVf/
Comment: Your question is not requiring an answer, but someone to do the work for you.
Answer: Maybe something like this?
http://jsfiddle.net/3Vrh9/4/
Making use of this plugin
http://demos.flesler.com/jquery/scrollTo/
Plugin source:
http://demos.flesler.com/jquery/scrollTo/js/jquery.scrollTo-min.js


temporarily set eth0 to dhcp linux

Question: My ip address on a beaglebone is set to:
$ ip address show dev eth0
4: eth0: <BROADCAST,MULTICAST,DYNAMIC,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 64:33:db:27:e9:d2 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.132/24 brd 192.168.1.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::6633:dbff:fe27:e9d2/64 scope link
       valid_lft forever preferred_lft forever

I can temporarily add a second address for 100 seconds with the command:
sudo ip addr add 192.168.4.244/23 dev eth0 valid_lft 100 preferred_lft 100

I would like to do the same thing only instead of the second address being static, I would like it assigned by the router (dhcp?/dynamic?) but for the life of me I can't figure out the syntax.  any ideas?
I was told that:
ifconfig eth0 0.0.0.0 0.0.0.0 && dhclient

would work but is that ok to do considering my static IP address was set with connman?  Also if ifconfig is ok to use how do add the timeout???
TIA
Answer:    dhclient eth0:dynamic

here dynamic is just a name for an aliased net
interface (you can use any other name here if you want)
dhclient will create an aliased interface on hardware eth0 (assuming eth0:dynamic is not already defined) and then call out on it to get an address using DHCP leaving your existing eth0 configuration untouched.
Comment: Thanks Jasen!   I'll have to play with this but in the meantime, I got it to work by:
1) getting rid of of /var/lib/connman/default.config
2) Plugging in the cable to the router
3) I noticed that in the directory I got:
$ ll /var/lib/connman
-rw-r--r--  1 root root   55 Dec  7 14:45 default_bu_221207.config
drwxrwxrwx  2 root root 4096 Apr 13  2022 ethernet_402e71cd1835_cable/
drwxrwxrwx  2 root root 4096 Dec  7 14:56 ethernet_6433db27e9d2_cable/
-rw-rw-rw-  1 root root   55 Oct 18 06:40 hide_default.config
-rw-r--r--  1 root root  216 Apr  6  2020 settings
Comment: and then issued:

> connmanctl config ethernet_985dad375f63_cable --ipv4 dhcp <

where I used my ethernet_blablabla_cable from the list of directories in /var/lib/connman

temporarily set eth0 to dhcp linux


Induction based on the 2-cocycle identity for $c': \Bbb Z/p \times \Bbb Z/p \to \Bbb Z/p$ and $c'(0, 0) = 0$

Question: Context:
I was trying to find the number of elements in $H^2(C_p; \Bbb Z/p)$ and my professor gave this hint (cf. Understanding the relation between central extensions and 2-cocycles and coboundaries):

Probably the main trick for a calculation like this is to use coboundaries to clean up a cocycle.   Let $b$ be a generator of $C_p$, and let $c$ be any 2-cocycle.   Then $c$ is equivalent to another cocycle $c'$ such that $c'(b^x,b^y) = 0$ for all non-negative $x$ and $y$ with $x+y < p$.   You can prove this by induction on the value of $x+y$.  You cannot make it happen for $x+y = p$.  However, after killing $c'(b^x,b^y)$ for $x+y < p$, the cocycle condition then implies that $c'(b^x,b^y)$ is equal for all values of $x+y \geq p$, provided that $0 \leq x,y < p$.   That is then the extra dimension in $Z^2(C_p;\Bbb Z/p)$ that is not present in $B^2(C_p;\Bbb Z/p)$.

Question:
Consider the 2-cocycle identity: $c'(y,z)+c'(x,y+z) = c'(x+y,z)+c'(x,y)$ where $c': \Bbb Z/p \times \Bbb Z/p \to \Bbb Z/p$ and $c'(0, 0) = 0$. $p$ is a prime.
I was given an exercise to show that $c'(x, y) = 0$ for all $x+y < p$ and $c'(x, y)$ is equal for all values $x+y \geq p$ provided that $0 \leq x, y < p$. $x$ and $y$ are non-negative integers.
Is there any simple way to show this?
My attempt:
I could prove so far that $c'(1, 0) = 0$ and $c'(0, 1) = 0$ as follows:
If $x= 1, y = 0$ and $x + y = 1$ (let $z=0$):
$$c'(x+y,z) = c'(y,z)+c'(x,y+z) - c'(x,y)
\\
\implies c'(1,0) = c'(0,0)+c'(x,0) - c'(x,0) = c'(0,0) = 0 $$
If $x = 0, y=1$ and $x + y = 1$ (let $z=p-1$):
$$c'(x,y) = c'(x,y+z) + c'(y,z) - c'(x+y,z)\\ c'(0,1) = c'(0,1+p-1) + c'(1,p-1) - c'(1,p-1) = c'(0, 0) = 0$$
How should I proceed after this?
Comment: Are you sure this is the correct statement? Because it seems to me it's not true.
Comment: @CaptainLama Please see the added context in the new edit...
Comment: Ok, this is completely different. It is indeed true that any cocycle is *cohomologous* to such a cocycle. But certainly not equal.
Answer: In what follows I will often not make a distinction between an integer $x$ and its class in $\mathbb{Z}/p\mathbb{Z}$. I will also write the law in $C_p$ additively, so if $x\in \mathbb{Z}$, I will allow myself to write $x\in C_p$, instead of $b^x$ where $b$ is a generator.
For any $x,y\in \mathbb{Z}$ with $0\leqslant x,y<p$, let us write $\chi(x,y)=0$ if $x+y<p$, and $\chi(x,y)=1$ if $x+y\geqslant p$. This defines a function $\chi: C_p^2\to \mathbb{Z}/p\mathbb{Z}$, and you can easily check that it is a $2$-cocycle. You can either verify directly the cocycle condition, or you can notice that it is the cocycle corresponding to the (non-split) extension $0\to \mathbb{Z}/p\mathbb{Z}\to \mathbb{Z}/p^2\mathbb{Z}\to \mathbb{Z}/p\mathbb{Z}\to 0$, with the obvious section $\mathbb{Z}/p\mathbb{Z}\to \mathbb{Z}/p^2\mathbb{Z}$ given by $x \text{ mod } p\mapsto x \text{ mod }p^2$ for $0\leqslant x<p$.
Another bit of notation: let us write $X$ for the set of functions $C_p\to \mathbb{Z}/p\mathbb{Z}$, and $d:X\to Z^2(C_p,\mathbb{Z}/p\mathbb{Z})$ for the coboundary map, that is
$$d(f): (x,y) \mapsto f(x) + f(y) - f(x,y).$$
By definition, $B^2(C_p,\mathbb{Z}/p\mathbb{Z})$ is the image of $d$.
Now we can identify the issue with what you are trying to do. What your teacher is telling you is that any $c\in Z^2(C_p,\mathbb{Z}/p\mathbb{Z})$ can be written as
$$c= d(f) + t\cdot \chi$$
for a certain $f\in X$ and a certain $t\in \mathbb{Z}/p\mathbb{Z}$. But what you are trying to prove is that $c=t\cdot \chi$, which in general is just not true, even if you assume $c(0,0)=0$. What you seem to have understood from your teacher's advice is that $c$ is equivalent to some $c'$ with $c'(0,0)=0$, and that this $c'$ automatically satisfies extra properties (which actually amount to $c'=t\cdot \chi$). But in reality, that is incorrect: even though there are many $c'$ equivalent to $c$ such that $c'(0,0)=0$, only one of them is a multiple of $\chi$.
So now what you need to do is, given $c\in Z^2(C_p,\mathbb{Z}/p\mathbb{Z})$, to find $f\in X$ such that $c-d(f)$ is a multiple of $\chi$. (Note that this $f$ is not unique, unless you add an extra condition, like $f(1)=0$ for instance, but this is not very useful.) As your teacher points out, it's actually sufficient to show that $c-d(f)$ is $0$ on all $(x,y)$ with $x+y<p$ (which must clearly be true if it is a multiple of $\chi$). You should try to prove this on your own.
After that it just remains to find $f$ such that $c(x,y)=f(x)+f(y)-f(x+y)$ for all $x,y\in \{0,\dots,p-1\}$ such that $x+y<p$. As your teacher suggests, a natural method is to do that by induction on $x+y$, starting with $f(0)=c(0,0)$, and using the cocycle condition for the induction step.

For a more theoretical flavor, note that what we are doing is essentially studying the exact sequence
$$0\to B^2(C_p,\mathbb{Z}/p\mathbb{Z})\xrightarrow{d} Z^2(C_p,\mathbb{Z}/p\mathbb{Z})\to H^2(C_p,\mathbb{Z}/p\mathbb{Z})\to 0.$$
Indeed, we just showed that $Z^2(C_p,\mathbb{Z}/p\mathbb{Z})/B^2(C_p,\mathbb{Z}/p\mathbb{Z})$ is generated by a single element $\chi$, so $H^2(C_p,\mathbb{Z}/p\mathbb{Z})$ is cyclic. There is a natural identification $H^2(C_p,\mathbb{Z}/p\mathbb{Z})\simeq \mathbb{Z}/p\mathbb{Z}$, and the element $\theta(c)\in \mathbb{Z}/p\mathbb{Z}$ corresponding to the cohomology class $[c]\in H^2(C_p,\mathbb{Z}/p\mathbb{Z})$ is the only one satisfying $c=d(f)+\theta(c)\chi$ for some $f$.
You can check that $\theta(c)=\sum_{g\in C_p}c(g,1)$.
Comment: Thanks for all the help. I more or less understand whole of the answer now. Could you just give me some hints for how to show the sufficiency of proving $c-d(f)$ is zero for $x+y < p$?
Comment: Please see: https://math.stackexchange.com/questions/3641802/sufficiency-of-c-df-0-forall-x-y-n-2-cocycles-and-2-coboundaries


How to create a GET-form

Question: For example a filter form on admin areas can best be GET forms, that way they are bookmarkable and can filters be maintained across pager-pages.
How can one best use form_api for such forms? Will the _validate hooks be submitted? Can the _submit hook be omitted?
For example views-exposed filters work this way; But the code in views handling this is convoluted and complex, too complex to be used as good example for when developing custom interfaces with simple filter forms.
Comment: I don't understand the question. You can create or hook_alter any form to grab GET-data, if that's what you mean.
Comment: I've updated the question with a reference to an examlple.
Answer: Use the #method parameter of the form like this:
<?php
  $form['#method'] = 'get';
?>

Comment: A form's method must be set to post for it's submit and validate functions to be called implicitly.
Comment: Sure. That is one part. But how about validation, submit hooks, and so on. Are the set?
Comment: Related: `form_data` keys `always_process` and `method` can also be set in the form definition which results in validate+process hooks being run. But I can't find an example of use for this and I still end up with `form_state` containing a `method` key set to `post`!
Answer: Just in case anyone stumbles upon this question, this is a more complete real-life, yet very simple example :)
you will want to define the form
function YOURMODULE_search_form($form, &$form_state) {
  $form['#method'] = 'get';
  $form['#action'] = '/search';
  $form['#attributes'] = array('class' => array('mymod-search'));
  $form['search'] = array(
    '#type' => 'textfield',
    '#size' => 20,
  );
  return $form;
}

and then you can use it
$searchform = drupal_get_form('YOURMODULE_search_form');
$output .= drupal_render($searchform);

The last line could be i.e. a block['content'] or whatever you need.
Comment: For search forms, you may want to also put `$form_state['redirect'] = false;` in the submit handler to disable redirecting after the form is submitted.

How to create a GET-form


Determining the Order of a Finitely Generated Abelian Group from the Order of its Generators

Question: Question:
If G is an abelian group with generators x and y of order 16 and 24 respectively, and $x^{2} = y^{3}$, what is the order of G?
My attempt at a solution:
Since the set of generators of the group is finite, and the order of each generator is given, we can combine the elements of the subgroups generated by x and y individually to get the total number of possible elements.
So, 16(24).
But then we must exclude repeats. I'm not sure where to go from here, working under the constraint that $x^{2} = y^{3}$. Any guidance as to how to take this constraint into consideration would be appreciated. Also, since the group is abelian would the total number of elements before this exclusion be 8(24)?
Answer: If $G$ is abelian and generated by $x$ and $y$, then any element can be written in the form $x^iy^j$ by commuting $x$ and $y$ as necessary. Since $x$ has order $16$ and $y$ has order $24$, we can also impose that $0\leq i \leq 15$ and $0 \leq j \leq 23$ which gives a total number of $16 \times 24$ elements.
If there were no other relations here, we would be done. However, we also know that $y^3=x^2$ which means that whenever we see a power of $y$ greater than $2$, we can turn some of those $y$'s into $x$'s and then reduce the power of $x$ to below $16$ again.
Hence any element can be written as $x^iy^j$ with $0\leq i \leq 15$ and $0\leq j \leq 2$ giving a total of $48$ elements and your group is (isomorphic to) $C_{16} \times C_3$, where $x=(1,0)$ and $y=(2,1)$.
Comment: What do you mean by "turn some of those y's into x's"? I can see how y's of certain powers (3, 6, 9, 12, 15, 18, 21, 24) can be turned into x's, but I do not see how y's of powers 4, 5, 7, 8, etc. can be turned into x's.
Comment: for example $y^4 = y^3 y = x^2 y$
Comment: @Daniel as M.U.'s example shows, I mean we note that $y^j=y^{3k+l}$ for some integers $k,l$ with $0\leq l \leq 2$ so $y^j=y^{3k}y^l=x^{2k}y^l$. I am not claiming that you can get rid of *all* $y$'s, just that you bring the power below $3$ and then you may need to reduce the power of $x$ again.


Which variables could I impute using the multiple imputation?

Question: Suppose I have a dataset, and I want to use it to analyse the association between BMI and stroke. The dataset has some missingness for BMI(independent variable) and some missingness for covariates such as blood pressure. There are many complete covariates and suppose the dataset could be imputed.
My question is whether I could impute the BMI (independent variable) and missed covariates using other complete covariates? A coauthor said that what I could impute is only covariates, not independent variable. Is it right?
If the outcome (dependent variable) is also missed, could I impute that? (impute independent and dependent variables and covariates using other complete variables?)
Answer: There are many opinions on the matter. Naysayers seem to get nervous, especially, about imputing outcomes. But the validity of imputation is a theoretical result, and the theory supports imputing anything you want: independent variable, outcome, and covariates. The known contraindication for imputation is missing not at random (MNAR) data, that is missingness depends on the missing value itself. I find it especially odd that, when the discussion of imputation is presented, there is an assumption that imputation of the outcome should be particularly scrutinized for this bias. Wrongly imputing any covariate can lead to arbitrarily bad/wrong inference! Unfortunately, there's no real way to verify the assumption, and the requirement of no MNAR is common to all missing data methods: even complete case analysis. As my professor told me: the best solution for missing data is not to have it. When I refer to "imputation" I specifically mean multiple imputation.
Comment: What would he do if the exposure is missing? Excluding records from analysis makes even stronger assumptions than any imputation. E.g. MI is valid under some assumptions (e.g. MAR + certain distributional assumptions, also some MNAR scenarios), & is somewhat wrong if assumptions aren't met. Excluding records ("complete case analysis") makes an incredibly strong missing completely at random assumption that is usually guaranteed to be wrong & is known to often lead to huge bias (you can of course **hope** that for you it's not so bad/that so little data are missing that it has little effect).
Comment: I like the opinion that your professor told you. Unfortunately, it is difficult to avoid missing data in practice. I have to deal with these missing data as correctly as possible. My professor is not familar with multiple imputation and told me I could not impute the exposure variable (only impute the covariates).
Comment: @lijiaqi tagging for transparency. Bjorn's point is well made and consistent with this answer: *not* imputing is also a decision that requires assumptions tantamount to those for imputation.
Comment: @Björn (My english is not good so I want to confirm your opinion. You think complete case analysis leads to huge bias, and imputation is necessary, right?) Most of our previous studies were based on complete case analysis and used dummy varibales for missed covariates. I read many journal`s statistical recommendations and started to use multiple imputation. I agree with your opinion and am reading more related paper.
Comment: Thank you AdamO. And could you tell me how to tag for transparency? I do not understand that.


Post-build event xcopy - how to copy linked files?

Question: In project i have as normal files as links (shortcuts) to existing file:

In post-build event i want to copy all files, including links (but as real file) to other directory, for example:
<code>"%RELEASEPATH%\Code\"
</code>
Using default xcopy command it do copy all files + directory, but not links:
<code>xcopy /E /Y /R "$(ProjectDir)Code" "%RELEASEPATH%\Code\"
</code>
If there a way to copy linked files (as real files) with xcopy as well?
Answer: I am not sure of xcopy, but if all you want is for copying the link file to the folder you put the link file in, then you can try:
(source from Copying linked content files at each build using MSBuild)

build by adding the following at the end of the .csproj file, just
  before the final  tag:

<code> <Target Name="CopyLinkedContentFiles" BeforeTargets="Build">
    <Copy SourceFiles="%(Content.Identity)"
          DestinationFiles="%(Content.Link)"
          SkipUnchangedFiles='true'
          OverwriteReadOnlyFiles='true'
          Condition="'%(Content.Link)' != ''" />
 </Target>
</code>
Comment: i added this, but its didn't take any effect (i didn't found files anywhere). Also i want to copy those files to **specific location**, in my case i specified it within post-build actions as: "%RELEASEPATH%\Code\"


What inequalities should one know to evaluate limits fluently?

Question: During the Calculus course, we often used common inequalities to estimate the terms of a sequence and find its limit in the end. The problem is that these inequalities, obvious though they may be, seldom come to mind if you have not used them to solve similar problems at least once. I have listed some of them but I think there are more - what should I add to the list?

Bernoulli's inequality
$n! > 2^n  \iff n \ge 4$
$2^n > n^2\iff n \ge5$
Comment: i wonder why Cauchy-Schwarz didn't show up anywhere...
also Hölder is sometimes pretty useful.
Comment: Muirhead as well.
Comment: FYI it's not just in calculus. It also comes up a lot when you want to analyze an error or other kind of deviation probabilistically (e.g. $\epsilon$ deviation with $\delta$ probability).
Answer: $-1\leq \sin(x)\leq 1$, and the same is true for $\cos$
The AM-GM inequality is so popular it has its own tag on this site.
This inequality involving the choose function is pretty commonly used when the choose function or exponential function pop up
$$\frac{n^k}{k^k}\leq {n\choose k}\leq\frac{n^k}{k!}\leq \frac{(n\cdot e)^k}{k^k}$$
Comment: $|\sin(x)| \leq |x|$ is also handy.
Answer: A good thing to have in mind is the hierarchy of common functions. In synthetic form
For all $a∈ℝ$, $b⩾1$, $c>1$, $d>1$ and $x>1$
$$
a ≺ \log(\log(n)) ≺ \log(n)^b ≺ n^{\frac{1}{c}} ≺ n ≺ n \log(n) ≺ n^d ≺ x^n ≺ n!≺  n^n
$$
when $n⟶+∞$, using Hardy's notations for asymptotic domination¹.
Note that this does not give you the specific $N$ where one gets superior to the other, though.
You might also derive useful comparisons from the Théorème de croissances comparées for which I don't know of any equivalent in English literature, but which is simply the following
For all $a>0$ and $b>0$
$$
x^a = o_{+∞}(e^{bx})
$$
$$
\ln(x)^a = o_{+∞}(x^b)
$$
and
$$
\lvert\ln(x)\rvert^a = o_{0}(x^b)
$$

 1. Which is messed up, because those are obsolete, but there are not other convenient notations for asymptotic domination as a (strict partial) order. What I was taught was that the Vinogradov notation $f ≪ g$ stood for $f=o(g)$, but apparently it is $f=O(g)$ instead. We really need a standardization of those things.
Answer: Two useful things to know in calculating limits are:

For all $a>1,\alpha > 0$, there exists some $N$ such that $\log_a n < n^\alpha$ for $n>N$
For all $a>1, \alpha > 0$, there exists some $N$ such that $a^n > n^\alpha$ for all $n>N$

In other words, the exponential function is faster than any power, and log is slower than any power.
Comment: You're second bullet requires $a > 1$, correct? Otherwise you have a decaying exponential.
Answer: For any function such that
$$x\in(a,b)\implies f''(x)>0$$
then
$$c,x\in[a,b]\implies f(c)+f'(c)(x-c)\le f(x)$$
$$c,d\in[a,b],~x\in[c,d]\implies f(c)+\frac{f(c)-f(d)}{c-d}(x-c)\ge f(x)$$
Most clear if you graph it out. All inequalities flipped when $f''(x)<0$.

For example,
$$x\in(-\infty,\infty)\implies1+x\le e^x$$
$$x\in[0,\pi]\implies x\ge\sin(x)$$
A lot of common inequalities can be derived from this. (Though note you have to take the derivative, so don't use it to prove fundamental derivatives.)
Comment: In words: The graph of a convex function lies above its tangent lines.
Comment: @MartinR And below its secant lines.
Answer: In general one should already be aware of the more famous and elementary inequalities like AM-GM. You have also noted down the Bernoulli inequality which is much simpler, less famous and highly powerful and useful in unexpected ways. Apart from the famous ones (those with a name) I find the following very helpful:

$\sin x<x<\tan x$ for $x\in(0,\pi/2)$.
$\log x\leq x-1$ for $x>0$.
$e^{x} \geq 1+x$ for all real $x$.


$\forall t \in \mathbb{R}, e^{i \alpha_n t} \rightarrow 1 \implies \alpha_n \rightarrow 0$?

Question: $\alpha_n \in \mathbb{R}$ is a fixed sequence of real numbers, for which the following holds:
$$
\forall t \in \mathbb{R}, \lim_{n \rightarrow \infty}e^{i\alpha_nt} = 1
$$
Is it necessarily the case that $\lim_{n \rightarrow \infty} \alpha_n = 0$?
Comment: no reason to downvote here.
Comment: The question and the title do not match.  Which one do you want answered?
Comment: $\lim e^{i\alpha_n t} \rightarrow 1$ makes more sense.
Comment: Of course, convergence for one fixed $t$, the answer is no as we have seen.  But here we want convervence for all $t$.
Comment: @anorton: I revised the title. Hopefully it matches the question closer. However, to be absolutely clear: it is the question (rather than the title) that I'm interested in.
Comment: What if you just look at $t$ of the form $1/k$? You then get that $\alpha_n$ has to converge to $0$ modulo $2\pi k$ as $n\to \infty$ for each $k\geq 1$. It seems like the only way this is possible is if $\alpha_n\to 0$....
Comment: @i707107: Thanks. Fixed.
Comment: @i707107: a limit doesn't converge... it *equals* something. sequences converge.
Comment: Related : http://math.stackexchange.com/questions/683507/convergence-of-series-of-functions-f-nx-u-n-sinnx
Comment: @Max That's my mistake. OP has the correct edit though.
Comment: ye, sorry, mathematicians are pedants :-)
Answer: Assume (as we may) that $\alpha_n\neq 0$ for all $n$. By the dominated convergence theorem and the assumption on $\alpha_n$, we have
$$\lim_{n\to\infty} \int_0^1 e^{i\alpha_n t}dt=1\, .$$
On the other hand,
$$\int_0^1e^{i\alpha_n t}dt=\frac{1}{i\alpha_n} (e^{i\alpha_n}-1)\, .$$
Since $e^{i\alpha_n}-1\to 0$, it follows that $\alpha_n\to 0$.
Comment: Beautiful! Thank you.
Comment: Amazingly neat.
Comment: Thanks for the comments...
Comment: Just a little mistake on $1/(i\alpha_n)$... but, a Very nice answer!
Answer: The convergence of $e^{i\alpha_n t}$ to $1$ implies the convergence of each component (real and imaginary part):
$$\lim_{n \rightarrow \infty}sin(\alpha_nt)=0$$
$$\lim_{n \rightarrow \infty}cos(\alpha_nt)=1$$
If we take $\alpha$ as the limit of $\alpha_n$ distinct of $0$ and take $t=\frac{1}{\alpha}$ by continuity of the functions cos and sin the limit have to be $cos(1)$ and $sin(1)$ then we have a contradiction with the original statement. And then we have two options: or $\alpha_n$ converges to $0$ or not converges.
If $\alpha_n$ have a convergent subsequence for each one of they we could apply the same argument an we have that limit points are $0$ then the problem is reducted to demostrate a contradiction in having a not convergent subsequence.
If the subsequence $\alpha_{n_k} \rightarrow \infty$ like @GEdgar said is a contradiction with the convergence of sin or cos (because the limit at infinity of both functions is not defined at infinity). Finally by this question the subsequence not having cluster points and being bounded converges to infinity, again a contradiction.
Answer: Let $\alpha_n$ be a sequence such that
$$
\lim_{n \to \infty}e^{i \alpha_n t} = 1\qquad\text{for all } t \in \mathbb R .
\tag{1}
$$
Suppose $\alpha_n$ does not converge to zero.  Replacing some $\alpha_n$ by $-\alpha_n$ if necessary, and taking a subsequence if necessary: we may assume there is $K>0$ so that $\alpha_n \ge K$ for all $n$.  Next, we may assume $\alpha \to \infty$: if not, there is a bounded subsequence, say $\alpha_n \le L$, and then $t = \pi/L$ contradicts the convergence (1) along that subsequence.
Now, for each $N \in \mathbb N$, define
$$
E_N = \bigcap_{n=N}^\infty \left\{t \in \mathbb R \colon \left|
e^{i\alpha_n t}-1\right| \le \frac{1}{10}\right\} .
$$
The sets $E_N$ are closed, but by (1) we have
$$
\bigcup_{N \in \mathbb N} E_N = \mathbb R .
$$
By the Baire Category Theorem, some set $E_N$ is somewhere dense: there is an interval $(a,b) \subseteq E_N$, say.  But since $\alpha_n \nearrow \infty$, there is $n \ge N$ so that $\alpha_n(b-a) > 2\pi$.  This means
$$
\{e^{i \alpha_n t}\colon t \in (a,b)\}
$$
covers the entire circle, so
$$
\left|e^{i\alpha_n t}-1\right| < \frac{1}{10}
$$
fails for some $t \in E_N$.  Contradiction.
Comment: "we may assume there is $K>0$ so that $\alpha_n \ge K$ for all $n$." Don't you mean: "for infinitely many $n$"?
Comment: Nice. This also solves my question. Thanks.
Comment: @Evan: yes, edited.
Answer: $\exp$ is $2\pi i$ periodically, so the answer is No. (if you mean $t\rightarrow\infty$)
edit: see comments
Comment: I was interpreting the question to mean $t\in \mathbb{R}$ is fixed, and $n\to \infty$. There is actually some work to do here, I think....
Comment: ah okay... then still $t\alpha_{n}$ can have multiple cluster points around multiples of $2\pi$
Comment: yes, but then if you choose $t = 1/2$, then you wouldn't get the convergence to $1$ (unless I misunderstand something)
Comment: But what about convergence of $e^{i \alpha_n t}$ for all $t$?
Comment: if that convergence holds for all $t$ with the same series $\alpha_{n}$ then it should be possible to show that $\alpha_{n}\rightarrow 0$
Comment: the question has been edited
Comment: maybe you could use continuity of $p\mapsto p^{\frac{1}{t}}$ for $t>0$ (this is just a guess)
Comment: "should be" ... but "needs proof".
Comment: yes but that would be work... you might want to consider several cases:  convergent subsequence and sequence has no clusterpoints, i think i would start from there.


Server accept socket but after that the socket cannot receive anything

Question: I've encountered a very strange problem (since this always worked before) when building a client-server chat program.
The serversocket accepts without any problem the incoming connection of the client, but when I try to read from the socket's inputstream the whole method blocks and only releases when I close the client's socket.
I've even tried it with the sample code on docs.oracle.com, but the problem remains.
Can anybody point me out the error I'm obviously not seeing?
Server code:
public class Server {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    System.out.println("Creating server socket");

    ServerSocket internetSocket = new ServerSocket(60000);
    if(!internetSocket.isClosed()) {

        while(true) {
            Socket s = internetSocket.accept();
            System.out.println("accepted socket!");

            BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));

            String line = null;
            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}
}

Client code:
public class Client {

public static void main(String[] args) throws IOException {
    Socket s = null;
    try {
        s = new Socket("localhost", 60000);
    } catch (UnknownHostException ex) {
        Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
    }

    PrintWriter outStream = new PrintWriter(s.getOutputStream());
    for(int i=0; i<10; i++) {
        outStream.println("test");
        System.out.println("Sending the message \"test\"");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    s.close();
}
}

Answer: You forgot to add a true as the 2nd parameter when creating the printwriter printwriter
new PrintWriter(s.getOutputStream(), true);

It will make it flush automatically.
Comment: Sorry, but I can't accept both answers ;-) I just saw the extra constructor argument in PrintWriter too. I guess I was too fast in writing my code. Anywayz also thank you for point it out!
Answer: the method readLine() is waiting for \n character to appear in the stream (the method blocks until it sees end line delimeter).
Try sending "test\\n" from the client and see what happens.
And remember to flush() the output stream on the client side
Comment: Thanks for the fast response, but nothing different is happening.
Comment: and make sure you flush() the things to the outputStream
Comment: AHA! Somehow adding the flush() did the trick! Any idea why it doesn't flush automatically?  I guess the printwriter initialization?
Comment: hmm.. I'm not sure why should it flush() automatically :)


clicar na div aumentar clicar novamente diminuir

Question: Pessoal se puderem me ajude nessa questão gostaria de clicar em uma div que esta fixa no rodape e ela aumentar e depois clicar novamente e ela diminuir, como faço isso?
Answer: Você deveria incluir um pouco do código do que você tentou fazer, mas aqui está um exemplo bem simples pra te dar pelo menos uma ideia de como começar:
HTML:

CSS:
#div {
    height: 100px;
    width: 100px;
    background-color: red;
}

Javascript:
var big = true;

$('#div').click(function() {
  if(big) {
    big = false;
    $(this).css('height', '50px');
    $(this).css('width', '50px');
  } else {
    big = true;
    $(this).css('height', '100px');
    $(this).css('width', '100px');
  }

});

Javascript utilizando Animação:
var big = true;

$('#div').click(function() {
  if(big) {
    big = false;
    $(this).animate({
      height : "50px",
      width : "50px"
    }, 1000);
  } else {
    big = true;
    $(this).animate({
      height : "100px",
      width : "100px"
    }, 1000);
  }

});

Pra ver ao vivo: https://codepen.io/leofontes/pen/bBrVbZ
Como eu disse, bem simples, pra te ajudar como iniciante.
Comment: é isso mesmo cara muito obrigado
Comment: man como faço isso em uma div fixa na parte inferior da tela?


Imprimir dois arrays lado a lado

Question: Como juntar dois arrays sendo que o índice do array 1 siga o índice do array 2.
Dados para junção:
descricao

array1= datacol1, datacol2, datacol3, datacol4

array2= collinha1, collinha2, collinha3 ,collinha4

Imprimir assim:

descricao, datacol1, collinha1
descricao, datacol2, collinha2
descricao, datacol3, collinha3
descricao, datacol4, collinha4

<?php
$desc1 = 'Listar=';
$nome['24-01-2016'] = 'João';
$nome['25-01-2016'] = 'Telma';
$nome['26-01-2016'] = 'Joana';
$nome['27-01-2016'] = 'Thiago';
$nome['28-01-2016'] = 'Marcio';
$nome['29-01-2016'] = 'Juliana';
$nome['30-01-2016'] = 'Marcos';
$nome['31-01-2016'] = 'Mariana';

foreach($nome as $indice => $valor){

print $desc1;
print '=>>>';
print $indice;
print '-';
print $valor;
print'
';

}
?>
Comment: De onde vem a descrição? E você quer mesmo juntar os dois (três?) ou só imprimir junto? São coisas diferentes. Para juntar dois _arrays_ "lado a lado" pode se usar `array_combine ( array $keys , array $values )`, mas sua pergunta precisa definir melhor o que quer. Tem inúmeras maneiras de se mexer com _arrays_ em PHP. Recomendo [edit] a pergunta e esclarecer melhor, antes que o pessoal comece a responder no "chute".
Comment: eu editei a postagem coloquei o codigo que consegui fazer eu tirei o indice e coloquei as datas veja so.
Comment: ja tentou fazer um array merge e depois um sorting ?
Comment: consegui aqui eu mudei fiz o esquema do ivcs me passou jeito mais certo.  mas desse modo também fica bom.
Comment: Peço que dêem uma olhada na minha resposta, apenas para saber tratar casos de iterar dois arrays, porém os mesmos com tamanhos diferentes.
Answer: A maneira mais simples de se fazer isso seria com um for (isso não juntaria os arrays, mas como percebi você quer apenas printar eles juntos), ficaria assim:
<?php

// your code goes here
$arr1 = array ('datacol1', 'datacol2', 'datacol3', 'datacol4');

$arr2= array ('collinha1', 'collinha2', 'collinha3', 'collinha4');

for($i = 0; $i < count($arr1); $i ++)
{
    echo 'descricao, '.$arr1[$i].', '.$arr2[$i].'
\n';
}

No Ideone
Comment: isso mesmo que quero obrigado ajudou muito.
Answer: Eu faria com um array_map para gerar um array "lado a lado" e, depois, iteraria ele com foreach.
$array1 = [1, 2, 3];

$array2 = [1, 2, 3, 4];

foreach (array_map(null, $array1, $array2) as $key => $value) {

    echo $value[0], ' e ', $value[1];

}

Utilizar array_map com mais de um array e com o null no primeiro parâmetro, ao invés de um callback, faz com que você gere um array (baseando-me no exemplo dado nessa resposta) assim:
[
   [1,1], [2, 2], [3,3], [null, 4]
]

Opcionalmente, se você estiver usando uma versão igual ou superior ao PHP 5.5, você pode usar foreach juntamente com o list.
foreach(array_map(null, $array1, $array2) as $key => list($a, $b)) {

    echo $a, ' e ', $b;
}

Comment: Na verdade, a resposta foi apenas um complemento. Ela foi apenas para você entender, de maneira fácil, como unir dois `arrays`, mesmo que eles não contenha a mesma quantidade de valores :D
Comment: muito obrigado, eu preferir com for, o esquema que o Ivcs passou acima.
Comment: haha valew melhorou muito meu conhecimento.

Imprimir dois arrays lado a lado


Make flex items automatically re-size to fill space when sibling is removed

Question: I've got four flex boxes which I'd like to close and have the others automatically resize to fit the newly empty space.
I think there's something simple wrong with my CSS, as currently the close button closes every box.
Can you spot where I've gone wrong?

#separator {
  width: 20%;
}
#firstbox {
  width: 20%;
  padding-right: 10px;
  border: 2px solid black;
  padding-left: 10px;
  margin-right: 4px;
  flex-grow: 1;
  flex-shrink: 1;
}
#secondbox {
  width: 20%;
  padding-right: 10px;
  border: 2px solid black;
  padding-left: 10px;
  margin-right: 4px;
  flex-grow: 1;
  flex-shrink: 1;
}
#thirdbox {
  width: 20%;
  padding-right: 10px;
  border: 2px solid black;
  padding-left: 10px;
  margin-right: 4px;
  flex-grow: 1;
  flex-shrink: 1;
}
#fourthbox img {
  width: 30%;
  height: 30%;
  flex-grow: 1;
  flex-shrink: 1;
}

    CLOSE
    <?php include 'test2.php';?>

    CLOSE
    <?php include 'test2.php';?>

    CLOSE
    <?php include 'test2.php';?>

Answer: By giving flex items flex-grow: 1, they each will expand to consume available space. Hence, if an item is removed, its siblings will automatically expand into that new space.
Try this simple approach:

flex-container {
  display: inline-flex;
  flex-direction: column;
  height: 150px;
}

/* key rule */
flex-container > * { flex: 1; }
/* shorthand for flex-grow: 1, flex-shrink: 1, flex-basis: 0 */

/* non-essential decorative styles */
#firstbox  { background-color: aqua; }
#secondbox { background-color: pink; }
#thirdbox  { background-color: lightgreen; }
flex-container > * { width: 100px;  border: 1px dashed black; text-align: center; }
<flex-container>

    Close Box #1
    <?php include 'test2.php';?>

    Close Box #2
    <?php include 'test2.php';?>

    Close Box #3
    <?php include 'test2.php';?>

</flex-container>


Index isn't unique for key

Question: I tried using the index as the key for mapped <option> elements in my render() function but it still isn't working. It's so odd, I console.log(activity_type_options) before I map through just to check if maybe I am reinitializing activity_type_options to something else. But the array does not change. The component itself renders three times I can see. But this shouldn't even cause this, right?

Warning: Each child in an array or iterator should have a unique "key" prop.

Inside render return
 activity_type_options.map(activity => {
      return (
        <option key={activity} value={activity}>
          {activity}
        </option>
      )
    })

activity_type_options

["BLDNG", "EQUIP", "CNSER", "TRNSP", "SFDEV", "STREG", "EXPNS", "RLEST"]

class ActivityModal extends React.Component {
  componentDidMount() {
    const {handleClick} = this.props
    const promise = new Promise(res => {
      res(handleClick({target: {name: this.activity_type.name, value: this.activity_type.value}}))
    })
    promise.then(() => {
      handleClick({target: {name: this.activity.name, value: this.activity.value}})
    })
  }
  render() {
    const {
      showModal,
      toggle,
      activity_type_options,
      activity_options,
      selectedType,
      selectedActivity,
      handleClick,
      saveActivity
    } = this.props
    return (

        <Modal
          style={{position: 'absolute', top: '100px', left: '50px'}}
          isOpen={showModal}
          toggle={() => toggle()}
          className={this.props.className}
        >
          <ModalHeader toggle={() => toggle()}>New Activity Line</ModalHeader>
          <ModalBody>

              Activity Type
              <select
                ref={element => (this.activity_type = element)}
                style={{fontWeight: '900', fontSize: '12px'}}
                id='activity_type'
                onChange={e => handleClick(e)}
                className='no-radius'
                name='selectedType'
              >
                {activity_type_options.map((activity, index) => {
                  return (
                    <option key={index} value={activity}>
                      {activity}
                    </option>
                  )
                })}
              </select>
              Activity
              <select
                ref={element => (this.activity = element)}
                style={{fontWeight: '900', fontSize: '12px'}}
                id='activity'
                onChange={e => handleClick(e)}
                className='no-radius'
                name='selectedActivity'
              >
                {activity_options
                  .filter(option => selectedType === option.activityRefName)
                  .map(activity => {
                    return <option value={activity.activityTypeName}>{activity.activityTypeName}</option>
                  })}
              </select>
              Activity Desc
              <input value={selectedActivity} disabled />
              Activity Name
              <input disabled value={selectedActivity} />

          </ModalBody>
          <ModalFooter>
            <Button color='secondary' onClick={() => toggle()}>
              Cancel
            </Button>{' '}
            <Button color='primary' onClick={saveActivity}>
              OK
            </Button>
          </ModalFooter>
        </Modal>

    )
  }
}

export default ActivityModal

Comment: Provide complete code. Maybe the error happens in other part of your app.
Comment: Your code has 2 instances of `map` for activity, and your second one doesn't have `key` property set.
Comment: I just saw that when I added the code. *Smashes head into keyboard*
Answer: Your component have 2 maps, and the second one is not using key props. Then, you should change it:
{activity_options.filter(option => selectedType === option.activityRefName)
              .map(activity => {
                return <option key={activity.activityTypeName} value={activity.activityTypeName}>{activity.activityTypeName}</option>
              })}

Comment: I was typing out the solution, but lemme give you the credit =]. Gimme 6 min
Comment: @user10204157 I appreciate it
Answer: The issue appears to be in your second <select> where the <option> elements are not rendered with a key prop.
Try revising your code so that the index of the array item (as passed via the second map callback parameter) is used for the key of options in the second select, as you have with the first:
<select ref={element => (this.activity = element)}
        style={{fontWeight: '900', fontSize: '12px'}}
        id='activity'
        onChange={e => handleClick(e)}
        className='no-radius'
        name='selectedActivity'> {

    activity_options
    .filter(option => selectedType === option.activityRefName)
    .map((activity, index) => (

        <option key={index}
                value={activity.activityTypeName}> { activity.activityTypeName }
        </option>
    ))
}
</select>

Comment: thanks @kinduser and mthrsj - just tided up the formatting to the code sample a bit. Hopefully that makes the answer a bit clearer
Comment: Well, he clearly mentioned that he already tried that option :\
Comment: @kinduser, no, He did not. He'd  tried it just for one of the `map()` that the code have
Comment: @mthrsj Dacre already edited his post so you are unable to see how did it look like at the beginning ;\
Comment: @kinduser got it

Index isn't unique for key


Matlab - How to obtain values of pixels?

Question: If I have an image, how can I obtain the values of each pixel in that image using matlab
Thanks.
Answer: Images are matrices (2D if grayscale, 3D if colored) in MATLAB.
You can use x(i,j) to access a pixel at location (i,j) in a grayscale image.
If the image is colored, you can use x(i,j,:) to access the r, g, b values in a 3-vector, respectively. If you need individual channels, then, you can use x(i,j,1) for red for example.
You may read this page to learn more.
Comment: That is the slicing operator `:`. See http://www.mathworks.com/company/newsletters/articles/Matrix-Indexing-in-MATLAB/matrix.html
Comment: Thanks for your reply. How can I retrieve the image indices? As when I used the following command: `p1=I(0,0);`, I got:
`??? Attempted to access I(0,0); index must be a positive integer or
logical.`
Comment: The indices start from 1 and goes to the length of the dimension. It is not like in C.
Comment: Got what you mean. But, isn't there some more practical way to get `all` the pixel values without going index by index? Especially as you know some times you may have an image with a large number of pixels, and would be very time consuming accessing each pixel individually. What do you think? Thanks
Comment: Literally had a computer vision professor who never taught us a single bit of code  with Matlab.  Thank you for this post.
Answer: You can use reshape to extract all the pixel values of the image into a vector with pixel values:
frame = imread('picture.jpg');
frame_size = size(frame);
allpixels = reshape(frame, frame_size(1)*frame_size(2), frame_size(3))

This can be useful when you want to vectorize your Matlab code (to avoid a for loop that goes through every pixel). To get back the original image representation:
frame2 = reshape(allpixels, frame_size);

Comment: How to transform coordinates of the "query" to pixels? E.g., I want to know the values at pixels (1,1) and (20,20). How do I write it?
Answer: to get the values at pixel(1,1) we simply write image(1,1).


Erro ao criar procedure no oracle

Question: Ao declarar o nome de uma procedure no sqldevelope
recebo essa mensagem
Erro: ORA-00972: identifier is too long

Exemplo de nomenclatura:
PRC_IMVW_TISS_VERIFICA_ELEGIBILIDADE

CREATE OR REPLACE PROCEDURE PRC_IMVW_TISS_VERIFICA_ELEGIBILIDADE AS
BEGIN

    DBMS_OUTPUT.PUT_LINE('Hello World!');

END PRC_IMVW_TISS_VERIFICA_ELEGIBILIDADE;

Answer: Quando você encontrar um erro ORA-00972, a seguinte mensagem de erro aparecerá:

ORA-00972: identifier is too long.

Tradução:

ORA-00972: o identificador é muito longo

Procurando encontrei a referencia sobre esse erro:

Cause: The name of a schema object exceeds 30 characters.
       Schema objects are tables, clusters, views, indexes, synonyms, tablespaces, and usernames.

Tradução

Você tentou fazer referência a uma tabela, cluster, exibição, índice,
  sinônimo, tablespace ou nome de usuário com um valor superior a 30
  caracteres.

Solução:

Action: Shorten the name to 30 characters or less.

Tradução

Os nomes para tabelas, clusters, visualizações, índices, sinônimos,
  espaços de tabela e nomes de usuários devem ter 30 caracteres ou
  menos. Você deve encurtar o nome para não mais de 30 caracteres para
  esses objetos.

O nome da sua procedure possui 36 caracteres, remova 6 caracteres que o erro não irá mais ocorrer.
Fonte: http://www.dba-oracle.com/sf_ora_00972_identifier_is_too_long.htm

Erro ao criar procedure no oracle


Why is my form validation only working for some fields with ajax submit?

Question: I have a custom form that uses ajax submit successfully. However, form validation is not working as expected. Fields marked as required are being highlighted in red, but other fields that do not pass validation are not being marked.
function my_custom_form($form, &$form_state, $nid=NULL) {
  global $user;
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
  );
  $form['#attributes'] = array('enctype' => "multipart/form-data");
  $form['video_fid'] = array(
    '#title' => t('Video'),
    '#type' => 'managed_file',
    '#description' => t('Upload your video.'),
    '#default_value' => variable_get('video_fid', ''),
    '#upload_location' => 'public://video/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('mp4'),
      // Pass the maximum file size in bytes
      'file_validate_size' => array(MAX_CUSTOM_UPLOAD_FILE_SIZE),
    ),
    '#progress indicator' => 'bar',
    '#required' => true,
  );
  $form['title'] = array(
    '#title' => t('Title'),
    '#type' => 'textfield',
    '#description' => t('Video title, ex. "First Attempt" etc.'),
    '#default_value' => '',
    '#size' => 60,
    '#maxlength' => 64,
    '#required' => true,
  );
  $form['notes'] = array(
    '#title' => t('Notes'),
    '#type' => 'textarea',
    '#description' => t('notes about this video'),
  );
  $form['team_message'] = array(
    '#markup' => 'Your team: '.$user->name.' (you)
',
  );
  $form['teammates'] = array (
    '#type' => 'textfield',
    '#autocomplete_path' => 'my_custom/teammate/autocomplete',
    '#description' => t('Type each teammate\'s username, separated by commas'),
    '#element_validate' => array('_my_custom_form_team_validate'),
    '#ajax' => array(
      'callback' => 'my_custom_form_validate_teammates',
      'wrapper' => 'teammates-error',
      'method' => 'html',
      'effect' => 'none',
      'progress' => array (
    'message' => NULL,
      ),
    ),
  );
  $form['teammates_verify'] = array (
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
'
  );
  if ('' != _are_teammates_valid($form_state['values']['teammates'])) {
    $form['teammates']['#error'] = true;
    $form['teammates_verify']['#markup'] = ''.t('The following are not valid users: ')._are_teammates_valid($form_state['values']['teammates']).'
'.print_r($form_state,1).'
';
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'my_custom_form_callback',
      'wrapper' => 'level-form',
      'method' => 'replace',
      'effect' => 'fade',
      'name' => 'submit',
    ),
    '#value' => t('Submit'),
  );
  return $form;
}
function _my_custom_form_team_validate($element, &$form_state) {
  if (!empty($element['#value']) && '' != _are_teammates_valid($element['#value'])) {
    form_error($element, t('!teammates are not valid user. Please check spelling.', array('!teammates' => _are_teammates_valid($element['#value']))));
  }
}
function my_custom_form_validate($form,&$form_state) {
  // validate file upload
  // validate teammate list
  if (''!=_are_teammates_valid($form_state['values']['teammates'])){
    form_set_error('teammates');
  }
}
function my_custom_form_validate_teammates($form, &$form_state) {
  if ('' != _are_teammates_valid($form_state['values']['teammates'])) {
    form_set_error('teammates');
  }
  return $form['teammates_verify'];
}
function _are_teammates_valid($teammates) {
  if ('' != $teammates) {
    $team = drupal_explode_tags($teammates);
    $bad_usernames = ',';
    foreach($team as $possible_teammate) {
      $teammate = user_load_by_name($possible_teammate);
      if (!$teammate) {
        $bad_usernames += $possible_teammate;
      }
    }
    if (2 < strlen($bad_usernames)) {
      form_set_error('teammates',t('The following are not valid users: ').substr(2,$bad_usernames).t('. Please recheck spelling.'));
    }
  }
}
function my_custom_form_callback($form, $form_state) {
  my_custom_form_validate($form,$form_state);
  if (form_get_errors()) {
    return $form;
  }

  global $user;
  $nid = $form_state['values']['nid'];
  // $account = user_load($user->uid);
  $file = file_load($form_state['values']['video_fid']);
  if (!$file) {
    $pre['message'] = array(
      '#markup' => '
'.t('Please upload file first').'
',
    );
    return $pre+$form;
  }
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  // TODO change this file_usage_add() call to reflect current module ownership - see http://api.drupal.org/api/drupal/includes!file.inc/function/file_usage_add/7
  file_usage_add($file, 'user', 'user', $user->uid);

  if (!file_save($file)) {
    return t('There was an error uploading the file');
  }

  $team = array_map('user_load_by_name',drupal_explode_tags($form_state['values']['teammates']));
  array_unshift($team, $user);
  foreach ($team as $teammate) {
    $vnid = _make_video_node($teammate->uid,$form_state['values']['title'],$form_state['values']['notes'],$form_state['values']['nid'],$file);
    _make_completion_node($teammate->uid, $form_state['values']['title'],$form_state['values']['notes'],$vnid,$form_state['values']['nid']);
  }

  if (_my_custom_form_completes($nid, $team)) {
    drupal_set_message('Level Completed');
    return '
'.t('Level completed!').'
';
  }
  drupal_set_message('Error Completing Level');
  return '
'.t('Error Completing Level').'
';
}

Answer: It would be helpful if you could write which fields actually get validated. But from the code I guess the only validation working is
function my_custom_form_validate($form,&$form_state) {
  // validate file upload
  // validate teammate list
  if (''!=_are_teammates_valid($form_state['values']['teammates'])){
    form_set_error('teammates');
  }
}

It looks like you have created many different validation functions. But the hook validate is per form and not per field. So if was to wrote a validation function for your form I would try this:
function my_custom_form_validate($form,&$form_state)
{
   if (_are_teammates_valid($form_state['values']['your form field'])!='')
   {
     form_set_error('teammates');t('Your error message.'));
   }
   if ($form_state['values']['your form field']!='What it should be')
   {
     form_set_error('your form field');t('Your error message.'));
   }

   // ... and so on...
 }

You basically create one validate function and check each field in "$form_state['values']" and set the correct error message.


Drupal Commons site has no style after installation

Question: Drupal Commons site has no style after installing it: It looks like campus-24.com.
Note the JavaScript and CSS files are in:

/home/vhost/WWW/campus-24.com/sites/default/files/js
/home/vhost/WWW/campus-24.com/sites/default/files/css
/home/vhost/WWW/campus-24.com/sites/default/files/imagecache
/home/vhost/WWW/campus-24.com/sites/default/files/ctools
/home/vhost/WWW/campus-24.com/sites/default/files/pictures

All the folders are empty. During the installation, I noticed warnings about too many files open.
I heard about the "css_1acaad3d96ebad99fc9b6ef9d4ee4.css" file: This is called an automatic generated file that compress all CSS styles used as to improve speed and help not overloading rendering. What if this file is missing in my folder? Does my site than have to look like the above mentioned site? I have not seen the following options: This is due to the fact in the performance administrative section (admin/settings/performance), in "Bandwidth optimizations" you have "Optimize CSS files" and "Optimize JavaScript files" enabled. These settings are normally very usefull for production (live) sites; for testing and customizing your Drupal Commons installation, it is better to disable them, and to have CSS and JavaScript development support with tools like Firebug.
Notes:

I have not seen where I can switch the options.
The original .htaccess file was changed by my server admin. I guess that I (and that means the site admin, my friend) miss, and have forgotten, an important option.

Now I found out how to see some overviews, and made a big step ahead; I have landed in the View activity_log_stream, displaying items of type Activity Log.

I need some recommendations to figure out how to get some styles in the page.
$view = new view;
$view->name = 'activity_log_stream';
$view->description = 'Displays activity streams.';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'activity_log_messages';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
  'message' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'exclude' => 0,
    'id' => 'message',
    'table' => 'activity_log_messages',
    'field' => 'message',
    'relationship' => 'none',
  ),
));
$handler->override_option('sorts', array(
  'last_updated' => array(
    'order' => 'DESC',
    'granularity' => 'second',
    'id' => 'last_updated',
    'table' => 'activity_log_messages',
    'field' => 'last_updated',
    'relationship' => 'none',
  ),
));
$handler->override_option('arguments', array(
  'stream_owner_type' => array(
    'default_action' => 'ignore',
    'style_plugin' => 'default_summary',
    'style_options' => array(),
    'wildcard' => 'all',
    'wildcard_substitution' => 'All',
    'title' => '',
    'breadcrumb' => '',
    'default_argument_type' => 'activity_log_default_stream_owner_type',
    'default_argument' => '',
    'validate_type' => 'activity_log_validate_stream_owner_type',
    'validate_fail' => 'not found',
    'glossary' => 0,
    'limit' => '0',
    'case' => 'none',
    'path_case' => 'none',
    'transform_dash' => 0,
    'id' => 'stream_owner_type',
    'table' => 'activity_log_messages',
    'field' => 'stream_owner_type',
    'validate_user_argument_type' => 'uid',
    'validate_user_roles' => array(
      '2' => 0,
    ),
    'relationship' => 'none',
    'default_options_div_prefix' => '',
    'default_argument_fixed' => '',
    'default_argument_user' => 0,
    'default_argument_activity_log_stream_owner_type' => 'user',
    'default_argument_php' => '',
    'validate_argument_node_type' => array(
      'page' => 0,
    ),
    'validate_argument_node_access' => 0,
    'validate_argument_nid_type' => 'nid',
    'validate_argument_vocabulary' => array(
      '1' => 0,
    ),
    'validate_argument_type' => 'tid',
    'validate_argument_transform' => 0,
    'validate_user_restrict_roles' => 0,
    'validate_argument_php' => '',
  ),
  'stream_owner_id' => array(
    'default_action' => 'ignore',
    'style_plugin' => 'default_summary',
    'style_options' => array(),
    'wildcard' => 'all',
    'wildcard_substitution' => 'All',
    'title' => '',
    'breadcrumb' => '',
    'default_argument_type' => 'current_user',
    'default_argument' => '',
    'validate_type' => 'none',
    'validate_fail' => 'not found',
    'break_phrase' => 0,
    'not' => 0,
    'include' => array(
      'og' => 0,
      'ur' => 0,
    ),
    'id' => 'stream_owner_id',
    'table' => 'activity_log_messages',
    'field' => 'stream_owner_id',
    'validate_user_argument_type' => 'uid',
    'validate_user_roles' => array(
      '2' => 0,
    ),
    'relationship' => 'none',
    'default_options_div_prefix' => '',
    'default_argument_fixed' => '',
    'default_argument_user' => 0,
    'default_argument_activity_log_stream_owner_type' => 'user',
    'default_argument_php' => '',
    'validate_argument_node_type' => array(
      'page' => 0,
    ),
    'validate_argument_node_access' => 0,
    'validate_argument_nid_type' => 'nid',
    'validate_argument_vocabulary' => array(
      '1' => 0,
    ),
    'validate_argument_type' => 'tid',
    'validate_argument_transform' => 0,
    'validate_user_restrict_roles' => 0,
    'validate_argument_php' => '',
  ),
));
$handler->override_option('filters', array(
  'display_type' => array(
    'operator' => '=',
    'value' => 'web',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'display_type',
    'table' => 'activity_log_templates',
    'field' => 'display_type',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'perm',
  'perm' => 'view all activity messages',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('empty', 'There are no visible status updates.');
$handler->override_option('empty_format', '1');
$handler->override_option('use_ajax', TRUE);
$handler->override_option('items_per_page', 20);
$handler->override_option('use_pager', '1');
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->override_option('path', 'activities');
$handler->override_option('menu', array(
  'type' => 'normal',
  'title' => 'Activity stream',
  'description' => 'Displays activity streams.',
  'weight' => '0',
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler = $view->new_display('page', 'Page', 'page_2');
$handler->override_option('path', '');
$handler->override_option('menu', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));

Update:
On a quick step I did toggle the CSS-aggregation, and switched it off.
Just have a closer look at this, here:

Your lack of styles on the site is due to inadequate file permissions on your server. Your site is unable to save the auto-generated compressed CSS file, thus there is no style information to be displayed. Installing a different theme would do nothing to fix this situation. If you cannot manage to get the proper files permissions set up, you may try disabling CSS aggregation by navigating to Administration -> Site Configuration -> Performance, and toggling off the CSS aggregation setting, then clicking the save button. This will have a negative impact on the site's performance (speed of loading pages, etc.) and I would strongly recommend that you fix the underlying issue (file permissions) permanently before launching a live site so that you can re-enable CSS aggregation!

See the very first result of configuring accordingly.

See the very same issue described here. The suggestion is to convert some files to UTF-8, but which specific files should I need to change to UTF-8?
Answer: I can't tell you what the problem is, but there are some things you can do to debug this. First things that come to my mind are:

Check the status report (/admin/reports/status) and recent log messages (/admin/reports/dblog) to see if everything is OK. You may find that the file system is not writable; in that case, modify the permissions on your file folder (on Linux it's usually chmod -R 777 sites/default/files).
If you think it's caused by the .htaccess file, try if replacing the original .htaccess solves the problem. If it does, apply the needed changes one by one and see when it breaks.
Check the PHP/Apache error logs (assuming that you're on a Apache web server) for clues.
Comment: hi marcvangend thx i do as adviced and come bakd to report all the findings -thx so far!
Comment: hello dear friends i have added some updates - see above... if you want to have access to adminarea just lemme know! i think that this goes over my head
Comment: hi marvangend - many thx for your great work here. and for the comments, replies and the editing, you do a superb job. well after 4 weeks i finally have found the above mentioned hints that helped me to fix the issue. well to toggle the css-aggregation is called to be a quick - rough - hack. i should have to talk to my server-admin that he carefully sets the chmods chowns of the files and folders - especially of those in the path sites/default/files - note:there the user wwwrun appeared in the last 4 weeks and thererfore i had troubles with the read of all content there... thx to you again –


How to get *binary photo data* from (v1.0) Get Photo API?

Question: I would like to get user's photo and display it in the application. How can I do it?
Get Photo API (http://graph.microsoft.io/GraphDocuments/api-reference/v1.0/api/photo_get.htm) returns the "photo" object (http://graph.microsoft.io/GraphDocuments/api-reference/v1.0/resources/photo.htm) which doesn't contain binary...any suggestion?
Thanks,
Raymond,
Comment: Please add some code to support :)
Answer: To get the binary please use https://graph.microsoft.com/v1.0/me/photo/$value
Comment: More info/samples can be found here: https://graph.microsoft.io/docs/api-reference/v1.0/api/profilephoto_get
Comment: It looks like the menu link in the documentation leads to the photo_get instead of profilephoto_get API. I created https://github.com/OfficeDev/microsoft-graph-docs/issues/23 to correct that.
Comment: Unfortunately the specified link doesn't provide you with much information regarding what to do with the response of the photo/$value endpoint. I included some more information in a blog post at http://blog.mastykarz.nl/office-365-groups-api/. It would be great if we could incorporate this information in the official documentation. I've submitted a related issue at https://github.com/OfficeDev/microsoft-graph-docs/issues/19.


How can I get value from promise & use in another function?

Question: Let me explain the issue, I am trying to show some details in a modal. I am using table in the modal to show details. In one section, I need the product name which is returned from a database query and I have to use that value returned from the database. The code for table is as follows:

                            {item.cartItems.map((item, i) =>

                                    {i + 1}
                                    <img src={`${API}/product/photo/${item.product}`} alt={item.product.name} width="60px" height="50px" />
                                    {**data returned from database**}
                                    {item.count}
                                    ৳ {item.price * item.count}

                            )}

To get the data from the database, I am using a function
const getProdcutName = id => {
    var productName;
    getProductDetails(id)
        .then(response => {
            productName = response.data.name;
        });
    return productName;
}

But I can't access the value. The main thing is, in every Iteration I need to send the {item.product} to getProductName(id) and I need the name from the database in return. But I can't access the data from promise scope to return it.
Comment: try to keep your code correctly indented, makes it easy for us to help you.
Answer:  const getProdcutName = (id) => {
    return getProductDetails(id)
        .then(response => {
            return response.data.name;
        });
    }

and you can get the value like this:
await getProdcutName(...)    // must be inside async function

if you want to use the value in that function, then:
 const getProdcutName = async (id) => {
     const name = await getProductDetails(id)
         .then(response => {
             return response.data.name;
         });
    console.log(name)
 }

Comment: How can I call a async function inside map with the HTML table?
{item.cartItems.map((item, i) =>
**Here**

{i + 1}

{**data returned from database**}

                            )}
Comment: You have to call it inside a specific component lifecycle, based on your needs, and store it in a state
Comment: Yes, I can do that but I need to fetch data from the database every time my item.cartItems iterates. In that case, If I had to call it inside a lifecycle, I have to send the id parameter but without iterating how can i do that? Can you please help me out briefly?
**const getProductName = async (id) => {
        await getProductDetails(id)
            .then(response => setProductName(response.data.name));
    }
    // useEffect(() => {
    //      getProductName(id);
    // }, [])**
** {item.cartItems.map((item, i) => {I need to call the function here by passingthe parameter}**
Comment: If you have to call a request on each iteration, separate your "tr" content in a different content, and make a request inside that component. const Tr = ({item}) => { useEffect(() => {here is the logic for fetching}, [item.id]);  return ...content}


Why do I need to reference all packages in a WPF appl. that are referenced by another project

Question: There are two C# projects together in one solution

Net.Company.Core
Net.Company.Application

The Core project references a few NuGet packages (e.g. LiteDB 4.1.4). The Application project references the Core project directly (i.e. not via NuGet).
Now when I want to run the Application project I'm getting an exception that a reference to any of the NuGet packages, referenced in the Core project, is not found (FileNotFoundException). In order to resolve this error I also reference the NuGet packages in the Application project.
Question: Why does the Application project need to reference these packages as well? My assumption is that the Core project already brings in these references.
Answer: When the Application Project Runs - it runs from its own bin/Debug folder. If you check the contents of that folder you will find the Core project dll and other stuff. But not the dll's libraries/nugets that core project needs. So when the Application project code uses the Core Project and the Core project uses one of those Nugets/libs... it fails becuase those libaries arent in the output (current executing folder).
One way to solve this would be to set the Build Output folder of Core project to be same as that of the Application project.
Comment: In all honesty - Application project doesnt need them in packages.config - because it doesnt directly use them. This situation has happened because you have added project reference of Core project into Application project. Preferred way would be to Bundle your Core Project as a nuget (with all dependencies assigned) - then use that Core project nuget in the Application project. So all dependencies will come along.
Comment: Yes. This is what I do in general. Here, the application project is just a test tool to test and verify the latest changes to the core project before they go live. That's why it is directly bundled to it. All "real" projects that use the core do include it via NuGet package.
Comment: So in other words. Because the Application project does not reference them in the packages.config file and only the dll is included from the Core project they are simply not there.


Make private pdf files Non-Downloadable via absolute url links

Question: In a content type I have option for pdf file upload, the uploaded files are stored in private folder.
The uploaded file has absolute url of http://example.com/system/files/abc.pdf
At the moment anyone with the absolute url can download the file (no matter the user roles, access and permissions)
I want to redirect visitors to the front page of the website (instead of downloading) if they use the absolute url of pdf in browser to download it.
So far I tried something with JavaScript something like:
$(document).ready(function() {
  if(window.location.href.indexOf(".pdf") > -1) {
    $(location).attr('href', window.location.protocol + "//" + window.location.host); // Redirect to front page
  }
});

Usually this would do the trick if it was rendered webpage where javaScript is loaded, but it doesn't work with pdf files (as javaScript is not loaded while clicking the absolute url of the pdf file).
I have already tried private files download permission module, but that doesn't do what I want, as my downloadable links are accessible to Anonymous users as well.
Any hints, suggestions, how to accomplish this?
Answer: It should be as easy as adding an implementation of hook_file_download() to a custom module:
function MYMODULE_file_download($file) {
  // Add whatever other conditions you need to this, e.g. test the
  // file extension for .pdf
  if (user_is_anonymous()) {
    // Deny
    return -1;
  }

  // Allow
  return file_get_content_headers($file);
}

Comment: couldn't thank you more !!! have a nice weekend :-)


Showing that an epimorphism of an ideal is again an ideal

Question:
Let $R, S$ be commutative rings, $f : R \rightarrow S$ an epimorphism, I an ideal of R. Show that $f(I)$ is an ideal of $S$.

As far as I understand, I need to show 4 things:
1) $0_s \in f(I)$
2) $sf(i) \in f(I), f(i)s \in f(I) \ \forall s \in S \ \forall f(i) \in f(I)$
and the subgroup properties
3) $f(a) + f(b) \in f(I) \ \forall a,b \in I$
4) $f(a)^{-1} \in f(I) \ \forall a \in I$
that's what I have so far:
1) $I$ ideal of R $\Rightarrow 0_R \in I \Rightarrow_{f(0_R) = 0_S} 0_S \in f(I)$
2)
$f$ surjective $\Rightarrow \exists s' \in R : f(s') = s$. $sf(i) = f(s')f(i) = f(\underbrace{s'i}_{\in I}) \in f(I)$.
(and the other direction similar).
3) $f(a) + f(b) = f(\underbrace{a + b}_{\in I}) \in f(I)$
4) I tried a few approaches, but didn't succeed in this part. Can you help me to show why the inverse element exists?
Is my approach correct?
Comment: You don't need to show closure under multiplicative inverses. In fact, if an ideal contains an invertible element, then the ideal contains $1$, and so so is the entire ring.
Answer: $a^{-1} \in I \Rightarrow f(a^{-1})=f(a)^{-1} \in f(I)$
EDIT:(as Simon suggested)
There is no need for inverse to show ideal
Comment: thank you for your answer! Do 1) - 3) look correct for you?
Comment: You are welcome. 1)-3) look fine to me


Como nomear um teste unitário quando utilizamos TDD?

Question: É comum utilizarmos substantivos para nomearmos: classes (Carro, Veiculo, NotaFiscal); verbos de ação (no infinitivo ou não) para nomes de métodos (CalcularTotal/CalculaTotal, LerTodasAsLinhas, FecharConexao, AbrirPorta/AbrePorta); interrogações para retornos booleanos (Enable, MustCalculate, ShouldDoSomething, EstaAberta, DisparouExcecao, EstaGravado, EstaAtivo). Essas são recomendações da OMG (para UML).
Porém, e quanto aos testes unitários? Existe algum padrão, guia para nomear os teste unitários?
A seguir, alguns exemplos de nomes que encontrei em alguns códigos que já tive contato:

Deve_retornar_zero: não diz a situação, nem o motivo, e nem o que está sendo testado, apenas mostra o comportamento desejado.
Nao_deve_ter_sobre_nome_ao_informar_...: tenta descrever um comportamento, mas esse nomes geralmente ficam bem grandes.
IntParse: nesse caso, é um teste para o método Parse(...) da classe Int.

Já vi nomes separados por underline, sem separação, mas escritos em camelcase, e muitas outras formas.
A minha dúvida é: existem guias/sugestões de melhores práticas para nomearmos testes unitários quanto utilizamos TDD?
Comment: Ao que tudo indica você já conhece vários "padrões". A resposta do @reinert esboça a minha forma pessoal também, de todas as outras formas que já usei ( as que você citou ) achei esta mais objetiva. Só um adendo, seja consistente. Se escolher uma forma use-a até o final converse com o seu time e decida isso junto com eles. Não se esqueça que TDD vai muito além disso, então seja significativo nos nomes, se conseguir isso, o padrão de nomenclatura passará a ser apenas um coadjuvante.
Answer: Sua pergunta trata de dois aspectos da nomeação de métodos; semântica e formatação, por assim dizer (classificações que me ocorreram agora).
Formatação
A questão da formatação é simples:

faca_alguma_coisa()
facaAlgumaCoisa()
FacaAlgumaCoisa()

A formatação é convencionada pelo time e é fácil de compreender e de manter. Eu sempre proponho ao time identificar a cultura da linguagem e seguir esta cultura. Por exemplo, em java utiliza-se muito o lowerCamelCase, diferente do C#, onde utiliza-se mais o UpperCamelCase para nomes de métodos, que é diferente de Ruby, onde utiliza-se lower case com underline como separador. Mas a decisão final é do time e um analisador automático de código pode identificar fácil o código que não estiver seguindo a convenção.
O que é mais importante aqui sobre a formatação é que não existe uma convenção para o TDD. Existe sim uma convenção para o time ou para o projeto. Todo o código deve seguir a convenção, seja o código de produção ou o código de testes.
Semântica
Como sabemos, o nome de um método deve revelar o seu comportamento, e deve obeder a linguagem de negócio (quando ele tratar de negócio). E a assinatura do método deve garantir a abstração de como o método trabalha. A assinatura deve revelar ao consumidor tudo que ele precisa saber sobre o método sem precisar olhar o código dentro dele.

O código dos testes unitários tem um conceito diferente. O nome de um
método de teste unitário não tem que revelar com precisão o
comportamento que ele espera, tampouco tem que revelar as condições,
entradas e saídas ("when..given.then")!

Embora o nome do método tenha que ser significativo, é o corpo dele, o código dentro, que vai descrever as condições, entradas e saídas esperadas.
Veja este exemplo:
public class JogoVelhaTeste {
    @Test
    public void naoHaVencedor() {

        String[] tabuleiro = {
                "X", "O", null,
                "O", "O", null,
                "X", null, "X"} ;

        JogoVelha jogoVelha = new JogoVelha();

        assertNull(jogoVelha.obtemVencedor(tabuleiro));
    }
}

Quando eu quiser saber o que determina se não há vencedor, o nome do método me permite encontrá-lo entre os outros, mas para saber de fato qual entrada determina que não há vencedor (no caso, um tabuleiro com determinadas jogadas), e para saber como é retornada a informação de que não há vencedor (no caso, o método obtemVencedor retorna null), eu olho o código dentro do método.
Assim, o próprio código dentro do método é a documentação das condições, entradas e saídas. E é uma documentação executável! Nunca estará desatualizada, como pode ocorrer com os comentários.
O artigo do Roy Osherove dá umas dicas bacanas, mas você não precisa de um método chamado Sum_NumberIgnoredIfBiggerThan1000. Seria melhor chamar de Sum_NumberIgnoredWhenTooBig, que provavelmente é suficientemente significativo. As entradas, como eu disse, estão descritas no póprio código dentro do método.
O teste não deve depender de comentários
Neste exemplo, o autor sugere um comentário para descrever o teste. Ok, não é um simples comentário; é atributo .Net! Mas no final não passa de um comentário, que não compila, que não afeta o funcionamento do teste, e que pode ficar desatualizado, e que só vai ser lido como última opção do desenvolvedor quando ele estiver procurando por um teste em código antigo (assim como o desenvolvedor também pode ler o código dentro do método).
Veja:
[TestMethod]
[Description("Given two tables And same data But different column order | When TableAssert | Then true")]
public void ColumnOrderDoesntMatter()

O nome deste método já é bastante significativo. Dispensa o comentário. As condições, entradas e saídas podem ser verificadas no corpo do próprio método, o qual o autor do exemplo não revela mas que bem pode ser algo assim:
[TestMethod]
public void ColumnOrderDoesntMatter() {

    Table tableAscValues = new Table("value 1", "value 2");
    Table tableDescValues = new Table("value 2", "value 1");

    Assert.Equals(tableAscValues, tableDescValues);
}

Trazer de volta o comentário (Description) para o método acima seria redundante.
Behavior Driven Development (BDD)
BDD é diferente de nomear o método no estilo when..given. then. BDD trata-se de escrever testes com esta semântica utilizando uma linguagem executável. Então, assim como no meu exemplo (que não é BDD), é o corpo do método de testes que diz as condições, entradas e saídas, e não o nome do método.
Escolhendo um nome de método de testes usando TDD
Em TDD escrevemos o teste primeiro. Muitas vezes ainda não sabemos como será o design da solução - ele vai emergir a partir dos testes. Então pode ser muito difícil escolher imediatamente um bom nome para o teste. Não tem problema. Escolha um nome qualquer que revele mais ou menos a intenção do que você quer testar, depois escreva mais alguns testes, depois revisite todos os métodos recém criados e os refatore, inclusive melhorando seus nomes.
Conclusão

O formato do nome do método de testes (lower camel case, underline...) deve seguir as mesmas regras do código de produção. Estas regras são convencionadas pelo time.

O nome do método de testes deve ser significativo, deve descrever sobretudo o comportamento de negócio que se está testando; mas as condições, entradas e saídas são descritas pelo código dentro do teste. Um método de testes não tem o mesmo tipo de abstração que devem ter os métodos dos objetos de negócio.

O corpo do método de testes é a documentação executável do comportamento do sistema.
Answer: Há gosto para tudo, nunca vi um padrão universalmente aceito. Nessa resposta coloquei padrões de nomenclatura bem aceitos porque basicamente foi estabelecido pela empresa criadora da linguagem C#, fazendo as devidas ressalvas. Neste caso acho mais complicado.
Para TDD, o qual eu tenho pouco experiência, dependendo da linguagem pode ter pequenas diferenças de padrão mas acho que o que você quer saber é algo que pode ser aplicado para todas as linguagens salvo diferenças estilísticas de usar maiúsculo, minúsculo, sublinhado, etc.
Já vi recomendações diferentes. Uma delas é descrever o que se espera que este teste representa de forma bem sucinta. Outra é descrever exatamente o que e como o método testa.
Particularmente a primeira me parece ser mais sensata. Os primeiros exemplos que citou parecem usar a segunda forma que eu citei. Sei que muita gente usa assim. Mas parece ser um caso das pessoas copiarem uma forma estabelecida no passado mas que ninguém pensou muito se faz sentido ou não. Já falei muitas vezes que isto ocorre muito na nossa indústria. Tem gente que ainda segue recomendações dos anos 50. Claro que algumas ainda podem ser válidas, mas não todas. Talvez era assim porque as ferramentas não eram boas. E talvez algumas ainda não sejam.
Então deve-se tentar entender porque o método deve retornar zero e descrever a motivação do teste. Deve-se usar um contexto. Quem vai dizer que deve retornar zero é o código.
Algumas linguagens permitem ainda ter um atributo/anotação que permite dar uma descrição detalhada do que o teste faz. Seria um comentário que a ferramenta vai aproveitar para ajudar descrever o teste quando ele rodar. Ex.:
[TestMethod]
[Description("Given two tables And same data But different column order | When TableAssert | Then true")]
public void ColumnOrderDoesntMatter()

Coloquei no GitHub para referência futura.
O exemplo foi retirado dessa página. Nela mostra como a forma detalhada de nomear o método é pior.
Acho que assim o programador está fazendo TDD de verdade. TDD deve demonstrar o que acontece no teste e não como é testado.
Nessa outra página há uma análise da forma mais usada.
Teste unitário é o termo errado.
Answer: Venho utilizando há bastante tempo o padrão [UnitOfWork_StateUnderTest_ExpectedBehavior] apresentado nesse histórico artigo por Roy Osherove e citado nessa respota.
Até hoje, ele vem se aplicando a todos os casos que me deparo. Claro que para isso é necessário habilidade do programador em modelar corretamente a unidade a ser testada, e se for o caso, redesenhar seu projeto para que este torne-se plausível. Inclusive, esse é um dos benefícios do TDD, influenciar positivamente no design.
Vale notar que este padrão descrito por Roy pode ser enxergado também da seguinte forma [When_Given_Then], induzindo-nos a desenvolver o nosso método de teste conforme a seguir:
UnitOfWork_StateUnderTest_ExpectedBehavior() {
    // Given
    // promova o estado sob teste...

    // When
    // acione a unidade de trabalho, ou o método...

    // Then
    // verifique o comportamento desejado...
}

Exemplo de teste de uma classe Foguete (com Mockito):
decolar_tanqueVazio_permanecerParadoExibindoAviso() {
    // Given
    foguete.esvaziarTanque(); // foguete é uma mock instance em escopo de classe

    // When
    foguete.decolar();

    // Then
    verify(foguete, never()).iniciarDecolagem();
    verify(foguete, atLeastOnce()).exibirAvisoTanqueVazio();
}


Devise skip_confirmation! fails to avoid to send the confirmation instructions

Question: My app is set up so that if a user signs in with Oauth or Openid, they don't have to confirm their email address.  However, Devise is still sending email confirmations.  When I call User.skip_confirmation! I get an undefined method error.  My model:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable,
  :trackable, :validatable, :confirmable, :lockable, :token_authenticatable, :omniauthable

  attr_accessible :username, :email, :password, :password_confirmation, :remember_me
  validates_presence_of :username
  validates_uniqueness_of :username, :case_sensitive => false

  def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info
    if user = User.where(:email => data.email).first
      user
    else
      #User.skip_confirmation!
      User.create!(:username => data.name, :email => data.email, :password =>    Devise.friendly_token[0,20])
    end
  end

  def skip_confirmation!
   self.confirmed_at = Time.now
 end
end

My Controller:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
    @user.skip_confirmation!
    if @user.persisted?
      sign_in @user
      @fname = @user.username
      redirect_to root_path, :flash => { :success => "Welcome #{@fname}!" }
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
end

thanks for any help.
Comment: Since you are already using :confirmable you don't really need the `skip_confirmation!` message (http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Confirmable#skip_confirmation%21-instance_method)
Could you post the stack-trace? I doubt it's the `skip_confirmation!` method that's missing.
Answer: You need to skip confirmation before you create the User objects and its persisted to the database. So the user creation part of your method would look like

user = User.new(:username => data.name, :email => data.email, :password =>    Devise.friendly_token[0,20])
user.skip_confirmation!
user.save
Comment: That worked after I changed user.save to user.create.  Thanks.
Comment: I think you also need to add 'user' as the last line so it will remain the return value of the function
Comment: Hi Rishav, I have exactly the same code in user.rb, still my app sends out the confirmation emails when I authorize it in Facebook. Any idea why user.skip_confirmation! is not doing anything?
Comment: @LaszloTenki - Its hard to suggest a solution without looking at your code. It might be something small that you might be missing.
Answer: If you're updating a user record, make sure to use skip_reconfirmation! (mind the re)


Prevent rounding of numbers when converting dictionary into dataframe

Question: I wrote a code where I first create a dictionary and then convert it to a dataframe. The dictionary contains lat and lon data. My issue is that during the transformation into the dataframe, the lon and lat data is rounded.
The code looks like this:
geodata = {'01067': (13.7210676148814, 51.0600336463379, u'Dresden'),
        '01069': (13.7389066401609, 51.039558876083, u'Dresden'),
        '01097': (13.7439674110642, 51.0667452412037, u'Dresden'),
        '01099': (13.8289798683304, 51.0926193047084, u'Dresden'),
        '01109': (13.7619645364861, 51.1201009324663, u'Dresden'),
        '01127': (13.733347378178, 51.0796304130158, u'Dresden'),
        '01129': (13.7274104697459, 51.0967944759693, u'Dresden'),
        '01139': (13.6911443969423, 51.0805574259239, u'Dresden'),
        '01157': (13.6708047478723, 51.0643076931977, u'Dresden')}

postal_data1= pd.DataFrame(geodata) # at this point the numbers are rounded

postal_data1 =  postal_data1.T
postal_data1['zip'] = postal_data1.index
postal_data1.columns = ['lon', 'lat', 'city', 'zip']
postal_data1 = postal_data1.reindex(columns=['zip', 'lat', 'lon', 'city'])
postal_data1 = postal_data1.reset_index(drop=True)

At the end the dataframe looks like this:
postal_data1.head()

     zip      lat      lon     city
0  01067    51.06  13.7211  Dresden
1  01069  51.0396  13.7389  Dresden
2  01097  51.0667   13.744  Dresden
3  01099  51.0926   13.829  Dresden
4  01109  51.1201   13.762  Dresden

Does anyone has an idea how I can prevent the rounding of the lat and lon data?
Thank you for your help.
Answer: That's not needed. The printed head() is just a representation pandas shows in prints. Altough the default data precision is higher, you can modify the representation using:
pd.set_option("display.precision", 10)

Comment: but when I access the dataframe via the variable explorer (I use spyder), it also shows only the rounded numbers. Wouldn't that mean that the numbers were indeed rounded?
Comment: it could use the representation anyway, you can check by accessing a single cell value (with .value)


RK4 Approximation

Question: I have the following differential equation:
$y'=xy^2-(y/x)$ with the initial value $y(1)=1$.
I'm trying to get a 4-digit approximation of this differential equation for $y(1.5)$ but I have thus far been unable to understand the RK4 method. I have been trying to understand how you would solve this without a computing system and so far I have been unable to figure this out.
Anything would help. Thanks!
Comment: Well actually it doesn't matter. Since you [don't care to appreciate help](https://math.stackexchange.com/users/464506/john-smith?tab=questions), I will not waste time here.
Comment: For me it is not clear what you actually want. Do you need to use the RK4 method? If not, why did you choose RK4?
Answer: You set $h=0.5$. Then compute per cook-book recipe using rounding to 2 digits
\begin{align}
k_1&=hf(x,y)&&=0.5f(1,1)&&=0\\
k_2&=hf(x+0.5h, y+0.5k_1)&&=0.5f(1.25, 1)&&=0.22\\
k_3&=hf(x+0.5h, y+0.5k_2)&&=0.5f(1.25, 1.1)&&=0.5(1.25\cdot 1.21-1.1⋅0.8)=0.32\\
k_2&=hf(x+h, y+k_3)&&=0.5f(1.5,1.32)&&=0.5(2.73-0.9)=0.87\\ \\
y(1.5)&\approx 1+(k_1+2k_2+2k_3+k_4)/6&&=1+1.95/6&&=1.32
\end{align}

The double computation gives
k1 = 0.0
k2 = 0.225
k3 = 0.32853515625
k4 = 0.8809091939608258
1+(k1+2k2+2k3+k4)/6 = 1.331329917743471

The exact solution results from $u(x)=\dfrac1{xy(x)}$, $u(1)=1$
$$
(xu)'=u+xu'=-\frac{y'}{y^2}=-x+u\\\implies u'=-1,\; u=2-x \\\implies y(x)=\frac{1}{2x-x^2}
$$
so that $y(\frac32)=\frac43=1.3333...$

RK4 Approximation


Why is my css class not firing upon initial load?

Question: I have a bootstrap tabbed component on my page. I am trying to control which tab is active upon reload of the page. But, on initial load the behavior of the tab is very peculiar. Here is the code:

<l1>

what it is showing in the markup and it is not working is (notice the active out outside the quotes

<l1>

the behavior only happens on inital load, but it the tabs are pressed, the behavior is normal, but the extra "active" remains. I am confused where the active outside the quotes is coming from?
Answer: The problem is your output doesn't render the double quotes so it looks like this, where the active class doesn't get attached to anything but the browser will just see it as a standalone attribute:

<l1>

Instead try this:

<l1>

Comment: yep, this was the answer, I cannot thank you enough. I started to go down this path, but for some reason I didn't think this would work.