Difference between arbitary collection and finite collection

Question: In basic topology of real number ( real analysis) , there is these two theorems which states : The union of arbitrary collection of open sets is open. Another one is : The intersection of finite collection of open sets is open. Here, I would like to ask what is the difference between arbitrary and finite ? If I change finite in the second theorem, will it still hold ? If it does not hold, can anyone give some examples to illustrate ?
Answer: An arbitrary collection of open sets is just that: any collection of open sets at all, finite or infinite, with no restriction save that the sets be open. If you change finite to arbitrary in the second statement, it becomes false. For example, in $\Bbb R$ the sets $(-x,x)$ for $x>0$ are all open, but their intersection is $\{0\}$, which is not open: $\bigcap_{x>0}(-x,x)=\{0\}$. Here are two more examples.

For each $q\in\Bbb Q$ let $U_q=\Bbb R\setminus\{q\}=(\leftarrow,q)\cup(q,\to)$; this is an open set. But $\bigcap_{q\in\Bbb Q}U_q=\Bbb R\setminus\Bbb Q$, the set of irrational numbers, which is definitely not an open set.
For each $n\ge 2$ let $U_n=\left(\frac1n,1+\frac1n\right)$; then $$\begin{align*}\bigcap_{n\ge 2}U_n&=\left(\frac12,\frac32\right)\cap\left(\frac13,\frac43\right)\cap\left(\frac14,\frac54\right)\cap\ldots\\
&=\left(\frac12,1\right]\;.\end{align*}$$ You may have to think a bit about that intersection to see that it really is $\left(\frac12,1\right]$.
Comment: thx for your explanation and examples. I understand now
Comment: @Idonknow: You're welcome; glad it helped.
Comment: Since set of irrational numbers is an open set, is the set of rational numbers  also an open set ?
Comment: @Idonknow: The set of irrational numbers is **not** an open set, and neither is the set of rational numbers. Neither of them even contains an open interval.


How to get the count on the select list in views?

Question: For example, I have a content type with field. The field is select list. The select list has four default values as well as it is required.
I want the output of a view as:
Provincial (2)
Federal (6)
Institutional (3)
...
Value (#)

where # is the number of nodes with this value
How can I accomplish this?
Answer: Assuming Drupal 7 and Views 3:

Create a view based on your content type with a page or block display
Add a contextual filter, based on your select field
Under "When the filter value is NOT available" select "Display a summary"
Configure the summary as you like, with "Display record count with link" enabled
Answer: Use direct database Query, Replace appearance of "field_select" with your field name in below code
SELECT count(*), `field_select_value` FROM `field_data_field_select` GROUP BY `field_select_value`

Then get the label of select field from value using below technique replace field_select with the field name of select list
$key = field_select_value; // Or whatever
$field = field_info_field('field_select');
$label = $field['settings']['allowed_values'][$key];

Comment: Thanks, from your answer, I have to write code to do it, right? If without any coding, can I do this? Actually I can use the same way to get the count on term reference, but not on the select list.
Answer: Check this answer https://drupal.stackexchange.com/a/81953/12163 for a similar approach. It uses the views_merge_rows module. No need for custom coding.
The fields of the views will be the Select list field and the nid. The nid will be aggrgated with "Count" and excluded from display. The select list will be overwritten with [select_list] ([nid]).
Answer: You may use Views Aggregator Plus module to display number of nodes.
After installing and enabling the module, In your view

Select table format as Table With Aggregation Options
In the settings, under your desired field select Group and Compress as a group aggregation function
For the number of nodes, select Count as a group aggregation function for the nodes field
Then render the column and add separator as you like for the display
Answer: You could use Views Aggregation feature to attain that result. Check https://drupal.stackexchange.com/a/15875/4915 for a solution similar.
Comment: Thanks a lot. I did use the same way as http://drupal.stackexchange.com/a/15875/4915, however I got the below output: "Provincial (1) Provincial (1)". I want to get "Provincial (2)".
Comment: If you've not already it's worth double checking you don't have a dodgy sort setting on your view. If you do have sorts, take them out and see if it works OK. You can put back after if it does and make sure aggregation settings are pukka on the sort fields.


How to add Angular 5 application to solution in Visual Studio?

Question: Let's say that in my solution Insig I have already project Insig.Api in Asp.net Core.
Then I've added new empty web project Insig.Web
Then I've created web application in Angular via ng new ClientApp.
And I've put ClientApp to wwwroot from Insig.Web and I set Multiple startup project for both of them.
Now when I press in Visual Studio Start then I'd like to run Api with my angular application. How can I do this?
I'm aware that I can do this using default Angular template from Visual Studio, but I'd like to do this from scratch as template contains a lot of unnecessary stuff.
Answer: I have found solution HERE
Hope it helps someone since in most tutorials is used default template from Visual Studio which is actually old version Angular 4...
By the way in Startup.cs there is no need to add lines with AddMvc and UseMvc of course if you want to have API in another project than Angular as I wanted.
And use ng build --watch to track changes.
And don't forget to disable CORS in Api Startup.cs
app.UseCors(builder => builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());


bootstrap page header h1 exit outside of layout

Question: I need small resize my actual h1 of page, I've tried with CSS but it is not working, my actual HTML page is this: http://www.bootply.com/UPAE5Fllat
Problem is h1 of page and search div go outside of layout, example in this image: https://snag.gy/8KcMva.jpg, how I can resize this h1 and search div to not go outside of the layout?
Answer: On line 120 you need to remove the row class.
This because the row class has a negative margin, and you need it only when is followed by a col-* element.
Answer: Try this
  <meta charset="UTF-8">
  <title>selfmarket.net - bitcoin marketplace </title>
  <link rel="stylesheet" href="/static/css/bootstrap.min.css">
  <link rel="alternate" type="application/atom+xml" title="Atom" href="/atom.xml">
  <link rel="stylesheet" href="/static/css/main.css">

             admin

  PREMIUM MEMBER

 Products

 Messages 0

                 Favorites

Items 1

Search 0

 Dashboard

 Admin panel

 Logout

        Add product

    <form class="form-inline" action="/" method="GET">

    <input type="text" class="form-control" placeholder="Search market....">

  <button type="submit" class="btn btn-primary">Search</button>

     Sort by:
     <select class="form-control">
       <option>Date Added</option><option>Lowest Price</option>
       <option>Higher Price</option><option>Best Seller</option>
     </select>
     <button type="submit" class="btn btn-primary">Apply</button>

</form>

New

          app

              1

          software

              1

          voucher

              4

test product instant

              voucher

         admin

2.99 $

test product 3

              voucher

         admin

1.99 $

am pula mare

              voucher

         admin

1.99 $

cauciucuri de top

              voucher

         admin

1.99 $

product 4

              app

         admin

1.00 $

product 111

              software

         admin

1.00 $

 © 2016
          selfmarket.net /
          RSS Feed /
          sitemap.xml

Answer: line 60 add "row" class
line 120 remove "row" class
This because bootstrap requires a hierarchy of classes for the padding to remain consistant.


How to write it formally? Convergence of an infinite sum

Question: I know that the following sum $$\sum_{n=1}^{\infty} \frac{1}{\sqrt{1+2n}} e^{-\sqrt{n}}$$ converges because it's basically looking at $$\sum_{n=1}^{\infty} \frac{1}{\sqrt{n}} e^{-\sqrt{n}} \sim \int_{1}^{\infty} \frac{1}{\sqrt{x}} e^{-\sqrt{x}} dx = \frac{2}{e},$$ which is convergent. But how can I make this reasoning more formal?
Comment: You don't need the $\frac{1}{\sqrt{1+2n}}$ to get convergence, so you can ignore it. The sum of the exponential is easy to prove converges, e.g. since $\exp\sqrt n$ grows faster than $n^2$.
Comment: Apply the inequality $$(2n+1)^{-1/2}e^{-n^{1/2}}\le n^{-1/2}e^{-n^{1/2}}\le \int\limits_{n-1}^nx^{-1/2}e^{-x^{1/2}}\,dx $$ Then sum up from $2$ to $\infty.$
Comment: Use the following inequalities:
$$
\sum_{n=1}^{\infty} \frac{1}{\sqrt{1+2n}} e^{-\sqrt{n}}<\sum_{n=1}^{\infty} \frac{1}{\sqrt{n}} e^{-\sqrt{n}} < \int_{0}^{\infty} \frac{1}{\sqrt{x}} e^{-\sqrt{x}} dx=2.
$$
Answer: With your results as given you could use the limit comparison test. Observe that
$$
 \frac{\left(\displaystyle \frac{1}{\sqrt{1+2n}} e^{-\sqrt{n}}\right)}{\left(\displaystyle \frac{1}{\sqrt{n}} e^{-\sqrt{n}}\right)}
= \sqrt{ \frac{n}{1+2n} } \xrightarrow{n \to \infty} \frac{1}{\sqrt 2} \in (0,\infty)
$$
Since you know that the simpler sum converges, you have the convergence of the desired sum.
Comment: I didn't know about this test. Thanks a lot!
Comment: I would rather apply the comparison test as $(2n+1)^{-1/2}\le n^{-1/2}.$ The limit comparison test is useful if the expressions cannot be compared easily but the asymptotic behaviour of their ratio can be determined.
Comment: Perhaps in general. I'm simply seeing the information given to me by the OP. With this information, finishing a proof via LCT is a one-liner. Is it the fastest way they could've done it overall? Perhaps not. But it is probably the fastest that they could do it with the work they've already done.
Answer: $$ \sum_{n=1}^{\infty}\frac{e^{-\sqrt{n}}}{\sqrt{1+2n}}\le \sum_{n=1}^{\infty}\frac{e^{-\sqrt{n}}}{\sqrt{n}}\le e^{-1}+\int_{1}^{\infty} \frac{e^{-\sqrt{x}}}{\sqrt{x}}\ dx=\frac{3}{e} $$
Answer: $$\begin{align*}\sum_{n=1}^{\infty} \frac{e^{-\sqrt{n}}}{\sqrt{1+2n}}&<\sum_{n=1}^{\infty} \frac{e^{-\sqrt{n}}}{\sqrt{2n}} \\
&\sim\sum_{n=1}^{\infty} \frac{e^{-\sqrt{n}}}{\sqrt{n}}\end{align*}$$
$e^{-\sqrt n}/\sqrt{n}$ is continuous and monotone decreasing on $n\in[1,\infty)$, hence by the integral test,
$$\sum_{n=1}^\infty\frac{e^{-\sqrt n}}{\sqrt{n}}\sim\underbrace{\int_1^\infty\frac{e^{-\sqrt x}}{\sqrt x}\ dx}_{2/e}$$
the improper integral is finite and the series converges.


TFS Build Automation(New project added to solution is not showing up in build output directory)

Question: We have build definition in place and it is building the solution and coping the binaries to the output directory as required. But when I added a new project to the solution, the binaries of the new project are not copied to the build output folder.
Do we need to do any changes to the build definition when we add a new project, because if I do any changes to the existing projects the build output is updated correctly as per the changes. Do I need to do any refresh kind of thing to build definition whenever new project is added to the solution?
Answer: There are a couple of things you can check.
Is the folder in Source Control mapped to the workspace of your build definition? It could be that the source isn't being brought down to the build server. If none of the other projects in your solution have any dependencies on the missing project you wont see any errors.
The other thing to check is the configuration you've set to build. In your build definition check the configuration in the build process (e.g. "Release", "Any CPU"). Then open your solution in Visual Studio and right click on the Solution in the Solution Explorer, select "Configuration Manager" and make sure that the same configuration exists, if it does make sure that the project is set to build for that configuration.
Answer: I think the only way to get the effect you 're having is if you 're actually building  another *.sln in your build definition. If you 're using the same sln & everything is build, there is no reason for the binaries of the new assembly to not get copied.If for some reason the sources aren't available, your build would fail.EDIT (after Comment "We are not building any other solution using this build definition. And it is building the solution successfully")I think you need to share some additional info. Are you saying that in your Build Agent you see under Sources both:C:\Builds\1...\Sources\SolutionName\OldProject\bin\"Config"\OldProject.dll
C:\Builds\1...\Sources\SolutionName\NewProject\bin\"Config"\NewProject.dll but then under Binaries onlyC:\Builds\1...\Binaries\"Config"\OldProject.dll ?
Comment: We are not building any other solution using this build definition. And it is building the solution successfully


Formula for $\mathbb E_\nu[Y]$ when formula for $\mathbb P_\nu$ is given

Question:
Given the formula for $\mathbb P_\nu[F]$, what is the formula for $\mathbb E_\nu[Y]$?
Answer: If $X$ is a simple random variable (i.e. $X$ takes only finitely many values), then
\begin{equation*}
X = \sum_{i = 1}^{N} x_{i} 1_{\{X = x_{i}\}}
\end{equation*}
for some $\{x_{1},\dots,x_{N}\} \subseteq \mathbb{R}$ and then elementary properties of the Lebesgue integral yield
\begin{equation*}
\mathbb{E}_{\nu}(X) = \sum_{i = 1}^{N} x_{i} \mathbb{P}_{\nu}(\{X=x_{i}\}) = \sum_{i = 1}^{N} x_{i} \frac{\mathbb{E}(\exp(\langle \nu,Y\rangle) 1_{\{X=x_{i}\}})}{\mathbb{E}(\exp(\langle \nu,Y \rangle))} = \frac{\mathbb{E}(\exp(\langle \nu, Y \rangle) X)}{\mathbb{E}(\exp (\langle \nu,Y \rangle))}
\end{equation*}
If $X$ is a bounded random variable, then we can fix simple random variables $(X_{n})_{n \in \mathbb{N}}$ such that $X_{n} \to X$ uniformly and hence
\begin{equation*}
\mathbb{E}_{\nu}(X) = \lim_{n \to \infty} \mathbb{E}_{\nu}(X_{n}) = \lim_{n \to \infty} \frac{\mathbb{E}(\exp(\langle \nu, Y \rangle) X_{n})}{\mathbb{E}(\exp (\langle \nu,Y \rangle))} = \frac{\mathbb{E}(\exp(\langle \nu, Y \rangle) X)}{\mathbb{E}(\exp (\langle \nu,Y \rangle))}
\end{equation*}
Finally, the preceding discussion shows that a random variable $X$ is integrable with respect to $\mathbb{P}_{\nu}$ if and only if $\exp (\langle \nu, Y \rangle)X$ is integrable with respect to $\mathbb{P}$.  One then finds (e.g. using $X_{M} = X 1_{\{|X| \leq M\}}$ and arguing as in the previous paragraph) that
\begin{equation*}
\mathbb{E}_{\nu}(X) = \frac{\mathbb{E}(\exp(\langle \nu, Y \rangle) X)}{\mathbb{E}(\exp (\langle \nu,Y \rangle))}
\end{equation*}


How to filter filter data after extracted data in Json form

Question: I've extracted data but having problem to filter some data that I would like to get only. Below is the code:
// 7. for each itemid, extract the metrics required (the list of metrics in section 2) //
      outdata.forEach(function (outJson) {
        var temp = []
        for (var j = 0; j =34){
            temp.pop() // remove the last empty column
        }

        temp.push(counter)
        // console.log(temp)
        toPrint.push(temp)
        counter++
      })
    }

The condition that I want to filter is as below but not sure how to amend and incorporate into the above chunk to make it work:
temp= temp.filter(function (row) { return (row[24] ==1); })

Answer: I'm not sure to understand everything well. As far as I understand, you can simply replace
temp = temp.filter(function (row) { return (row[24] ==1); })

by
if(row[24] == 1) {
    // do stuff
}

And, if your aim is to, for each outdata, get the item n°24 and if, and only if, it's 1, you can simplify your code as:
// Map return an array of every 24th values
// Filter return an array of only one
outdata.map((data) => data[head[24]]).filter((data) => data == 1)

// To get the number of one, you can then simply use
outdata.length

Comment: I think i'm thinking too much ==" Thank you

Yes this works by simply use
```if(row[24] == 1) {
    // do stuff
}```


Binary String Collision Probability Distribution

Question: This is not a homework or exam question
Greetings Community!
I am working a piece of a problem that I came up with on my own and the challenge below is a step that I can't seem to view in a way so as to solve it myself. I thought that perhaps the community may see a way to solve this that I am just not seeing. Any insights you are willing to provide are most appreciated. If you require additional information or something is not clear, please let me know.
Assume you have two binary strings $A$ and $H$ each with length $N$. The $j^{th}$ position of both strings is denoted by $a_j$ and $h_j$ respectively.
$A$ and $H$ are randomly generated with one condition: $A$ and $H$ must have a predefined and an equal number, of 1's, namely M.
We now define the variable $X$ such that if $a_j = h_j$ then $x_j = 1$ otherwise $x_j = 0$. This is the NXOR operation. An example is below:
A = 00010010101
H = 00101001011
X = 11000100001
The string for X is essentially tracking where the collisions of A and H take place. Here is where the challenge comes in.
Define $W = \sum_{j=1}^N x_j$. What is the distribution of $W$ given the parameters of $M$ and $N$?
Current (yet minimal) progress:
As I had eluded to, this problem seems to be a derivative from the problem set that deals with hash collisions in cryptography and so seems to be related to the birthday problem.
The bounds on the distribution would have to be $[|N-M|, N]$. This is because unless you have an equal number of 0's and 1's you will always have $W > 0$.
I think this would be some kind of hypergeometric distribution but I seem to be stuck on my condition that a certain number of 1's be present.
Answer: First of all, when you say "random," I assume you mean that each of the $\binom{N}{M}$ $n-$bit strings with exactly $M$ ones is equally likely.
Let $A$ be given.  For $0 \le w \le M$ the are $\binom{M}{w}$ ways to choose $w$ positions for ones in H that will match the ones in $A$.  We can match the remaining $M-w$ ones to zeroes of A in $\binom{N-M}{M-w}$ ways.  Then we assign zeroes to all the remaining positions in $H$.  How may matches did we get?  We matched $w$ ones and $N-M-(M-w)$ zeroes, for a total of $N-2(M-w)$ matches.
To be able to assign the unmatched ones, we need $M-w \le N-M,$ that is, $w \ge 2M-N.$  Finally, the probability that we get $N-2(M-w)$ matches is
$$\frac{\binom{M}{w}\binom{N-M}{M-w}}{\binom{N}{M}} \text{ for } \max(0,2M-N) \le w \le M,$$ and $0$ otherwise.


Is it possible to export only specific content types?

Question: While I was working on the theme update on my test server, original website got quite a lot of updates. But I can't just re-import the whole database, since I've got some new blocks and views here now. Can I somehow export only specific content types and import only them?
Any handy feature in Drupal itself, or maybe module? It should be a wide-spread requirement, since Drupal is such content oriented.
Answer: Take a look at the Node export module.  From the project page:

This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site. The idea is similar
  to the way you export/import Views or Content Types.


Fatal error: Class name must be a valid object or a string

Question: A "Fatal error: Class name must be a valid object or a string […] common.inc" appears on every page on the backoffice.
We don't how to reproduce this because it happens suddenly. When I've done a var_dump() of $class, and $entity_type, this is the result I obtained:

    string 'user' (length=4)
    TaxonomyTermController
    string 'taxonomy_term' (length=13)
    string 'user' (length=4)

The debug code has been added to entity_get_controller().
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    echo $class;
    var_dump($entity_type);
    $controllers[$entity_type] = new $class($entity_type);
  }

  return $controllers[$entity_type];
}

It seems that $type_info['controller class'] doesn't exist for "User".
This problem is solved when we flush the cache_bootstrap (via DELETE FROM cache_bootstrap) and cache (via DELETE FROM CACHE), but this is a temporary solution because it appears again.
It's a big problem for us. Any idea will be really appreciated.
Comment: It would be interesting to see the output of `$entities = module_invoke_all('entity_info'); var_export($entities);`.
Comment: Also, as you are not getting the error when you clean the cache, then something could be wrong with the cached data; maybe they are corrupted.
Comment: Can you show the output of the code I reported in the first comment?
Comment: Thank you for your answer. I agree with you about the corrupted cached data. What origin of this behavior ? Thanks of lot !
Comment: I am getting this same error with nowhere to start looking. I cleared the cache and cache bootstrap tables many times to no avail.
Comment: What line throws the error? As you can see there are MANY people having the same kind of problem, but the solutions are different each time: http://drupal.org/search/apachesolr_multisitesearch/class%20name%20common.inc
Comment: Here is more: http://drupal.org/node/1379690#comment-6032428 - I had to get around this but it points to Date filter for me.
Comment: Is it possible that the "user" module has been marked as disabled? That _should_ not be possible under normal circumstances, but check the "status" column in the "system" table for the user entry.
Comment: See if anything is implementing hook_user_load or hook_entity_load (or alter) and corrupting the object. Quick way to see: `egrep -rn "Implements hook_user_load" .`
Comment: Yes, in a custom block on the homepage, mycustomentity_load was being used. Can't do that?
Comment: I truncated all the `cache_' tables and that seemed to have worked, clearing cache with drush failed
Answer: The function entity_get_info() is responsible for gathering up this data about your entities. I would try to debug that one, and see what goes wrong.
You will want to have just cleared the cache when you do this, or you debug results will not be correct.
Can't think of a better answer to the question that is still generic enough to be useful for someone else.
Comment: It was actually errorring out because customentity_load (arg(1)) was being used in a block on the website. I replaced it with entity_load($params)- but this seems like the same path... now that functionality does not work, but the error is gone.


How to show that the singularity of $\sum_{n=0}^{\infty} e^{nx}$ at $x=0$ is a simple pole of order 1?

Question: Consider the function
$$\sum_{n=0}^{\infty} e^{nx} = -\frac{1}{x}+\frac{1}{2}-\frac{1}{12}x \ +\dots  $$
There is an elementary "trick" to show this has as simple pole of order 1 which is equating $\sum_{n=0}^{\infty} e^{nx}$  with $\frac{1}{1-e^x}$ and then carrying out a laurent expansion of this. But i'm not really interested in this trick. Instead just I want to work explicitly with the series:
$$\sum_{n=0}^{\infty} e^{nx} = 1 + e^x + e^{2x} + e^{3x} + ... $$
And prove that the pole at $x=0$ is of order 1 directly. So a first start would be to just guess the pole has order one and then consider the expression:
$$ \lim_{x \rightarrow 0^-} \left[  x \sum_{n=0}^{\infty} e^{nx} \right] $$
Evaluating this directly leads to the expression $0 \times \infty $ which is indeterminate.
Trying to use L'Hopitals doesn't seem to be of much help either:
$$ \lim_{x \rightarrow 0} \left[  x \sum_{n=0}^{\infty} e^{nx} \right]  = \lim_{x \rightarrow 0} \frac{\sum_{n=0}^{\infty} e^{nx}}{\frac{1}{x}}$$
As you just end up differentiating the top and bottom expressions indefinitely.
Expanding as a taylor series isn't useful EITHER because the expansions come out to
$$ \sum_{n=0}^{\infty} e^{nx} = 1 + (1 + 1 + 1 ... ) + (1 + 2 + 3 + ... ) x + \frac{1}{2!} (1^2 + 2^2 + 3^2 + ... )x^2 + ... $$
Even if you knew about the Riemann Zeta function AND could account for shifting in the series you would INCORRECTLY conclude
$$  \sum_{n=0}^{\infty} e^{nx} = \frac{1}{2} - \frac{1}{12}x  + \ ... $$
And miss that singularity entirely.
So now that motivates a very natural question. Using simple first principles for real and complex analysis at the undergraduate level. How do you actually conclude that this series has a pole of order 1?
One More Idea:
We need to consider $$ \lim_{k \rightarrow \infty} \lim_{x \rightarrow 0} \left[ x \sum_{n=0}^{k} e^{nx} \right] $$
We need to find an explicit sequence $x_n \rightarrow 0$ and $k_n \rightarrow \infty$ such that $\forall \epsilon > 0, \exists \delta$ s.t.  $\forall n \in \mathbb{N}, n > \delta$
$$ \left| \left[ x_n \sum_{i=0}^{k_n} e^{ix_n} \right] - 1 \right| < \epsilon $$
Comment: @Masacroso something something analytic continuation
Comment: the series $\sum_{k\geqslant 0}e^{kz}$ clearly diverges when $z>0$, therefore $z=0$ can't be a pole as the function is not defined at any neighborhood to the right of zero
Comment: What about just multiplying by $x$ and showing the limit is nonzero as $x\to0$? With the series expression at the top, that much is "clear" and then it must be a pole of order $1$.
Comment: Its not obvious to me that $x \sum_{n=0}^{\infty} e^{nx} \rightarrow 1$ as $x \rightarrow 0$ from the left. I want to actually name an explicit sequence $x_n$ and $k_n$ for the sum so I can actually show that $\epsilon$-inequality. Directly evaluating the limit seems to have failed in my work above.
Comment: @Masacroso is there a definition for a pole-like-object even when you don't have neighborhoods?
Answer: I guess you'd basically like a proof that $\lim_{x \rightarrow 0^-} \left[  x \sum_{n=0}^{\infty} e^{nx} \right]$ exists and is finite and nonzero, without using the geometric series formula.
This limit will look less confusing after a change of variables $r = e^x$, getting $\lim_{r \to 1^-} \ln(r) \sum_{n=0}^\infty r^n$. At this point we can once again see that it'll be easy to proceed if we used the geometric series formula, but that's not allowed! Instead, let $f(r) = \sum_{n=0}^\infty r^n$ and use l'Hopital's rule:
$$
\begin{align}
\lim_{r \to 1^-} \ln(r) f(r) &= \lim_{r \to 1^-} \frac{\ln(r)} {\frac 1 {f(r)}} \\
&= \lim_{r \to 1^-} \frac{1/r}{-f'(r) f(r)^{-2}} \\
&= -\lim_{r \to 1^-} \left(\frac{1}{r}\right) \frac{f(r)^2}{f'(r)}
\end{align}
$$
We can separately compute $$f(r)^2 = \left(\sum_{n=0}^\infty r^n\right)^2 = (1+r+r^2+r^3+\cdots)^2 = 1 + 2r + 3r^2 + \cdots = \sum_{n=1}^\infty (n-1) r^n$$
$$f'(r) = \frac{d}{dr} \left( \sum_{n=0}^\infty r^n \right) = \sum_{n=1}^\infty (n-1) r^{n-1}$$
so $f(r)^2 = f'(r)$ and thus our limit above just becomes $-\lim_{r \to 1^-} \left( \frac 1 r \right)$ which is $-1$. As desired, this is finite and nonzero, meaning that $x^1$ really was the correct power to multiply by at the start.

For simplicity, I skipped justifying a couple of steps above.
When simplifying $f(r)^2$ I "multiplied two power series together in the obvious way". This is actually valid at any point within the radius of convergence of both series (source) but it's not trivial.
Second, when simplifying $f'(r)$ I "swapped the order of $\sum_{n=0}^\infty$ and $\frac d {dr}$". Again this is true within the radius of convergence, but again it's not trivial; here's a source.
Comment: Ah thats clever with the change of variables.
Comment: @Masacroso The limit you just typed is a one-sided limit as $r \to 1^-$, so the behaviour for $r > 1$ is not relevant here. Throughout this answer I'm only working with values $|r| < 1$, for exactly the reason you're worried about.
Answer: Here's a slightly silly answer. Note that
$$\lim_{x \to 0} \frac{e^x - 1}{x} = 1$$
and so
\begin{align*}
\lim_{x \to 0^{-}} x \sum_{n=0}^\infty e^{nx}&=\lim_{x \to 0^{-}} (e^x - 1)\sum_{n=0}^\infty e^{nx} &&\text{(by the multiplication rule for limits)}\\
&=\lim_{x \to 0^-} \left[\sum_{n=1}^\infty e^{nx}-\sum_{n=0}^\infty e^{nx}\right]&&\text{(multiplying the two factors)}\\
&=\lim_{x \to 0^-} e^{0x}&&\text{(canceling like terms from each sum)}\\
&= 1
\end{align*}
(Why is this silly? Because the only reason we're not using the geometric series formula is that we're actually proving it!)
Comment: I think this might be legit because the limit you presented in the beginning doesn't depend on the definition of the geometric series


Can't block access to a file using htaccess

Question: I want to block a file config.json from access, so I put .htaccess file like this:
RewriteEngine on

RewriteRule config.json - [F]

In directory ~/projects/bush but when I access localhost/projects/bush/config.json I still see the content of the file, what wrongs here?
Comment: Do .htaccess files work otherwise in other contexts?  At the server level, `AllowOverride` must be set to enable them at the directory level...
Comment: It doesn't actually affect your use case, but the `.` should be escaped as `config\.json` - otherwise it matches any character so if you had a valid file `configxjson` that would also be blocked by your rule.  Just good practice.
Answer: Check the web server's configuration (httpd.conf) for AllowOverride None as it disables reading of .htaccess for the directories it applies to. It is often done to increase performance.
Comment: Yes, that was it, found it before I see the answer, I've None in `/etc/apache2/sites-available/default` and change it to `AllowOverride All`
Answer: try:
RewriteRule ^/?config\.json$ - [F,L]

This probably will work.


Is this Fourier Transform relation correct?

Question: Is the Fourier Transform of $$\nabla f\cdot \nabla g$$ from $\vec{x}$ to $\vec{k}$ space a convolution?
I know that, for a certain definition of the FT, $$\nabla f\to \vec{k} F $$
where $F(\vec{k})$ is $f(\vec{x})$ after FT.
I suspect  the FT of $\nabla f\cdot \nabla g$ involves a convolution though? Something like
$$\int d^3 k' \,\,\vec{k}\, F(\vec{k})\cdot (\vec{k}-\vec{k}')G(\vec{k}-\vec{k}') \,\, ?$$
Sorry for the probably simple question. Also, if anyone has good comprehensive notes on FTs that'd be much appreciated too. Thanks!
Answer: Lets try to figure it out. Let $\phi(\vec{k})$ be the Fourier transform of $\nabla f \cdot \nabla g $.
$$  \nabla f \cdot \nabla g = \int \phi(\vec{k}) \ e^{i\vec{k}\cdot\vec{x}} \ \mathrm d^3\vec{k} $$
Now we write $f$ and $g$ in terms of their Fourier transforms.
$$  \int \int \nabla \left(\hat{f}(\vec{k})e^{i\vec{k}\cdot\vec{x}}\right) \cdot \left(\hat{g}(\vec{q})e^{i\vec{q}\cdot\vec{x}}\right)\ \mathrm d^3\vec{k}\ \mathrm d^3\vec{q}  = \int \phi(\vec{k}) \ e^{i\vec{k}\cdot\vec{x}} \ \mathrm d^3\vec{k} $$
$$  \int \int \hat{f}(\vec{k})\hat{g}(\vec{q}) \left( \vec{k} \cdot \vec{q}\right) e^{i(\vec{q}+\vec{k})\cdot\vec{x}} \ \mathrm d^3\vec{k}\ \mathrm d^3\vec{q}  = \int \phi(\vec{k}) \ e^{i\vec{k}\cdot\vec{x}} \ \mathrm d^3\vec{k} $$
To kill some of the integrals I am going to apply the fourier transform to both sides, i.e., multiply both sides by $\exp(-ip\cdot x)/ (2 \pi)^3$ and integrating with respect to $x$. On the right we will get $\phi(p)$ on the left we will get a delta function which collapses one of the integrals.
$$  \frac{1}{(2\pi)^3} \int\int \int \hat{f}(\vec{k})\hat{g}(\vec{q}) \left( \vec{k} \cdot \vec{q}\right) e^{i(\vec{q}+\vec{k}-\vec{p})\cdot\vec{x}} \ \ \mathrm d^3\vec{x} \mathrm d^3\vec{k}\ \mathrm d^3\vec{q}  = \phi(\vec{p}) $$
$$  \frac{1}{(2\pi)^3} \int\int  \hat{f}(\vec{k})\hat{g}(\vec{q}) \left( \vec{k} \cdot \vec{q}\right)(2\pi)^3 \delta^{(3)}(\vec{q}+\vec{k}-\vec{p})\  \mathrm d^3\vec{k}\ \mathrm d^3\vec{q}  = \phi(\vec{p}) $$
$$   \int  \hat{f}(\vec{k})\hat{g}(\vec{p}-\vec{k}) \left( \vec{k} \cdot (\vec{p}-\vec{k})\right) \  \mathrm d^3\vec{k}  = \phi(\vec{p}) $$
So it seems that the identity you propose it true, or at least consistent with my result.


Outlier Detection Using VAE Latent Space

Question: I am trying to perform outlier detection using VAE.
Before I was performing the same task using normal autoencoder and I used reconstruction error, I trained the network, then I passed new samples as input and marked those with high reconstruction error as outliers.
I know that similar things can be done with VAE, but I was wondering if I could somehow use information from LATENT SPACE? An encoder is learning to get means and STDs that are close to a normal distribution and then decoder to sample from those and recreate input.
But I was wondering if now after training I can pass a new sample through just ENCODER, obtain latent space variables, and based on them decide somehow if the sample is an outlier or not?
I thought about sampling from obtained distribution, checking how far from 0 is the point and if far then marking this sample as an outlier, but using sampling feels a bit random. Or maybe most outlying samples should return after encoding most "unnormal" mean and std?
Answer: One concern I would have about this approach is that I believe it's been shown that powerful enough decoders may essentially ignore the stochasticity of the latent space, so your encodings may not need to be very good.
That said, let's assume you got a good reconstruction with a weak decoder. I would say this is doable in that case. I would think a good measure would be to just measure the mean Kullback-Leibler Divergence between your candidate outlier and either some representative subset of known good encodings of that class (e.g. training data - but if you can take a peek at decent production embeddings, should be fine too), or to approximate the whole latent cluster's mean and covariance matrix and KLD against that.
It's more or less the same approach as training the VAE in the first place, only you're comparing against the cluster parameters as your ideal, rather than the (0, 1) Standard Normal parameters.
The first approach seems like it could be a bit more robust, but is far more of a pain to actually crunch the numbers for, the latter introduces the risk that your estimate of the cluster parameters is off. Finally, if you're feeling like something really cheap and simple and likely to go off the rails, you could just use a plain Euclidean distance from the mean, but that's really hacky.
Answer: That's an interesting approach and I think you can try it.
If indeed VAE works as expected, the latent space has to be the multivariate normal distribution, after all the objects are generated by sampling random numbers from this distribution, i.e., after the training, the input to the decoder is random numbers sampled from a normal distribution.
So one approach is to pass your object to the encoder, and check how far this output is from a normal distribution. You can use a t-test for that. see here for more details regarding the t-test for multivariate normal distribution.
Another approach can be to use a similar approach to VAE-VQ. In this approach, the output of the encoder is clustered using a vector quantizer. After having the clusters you can check the distance from these clusters. See more details here.


In Drupal Commerce, what is the difference from a product, product type, and product display?

Question: I'm coming from ubercart and want to transition to drupal 7 commerce 1.x, but its very confusing on how this all relates to one another. First off I just want to clarify, what the difference from a product, product type, and product display?
I read a few online tutorials, but its not very clear on distinguishing how each one relates and how it is setup.
Comment: Drupal Commerce has documentation explaining such basic concepts: http://www.drupalcommerce.org/user-guide/products
Comment: I read that and its confusing...
Answer: Okay after reading a bit and messing around with the commerce module, its a bit more clear now. Don't even try to just read the documentation without clicking around and testing Drupal commerce as its very confusing if your not messing with the site. It's best to install just the Drupal Commerce module and not the Commerce Kickstart module so you can get a CORE knowledge of how it works from the ground up. Kickstart has too many other modules installed and will make it confusing of how thins are built.
Hopefully I can explain it a bit easier than the documentation. When starting out with Drupal Commerce and your coming from Ubercart, its good to know that there are no Options or Attributes as a configuration option as you have it in Ubercart. The idea of how Drupal Commerce was constructed was that every type of options within an attribute is its own product. (This is something I had to get my brain used to.)
Let's say I am selling T-shirts and I have SIZE and COLOR as an attribute. Now I have 5 difference sizes (X-Small, Small, Medium, Large, X-Large) and have 5 different COLORS (Red, Blue, White, Black, Green). YES, I know its a crap load of products to deal with compared to Ubercart which would have been only ONE and you just set attributes and options for it!
In Commerce, a product page is constructed in this way:
Product Type > Product > Product Display
Product Type
You can think of Product Type as you creating a new Content Type under structure, but it just has its own section for it. Which is why this is called an Entity! Structure > Content Type is a type of Entity. And Product Type is just another Entity. Hence the different page to set this up.
Product
You create a product out of a product type. Same as if you create a new content type called "Basic Page", you would create a new page when you click on basic page under structre.
Product Display
Now here's the tricky part to wrap your head around. When you create a product, there is no page where you can view it as its not a "DISPLAY". Its just a record in your site saying you have this product, but you cant view it. Now you create "PRODUCT DISPLAYS" via the regular structure menu as if you were creating a new content type. You can call it whatever. You know what, just use the default "Basic Page" and add a new field to it. That new field will have to be a type of "Product Reference", which you select under the type option when you add new fields. Once you add a product reference option. Your BASIC PAGE is now considered a "PRODUCT DISPLAY".  When you first install commerce without anything else, you will have to make your own product display, so don't expect to see a product display option under structure. Once that is done, create a new BASIC PAGE and add a few products you already made and it will pop up with the add to cart forms and stuff.
I hope this was clear, if not let me know and I'll try to be a bit more precise.
Comment: I also recommend learning with Commerce Kickstart 1.x - you get the full core Commerce experience without the store trappings of Kickstart 2.x.

The simplest way to understand it is by thinking about taxonomy, another core Drupal entity type that is displayed in the context of other entities. Taxonomy terms have different types (their vocabularies), a list of terms, and a term reference field to attach them to content.

Products have different types (aptly named product types), the products themselves, and a product reference field to attach them to content.


Integration by parts problem

Question: If $\textbf{x}\in \Omega \subset\mathbb{R}^n,$ where $\Omega$ is a bounded open set, $u:\Omega\rightarrow\mathbb{R}, \;\eta:\Omega\rightarrow\mathbb{R},\;u'=\nabla u = \displaystyle\left(\frac{\partial u}{\partial x_1}\cdots\frac{\partial u}{\partial x_n}\right), \;\;\eta'=\nabla \eta = \displaystyle\left(\frac{\partial \eta}{\partial x_1}\cdots\frac{\partial \eta}{\partial x_n}\right)$ and I have the functions:
$$J(u)=\int_\Omega F(\textbf{x}, u, u')\;d\textbf{x}=\int_\Omega F(\textbf{x},u,u')\;dx_1\cdots dx_n$$
$$\Phi(\varepsilon)=J(u+\varepsilon\eta)=J(z)=\int_\Omega F(\textbf{x}, z,z')\;d\textbf{x},$$
where $\varepsilon$ is some small number and $F$ is a function of $\textbf{x}, z$ and $z'$. My problem is to calculate the derivative of $\Phi$ at the point $\varepsilon = 0$ and equating it to $0$. I get the following:
$$0=\Phi'(\varepsilon)=\int_\Omega F_z\eta+\sum_{i=1}^n\left(\frac{\partial F}{\partial p_i}\frac{\partial \eta}{\partial x_i}\right)\;d\textbf{x},\;\;\;(1)$$
where $p_i=\displaystyle\frac{\partial u}{\partial x_i}+\varepsilon\frac{\partial \eta}{\partial x_i}$. Now by integrating by parts I should get $(1)$ to be  equal to: (this is given to me in reference material)
$$\int_\Omega F_z\eta+\sum_{i=1}^n\left(\frac{\partial F}{\partial p_i}\frac{\partial \eta}{\partial x_i}\right)\;d\textbf{x}=F_z-\sum_{i=1}^n\frac{d}{dx_i}\left(\frac{\partial F}{\partial p_i}\right)\;\;\;(2)$$
Can someone show me the steps how does one get from $(1)$ to $(2)$. My teacher tells me that simple integration by parts is applied, but I can't get it. Any advices? thank you =)
Comment: there still should be an integral on the right side of equation 2. Regarding your question: it's defined in the usual way for every single term in the sum.
Comment: Thank you for your help @tired there is no integral on the right side of eqution 2 in my reference material? Could this be wrong then? In my lecture material I mean...here you can see my reference material in case you want to check: http://math.stackexchange.com/questions/1115621/how-does-integration-by-parts-work-with-multivariable-functions
Comment: I think it should be $$\int_\Omega F_z\eta+\sum_{i=1}^n\left(\frac{\partial F}{\partial p_i}\frac{\partial \eta}{\partial x_i}\right)\;d\textbf{x}=\int_{\Omega}\eta F_z-\sum_{i=1}^n\frac{d}{dx_i}\left( \frac{\partial F}{\partial p_i} \right) \eta$$
Comment: Thank you :) @tired so do you think there is a mistake in the reference? P.S. I used my own notation in tmy question, because I think the notation in the reference is bad.
Answer: Maybe it's better to put it in an answer:
$$\int_\Omega F_z\eta+\sum_{i=1}^n\left(\frac{\partial F}{\partial p_i}\frac{\partial \eta}{\partial x_i}\right)\;d\textbf{x}=\int_{\Omega}\eta \left( F_z-\sum_{i=1}^n\frac{d}{dx_i}\left( \frac{\partial F}{\partial p_i} \right) \right)\text{d}\textbf{x} \rightarrow \\
 F_z-\sum_{i=1}^n\frac{d}{dx_i}\left( \frac{\partial F}{\partial p_i} \right)=0
$$
As mentioned in the comment, we used integration by parts for every  term in the sum  to get the first line.
Rememeber that our goal was to find the minimum of our functional derivative $ \Phi'(0)$ therefore we introduced the auxillary function $\eta$. It should be clear that our final equation should be independent of this quantity. To assure this the term in the second line has to be zero.
For further informations please have a look at this excellent book
Mathematics for Physics - M. Stone & P. Goldbart
Comment: Thank you very much! =) Can you emphasize a little bit more your answer, why is the first equation true? Where did $d\textbf{x}$ disappear and why does the last equation follow? =) I'm sorry for being so demanding, the multidimensionality troubles me here. Could you maybe write out few more details into your answer that explicitly show why it is true? Thank you very much if you could do this! =) For example when you stated: "The second follows from the fact, that our integral should be zero regardless of the value of the parameter η". My question is why?
Comment: hey, the missing "dx" was my fault...
Comment: Okay, no problem at all :) Sorry if I'm bugging you ;D I've just tried to figure this out for some time and I want everything to be crystal clear in my mind why the above is true with no question marks left unsolved :)
Comment: i added a few comments...
Comment: Hi @tired one last question and then everything is clear =) Why is $\displaystyle \frac{\partial F}{\partial p_i}\eta = 0$?
Comment: In most applications of variational calculus we assume that $\eta|_{\partial \Omega }=0$
Comment: Aaaah, now pieces are starting to fit together x) So when we evaluate the function $$\displaystyle \frac{\partial F}{\partial p_i}\eta$$, given that $\eta \in C^{\infty}_0$, we get that $\displaystyle\left[\frac{\partial F}{\partial p_i}\eta\right]_{\partial \Omega}=0$. I got it finally! thank you!

Integration by parts problem


What is the best way to update Drupal periodically using a cron job?

Question: Previously I periodically updated Drupal sites by using a cron-job with a "drush up -y" script running every Wednesday 15,16,17,18,19,20,21,22 hours UTC. which is when "Security releases happen" according to https://www.drupal.org/node/1173280
Lately I noticed that when security issues are really urgent, the update can take place just any time during the week. I now let the update cron take place every hour every day. I am aware this is not an ideal solution. What is the better solution to update Drupal with a cron script say within the hour of any release?
Comment: You seem to have a custom local cron-job that doesn't have anything with how Drupal or Drupal updates work. There is no such a thing as `update window` as the new releases are rolled out publicly and anyone after that can run update any time.
Comment: Updates are not automatic.
Comment: Clarifying: the update manager module _will_ tell you (in the admin) when critical updates or updates are available for core or contributed modules. But nothing will automatically update it all for you. You can also have the system email you when updates are found, too.
Comment: @Kevin If you add that Wednesday is when the Security Team makes public any security issue on covered third-party modules, you get a pretty answer. Do you care to write it?
Comment: I don't want to defend here if updates are automatic or not or if they are appropriate or not. I just made a cron script using drush up -y and that is my choice, not under discussion here and hardly an answer to the questions.
Answer:
How can we automate our updates when these exceptions take place?

Updates are not automatic. The update manager module will tell you (in the admin) when critical updates or updates are available for core or contributed modules. But nothing will automatically update it all for you. You can also have the system email you when updates are found, too - per site. This is also helpful for staying informed.
You could theoretically "auto update" with a CI/build workflow that builds X times per day, but there is more inherent risk there of breaking the site unless you are strict about versions of contrib, and specify drupal/core as ~8.0 and minimum stability stable. Though, that is not bulletproof. In the last update from 8.4 to 8.5, I had to patch over a contrib module due to a change introduced in core. That contrib module still has not updated to comply with the change. If I had this sort of workflow, core would have updated and broke the site. That isn't so much the fault of core, but the contrib module(s) not keeping pace with the changelog or the sometimes unfortunate BC breaks.
While auto update sounds like a good idea, its usually not worth the mentioned risk. I prefer to clone locally and run through the application to see if anything has changed, moved, or flat out broke instead of have it hit production immediately. I think most would agree.
With this latest PSA, everyone was given a weeks notice that it was coming so people could prepare and plan their release window around it. So there should have been plenty of time to stay informed, and most hosting companies (i.e.: ones who promote Drupal) should have notified their customers.
Wednesday is when the Security Team makes public any security issue on covered third-party modules.
Comment: Also, there is a setting for the security announcements newsletter in your drupal.org profile settings, at https://www.drupal.org/user/YOURUSERID/edit/newsletter - In case you have it switched off, you can enable it again there.
Comment: I can't understand why you'd risk taking down a production site at any moment (as well as change the codebase) without being present. I just can't see any good scenario for this, not to mention the fact that you can't easily roll back the code, so I think this should stand as a warning for anyone coming around and reading.
Comment: Thats understandable but the whole thing sounds like "how do I pull the trigger automatically on prod" which I think should be advised against for a majority of viewers who arent in devops. Doing this at a lower level, having tests, a build process and notification setup that would be fine. I assume that most do not.
Comment: What if the user / administrator decides to take the mentioned risks, when he find security to be updated more important than security that it is working? This is the reason I use cron jobs.
Comment: @ñull – Then simply let a cron job periodically run `composer update` or `drush up` or whatever routine you want. NOT RECOMMENDED!
Comment: Maybe they do this on a different server, then trigger some CI routine which first gets wired through a shipload of behavior tests and regression tests before it gets deployed only when all flags are green. Some real DevOps Voodoo from down the crypt.
Comment: I don't have enough manpower to do what is suggested here and I want patches to be installed early before vulnerabilities are being abused. When site owners want stability, they have to find a better company than mine, may be yours? So what's the worry? BTW, the script includes making a backup before upgrade.


Cálculo dos dias de um mês

Question: Estou montando uma agenda e vou fazer um calendário. Preciso saber quantos dias tem no mês e também que dia da semana é o dia 1º de cada mês. Como fazer isso com PHP?
Comment: achei estes exemplos meio prontos: http://davidwalsh.name/php-calendar http://www.php-calendar.org/
Comment: fullCalendar é uma lib muito boa, simples e com uma boa documentação.
Comment: Alterei a pergunta, acho que ficou mais fácil de responder agora!!! aguardo mais respostas...
Comment: Porque usou as tags jQuery e JavaScript?
Answer: Isso pode não responder completamente tua pergunta, mas usei uma vez a biblioteca Full Calendar para datas e funcionou muito bem.
É um biblioteca em jQuery de uma interface estilo Google Calendar, toda com drag-and-drop, tem uma demo do que pode ser feito com ela.
Para processar os dados gerados por funções de callback tipo:
$('#calendar').fullCalendar({
  dayClick: function() {
    alert('a day has been clicked!');
    }
});

Answer: Baseado em um modelo que postaram eu criei esse calendário simples:
<?php
    $month = 8;
    $year = 2014;
    $days_in_month = date('t',mktime(0,0,0,$month,1,$year));

    for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    echo "
$list_day
";
    endfor;
?>

Precisa ser modificado para ficar "usavel", é só a base que eu precisava!!!
Comment: Acredito que esta é uma resposta a que o usuário chegou sozinho. Se for este caso, seria melhor marcá-la como certa.

Cálculo dos dias de um mês


Como melhorar a velocidade do TestCase no Django?

Question: Estou rodando um teste no Django com apenas duas querys e no cronômetro está levando 1 min e 10 segundos para finalizar o teste. Existe alguma configuração que possa ajustar para acelerar os testes?
Atualmente estou usando postgresql no banco de dados do projeto.
Answer: Consegui melhorar o desempenho alterando o banco para sqlite3 e direcionando o teste para um app específico:
settings.py (ao final do arquivo):
<code>import sys
if 'test' in sys.argv:
    DATABASES['default'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'test_db'
    }
</code>
terminal:
<code>$ ./manage.py test animals.tests
</code>
Ao rodar o teste o tempo caiu para 5 segundos.


How can I find from which key the timeout signal sent from Qtimer objects in Qmap comes from?

Question: In a function, how to understand the signal sent from Qtimer objects that I created in Qmap, how to find from which object the signal comes from in the slot function.
I created Qmap above  code
SQL.h
public slots:
 void experiment();
 void run();
private:
 QMap<QString,QTimer*> job;

I create QMap value and key with Qtimer.
SQL.cpp
void SQL::experiment()
{
  QTimer *timer=new Qtimer();

  job.insert("dd",timer);

  QTimer *timer1=new Qtimer();
  job.insert("ss",timer1);

  job.value("dd")->start();
  job.value("dd")->setInterval)(5000);

  job.value("ss")->start();
  job.value("ss")->setInterval)(10000);

  connect(job.value("dd"),SIGNAL(timeout()),this,SLOT(run()));
  connect(job.value("ss"),SIGNAL(timeout()),this,SLOT(run()));

}

In this slot, how can I understand which of the Qtimer in the Qmap receives a signal at that time?
void SQL::run()
{
  //job.value(key)  // how to understand key

}

I thought I could use sender() with Qmapiterator, but I couldn't find out how. can you help?
Comment: Why don't you use `setObjectName()` for each `QTimer` and then ask for it with `sender().objectName()` instead of using this map?
Comment: how to use your method, you can give me examples code
Comment: ı will write many timer
Comment: Each `QObject` (so also `QTimer`) can have an object name. This can be set with `QObject::setObjectName()` and get `QObject::objectName()`. It is really handy feature, you should use it instead of some complicated maps.
Answer: Old way is using QSignalMapper. You could also set the key as dynamic property of the timer object, so you could access it through QObject::sender(). But, today you should probably just use a lambda.
First, change the run slot to take any parameters you want:
void SQL::run(const QString &key)
{
    QTimer *timer = job.value(key);
}

Then, just use lambda to easily pass the required parameters
QString name="ff";
connect(job.value(name), &QTimer::timeout, this, [this, name]() {
            run(name);
        });
        // name is capture by value above,
        // so changing name variable later does not
        // affect the value captured by the lambda

As a side note, you shouldn't use the old SIGNAL() and SLOT() macros unless you really have to for some reason. Use the "new" (10 years old) connect syntax.
Comment: how can i change dd name to dynamic, When ı write QString name="ff";  connect(job.value("dd"), &QTimer::timeout, this, [this]() {
            run(name);
        });   this error, how to solve this problem.
Comment: @Mahmut Depends on what you mean by "dynamic". I edit the answer a bit, avoiding the repetition of the map key.
Comment: I recommend you spend a day studying C++ lambdas, it's quite a broad subject. Especially learn about capturing by reference vs capturing by value, and the special meaning of capturing `this`.
Comment: this is error, 'name'  cannot be implicity captured because no default mode has been specified
Comment: Did you remember to add `name` to the capture list? You'd get that error, if you didn't specify default capture mode, and didn't specify explicit capture.
Comment: how can ı specify this
Comment: @Mahmut It's in the answer already, in the `[this, name]`. That captures both `this` and `name` by value.


Drupal 8: how can I "eager load" Entities referenced via EntityReferenceFieldItemList field

Question: Note: this is my first Drupal project as I am usually working with Laravel.
I have some entities my-nodes that have a field EntityReferenceFieldItemList (a multi-select linking to other entities of another content type related-nodes).
I want to query the my-nodes entities together with the related entities in 1 query (in Laravel I would describe this as eager loading the relationship).
The my-nodes entities all reference different related-nodes entities and I need to access related-nodes related values.
I'd like to optimize the amount of calls to the database to possibly only 1.
Method referencedEntities does not look like what I need because it's lazy loading, not eager loading:
$node->get($field)->referencedEntities();

Any idea?
Thanks in advance!
Comment: Laravel queries are pretty much the same as in Drupal. To eager load you join the tables and query the fields you are interested in. The method referencedEntities() is simply a method specific to the class mentioned, so only can be used after you've retrieved the parent node of the field, so it can only be lazy.
Comment: Before you try to build a query for referenced entities, I would first build this in a View and see how Views puts together this query, because there are more than two tables involved when you have added the field to a content type (bundle field).
Answer: This doesn't exist in Drupal, you can't load entities of different types at once, the best you can do is load all referenced entities of the same type at once, which is what referencedEntities() does.
Each entity type has its own storage handler which doesn't know anything about other entity types, as far as those handlers are concerned, those other entities might not even be in the database but stored in MongoDB or text files.


Construct a function that is not Lebesgue-integrable but it is Riemann-interagrable

Question: I must construct a function $f: [0,\infty) \to \mathbb{R}$, but not Lebesgue-Integrable, but $f$ in $[0,c)$ is Riemann-integrable and $$\lim_{c \to \infty} \int_{0}^{c} f(x)dx$$ exists.
What I am thinking is: $f(x)=1/x$ on $\mathbb{R}$ and $f(x)=c, x=0$, which is measurable but it is not Lebesgue-Integrable because both sides of Lebesgue integral positive and negative must be finite.
Problem is that limit of this function doesn't exist since it is $\infty$, so it diverges and so it is not Riemann-Integrable.
What should I do? Thanks in advance!
Comment: The title is misleading:  A Riemann integrable function is always Lebesgue integrable. You're talking about an improper Riemann integral.
Answer: You can show that : $t\mapsto\frac{\sin t}{t}$ on $[0,+\infty[$ is "Riemann-integrable" (more precisely it's a generalized integral, i.e., limits of Riemann integrals) but that $t\mapsto\frac{\sin t}{t}$ is not Lebesgue-integrable on $[0,+\infty[$ (because $t\mapsto\left\lvert\frac{\sin t}{t}\right\rvert$ is not integrable on $[0,+\infty[$ and so the Lebesgue integral can't be defined).
Note that we talk about "Riemann-integrable" function on compacts intervals only, and that all the integrals of functions on (semi)-open intervals are get as Riemann-integrals limits, and that Riemann-integrable implies Lebesgue-integrable : indeed, for stairs functions $g$ and $h$ such as $g\leq f\leq h$, we have the equalities
$$\int_a^bg(x)\,dx=\int_{[a,b]}g\,d\lambda\leq\int_{[a,b]}f\,d\lambda\leq\int_{[a,b]}h\,d\lambda=\int_a^bh(x)\,dx$$ showing that Riemann-integrable implies Lebesgue-integrable in all generality.
Comment: The subtle point is that the Lebesgue integral $\int_{0}^{\infty}f(x)dx$ is defined as $\int_Af(x)dx+\int_Bf(x)dx$ where $A=\{x\geq 0 :f(x)\geq 0\}$ and $B=\{x\geq 0 :f(x)<0\}$  which is not the same as $\lim_{c\to \infty}\int_0^c f(x)dx$.


Diffeomorphism of sphere

Question: Is possible to define a diffeomorphism between $x^2+y^2+z^2=1$ and $1=x^2-y^2$?
Any hint? I try to draw the surface but I have problem with the points $(0,1,0)$ of the sphere for example.
Comment: In addition to connectedness, the sphere is compact and the hyperbolic cylinder isn't. So it is not even homeomorphic to either of its two connected components.
Comment: Homeomorphism preserve connectedness. So ...
Answer: No. The sphere is connected, while the surface described in space by $1=x^2-y^2$  (the variable $z$ just happens to be absent, meaning that $z$ ranges over $\Bbb R$) is not. In fact, this surface has 2 connected components, indexed by the sign of $x$. So, the given surfaces are not diffeomorphic (not even homeomorphic).
Comment: I think it only has 2 components, it's a cylinder over a hyperbola.
Comment: Oopsie. You're right, two components. I was thinking of $x^2-y^2 = \pm 1$.

Diffeomorphism of sphere


Replace a int or long with a string in for loop?

Question: I needed to print the Fibonacci Sequence up to 50 numbers, which I eventually figured out, but I also need to replace certain numbers that are divisible by some number with certain words. I kind of figured this out. I got the words to come up, but I could not replace the number. I tried using String.valueOf and replaceAll, but the number still keeps showing up. I left that part of the code in comments because it was not working. I am going to post my code below:
<code>    public static void main(String[] args) {
    long n = 50;
    System.out.print("1 ");
    long x = 0;
    long y = 1;

    String mult3 = "cheese";
    String mult5 = "cake";
    String mult7 = "factory";
    String mult2 = "blah";

    for (long i = 1; i < n; i++) {
        long forSum = x + y;
        x = y;
        y = forSum;

        if(forSum==89){
            System.out.println("");
        }
        if(forSum==10946){
            System.out.println("");
        }
        if(forSum==1346269){
            System.out.println("");
        }
        if(forSum==165580141){
            System.out.println("");
        }

        if(forSum %3 == 0){
            //String mult3 = String.valueOf(forSum);
            //String mult4 = "cheese";
            //String mult3cheese = mult3.replaceAll(mult3, mult4);
            //System.out.print(mult3cheese);
            System.out.print(mult3);
        }
        if(forSum %5 == 0){
            System.out.print(mult5);
        }
        if(forSum %7 == 0){
            System.out.print(mult7);
        }

        if(forSum %2 == 0){
            System.out.print(mult2);
        }
        System.out.print(forSum + " ");
    }//for loop for forSum
}//public static void main
</code>
Comment: String.valueOf, Integer.toString, or just (num + "") will all convert to a String. What exactly isn't working? What's the intended behavior and what is the actual output?
Comment: oh, this is just the famous fizz buzz problem... millions of solutions available online.
Comment: @Renato wow, I didn't even realize that. That makes this much easier, thank you!
Answer: You need to place some "continue" statements to skip past the line that prints the number, if you have matched a "replace the number" condition:
<code>public static void main(String[] args) {
long n = 50;
System.out.print("1 ");
long x = 0;
long y = 1;

String mult3 = "cheese";
String mult5 = "cake";
String mult7 = "factory";
String mult2 = "blah";

for (long i = 1; i < n; i++) {
    long forSum = x + y;
    x = y;
    y = forSum;

    if(forSum==89){
        continue;
    }
    if(forSum==10946){
        continue;
    }
    if(forSum==1346269){
        continue;
    }
    if(forSum==165580141){
        continue;
    }

    if(forSum %3 == 0){
        //String mult3 = String.valueOf(forSum);
        //String mult4 = "cheese";
        //String mult3cheese = mult3.replaceAll(mult3, mult4);
        //System.out.print(mult3cheese);
        System.out.print(mult3 + " ");
        continue
    }
    if(forSum %5 == 0){
        System.out.print(mult5 + " ");
        continue;
    }
    if(forSum %7 == 0){
        System.out.print(mult7 + " ");
        continue;
    }

    if(forSum %2 == 0){
        System.out.print(mult2 + " ");
        continue;
    }
    System.out.print(forSum + " ");
  }//for loop for forSum
}//public static void main
</code>
"continue" means "skip the rest of the code inside this loop and do the next iteration of the loop"


"Really" disable entire cache during development (also routing, twig templates, css+js libraries)

Question: I have followed the community documentation page at https://www.drupal.org/node/2598914 (Disable Drupal 8 caching during development). Now I expect that the caching in my Drupal 8 site is entirely switched off. However, for setting up an new route, a twig template or any css/js library in mymodule/mymodule.libraries.yml, I still need to run
<code>drush cr
</code>
to get my stuff recognized by Drupal 8. How can I "fully" disable caching? It is annoying to run "drush cr" dozens of times and repeatedly guess if the specific item is either cached or not..
Answer: I asked this on twitter and @renebakx replied:

@stevepurkiss check how devel modules handles this, it worked for
  templates and added css/js to the theme's library. Not for added
  routes


delete script msgbox upgrade idea?

Question: I have a script to remove outdated files, but I would like to upgrade it and I'm stuck.
On Error Resume Next

Set objShell = Wscript.CreateObject("Wscript.Shell")
Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = "C:\Users\admin\Desktop\LOGS\test"
today = Date
nMaxFileAge = 1

DeleteFiles(sRoot)

Function DeleteFiles(ByVal sFolder)
  Set oFolder = oFileSys.GetFolder(sFolder)
  Set aFiles = oFolder.Files
  Set aSubFolders = oFolder.SubFolders

  For Each file in aFiles
    dFileCreated = FormatDateTime(file.DateCreated, "2")
    If DateDiff("d", dFileCreated, today) > nMaxFileAge Then
      objShell.Popup "Old file will be deleted after clicking ok",, "Warning"
      file.Delete(True)
    End If
  Next

  For Each folder in aSubFolders
    DeleteFiles(folder.Path)
  Next

I upgraded this script by adding
objShell.Popup "Old file will be deleted after clicking ok",, "Warning"

this popup box but of course now I have to click on OK as many times as many files are to delete...
I would like to have this popup only once, then after clicking OK, everything is automatically deleted.
Answer: For one thing: with your current code the file would be deleted regardless of whether you do or don't click OK. You need to check which button was actually clicked and react accordingly. You may also want a MsgBox with "Yes" and "No" buttons instead of a popup.
res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
If res = vbYes Then
  file.Delete True
End If

To avoid having to confirm each file separately you need to move the confirmation dialog before the loop:
res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
If res = vbYes Then
  For Each file in aFiles
    If DateDiff("d", file.DateCreated, today) > nMaxFileAge Then
      file.Delete True
    End If
  Next
End If

If you want to ask for confirmation only if files matching your criteria are found, you can either use a flag variable to indicate whether or not to delete the files:
Dim doDelete
For Each file in aFiles
  If DateDiff("d", file.DateCreated, today) > nMaxFileAge Then
    If IsEmpty(doDelete) Then
      res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
      If res = vbYes Then
        doDelete = True
      Else
        doDelete = False
      End If
    End If
    If doDelete Then file.Delete True
  End If
Next

or you can collect the matching files in a list and process that list after asking for confirmation:
Set toBeDeleted = CreateObject("System.Collections.ArrayList")

For Each file in aFiles
  If DateDiff("d", file.DateCreated, today) > nMaxFileAge Then
    toBeDeleted.Add file
  End If
Next

res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
If res = vbYes Then
  For Each file in toBeDeleted
    file.Delete True
  Next
End If

Comment: Hey! Thank you... but now he will ask every time no matter if there are some files to delete or not.... I want him to ask only when there are some outdated files...
Answer: Problem Solved!
heres solution:
Dim bConfirmed
bConfirmed = False

For Each file in aFiles
 If DateDiff("d", dFileCreated, today) > nMaxFileAge Then
  If Not bConfirmed Then
   objShell.Popup "Old file will be deleted after clicking ok",,"Warning"
     bConfirmed = True
  End If
 file.Delete(True)
End If

he is asking only one time ( if there are any outdated files ) and don't repeat question for every file.
Comment: That will still unconditionally delete the files, regardless of whether the user pressed "OK" or "Cancel".

delete script msgbox upgrade idea?


Evaluating $\int_c^\infty \sqrt{x} e^{-x/a} dx$?

Question: How can we evaluate $\int_c^\infty \sqrt{x} e^{-x/a} dx$?
Wolfram alpha can't evaluate it for an arbitrary $a$, but if I set $a$ to be an integer, such as $a=3$, I get
$$
\int_c^\infty \sqrt{x} e^{-x/a} dx= \frac{3}{2} \sqrt{3\pi} \text{erfc}(\sqrt{c}/\sqrt{3}) + 3 \sqrt{c} e^{-c/3}.
$$
So it seems the formula for arbitrary $a$ is
$$
\int_c^\infty \sqrt{x} e^{-x/a} dx= \frac{a}{2} \sqrt{a\pi} \text{erfc}(\sqrt{c}/\sqrt{a}) + a \sqrt{c} e^{-c/a},
$$
but how can we derive it without Wolfram alpha?
Comment: Maple will evaluate this for arbitrary $a$, provided I tell it that $a$ is positive.  Maybe Wolfram will, too?   https://www.wolframalpha.com/input/?i=integrate+sqrt%28x%29+e%5E%7B-+x%2Fa%7D+from+x%3Dc+to+infinity+assuming+a%3E0
Comment: First, show that the derivative with respect to $c$ of both sides is the same. Then show that as $c\to +\infty$ both sides tend to $0$. Alternatively, you can integrate once by parts and then make a change of integration variables $x=a t^2$.
Answer: By 'arbitrary $a$', I assume you add the constraints $a>0$ (otherwise the integral diverges) and $c\geq 0$. We start by using the transformation $u=\sqrt{x/a}$. The substitution leads to
$$\int_c^{\infty} \sqrt{x}e^{-x/a}~dx=2a\sqrt{a}\int_{\sqrt{c/a}}^{\infty} u^2 e^{-u^2}~du. \tag{1}$$
The resulting integral is dealt with using integration by parts
$$\begin{align} \int_{\sqrt{c/a}}^{\infty} u^2 e^{-u^2}~du&=\left[-u\cdot \frac{e^{-u^2}}{2}\right]_{\sqrt{c/a}}^{\infty}+\frac{1}{2}\int_{\sqrt{c/a}}^{\infty} e^{-u^2}~du\\&=\frac{\sqrt{c/a}\cdot e^{-c/a}}{2}+\frac{\sqrt{\pi}}{4}\operatorname{erfc}\left(\sqrt{c/a}\right), \end{align}$$
where the complementary error function $\operatorname{erfc}$ is defined to be:
$$\operatorname{erfc}(x):= 1-\operatorname{erf}(x)=\frac{2}{\sqrt{\pi}}\int_x^{\infty} e^{-t^2}~dt.$$
Applying $(1)$ gives your conjectured result.
Comment: The integration by parts is specifically letting $v=u, dw=ue^{-u^2}du.$


Set initial path for a SSH config host

Question: What would I have to add to a SSH hosts entry in my config file so that everytime I ssh into that host, I get sent to specific initial path?
Host foobar
    HostName    foobar.com
    User        foobar

Answer: While the existing answers are fine, not one person specifically mentioned that setting the home directory is done in the password file.
You can change the home directory by editing the /etc/passwd file (use vipw) or running the following command:
usermod -d /user/wants/this/path username
Utilities and methods differ between UNIXes, I'm assuming Linux.  Modifying /etc/passwd directly will work for all of them.
Comment: +1 Of course, it is so obvious
I was assuming he was just a user on the server and not the administrator.
Comment: I specifically didn't mention this, because many programs write their config files into HOME, so either the directory gets cluttered with dotfiles or if the user doesn't have write access, many programs may give errors.
Comment: I specify system users home directories outside of /home all the time but they're not to be authenticated to.  I didn't make any assumptions.  Good point though, if the Jose actually intends to authenticate to this user, it would probably be better to do a rc hack with a cd.
Answer: That is not up to SSH. You will typically have your CWD set to HOME on login. May I suggest reading the man-page of your shell and putting a cd command in the initial login file?
Answer: I don't believe this is possible, but what you can do is add
cd /path/to/where/you/want

to the end of your .bashrc file (assuming you are running bash)

Set initial path for a SSH config host


Hiding fields from RESTful services?

Question: So, this may be a stupid question because it seems pretty basic to me, but I can't find any information about this on here or elsewhere. Is it possible to specify fields to be visible/invisible to RESTful requests in Drupal 8? I would expect that this should be possible to configure--or, at the least, that fields hidden from the display would not be accessible via such requests.
Is this possible, or is there something that I'm simply not understanding here?
Answer: The only way to do this is using field access (hook_entity_field_access()) and denying view access to fields that you don't want to be visible.
The primary use case that the default rest.module/entity integration aims to support is data synchronization. My standard suggestion for anyone who wants to offer public services on a site or build a custom frontend is to consider writing and defining services tailored for that specific use case.
It's also quite possible that more flexible solutions will be developed in contrib, one of those is relaxed, I don't know if it helps with this specific use case, though.
Comment: Oooh, ok, that makes sense and also explains why there is so much documentation regarding creating content via POST. Thank you for the explanation.

Hiding fields from RESTful services?


How to hide row of a multiple column based on hided data values

Question: I am able to hide data of column NAME by some value of XXXX for which i want to hide the other two column like the NAME column data have some values of XXXX for which i want to hide the data of Address and Number
    data = [['NISAMANEE ROWELL', '9198762345','qwerpoiuytr','98 Oxford Ave.Elk Grove Village, IL 60007'], ['ALICE BAISDEN', '8756342865','asdfghjklxc', '94 Valley Rd.Miami Gardens, FL 33056'], ['MARC COGNETTI', '9198762345', 'qwerasdfzxcv' , '221 Summer CircleGreer, SC 29650'], ['JOHNS HOPKINS HEALTHCARE', '9654987642','asdfghjkl', '8522 Pendergast AvenueVilla Park, IL 60181'], ['AMANDA PELLETIER', '9654987642','acderfgds', '8522 Pendergast AvenueVilla Park, IL 60181']]
    df = pd.DataFrame(data, columns = ['Name', 'Number','Information','Address'])
    df
def name(x):
    x=x.title()                              # title the string
    res=pos_tag(word_tokenize(x))            #tokenizing
    arr_Val=[]                               # storing each word in this array
    #exceptionList=['Healthcare','Lerner']    # exception list .. MUST UPDATE HERE !!!!
    exc_list=['Mackesson Inc','Care','Healthcare','Henery Schien','Besse','LLC','CandP','INC','LTD','PHARMACY','PHARMACEUTICAL','HOSPITAL','COMPANY','ELECTRONICS','APP','VOLUNTEERS','SPECIALITIES','APPLIANCE','EXPRESS','MAGAZINE','SUPPLY','ENDOSCOPY','NETWandK','SCHOOL','AT&T','SOLUTIONS','SANITATION','SYSTEMS','COMPOUNDING','CLINIC','UTILITIES','DEPARTMENT','CREATIVE','PIN','employment','consultant','units','label','machine','anesthesia','services','medical','community','plaza','tech','bipolar','brand','commerce','testing','inspection','killer','plus','electric','division','diagnostic','materials','imaging','international','district','chamber','city','products','essentials','life','scissand','leasing','units','health','healthcare','surgical','enterprises','print','radiology','water','screens','telecom','neurology','biologicals','laundry','owners','law','offices','pharm','office','fire','safety','family','instruments','publishing','automation','center','plate','group','mall','diabetes','estate','electronic','fire','coffee','water','café','factandy','society','group','precision','oxygen','pizza','mills','lock','exterminate','fresh','graves','emeregency','care','security','empire','chemical','associate','mind','optics','coland','toolbox','properties','contract','agreement','learning','exchange','plumbing','leica','sales','shoppe','league','institute','thermo','gas','print','shack','manufacturing','colgate','environmental','neuro','state','board','children','journal','phone','USA','paper','urgent','radio','day','admin','level','bag','church','coast','account','financial','candpandation','sales','andthopedics','andtho','control','handler','king','test','filter','nandth','south','east','west','refrige','laband','bank','system','scientific','instrument','capital','pfizer','lab','labanda','alcon','group','vision','care','alarm','endo','stryke','realty','pest','optic','renewal','star','surgery','stuff','notes','tables','ssurgical','plasma','plaster','code','construction','notes','ink','park','power','gear','link','recandds','amazon','sweet','fish','food','sign','farm','concept','guard','county','prod','duplex','dental','safe','tax','shop','american','ameri','wandks','cloud','exam','therapy','optical','insurance','depot','doctands','telephone','distibutands','cable','comcast','image','first','choice','wear','energy','duke','nandthside','transcription','engineers','alarm','deli','universal','shield','cleaning','resources','int','direct','out','steak','americas','bread','panera','design','media','eye','kreme','krispy','verizon','one','procare','access','point','shield','total','display','pepsi','cola','distributand','consulting','cleaners','flags','mutual','comp','premier','pedaitrics','.com','enterprise','café','linen','opthalmic','upholstery','card','business','waste','innovations','architectural','agency','photography','exterminatands','times','global','house','ultrasound','aetna','flandist','scripture','steel','fast','vascular','corp','town','partnership','utility','advanced','disposal','bcbs','village','payments','corporation','benefit','service','court','dept','partnership','height','coporation','national','grid','fedex','xerox','walgreen','united','walmart','pse&g','communication','reliant','cross','cigna','terminix','staffing','office','admin','phone','expert','source','management','cash','plumber','springs','communications','expert','berkshire','staples','highmark','berkshire','of','Network','window','Locum','Delta','Greater','Treasurer','Investment','Elite','Explore','Foundation','Rentals','Rental','Textile','Municipal','Authority','Treat','Development','University','ACCRUENT','ROTO-ROOTER','KPMG','LLP','Fertilizing','Roofing','Central','Collection','UNIT','Aviation','Development','Acquisition','Square','Unlimited','light','bulbs','CO.','Doctors','Exterminators','Public','Utilities','Registration','Attorney']
    exceptionList = [x.title() for x in exc_list]

    for i in range( len (res)):              # looping to store tokenized words into array
        if( res[i][0] in exceptionList ):
            return x
        else:
            arr_Val.append(res[i][0])
            #print(res)

    for i in range( len(res) ):             # checking the POS as proper Noun (NNP)
        if( res[i][1]=='NNP'):
            length=len(res[i][0])
            arr_Val[i]=str(length*'X' )
    return(' '.join(arr_Val))

df['Name'] = df['Name'].astype(str).apply(name)

I want to hide the rows of two column Address and Number for which the the name column has contain  XXXXX  the column Address and Number data should also be hided by the XXXXX of any length
Answer: The crux of this problem is the masking of all maskable columns for rows that fit some requirement.  Supposing that I had a boolean series that told me which rows to mask (call it mask), I could use pandas.DataFrame.where to mask out where my mask is False.  You can also pass a parameter to supply alternatives.
In this case, we are passing a pandas.Series with aligns with the DataFrame's index.
The rest of the functions are components to calculate OP's desired conditions.

from nltk import pos_tag, word_tokenize

def get_tags(x):
    """Should be obvious"""
    return pos_tag(word_tokenize(x.title()))

def is_proper(y):
    """Check second element equal to 'NNP'"""
    return y[1] == 'NNP'

def has_proper(tags):
    """Check all tags to see if any are 'NNP'"""
    return any(map(is_proper, tags))

def get_exceptions_checker(exc_list):
    """Return a function that checks for membership in the
    exceptions list.  I want to clean this up so we use `set`
    containment and process it once."""
    exceptions = set(map(str.title, exc_list))
    return lambda x: x[0] in exceptions

def has_exception(tags, checker):
    """Check if any tags has an exception"""
    return any(map(checker, tags))

def should_hide(x, checker):
    """Combine `proper` and `exception` checks.
    Essentially, this keeps the creation of tags to a minimum."""
    tags = get_tags(x.title())
    proper = has_proper(tags)
    exception = has_exception(tags, checker)
    return proper and not exception

def hider(x):
    """Defines what to replace with.
    Feel free to play with this to define other ways."""
    return 'X' * len(str(x))

# `is_exception` is the function that you pass `x` to and
# it will tell you if `x` is an exception
is_exception = get_exceptions_checker(['Mackesson Inc', 'Care', 'Healthcare'])

# define all the columns you want to hide if the condition is satisfied
cols_to_hide = ['Name', 'Number', 'Address']

# Boolean values specifying which rows to hide
mask = df.Name.apply(should_hide, checker=is_exception)

#             Subsetted df   Hide Everything   but only keep rows
#                                              where mask is `True`
#             ____________     __________      ___________
#           /              \ /            \  /             \
df.assign(**df[cols_to_hide].applymap(hider).where(mask, df))

                       Name      Number   Information                                     Address
0          XXXXXXXXXXXXXXXX  XXXXXXXXXX   qwerpoiuytr   XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1             XXXXXXXXXXXXX  XXXXXXXXXX   asdfghjklxc        XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2             XXXXXXXXXXXXX  XXXXXXXXXX  qwerasdfzxcv            XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3  JOHNS HOPKINS HEALTHCARE  9654987642     asdfghjkl  8522 Pendergast AvenueVilla Park, IL 60181
4          XXXXXXXXXXXXXXXX  XXXXXXXXXX     acderfgds  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Comment: Thanks for the solution ,can you please explain your code ,it will be helpful for me
Comment: I will. I had to step away from my desk
Comment: I would just say the 'hider' function should return a Xs of the same length no matter the underlying data to properly mask.
Comment: Thankyou so much @piRSquared it would be so helpful
Comment: @PURU let me know if that helps.
Comment: hi @piRSquared it helps a lot but i had a doubt how( return proper and not exception ) as it return false and true i didn't understand this line and what is the role def is_proper(y)


Unsure of how to store integers from a file to a struct in c

Question: I created two structs to store values in.
struct pair {
    int x_pos;
    int y_pos;
};

struct coordinates_header {
    int length;
    struct pair data[1000];
};

typedef struct coordinates_header coordinates;
coordinates *coords;

I then try to store data from a file using
char line[max_read];
int x, y;
FILE *in_file = fopen(filename, "r");
int i = 0;
coordinates *new = (coordinates *)coords;
while (fgets(line,max_read,in_file) != NULL) {
        sscanf(line,"%d %d", &x, &y);
        new -> data[i].x_pos = x;
        new -> data[i].y_pos = y;
        i++;
    }
new -> length = i;

Then I try to print out the values
int print_struct(void *coords) {
    coordinates *new = (coordinates *)coords;
    for (int i = 0; i < new -> length; i++) {
        printf("%d, %d\n", new->data[i].x_pos, new->data[i].y_pos);
    }
    return 0;
}

And then I get a segmentation fault
I was wondering if someone could point out where the error is. I have no experience with void but require the flexibility for the structure in some functions I'm going to use.
The file read will have the form
100 30
50 200
.. ..

Comment: Show definition of `coords` and `coordinates`
Comment: 1) `i += 2;` --> `i++;` 2) `i <= new -> length;` --> `i < new->length;`
Comment: See [ask] and provide a [mcve]. And don't use things you don't understand. `void *` should only be used under specific circumstances and from the code, your's are not one of them. Don't dfy type-checking, your compiler is your friend, not your foe!
Comment: You still have not shown what `coords` is. Please take the time to read how to post a [mcve]. We need to be able to copy your code *exactly* as shown and run it to see the same problem as described.
Comment: Sorry forgot to add this
Comment: typedef struct coordinates_header coordinates;
Comment: Some of the code was provided by the instructor including void so that it is compatible with all students, hopefully this explains any weird code decisions. Also I just started to learn c a week ago, so if you have any advice on how to deal with void in the future, I'd be grateful. Thanks
Comment: `coordinates *coords;` declares an uninitialized pointer. You must first allocate data block with `malloc()` and then assign the pointer to it to the variable `coords`.
Comment: would sizeof(coordinates_header) be the correct byte size?
Comment: Is `filename` just a pair of `x y` coords on each line?
Comment: 1. You need to set `coords` to point to a valid buffer. 2. `i <= new->length` needs to be `i < new->length` 3. You need to learn to use a debugger.
Comment: There is no point in having a pointer to `coords` (which is the reason for the segfault). Just declare a static variable `coordinates coords;` (no asterisk!) and replace all `->` with `.`.
Comment: Just a nit (more style to avoid confusion). You will want to avoid using `new` as a variable name as it is an allocation function in C++. Yes, it is technically OK in C, but for someone scanning your code, you may create a bit of confusion. As it is a style/readability issue -- it is completely up to you.
Answer: I believe their are some mistakes in your code:

Instead of using coordinates *coords;, which is just a dangling pointer not pointing anywhere in memory, you should just declare a structure member coordinates coords.
Their is no need for void* pointers in your code. You would be better off using coordinates *coords to access the address of the structure member coordinates coords, instead of void *coords.
You are not checking the return value of FILE *in_file, which could return NULL if not opened properly.
It is always good to check the result of sscanf(), just incase two x and y coordinates were not found on a line.

With these recommendations, you can write your code like this:
#include <stdio.h>
#include <stdlib.h>

#define NUMCOORDS 1000
#define MAXREAD 100

typedef struct {
    int x_pos;
    int y_pos;
} coords_t;

typedef struct {
    coords_t coords[NUMCOORDS];
    int length;
} coordinates_t;

void print_struct(coordinates_t *coordinates);

int main(void) {
    coordinates_t coordinates;
    char line[MAXREAD];
    FILE *in_file;
    int i = 0;

    in_file = fopen("coords.txt", "r");
    if (in_file == NULL) {
        fprintf(stderr, "Error reading file.\n");
        exit(EXIT_FAILURE);
    }

    while (fgets(line, MAXREAD, in_file) != NULL) {
        if (sscanf(line, "%d %d", &coordinates.coords[i].x_pos,
                                  &coordinates.coords[i].y_pos) != 2) {

            fprintf(stderr, "two coordinates(x, y) not found.\n");
            exit(EXIT_FAILURE);
        }
        i++;
    }
    coordinates.length = i;

    print_struct(&coordinates);

    fclose(in_file);

    return 0;
}

void print_struct(coordinates_t *coordinates) {
    int i;

    for (i = 0; i < coordinates->length; i++) {
        printf("%d, %d\n", coordinates->coords[i].x_pos, coordinates->coords[i].y_pos);
    }
}

Comment: @Kayanda if this answer helps, give it a tick.


Tensorflow error failed to create directory

Question: I am creating a deep learning program and am trying to train the data. I have began to use the tensorboard but ran into an error in relation to the file created, saying that the program failed to create a directory, and that there is no such file or directory.
I followed sentdex tutorial for deep learning on python part 4 and still had errors.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
import pickle
import time
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import TensorBoard

NAME = 'Tagged-vs-untagged-cnn-64x2-{}'.format(int(time.time()))
tensorboard = TensorBoard(log_dir='logs/{}'.format(NAME))

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

X = pickle.load(open('X.pickle', 'rb'))
y = pickle.load(open('y.pickle', 'rb'))

#data must be normalised
X = X/255.0

model = Sequential()
model.add(Conv2D(64, (3,3), input_shape = X.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())

model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X, y, batch_size=32, epochs=10, validation_split=0.3, callbacks=[tensorboard])

I expect the program to train all the data set and trace through the validation accuracy and loss etc. I get the following error:
Traceback (most recent call last):
  File "C:/Users/owner/Documents/MachineLearning/TNA/DigitalMagnets/cnn.py", line 41, in
    model.fit(X, y, batch_size=32, epochs=10, validation_split=0.3, callbacks=[tensorboard])
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 780, in fit
    steps_name='steps_per_epoch')
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 374, in model_iteration
    callbacks._call_batch_hook(mode, 'end', batch_index, batch_logs)
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py", line 248, in _call_batch_hook
    batch_hook(batch, logs)
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py", line 531, in on_train_batch_end
    self.on_batch_end(batch, logs=logs)
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks_v1.py", line 362, in on_batch_end
    profiler.save(self.log_dir, profiler.stop())
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\profiler.py", line 144, in save
    gfile.MakeDirs(plugin_dir)
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 438, in recursive_create_dir
    recursive_create_dir_v2(dirname)
  File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 453, in recursive_create_dir_v2
    pywrap_tensorflow.RecursivelyCreateDir(compat.as_bytes(path))
tensorflow.python.framework.errors_impl.NotFoundError: Failed to create a directory: logs/Tagged-vs-untagged-cnn-64x2-1563447772\plugins\profile\2019-07-18_12-02-54; No such file or directory
Comment: do you have a logs folder in your current directory?
Comment: yes, this file is within a folder named digitalMagnets and then the logs folder is also within that, which is right isn't it?
Answer: The issue isn't with TensorFlow or tensorboard but rather with python, that too specifically for windows.
Currently, on Unix, SplitPath splits only on forward slashes; on
Windows, it splits on forward slashes unless there are no forward
slashes in the string, in which case it splits on backslashes. This is
confusing, and inconsistent with platform APIs like _wmkdir and Tensorflow, which
interpret both \ and / as valid path delimiters.
The fix is to use the platform-appropriate path separators in log_dir
rather than hard-coding forward slashes via os.path.join:
So try this:
tboard_log_dir = os.path.join("logs",NAME)
tensorboard = TensorBoard(log_dir = tboard_log_dir)

This should work


download file on form submission

Question: I have created a form which has only a submit button. In the submit function I am generating csv file and saving it to the files folder using fputcsv function.
But Now I need extra functionality of submit. After saving the file it should download the file also.
How to do this? Any one have some idea about this?
Answer: In Drupal 8 to have the file download rather than redirect to it you can use:
$uri = $file->getFileUri();
  $headers = array(
    'Content-Type'     => $file->getMimeType(),
    'Content-Disposition' => 'attachment;filename="'.$file->getFilename().'"'
  );
  $form_state->setResponse(new \Symfony\Component\HttpFoundation\BinaryFileResponse($uri, 200, $headers, true));

Answer: Attach a form submit handler (code here: Drupal 7 custom form submit handler is not being called).
Then set the file url to $form_state['redirect'].
The file download should begin when submitted.
Answer: In the following code I am downloading file as attachment created with phpExcel.
It may help someone.
function dn_preorder_form_submit($form,&$form_state){
                $excel = new PHPExcel();
                $excel->setActiveSheetIndex(0);
                $excel->getActiveSheet()->setCellValue('A1',"TEST");

                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment; filename="var.xlsx"');
                header("Pragma: no-cache");
                header("Cache-Control: no-cache");
                header("Cache-Control: nmax-age=0");

                $file = PHPExcel_IOFactory::createWriter($excel,'Excel2007');

                $file->save('php://output');
                exit();
    }

Answer: Assuming you are using a file stream, and Drupal specific
$filename = "report.csv";
$stream = "public://";
$uri = $stream . $filename; // Better to add a subfolder per context

$headers = [
  'Content-Type' => 'text/csv',
  'Content-Description' => 'File Download',
  'Content-Disposition' => 'attachment; filename="' . $filename . '"'
];

$rfh = fopen($uri, 'w');

fputcsv($rfh, ['ID', 'Mail', 'Name']);
fputcsv($rfh, ['1', 'email@example.com', 'Jaffe Joffer']);

fclose($rfh);

$form_state->setResponse(new \Symfony\Component\HttpFoundation\BinaryFileResponse($uri, 200, $headers, true));

download file on form submission


Drupal 7 Not Rendering HTML tags

Question: I have been trying to research this issue for about a week now but not having much luck as some of the similar postings do not make too much sense to me. Either way, I appreciate any help and guidance on this!
I have a custom module that utilizes the CKeditor and submits HTML tags to the appropriate column in the database table. Example tags:

I am using the views module to display results but instead of the HTML tags rendering, I am seeing:

This is a test:

test 1

test 2

test 3

When I inspect the browser I actually see:
<p>This is a test:</p>
<ul>
    <li>test 1</li>
    <li>test 2</li>
    <li>test 3</li>
</ul>

What I want to see is:
This is a test:  test 1 test 2 test 3
Answer: You should define the HTML tags in the view using the style options for the field settings otherwise it will treat your tags like text, which is why you are seeing the text translations of those tags.
In this example, I wanted the field "category" to be formatted as a div with a certain class. See screenshot below:

I am not sure what you mean but "appropriate column in the database" table. When using views, you don't really need to worry about how Drupal is writing to the database columns.
Notice that my format is "Unformatted List". You would want to change yours to HTML List:
Answer: Figured out a workaround.
With having the views_php module https://www.drupal.org/project/views_php , I went into the view I was working on and clicked "add" in the fields section.
I chose Global: PHP and the field that would be pulling my database (descr in this case).
For the field that would be pulling from my database (descr), I chose to "Exclude from Display" and in the Global:PHP field, I choose the available variable (which was $row->descr).
There are probably better ways to do this but after spending close to a week, this works for me.
Comment: See my answer. This functionality is already built in without having to use a Global PHP field, which should be avoided unless absolutely necessary.
Comment: Christia - I appreciate your feedback! I tried your below suggestion prior to posting to this board as I saw it in other how-to and forum postings but that didn't seem to work. Just wondering, why should the Global PHP option be avoided? Thanks again for taking the time to post back and help me out!

Drupal 7 Not Rendering HTML tags


What is a Parameter in PHP?

Question: I was wondering what exactly is a parameter in PHP?
Comment: By parameter do you mean a [function argument](http://php.net/manual/en/functions.arguments.php)?
Answer: A parameter is anything you pass to a function or method. It can be some value stored in a variable, or a literal value you pass on the fly. They are also known as arguments.
some_function($some_param, "some other param");

It's kind of like using a blender to make a smoothie: the blender is the function, the ingredients and the milk you put in the blender to blend are the parameters/arguments, and the smoothie is the return value :)
$banana_smoothie = make_smoothie('banana', 'milk');

You can also see similar analogies in the PHP manual entry I link to (makecoffee() and makeyogurt()).

What is a Parameter in PHP?


How to implement Auto Text search in html?

Question: I want to add text search to my webpage.but i want it to search automatically
when the user enter the text without clicking on find button. i want to remove button and make it auto search
example code

function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);

        while (window.find(text)) {
            document.getElementById("button").blur();
            document.execCommand("HiliteColor", false, "yellow");
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}
<input type="text" id="search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">

Here is some searchable text with some lápices in it, and more lápices, and some formatting

Comment: [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.oninput).
Comment: Have you tried removing the button and watching events on the textbox?  Please show us your progress beyond your initial state.
Comment: i have tried but it's not working can you change the code
Answer:

<input type="text" id="search" onkeypress="doSearch(this.value)">

http://www.w3schools.com/jsref/event_onkeypress.asp